@chemx/starter-kit 26.10.29-360 → 26.11.15-614

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 (103) hide show
  1. package/README.md +106 -433
  2. package/cli/audit/ratchet.js +52 -7
  3. package/cli/commands/cmd-router.js +3 -1
  4. package/cli/commands-schema-commit.js +3 -2
  5. package/cli/commands-schema-search.js +1 -0
  6. package/cli/commands-schema-team.js +11 -4
  7. package/cli/commit/commit-args.js +5 -4
  8. package/cli/commit/commit-hunks.js +108 -0
  9. package/cli/commit/commit-run.js +33 -2
  10. package/cli/config/index.js +28 -0
  11. package/cli/docs-check/command-tree.js +1 -1
  12. package/cli/generator-indexer.js +3 -2
  13. package/cli/index-seed.js +1 -0
  14. package/cli/lang/detect.js +189 -0
  15. package/cli/lang/legacy-extensions.js +9 -0
  16. package/cli/lang/records/c.js +53 -0
  17. package/cli/lang/records/cpp.js +76 -0
  18. package/cli/lang/records/csharp.js +59 -0
  19. package/cli/lang/records/go.js +47 -0
  20. package/cli/lang/records/index.js +18 -0
  21. package/cli/lang/records/java.js +55 -0
  22. package/cli/lang/records/javascript.js +50 -0
  23. package/cli/lang/records/kotlin.js +48 -0
  24. package/cli/lang/records/php.js +54 -0
  25. package/cli/lang/records/python.js +50 -0
  26. package/cli/lang/records/rust.js +47 -0
  27. package/cli/lang/records/svelte.js +45 -0
  28. package/cli/lang/records/typescript.js +66 -0
  29. package/cli/lang/records/vue.js +45 -0
  30. package/cli/lang/registry.js +73 -0
  31. package/cli/lang/rollout.js +114 -0
  32. package/cli/lang/schema.js +288 -0
  33. package/cli/lang/static-table.js +71 -0
  34. package/cli/lang/types.d.ts +142 -0
  35. package/cli/lang/vocab.js +90 -0
  36. package/cli/languages.js +50 -88
  37. package/cli/search-args.js +1 -1
  38. package/cli/search-ast-module.js +26 -3
  39. package/cli/search-ast.js +4 -2
  40. package/cli/search-commands.js +44 -0
  41. package/cli/search-db.js +1 -0
  42. package/cli/search-index-meta.js +23 -7
  43. package/cli/search-index-write.js +5 -2
  44. package/cli/search-literal.js +24 -6
  45. package/cli/search-queries.js +19 -0
  46. package/cli/search-schema-ddl.js +11 -0
  47. package/cli/search-schema.js +6 -3
  48. package/cli/search-sync-paths.js +4 -3
  49. package/cli/search-sync-rows.js +2 -2
  50. package/cli/search-sync.js +2 -0
  51. package/cli/search.js +8 -3
  52. package/cli/team/check-delivery.js +115 -0
  53. package/cli/team/check-drainer.js +288 -0
  54. package/cli/team/check-executor.js +106 -0
  55. package/cli/team/check-fingerprint.js +105 -0
  56. package/cli/team/check-queue.js +114 -0
  57. package/cli/team/help/card-rows.js +2 -1
  58. package/cli/team/help/check.js +6 -0
  59. package/cli/team/team-commands-check.js +142 -0
  60. package/cli/team/team-commands.js +6 -4
  61. package/cli/team/team-db-feed.js +6 -0
  62. package/cli/team/team-db-task-helpers.js +9 -6
  63. package/cli/team/team-dispatch-prompts.js +10 -1
  64. package/cli/team/team-dispatch-select.js +1 -0
  65. package/cli/team/team-dispatch-v2.js +1 -0
  66. package/cli/team/team-dispatch.js +3 -1
  67. package/cli/team/team-help-golden.json +20 -5
  68. package/cli/team/team-schema-checks.js +46 -0
  69. package/cli/team/team-schema.js +2 -0
  70. package/cli/ui-api-index.js +39 -0
  71. package/cli/ui-handlers.js +17 -20
  72. package/cli/ui-html.js +17 -4
  73. package/cli/ui-index.html +298 -107
  74. package/cli/ui-page/components/00-core.css +10 -0
  75. package/cli/ui-page/components/00-core.js +78 -0
  76. package/cli/ui-page/components/xo-agent-profile.js +6 -0
  77. package/cli/ui-page/components/xo-avatar.js +17 -0
  78. package/cli/ui-page/components/xo-composer.js +5 -0
  79. package/cli/ui-page/components/xo-notification-bell.js +5 -0
  80. package/cli/ui-page/components/xo-post-card.js +20 -0
  81. package/cli/ui-page/components/xo-post-permalink.js +5 -0
  82. package/cli/ui-page/components/xo-post-thread.js +5 -0
  83. package/cli/ui-page/components/xo-timeline.js +52 -0
  84. package/cli/ui-page/components/xo-today-card.js +5 -0
  85. package/cli/ui-paging-agents.js +34 -0
  86. package/cli/ui-paging-feed.js +14 -0
  87. package/cli/ui-paging-task-where.js +63 -0
  88. package/cli/ui-paging-tasks.js +68 -0
  89. package/cli/ui-paging.js +35 -0
  90. package/cli/ui-server-routes.js +5 -4
  91. package/cli/ui-server.js +12 -0
  92. package/cli/ui-social-digest.js +12 -0
  93. package/cli/ui-social-feed.js +12 -0
  94. package/cli/ui-social-mentions.js +12 -0
  95. package/cli/ui-social-notify.js +12 -0
  96. package/cli/ui-social-posts.js +12 -0
  97. package/cli/ui-social-profile.js +12 -0
  98. package/cli/ui-social-routes.js +21 -0
  99. package/cli/ui-social-threads.js +12 -0
  100. package/package.json +2 -2
  101. package/scripts/package-json-guard.mjs +35 -0
  102. package/scripts/package-json-guard.spec.mjs +50 -0
  103. package/scripts/publish-both.mjs +25 -7
@@ -3,6 +3,7 @@ import path from 'node:path';
3
3
  import { RULESET_VERSION, resolveRuleRevision } from './rule-revisions.js';
4
4
  import { RULE_REGISTRY } from './rules-registry.js';
5
5
  import { LANGUAGE_DEFINITIONS } from '../languages.js';
6
+ import { LEGACY_LANGUAGES } from '../lang/legacy-extensions.js';
6
7
 
7
8
  /**
8
9
  * chemx-ratchet.json, format version 2:
@@ -17,13 +18,14 @@ import { LANGUAGE_DEFINITIONS } from '../languages.js';
17
18
  * read as the extensions scanned before PHP support (LEGACY_LANGUAGES). Counts from
18
19
  * violations in a file whose extension is not in that set are adopted, not gated, and the
19
20
  * extension is then recorded; violations without a file path are always gated.
21
+ * `byExtension` ({ '.py': { RULE: n } }) is the per-extension split of the counts that became
22
+ * the baseline. It is written with the baseline (writeRatchet) and with every rewrite that
23
+ * happens anyway (upgradeScope); it never makes a scan rewrite the file by itself.
20
24
  */
21
25
  export const RATCHET_FILE = 'chemx-ratchet.json';
22
26
  const RATCHET_VERSION = 2;
23
27
 
24
- const PRE_PHP_EXCLUDED = new Set(['.php']);
25
28
  const allExtensions = () => Object.values(LANGUAGE_DEFINITIONS).flatMap((lang) => [...lang.extensions]);
26
- const LEGACY_LANGUAGES = allExtensions().filter((ext) => !PRE_PHP_EXCLUDED.has(ext)).sort();
27
29
 
28
30
  /** The extensions a full scan covers now (what a scope records). */
29
31
  const currentLanguages = () => allExtensions().sort();
@@ -51,6 +53,19 @@ export const countViolationsByRule = (violations = []) => {
51
53
  return counts;
52
54
  };
53
55
 
56
+ /** { '.ts': { RULE: n } } for violations that carry a file path; others have no extension to split by. */
57
+ const countByExtension = (violations = []) => {
58
+ const split = {};
59
+ for (const v of violations) {
60
+ const ext = extensionOf(v);
61
+ const hasNoPath = ext === '';
62
+ if (hasNoPath) continue;
63
+ split[ext] ??= {};
64
+ split[ext][v.rule] = (split[ext][v.rule] ?? 0) + 1;
65
+ }
66
+ return Object.fromEntries(Object.entries(split).sort(([a], [b]) => a.localeCompare(b)).map(([ext, rules]) => [ext, sortKeys(rules)]));
67
+ };
68
+
54
69
  const sortKeys = (record) => Object.fromEntries(Object.entries(record).sort(([a], [b]) => a.localeCompare(b)));
55
70
 
56
71
  const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
@@ -98,7 +113,7 @@ const readExistingOrEmpty = (projectRoot) => {
98
113
  export const writeRatchet = (projectRoot, { scope, violations }) => {
99
114
  const ratchet = readExistingOrEmpty(projectRoot);
100
115
  const rules = sortKeys(countViolationsByRule(violations));
101
- ratchet.scopes[scope] = { ruleset: RULESET_VERSION, allRules: true, rules, revisions: currentRevisions(rules), languages: currentLanguages() };
116
+ ratchet.scopes[scope] = { ruleset: RULESET_VERSION, allRules: true, rules, revisions: currentRevisions(rules), languages: currentLanguages(), byExtension: countByExtension(violations) };
102
117
  persistRatchet(projectRoot, ratchet);
103
118
  return ratchet.scopes[scope];
104
119
  };
@@ -111,19 +126,42 @@ export const writeRatchet = (projectRoot, { scope, violations }) => {
111
126
  const upgradeScope = (entry, adopted) => {
112
127
  const rules = { ...entry.rules };
113
128
  for (const { rule, current } of adopted) rules[rule] = current;
114
- return {
129
+ const upgraded = {
115
130
  ruleset: Math.max(entry.ruleset ?? 1, RULESET_VERSION),
116
131
  allRules: true,
117
132
  rules: sortKeys(rules),
118
133
  revisions: currentRevisions(rules),
119
134
  languages: mergeLanguages(entry, adopted)
120
135
  };
136
+ const byExtension = adoptSnapshot(entry.byExtension, adopted);
137
+ return byExtension ? { ...upgraded, byExtension } : upgraded;
138
+ };
139
+
140
+ /**
141
+ * Folds the adopted rules' per-extension counts into the snapshot. A rule adopted for a new
142
+ * revision is re-split over every extension; a language adoption only adds its new extensions.
143
+ * A scope with no snapshot gets one only for the adopted rules, so it stays partial.
144
+ */
145
+ const adoptSnapshot = (existing, adopted) => {
146
+ const withSplit = adopted.filter((item) => isRecord(item.byExtension));
147
+ const hasNoSplit = withSplit.length === 0;
148
+ if (hasNoSplit) return isRecord(existing) ? existing : null;
149
+ const snapshot = Object.fromEntries(Object.entries(existing ?? {}).map(([ext, rules]) => [ext, { ...rules }]));
150
+ for (const { rule, byExtension, reason } of withSplit) {
151
+ const isRevision = reason !== 'language';
152
+ if (isRevision) {
153
+ for (const rules of Object.values(snapshot)) delete rules[rule];
154
+ }
155
+ for (const [ext, count] of Object.entries(byExtension)) (snapshot[ext] ??= {})[rule] = count;
156
+ }
157
+ const populated = Object.entries(snapshot).filter(([, rules]) => Object.keys(rules).length > 0);
158
+ return Object.fromEntries(populated.sort(([a], [b]) => a.localeCompare(b)).map(([ext, rules]) => [ext, sortKeys(rules)]));
121
159
  };
122
160
 
123
161
  /** True when the scope must be rewritten after this scan (adoptions or an older rule set). */
124
162
  export const needsScopeUpgrade = (entry, adopted = []) => {
125
163
  if (!entry) return false;
126
- const upgraded = upgradeScope(entry, adopted);
164
+ const { byExtension: _snapshot, ...upgraded } = upgradeScope(entry, adopted);
127
165
  const stored = { ruleset: entry.ruleset, allRules: entry.allRules, rules: entry.rules, revisions: entry.revisions, languages: entry.languages };
128
166
  const isSame = JSON.stringify(upgraded) === JSON.stringify(stored);
129
167
  return !isSame;
@@ -146,7 +184,14 @@ const recordedRevision = (entry, rule) => {
146
184
  return isNewRegisteredRule ? 0 : (entry.ruleset ?? 1);
147
185
  };
148
186
 
187
+ /** The adopted rule's count per extension: all of them for a revision, only the outside ones for a language. */
188
+ const splitFor = (split, rule, only) => {
189
+ const entries = Object.entries(split).filter(([ext, rules]) => rules[rule] && (!only || only.includes(ext)));
190
+ return Object.fromEntries(entries.map(([ext, rules]) => [ext, rules[rule]]));
191
+ };
192
+
149
193
  const compareToBaseline = (entry, violations) => {
194
+ const split = countByExtension(violations);
150
195
  const languages = new Set(recordedLanguages(entry));
151
196
  const current = countViolationsByRule(violations);
152
197
  const outsideViolations = violations.filter((v) => isOutsideLanguages(v, languages));
@@ -162,9 +207,9 @@ const compareToBaseline = (entry, violations) => {
162
207
  const outsideCount = outside[rule] ?? 0;
163
208
  const gatedCount = count - outsideCount;
164
209
  const extensions = [...new Set(outsideViolations.filter((v) => v.rule === rule).map(extensionOf))];
165
- if (isNewerRevision) adopted.push({ rule, baseline, current: count, revision, extensions });
210
+ if (isNewerRevision) adopted.push({ rule, baseline, current: count, revision, extensions, byExtension: splitFor(split, rule) });
166
211
  const isLanguageAdoption = !isNewerRevision && outsideCount > 0;
167
- if (isLanguageAdoption) adopted.push({ rule, baseline, current: baseline + outsideCount, revision, reason: 'language', extensions });
212
+ if (isLanguageAdoption) adopted.push({ rule, baseline, current: baseline + outsideCount, revision, reason: 'language', extensions, byExtension: splitFor(split, rule, extensions) });
168
213
  const isRegression = !isNewerRevision && gatedCount > baseline;
169
214
  if (isRegression) regressions.push({ rule, baseline, current: gatedCount });
170
215
  }
@@ -402,8 +402,10 @@ export const dispatchCommand = async (firstArg, rawArgs, runAudit, getPackageVer
402
402
  const hostArg = rawArgs.find((a) => a.startsWith('--host='));
403
403
  const host = hostArg ? hostArg.split('=')[1] : undefined;
404
404
  const isDev = rawArgs.includes('--dev') || rawArgs.includes('-d') || process.env.CHEMX_UI_DEV === '1';
405
+ const tokenArg = rawArgs.find((a) => a.startsWith('--token='));
406
+ const token = (tokenArg ? tokenArg.split('=')[1] : undefined) || process.env.CHEMX_UI_TOKEN;
405
407
  const allowHosts = rawArgs.filter((a) => a.startsWith('--allow-host=')).flatMap((a) => a.slice('--allow-host='.length).split(',')).filter(Boolean);
406
- const { server } = await startUiServer({ port, host, allowHosts, dev: isDev, isCli: true, cwd: process.cwd() });
408
+ const { server } = await startUiServer({ port, host, token, allowHosts, dev: isDev, isCli: true, cwd: process.cwd() });
407
409
  await new Promise((resolve) => {
408
410
  const shutdown = () => {
409
411
  server.close(() => resolve());
@@ -5,7 +5,7 @@ export const COMMIT_COMMANDS = [
5
5
  aliases: [],
6
6
  group: 'wrappers',
7
7
  brief: 'Commit only the listed files, lease-checked',
8
- usage: 'chemx commit <files...> -m <subject> [-m <body>] [--task=<id> | --no-task=<reason>] [--board=<dir>] [--release] [--skip-ci | --no-skip-ci] [--json] [--as=@handle]',
8
+ usage: 'chemx commit <files...> [--hunks=<file>:<n,m-k>] -m <subject> [-m <body>] [--task=<id> | --no-task=<reason>] [--board=<dir>] [--release] [--skip-ci | --no-skip-ci] [--json] [--as=@handle]',
9
9
  summary: 'Path-limited git commit that checks leases and the task id, then records the commit on the task.',
10
10
  description: 'Stages only the listed files and commits only them; the repository pre-commit hook always runs. Refuses -a/--all, --no-verify, an empty file list, other already-staged paths, a file under another handle\'s live lease, and a commit with neither a task id (#<id> in the message or --task) nor --no-task=<reason>. The task id is checked, and the commit recorded, on the board in this order: --board=<dir>; the board where the committer claimed that task (`chemx team task claim` leaves a pointer, so a repo whose directory resolves to another board still finds it); the directory\'s own board. A refusal for an unknown id names every board it looked in. --no-task never scans the subject for a #id. Adds [skip ci] only while HEAD is the default branch (main, master or the branch origin/HEAD names) and .chemxrc has commit.skipCi; --skip-ci forces it on any branch, --no-skip-ci drops it. Adds a Co-Authored-By trailer only when CHEMX_COAUTHOR or commit.coAuthor names one. Retries a held .git/index.lock up to 6 times over about 20 s. A failed gate leaves the listed files staged. Lease checks and the task event are best effort: a lease taken after the check is not seen, and an unavailable team db skips the event.',
11
11
  flags: [
@@ -13,12 +13,13 @@ export const COMMIT_COMMANDS = [
13
13
  { flag: '--task=<id>', desc: 'Task the commit belongs to; added to the subject as (#<id>) when missing' },
14
14
  { flag: '--no-task=<reason>', desc: 'Commit without a task; the reason is recorded in the body and the feed, and the subject is not scanned for #ids' },
15
15
  { flag: '--board=<dir>', desc: 'Check the task id and record the commit on the board of this directory, whatever the claim or cwd say' },
16
+ { flag: '--hunks=<file>:<n,a-b>', desc: 'Commit only these hunks of a file (numbered as git diff -U0 HEAD -- <file> lists them, from 1); repeatable. The file is then also a listed file. The rest of it stays uncommitted, and nothing others staged rides along' },
16
17
  { flag: '--release', desc: 'Release your own leases on the committed files after a successful commit' },
17
18
  { flag: '--skip-ci', desc: 'Add [skip ci] to the subject on any branch (default: only commit.skipCi on the default branch)' },
18
19
  { flag: '--no-skip-ci', desc: 'Never add [skip ci], even on the default branch with commit.skipCi set' },
19
20
  { flag: '--as=@handle', desc: 'Committer handle (default: CHEMX_AGENT_ID, else a session handle)' },
20
21
  { flag: '--json', desc: 'Print the result as one object' }
21
22
  ],
22
- examples: ['chemx commit src/a.js src/b.js -m "fix(a): handle empty input (#42)"', 'chemx commit docs/x.md -m "docs: x" --task=42 --release', 'chemx commit notes.txt -m "chore: notes" --no-task="one-off cleanup"', 'chemx commit plugin/a.php -m "fix: a (#42)" --board=../app']
23
+ examples: ['chemx commit src/shared.ts --hunks=src/shared.ts:1,3-4 -m "feat: my part of shared (#42)"', 'chemx commit src/a.js src/b.js -m "fix(a): handle empty input (#42)"', 'chemx commit docs/x.md -m "docs: x" --task=42 --release', 'chemx commit notes.txt -m "chore: notes" --no-task="one-off cleanup"', 'chemx commit plugin/a.php -m "fix: a (#42)" --board=../app']
23
24
  }
24
25
  ];
@@ -13,6 +13,7 @@ export const SEARCH_COMMANDS = [
13
13
  { flag: '--columnar', desc: 'Token-compact columnar format (cols/rows) for agent pipelines' },
14
14
  { flag: '-i, --inspect', desc: 'Inspect props and hooks without full source' },
15
15
  { flag: '--tier=<tier>', desc: 'Filter by tier: atom, molecule, organism, hook, view' },
16
+ { flag: '--uses, --usages', desc: 'Every indexed use of the name as path:line:text (grep-style, from the index; no grep)' },
16
17
  { flag: '--blast-radius, --blast, --impact', desc: 'Map direct consumers, transitive dependents and impacted tiers' },
17
18
  { flag: '--trace', desc: 'Forward call trace: downstream functions invoked by target' },
18
19
  { flag: '--backtrace', desc: 'Reverse backtrace: upstream callers leading to target' },
@@ -48,9 +48,14 @@ const STATUS_FLAGS = [
48
48
  { flag: '--blockers', desc: 'status: also list the blocked tasks' }
49
49
  ];
50
50
 
51
+ const CHECK_FLAGS = [
52
+ { flag: '--once', desc: 'check drain: run the queued jobs, then exit instead of waiting for more' },
53
+ { flag: '--idle-exit-s=<n>', desc: 'check drain: exit after n idle seconds (default 60)' }
54
+ ];
55
+
51
56
  const JSON_FLAGS = [{ flag: '--json', desc: 'Output data as JSON' }];
52
57
 
53
- const FLAGS = [AS_FLAGS, TASK_DONE_FLAGS, TOKENS_FLAGS, FEED_FLAGS, TASK_ADD_FLAGS, TASK_LIST_FLAGS, BRIEF_FLAGS, TASK_SHOW_FLAGS, STATUS_FLAGS, JSON_FLAGS].flat();
58
+ const FLAGS = [AS_FLAGS, TASK_DONE_FLAGS, TOKENS_FLAGS, FEED_FLAGS, TASK_ADD_FLAGS, TASK_LIST_FLAGS, BRIEF_FLAGS, TASK_SHOW_FLAGS, STATUS_FLAGS, CHECK_FLAGS, JSON_FLAGS].flat();
54
59
 
55
60
  const TASK_EXAMPLES = [
56
61
  'chemx team task list',
@@ -70,7 +75,9 @@ const FEED_EXAMPLES = ['chemx team feed --from=@coder --type=lock'];
70
75
 
71
76
  const STATUS_EXAMPLES = ['chemx team status --mine'];
72
77
 
73
- const EXAMPLES = [TASK_EXAMPLES, TASK_SHOW_EXAMPLES, LOCK_EXAMPLES, TASK_DONE_EXAMPLES, FEED_EXAMPLES, STATUS_EXAMPLES].flat();
78
+ const CHECK_EXAMPLES = ['chemx team check typecheck --as=@coder', 'chemx team check status'];
79
+
80
+ const EXAMPLES = [TASK_EXAMPLES, TASK_SHOW_EXAMPLES, LOCK_EXAMPLES, TASK_DONE_EXAMPLES, FEED_EXAMPLES, STATUS_EXAMPLES, CHECK_EXAMPLES].flat();
74
81
 
75
82
  export const TEAM_COMMANDS = [
76
83
  {
@@ -78,9 +85,9 @@ export const TEAM_COMMANDS = [
78
85
  aliases: ['swarm', 'feed', 'tokens', 'telemetry', 'benchmark', 'ablation', 'memory', 'task'],
79
86
  group: 'agents',
80
87
  brief: 'Tasks, file locks, DMs and feed',
81
- usage: 'chemx team <status|task|brief|lock|unlock|feed|post|inbox|dm|tokens|benchmark> [options]',
88
+ usage: 'chemx team <status|task|brief|lock|unlock|feed|post|inbox|dm|check|tokens|benchmark> [options]',
82
89
  summary: 'Multi-agent coordination layer backed by SQLite (.chemx/index.db).',
83
- description: 'Task queues, status transitions, AST verification on completion and file locks. `tokens` and `benchmark` are team subcommands. `chemx task <action>` is the same as `chemx team task <action>`; run `chemx team task --help` (or `chemx task show --help`) for task detail. `chemx team brief <id>` stores or prints a task\'s long brief. An option with a value takes it after a space or an equals sign (`--prio 2`, `--prio=2`).',
90
+ description: 'Task queues, status transitions, AST verification on completion and file locks. `tokens` and `benchmark` are team subcommands. `chemx task <action>` is the same as `chemx team task <action>`; run `chemx team task --help` (or `chemx task show --help`) for task detail. `chemx team brief <id>` stores or prints a task\'s long brief. `chemx team check <typecheck|test|verify|build>` queues the check and returns at once; a detached drain worker runs it one job at a time and DMs the result (status, list, show, cancel, drain are its subcommands). An option with a value takes it after a space or an equals sign (`--prio 2`, `--prio=2`).',
84
91
  flags: FLAGS,
85
92
  examples: EXAMPLES
86
93
  }
@@ -4,7 +4,7 @@
4
4
  * validator can refuse it by name instead of passing it on to git.
5
5
  */
6
6
 
7
- const VALUE_FLAGS = new Set(['-m', '--message', '--task', '--no-task', '--as', '--board']);
7
+ const VALUE_FLAGS = new Set(['-m', '--message', '--task', '--no-task', '--as', '--board', '--hunks']);
8
8
  const KNOWN_FLAGS = new Set(['--release', '--json', '-a', '--all', '--no-verify', '-n', '--skip-ci', '--no-skip-ci']);
9
9
 
10
10
  // Splits `--flag=value` into its name and value; a bare token has value undefined.
@@ -16,7 +16,7 @@ const splitToken = (token) => {
16
16
  };
17
17
 
18
18
  const emptyParsed = () => ({
19
- files: [], messages: [], taskId: null, noTask: null, as: null, board: null,
19
+ files: [], hunks: [], messages: [], taskId: null, noTask: null, as: null, board: null,
20
20
  release: false, json: false, all: false, skipVerify: false, skipCi: false, noSkipCi: false, unknown: [], missingValue: []
21
21
  });
22
22
 
@@ -26,7 +26,8 @@ const VALUE_SETTERS = {
26
26
  '--task': (parsed, value) => { parsed.taskId = String(value).replace(/^#/, ''); },
27
27
  '--no-task': (parsed, value) => { parsed.noTask = value; },
28
28
  '--as': (parsed, value) => { parsed.as = value; },
29
- '--board': (parsed, value) => { parsed.board = value; }
29
+ '--board': (parsed, value) => { parsed.board = value; },
30
+ '--hunks': (parsed, value) => parsed.hunks.push(value)
30
31
  };
31
32
 
32
33
  const BOOLEAN_SETTERS = {
@@ -45,7 +46,7 @@ const applyBooleanFlag = (parsed, name) => BOOLEAN_SETTERS[name](parsed);
45
46
 
46
47
  /**
47
48
  * @param {string[]} args Everything after `chemx commit`.
48
- * @returns {{ files: string[], messages: string[], taskId: string|null, noTask: string|null, as: string|null,
49
+ * @returns {{ files: string[], hunks: string[], messages: string[], taskId: string|null, noTask: string|null, as: string|null,
49
50
  * board: string|null, release: boolean, json: boolean, all: boolean, skipVerify: boolean, skipCi: boolean,
50
51
  * noSkipCi: boolean, unknown: string[], missingValue: string[] }}
51
52
  */
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Chemical X Protocol: `chemx commit --hunks=<file>:<n,m-k>` commits only some hunks of a file (#7599).
3
+ * A file other sessions are also editing cannot be committed whole without taking their half-finished
4
+ * work. The hunks are numbered as `git diff -U0 HEAD -- <file>` lists them (1-based). The commit is built on a private index
5
+ * that starts from HEAD, so only the listed files can differ in it and nothing another handle staged rides
6
+ * along. Not guaranteed: hunks are cut at zero context, so two changes on adjoining lines are one hunk;
7
+ * a spec that selects half of a change a later hunk depends on commits that half as written.
8
+ */
9
+ import fs from 'node:fs';
10
+ import os from 'node:os';
11
+ import path from 'node:path';
12
+ import { spawnSync } from 'node:child_process';
13
+ import { runGit } from './commit-git.js';
14
+
15
+ const SPEC_PART = /^(\d+)(?:-(\d+))?$/;
16
+
17
+ /** `1,3-4` to [1, 3, 4]; null when any part is not a positive number or a range that runs up. */
18
+ export const parseRanges = (spec) => {
19
+ const numbers = [];
20
+ for (const part of spec.split(',')) {
21
+ const found = SPEC_PART.exec(part.trim());
22
+ if (!found) return null;
23
+ const from = Number(found[1]);
24
+ const to = found[2] === undefined ? from : Number(found[2]);
25
+ const isBackwards = from < 1 || to < from;
26
+ if (isBackwards) return null;
27
+ for (let at = from; at <= to; at += 1) numbers.push(at);
28
+ }
29
+ return numbers;
30
+ };
31
+
32
+ /** `--hunks` values to { file, numbers } entries and the messages for any that cannot be read. */
33
+ export const parseHunkSpecs = (raw) => {
34
+ const specs = [];
35
+ const errors = [];
36
+ for (const value of raw) {
37
+ const colon = value.lastIndexOf(':');
38
+ const file = colon > 0 ? value.slice(0, colon) : '';
39
+ const numbers = colon > 0 ? parseRanges(value.slice(colon + 1)) : null;
40
+ const isBad = file === '' || numbers === null;
41
+ if (isBad) errors.push(`Refused: --hunks=${value} is not <file>:<n[,n|a-b]> with hunk numbers from 1.`);
42
+ else specs.push({ file, numbers });
43
+ }
44
+ return { specs, errors };
45
+ };
46
+
47
+ /** A diff cut into its header lines and its hunks, each hunk with its own header and body. */
48
+ export const splitDiff = (diff) => {
49
+ const lines = diff.split('\n');
50
+ const firstHunk = lines.findIndex((line) => line.startsWith('@@'));
51
+ const hasNoHunks = firstHunk < 0;
52
+ if (hasNoHunks) return { header: lines, hunks: [] };
53
+ const hunks = [];
54
+ for (const line of lines.slice(firstHunk)) {
55
+ if (line.startsWith('@@')) hunks.push([line]);
56
+ else hunks[hunks.length - 1].push(line);
57
+ }
58
+ return { header: lines.slice(0, firstHunk), hunks };
59
+ };
60
+
61
+ /** The patch holding only the wanted hunks of one file, or the reasons it cannot be cut. */
62
+ export const patchFor = (root, spec) => {
63
+ const diff = runGit(root, ['diff', '-U0', '--no-color', '--no-ext-diff', 'HEAD', '--', spec.file]);
64
+ const { header, hunks } = splitDiff(diff.stdout);
65
+ const outOfRange = spec.numbers.filter((number) => number > hunks.length);
66
+ const isEmpty = hunks.length === 0;
67
+ if (isEmpty) return { errors: [`Refused: ${spec.file} has no changes against HEAD to take hunks from.`] };
68
+ if (outOfRange.length) return { errors: [`Refused: ${spec.file} has ${hunks.length} hunk(s) against HEAD; there is no hunk ${outOfRange.join(', ')}.`] };
69
+ const chosen = [...new Set(spec.numbers)].sort((a, b) => a - b).flatMap((number) => hunks[number - 1]);
70
+ return { patch: [...header, ...chosen].join('\n').replace(/\n*$/, '\n'), errors: [] };
71
+ };
72
+
73
+ const privateIndex = (root) => {
74
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'chemx-commit-index-'));
75
+ const hasHead = runGit(root, ['rev-parse', '--verify', '-q', 'HEAD']).status === 0;
76
+ return { dir, file: path.join(dir, 'index'), hasHead };
77
+ };
78
+
79
+ /**
80
+ * Builds the index the commit is made from: HEAD, then the whole listed files, then the chosen hunks of
81
+ * the others. Returns the env to commit with and a cleanup, or the reasons it could not be built.
82
+ */
83
+ export const buildHunkIndex = (root, files, specs, env) => {
84
+ const { dir, file, hasHead } = privateIndex(root);
85
+ const cleanup = () => fs.rmSync(dir, { recursive: true, force: true });
86
+ const indexEnv = { ...env, GIT_INDEX_FILE: file };
87
+ const fail = (errors) => { cleanup(); return { errors }; };
88
+ const reading = runGit(root, hasHead ? ['read-tree', 'HEAD'] : ['read-tree', '--empty'], indexEnv);
89
+ const isReadFailed = reading.status !== 0;
90
+ if (isReadFailed) return fail([`Failed: could not start a private index. ${reading.output.trim()}`]);
91
+ const partial = new Set(specs.map((spec) => spec.file));
92
+ const whole = files.filter((candidate) => !partial.has(candidate));
93
+ const adding = whole.length ? runGit(root, ['add', '--', ...whole], indexEnv) : { status: 0, output: '' };
94
+ const isAddFailed = adding.status !== 0;
95
+ if (isAddFailed) return fail([`Failed: git add did not complete. ${adding.output.trim()}`]);
96
+ for (const spec of specs) {
97
+ const cut = patchFor(root, spec);
98
+ const isCutFailed = cut.errors.length > 0;
99
+ if (isCutFailed) return fail(cut.errors);
100
+ const applied = spawnSync('git', ['apply', '--cached', '--unidiff-zero', '-'], { cwd: root, encoding: 'utf-8', env: indexEnv, input: cut.patch });
101
+ const isApplyFailed = applied.status !== 0;
102
+ if (isApplyFailed) return fail([`Failed: the chosen hunks of ${spec.file} did not apply. ${(applied.stderr ?? '').trim()}`]);
103
+ }
104
+ return { env: indexEnv, cleanup, errors: [] };
105
+ };
106
+
107
+ /** After the commit, the real index entries of the listed files are put level with the new HEAD. */
108
+ export const levelIndex = (root, files) => runGit(root, ['reset', '-q', '--', ...files]).status === 0;
@@ -16,6 +16,7 @@ import { collectRefusals } from './commit-validate.js';
16
16
  import { gatherFacts } from './commit-facts.js';
17
17
  import { openCommitDb, recordCommit, releaseLeases } from './commit-record.js';
18
18
  import { snapshotIndex, restoreIndex } from './commit-index.js';
19
+ import { buildHunkIndex, levelIndex, parseHunkSpecs } from './commit-hunks.js';
19
20
  import {
20
21
  gitRoot, stagedAmong, shortSha, hasPreCommitHook, gitWithRetry, compactFailure
21
22
  } from './commit-git.js';
@@ -136,12 +137,19 @@ const routeToOwner = (parsed, cwd) => {
136
137
  * @returns {Promise<{ ok: boolean, exitCode: number, lines: string[], refusals: string[], json: boolean, data?: object }>}
137
138
  */
138
139
  export const runCommit = async (args, options = {}) => {
139
- const parsed = parseCommitArgs(args);
140
+ const parsedArgs = parseCommitArgs(args);
140
141
  const startCwd = options.cwd ?? process.cwd();
142
+ const hunkParse = parseHunkSpecs(parsedArgs.hunks);
143
+ // A file named in --hunks is a listed file, whether or not it is also named plainly.
144
+ const hunkFiles = hunkParse.specs.map((spec) => spec.file);
145
+ const parsed = { ...parsedArgs, files: [...new Set([...parsedArgs.files, ...hunkFiles])], hunkSpecs: hunkParse.specs };
146
+ if (hunkParse.errors.length) return refused(hunkParse.errors, parsed);
141
147
  const routed = parsed.files.length ? routeToOwner(parsed, startCwd) : { cwd: startCwd, files: parsed.files };
142
148
  const isRefused = Boolean(routed.refusal);
143
149
  if (isRefused) return refused(routed.refusal, parsed);
144
- return commitInRepo({ ...parsed, files: routed.files }, routed.cwd, options);
150
+ const moved = routed.files !== parsed.files;
151
+ const hunkSpecs = parsed.hunkSpecs.map((spec) => ({ ...spec, file: moved ? path.resolve(startCwd, spec.file) : spec.file }));
152
+ return commitInRepo({ ...parsed, files: routed.files, hunkSpecs }, routed.cwd, options);
145
153
  };
146
154
 
147
155
  const commitInRepo = async (parsed, cwd, options) => {
@@ -153,6 +161,8 @@ const commitInRepo = async (parsed, cwd, options) => {
153
161
  const gitEnv = facts?.committer ? { ...env, CHEMX_AGENT_ID: facts.committer } : env;
154
162
  const retry = { sleep: options.sleep, delaysMs: options.delaysMs, env: gitEnv };
155
163
  const isPreflightClean = preflight.length === 0;
164
+ const hasHunks = isPreflightClean && parsed.hunkSpecs.length > 0;
165
+ if (hasHunks) return commitHunks({ parsed, cwd, root, facts, env, gitEnv, retry });
156
166
  const snapshot = isPreflightClean ? snapshotIndex(root, facts.rel) : [];
157
167
  const staging = isPreflightClean ? await stageFiles(root, facts.rel, retry) : { reasons: [], isFailure: false };
158
168
  if (staging.isFailure) return failed(staging.reasons, parsed, { attempts: staging.added.attempts, lockHolder: staging.added.lockHolder });
@@ -167,3 +177,24 @@ const commitInRepo = async (parsed, cwd, options) => {
167
177
  const data = afterCommit(root, cwd, facts, message, hasHook);
168
178
  return { ok: true, exitCode: 0, refusals: [], json: parsed.json, lines: formatSuccessLines(data, parsed.release), data };
169
179
  };
180
+
181
+ // A commit of chosen hunks: made on a private index that starts from HEAD, so only the listed files differ in it.
182
+ const commitHunks = async ({ parsed, cwd, root, facts, env, gitEnv, retry }) => {
183
+ const specs = parsed.hunkSpecs.map((spec) => ({ ...spec, file: path.relative(root, path.resolve(cwd, spec.file)) }));
184
+ const built = buildHunkIndex(root, facts.rel, specs, gitEnv);
185
+ const isBuildFailed = built.errors.length > 0;
186
+ if (isBuildFailed) return refused(built.errors, parsed);
187
+ const message = buildCommitMessage({ messages: parsed.messages, taskId: facts.taskId, noTask: parsed.noTask, config: facts.config, env, isSkipCi: facts.isSkipCi });
188
+ const hasHook = hasPreCommitHook(root);
189
+ const commitArgs = ['commit', '-m', message.subject, ...message.paragraphs.flatMap((paragraph) => ['-m', paragraph])];
190
+ const outcome = await gitWithRetry(root, commitArgs, { ...retry, env: built.env });
191
+ built.cleanup();
192
+ const isCommitFailed = outcome.status !== 0;
193
+ if (isCommitFailed) return failed(failureLines(outcome), parsed, { attempts: outcome.attempts, lockHolder: outcome.lockHolder });
194
+ const isLevel = levelIndex(root, facts.rel);
195
+ const data = afterCommit(root, cwd, facts, message, hasHook);
196
+ const lines = formatSuccessLines(data, parsed.release);
197
+ const hunkLines = [`hunks: ${specs.map((spec) => `${spec.file}:${spec.numbers.join(',')}`).join('; ')} (the rest of those files stays uncommitted)`];
198
+ const levelLines = isLevel ? [] : ['warning: could not put the index level with HEAD for the listed files (git reset -q -- <files>).'];
199
+ return { ok: true, exitCode: 0, refusals: [], json: parsed.json, lines: [...lines, ...hunkLines, ...levelLines], data };
200
+ };
@@ -2,6 +2,33 @@ import { PROFILES, DEFAULT_PROFILE, getProfileDefaults } from './profiles.js';
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { findAndLoadConfigFile } from './loader.js';
5
+ import { CAPABILITIES, STAGES } from '../lang/vocab.js';
6
+
7
+ const isPlainObject = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
8
+ const stringList = (value) => (Array.isArray(value) ? value.filter((v) => typeof v === 'string') : []);
9
+
10
+ /**
11
+ * The `.chemxrc` `languages` block (design spec 4.4), reduced to valid entries: stages per
12
+ * language and capability, the shadow-logging flag, requireGrammars (true or language ids),
13
+ * disable (language ids), map (path glob to language id) and grammars (passed through).
14
+ */
15
+ export const normalizeLanguagesConfig = (raw) => {
16
+ const input = isPlainObject(raw) ? raw : {};
17
+ const stages = {};
18
+ for (const [lang, caps] of Object.entries(isPlainObject(input.stages) ? input.stages : {})) {
19
+ const valid = Object.entries(isPlainObject(caps) ? caps : {}).filter(([cap, stage]) => CAPABILITIES.includes(cap) && STAGES.includes(stage));
20
+ if (valid.length) stages[lang] = Object.fromEntries(valid);
21
+ }
22
+ const map = Object.fromEntries(Object.entries(isPlainObject(input.map) ? input.map : {}).filter(([, id]) => typeof id === 'string'));
23
+ return {
24
+ stages,
25
+ shadow: input.shadow === true,
26
+ requireGrammars: input.requireGrammars === true ? true : stringList(input.requireGrammars),
27
+ disable: stringList(input.disable),
28
+ map,
29
+ grammars: isPlainObject(input.grammars) ? input.grammars : {}
30
+ };
31
+ };
5
32
 
6
33
  /** The product pillar selection written by `chemx pillars` (null when never chosen). */
7
34
  const readPillarSelection = (cwd, fileConfig) => {
@@ -76,6 +103,7 @@ export const loadProjectConfig = (cwd = process.cwd(), rawArgs = []) => {
76
103
  pillars: readPillarSelection(cwd, fileConfig),
77
104
  wordpress: fileConfig.raw?.wordpress,
78
105
  php: fileConfig.raw?.php,
106
+ languages: normalizeLanguagesConfig(fileConfig.raw?.languages),
79
107
  raw: fileConfig.raw || {},
80
108
  stage: fileConfig.raw?.stage || 'strict'
81
109
  };
@@ -6,7 +6,7 @@
6
6
 
7
7
  export const TEAM_SUBCOMMANDS = [
8
8
  'status', 'task', 'brief', 'tokens', 'telemetry', 'feed', 'post', 'lock', 'unlock', 'triage', 'inbox',
9
- 'dm', 'train', 'benchmark', 'ablation', 'memory', 'profile', 'handoff', 'dispatch', 'route', 'migrate', 'audit-run', 'help'
9
+ 'dm', 'train', 'benchmark', 'ablation', 'memory', 'profile', 'handoff', 'dispatch', 'route', 'check', 'migrate', 'audit-run', 'help'
10
10
  ];
11
11
 
12
12
  export const TEAM_TASK_ACTIONS = [
@@ -10,7 +10,7 @@ export const parseFileAst = (absPath, relPath) => {
10
10
  const lines = content.split('\n').length;
11
11
  const chars = content.length;
12
12
  const tier = resolveArchitectureTier(relPath);
13
- const { symbols, props, hooks, imports } = extractAstMetadata(content, absPath);
13
+ const { symbols, props, hooks, imports, occurrences } = extractAstMetadata(content, absPath);
14
14
  return {
15
15
  path: relPath,
16
16
  mtime: Math.floor(stat.mtimeMs),
@@ -21,7 +21,8 @@ export const parseFileAst = (absPath, relPath) => {
21
21
  symbols,
22
22
  props,
23
23
  hooks,
24
- imports
24
+ imports,
25
+ occurrences
25
26
  };
26
27
  };
27
28
 
package/cli/index-seed.js CHANGED
@@ -30,6 +30,7 @@ const ROW_TABLES = [
30
30
  { table: 'props', pathColumn: 'file_path', columns: 'file_path, name, prop_type' },
31
31
  { table: 'hooks', pathColumn: 'file_path', columns: 'file_path, name' },
32
32
  { table: 'imports', pathColumn: 'importer_path', columns: 'importer_path, imported_symbol, source_module, resolved_path, line' },
33
+ { table: 'occurrences', pathColumn: 'file_path', columns: 'file_path, name, line' },
33
34
  { table: 'embeddings', pathColumn: 'file_path', columns: 'file_path, target_type, target_name, vector, dimensions, model, updated_at' },
34
35
  { table: 'fts_index', pathColumn: 'file_path', columns: 'file_path, name, kind, tier, tokens' }
35
36
  ];