swarmdo 1.19.0 → 1.29.0

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 (59) hide show
  1. package/.claude/helpers/auto-memory-hook.mjs +5 -1
  2. package/.claude-plugin/README.md +3 -3
  3. package/.claude-plugin/docs/INSTALLATION.md +1 -1
  4. package/.claude-plugin/docs/PLUGIN_SUMMARY.md +1 -1
  5. package/.claude-plugin/docs/QUICKSTART.md +3 -3
  6. package/.claude-plugin/hooks/hooks.json +19 -1
  7. package/.claude-plugin/marketplace.json +17 -17
  8. package/.claude-plugin/plugin.json +7 -39
  9. package/.claude-plugin/scripts/install.sh +3 -3
  10. package/.claude-plugin/scripts/swarmdo-hook.sh +1 -1
  11. package/.claude-plugin/scripts/verify.sh +2 -2
  12. package/README.md +10 -8
  13. package/package.json +1 -1
  14. package/v3/@swarmdo/cli/.claude/helpers/auto-memory-hook.mjs +5 -1
  15. package/v3/@swarmdo/cli/bin/cli.js +38 -0
  16. package/v3/@swarmdo/cli/dist/src/apply/apply.d.ts +8 -0
  17. package/v3/@swarmdo/cli/dist/src/apply/apply.js +70 -10
  18. package/v3/@swarmdo/cli/dist/src/changelog/changelog.js +26 -3
  19. package/v3/@swarmdo/cli/dist/src/codegraph/codegraph.d.ts +26 -7
  20. package/v3/@swarmdo/cli/dist/src/codegraph/codegraph.js +97 -13
  21. package/v3/@swarmdo/cli/dist/src/codegraph/store.d.ts +8 -1
  22. package/v3/@swarmdo/cli/dist/src/codegraph/store.js +78 -1
  23. package/v3/@swarmdo/cli/dist/src/commands/apply.js +17 -4
  24. package/v3/@swarmdo/cli/dist/src/commands/compact-snapshot.d.ts +17 -0
  25. package/v3/@swarmdo/cli/dist/src/commands/compact-snapshot.js +133 -0
  26. package/v3/@swarmdo/cli/dist/src/commands/cycles.js +4 -1
  27. package/v3/@swarmdo/cli/dist/src/commands/hotspots.js +5 -2
  28. package/v3/@swarmdo/cli/dist/src/commands/index.js +4 -3
  29. package/v3/@swarmdo/cli/dist/src/commands/pack.d.ts +8 -0
  30. package/v3/@swarmdo/cli/dist/src/commands/pack.js +28 -2
  31. package/v3/@swarmdo/cli/dist/src/commands/release.js +5 -1
  32. package/v3/@swarmdo/cli/dist/src/commands/testreport.js +2 -1
  33. package/v3/@swarmdo/cli/dist/src/compact/compact.js +17 -7
  34. package/v3/@swarmdo/cli/dist/src/compact-snapshot/compact-snapshot.d.ts +58 -0
  35. package/v3/@swarmdo/cli/dist/src/compact-snapshot/compact-snapshot.js +104 -0
  36. package/v3/@swarmdo/cli/dist/src/config-lint/lint.js +16 -2
  37. package/v3/@swarmdo/cli/dist/src/cycles/cycles.d.ts +12 -2
  38. package/v3/@swarmdo/cli/dist/src/cycles/cycles.js +5 -3
  39. package/v3/@swarmdo/cli/dist/src/env/env.d.ts +5 -2
  40. package/v3/@swarmdo/cli/dist/src/env/env.js +24 -3
  41. package/v3/@swarmdo/cli/dist/src/hotspots/hotspots.d.ts +15 -0
  42. package/v3/@swarmdo/cli/dist/src/hotspots/hotspots.js +33 -1
  43. package/v3/@swarmdo/cli/dist/src/init/helpers-generator.js +33 -3
  44. package/v3/@swarmdo/cli/dist/src/license/license.d.ts +31 -2
  45. package/v3/@swarmdo/cli/dist/src/license/license.js +133 -11
  46. package/v3/@swarmdo/cli/dist/src/pack/pack.d.ts +2 -3
  47. package/v3/@swarmdo/cli/dist/src/pack/pack.js +68 -12
  48. package/v3/@swarmdo/cli/dist/src/redact/redact.js +14 -2
  49. package/v3/@swarmdo/cli/dist/src/sbom/sbom.d.ts +16 -0
  50. package/v3/@swarmdo/cli/dist/src/sbom/sbom.js +33 -3
  51. package/v3/@swarmdo/cli/dist/src/swarmvector/model-prices.js +12 -2
  52. package/v3/@swarmdo/cli/dist/src/testreport/testreport.d.ts +14 -0
  53. package/v3/@swarmdo/cli/dist/src/testreport/testreport.js +82 -9
  54. package/v3/@swarmdo/cli/dist/src/transcript/export.d.ts +5 -0
  55. package/v3/@swarmdo/cli/dist/src/transcript/export.js +8 -1
  56. package/v3/@swarmdo/cli/dist/src/usage/claude-pricing.d.ts +12 -2
  57. package/v3/@swarmdo/cli/dist/src/usage/claude-pricing.js +45 -13
  58. package/v3/@swarmdo/cli/dist/src/usage/transcript-usage.js +5 -2
  59. package/v3/@swarmdo/cli/package.json +2 -2
@@ -19,7 +19,10 @@ export function parsePatch(text) {
19
19
  let hunk = null;
20
20
  const stripPrefix = (p) => p.replace(/^[ab]\//, '').replace(/\t.*$/, '').trim();
21
21
  for (let i = 0; i < lines.length; i++) {
22
- const line = lines[i];
22
+ // CRLF tolerance (#9): a diff generated on/for CRLF files carries \r on
23
+ // every line; strip it so hunk content compares EOL-agnostically.
24
+ const raw = lines[i];
25
+ const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw;
23
26
  if (line.startsWith('diff --git')) {
24
27
  cur = null;
25
28
  hunk = null;
@@ -54,7 +57,10 @@ export function parsePatch(text) {
54
57
  hunk.lines.push({ type: ' ', content: '' }); // blank context line written without the leading space
55
58
  }
56
59
  else if (line.startsWith('\\')) {
57
- // "" — ignore
60
+ // "" — attaches to the preceding hunk line,
61
+ // recording that that side of the diff has no trailing newline.
62
+ if (hunk.lines.length)
63
+ hunk.lines[hunk.lines.length - 1].noEol = true;
58
64
  }
59
65
  else {
60
66
  hunk = null; // end of hunk block
@@ -87,6 +93,16 @@ function blockMatchesAt(source, at, block) {
87
93
  return false;
88
94
  return true;
89
95
  }
96
+ /** How many positions in `source` the `block` matches. Pure. */
97
+ function countMatches(source, block) {
98
+ if (block.length === 0)
99
+ return 0;
100
+ let n = 0;
101
+ for (let i = 0; i + block.length <= source.length; i++)
102
+ if (blockMatchesAt(source, i, block))
103
+ n++;
104
+ return n;
105
+ }
90
106
  /**
91
107
  * Find where `block` occurs in `source`, preferring the position nearest
92
108
  * `expected` (0-based). Returns -1 if not found. Deterministic: on ties the
@@ -114,11 +130,24 @@ function findBlock(source, block, expected) {
114
130
  export function applyPatch(source, patch, opts = {}) {
115
131
  const fuzz = opts.fuzz ?? 2;
116
132
  const trailingNewline = source.endsWith('\n');
133
+ // CRLF support (#9): match EOL-agnostically, then write inserted lines with
134
+ // the file's dominant EOL so CRLF sources stay CRLF. `lines` keeps each
135
+ // line's original bytes (untouched lines round-trip exactly); `matchLines`
136
+ // is the \r-stripped twin every comparison runs against. The two are spliced
137
+ // in lockstep so indices stay aligned.
138
+ const crlfCount = (source.match(/\r\n/g) ?? []).length;
139
+ const newlineCount = (source.match(/\n/g) ?? []).length;
140
+ const dominantCrlf = crlfCount > newlineCount - crlfCount;
117
141
  const lines = source.split('\n');
118
142
  if (trailingNewline)
119
143
  lines.pop(); // drop the empty element from a trailing \n
144
+ const stripCr = (s) => (s.endsWith('\r') ? s.slice(0, -1) : s);
145
+ const matchLines = lines.map(stripCr);
120
146
  let offset = 0;
121
147
  const results = [];
148
+ // If a hunk that reaches EOF carries an explicit no-newline marker, it — not
149
+ // the source — decides the output's trailing newline. undefined = no marker.
150
+ let eofNoEol;
122
151
  for (const hunk of patch.hunks) {
123
152
  const { oldBlock, newBlock } = hunkBlocks(hunk);
124
153
  const expected = hunk.oldStart - 1 + offset;
@@ -136,7 +165,7 @@ export function applyPatch(source, patch, opts = {}) {
136
165
  if (lead > leadTrimmable || tail > tailTrimmable)
137
166
  continue;
138
167
  const trimmed = oldBlock.slice(lead, oldBlock.length - tail);
139
- const at = findBlock(lines, trimmed, expected + lead);
168
+ const at = findBlock(matchLines, trimmed, expected + lead);
140
169
  if (at >= 0) {
141
170
  placed = at - lead;
142
171
  usedFuzz = f;
@@ -150,19 +179,50 @@ export function applyPatch(source, patch, opts = {}) {
150
179
  results.push({ hunk, applied: false });
151
180
  continue;
152
181
  }
153
- // Splice: remove oldBlock.length lines at `placed`, insert newBlock.
154
- // (trimLead/trimTail only affected *matching*, not what we replace.)
155
- void trimLead;
156
- void trimTail;
157
- lines.splice(placed, oldBlock.length, ...newBlock);
182
+ // A hunk is AMBIGUOUS if the block it matched on occurs elsewhere too — the
183
+ // nearest-match tiebreak may have picked the wrong duplicate. Check the
184
+ // matched (trimmed) block against the current lines BEFORE splicing.
185
+ const matchedBlock = oldBlock.slice(trimLead, oldBlock.length - trimTail);
186
+ const ambiguous = countMatches(matchLines, matchedBlock) > 1;
187
+ // Splice: remove oldBlock.length lines at `placed`, insert newBlock —
188
+ // raw lines get the file's dominant EOL, the match twin stays stripped.
189
+ const insertRaw = dominantCrlf ? newBlock.map((l) => l + '\r') : newBlock;
190
+ lines.splice(placed, oldBlock.length, ...insertRaw);
191
+ matchLines.splice(placed, oldBlock.length, ...newBlock);
158
192
  offset += newBlock.length - oldBlock.length;
159
- results.push({ hunk, applied: true, at: placed, fuzzUsed: usedFuzz });
193
+ results.push({ hunk, applied: true, at: placed, fuzzUsed: usedFuzz, ...(ambiguous && { ambiguous: true }) });
194
+ // If this hunk's new content is now the tail of the file, its markers
195
+ // determine whether the file ends with a newline.
196
+ if (placed + newBlock.length === lines.length)
197
+ eofNoEol = newSideEndsNoEol(hunk);
160
198
  }
161
199
  let result = lines.join('\n');
162
- if (trailingNewline)
200
+ // The patch's explicit EOF marker wins; absent one, keep the source's state.
201
+ const endWithNewline = eofNoEol === undefined ? trailingNewline : !eofNoEol;
202
+ if (endWithNewline)
163
203
  result += '\n';
204
+ // An inserted line that became the no-trailing-newline tail carries the
205
+ // dominant-EOL \r it was given for joining — a bare CR at EOF is never
206
+ // meaningful, so drop it.
207
+ else if (result.endsWith('\r'))
208
+ result = result.slice(0, -1);
164
209
  return { ok: results.every((r) => r.applied), result, hunks: results };
165
210
  }
211
+ /**
212
+ * Whether the NEW side of `hunk` ends without a trailing newline — read from the
213
+ * last context/addition line's marker. Returns undefined if the hunk carries no
214
+ * `\ No newline` marker at all (so the source's state should be kept). Pure.
215
+ */
216
+ function newSideEndsNoEol(hunk) {
217
+ if (!hunk.lines.some((l) => l.noEol))
218
+ return undefined;
219
+ for (let i = hunk.lines.length - 1; i >= 0; i--) {
220
+ const l = hunk.lines[i];
221
+ if (l.type === ' ' || l.type === '+')
222
+ return !!l.noEol;
223
+ }
224
+ return undefined;
225
+ }
166
226
  function countLeadingContext(hunk) {
167
227
  let n = 0;
168
228
  for (const l of hunk.lines) {
@@ -24,18 +24,41 @@ export const SECTIONS = [
24
24
  { type: 'chore', label: 'Chores', hidden: true },
25
25
  ];
26
26
  const SUBJECT_RE = /^(\w+)(?:\(([^)]+)\))?(!)?:\s+(.+)$/;
27
+ // git's default revert subject: `Revert "<original subject>"` (git-revert(1)).
28
+ // The conventional `revert:` type is handled by SUBJECT_RE; this catches the
29
+ // bare git form, which otherwise falls into the hidden `other` bucket.
30
+ const REVERT_RE = /^Revert\s+"(.+)"$/;
31
+ // Conventional Commits: a breaking-change footer MUST be the uppercase token
32
+ // `BREAKING CHANGE` (or `BREAKING-CHANGE`) at the start of a footer line,
33
+ // followed by `: `. Anchoring to a line start avoids a false positive when the
34
+ // phrase merely appears in prose ("this is not a BREAKING CHANGE, just …").
35
+ const BREAKING_RE = /^BREAKING[ -]CHANGE:\s/m;
27
36
  /** Parse one conventional-commit subject (+ optional body for BREAKING CHANGE). */
28
37
  export function parseCommit(hash, subject, body = '') {
29
- const m = SUBJECT_RE.exec(subject.trim());
38
+ const trimmed = subject.trim();
39
+ const rev = REVERT_RE.exec(trimmed);
40
+ if (rev) {
41
+ // Recurse into the quoted original subject to lift its scope/description.
42
+ const inner = SUBJECT_RE.exec(rev[1].trim());
43
+ return {
44
+ hash,
45
+ type: 'revert',
46
+ scope: inner ? inner[2] ?? null : null,
47
+ breaking: BREAKING_RE.test(body),
48
+ subject: inner ? inner[4].trim() : rev[1].trim(),
49
+ raw: trimmed,
50
+ };
51
+ }
52
+ const m = SUBJECT_RE.exec(trimmed);
30
53
  if (!m) {
31
- return { hash, type: null, scope: null, breaking: /BREAKING[ -]CHANGE/.test(body), subject: subject.trim(), raw: subject.trim() };
54
+ return { hash, type: null, scope: null, breaking: BREAKING_RE.test(body), subject: subject.trim(), raw: subject.trim() };
32
55
  }
33
56
  const [, type, scope, bang, desc] = m;
34
57
  return {
35
58
  hash,
36
59
  type: type.toLowerCase(),
37
60
  scope: scope ?? null,
38
- breaking: bang === '!' || /BREAKING[ -]CHANGE/.test(body),
61
+ breaking: bang === '!' || BREAKING_RE.test(body),
39
62
  subject: desc.trim(),
40
63
  raw: subject.trim(),
41
64
  };
@@ -31,6 +31,13 @@ export interface ImportEdge {
31
31
  resolved: string | null;
32
32
  /** 1-based line of the import */
33
33
  line: number;
34
+ /**
35
+ * True for a TypeScript type-only import/export (`import type …`,
36
+ * `export type … from …`). These are erased at compile time (with
37
+ * isolatedModules/verbatimModuleSyntax) so they create NO runtime dependency
38
+ * — relevant to cycle detection, where a type-only "cycle" is benign.
39
+ */
40
+ isTypeOnly?: boolean;
34
41
  }
35
42
  export interface CodeIndex {
36
43
  /** Repo-relative file → symbols declared in it. */
@@ -46,19 +53,31 @@ export declare function extractImports(source: string, file: string): Array<{
46
53
  from: string;
47
54
  spec: string;
48
55
  line: number;
56
+ isTypeOnly: boolean;
49
57
  }>;
50
58
  /**
51
- * Resolve a spec to a repo-relative file in `fileSet`, or null. Only relative
52
- * specs (`.`/`..`) resolve; bare specifiers (packages, aliases, `node:`) are
53
- * external null. Tries the path as-is, common extensions, and `/index.*`,
54
- * and rewrites a `.js` spec to its `.ts` sibling (TS ESM convention).
59
+ * A tsconfig `paths` / workspace alias: a bare-specifier pattern mapped to a
60
+ * repo-relative target (baseUrl already applied), each optionally containing a
61
+ * single star wildcard e.g. pattern `@swarmdo/[star]` target
62
+ * `v3/@swarmdo/[star]/src`, where `[star]` captures the remaining spec.
55
63
  */
56
- export declare function resolveImport(fromFile: string, spec: string, fileSet: Set<string>): string | null;
57
- /** Build an index from already-read files. Pure. */
64
+ export interface ImportAlias {
65
+ pattern: string;
66
+ target: string;
67
+ }
68
+ /**
69
+ * Resolve a spec to a repo-relative file in `fileSet`, or null. Relative specs
70
+ * (`.`/`..`) resolve against the importing file's dir. Bare specifiers resolve
71
+ * only if they match a tsconfig-`paths`/workspace `alias` — otherwise they're
72
+ * external (packages, `node:`) → null. Tries common extensions and `/index.*`,
73
+ * and rewrites a `.js` spec to its `.ts` sibling (TS ESM convention). Pure.
74
+ */
75
+ export declare function resolveImport(fromFile: string, spec: string, fileSet: Set<string>, aliases?: ImportAlias[]): string | null;
76
+ /** Build an index from already-read files. `aliases` resolve bare-specifier internal imports. Pure. */
58
77
  export declare function buildIndex(files: Array<{
59
78
  file: string;
60
79
  source: string;
61
- }>): CodeIndex;
80
+ }>, aliases?: ImportAlias[]): CodeIndex;
62
81
  export interface QueryOptions {
63
82
  /** Substring/case-insensitive match instead of exact. */
64
83
  fuzzy?: boolean;
@@ -28,6 +28,43 @@ const MATCHERS = [
28
28
  { kind: 'enum', re: /^export\s+(?:const\s+)?enum\s+([A-Za-z_$][\w$]*)/ },
29
29
  { kind: 'const', re: /^export\s+(?:const|let|var)\s+([A-Za-z_$][\w$]*)/ },
30
30
  ];
31
+ /**
32
+ * Top-level (comma-separated) simple-identifier declarator names in a
33
+ * const/let/var declaration list, e.g. `a = 1, b = fn(1, 2), c = 3` → [a,b,c].
34
+ * Commas inside parens/brackets/braces/strings don't split. Destructuring
35
+ * patterns (a segment starting with `{`/`[`) yield no name — kept as-is. Pure.
36
+ */
37
+ function declaratorNames(decl) {
38
+ const names = [];
39
+ let depth = 0;
40
+ let start = 0;
41
+ let str = null;
42
+ const take = (seg) => {
43
+ const m = seg.trim().match(/^([A-Za-z_$][\w$]*)/);
44
+ if (m)
45
+ names.push(m[1]);
46
+ };
47
+ for (let i = 0; i < decl.length; i++) {
48
+ const ch = decl[i];
49
+ if (str) {
50
+ if (ch === str && decl[i - 1] !== '\\')
51
+ str = null;
52
+ continue;
53
+ }
54
+ if (ch === '"' || ch === "'" || ch === '`')
55
+ str = ch;
56
+ else if (ch === '(' || ch === '[' || ch === '{')
57
+ depth++;
58
+ else if (ch === ')' || ch === ']' || ch === '}')
59
+ depth--;
60
+ else if (ch === ',' && depth === 0) {
61
+ take(decl.slice(start, i));
62
+ start = i + 1;
63
+ }
64
+ }
65
+ take(decl.slice(start));
66
+ return names;
67
+ }
31
68
  /** Extract exported symbols from one source file. Pure. */
32
69
  export function extractSymbols(source, file) {
33
70
  const out = [];
@@ -37,9 +74,29 @@ export function extractSymbols(source, file) {
37
74
  const trimmed = raw.trimStart();
38
75
  if (!trimmed.startsWith('export'))
39
76
  continue;
77
+ // `export * as ns from '…'` (ES2020) creates a real named export `ns` — a
78
+ // namespace binding — unlike bare `export * from '…'` which adds no local
79
+ // name. Index it (kind 'const', the closest value-binding kind) before the
80
+ // blanket `export *` skip below.
81
+ const nsRe = /^export\s+\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\b/;
82
+ const nsm = trimmed.match(nsRe);
83
+ if (nsm) {
84
+ out.push({ name: nsm[1], kind: 'const', file, line: i + 1, signature: trimmed.slice(0, SIG_MAX).replace(/\s+$/, '') });
85
+ continue;
86
+ }
40
87
  // Skip re-export / bare forms handled elsewhere: `export {` and `export *`.
41
88
  if (/^export\s*[*{]/.test(trimmed))
42
89
  continue;
90
+ // const/let/var can declare MULTIPLE comma-separated bindings — index each
91
+ // (`export const a = 1, b = 2` → a AND b). Exclude `const enum` (handled by
92
+ // the enum matcher) and leave destructuring exports unindexed as before.
93
+ const declM = trimmed.match(/^export\s+(?:const|let|var)\s+(?!enum\b)(.*)$/);
94
+ if (declM) {
95
+ const sig = trimmed.slice(0, SIG_MAX).replace(/\s+$/, '');
96
+ for (const name of declaratorNames(declM[1]))
97
+ out.push({ name, kind: 'const', file, line: i + 1, signature: sig });
98
+ continue;
99
+ }
43
100
  for (const { kind, re } of MATCHERS) {
44
101
  const m = trimmed.match(re);
45
102
  if (!m)
@@ -77,6 +134,9 @@ export function extractImports(source, file) {
77
134
  const line = lines[i];
78
135
  if (!/\b(?:from|import|require)\b/.test(line))
79
136
  continue;
137
+ // A whole-import type-only form: `import type …` / `export type …`. NOT
138
+ // inline `import { type X }` (mixed with value imports → still a runtime edge).
139
+ const isTypeOnly = /^\s*(?:import|export)\s+type\b/.test(line);
80
140
  const seen = new Set();
81
141
  for (const re of IMPORT_RES) {
82
142
  re.lastIndex = 0;
@@ -86,7 +146,7 @@ export function extractImports(source, file) {
86
146
  if (seen.has(spec))
87
147
  continue; // same spec caught by two patterns on one line
88
148
  seen.add(spec);
89
- out.push({ from: file, spec, line: i + 1 });
149
+ out.push({ from: file, spec, line: i + 1, isTypeOnly });
90
150
  }
91
151
  }
92
152
  }
@@ -106,16 +166,20 @@ function joinRelative(fromFile, spec) {
106
166
  return parts.join('/');
107
167
  }
108
168
  const RESOLVE_EXTS = ['', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.mts', '.cts'];
109
- /**
110
- * Resolve a spec to a repo-relative file in `fileSet`, or null. Only relative
111
- * specs (`.`/`..`) resolve; bare specifiers (packages, aliases, `node:`) are
112
- * external → null. Tries the path as-is, common extensions, and `/index.*`,
113
- * and rewrites a `.js` spec to its `.ts` sibling (TS ESM convention).
114
- */
115
- export function resolveImport(fromFile, spec, fileSet) {
116
- if (!spec.startsWith('.'))
169
+ /** Substitute a spec through one alias (with `*` wildcard), or null if no match. Pure. */
170
+ function applyAlias(pattern, target, spec) {
171
+ const star = pattern.indexOf('*');
172
+ if (star < 0)
173
+ return spec === pattern ? target : null;
174
+ const prefix = pattern.slice(0, star);
175
+ const suffix = pattern.slice(star + 1);
176
+ if (spec.length < prefix.length + suffix.length || !spec.startsWith(prefix) || !spec.endsWith(suffix))
117
177
  return null;
118
- const base = joinRelative(fromFile, spec);
178
+ const mid = spec.slice(prefix.length, spec.length - suffix.length);
179
+ return target.includes('*') ? target.replace('*', mid) : target;
180
+ }
181
+ /** Resolve a bare repo-relative base path to a file in `fileSet` (exts + /index + .js→.ts). Pure. */
182
+ function resolveInFileSet(base, fileSet) {
119
183
  const bases = [base];
120
184
  const jsExt = base.match(/\.(js|jsx|mjs|cjs)$/);
121
185
  if (jsExt)
@@ -132,15 +196,35 @@ export function resolveImport(fromFile, spec, fileSet) {
132
196
  }
133
197
  return null;
134
198
  }
135
- /** Build an index from already-read files. Pure. */
136
- export function buildIndex(files) {
199
+ /**
200
+ * Resolve a spec to a repo-relative file in `fileSet`, or null. Relative specs
201
+ * (`.`/`..`) resolve against the importing file's dir. Bare specifiers resolve
202
+ * only if they match a tsconfig-`paths`/workspace `alias` — otherwise they're
203
+ * external (packages, `node:`) → null. Tries common extensions and `/index.*`,
204
+ * and rewrites a `.js` spec to its `.ts` sibling (TS ESM convention). Pure.
205
+ */
206
+ export function resolveImport(fromFile, spec, fileSet, aliases = []) {
207
+ if (spec.startsWith('.'))
208
+ return resolveInFileSet(joinRelative(fromFile, spec), fileSet);
209
+ for (const a of aliases) {
210
+ const cand = applyAlias(a.pattern, a.target, spec);
211
+ if (cand == null)
212
+ continue;
213
+ const r = resolveInFileSet(cand, fileSet);
214
+ if (r)
215
+ return r;
216
+ }
217
+ return null;
218
+ }
219
+ /** Build an index from already-read files. `aliases` resolve bare-specifier internal imports. Pure. */
220
+ export function buildIndex(files, aliases = []) {
137
221
  const symbols = [];
138
222
  const fileSet = new Set(files.map((f) => f.file));
139
223
  const imports = [];
140
224
  for (const { file, source } of files) {
141
225
  symbols.push(...extractSymbols(source, file));
142
226
  for (const imp of extractImports(source, file)) {
143
- imports.push({ ...imp, resolved: resolveImport(imp.from, imp.spec, fileSet) });
227
+ imports.push({ ...imp, resolved: resolveImport(imp.from, imp.spec, fileSet, aliases) });
144
228
  }
145
229
  }
146
230
  // Stable order: file, then line.
@@ -4,11 +4,18 @@
4
4
  * Shared by the `codegraph` CLI command and the codegraph MCP tools so the
5
5
  * scan/persist behaviour can't drift between them.
6
6
  */
7
- import { type CodeIndex } from './codegraph.js';
7
+ import { type CodeIndex, type ImportAlias } from './codegraph.js';
8
8
  export declare const INDEX_REL: string;
9
9
  /** Recursively collect source files under `root`, skipping vendor/build dirs and .d.ts. */
10
10
  export declare function walkSourceFiles(root: string): string[];
11
11
  export declare function indexPath(root: string): string;
12
+ /**
13
+ * Read `<root>/tsconfig.json` and derive repo-relative import aliases from
14
+ * `compilerOptions.paths` (+ `baseUrl`). Tolerant of JSONC comments/trailing
15
+ * commas; returns [] on any problem (so bare-specifier imports stay external,
16
+ * as before). Only the first target of each path pattern is used. Pure-ish (fs read).
17
+ */
18
+ export declare function parseTsconfigAliases(root: string): ImportAlias[];
12
19
  /** Scan a repo (or a subpath of it) and build the index. `root` is the repo
13
20
  * root used for relative paths; `scanRoot` (default = root) is where to walk. */
14
21
  export declare function scanRepo(root: string, scanRoot?: string): CodeIndex;
@@ -53,6 +53,83 @@ function safeRead(abs) {
53
53
  export function indexPath(root) {
54
54
  return path.join(root, INDEX_REL);
55
55
  }
56
+ /**
57
+ * Strip JSONC `//` and block comments + trailing commas, STRING-AWARE so a `/*`
58
+ * inside a path pattern (e.g. `"@app/*"`, ubiquitous in tsconfig paths) isn't
59
+ * mistaken for a comment start. Pure.
60
+ */
61
+ function stripJsonc(s) {
62
+ let out = '';
63
+ let inStr = false, esc = false;
64
+ for (let i = 0; i < s.length; i++) {
65
+ const ch = s[i];
66
+ if (inStr) {
67
+ out += ch;
68
+ if (esc)
69
+ esc = false;
70
+ else if (ch === '\\')
71
+ esc = true;
72
+ else if (ch === '"')
73
+ inStr = false;
74
+ continue;
75
+ }
76
+ if (ch === '"') {
77
+ inStr = true;
78
+ out += ch;
79
+ continue;
80
+ }
81
+ if (ch === '/' && s[i + 1] === '/') {
82
+ while (i < s.length && s[i] !== '\n')
83
+ i++;
84
+ out += '\n';
85
+ continue;
86
+ }
87
+ if (ch === '/' && s[i + 1] === '*') {
88
+ i += 2;
89
+ while (i < s.length && !(s[i] === '*' && s[i + 1] === '/'))
90
+ i++;
91
+ i++;
92
+ continue;
93
+ }
94
+ out += ch;
95
+ }
96
+ return out.replace(/,(\s*[}\]])/g, '$1');
97
+ }
98
+ /**
99
+ * Read `<root>/tsconfig.json` and derive repo-relative import aliases from
100
+ * `compilerOptions.paths` (+ `baseUrl`). Tolerant of JSONC comments/trailing
101
+ * commas; returns [] on any problem (so bare-specifier imports stay external,
102
+ * as before). Only the first target of each path pattern is used. Pure-ish (fs read).
103
+ */
104
+ export function parseTsconfigAliases(root) {
105
+ let raw;
106
+ try {
107
+ raw = fs.readFileSync(path.join(root, 'tsconfig.json'), 'utf8');
108
+ }
109
+ catch {
110
+ return [];
111
+ }
112
+ const json = stripJsonc(raw);
113
+ let cfg;
114
+ try {
115
+ cfg = JSON.parse(json);
116
+ }
117
+ catch {
118
+ return [];
119
+ }
120
+ const co = cfg.compilerOptions ?? {};
121
+ if (!co.paths || typeof co.paths !== 'object')
122
+ return [];
123
+ const baseUrl = typeof co.baseUrl === 'string' ? co.baseUrl : '.';
124
+ const aliases = [];
125
+ for (const [pattern, targets] of Object.entries(co.paths)) {
126
+ const first = Array.isArray(targets) ? targets[0] : undefined;
127
+ if (typeof first !== 'string')
128
+ continue;
129
+ aliases.push({ pattern, target: path.join(baseUrl, first).split(path.sep).join('/') });
130
+ }
131
+ return aliases;
132
+ }
56
133
  /** Scan a repo (or a subpath of it) and build the index. `root` is the repo
57
134
  * root used for relative paths; `scanRoot` (default = root) is where to walk. */
58
135
  export function scanRepo(root, scanRoot = root) {
@@ -60,7 +137,7 @@ export function scanRepo(root, scanRoot = root) {
60
137
  const read = files
61
138
  .map((abs) => ({ file: path.relative(root, abs), source: safeRead(abs) }))
62
139
  .filter((f) => f.source !== null);
63
- return buildIndex(read);
140
+ return buildIndex(read, parseTsconfigAliases(root));
64
141
  }
65
142
  /** Persist the index to .swarm/codegraph.json under `root`. */
66
143
  export function saveIndex(root, index) {
@@ -32,6 +32,7 @@ async function run(ctx) {
32
32
  const root = ctx.cwd || process.cwd();
33
33
  const dryRun = ctx.flags['dry-run'] === true;
34
34
  const partial = ctx.flags.partial === true;
35
+ const strict = ctx.flags.strict === true;
35
36
  // The parser may deliver --fuzz as a number or a string; accept both.
36
37
  const fuzz = typeof ctx.flags.fuzz === 'number' ? ctx.flags.fuzz
37
38
  : typeof ctx.flags.fuzz === 'string' ? parseInt(ctx.flags.fuzz, 10)
@@ -61,6 +62,7 @@ async function run(ctx) {
61
62
  }
62
63
  let totalApplied = 0;
63
64
  let totalRejected = 0;
65
+ let totalAmbiguous = 0;
64
66
  const writes = [];
65
67
  for (const fp of patches) {
66
68
  const file = targetFile(root, fp);
@@ -85,8 +87,16 @@ async function run(ctx) {
85
87
  totalApplied += applied;
86
88
  totalRejected += rejected;
87
89
  const fuzzy = res.hunks.filter((h) => h.applied && (h.fuzzUsed ?? 0) > 0).length;
90
+ const ambiguous = res.hunks.filter((h) => h.applied && h.ambiguous).length;
91
+ totalAmbiguous += ambiguous;
88
92
  const tag = rejected === 0 ? output.dim('ok') : output.bold(`${rejected} rejected`);
89
- output.writeln(`${rel} ${applied}/${res.hunks.length} hunks${fuzzy ? output.dim(` (${fuzzy} fuzzy)`) : ''} ${tag}`);
93
+ const ambTag = ambiguous ? output.error(` ${ambiguous} ambiguous`) : '';
94
+ output.writeln(`${rel} ${applied}/${res.hunks.length} hunks${fuzzy ? output.dim(` (${fuzzy} fuzzy)`) : ''} ${tag}${ambTag}`);
95
+ if (ambiguous) {
96
+ for (const h of res.hunks.filter((x) => x.applied && x.ambiguous)) {
97
+ output.writeln(output.dim(` ⚠ hunk @ line ${(h.at ?? 0) + 1}: matched a block that also appears elsewhere — verify it landed on the intended one`));
98
+ }
99
+ }
90
100
  if (rejected === 0 || partial) {
91
101
  if (res.result !== source)
92
102
  writes.push({ file, content: res.result });
@@ -97,9 +107,11 @@ async function run(ctx) {
97
107
  fs.writeFileSync(w.file, w.content);
98
108
  }
99
109
  const verb = dryRun ? 'would apply' : 'applied';
100
- output.writeln(output.dim(`${verb} ${totalApplied} hunks, ${totalRejected} rejected${dryRun ? ' (dry run)' : ''}`));
101
- // Exit 1 if anything was rejected a CI/agent can branch on it.
102
- const code = totalRejected > 0 ? 1 : 0;
110
+ const ambSummary = totalAmbiguous ? `, ${totalAmbiguous} ambiguous` : '';
111
+ output.writeln(output.dim(`${verb} ${totalApplied} hunks, ${totalRejected} rejected${ambSummary}${dryRun ? ' (dry run)' : ''}`));
112
+ // Exit 1 if anything was rejected a CI/agent can branch on it. With --strict,
113
+ // an ambiguous match (possibly landed on the wrong duplicate) also fails.
114
+ const code = totalRejected > 0 || (strict && totalAmbiguous > 0) ? 1 : 0;
103
115
  return { success: code === 0, exitCode: code };
104
116
  }
105
117
  export const applyCommand = {
@@ -109,6 +121,7 @@ export const applyCommand = {
109
121
  { name: 'dry-run', description: 'report what would apply/reject without writing', type: 'boolean' },
110
122
  { name: 'fuzz', description: 'max context lines to drop when matching a drifted hunk (default 2)', type: 'string' },
111
123
  { name: 'partial', description: 'write files even when some of their hunks are rejected', type: 'boolean' },
124
+ { name: 'strict', description: 'exit 1 if any hunk matched an ambiguous (duplicated) block, even if it applied', type: 'boolean' },
112
125
  ],
113
126
  examples: [
114
127
  { command: 'swarmdo apply changes.patch', description: 'Apply a patch file' },
@@ -0,0 +1,17 @@
1
+ /**
2
+ * `swarmdo compact-snapshot` — capture / restore a compaction-survival digest.
3
+ *
4
+ * swarmdo compact-snapshot write # snapshot working state (call on PreCompact)
5
+ * swarmdo compact-snapshot read # print the digest, then consume it (first
6
+ * # prompt after compaction re-injects it)
7
+ * swarmdo compact-snapshot read --keep # print without consuming
8
+ *
9
+ * The digest (recently edited files, uncommitted changes, branch) lets an agent
10
+ * re-ground after context compaction instead of re-exploring. The engine is
11
+ * pure + tested (../compact-snapshot/compact-snapshot.ts); this wrapper does the
12
+ * fs read (edit ledger), git calls, and one-shot persistence.
13
+ */
14
+ import type { Command } from '../types.js';
15
+ export declare const compactSnapshotCommand: Command;
16
+ export default compactSnapshotCommand;
17
+ //# sourceMappingURL=compact-snapshot.d.ts.map