@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
@@ -8,9 +8,11 @@ import {
8
8
  toCamelCase,
9
9
  buildReactComponent,
10
10
  buildVueComponent,
11
- buildSvelteComponent
11
+ buildSvelteComponent,
12
+ buildIndex
12
13
  } from './generator-templates.js';
13
14
  import { handleCheckCommand } from './search-commands.js';
15
+ import { obtainLicenseKey } from './license.js';
14
16
 
15
17
  test('generator-templates: toPascalCase and toCamelCase convert slugs correctly', () => {
16
18
  assert.strictEqual(toPascalCase('m-user-avatar'), 'UserAvatar');
@@ -123,3 +125,61 @@ test('generator-templates: binds to @chemx/x-atoms when atomsPackage option is p
123
125
  assert.ok(svelteCode.includes('<AtomButton'));
124
126
  assert.ok(!svelteCode.includes('<button'));
125
127
  });
128
+
129
+ test('generator-templates: supports hasController = false for atom/lean capsules', () => {
130
+ const reactCode = buildReactComponent('a-badge', 'Badge', { hasController: false });
131
+ assert.ok(!reactCode.includes('.controller'));
132
+ assert.ok(!reactCode.includes('useBadgeController'));
133
+ assert.ok(reactCode.includes('canProceed = true'));
134
+
135
+ const vueCode = buildVueComponent('a-badge', 'Badge', { hasController: false });
136
+ assert.ok(!vueCode.includes('.controller'));
137
+ assert.ok(!vueCode.includes('useBadgeController'));
138
+ assert.ok(vueCode.includes('canProceed = true'));
139
+
140
+ const svelteCode = buildSvelteComponent('a-badge', 'Badge', { hasController: false });
141
+ assert.ok(!svelteCode.includes('.controller'));
142
+ assert.ok(!svelteCode.includes('createBadgeController'));
143
+ assert.ok(svelteCode.includes('canProceed: true'));
144
+
145
+ const indexCode = buildIndex('a-badge', 'Badge', 'tsx', false);
146
+ assert.ok(!indexCode.includes('useBadgeController'));
147
+ assert.ok(indexCode.includes("export { Badge } from './a-badge';"));
148
+ });
149
+
150
+ test('runGenerateWizard: scaffolds atom capsule without controller or controller import', async () => {
151
+ const tmpDir = path.resolve(process.cwd(), 'scratch/test-gen-atom');
152
+ if (fs.existsSync(tmpDir)) fs.rmSync(tmpDir, { recursive: true, force: true });
153
+
154
+ const res = await runGenerateWizard([
155
+ 'atom',
156
+ 'badge-pill',
157
+ '-y',
158
+ `--dir=${tmpDir}`,
159
+ '--framework=react'
160
+ ]);
161
+
162
+ assert.strictEqual(res.success, true);
163
+ assert.strictEqual(res.tier, 'atom');
164
+ assert.strictEqual(res.capsuleName, 'a-badge-pill');
165
+
166
+ const capsuleDir = path.join(tmpDir, 'a-badge-pill');
167
+ assert.ok(fs.existsSync(path.join(capsuleDir, 'a-badge-pill.tsx')));
168
+ assert.ok(!fs.existsSync(path.join(capsuleDir, 'a-badge-pill.controller.ts')));
169
+
170
+ const compContent = fs.readFileSync(path.join(capsuleDir, 'a-badge-pill.tsx'), 'utf-8');
171
+ assert.ok(!compContent.includes('useBadgePillController'));
172
+ assert.ok(!compContent.includes('.controller'));
173
+
174
+ const indexContent = fs.readFileSync(path.join(capsuleDir, 'index.ts'), 'utf-8');
175
+ assert.ok(!indexContent.includes('useBadgePillController'));
176
+
177
+ fs.rmSync(tmpDir, { recursive: true, force: true });
178
+ });
179
+
180
+ test('obtainLicenseKey: returns null immediately when --headless is passed without interactive prompts', async () => {
181
+ const key = await obtainLicenseKey(['--headless']);
182
+ assert.strictEqual(key, null);
183
+ });
184
+
185
+
package/cli/help.js CHANGED
@@ -51,6 +51,25 @@ export const printHelp = () => {
51
51
  ` Flags: ${CYAN}--json${RESET}, ${CYAN}--silent${RESET}, ${CYAN}--raw${RESET}, ${CYAN}--summary${RESET}`,
52
52
  ` Examples: ${CYAN}npx chemx build${RESET} or ${CYAN}npx chemx build -- pnpm build${RESET}`,
53
53
  '',
54
+ ` ${CYAN}verify${RESET} [options] ${DIM}(alias: check:all)${RESET}`,
55
+ ` Zero-token-burn project verification pipeline (AST Audit + Typecheck + Tests).`,
56
+ ` Runs all verification layers silently and emits a single summary card (~45 tokens if green).`,
57
+ ` AI agents should always run this instead of separate raw shell commands.`,
58
+ ` Flags: ${CYAN}--dir=<path>${RESET}, ${CYAN}--build${RESET}, ${CYAN}--json${RESET}`,
59
+ ` Examples: ${CYAN}npx chemx verify${RESET} or ${CYAN}npx chemx verify --json${RESET}`,
60
+ '',
61
+ ` ${CYAN}typecheck${RESET} [options] [-- <command>] ${DIM}(aliases: check:types, tsc)${RESET}`,
62
+ ` Silent TypeScript typecheck audit. Drops compiler noise and returns structured`,
63
+ ` file, line, code, and suggestion metadata only if errors exist. Zero noise when clean.`,
64
+ ` Flags: ${CYAN}--json${RESET}, ${CYAN}--raw${RESET}`,
65
+ ` Examples: ${CYAN}npx chemx typecheck${RESET} or ${CYAN}npx chemx typecheck --json${RESET}`,
66
+ '',
67
+ ` ${CYAN}test${RESET} [options] [-- <command>] ${DIM}(aliases: tests, check:test)${RESET}`,
68
+ ` Silent, failure-only project test runner. Suppresses hundreds of passing checkmarks`,
69
+ ` and runtime banners; emits ONLY failing test assertions and stack diffs.`,
70
+ ` Flags: ${CYAN}--json${RESET}, ${CYAN}--raw${RESET}`,
71
+ ` Examples: ${CYAN}npx chemx test${RESET} or ${CYAN}npx chemx test --json${RESET}`,
72
+ '',
54
73
  ` ${CYAN}audit${RESET} [options]`,
55
74
  ` Run the 7-Pillar Molecular Architecture static analysis audit.`,
56
75
  ` Scans AST for line budgets, control flow booleans, nested ternaries,`,
@@ -97,20 +116,35 @@ export const printHelp = () => {
97
116
  ` ${CYAN}mcp${RESET} ${DIM}(aliases: mcp-server)${RESET}`,
98
117
  ` ${GREEN}[FREE]${RESET} Launch the Chemical X Model Context Protocol (MCP) server.`,
99
118
  ` Communicates via JSON-RPC 2.0 stdio with Cursor, Claude Desktop, Windsurf, and Antigravity.`,
100
- ` Exposes 6 core tools (chemx_query_patterns, chemx_autofix, chemx_audit,`,
101
- ` chemx_generate_capsule, chemx_get_refactor_prompt, chemx_audit_build),`,
102
- ` living resources (chemx://directives, chemx://scorecard), and prompts.`,
119
+ ` Exposes 10 AST-aware tools:`,
120
+ ` • Discovery: chemx_query_patterns, chemx_q`,
121
+ ` • Reading & Patching: chemx_read, chemx_patch`,
122
+ ` • Verification: chemx_verify, chemx_typecheck, chemx_test, chemx_audit, chemx_check, chemx_audit_build`,
123
+ ` • Remediation: chemx_autofix, chemx_generate_capsule, chemx_get_refactor_prompt`,
124
+ ` Plus living resources (chemx://directives, chemx://scorecard) and prompts.`,
103
125
  ` Example: ${CYAN}npx chemx mcp${RESET}`,
104
126
  '',
105
127
  ` ${CYAN}install-mcp${RESET} [directory] ${DIM}(aliases: setup-mcp)${RESET}`,
106
- ` ${GREEN}[FREE]${RESET} Auto-configure Chemical X MCP server for your project and tools.`,
128
+ ` ${GREEN}[FREE]${RESET} Auto-configure Chemical X MCP server for your project and editors.`,
107
129
  ` Registers in .cursor/mcp.json, .vscode/mcp.json, and ~/.gemini/config/mcp_config.json.`,
108
130
  ` Example: ${CYAN}npx chemx install-mcp${RESET}`,
109
131
  '',
132
+ ` ${CYAN}--version${RESET}, ${CYAN}-v${RESET}, ${CYAN}version${RESET}`,
133
+ ` Display current Chemical X package version string.`,
134
+ '',
110
135
  ` ${CYAN}help${RESET}, ${CYAN}--help${RESET}, ${CYAN}-h${RESET}`,
111
136
  ` Display this comprehensive CLI documentation and options guide.`,
112
137
  '',
113
138
  `${BOLD}AUDIT OPTIONS & FLAGS${RESET}`,
139
+ ` ${CYAN}--fast${RESET}, ${CYAN}--quick${RESET}`,
140
+ ` Fast scan: verify line budgets, token burn, and file metrics, bypassing deep AST traversal.`,
141
+ '',
142
+ ` ${CYAN}--git${RESET}, ${CYAN}--changed${RESET}`,
143
+ ` Scope audit strictly to modified, staged, or untracked source files in git.`,
144
+ '',
145
+ ` ${CYAN}-y${RESET}, ${CYAN}--yes${RESET}`,
146
+ ` Accept defaults and bypass interactive pre-flight wizard questions.`,
147
+ '',
114
148
  ` ${CYAN}--dir=<path>${RESET}`,
115
149
  ` Directory to analyze. Defaults to ${CYAN}src${RESET} if present, else current working directory.`,
116
150
  ` Example: ${CYAN}npx chemx audit --dir=apps/web/src${RESET}`,
package/cli/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ import './silence-warnings.js';
3
4
  import fs from 'node:fs';
4
5
  import path from 'node:path';
5
6
  import {
@@ -30,14 +31,32 @@ import {
30
31
  evaluateAuditFailure,
31
32
  isNonInteractiveSession
32
33
  } from './audit/rules-predicates.js';
34
+ import { runAuditPreflight, resolveGitAuditScope } from './audit-preflight.js';
33
35
  import { runInstallWizard } from './installer.js';
34
36
  import { runBadgeCommand } from './badge.js';
35
37
  import { runBuildAudit } from './build.js';
36
38
  import { runSearch, syncSearchIndex, resolveTargetDir, syncViolationsIndex, recordAuditSnapshot, handleCheckCommand } from './search.js';
37
39
  import { runMutatorCli } from './mutators.js';
38
40
  import { runReaderCli, readTokenOptimized } from './reader.js';
39
- import { runPatcherCli, patchFile } from './patcher.js';
41
+ import { runPatcherCli, patchFile, runWriterCli, writeFile } from './patcher.js';
40
42
  import { runMcpServer, runMcpInstaller } from './mcp/index.js';
43
+ import { runTypecheckAudit, runTestAudit, runProjectVerify } from './verify.js';
44
+ import { runTeamCli } from './team/index.js';
45
+ import { startUiServer } from './ui-server.js';
46
+ import { sanitizeOutputStreams } from './terminal.js';
47
+
48
+ sanitizeOutputStreams();
49
+
50
+ const getPackageVersion = () => {
51
+ try {
52
+ const pkgPath = new URL('../package.json', import.meta.url);
53
+ const pkgContent = fs.readFileSync(pkgPath, 'utf-8');
54
+ const pkg = JSON.parse(pkgContent);
55
+ return pkg.version || 'unknown';
56
+ } catch {
57
+ return 'unknown';
58
+ }
59
+ };
41
60
 
42
61
  const rawArgs = process.argv.slice(2);
43
62
  const invokedBin = path.basename(process.argv[1] || '');
@@ -84,8 +103,42 @@ export const runAudit = async (customDir = null, isCli = false) => {
84
103
  const costFlag = rawArgs.find((arg) => arg.startsWith('--cost-per-million='));
85
104
  const costPerMillion = costFlag ? parseFloat(costFlag.split('=')[1]) : null;
86
105
 
87
- const targetDir = resolveTargetDir(customDir, dirFlag);
88
- const report = executeAstAudit(targetDir, { outputFile, model, costPerMillion });
106
+ const isNonInteractive = isNonInteractiveSession(rawArgs);
107
+ const isInteractive = !isNonInteractive && Boolean(process.stdin.isTTY && process.stdout.isTTY);
108
+
109
+ let targetDir = resolveTargetDir(customDir, dirFlag);
110
+ let isFast = rawArgs.includes('--fast') || rawArgs.includes('--quick');
111
+ let fileList = null;
112
+
113
+ const hasGitFlag = rawArgs.includes('--git') || rawArgs.includes('--changed');
114
+ if (hasGitFlag) {
115
+ const gitScope = resolveGitAuditScope(process.cwd());
116
+ if (gitScope.ok) {
117
+ fileList = gitScope.files;
118
+ }
119
+ }
120
+
121
+ const shouldRunPreflight = isCli && isInteractive && !isJson && !isMarkdown && !isShare;
122
+ if (shouldRunPreflight) {
123
+ const preflight = await runAuditPreflight(rawArgs, {
124
+ customDir,
125
+ defaultDir: targetDir,
126
+ cwd: process.cwd()
127
+ });
128
+ targetDir = preflight.targetDir;
129
+ isFast = preflight.fast;
130
+ fileList = preflight.fileList;
131
+ }
132
+
133
+ const auditOptions = {
134
+ outputFile,
135
+ model,
136
+ costPerMillion,
137
+ fast: isFast,
138
+ fileList
139
+ };
140
+
141
+ const report = executeAstAudit(targetDir, auditOptions);
89
142
  saveAuditSnapshot(report);
90
143
  const syncRes = syncSearchIndex(targetDir, process.cwd());
91
144
  if (syncRes?.db) {
@@ -93,11 +146,19 @@ export const runAudit = async (customDir = null, isCli = false) => {
93
146
  recordAuditSnapshot(syncRes.db, report);
94
147
  }
95
148
 
96
- const hasCriticalOrHigh = report.violations.some((v) => v.severity === 'CRITICAL' || v.severity === 'HIGH');
97
- const isStrictFail = isStrict && report.violations.length > 0;
149
+ const isSevereViolation = (v) => {
150
+ const isCritical = v.severity === 'CRITICAL';
151
+ const isHigh = v.severity === 'HIGH';
152
+ return isCritical || isHigh;
153
+ };
154
+
155
+ const hasCriticalOrHigh = report.violations.some(isSevereViolation);
156
+ const hasViolations = report.violations.length > 0;
157
+ const isStrictFail = isStrict && hasViolations;
98
158
  const isGradeFail = isGradeBelowMinimum(report.health.grade, minGrade);
99
- const isScoreFail = minScore !== null && !isNaN(minScore) && report.health.score < minScore;
100
- const hasThreshold = Boolean(minGrade) || (minScore !== null && !isNaN(minScore));
159
+ const hasMinScore = minScore !== null && !isNaN(minScore);
160
+ const isScoreFail = hasMinScore && report.health.score < minScore;
161
+ const hasThreshold = Boolean(minGrade) || hasMinScore;
101
162
  const isDefaultFail = !hasThreshold && !isStrict && hasCriticalOrHigh;
102
163
  const hasFailingViolations = evaluateAuditFailure([isStrictFail, isDefaultFail, isGradeFail, isScoreFail]);
103
164
 
@@ -120,12 +181,9 @@ export const runAudit = async (customDir = null, isCli = false) => {
120
181
  process.exit(0);
121
182
  }
122
183
 
123
- const isNonInteractive = isNonInteractiveSession(rawArgs);
124
- const isInteractive = !isNonInteractive && Boolean(process.stdin.isTTY && process.stdout.isTTY);
125
-
126
184
  if (isInteractive && !isUnroll) {
127
185
  const handleReAudit = () => {
128
- const refreshed = executeAstAudit(targetDir, { outputFile, model, costPerMillion });
186
+ const refreshed = executeAstAudit(targetDir, auditOptions);
129
187
  saveAuditSnapshot(refreshed);
130
188
  return refreshed;
131
189
  };
@@ -198,11 +256,16 @@ export {
198
256
  runBuildAudit,
199
257
  runSearch,
200
258
  syncSearchIndex,
201
- startMcpServer,
259
+ runMcpServer,
260
+ runMcpServer as startMcpServer,
261
+ runMcpInstaller,
202
262
  runReaderCli,
203
263
  readTokenOptimized,
204
264
  runPatcherCli,
205
- patchFile
265
+ patchFile,
266
+ runWriterCli,
267
+ writeFile,
268
+ runTeamCli
206
269
  };
207
270
 
208
271
  const main = async () => {
@@ -215,6 +278,11 @@ const main = async () => {
215
278
  }
216
279
 
217
280
  switch (firstArg) {
281
+ case 'team':
282
+ case 'swarm':
283
+ case 'feed':
284
+ runTeamCli(rawArgs.slice(1), true);
285
+ break;
218
286
  case 'mcp':
219
287
  case 'mcp-server':
220
288
  case 'server':
@@ -228,6 +296,9 @@ const main = async () => {
228
296
  case 'edit':
229
297
  runPatcherCli(rawArgs.slice(1), true);
230
298
  break;
299
+ case 'write':
300
+ runWriterCli(rawArgs.slice(1), true);
301
+ break;
231
302
  case 'search':
232
303
  case 'q':
233
304
  case 'query':
@@ -257,7 +328,6 @@ const main = async () => {
257
328
  await runInstallWizard(rawArgs[1] || process.cwd());
258
329
  break;
259
330
  case 'check':
260
- case 'verify':
261
331
  handleCheckCommand(rawArgs[1], {
262
332
  isJson: rawArgs.includes('--json'),
263
333
  isCli: true
@@ -290,6 +360,34 @@ const main = async () => {
290
360
  case 'setup-mcp':
291
361
  await runMcpInstaller(rawArgs.slice(1));
292
362
  break;
363
+ case '-v':
364
+ case '--version':
365
+ case 'version':
366
+ process.stdout.write(`create-chemx v${getPackageVersion()}\n`);
367
+ break;
368
+ case 'verify':
369
+ case 'check:all':
370
+ await runProjectVerify(rawArgs.slice(1), true);
371
+ break;
372
+ case 'typecheck':
373
+ case 'check:types':
374
+ case 'tsc':
375
+ await runTypecheckAudit(rawArgs.slice(1), true);
376
+ break;
377
+ case 'test':
378
+ case 'tests':
379
+ case 'check:test':
380
+ await runTestAudit(rawArgs.slice(1), true);
381
+ break;
382
+ case 'ui':
383
+ case 'preview':
384
+ case 'dashboard':
385
+ {
386
+ const portArg = rawArgs.find((a) => a.startsWith('--port='));
387
+ const port = portArg ? parseInt(portArg.split('=')[1], 10) : 4173;
388
+ await startUiServer({ port, isCli: true, cwd: process.cwd() });
389
+ }
390
+ break;
293
391
  case 'help':
294
392
  case '--help':
295
393
  case '-h':
@@ -2,15 +2,66 @@ export const buildPreCommitHookScript = (minGrade = 'B', minScore = 80) => `#!/b
2
2
  # Chemical X Protocol: Pre-Commit Line Budget & Architecture Gatekeeper
3
3
  # Free architectural guardrail preventing context bloat and monolith sprawl.
4
4
 
5
- MIN_GRADE="\${CHEMX_MIN_GRADE:-${minGrade}}"
6
- MIN_SCORE="\${CHEMX_MIN_SCORE:-${minScore}}"
7
- MAX_LINES="\${CHEMX_MAX_LINES:-500}"
8
- MAX_MOLECULE_LINES="\${CHEMX_MAX_MOLECULE_LINES:-100}"
9
-
10
5
  REPO_ROOT="\$(git rev-parse --show-toplevel 2>/dev/null)"
11
6
  [ -z "\$REPO_ROOT" ] && exit 0
12
7
  cd "\$REPO_ROOT" || exit 1
13
8
 
9
+ # Delegate to version-controlled script if present
10
+ if [ -f "\$REPO_ROOT/scripts/pre-commit.sh" ]; then
11
+ exec "\$REPO_ROOT/scripts/pre-commit.sh" "\$@"
12
+ fi
13
+
14
+ # Detect TTY and color support
15
+ if [ -t 1 ] && [ -z "\$NO_COLOR" ] && [ "\$TERM" != "dumb" ]; then
16
+ C_RESET="\$(printf '\\033[0m')"
17
+ C_BOLD="\$(printf '\\033[1m')"
18
+ C_RED="\$(printf '\\033[31m')"
19
+ C_GREEN="\$(printf '\\033[32m')"
20
+ C_YELLOW="\$(printf '\\033[33m')"
21
+ C_CYAN="\$(printf '\\033[36m')"
22
+ C_BLUE="\$(printf '\\033[38;2;98;201;255m')"
23
+ else
24
+ C_RESET=""
25
+ C_BOLD=""
26
+ C_RED=""
27
+ C_GREEN=""
28
+ C_YELLOW=""
29
+ C_CYAN=""
30
+ C_BLUE=""
31
+ export NO_COLOR=1
32
+ fi
33
+
34
+ # Load thresholds from .chemx/config.json if available
35
+ CONF_MAX_LINES=""
36
+ CONF_MAX_MOL=""
37
+ CONF_MIN_GRADE=""
38
+ CONF_MIN_SCORE=""
39
+ CONFIG_FILE="\$REPO_ROOT/.chemx/config.json"
40
+
41
+ if [ -f "\$CONFIG_FILE" ]; then
42
+ if command -v node >/dev/null 2>&1; then
43
+ eval \$(node -e "
44
+ try {
45
+ const c = JSON.parse(require('fs').readFileSync('\$CONFIG_FILE', 'utf8'));
46
+ if (c.maxLineCount || c.maxLines) console.log('CONF_MAX_LINES=' + (c.maxLineCount || c.maxLines));
47
+ if (c.maxMoleculeLineCount || c.maxMoleculeLines) console.log('CONF_MAX_MOL=' + (c.maxMoleculeLineCount || c.maxMoleculeLines));
48
+ if (c.minGrade) console.log('CONF_MIN_GRADE=' + c.minGrade);
49
+ if (c.minScore) console.log('CONF_MIN_SCORE=' + c.minScore);
50
+ } catch (e) {}
51
+ ")
52
+ else
53
+ CONF_MAX_LINES=\$(grep -o '"maxLineCount"[[:space:]]*:[[:space:]]*[0-9]*' "\$CONFIG_FILE" 2>/dev/null | grep -o '[0-9]*\$')
54
+ CONF_MAX_MOL=\$(grep -o '"maxMoleculeLineCount"[[:space:]]*:[[:space:]]*[0-9]*' "\$CONFIG_FILE" 2>/dev/null | grep -o '[0-9]*\$')
55
+ CONF_MIN_GRADE=\$(grep -o '"minGrade"[[:space:]]*:[[:space:]]*"[^"]*"' "\$CONFIG_FILE" 2>/dev/null | sed 's/.*"minGrade"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\\1/')
56
+ CONF_MIN_SCORE=\$(grep -o '"minScore"[[:space:]]*:[[:space:]]*[0-9]*' "\$CONFIG_FILE" 2>/dev/null | grep -o '[0-9]*\$')
57
+ fi
58
+ fi
59
+
60
+ MIN_GRADE="\${CHEMX_MIN_GRADE:-\${CONF_MIN_GRADE:-${minGrade}}}"
61
+ MIN_SCORE="\${CHEMX_MIN_SCORE:-\${CONF_MIN_SCORE:-${minScore}}}"
62
+ MAX_LINES="\${CHEMX_MAX_LINES:-\${CONF_MAX_LINES:-500}}"
63
+ MAX_MOLECULE_LINES="\${CHEMX_MAX_MOLECULE_LINES:-\${CONF_MAX_MOL:-100}}"
64
+
14
65
  STAGED_FILES=\$(git diff --cached --name-only --diff-filter=ACM | grep -E '\\.(jsx?|tsx?|vue|svelte)\$' | grep -vE '(\\.(d\\.ts|min\\.|test\\.|spec\\.))')
15
66
  [ -z "\$STAGED_FILES" ] && exit 0
16
67
 
@@ -21,14 +72,18 @@ for F in \$STAGED_FILES; do
21
72
  L=\$(wc -l < "\$F" | tr -d ' ')
22
73
  case "\$F" in
23
74
  *molecules*|*/m-*|*m-*)
24
- [ "\$L" -gt "\$MAX_MOLECULE_LINES" ] && FAILED=1 && ERRORS="\${ERRORS}\\n \\033[31m✕\\033[0m \$F (\$L LOC > \$MAX_MOLECULE_LINES molecule limit)" ;;
75
+ [ "\$L" -gt "\$MAX_MOLECULE_LINES" ] && FAILED=1 && ERRORS="\${ERRORS}\\n \${C_RED}✕\${C_RESET} \$F (\$L LOC > \$MAX_MOLECULE_LINES molecule limit)" ;;
25
76
  *)
26
- [ "\$L" -gt "\$MAX_LINES" ] && FAILED=1 && ERRORS="\${ERRORS}\\n \\033[31m✕\\033[0m \$F (\$L LOC > \$MAX_LINES file budget)" ;;
77
+ [ "\$L" -gt "\$MAX_LINES" ] && FAILED=1 && ERRORS="\${ERRORS}\\n \${C_RED}✕\${C_RESET} \$F (\$L LOC > \$MAX_LINES file budget)" ;;
27
78
  esac
28
79
  done
29
80
 
30
81
  if [ "\$FAILED" -eq 1 ]; then
31
- printf "\\n\\033[1m\\033[31m[Chemical X] Commit Blocked: Staged files exceed architectural line budgets\\033[0m\\n\$ERRORS\\n\\n"
82
+ printf "\\n%s%s[Chemical X] Commit Blocked: Staged files exceed architectural line budgets%s\\n" "\$C_BOLD" "\$C_RED" "\$C_RESET"
83
+ printf "%b\\n\\n" "\$ERRORS"
84
+ printf "%sMonolithic files degrade AI context windows and cause hallucination loops.%s\\n" "\$C_YELLOW" "\$C_RESET"
85
+ printf "Decompose large files into single-purpose crystalline capsules or configure thresholds in .chemx/config.json before committing.\\n\\n"
86
+ exit 1
32
87
  fi
33
88
 
34
89
  AUDIT_BIN=""
@@ -43,16 +98,15 @@ elif command -v npx >/dev/null 2>&1; then
43
98
  fi
44
99
 
45
100
  if [ -n "\$AUDIT_BIN" ]; then
46
- printf "\\033[38;2;98;201;255m[Chemical X] Verifying architectural health (Min Grade: %s, Min Score: %s)...\\033[0m\\n" "\$MIN_GRADE" "\$MIN_SCORE"
101
+ printf "%s[Chemical X] Verifying architectural health (Min Grade: %s, Min Score: %s)...%s\\n" "\$C_BLUE" "\$MIN_GRADE" "\$MIN_SCORE" "\$C_RESET"
47
102
  if ! \$AUDIT_BIN audit --min-grade="\$MIN_GRADE" --min-score="\$MIN_SCORE" --non-interactive < /dev/null; then
48
- printf "\\n\\033[1m\\033[31m[Chemical X] Commit Blocked: Architectural health verification failed\\033[0m\\n"
49
- printf "\\033[36m💡 Tip: Want crystalline drop-in templates? Run 'npm create chemx' or sponsor at https://github.com/sponsors/Chemical-X-Protocol\\033[0m\\n\\n"
103
+ printf "\\n%s%s[Chemical X] Commit Blocked: Architectural health verification failed%s\\n" "\$C_BOLD" "\$C_RED" "\$C_RESET"
104
+ printf "%s💡 Tip: Want crystalline drop-in templates? Run 'npm create chemx' or sponsor at https://github.com/sponsors/Chemical-X-Protocol%s\\n\\n" "\$C_CYAN" "\$C_RESET"
50
105
  exit 1
51
106
  fi
52
107
  fi
53
108
 
54
- [ "\$FAILED" -eq 1 ] && exit 1
55
- printf "\\033[32m✔ [Chemical X] Pre-commit architectural guardrails passed.\\033[0m\\n"
109
+ printf "%s✔ [Chemical X] Pre-commit architectural guardrails passed.%s\\n" "\$C_GREEN" "\$C_RESET"
56
110
  exit 0
57
111
  `;
58
112
 
@@ -19,5 +19,7 @@ export declare function installPreCommitHook(targetDir?: string, options?: Insta
19
19
  export declare function installGitHubWorkflow(targetDir?: string, options?: InstallOptions): boolean;
20
20
  export declare function saveProjectConfig(targetDir?: string, config?: Partial<ProjectConfig>): void;
21
21
  export declare function areGuardrailsInstalled(targetDir?: string): boolean;
22
+ export declare function ensurePackageScripts(targetDir?: string): boolean;
23
+ export declare function installAgentSearchConfig(targetDir?: string): Promise<boolean>;
22
24
  export declare function runInstallWizard(targetDir?: string): Promise<void>;
23
25
 
package/cli/installer.js CHANGED
@@ -51,6 +51,7 @@ export const installPreCommitHook = (targetDir = '.', options = {}) => {
51
51
  fs.writeFileSync(hookPath, buildPreCommitHookScript(options.minGrade, options.minScore), { mode: 0o755 });
52
52
  const relativeHook = path.relative(path.resolve(targetDir), hookPath);
53
53
  process.stdout.write(` \x1b[32m✔\x1b[0m Installed git pre-commit hook: ${relativeHook} (chmod +x)\n`);
54
+ ensurePackageScripts(targetDir);
54
55
  return true;
55
56
  };
56
57
 
@@ -94,40 +95,63 @@ export const areGuardrailsInstalled = (targetDir = '.') => {
94
95
  return hasWf && hasHook;
95
96
  };
96
97
 
97
- export const installAgentSearchConfig = async (targetDir = '.') => {
98
+ export const ensurePackageScripts = (targetDir = '.') => {
98
99
  const resolvedTarget = path.resolve(targetDir);
99
-
100
- // 1. Update package.json scripts
101
100
  const pkgPath = path.join(resolvedTarget, 'package.json');
102
- if (fs.existsSync(pkgPath)) {
103
- try {
104
- const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
105
- pkg.scripts = pkg.scripts || {};
106
- pkg.scripts.q = 'chemx search';
107
- pkg.scripts.search = 'chemx search';
101
+ if (!fs.existsSync(pkgPath)) return false;
102
+
103
+ try {
104
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
105
+ pkg.scripts = pkg.scripts || {};
106
+ if (!pkg.scripts.chemx) {
107
+ pkg.scripts.chemx = 'chemx';
108
108
  fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n', 'utf-8');
109
- process.stdout.write(' \x1b[32m✔\x1b[0m Configured "q" and "search" scripts in package.json (run via pnpm q <query>)\n');
110
- } catch {
111
- process.stdout.write(' \x1b[33m⚠\x1b[0m Could not update package.json scripts\n');
109
+ process.stdout.write(' \x1b[32m✔\x1b[0m Configured minimal "chemx": "chemx" entry in package.json\n');
112
110
  }
111
+ return true;
112
+ } catch {
113
+ process.stdout.write(' \x1b[33m⚠\x1b[0m Could not update package.json scripts\n');
114
+ return false;
113
115
  }
116
+ };
117
+
118
+ export const installAgentSearchConfig = async (targetDir = '.') => {
119
+ const resolvedTarget = path.resolve(targetDir);
120
+
121
+ // 1. Update package.json with minimal single entry
122
+ ensurePackageScripts(resolvedTarget);
114
123
 
115
124
  // 2. Inject rule into AGENTS.md
116
125
  const agentsPath = path.join(resolvedTarget, 'AGENTS.md');
117
- const searchDirective = `
126
+ const agentDirectives = `
118
127
  ## Chemical X Codebase Query Machine Protocol
119
- - Search First Rule: AI agents MUST invoke 'pnpm q "<query>"' (or 'npx chemx search "<query>"') before running broad ripgrep, find, or file dumping.
120
- - AST Architecture Intelligence: Always leverage 'pnpm q' to inspect component tiers, exported symbols, props, and hooks with minimal token burn.
121
- - Inspect Mode: Use 'pnpm q "<capsule-name>" --inspect' to examine props and hooks without catting entire source files.
122
- - JSON Mode: Use 'pnpm q "<query>" --json' for zero-overhead, machine-readable agent lookups.
128
+ - Search First Rule: AI agents MUST invoke 'pnpm chemx q "<query>"' (or 'npx chemx search "<query>"') before running broad ripgrep, find, or file dumping.
129
+ - AST Architecture Intelligence: Always leverage 'pnpm chemx q' to inspect component tiers, exported symbols, props, and hooks with minimal token burn.
130
+ - Inspect Mode: Use 'pnpm chemx q "<capsule-name>" --inspect' to examine props and hooks without reading entire source files.
131
+ - JSON Mode: Use 'pnpm chemx q "<query>" --json' for zero-overhead, machine-readable agent lookups.
132
+
133
+ ## Chemical X Verification-First Protocol & Zero-Token-Burn Pipeline
134
+ - Verification First Rule: AI agents MUST NEVER run raw, unthrottled "npm test", "pnpm test", "vitest", "tsc --noEmit", or "npm run build" directly in a bash subshell.
135
+ - MCP Verification Tools First: AI agents MUST invoke dedicated Chemical X MCP tools or CLI wrappers ('pnpm chemx verify', 'npx chemx verify', 'pnpm chemx build', 'npx chemx build') before running terminal commands.
123
136
  `;
124
137
 
125
138
  if (fs.existsSync(agentsPath)) {
126
139
  try {
127
140
  const content = fs.readFileSync(agentsPath, 'utf-8');
128
- if (!content.includes('Chemical X Codebase Query Machine Protocol')) {
129
- fs.appendFileSync(agentsPath, `\n${searchDirective}\n`, 'utf-8');
130
- process.stdout.write(' \x1b[32m✔\x1b[0m Injected search-first directive into AGENTS.md\n');
141
+ const hasQueryProtocol = content.includes('Chemical X Codebase Query Machine Protocol');
142
+ const hasVerifyProtocol = content.includes('Chemical X Verification-First Protocol');
143
+
144
+ if (!hasQueryProtocol && !hasVerifyProtocol) {
145
+ fs.appendFileSync(agentsPath, `\n${agentDirectives}\n`, 'utf-8');
146
+ process.stdout.write(' \x1b[32m✔\x1b[0m Injected query and verification directives into AGENTS.md\n');
147
+ } else if (!hasVerifyProtocol) {
148
+ const verifyOnly = `
149
+ ## Chemical X Verification-First Protocol & Zero-Token-Burn Pipeline
150
+ - Verification First Rule: AI agents MUST NEVER run raw, unthrottled "npm test", "pnpm test", "vitest", "tsc --noEmit", or "npm run build" directly in a bash subshell.
151
+ - MCP Verification Tools First: AI agents MUST invoke dedicated Chemical X MCP tools or CLI wrappers ('pnpm chemx verify', 'npx chemx verify', 'pnpm chemx build', 'npx chemx build') before running terminal commands.
152
+ `;
153
+ fs.appendFileSync(agentsPath, `\n${verifyOnly}\n`, 'utf-8');
154
+ process.stdout.write(' \x1b[32m✔\x1b[0m Injected verification-first directive into AGENTS.md\n');
131
155
  }
132
156
  } catch (err) {
133
157
  const error = err instanceof Error ? err : new Error(String(err));
@@ -193,7 +217,10 @@ export const runInstallWizard = async (targetDir = '.') => {
193
217
 
194
218
  if (shouldHook) {
195
219
  if (isGit) installPreCommitHook(targetDir, opts);
196
- else process.stdout.write(' \x1b[33m⚠\x1b[0m Skipped .git/hooks (current directory is not a git repository root or submodule).\n');
220
+ else {
221
+ process.stdout.write(' \x1b[33m⚠\x1b[0m Skipped .git/hooks (current directory is not a git repository root or submodule).\n');
222
+ ensurePackageScripts(targetDir);
223
+ }
197
224
  }
198
225
  if (shouldWf) installGitHubWorkflow(targetDir, opts);
199
226
  if (shouldMcp) installAllMcpConfigs(targetDir, { silent: false });
@@ -0,0 +1,72 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { ensurePackageScripts } from './installer.js';
6
+
7
+ test('installer: ensurePackageScripts adds minimal "chemx": "chemx" when missing', () => {
8
+ const tmpDir = path.resolve(process.cwd(), 'scratch/test-installer-scripts-add');
9
+ if (fs.existsSync(tmpDir)) fs.rmSync(tmpDir, { recursive: true, force: true });
10
+ fs.mkdirSync(tmpDir, { recursive: true });
11
+
12
+ fs.writeFileSync(
13
+ path.join(tmpDir, 'package.json'),
14
+ JSON.stringify({
15
+ name: 'consumer-app',
16
+ scripts: {
17
+ dev: 'vite',
18
+ build: 'vite build'
19
+ }
20
+ }, null, 2),
21
+ 'utf-8'
22
+ );
23
+
24
+ const res = ensurePackageScripts(tmpDir);
25
+ assert.strictEqual(res, true);
26
+
27
+ const updatedPkg = JSON.parse(fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'));
28
+ assert.strictEqual(updatedPkg.scripts.chemx, 'chemx');
29
+ assert.strictEqual(updatedPkg.scripts.dev, 'vite');
30
+ assert.strictEqual(updatedPkg.scripts.build, 'vite build');
31
+ // Ensure we didn't add unnecessary extra scripts that muddle consumer package.json
32
+ assert.strictEqual(updatedPkg.scripts.verify, undefined);
33
+ assert.strictEqual(updatedPkg.scripts.q, undefined);
34
+
35
+ fs.rmSync(tmpDir, { recursive: true, force: true });
36
+ });
37
+
38
+ test('installer: ensurePackageScripts does not overwrite existing chemx script', () => {
39
+ const tmpDir = path.resolve(process.cwd(), 'scratch/test-installer-scripts-keep');
40
+ if (fs.existsSync(tmpDir)) fs.rmSync(tmpDir, { recursive: true, force: true });
41
+ fs.mkdirSync(tmpDir, { recursive: true });
42
+
43
+ fs.writeFileSync(
44
+ path.join(tmpDir, 'package.json'),
45
+ JSON.stringify({
46
+ name: 'consumer-app',
47
+ scripts: {
48
+ chemx: 'node ./custom-chemx.js'
49
+ }
50
+ }, null, 2),
51
+ 'utf-8'
52
+ );
53
+
54
+ const res = ensurePackageScripts(tmpDir);
55
+ assert.strictEqual(res, true);
56
+
57
+ const updatedPkg = JSON.parse(fs.readFileSync(path.join(tmpDir, 'package.json'), 'utf-8'));
58
+ assert.strictEqual(updatedPkg.scripts.chemx, 'node ./custom-chemx.js');
59
+
60
+ fs.rmSync(tmpDir, { recursive: true, force: true });
61
+ });
62
+
63
+ test('installer: ensurePackageScripts returns false gracefully if package.json does not exist', () => {
64
+ const tmpDir = path.resolve(process.cwd(), 'scratch/test-installer-no-pkg');
65
+ if (fs.existsSync(tmpDir)) fs.rmSync(tmpDir, { recursive: true, force: true });
66
+ fs.mkdirSync(tmpDir, { recursive: true });
67
+
68
+ const res = ensurePackageScripts(tmpDir);
69
+ assert.strictEqual(res, false);
70
+
71
+ fs.rmSync(tmpDir, { recursive: true, force: true });
72
+ });