@chemx/starter-kit 26.9.16-41 → 26.9.17-1100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/README.md +181 -2
  2. package/assets/chemx-starter-kit-logo.gif +0 -0
  3. package/blueprints/_view-template.scss +24 -0
  4. package/blueprints/atoms/a-button.vue +43 -0
  5. package/blueprints/molecule-capsule/_m-sample-card.scss +75 -0
  6. package/blueprints/molecule-capsule/index.ts +2 -0
  7. package/blueprints/molecule-capsule/m-chemx-badge/_m-chemx-badge.scss +76 -0
  8. package/blueprints/molecule-capsule/m-chemx-badge/index.ts +3 -0
  9. package/blueprints/molecule-capsule/m-chemx-badge/m-chemx-badge.spec.ts +74 -0
  10. package/blueprints/molecule-capsule/m-chemx-badge/m-chemx-badge.tsx +39 -0
  11. package/blueprints/molecule-capsule/m-chemx-badge/m-chemx-badge.vue +42 -0
  12. package/blueprints/molecule-capsule/m-chemx-badge/types.d.ts +12 -0
  13. package/blueprints/molecule-capsule/m-sample-card.spec.ts +74 -0
  14. package/blueprints/molecule-capsule/m-sample-card.tsx +72 -0
  15. package/blueprints/molecule-capsule/m-tab-button/_m-tab-button.scss +49 -0
  16. package/blueprints/molecule-capsule/m-tab-button/index.ts +3 -0
  17. package/blueprints/molecule-capsule/m-tab-button/m-tab-button.controller.ts +40 -0
  18. package/blueprints/molecule-capsule/m-tab-button/m-tab-button.spec.ts +40 -0
  19. package/blueprints/molecule-capsule/m-tab-button/m-tab-button.vue +38 -0
  20. package/blueprints/molecule-capsule/m-tab-button/types.d.ts +14 -0
  21. package/blueprints/molecule-capsule/types.d.ts +12 -0
  22. package/blueprints/shims-vue.d.ts +4 -0
  23. package/blueprints/view-template.tsx +20 -0
  24. package/blueprints/workflows/chemx-audit.yml +79 -0
  25. package/cli/audit/ast-visitors.js +73 -0
  26. package/cli/audit/autofix.js +4 -5
  27. package/cli/audit/extended-visitors.js +243 -0
  28. package/cli/audit/pattern-detector.js +90 -3
  29. package/cli/audit/pattern-detector.spec.js +36 -1
  30. package/cli/audit/prompts.js +10 -12
  31. package/cli/audit/reporter-utils.js +13 -22
  32. package/cli/audit/roadmap.js +5 -20
  33. package/cli/audit/rules-predicates.js +3 -2
  34. package/cli/audit/rules-registry.js +25 -0
  35. package/cli/audit/rules.js +4 -0
  36. package/cli/audit/rules.spec.js +205 -0
  37. package/cli/audit-preflight-git.js +54 -0
  38. package/cli/audit-preflight-scope.js +87 -0
  39. package/cli/audit-preflight.d.ts +16 -0
  40. package/cli/audit-preflight.js +85 -0
  41. package/cli/audit-preflight.spec.js +115 -0
  42. package/cli/audit.js +48 -22
  43. package/cli/build/detector.js +40 -23
  44. package/cli/build/detector.spec.js +81 -0
  45. package/cli/build.d.ts +2 -1
  46. package/cli/build.js +16 -12
  47. package/cli/columnar.d.ts +14 -0
  48. package/cli/columnar.js +52 -0
  49. package/cli/columnar.spec.js +49 -0
  50. package/cli/generator-templates/controller.js +36 -0
  51. package/cli/generator-templates/hooks.js +60 -0
  52. package/cli/generator-templates/naming.js +14 -0
  53. package/cli/generator-templates/react.js +63 -0
  54. package/cli/generator-templates/specs.js +38 -0
  55. package/cli/generator-templates/styles.js +64 -0
  56. package/cli/generator-templates/svelte.js +66 -0
  57. package/cli/generator-templates/types.js +29 -0
  58. package/cli/generator-templates/views.js +76 -0
  59. package/cli/generator-templates/vue.js +62 -0
  60. package/cli/generator-templates.d.ts +35 -0
  61. package/cli/generator-templates.js +28 -480
  62. package/cli/generator-templates.spec.js +108 -0
  63. package/cli/generator.js +2 -2
  64. package/cli/generator.spec.js +61 -1
  65. package/cli/help.js +38 -4
  66. package/cli/index.js +112 -14
  67. package/cli/installer-templates.js +67 -13
  68. package/cli/installer.d.ts +2 -0
  69. package/cli/installer.js +48 -21
  70. package/cli/installer.spec.js +72 -0
  71. package/cli/license.js +22 -1
  72. package/cli/mcp/antigravity.js +59 -0
  73. package/cli/mcp/index.js +2 -1
  74. package/cli/mcp/installer.js +54 -22
  75. package/cli/mcp/installer.spec.js +24 -1
  76. package/cli/mcp/manifests.js +332 -0
  77. package/cli/mcp/prompts.js +28 -0
  78. package/cli/mcp/resources.js +175 -64
  79. package/cli/mcp/server.js +51 -5
  80. package/cli/mcp/server.spec.js +247 -1
  81. package/cli/mcp/tools.js +386 -194
  82. package/cli/mcp/types.d.ts +37 -0
  83. package/cli/navigator-actions.js +23 -10
  84. package/cli/navigator-banner-helpers.js +33 -0
  85. package/cli/navigator-banner.js +19 -38
  86. package/cli/navigator-banner.spec.js +68 -0
  87. package/cli/navigator-guide.js +73 -0
  88. package/cli/navigator-menu.js +20 -0
  89. package/cli/navigator.js +1 -0
  90. package/cli/patcher.d.ts +73 -0
  91. package/cli/patcher.js +249 -4
  92. package/cli/patcher.spec.js +148 -0
  93. package/cli/postinstall.js +27 -0
  94. package/cli/project-detector.js +20 -2
  95. package/cli/project-detector.spec.js +19 -0
  96. package/cli/reader.js +18 -4
  97. package/cli/scaffold.js +26 -4
  98. package/cli/search-commands.js +10 -8
  99. package/cli/search-queries.js +8 -3
  100. package/cli/search-schema.js +5 -0
  101. package/cli/search.d.ts +16 -0
  102. package/cli/search.js +103 -11
  103. package/cli/silence-warnings.js +17 -0
  104. package/cli/team/index.js +30 -0
  105. package/cli/team/team-adversarial-locks.spec.js +105 -0
  106. package/cli/team/team-adversarial-telemetry.spec.js +93 -0
  107. package/cli/team/team-commands.js +199 -0
  108. package/cli/team/team-db-agents.js +79 -0
  109. package/cli/team/team-db-feed.js +84 -0
  110. package/cli/team/team-db-lock-promotion.js +91 -0
  111. package/cli/team/team-db-locks.js +94 -0
  112. package/cli/team/team-db-task-helpers.js +94 -0
  113. package/cli/team/team-db-tasks.js +90 -0
  114. package/cli/team/team-db.js +93 -0
  115. package/cli/team/team-format.js +80 -0
  116. package/cli/team/team-lock-concurrency.spec.js +182 -0
  117. package/cli/team/team-schema.js +74 -0
  118. package/cli/team/team-telemetry.js +104 -0
  119. package/cli/team/team-triage.js +88 -0
  120. package/cli/team/team.spec.js +344 -0
  121. package/cli/terminal.js +36 -1
  122. package/cli/ui-actions-helpers.js +66 -0
  123. package/cli/ui-actions.js +85 -0
  124. package/cli/ui-attention.js +74 -0
  125. package/cli/ui-client-api.js +49 -0
  126. package/cli/ui-client-cert.js +27 -0
  127. package/cli/ui-client-script.js +83 -0
  128. package/cli/ui-db-studio.js +79 -0
  129. package/cli/ui-handlers.js +95 -0
  130. package/cli/ui-html.js +35 -0
  131. package/cli/ui-server-routes.js +63 -0
  132. package/cli/ui-server.js +75 -0
  133. package/cli/ui-styles.js +34 -0
  134. package/cli/ui-template-views.js +63 -0
  135. package/cli/ui-template.js +91 -0
  136. package/cli/ui.spec.js +305 -0
  137. package/cli/verify.js +367 -0
  138. package/cli/verify.spec.js +98 -0
  139. package/docs/CHANGELOG.md +10 -0
  140. package/package.json +13 -15
  141. package/scripts/postinstall.mjs +27 -0
  142. package/scripts/pre-commit.sh +135 -0
  143. package/scripts/publish-both.mjs +108 -0
  144. package/cli/mcp.js +0 -326
package/cli/license.js CHANGED
@@ -109,6 +109,22 @@ export const obtainLicenseKey = async (rawArgs = [], onRunAudit = null) => {
109
109
  return effectiveKey;
110
110
  }
111
111
 
112
+ const isHeadless =
113
+ rawArgs.includes('--headless') ||
114
+ rawArgs.includes('--yes') ||
115
+ rawArgs.includes('-y') ||
116
+ rawArgs.includes('--ci') ||
117
+ rawArgs.includes('--non-interactive') ||
118
+ rawArgs.includes('--no-interactive') ||
119
+ Boolean(process.env.CI) ||
120
+ process.stdout?.isTTY === false ||
121
+ process.stdin?.isTTY === false ||
122
+ Boolean(process.argv?.some((arg) => arg === '--headless' || arg === '--ci' || arg === '--yes' || arg === '-y'));
123
+
124
+ if (isHeadless) {
125
+ return null;
126
+ }
127
+
112
128
  const useGum = hasGum();
113
129
 
114
130
  if (useGum) {
@@ -211,7 +227,12 @@ export const checkOrPromptEvaluation = async (actionLabel = 'generate capsule',
211
227
  return { licensed: true, key: cachedKey };
212
228
  }
213
229
 
214
- const isNonInteractive = options.isYes || Boolean(process.env.CI) || !process.stdin.isTTY;
230
+ const isNonInteractive =
231
+ options.isYes ||
232
+ Boolean(process.env.CI) ||
233
+ process.stdin?.isTTY === false ||
234
+ process.stdout?.isTTY === false ||
235
+ Boolean(process.argv?.some((arg) => arg === '--headless' || arg === '--yes' || arg === '-y' || arg === '--ci' || arg === '--non-interactive'));
215
236
  if (isNonInteractive) {
216
237
  return { licensed: false, proceed: true };
217
238
  }
@@ -0,0 +1,59 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { MCP_TOOLS } from './manifests.js';
5
+
6
+ export const buildMcpInstructions = () => {
7
+ return [
8
+ '# Chemical X Protocol: Mandatory AI Agent Directives',
9
+ '',
10
+ 'MANDATORY VERIFICATION & TOKEN CONSERVATION PROTOCOL:',
11
+ '1. NEVER execute raw, unthrottled "npm test", "pnpm test", "vitest", "tsc --noEmit", or "npm run build" in a bash shell. Raw execution floods context with hundreds of lines of passing checkmarks and compiler spam.',
12
+ '2. ALWAYS invoke Chemical X MCP tools or CLI wrappers first:',
13
+ ' - chemx_verify (or "npx chemx verify --json"): Complete AST Audit + Typecheck + Tests (~45 tokens if green).',
14
+ ' - chemx_typecheck (or "npx chemx typecheck --json"): Silent TypeScript audit; returns structured errors only.',
15
+ ' - chemx_test (or "npx chemx test --json"): Silent test runner; returns ONLY failing assertions and diffs.',
16
+ ' - chemx_audit_build (or "npx chemx build --json"): Silent build audit; categorizes errors by subsystem.',
17
+ '',
18
+ 'AST SEARCH & SURGICAL EDITING PROTOCOL:',
19
+ '3. ALWAYS invoke chemx_q (or "pnpm q <query>") for AST symbol search before running broad ripgrep or find.',
20
+ '4. ALWAYS use chemx_read (with outline: true or symbol: "name") to inspect code structure without dumping entire files into context.',
21
+ '5. ALWAYS use chemx_patch for surgical file edits and chemx_check to verify molecular boundary compliance.',
22
+ '',
23
+ 'MOLECULAR ARCHITECTURE GUARDRAILS:',
24
+ '6. 100-line outer bound per molecule capsule file. Never exceed.',
25
+ '7. Zero raw DOM elements in molecules or organisms: raw HTML tags are restricted exclusively to foundational atoms.',
26
+ '8. Two-stage atomic boolean composition: break multi-clause logic into named booleans before decision computeds.',
27
+ ''
28
+ ].join('\n');
29
+ };
30
+
31
+ export const syncAntigravityMcpSchemas = (customTargetDir = null, options = {}) => {
32
+ const isSilent = Boolean(options.silent);
33
+ const targetDir = customTargetDir || path.join(os.homedir(), '.gemini', 'antigravity', 'mcp', 'chemical-x');
34
+
35
+ if (!fs.existsSync(targetDir)) {
36
+ fs.mkdirSync(targetDir, { recursive: true });
37
+ }
38
+
39
+ let toolCount = 0;
40
+ for (const tool of MCP_TOOLS) {
41
+ const filePath = path.join(targetDir, `${tool.name}.json`);
42
+ const schema = JSON.stringify({
43
+ name: tool.name,
44
+ description: tool.description,
45
+ parameters: tool.inputSchema
46
+ });
47
+ fs.writeFileSync(filePath, schema, 'utf-8');
48
+ toolCount += 1;
49
+ }
50
+
51
+ const instructionsPath = path.join(targetDir, 'instructions.md');
52
+ fs.writeFileSync(instructionsPath, buildMcpInstructions(), 'utf-8');
53
+
54
+ if (!isSilent) {
55
+ process.stdout.write(` \x1b[32m✔\x1b[0m Synchronized ${toolCount} MCP tool schemas and instructions.md in: ${targetDir}\n`);
56
+ }
57
+
58
+ return { targetDir, toolCount, instructions: true };
59
+ };
package/cli/mcp/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { startStdioServer, createMcpHandler } from './server.js';
2
- import { MCP_TOOLS, executeMcpTool } from './tools.js';
2
+ import { MCP_TOOLS, executeMcpTool, Tools } from './tools.js';
3
3
  import { MCP_RESOURCES, readMcpResource } from './resources.js';
4
4
  import { MCP_PROMPTS, getMcpPrompt } from './prompts.js';
5
5
  import {
@@ -27,6 +27,7 @@ export {
27
27
  startStdioServer,
28
28
  MCP_TOOLS,
29
29
  executeMcpTool,
30
+ Tools,
30
31
  MCP_RESOURCES,
31
32
  readMcpResource,
32
33
  MCP_PROMPTS,
@@ -1,21 +1,30 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import os from 'node:os';
4
+ import { syncAntigravityMcpSchemas } from './antigravity.js';
5
+
6
+ export { syncAntigravityMcpSchemas } from './antigravity.js';
4
7
 
5
8
  const SERVER_KEY = 'chemical-x';
6
9
 
10
+ const toResultSync = (operation) => {
11
+ try {
12
+ const value = operation();
13
+ return [value, null];
14
+ } catch (err) {
15
+ const normalizedError = err instanceof Error ? err : new Error(String(err));
16
+ return [null, normalizedError];
17
+ }
18
+ };
19
+
7
20
  export const mergeMcpServerConfig = (existingJsonString = '', serverDef = {}) => {
8
21
  let parsed = { mcpServers: {} };
9
22
 
10
23
  const hasExistingString = Boolean(existingJsonString && existingJsonString.trim());
11
24
  if (hasExistingString) {
12
- try {
13
- const json = JSON.parse(existingJsonString);
14
- if (json && typeof json === 'object') {
15
- parsed = json;
16
- }
17
- } catch {
18
- parsed = { mcpServers: {} };
25
+ const [json, parseError] = toResultSync(() => JSON.parse(existingJsonString));
26
+ if (!parseError && json && typeof json === 'object') {
27
+ parsed = json;
19
28
  }
20
29
  }
21
30
 
@@ -101,25 +110,45 @@ export const installProjectMcpConfig = (targetDir = '.', options = {}) => {
101
110
  process.stdout.write(' \x1b[32m✔\x1b[0m Configured VS Code MCP server in: .vscode/mcp.json\n');
102
111
  }
103
112
 
104
- // 3. Inject helper script to consumer package.json if available
113
+ // 3. Inject helper scripts to consumer package.json if available
105
114
  const pkgPath = path.join(resolvedTarget, 'package.json');
106
115
  if (fs.existsSync(pkgPath)) {
107
- try {
108
- const pkgContent = fs.readFileSync(pkgPath, 'utf-8');
109
- const pkg = JSON.parse(pkgContent);
110
- if (!pkg.scripts) pkg.scripts = {};
111
-
112
- const hasMcpScript = Boolean(pkg.scripts['chemx:mcp'] || pkg.scripts['mcp']);
113
- if (!hasMcpScript) {
114
- pkg.scripts['chemx:mcp'] = 'chemx mcp';
115
- fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n', 'utf-8');
116
- results.packageJson = true;
117
- if (!isSilent) {
118
- process.stdout.write(' \x1b[32m✔\x1b[0m Added "chemx:mcp" script to package.json\n');
116
+ const [pkgContent, readError] = toResultSync(() => fs.readFileSync(pkgPath, 'utf-8'));
117
+ if (!readError && pkgContent) {
118
+ const [pkg, parseError] = toResultSync(() => JSON.parse(pkgContent));
119
+ if (!parseError && pkg && typeof pkg === 'object') {
120
+ if (!pkg.scripts) pkg.scripts = {};
121
+
122
+ let modified = false;
123
+ if (!pkg.scripts['chemx:mcp'] && !pkg.scripts['mcp']) {
124
+ pkg.scripts['chemx:mcp'] = 'chemx mcp';
125
+ modified = true;
126
+ }
127
+ if (!pkg.scripts['chemx:verify']) {
128
+ pkg.scripts['chemx:verify'] = 'chemx verify';
129
+ modified = true;
130
+ }
131
+ if (!pkg.scripts['chemx:test']) {
132
+ pkg.scripts['chemx:test'] = 'chemx test';
133
+ modified = true;
134
+ }
135
+ if (!pkg.scripts['chemx:typecheck']) {
136
+ pkg.scripts['chemx:typecheck'] = 'chemx typecheck';
137
+ modified = true;
138
+ }
139
+
140
+ if (modified) {
141
+ const [, writeError] = toResultSync(() => {
142
+ fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n', 'utf-8');
143
+ });
144
+ if (!writeError) {
145
+ results.packageJson = true;
146
+ if (!isSilent) {
147
+ process.stdout.write(' \x1b[32m✔\x1b[0m Added chemx verification & MCP scripts to package.json\n');
148
+ }
149
+ }
119
150
  }
120
151
  }
121
- } catch {
122
- // Ignore package.json parsing issues gracefully
123
152
  }
124
153
  }
125
154
 
@@ -148,6 +177,9 @@ export const installAntigravityMcpConfig = (targetDir = '.', options = {}) => {
148
177
  const merged = mergeMcpServerConfig(existing, serverDef);
149
178
  fs.writeFileSync(configFile, merged, 'utf-8');
150
179
 
180
+ // Synchronize full 14-tool schemas and instructions.md for Antigravity agents
181
+ syncAntigravityMcpSchemas(null, { silent: isSilent });
182
+
151
183
  if (!isSilent) {
152
184
  process.stdout.write(' \x1b[32m✔\x1b[0m Registered Chemical X in Antigravity: ~/.gemini/config/mcp_config.json\n');
153
185
  }
@@ -7,8 +7,10 @@ import {
7
7
  mergeMcpServerConfig,
8
8
  resolveMcpServerCommand,
9
9
  installProjectMcpConfig,
10
- installAllMcpConfigs
10
+ installAllMcpConfigs,
11
+ syncAntigravityMcpSchemas
11
12
  } from './installer.js';
13
+ import { MCP_TOOLS } from './manifests.js';
12
14
 
13
15
  test('mergeMcpServerConfig: creates valid config when input is empty', () => {
14
16
  const res = mergeMcpServerConfig('', { command: 'npx', args: ['chemx', 'mcp'] });
@@ -80,6 +82,27 @@ test('installProjectMcpConfig: creates .cursor and .vscode configs and updates p
80
82
 
81
83
  const updatedPkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
82
84
  assert.strictEqual(updatedPkg.scripts['chemx:mcp'], 'chemx mcp');
85
+ assert.strictEqual(updatedPkg.scripts['chemx:verify'], 'chemx verify');
86
+ assert.strictEqual(updatedPkg.scripts['chemx:test'], 'chemx test');
87
+ assert.strictEqual(updatedPkg.scripts['chemx:typecheck'], 'chemx typecheck');
88
+ } finally {
89
+ fs.rmSync(tmpDir, { recursive: true, force: true });
90
+ }
91
+ });
92
+
93
+ test('syncAntigravityMcpSchemas: writes all 14 tool schemas and instructions.md', () => {
94
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'chemx-antigravity-test-'));
95
+ try {
96
+ const res = syncAntigravityMcpSchemas(tmpDir, { silent: true });
97
+ assert.strictEqual(res.toolCount, MCP_TOOLS.length);
98
+ assert.ok(fs.existsSync(path.join(tmpDir, 'chemx_verify.json')));
99
+ assert.ok(fs.existsSync(path.join(tmpDir, 'chemx_typecheck.json')));
100
+ assert.ok(fs.existsSync(path.join(tmpDir, 'chemx_test.json')));
101
+ assert.ok(fs.existsSync(path.join(tmpDir, 'instructions.md')));
102
+
103
+ const instructions = fs.readFileSync(path.join(tmpDir, 'instructions.md'), 'utf-8');
104
+ assert.ok(instructions.includes('chemx_verify'));
105
+ assert.ok(instructions.includes('MANDATORY VERIFICATION'));
83
106
  } finally {
84
107
  fs.rmSync(tmpDir, { recursive: true, force: true });
85
108
  }
@@ -0,0 +1,332 @@
1
+ /**
2
+ * Chemical X Protocol: Model Context Protocol (MCP) Tools Manifest
3
+ * Declarative JSON Schema definitions for AI Agent Host integration.
4
+ */
5
+
6
+ export const MCP_TOOLS = [
7
+ {
8
+ name: 'chemx_query_patterns',
9
+ description: 'Execute single-pass AST fingerprinting across candidate files or directory to discover cross-file clones, duplicated predicates, shared state machines, and parallel controller returns before decomposing monoliths (Chemical X Directive 1.F Pre-Split Pattern Discovery).',
10
+ inputSchema: {
11
+ type: 'object',
12
+ properties: {
13
+ dir: {
14
+ type: 'string',
15
+ description: 'Target directory or path to scan (defaults to "src" or current working directory).'
16
+ },
17
+ type: {
18
+ type: 'string',
19
+ enum: ['ALL', 'STATE_UNION', 'UI_STRUCTURE', 'PREDICATE_LOGIC', 'HOOK_SIGNATURE'],
20
+ description: 'Filter pattern types: STATE_UNION (shared state machines), UI_STRUCTURE (cloned JSX layouts), PREDICATE_LOGIC (duplicated booleans), HOOK_SIGNATURE (parallel hooks).'
21
+ },
22
+ minOccurrences: {
23
+ type: 'number',
24
+ description: 'Minimum file occurrences required to qualify as a candidate (default: 2).'
25
+ },
26
+ compact: {
27
+ type: 'boolean',
28
+ description: 'Enable token-conserving compact output (unique files and top 3 samples only, defaults to true).'
29
+ }
30
+ }
31
+ }
32
+ },
33
+ {
34
+ name: 'chemx_autofix',
35
+ description: 'Execute deterministic remediation of safe code violations (typography em dashes, leaked markdown fences, conversational residue comments, and lazy truncation placeholders) with token-compact summaries.',
36
+ inputSchema: {
37
+ type: 'object',
38
+ properties: {
39
+ path: {
40
+ type: 'string',
41
+ description: 'Target file or directory path to autofix (defaults to "src").'
42
+ },
43
+ dryRun: {
44
+ type: 'boolean',
45
+ description: 'Simulate changes without writing files to disk (defaults to false).'
46
+ },
47
+ rules: {
48
+ type: 'array',
49
+ items: { type: 'string' },
50
+ description: 'Optional rule filters (TYPOGRAPHY_EM_DASH, AI_SLOP_CONVERSATIONAL_ARTIFACT, AI_SLOP_LAZY_PLACEHOLDER).'
51
+ }
52
+ }
53
+ }
54
+ },
55
+ {
56
+ name: 'chemx_audit',
57
+ description: 'Run the 7-Pillar Chemical X static AST audit on a file or directory. Analyzes line budgets, 2-stage booleans, hook saturation, self-cleaning timers, anti-Tailwind soup, AI slop, and token burn metrics.',
58
+ inputSchema: {
59
+ type: 'object',
60
+ properties: {
61
+ path: {
62
+ type: 'string',
63
+ description: 'Target file or directory path to audit (defaults to "src").'
64
+ },
65
+ strict: {
66
+ type: 'boolean',
67
+ description: 'Strict mode: fail on any violation including low-severity hygiene issues.'
68
+ },
69
+ minGrade: {
70
+ type: 'string',
71
+ description: 'Minimum acceptable health grade tier (A+, A, B, C, D).'
72
+ },
73
+ minScore: {
74
+ type: 'number',
75
+ description: 'Minimum acceptable score out of 100.'
76
+ },
77
+ model: {
78
+ type: 'string',
79
+ description: 'Pricing baseline for token context burn analysis (claude, gpt4o, blended).'
80
+ }
81
+ }
82
+ }
83
+ },
84
+ {
85
+ name: 'chemx_generate_capsule',
86
+ description: 'Deterministically generate a compliant Chemical X crystalline capsule directory (component, controller hook, mixin-only SCSS, co-located types, barrel index) for React 19, Vue 3.4+, or Svelte 5.',
87
+ inputSchema: {
88
+ type: 'object',
89
+ properties: {
90
+ name: {
91
+ type: 'string',
92
+ description: 'Capsule feature name (e.g. "m-spark-kpi", "a-action-button", "user-avatar").'
93
+ },
94
+ framework: {
95
+ type: 'string',
96
+ enum: ['react', 'vue', 'svelte'],
97
+ description: 'Target framework flavor: React 19 (TSX), Vue 3.4+ (SFC script setup), or Svelte 5 (Runes).'
98
+ },
99
+ tier: {
100
+ type: 'string',
101
+ enum: ['m', 'a', 'o', 't'],
102
+ description: 'Architectural tier: m (molecule < 100 lines), a (atom), o (organism), t (template).'
103
+ },
104
+ targetDir: {
105
+ type: 'string',
106
+ description: 'Destination parent directory. Defaults to detected components directory.'
107
+ },
108
+ lean: {
109
+ type: 'boolean',
110
+ description: 'When true, skip generating controller and SCSS files (useful for minimal UI atoms).'
111
+ }
112
+ },
113
+ required: ['name', 'framework']
114
+ }
115
+ },
116
+ {
117
+ name: 'chemx_get_refactor_prompt',
118
+ description: 'Synthesize targeted Chemical X AI refactoring prompts for Grade F critical hazards, Grade D high debts, Grade C medium debts, AI slop artifacts, or monolithic hotspots.',
119
+ inputSchema: {
120
+ type: 'object',
121
+ properties: {
122
+ dir: {
123
+ type: 'string',
124
+ description: 'Target directory to analyze (defaults to "src").'
125
+ },
126
+ scope: {
127
+ type: 'string',
128
+ enum: ['master', 'grade-f', 'grade-d', 'grade-c', 'grade-b', 'ai-slop', 'hotspots'],
129
+ description: 'Prompt scope to generate (default: "master").'
130
+ }
131
+ }
132
+ }
133
+ },
134
+ {
135
+ name: 'chemx_audit_build',
136
+ description: 'Wrap and audit a build command with token-conserving silent execution. Suppresses compiler noise and catalogs diagnostics into structured categories (TypeScript, Vite/Rollup, Style, Budget).',
137
+ inputSchema: {
138
+ type: 'object',
139
+ properties: {
140
+ command: {
141
+ type: 'string',
142
+ description: 'Build command to run (defaults to project build script e.g. "npm run build").'
143
+ },
144
+ dir: {
145
+ type: 'string',
146
+ description: 'Target workspace directory to build (e.g. "apps/my-card-vault"). Defaults to current working directory.'
147
+ }
148
+ }
149
+ }
150
+ },
151
+ {
152
+ name: 'chemx_q',
153
+ description: 'Chemical X AST-indexed query machine. Finds capsules, symbols, and files with token-minified outputs (Directive 1.H).',
154
+ inputSchema: {
155
+ type: 'object',
156
+ properties: {
157
+ query: { type: 'string', description: 'Search query or symbol name' },
158
+ tier: {
159
+ type: 'string',
160
+ enum: ['atom', 'molecule', 'organism', 'template', 'view', 'hook', 'all'],
161
+ description: 'Architectural tier filter'
162
+ },
163
+ inspect: { type: 'boolean', description: 'Include props and hooks breakdown' },
164
+ columnar: { type: 'boolean', description: 'Return results in compact Columnar JSON format (cols + rows) to eliminate repeated keys and reduce tokens by 60%' },
165
+ limit: { type: 'integer', description: 'Maximum results to return (default: 20)' }
166
+ },
167
+ required: ['query']
168
+ }
169
+ },
170
+ {
171
+ name: 'chemx_read',
172
+ description: 'Token-minified file reader. Extracts AST outlines, stripped comments, line ranges, or specific symbol blocks to minimize token consumption.',
173
+ inputSchema: {
174
+ type: 'object',
175
+ properties: {
176
+ path: { type: 'string', description: 'Relative or absolute file path' },
177
+ outline: { type: 'boolean', description: 'Extract structural AST outline only (types/interfaces/exports, saves 80%+ tokens)' },
178
+ symbol: { type: 'string', description: 'Extract only this symbol declaration and body' },
179
+ stripComments: { type: 'boolean', description: 'Strip comments from output' },
180
+ compact: { type: 'boolean', description: 'Collapse blank lines and trim spaces' },
181
+ startLine: { type: 'integer', description: '1-based start line' },
182
+ endLine: { type: 'integer', description: '1-based end line' }
183
+ },
184
+ required: ['path']
185
+ }
186
+ },
187
+ {
188
+ name: 'chemx_patch',
189
+ description: 'Surgically patch a file using exact search and replace without dumping entire file contents into context. Automatically updates SQLite AST index in real-time and evaluates Chemical X architectural guardrails (Directive 1.A line budgets and Directive 1.G Zero-Raw-DOM).',
190
+ inputSchema: {
191
+ type: 'object',
192
+ properties: {
193
+ path: { type: 'string', description: 'Target file path' },
194
+ targetContent: { type: 'string', description: 'Exact string chunk to replace' },
195
+ replacementContent: { type: 'string', description: 'New replacement content' },
196
+ allowMultiple: { type: 'boolean', description: 'Allow multiple replacements' }
197
+ },
198
+ required: ['path', 'targetContent', 'replacementContent']
199
+ }
200
+ },
201
+ {
202
+ name: 'chemx_check',
203
+ description: 'Check single file or capsule against molecular boundary rules (line limits, raw DOM, 2-stage booleans).',
204
+ inputSchema: {
205
+ type: 'object',
206
+ properties: {
207
+ path: { type: 'string', description: 'File or capsule path to verify' }
208
+ },
209
+ required: ['path']
210
+ }
211
+ },
212
+ {
213
+ name: 'chemx_write',
214
+ description: 'Create or overwrite a file with automatic SQLite AST micro-indexing and architectural boundary verification (100-line limit and Zero-Raw-DOM).',
215
+ inputSchema: {
216
+ type: 'object',
217
+ properties: {
218
+ path: { type: 'string', description: 'Target file path to write' },
219
+ content: { type: 'string', description: 'Code content to write' }
220
+ },
221
+ required: ['path', 'content']
222
+ }
223
+ },
224
+ {
225
+ name: 'chemx_typecheck',
226
+ description: 'Execute silent, token-conserving TypeScript typecheck audit. AI agents MUST use this tool first instead of running raw tsc or terminal commands to avoid dumping noisy compiler output into context. Returns structured diagnostics only if errors exist.',
227
+ inputSchema: {
228
+ type: 'object',
229
+ properties: {
230
+ command: { type: 'string', description: 'Optional custom typecheck command (e.g. "pnpm run typecheck" or "npx tsc --noEmit")' },
231
+ dir: { type: 'string', description: 'Target workspace directory (defaults to current working directory)' }
232
+ }
233
+ }
234
+ },
235
+ {
236
+ name: 'chemx_test',
237
+ description: 'Execute silent, token-conserving project test runner. AI agents MUST use this tool first instead of running raw npm/pnpm test in the shell to avoid burning thousands of tokens on passing tests. Suppresses passing checkmarks; returns ONLY failing test assertions and diffs.',
238
+ inputSchema: {
239
+ type: 'object',
240
+ properties: {
241
+ command: { type: 'string', description: 'Optional custom test command (e.g. "pnpm test" or "npx vitest run")' },
242
+ dir: { type: 'string', description: 'Target workspace directory (defaults to current working directory)' }
243
+ }
244
+ }
245
+ },
246
+ {
247
+ name: 'chemx_verify',
248
+ description: 'Execute the complete zero-token-burn project verification pipeline (7-Pillar AST Audit + Typecheck + Tests). AI agents MUST invoke this tool first before launching expensive raw terminal test/build commands. Emits a compact status card (~45 tokens if all pass) or pinpoint failure diagnostics.',
249
+ inputSchema: {
250
+ type: 'object',
251
+ properties: {
252
+ dir: { type: 'string', description: 'Target directory for architectural audit (defaults to "src" or "blueprints")' },
253
+ includeBuild: { type: 'boolean', description: 'Whether to also run production build verification (defaults to false)' }
254
+ }
255
+ }
256
+ },
257
+ {
258
+ name: 'chemx_team_status',
259
+ description: 'Query the multi-agent swarm control panel from .chemx/index.db (active agents, tasks breakdown, held file leases, FIFO lock waiters, and recent feed) in token-conserving columnar format.',
260
+ inputSchema: {
261
+ type: 'object',
262
+ properties: {
263
+ compact: { type: 'boolean', description: 'Return minimal token summary' }
264
+ }
265
+ }
266
+ },
267
+ {
268
+ name: 'chemx_team_feed',
269
+ description: 'Read the swarm activity feed and discussion threads from .chemx/index.db with token-efficient columnar formatting.',
270
+ inputSchema: {
271
+ type: 'object',
272
+ properties: {
273
+ sinceId: { type: 'number', description: 'Fetch only events newer than this sequential ID' },
274
+ threadId: { type: 'number', description: 'Filter events by parent discussion thread ID' },
275
+ taskId: { type: 'number', description: 'Filter events by linked task ID' },
276
+ agentId: { type: 'string', description: 'Filter events where agent is author, recipient, or public' },
277
+ limit: { type: 'number', description: 'Maximum number of feed events to return (default: 50)' }
278
+ }
279
+ }
280
+ },
281
+ {
282
+ name: 'chemx_team_post',
283
+ description: 'Post an event, progress update, thread reply, or @mention message to the shared swarm activity feed in .chemx/index.db.',
284
+ inputSchema: {
285
+ type: 'object',
286
+ required: ['message'],
287
+ properties: {
288
+ message: { type: 'string', description: 'Message or event description' },
289
+ authorId: { type: 'string', description: 'Agent handle posting the event (e.g. "@coder-1")' },
290
+ recipientId: { type: 'string', description: 'Optional target agent handle for direct pings/@mentions' },
291
+ threadId: { type: 'number', description: 'Optional parent thread ID for replies' },
292
+ taskId: { type: 'number', description: 'Optional linked task ID' },
293
+ filePath: { type: 'string', description: 'Optional file path associated with the update' },
294
+ eventType: { type: 'string', description: 'Event type (e.g. "broadcast", "mention", "progress", "blocker")' }
295
+ }
296
+ }
297
+ },
298
+ {
299
+ name: 'chemx_team_task',
300
+ description: 'Manage swarm tasks in .chemx/index.db (list, create, claim, complete, report blocker) with automatic AST health verification.',
301
+ inputSchema: {
302
+ type: 'object',
303
+ required: ['action'],
304
+ properties: {
305
+ action: { type: 'string', enum: ['list', 'create', 'claim', 'done', 'block'], description: 'Task action' },
306
+ taskId: { type: 'number', description: 'Target task ID for claim, done, or block' },
307
+ agentId: { type: 'string', description: 'Agent handle performing the action' },
308
+ title: { type: 'string', description: 'Task title (for create)' },
309
+ targetPath: { type: 'string', description: 'Target file path (for create)' },
310
+ tier: { type: 'string', description: 'Component tier (for create)' },
311
+ priority: { type: 'number', description: 'Priority weight 1-3 (for create)' },
312
+ blockedReason: { type: 'string', description: 'Reason for blocker (for block)' },
313
+ status: { type: 'string', description: 'Filter by status (for list)' }
314
+ }
315
+ }
316
+ },
317
+ {
318
+ name: 'chemx_team_lock',
319
+ description: 'Acquire or release a deterministic file lease in .chemx/index.db. If file is currently locked by another agent, enqueues into the zero-token FIFO lock queue.',
320
+ inputSchema: {
321
+ type: 'object',
322
+ required: ['action', 'filePath', 'agentId'],
323
+ properties: {
324
+ action: { type: 'string', enum: ['acquire', 'release', 'status'], description: 'Lock action' },
325
+ filePath: { type: 'string', description: 'Workspace relative file path to lock' },
326
+ agentId: { type: 'string', description: 'Agent handle' },
327
+ purpose: { type: 'string', description: 'Optional note explaining the lock purpose' },
328
+ ttlMs: { type: 'number', description: 'Lock expiration TTL in milliseconds (default: 300000)' }
329
+ }
330
+ }
331
+ }
332
+ ];
@@ -1,3 +1,7 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { auditFile } from '../audit.js';
4
+
1
5
  export const MCP_PROMPTS = [
2
6
  {
3
7
  name: 'chemx_remediate_hotspot',
@@ -37,6 +41,29 @@ export const getMcpPrompt = async (name, args = {}) => {
37
41
  }
38
42
  const framework = args.targetFramework || 'React/Vue';
39
43
 
44
+ const resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(process.cwd(), filePath);
45
+ const relPath = path.relative(process.cwd(), resolvedPath);
46
+ const diagnosticLines = [];
47
+
48
+ if (fs.existsSync(resolvedPath) && fs.statSync(resolvedPath).isFile()) {
49
+ const fileContent = fs.readFileSync(resolvedPath, 'utf-8');
50
+ const lineCount = fileContent.split(/\r?\n/).length;
51
+ const violations = auditFile(resolvedPath, relPath);
52
+ diagnosticLines.push(
53
+ '',
54
+ '### LIVE AST DIAGNOSTICS:',
55
+ `- Target File: \`${relPath}\``,
56
+ `- Total Lines: ${lineCount}L (Molecular limit: 100L)`,
57
+ `- Active Violations: ${violations.length}`
58
+ );
59
+ if (violations.length > 0) {
60
+ diagnosticLines.push('Critical & High Hazards:');
61
+ for (const v of violations.slice(0, 10)) {
62
+ diagnosticLines.push(` * Line ${v.line}: [${v.ruleId}] ${v.message} (${v.severity})`);
63
+ }
64
+ }
65
+ }
66
+
40
67
  const userText = [
41
68
  `Act as a Principal Systems Architect. Surgically refactor the monolithic file \`${filePath}\` according to Chemical X Molecular Architecture Standards:`,
42
69
  '',
@@ -49,6 +76,7 @@ export const getMcpPrompt = async (name, args = {}) => {
49
76
  '6. Co-located Types: Co-locate granular types/*.d.ts inside each capsule (< 100 lines). Avoid type monoliths.',
50
77
  '7. Zero synthetic or mock data: Return live data or explicit empty states.',
51
78
  `8. Framework: Calibrate bindings for ${framework}.`,
79
+ ...diagnosticLines,
52
80
  '',
53
81
  `Target file: \`${filePath}\`. Please produce a phased decomposition plan followed by modular capsule implementations.`
54
82
  ].join('\n');