swarmdo 1.27.0 → 1.30.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 (51) hide show
  1. package/.claude/helpers/auto-memory-hook.mjs +71 -34
  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 +11 -9
  13. package/package.json +1 -1
  14. package/v3/@swarmdo/cli/.claude/helpers/auto-memory-hook.mjs +70 -33
  15. package/v3/@swarmdo/cli/bin/cli.js +38 -0
  16. package/v3/@swarmdo/cli/dist/src/apply/apply.d.ts +6 -0
  17. package/v3/@swarmdo/cli/dist/src/apply/apply.js +41 -8
  18. package/v3/@swarmdo/cli/dist/src/commands/apply.js +17 -4
  19. package/v3/@swarmdo/cli/dist/src/commands/compact-snapshot.d.ts +17 -0
  20. package/v3/@swarmdo/cli/dist/src/commands/compact-snapshot.js +133 -0
  21. package/v3/@swarmdo/cli/dist/src/commands/index.js +4 -3
  22. package/v3/@swarmdo/cli/dist/src/commands/pack.d.ts +8 -0
  23. package/v3/@swarmdo/cli/dist/src/commands/pack.js +28 -2
  24. package/v3/@swarmdo/cli/dist/src/commands/usage.js +174 -2
  25. package/v3/@swarmdo/cli/dist/src/compact/compact.js +17 -7
  26. package/v3/@swarmdo/cli/dist/src/compact-snapshot/compact-snapshot.d.ts +58 -0
  27. package/v3/@swarmdo/cli/dist/src/compact-snapshot/compact-snapshot.js +104 -0
  28. package/v3/@swarmdo/cli/dist/src/config-lint/lint.js +16 -2
  29. package/v3/@swarmdo/cli/dist/src/init/helpers-generator.js +33 -3
  30. package/v3/@swarmdo/cli/dist/src/redact/redact.js +1 -1
  31. package/v3/@swarmdo/cli/dist/src/sbom/sbom.js +5 -2
  32. package/v3/@swarmdo/cli/dist/src/swarmvector/model-prices.js +12 -2
  33. package/v3/@swarmdo/cli/dist/src/testreport/testreport.js +11 -2
  34. package/v3/@swarmdo/cli/dist/src/transcript/export.d.ts +5 -0
  35. package/v3/@swarmdo/cli/dist/src/transcript/export.js +8 -1
  36. package/v3/@swarmdo/cli/dist/src/usage/claude-pricing.d.ts +6 -2
  37. package/v3/@swarmdo/cli/dist/src/usage/claude-pricing.js +33 -4
  38. package/v3/@swarmdo/cli/dist/src/usage/limits.d.ts +77 -0
  39. package/v3/@swarmdo/cli/dist/src/usage/limits.js +134 -0
  40. package/v3/@swarmdo/cli/dist/src/usage/reflect-html.d.ts +23 -0
  41. package/v3/@swarmdo/cli/dist/src/usage/reflect-html.js +94 -0
  42. package/v3/@swarmdo/cli/dist/src/usage/reflect.d.ts +105 -0
  43. package/v3/@swarmdo/cli/dist/src/usage/reflect.js +165 -0
  44. package/v3/@swarmdo/cli/dist/src/usage/spend-forecast.d.ts +28 -0
  45. package/v3/@swarmdo/cli/dist/src/usage/spend-forecast.js +33 -0
  46. package/v3/@swarmdo/cli/dist/src/usage/transcript-errors.d.ts +14 -0
  47. package/v3/@swarmdo/cli/dist/src/usage/transcript-errors.js +10 -0
  48. package/v3/@swarmdo/cli/dist/src/usage/transcript-usage.js +1 -1
  49. package/v3/@swarmdo/cli/dist/src/util/csv.d.ts +14 -0
  50. package/v3/@swarmdo/cli/dist/src/util/csv.js +20 -0
  51. package/v3/@swarmdo/cli/package.json +2 -2
@@ -13,7 +13,7 @@
13
13
 
14
14
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
15
15
  import { join, dirname } from 'path';
16
- import { fileURLToPath } from 'url';
16
+ import { fileURLToPath, pathToFileURL } from 'url';
17
17
 
18
18
  const __filename = fileURLToPath(import.meta.url);
19
19
  const __dirname = dirname(__filename);
@@ -52,13 +52,30 @@ async function gracefulExit(signal) {
52
52
  process.on('SIGTERM', () => { gracefulExit('SIGTERM'); });
53
53
  process.on('SIGINT', () => { gracefulExit('SIGINT'); });
54
54
 
55
- // Ensure data dir
56
- if (!existsSync(DATA_DIR)) mkdirSync(DATA_DIR, { recursive: true });
57
-
58
55
  // ============================================================================
59
56
  // Simple JSON File Backend (implements IMemoryBackend interface)
60
57
  // ============================================================================
61
58
 
59
+ // Collapse entries that are the SAME memory — identical content signature but
60
+ // distinct ids — keeping the first occurrence. The auto-memory bridge
61
+ // historically re-imported every session with a fresh random id, bloating the
62
+ // store ~22x (#53); this heals already-bloated stores and de-dupes defensively.
63
+ // Keyed by namespace + content hash (or raw content) so genuinely distinct
64
+ // memories are never merged. Pure.
65
+ function dedupeByContentSignature(entries) {
66
+ const seen = new Set();
67
+ const out = [];
68
+ for (const e of entries) {
69
+ const ns = (e && e.namespace) || 'default';
70
+ const body = (e && e.metadata && e.metadata.contentHash) || (e && (e.content || e.value)) || '';
71
+ const sig = ns + '\u0001' + body;
72
+ if (seen.has(sig)) continue;
73
+ seen.add(sig);
74
+ out.push(e);
75
+ }
76
+ return out;
77
+ }
78
+
62
79
  class JsonFileBackend {
63
80
  constructor(filePath) {
64
81
  this.filePath = filePath;
@@ -70,7 +87,12 @@ class JsonFileBackend {
70
87
  try {
71
88
  const data = JSON.parse(readFileSync(this.filePath, 'utf-8'));
72
89
  if (Array.isArray(data)) {
73
- for (const entry of data) this.entries.set(entry.id, entry);
90
+ // Collapse content-duplicates left by the pre-#53 import bug (same
91
+ // memory re-imported each session under a fresh id). Auto-heals an
92
+ // already-bloated store by rewriting it once when dupes are dropped.
93
+ const deduped = dedupeByContentSignature(data);
94
+ for (const entry of deduped) this.entries.set(entry.id, entry);
95
+ if (deduped.length < data.length) this._persist();
74
96
  }
75
97
  } catch { /* start fresh */ }
76
98
  }
@@ -99,7 +121,11 @@ class JsonFileBackend {
99
121
  async query(opts) {
100
122
  let results = [...this.entries.values()];
101
123
  if (opts?.namespace) results = results.filter(e => e.namespace === opts.namespace);
102
- if (opts?.type) results = results.filter(e => e.type === opts.type);
124
+ // NOTE: opts.type is the QueryType search STRATEGY (semantic|keyword|hybrid|…),
125
+ // NOT an entry MemoryType. This JSON backend has no vector search, so the
126
+ // strategy is moot — filtering entries by it excluded everything (a 'hybrid'
127
+ // query matched no 'semantic' entries), which zeroed out the bridge's
128
+ // content-hash dedup and let the store bloat ~22x per re-import (#53).
103
129
  if (opts?.limit) results = results.slice(0, opts.limit);
104
130
  return results;
105
131
  }
@@ -367,32 +393,43 @@ async function doStatus() {
367
393
  // Main
368
394
  // ============================================================================
369
395
 
370
- const command = process.argv[2] || 'status';
371
-
372
- // Dynamic import() failures can surface as unhandled rejections on a later
373
- // microtask even when the awaiting call site already caught them, which would
374
- // otherwise force a non-zero exit. Swallow to keep hooks exit-0, but surface the
375
- // reason under SWARMDO_DEBUG/DEBUG so genuine async bugs aren't silently hidden
376
- // (FIX 2 — the previous `() => {}` discarded every rejection process-wide).
377
- process.on('unhandledRejection', (reason) => {
378
- if (DEBUG) {
379
- const detail = reason && reason.message ? reason.message : String(reason);
380
- process.stderr.write(`[AutoMemory] unhandledRejection (suppressed): ${detail}\n`);
381
- }
382
- });
383
-
384
- try {
385
- switch (command) {
386
- case 'import': await doImport(); break;
387
- case 'sync': await doSync(); break;
388
- case 'status': await doStatus(); break;
389
- default:
390
- console.log('Usage: auto-memory-hook.mjs <import|sync|status>');
391
- break;
396
+ // Only dispatch CLI commands when this file is executed directly
397
+ // (`node auto-memory-hook.mjs …`), NOT when it is imported by a test —
398
+ // importing must not run a command or exit the process (#53 regression test
399
+ // imports JsonFileBackend + dedupeByContentSignature below).
400
+ if (import.meta.url === pathToFileURL(process.argv[1] || '').href) {
401
+ // Ensure data dir (only when actually running a command, not on import)
402
+ if (!existsSync(DATA_DIR)) mkdirSync(DATA_DIR, { recursive: true });
403
+ const command = process.argv[2] || 'status';
404
+
405
+ // Dynamic import() failures can surface as unhandled rejections on a later
406
+ // microtask even when the awaiting call site already caught them, which would
407
+ // otherwise force a non-zero exit. Swallow to keep hooks exit-0, but surface the
408
+ // reason under SWARMDO_DEBUG/DEBUG so genuine async bugs aren't silently hidden
409
+ // (FIX 2 — the previous `() => {}` discarded every rejection process-wide).
410
+ process.on('unhandledRejection', (reason) => {
411
+ if (DEBUG) {
412
+ const detail = reason && reason.message ? reason.message : String(reason);
413
+ process.stderr.write(`[AutoMemory] unhandledRejection (suppressed): ${detail}\n`);
414
+ }
415
+ });
416
+
417
+ try {
418
+ switch (command) {
419
+ case 'import': await doImport(); break;
420
+ case 'sync': await doSync(); break;
421
+ case 'status': await doStatus(); break;
422
+ default:
423
+ console.log('Usage: auto-memory-hook.mjs <import|sync|status>');
424
+ break;
425
+ }
426
+ } catch (err) {
427
+ // Hooks must never crash Claude Code - fail silently
428
+ try { dim(`Error (non-critical): ${err.message}`); } catch (_) {}
392
429
  }
393
- } catch (err) {
394
- // Hooks must never crash Claude Code - fail silently
395
- try { dim(`Error (non-critical): ${err.message}`); } catch (_) {}
430
+ // Force clean exit — process.exitCode alone isn't enough if async errors override it
431
+ process.exit(0);
396
432
  }
397
- // Force clean exit — process.exitCode alone isn't enough if async errors override it
398
- process.exit(0);
433
+
434
+ // Exported for unit tests (the run-guard above keeps import side-effect-free).
435
+ export { JsonFileBackend, dedupeByContentSignature };
@@ -93,6 +93,20 @@ console.log = (...args) => {
93
93
  _origLog.apply(console, args);
94
94
  };
95
95
 
96
+ // Claude Code plugin hint (code.claude.com/docs/en/plugin-hints): when a
97
+ // session runs swarmdo through Claude Code's Bash tool, emit the one-line
98
+ // marker so Claude Code can offer to install our plugin. Emitted here in the
99
+ // bin shim — NOT in dist/src/index.js — so it also covers the #2256 fast
100
+ // paths below (--version/--help are exactly the probes Claude runs on an
101
+ // unfamiliar CLI). Claude Code strips the line from all output before it
102
+ // reaches the model and only prompts if/when swarmdo-core is listed in the
103
+ // official Anthropic marketplace; until then it is silently dropped.
104
+ if (process.env.CLAUDECODE) {
105
+ process.stderr.write(
106
+ '<claude-code-hint v="1" type="plugin" value="swarmdo-core@claude-plugins-official" />\n'
107
+ );
108
+ }
109
+
96
110
  // #2256 fast path: --version / -V / --help / -h must NOT trigger heavy
97
111
  // imports (agentic-flow, swarmvector ONNX, etc.) — those eagerly download a
98
112
  // 23 MB ONNX model on cold cache, blocking 60+ s and causing SIGTERM
@@ -116,6 +130,30 @@ console.log = (...args) => {
116
130
  // loading. The version short-circuit is the only one safe to inline.
117
131
  }
118
132
 
133
+ // #45 fast path: `compact-snapshot` is wired to UserPromptSubmit (fires on
134
+ // EVERY prompt) and PreCompact, so it must not pay the full-CLI bootstrap
135
+ // (~0.6s incl. the 23 MB ONNX load). Its own module imports only fs/git/output
136
+ // + the pure engine, so dispatch it directly and exit before any heavy import.
137
+ // A bare `--help` still falls through to the rich help path below.
138
+ {
139
+ const _argv = process.argv.slice(2);
140
+ if (_argv[0] === 'compact-snapshot' && !_argv.includes('--help') && !_argv.includes('-h')) {
141
+ try {
142
+ const mod = await import('../dist/src/commands/compact-snapshot.js');
143
+ const cmd = mod.default ?? mod.compactSnapshotCommand;
144
+ const rest = _argv.slice(1);
145
+ const args = rest.filter((a) => !a.startsWith('-'));
146
+ const flags = {};
147
+ for (const a of rest) if (a.startsWith('--')) flags[a.replace(/^--/, '')] = true;
148
+ const res = await cmd.action({ cwd: process.cwd(), args, flags, rawArgs: rest });
149
+ process.exit(res && typeof res.exitCode === 'number' ? res.exitCode : 0);
150
+ } catch (e) {
151
+ // Best-effort: a failure here must never block a turn (it runs in hooks).
152
+ process.exit(0);
153
+ }
154
+ }
155
+ }
156
+
119
157
  // Check if we should run in MCP server mode
120
158
  // Conditions:
121
159
  // 1. stdin is being piped AND no CLI arguments provided (auto-detect)
@@ -41,6 +41,12 @@ export interface HunkResult {
41
41
  at?: number;
42
42
  /** how many context lines were trimmed to make it fit */
43
43
  fuzzUsed?: number;
44
+ /**
45
+ * True when the matched block occurs at MORE THAN ONE position in the file —
46
+ * the hunk landed at the nearest, but a duplicate/boilerplate block elsewhere
47
+ * means it may have modified the wrong occurrence. Callers should verify.
48
+ */
49
+ ambiguous?: boolean;
44
50
  }
45
51
  export interface ApplyResult {
46
52
  ok: boolean;
@@ -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;
@@ -90,6 +93,16 @@ function blockMatchesAt(source, at, block) {
90
93
  return false;
91
94
  return true;
92
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
+ }
93
106
  /**
94
107
  * Find where `block` occurs in `source`, preferring the position nearest
95
108
  * `expected` (0-based). Returns -1 if not found. Deterministic: on ties the
@@ -117,9 +130,19 @@ function findBlock(source, block, expected) {
117
130
  export function applyPatch(source, patch, opts = {}) {
118
131
  const fuzz = opts.fuzz ?? 2;
119
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;
120
141
  const lines = source.split('\n');
121
142
  if (trailingNewline)
122
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);
123
146
  let offset = 0;
124
147
  const results = [];
125
148
  // If a hunk that reaches EOF carries an explicit no-newline marker, it — not
@@ -142,7 +165,7 @@ export function applyPatch(source, patch, opts = {}) {
142
165
  if (lead > leadTrimmable || tail > tailTrimmable)
143
166
  continue;
144
167
  const trimmed = oldBlock.slice(lead, oldBlock.length - tail);
145
- const at = findBlock(lines, trimmed, expected + lead);
168
+ const at = findBlock(matchLines, trimmed, expected + lead);
146
169
  if (at >= 0) {
147
170
  placed = at - lead;
148
171
  usedFuzz = f;
@@ -156,13 +179,18 @@ export function applyPatch(source, patch, opts = {}) {
156
179
  results.push({ hunk, applied: false });
157
180
  continue;
158
181
  }
159
- // Splice: remove oldBlock.length lines at `placed`, insert newBlock.
160
- // (trimLead/trimTail only affected *matching*, not what we replace.)
161
- void trimLead;
162
- void trimTail;
163
- 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);
164
192
  offset += newBlock.length - oldBlock.length;
165
- results.push({ hunk, applied: true, at: placed, fuzzUsed: usedFuzz });
193
+ results.push({ hunk, applied: true, at: placed, fuzzUsed: usedFuzz, ...(ambiguous && { ambiguous: true }) });
166
194
  // If this hunk's new content is now the tail of the file, its markers
167
195
  // determine whether the file ends with a newline.
168
196
  if (placed + newBlock.length === lines.length)
@@ -173,6 +201,11 @@ export function applyPatch(source, patch, opts = {}) {
173
201
  const endWithNewline = eofNoEol === undefined ? trailingNewline : !eofNoEol;
174
202
  if (endWithNewline)
175
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);
176
209
  return { ok: results.every((r) => r.applied), result, hunks: results };
177
210
  }
178
211
  /**
@@ -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
@@ -0,0 +1,133 @@
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 { execFileSync } from 'node:child_process';
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+ import { output } from '../output.js';
18
+ import { buildDigest, formatDigest, isDigestEmpty, } from '../compact-snapshot/compact-snapshot.js';
19
+ const DIGEST_FILE = 'compact-digest.json';
20
+ const LEDGER_FILE = 'pending-insights.jsonl';
21
+ function dataDir(root) {
22
+ return path.join(root, '.swarmdo', 'data');
23
+ }
24
+ /** Best-effort git; returns '' on any failure (not-a-repo, no git). */
25
+ function git(root, args) {
26
+ try {
27
+ return execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 8 * 1024 * 1024 });
28
+ }
29
+ catch {
30
+ return '';
31
+ }
32
+ }
33
+ /** Read edit records from the pending-insights ledger. Tolerant of junk lines. */
34
+ function readEdits(root) {
35
+ const p = path.join(dataDir(root), LEDGER_FILE);
36
+ let raw;
37
+ try {
38
+ raw = fs.readFileSync(p, 'utf8');
39
+ }
40
+ catch {
41
+ return [];
42
+ }
43
+ const out = [];
44
+ for (const line of raw.split('\n')) {
45
+ if (!line.trim())
46
+ continue;
47
+ try {
48
+ const rec = JSON.parse(line);
49
+ if (rec && rec.type === 'edit' && typeof rec.file === 'string') {
50
+ out.push({ file: rec.file, timestamp: typeof rec.timestamp === 'number' ? rec.timestamp : 0 });
51
+ }
52
+ }
53
+ catch { /* skip malformed line */ }
54
+ }
55
+ return out;
56
+ }
57
+ function doWrite(root) {
58
+ // Drop swarmdo's own state dirs — they're not the user's working set and
59
+ // are usually gitignored anyway; filtering keeps the digest signal clean.
60
+ const gitStatus = git(root, ['status', '--porcelain'])
61
+ .split('\n')
62
+ .filter(Boolean)
63
+ .filter((l) => !/(^|\s|"|-> )\.(swarmdo|swarm|git)\//.test(l));
64
+ const digest = buildDigest({
65
+ now: Date.now(),
66
+ edits: readEdits(root),
67
+ gitStatus,
68
+ branch: git(root, ['rev-parse', '--abbrev-ref', 'HEAD']).trim() || undefined,
69
+ });
70
+ if (isDigestEmpty(digest)) {
71
+ // Nothing worth restoring — remove any stale digest so a later `read` is clean.
72
+ try {
73
+ fs.rmSync(path.join(dataDir(root), DIGEST_FILE));
74
+ }
75
+ catch { /* none */ }
76
+ output.writeln('compact-snapshot: no working state to capture');
77
+ return { success: true, exitCode: 0 };
78
+ }
79
+ try {
80
+ fs.mkdirSync(dataDir(root), { recursive: true });
81
+ fs.writeFileSync(path.join(dataDir(root), DIGEST_FILE), JSON.stringify(digest, null, 2) + '\n');
82
+ }
83
+ catch (e) {
84
+ output.printError(`compact-snapshot: could not write digest — ${e.message}`);
85
+ return { success: false, exitCode: 1 };
86
+ }
87
+ output.writeln(`compact-snapshot: captured ${digest.recentFiles.length} edited + ${digest.uncommitted.length} uncommitted`);
88
+ return { success: true, exitCode: 0 };
89
+ }
90
+ function doRead(root, keep) {
91
+ const file = path.join(dataDir(root), DIGEST_FILE);
92
+ let digest;
93
+ try {
94
+ digest = JSON.parse(fs.readFileSync(file, 'utf8'));
95
+ }
96
+ catch {
97
+ return { success: true, exitCode: 0 };
98
+ } // no digest → nothing to inject
99
+ const text = formatDigest(digest, Date.now());
100
+ if (text)
101
+ process.stdout.write(text + '\n');
102
+ if (!keep) {
103
+ try {
104
+ fs.rmSync(file);
105
+ }
106
+ catch { /* already gone */ }
107
+ } // consume-once
108
+ return { success: true, exitCode: 0 };
109
+ }
110
+ async function run(ctx) {
111
+ const root = ctx.cwd || process.cwd();
112
+ const mode = (ctx.args[0] ?? 'read').toLowerCase();
113
+ if (mode === 'write')
114
+ return doWrite(root);
115
+ if (mode === 'read')
116
+ return doRead(root, ctx.flags.keep === true);
117
+ output.printError(`compact-snapshot: unknown mode "${mode}" (use write | read)`);
118
+ return { success: false, exitCode: 1 };
119
+ }
120
+ export const compactSnapshotCommand = {
121
+ name: 'compact-snapshot',
122
+ description: 'Capture/restore a working-state digest that survives context compaction — recent edits, uncommitted changes, branch — so an agent re-grounds instead of re-exploring',
123
+ options: [
124
+ { name: 'keep', description: 'on read, print the digest without consuming it', type: 'boolean' },
125
+ ],
126
+ examples: [
127
+ { command: 'swarmdo compact-snapshot write', description: 'Snapshot working state (wire to a PreCompact hook)' },
128
+ { command: 'swarmdo compact-snapshot read', description: 'Print + consume the digest (wire to the first post-compaction prompt)' },
129
+ ],
130
+ action: run,
131
+ };
132
+ export default compactSnapshotCommand;
133
+ //# sourceMappingURL=compact-snapshot.js.map
@@ -22,6 +22,7 @@ const commandLoaders = {
22
22
  // Deterministic command-output compression (rtk/headroom demand) — a
23
23
  // zero-token stream filter, distinct from caveman `compress` for files.
24
24
  compact: () => import('./compact.js'),
25
+ 'compact-snapshot': () => import('./compact-snapshot.js'),
25
26
  // Secret detection + redaction on the agent data path (gitleaks/trufflehog
26
27
  // demand) — mask API keys/tokens before they reach an LLM/log/memory.
27
28
  redact: () => import('./redact.js'),
@@ -286,7 +287,7 @@ export async function getCommandsByCategory() {
286
287
  // three slots from 'statusline' onward (completionsCmd received the
287
288
  // statusline module, analyzeCmd received completions, …), scrambling the
288
289
  // categorized help. Every load now has a named slot.
289
- const [daemonCmd, doctorCmd, embeddingsCmd, neuralCmd, performanceCmd, securityCmd, swarmvectorCmd, hiveMindCmd, configCmd, statuslineCmd, compressCmd, efficiencyCmd, completionsCmd, migrateCmd, workflowCmd, analyzeCmd, routeCmd, progressCmd, providersCmd, pluginsCmd, deploymentCmd, claimsCmd, issuesCmd, updateCmd, processCmd, guidanceCmd, applianceCmd, cleanupCmd, autopilotCmd, demoCmd, usageCmd, repairCmd, hudCmd, compactCmd, codegraphCmd, redactCmd, packCmd, envCmd, licenseCmd, sbomCmd, applyCmd, hotspotsCmd, affectedCmd, cyclesCmd, testreportCmd,] = await Promise.all([
290
+ const [daemonCmd, doctorCmd, embeddingsCmd, neuralCmd, performanceCmd, securityCmd, swarmvectorCmd, hiveMindCmd, configCmd, statuslineCmd, compressCmd, efficiencyCmd, completionsCmd, migrateCmd, workflowCmd, analyzeCmd, routeCmd, progressCmd, providersCmd, pluginsCmd, deploymentCmd, claimsCmd, issuesCmd, updateCmd, processCmd, guidanceCmd, applianceCmd, cleanupCmd, autopilotCmd, demoCmd, usageCmd, repairCmd, hudCmd, compactCmd, codegraphCmd, redactCmd, packCmd, envCmd, licenseCmd, sbomCmd, applyCmd, hotspotsCmd, affectedCmd, cyclesCmd, testreportCmd, compactSnapshotCmd,] = await Promise.all([
290
291
  loadCommand('daemon'), loadCommand('doctor'), loadCommand('embeddings'), loadCommand('neural'),
291
292
  loadCommand('performance'), loadCommand('security'), loadCommand('swarmvector'), loadCommand('hive-mind'),
292
293
  loadCommand('config'), loadCommand('statusline'), loadCommand('compress'), loadCommand('efficiency'),
@@ -294,7 +295,7 @@ export async function getCommandsByCategory() {
294
295
  loadCommand('analyze'), loadCommand('route'), loadCommand('progress'), loadCommand('providers'),
295
296
  loadCommand('plugins'), loadCommand('deployment'), loadCommand('claims'), loadCommand('issues'),
296
297
  loadCommand('update'), loadCommand('process'), loadCommand('guidance'), loadCommand('appliance'),
297
- loadCommand('cleanup'), loadCommand('autopilot'), loadCommand('demo'), loadCommand('usage'), loadCommand('repair'), loadCommand('hud'), loadCommand('compact'), loadCommand('codegraph'), loadCommand('redact'), loadCommand('pack'), loadCommand('env'), loadCommand('license'), loadCommand('sbom'), loadCommand('apply'), loadCommand('hotspots'), loadCommand('affected'), loadCommand('cycles'), loadCommand('testreport'),
298
+ loadCommand('cleanup'), loadCommand('autopilot'), loadCommand('demo'), loadCommand('usage'), loadCommand('repair'), loadCommand('hud'), loadCommand('compact'), loadCommand('codegraph'), loadCommand('redact'), loadCommand('pack'), loadCommand('env'), loadCommand('license'), loadCommand('sbom'), loadCommand('apply'), loadCommand('hotspots'), loadCommand('affected'), loadCommand('cycles'), loadCommand('testreport'), loadCommand('compact-snapshot'),
298
299
  ]);
299
300
  return {
300
301
  primary: [
@@ -310,7 +311,7 @@ export async function getCommandsByCategory() {
310
311
  utility: [
311
312
  configCmd, doctorCmd, daemonCmd, completionsCmd,
312
313
  migrateCmd, workflowCmd, demoCmd,
313
- statuslineCmd, compressCmd, compactCmd, redactCmd, packCmd, envCmd, licenseCmd, sbomCmd, applyCmd, hotspotsCmd, affectedCmd, cyclesCmd, testreportCmd, efficiencyCmd,
314
+ statuslineCmd, compressCmd, compactCmd, redactCmd, packCmd, envCmd, licenseCmd, sbomCmd, applyCmd, hotspotsCmd, affectedCmd, cyclesCmd, testreportCmd, compactSnapshotCmd, efficiencyCmd,
314
315
  ].filter(Boolean),
315
316
  analysis: [
316
317
  analyzeCmd, routeCmd, progressCmd, usageCmd, hudCmd, codegraphCmd,
@@ -13,6 +13,14 @@
13
13
  * land in the bundle.
14
14
  */
15
15
  import type { Command } from '../types.js';
16
+ /**
17
+ * Decode a file buffer to bundle text, honoring BOMs (#10). UTF-16 LE/BE
18
+ * files decode to text (previously their NUL bytes tripped the binary
19
+ * heuristic and the file was silently dropped); a UTF-8 BOM is stripped
20
+ * instead of leaking into the bundle. Returns null for genuinely-binary
21
+ * content (NUL byte without a text BOM). Exported for tests.
22
+ */
23
+ export declare function decodeText(buf: Buffer): string | null;
16
24
  export declare const packCommand: Command;
17
25
  export default packCommand;
18
26
  //# sourceMappingURL=pack.d.ts.map
@@ -35,6 +35,31 @@ function looksBinary(buf) {
35
35
  return true;
36
36
  return false;
37
37
  }
38
+ /**
39
+ * Decode a file buffer to bundle text, honoring BOMs (#10). UTF-16 LE/BE
40
+ * files decode to text (previously their NUL bytes tripped the binary
41
+ * heuristic and the file was silently dropped); a UTF-8 BOM is stripped
42
+ * instead of leaking into the bundle. Returns null for genuinely-binary
43
+ * content (NUL byte without a text BOM). Exported for tests.
44
+ */
45
+ export function decodeText(buf) {
46
+ if (buf.length >= 3 && buf[0] === 0xef && buf[1] === 0xbb && buf[2] === 0xbf) {
47
+ return buf.subarray(3).toString('utf8');
48
+ }
49
+ if (buf.length >= 2 && buf[0] === 0xff && buf[1] === 0xfe) {
50
+ const body = buf.subarray(2);
51
+ if (body.length % 2 !== 0)
52
+ return null;
53
+ return body.toString('utf16le');
54
+ }
55
+ if (buf.length >= 2 && buf[0] === 0xfe && buf[1] === 0xff) {
56
+ const body = Buffer.from(buf.subarray(2)); // copy: swap16 mutates in place
57
+ if (body.length % 2 !== 0)
58
+ return null;
59
+ return body.swap16().toString('utf16le');
60
+ }
61
+ return looksBinary(buf) ? null : buf.toString('utf8');
62
+ }
38
63
  function walk(o) {
39
64
  const files = [];
40
65
  const stack = [o.root];
@@ -82,9 +107,10 @@ function walk(o) {
82
107
  catch {
83
108
  continue;
84
109
  }
85
- if (looksBinary(buf))
110
+ const text = decodeText(buf);
111
+ if (text === null)
86
112
  continue;
87
- files.push({ path: rel, content: buf.toString('utf8') });
113
+ files.push({ path: rel, content: text });
88
114
  }
89
115
  }
90
116
  }