@staix/agent-mem 0.31.0 → 0.32.1

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-mem",
3
- "version": "0.31.0",
3
+ "version": "0.32.1",
4
4
  "description": "Bounded project memory tools and seven deterministic capture hooks, without a resident worker.",
5
5
  "mcpServers": {
6
6
  "agent-mem": {
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  Curated memory with append-only JSONL logs, a derived SQLite index, short- and long-term tiers, a typed graph, goals with leases, and git sync between machines. Extracted from [agent-hub](https://github.com/STAIxBWLB/agent-hub), with compatible storage and entry IDs.
4
4
 
5
5
  <!-- facts:version -->
6
- Version: 0.31.0. Requires Bun 1.4.2 or later; no runtime dependencies.
6
+ Version: 0.32.1. Requires Bun 1.4.2 or later; no runtime dependencies.
7
7
  <!-- /facts:version -->
8
8
 
9
9
  ## Quick start
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staix/agent-mem",
3
- "version": "0.31.0",
3
+ "version": "0.32.1",
4
4
  "description": "Curated, shared memory for coding agents: append-only logs, a derived index, tiers and a typed graph.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -15,6 +15,7 @@ const RESULT_BYTES = 262_144;
15
15
 
16
16
  /** A refusal decided from the parsed command alone, before any store or file is opened: safe to show as is. */
17
17
  export class AgentUsageError extends Error {
18
+ readonly exitCode = 2;
18
19
  constructor(message: string) { super(message); this.name = "AgentUsageError"; }
19
20
  }
20
21
  const accepts = (command: string, allowed: readonly string[]) => new AgentUsageError(allowed.length
@@ -49,7 +50,7 @@ function route(parsed: ParsedCommand, argv: readonly string[]): ReadCall | undef
49
50
  // through the person handler with its own preview/--confirm or --apply steps and policy screens.
50
51
  if (definition.mutates !== undefined) return undefined;
51
52
 
52
- const flags = Object.keys(options).filter(key => key !== "--json" && key !== "--policy-free");
53
+ const flags = Object.keys(options).filter(key => key !== "--json" && key !== "--policy-free" && key !== "--color" && key !== "--ascii");
53
54
  const only = (...allowed: string[]) => flags.every(flag => allowed.includes(flag));
54
55
  const limit = positiveLimit(options["--limit"]);
55
56
  const checkedLimit = () => {
package/src/cli.ts CHANGED
@@ -68,7 +68,7 @@ import { buildNote, FAIL_TEMPLATE, hasFailLabel, noteAdd, parseFailTemplate, typ
68
68
  import { runEditor } from "./memory/editor.ts";
69
69
  import { doctorReport, doctorText } from "./memory/doctor.ts";
70
70
  import { statusText, type StatusView } from "./memory/status-text.ts";
71
- import { colorEnabled, style, facts, label, PLAIN, type Style } from "./memory/style.ts";
71
+ import { asciiMarkers, markerCell, paint, resolveColor, streamEnv, style, wrapReport, facts, label, PLAIN, type Style } from "./memory/style.ts";
72
72
  import { endLikeSignal, nextSyncAt, readSyncState, recordSyncAttempt, remoteConfigured, syncDue, stopSignal, syncOutcome, usableState, SYNC_IF_DUE_DEADLINE_MS, type StopCause } from "./memory/sync-cadence.ts";
73
73
 
74
74
  const VERSION = (JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version: string }).version;
@@ -234,7 +234,7 @@ class CliPartialApplyError extends Error {
234
234
  : "Operation stopped; the failed target may have changed. Receipt withheld by policy. Inspect state before retrying.");
235
235
  }
236
236
  render(): string {
237
- return this.jsonOutput ? JSON.stringify({ ok: false, partial: this.appliedCount > 0, appliedCount: this.appliedCount, failedMayHaveChanged: true, receiptWithheld: true }) : this.message;
237
+ return this.jsonOutput ? JSON.stringify({ ok: false, partial: this.appliedCount > 0, appliedCount: this.appliedCount, failedMayHaveChanged: true, receiptWithheld: true }, null, 2) : this.message;
238
238
  }
239
239
  }
240
240
 
@@ -314,8 +314,21 @@ class ReadPolicyWithheld extends Error {
314
314
  export const AUDIT_SCORE_REFUSED = "Audit score refused [cause: policy_denied]: the configured policy denies a value in the rendered score (its seed, as-of or project digest); no partial result is shown. Next step: check the policy (amem.config.json in the memory home, narrowed by the repository's .amem/config) against those values, or sample again with a different --seed.";
315
315
 
316
316
  export async function runCli(argv: readonly string[], context: CliContext = {}): Promise<string> {
317
+ if (argv.includes("-h")) argv = argv.map(arg => arg === "-h" ? "--help" : arg);
318
+ // The output flags may precede the command, but capture and MCP dispatch still need the command first.
319
+ const leading: string[] = [];
320
+ let offset = 0;
321
+ while (offset < argv.length) {
322
+ const token = argv[offset]!;
323
+ if (token === "--ascii" || token.startsWith("--color=")) { leading.push(token); offset++; continue; }
324
+ if (token === "--color" && argv[offset + 1] !== undefined && !argv[offset + 1]!.startsWith("--")) {
325
+ leading.push(token, argv[offset + 1]!); offset += 2; continue;
326
+ }
327
+ break;
328
+ }
329
+ if (leading.length && argv[offset] !== undefined && !argv[offset]!.startsWith("--")) argv = [...argv.slice(offset), ...leading];
317
330
  // Native capture and the MCP server retain their existing surfaces and attribution.
318
- if (argv[0] === "hook" || argv[0] === "ingest" || argv.length === 1 && argv[0] === "mcp") return runCliCommand(argv, context);
331
+ if (argv[0] === "hook" || argv[0] === "ingest" || argv[0] === "mcp") return runCliCommand(argv, context);
319
332
  const env = context.env ?? process.env, marked = agentMarked(env);
320
333
  const peer = !marked ? "person" : env.AGENTHUB_PEER_ID !== undefined ? env.AGENTHUB_PEER_ID || "agent"
321
334
  : env.CLAUDECODE !== undefined || env.CLAUDE_CODE_SESSION_ID !== undefined ? "claude" : env.CODEX_THREAD_ID !== undefined ? "codex" : "pi";
@@ -364,6 +377,12 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
364
377
  // #288 step 3: checkpoint refusals are fixed cause-and-next-step strings with numbers only (no path, row or project).
365
378
  if (marked && error instanceof Error && error.name === "PlacementCheckpointError" && error instanceof (await import("./memory/sync-placement-checkpoint-person.ts")).PlacementCheckpointError) throw new Error(error.message);
366
379
  const recovery=marked?safeProfileLockMessage(error):undefined;if(recovery)throw new Error(recovery);
380
+ // #520: a placement refusal caused by an applied setup receipt for a removed install keeps its target and remedy as
381
+ // fixed data; every other placement and sync failure keeps the generic masked refusal below.
382
+ if (marked) {
383
+ const refusal = (await import("./sync-placement-writer-context.ts")).markedSetupReceiptRefusal(error);
384
+ if (refusal) throw new Error(refusal);
385
+ }
367
386
  if (marked) {
368
387
  // parseCommand is pure: when it rejects argv, the error it raised is a usage error, not memory data.
369
388
  let usage: Error | undefined, parsed: ReturnType<typeof parseCommand> | undefined;
@@ -380,6 +399,14 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
380
399
  // Marked administrative failures must not reveal a target's private state or native errors.
381
400
  if (marked) throw Error("Memory operation unavailable or refused; no partial result is shown.");
382
401
  throw error;
402
+ }).then(output => {
403
+ // Preserve the value and the policy-screened result; only the JSON presentation changes.
404
+ try {
405
+ const parsed = parseCommand(argv);
406
+ if (parsed.options["--json"] === true) return JSON.stringify(JSON.parse(output), null, 2);
407
+ if (parsed.path[0] === "status" || parsed.path[0] === "doctor") return wrapReport(output, reportWidth(context));
408
+ } catch { /* Help and non-JSON special commands keep their existing output. */ }
409
+ return output;
383
410
  });
384
411
  }
385
412
  /**
@@ -391,7 +418,8 @@ export const MCP_PRELOAD = ["./memory/store.ts", "./memory/capture.ts", "./memor
391
418
  // The boundary check admits only literal specifiers, so the list above is spelled out again here; the test compares the two.
392
419
  const preloadMcp = () => Promise.all([import("./memory/store.ts"), import("./memory/capture.ts"), import("./memory/sync.ts"), import("./memory/shard-sync.ts"), import("./memory/public-prune-advance.ts")]);
393
420
  async function runCliCommand(argv: readonly string[], context: CliContext): Promise<string> {
394
- if (argv.length === 1 && argv[0] === "mcp") {
421
+ if (argv[0] === "mcp" && !argv.includes("--help")) {
422
+ parseCommand(argv);
395
423
  await preloadMcp();
396
424
  // #323: a host that knows the proposing session passes it; the CLI keys it like capture does, so a candidate points at the same session rows.
397
425
  const env = context.env ?? process.env;
@@ -403,7 +431,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
403
431
  }
404
432
  if (argv[0] === "hook" && !argv.includes("--help")) {
405
433
  const { hookMain } = await import("./hooks.ts");
406
- return hookMain(argv.slice(1));
434
+ return hookMain(argv.some(arg => arg === "--ascii" || arg === "--color" || arg.startsWith("--color=")) ? parseCommand(argv).positionals : argv.slice(1));
407
435
  }
408
436
  if (argv[0] === "ingest") {
409
437
  // Capture-only native intake: no project/home override, policy bypass or curated write capability.
@@ -416,13 +444,14 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
416
444
  cwd: context.cwd ?? process.cwd(), base: memoryHome(context.env ?? process.env),
417
445
  ...(typeof parsed.options["--since"] === "string" ? { since: parsed.options["--since"] as string } : {}),
418
446
  });
419
- return parsed.options["--json"] === true || !(context.stdoutTTY ?? process.stdout.isTTY) ? JSON.stringify(result) : ingestText(kind as IngestKind, result, outputStyle(context));
447
+ return parsed.options["--json"] === true ? JSON.stringify(result, null, 2) : ingestText(kind as IngestKind, result, outputStyle(context, parsed.options));
420
448
  }
421
449
  // Help and version carry no memory data.
422
450
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "version")) return `amem ${VERSION}`;
423
451
  if (argv.length === 1 && (argv[0] === "--help" || argv[0] === "help")) return commandHelp();
424
452
  if (argv[0] === "--version" || argv[0] === "version") return `amem ${VERSION}`;
425
- if (argv[0] === "--help" || argv[0] === "help" || argv.includes("--help")) return commandHelp(argv);
453
+ if (argv[0] === "help") return commandHelp(argv.slice(1));
454
+ if (argv[0] === "--help" || argv.includes("--help")) return commandHelp(argv);
426
455
  let parsed;
427
456
  try {
428
457
  parsed = parseCommand(argv);
@@ -478,7 +507,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
478
507
  env: context.env ?? process.env, stdinTTY: context.stdinTTY ?? process.stdin.isTTY, cwd: context.cwd ?? process.cwd(),
479
508
  ...(typeof options["--root"] === "string" ? { root: options["--root"] } : {}),
480
509
  ...(options["--adopt-current"] === true ? { adoptCurrent: true } : {}),
481
- ...(context.setupConfirm ? { confirm: context.setupConfirm } : {}), json: options["--json"] === true, style: outputStyle(context),
510
+ ...(context.setupConfirm ? { confirm: context.setupConfirm } : {}), json: options["--json"] === true, style: outputStyle(context, options),
482
511
  });
483
512
  }
484
513
  if (identity.actor === "agent") {
@@ -636,12 +665,12 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
636
665
  if (mode === "deactivate") throw new Error("--deactivate is not a shard migration mode");
637
666
  if (actor === "agent" && mode !== "dry-run") administrative(await migrateShards({ ...common, mode: "dry-run" }));
638
667
  const result = await migrateShards({ ...common, mode });
639
- return options["--json"] ? JSON.stringify(result, null, 2) : shardMigrationText(result, outputStyle(context));
668
+ return options["--json"] ? JSON.stringify(result, null, 2) : shardMigrationText(result, outputStyle(context, options));
640
669
  }
641
670
  if (actor === "agent" && mode === "deactivate") administrative({ target: common.memoryDir, selector: readSelector(common.memoryDir), mode });
642
671
  else if (actor === "agent" && mode !== "dry-run") administrative(await migrate({ ...common, mode: "dry-run" }));
643
672
  const result = await migrate({ ...common, mode });
644
- return options["--json"] ? JSON.stringify(result, null, 2) : migrationText(result, outputStyle(context));
673
+ return options["--json"] ? JSON.stringify(result, null, 2) : migrationText(result, outputStyle(context, options));
645
674
  }
646
675
  if (sub === "status") {
647
676
  // F1: say where the memory lives and which configuration is in effect. The migration fields keep their names and shape; `home` and `config` are added.
@@ -656,7 +685,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
656
685
  if (summary === null) return { unavailable: "candidates.db exists but cannot be read" };
657
686
  return { ...summary, ...(summary.dueWithin7Days ? { warning: `${summary.dueWithin7Days} candidate${summary.dueWithin7Days === 1 ? "" : "s"} within 7 days of expiry: run \`amem review walk\`` } : {}) }; })(),
658
687
  ...shardMigrationStatus(where.home) };
659
- return options["--json"] ? JSON.stringify(status, null, 2) : statusText(status as unknown as StatusView, outputStyle(context));
688
+ return options["--json"] ? JSON.stringify(status, null, 2) : statusText(status as unknown as StatusView, outputStyle(context, options));
660
689
  }
661
690
  if (parsed.path[0] === "formats" && parsed.path[1] === "raise") {
662
691
  const { planFormatRaise, applyFormatRaise, formatRaiseRefusal, installVersion, runningAmemRoots } = await import("./memory/formats-raise.ts");
@@ -699,7 +728,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
699
728
  const where = resolveMemoryHome(), project = boundProject();
700
729
  const report = await doctorReport({ home: where.home, homeSource: where.source, cwd: policyCwd, project, aliases: aliasedKeys(where.home, project), now: Date.now(),
701
730
  openCurated: base => curatedStoreAt(base, project, { deferPromotions: true }) });
702
- return options["--json"] ? JSON.stringify(report, null, 2) : doctorText(report, outputStyle(context));
731
+ return options["--json"] ? JSON.stringify(report, null, 2) : doctorText(report, outputStyle(context, options));
703
732
  }
704
733
  if (sub === "prune") {
705
734
  const applying = options["--apply"] === true;
@@ -728,7 +757,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
728
757
  administrative(port.snapshot().rows.filter(source => ids.has(source.row.id)).map(source => source.row));
729
758
  }
730
759
  const result = applying ? applyPrune(port, input, auth) : plan;
731
- return options["--json"] ? JSON.stringify(result, null, 2) : pruneText(result, outputStyle(context));
760
+ return options["--json"] ? JSON.stringify(result, null, 2) : pruneText(result, outputStyle(context, options));
732
761
  } finally { store.close(); }
733
762
  }
734
763
  if (sub === "decay") {
@@ -1003,13 +1032,13 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1003
1032
  if (sub === "vault-candidates" && (options["--all-projects"] === true || options["--project"] !== undefined)) {
1004
1033
  if (options["--all-projects"] === true && options["--project"] !== undefined) throw new Error("choose either --all-projects or --project <key>, not both");
1005
1034
  const result = await vaultCandidatesAll(memoryHome(), { policy: policyOf(), ...(options["--project"] !== undefined ? { project: resolveAlias(memoryHome(), String(options["--project"])) } : {}), ...(options["--limit"] ? { limit: Number(options["--limit"]) } : {}) });
1006
- return options["--json"] ? JSON.stringify(result, null, 2) : vaultCandidatesAllText(result, outputStyle(context));
1035
+ return options["--json"] ? JSON.stringify(result, null, 2) : vaultCandidatesAllText(result, outputStyle(context, options));
1007
1036
  }
1008
1037
  if (sub === "vault-candidates") {
1009
1038
  const project = boundProject(), store = curatedStore(project, { deferPromotions: true });
1010
1039
  try {
1011
1040
  const result = await vaultCandidates(store, { project, policy: policyOf(), ...(options["--limit"] ? { limit: Number(options["--limit"]) } : {}) });
1012
- return options["--json"] ? JSON.stringify(result, null, 2) : vaultCandidatesText(result, outputStyle(context));
1041
+ return options["--json"] ? JSON.stringify(result, null, 2) : vaultCandidatesText(result, outputStyle(context, options));
1013
1042
  } finally { store.close(); }
1014
1043
  }
1015
1044
  if (sub === "eval") {
@@ -1088,7 +1117,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1088
1117
  if (options["--cap-mb"] !== undefined || options["--retention-days"] !== undefined) throw new Error("--split computes each shard's values; do not combine it with --cap-mb or --retention-days");
1089
1118
  const diskShare = share !== undefined ? { diskShare: Number(share) } : {};
1090
1119
  const result = options["--confirm"] === true ? applySplit(memoryHome(), diskShare) : previewSplit(memoryHome(), diskShare);
1091
- return options["--json"] ? JSON.stringify(result, null, 2) : capacitySplitText(result, outputStyle(context));
1120
+ return options["--json"] ? JSON.stringify(result, null, 2) : capacitySplitText(result, outputStyle(context, options));
1092
1121
  }
1093
1122
  // Preview first; --confirm writes the bound home default config.
1094
1123
  const file = join(memoryHome(), "capture-config.json");
@@ -1102,7 +1131,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1102
1131
  if (options["--confirm"] !== true) {
1103
1132
  writeFileSync(previewFile, JSON.stringify(preview) + "\n", { mode: 0o600 });
1104
1133
  const result = { preview, confirm: "re-run with --confirm to write" };
1105
- return options["--json"] ? JSON.stringify(result, null, 2) : capacityApplyText(result, outputStyle(context));
1134
+ return options["--json"] ? JSON.stringify(result, null, 2) : capacityApplyText(result, outputStyle(context, options));
1106
1135
  }
1107
1136
  let approved: { file?: string; current?: unknown; target?: CaptureConfig };
1108
1137
  try { approved = JSON.parse(readFileSync(previewFile, "utf8")) as typeof approved; }
@@ -1114,7 +1143,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1114
1143
  const written = writeCaptureConfigFile(file, target);
1115
1144
  rmSync(previewFile, { force: true });
1116
1145
  const result = { preview, written: { cap_mb: written.capMb, retention_days: written.retentionDays } };
1117
- return options["--json"] ? JSON.stringify(result, null, 2) : capacityApplyText(result, outputStyle(context));
1146
+ return options["--json"] ? JSON.stringify(result, null, 2) : capacityApplyText(result, outputStyle(context, options));
1118
1147
  }
1119
1148
  if (sub === "projects") {
1120
1149
  // Archived projects stay listed (the person must see what is cold); a forgotten one is out of the default view, and --all brings it back with its state.
@@ -1410,7 +1439,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1410
1439
  } catch (error) {
1411
1440
  if (sub === "sync") progress?.finish(stop?.cause() ? "cancelled" : "failed", stop?.cause() ? "cancelled" : "unavailable");
1412
1441
  if (sub === "sync") stampSync((error as Error).message, stop?.cause());
1413
- if (sub === "sync" && placementWriters?.lastRefusal) throw Error(`${placementWriters.lastRefusal.message} ${(error as Error).message}`);
1442
+ if (sub === "sync" && placementWriters?.lastRefusal) throw (await import("./sync-placement-writer-context.ts")).placementSyncFailure(placementWriters.lastRefusal, error);
1414
1443
  throw error;
1415
1444
  }
1416
1445
  finally {
@@ -1438,7 +1467,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1438
1467
  const work = await importClaudeMemWorkState({ base: memoryHome(), project: boundProject(), policy: row => policy.screen(row), ...db, ...limit, restart });
1439
1468
  const capture = captureDays === undefined ? undefined : await importClaudeMemCapture({ base: memoryHome(), project: boundProject(), cwd, days: captureDays, ...db, ...limit, restart, policy: { host: policy } });
1440
1469
  return options["--json"] ? JSON.stringify({ ...JSON.parse(output), work, ...(capture ? { capture } : {}) }, null, 2)
1441
- : claudeMemImportText(JSON.parse(output), work, capture, { captureDays, restart }, outputStyle(context));
1470
+ : claudeMemImportText(JSON.parse(output), work, capture, { captureDays, restart }, outputStyle(context, options));
1442
1471
  }
1443
1472
  return !options["--json"] && receipt.bridgeStatus
1444
1473
  ? `${output}\n(legacy malformed lines skipped: ${receipt.bridgeStatus.skippedRows})` : output;
@@ -1457,7 +1486,16 @@ async function placementProgress(home: string, mode: string, context: CliContext
1457
1486
  const live = new Set(parts.keys());
1458
1487
  return new SyncProgress({ sink: snapshot => { for (const index of live) try { parts[index]!(snapshot); } catch { live.delete(index); } } });
1459
1488
  }
1460
- function outputStyle(context: CliContext): Style { return style(colorEnabled(context.env ?? process.env, context.stdoutTTY ?? process.stdout.isTTY)); }
1489
+ function outputStyle(context: CliContext, options: Record<string, string | boolean>): Style {
1490
+ const color = resolveColor(typeof options["--color"] === "string" ? options["--color"] : undefined, streamEnv((context.stdoutTTY ?? process.stdout.isTTY) === true, context.env ?? process.env));
1491
+ if (color instanceof Error) throw color;
1492
+ return style(options["--json"] !== true && color, asciiMarkers(context.env ?? process.env, options["--ascii"] === true));
1493
+ }
1494
+ function reportWidth(context: CliContext): number | undefined {
1495
+ const env = context.env ?? process.env, configured = Number(env.COLUMNS);
1496
+ if (Number.isSafeInteger(configured) && configured >= 20) return configured;
1497
+ return (context.stdoutTTY ?? process.stdout.isTTY) ? process.stdout.columns : undefined;
1498
+ }
1461
1499
 
1462
1500
  /** Native ingest remains capture-only and agent-reachable; this formats only its returned receipt. */
1463
1501
  export function ingestText(kind: IngestKind, result: IngestReceipt, s: Style = PLAIN): string {
@@ -1484,7 +1522,11 @@ export function ingestText(kind: IngestKind, result: IngestReceipt, s: Style = P
1484
1522
  `Next action: ${action}`].join("\n");
1485
1523
  }
1486
1524
 
1487
- export function formatCliError(error: unknown): string { return error instanceof DecayApplyError || error instanceof CliPartialApplyError ? error.render() : `amem: ${(error as Error).message}`; }
1525
+ export function formatCliError(error: unknown, usage = false): string {
1526
+ if (error instanceof DecayApplyError || error instanceof CliPartialApplyError) return error.render();
1527
+ const message = `amem: ${(error as Error).message}`;
1528
+ return usage || (error as { exitCode?: number }).exitCode === 2 ? `${message}\nUsage: amem <command> [options]\nRun 'amem --help' for details.` : message;
1529
+ }
1488
1530
 
1489
1531
  /** A completed write means rendered output, never evidence of host delivery or citation. */
1490
1532
  export async function writeCliOutput(text: string, output: Writable = process.stdout): Promise<void> { await writeConfirmed(output, text); }
@@ -1494,7 +1536,16 @@ export async function main(argv = process.argv.slice(2)): Promise<void> {
1494
1536
  const receipts: CliOutputReceipt[] = [], output = await runCli(argv, { onOutputReady: receipt => receipts.push(receipt), onPersonStop: name => { personStop ??= name; } });
1495
1537
  if (output) { await writeCliOutput(output + "\n"); for (const receipt of receipts) { try { receipt.rendered(); } catch { /* telemetry stays optional */ } } }
1496
1538
  } catch (error) {
1497
- console.error(formatCliError(error)); process.exitCode = (error as { exitCode?: number }).exitCode ?? 1;
1539
+ let prefix = "";
1540
+ if (process.stderr.isTTY) {
1541
+ let options: Record<string, string | boolean> = {};
1542
+ try { options = parseCommand(argv).options; } catch { /* Invalid options still report their usage error. */ }
1543
+ const color = resolveColor(typeof options["--color"] === "string" ? options["--color"] : undefined, streamEnv(true, process.env));
1544
+ const ascii = asciiMarkers(process.env, options["--ascii"] === true);
1545
+ prefix = `${paint("error", markerCell("fail", ascii), !argv.includes("--json") && color === true)} `;
1546
+ }
1547
+ const code = (error as { exitCode?: number }).exitCode ?? ((error as Error).message.startsWith("usage:") ? 2 : 1);
1548
+ console.error(prefix + formatCliError(error, code === 2)); process.exitCode = code;
1498
1549
  }
1499
1550
  if (personStop !== undefined) endLikeSignal(personStop); // after the report, with amem's own handlers already removed
1500
1551
  }
@@ -1,5 +1,6 @@
1
1
  import { HOOK_EVENTS } from "./hook-contract.ts";
2
2
  import { GOAL_STATES, KINDS } from "./memory/store.ts";
3
+ import { wrapReport } from "./memory/style.ts";
3
4
 
4
5
  export interface OptionDefinition { description: string; value?: "text" | "path" | readonly string[] }
5
6
  export interface ArgumentDefinition { name: string; values?: readonly string[]; path?: boolean; variadic?: boolean }
@@ -21,7 +22,7 @@ const policy = { "--policy-free": flag("Accepted and ignored: the configured pri
21
22
  const filters = { ...json, "--tier": { description: "Memory tier", value: ["short", "long"] } as OptionDefinition,
22
23
  "--kind": { description: "Note kind", value: KINDS }, "--peer": text("Author peer"), "--machine": text("Machine ID"),
23
24
  "--since": text("ISO date or time"), "--limit": text("Maximum results") };
24
- export const GLOBAL_OPTIONS = { "--help": flag("Show help") };
25
+ export const GLOBAL_OPTIONS = { "--help": flag("Show help"), "--color": { description: "Color output: auto, always or never", value: ["auto", "always", "never"] } as OptionDefinition, "--ascii": flag("Use ASCII markers") };
25
26
  export const ROOT_OPTIONS = { "--version": flag("Show version"), ...json };
26
27
  export const COMMANDS: Record<string, CommandDefinition> = {
27
28
  consolidate: { description: "Queue deterministic project-local consolidation candidates; curated notes change only after explicit acceptance", mutates: true, options: { ...json, "--project": text("The current project's key; another project is refused (run from its directory)") } },
@@ -177,6 +178,7 @@ export function completionDefinitions(): CompletionDefinition[] {
177
178
  walk(COMMANDS, [], GLOBAL_OPTIONS); return rows;
178
179
  }
179
180
  export interface ParsedCommand { path: string[]; definition: CommandDefinition; options: Record<string, string | boolean>; positionals: string[]; rawArgs: string[] }
181
+ export class CommandUsageError extends Error { readonly exitCode = 2; }
180
182
 
181
183
  /** Pure validation, shared definitions with help/completion; no store, files or network. */
182
184
  export function parseCommand(argv: readonly string[]): ParsedCommand {
@@ -192,16 +194,16 @@ export function parseCommand(argv: readonly string[]): ParsedCommand {
192
194
  const token = tokens[i]!;
193
195
  if (token.startsWith("--")) {
194
196
  const option = available[token];
195
- if (!option) throw new Error(`unknown option ${token}`);
197
+ if (!option) throw new CommandUsageError(`unknown option ${token}`);
196
198
  if (option.value !== undefined) {
197
199
  const value = tokens[++i];
198
- if (value === undefined || value.startsWith("--")) throw new Error(`${token} needs a value`);
199
- if (Array.isArray(option.value) && !option.value.includes(value)) throw new Error(`${token} takes ${option.value.join(" or ")}`);
200
+ if (value === undefined || value.startsWith("--")) throw new CommandUsageError(`${token} needs a value`);
201
+ if (Array.isArray(option.value) && !option.value.includes(value)) throw new CommandUsageError(`${token} takes ${option.value.join(" or ")}`);
200
202
  options[token] = value;
201
203
  } else options[token] = true;
202
204
  } else if (definition.commands) {
203
205
  const child: CommandDefinition | undefined = Object.hasOwn(definition.commands, token) ? definition.commands[token] : undefined;
204
- if (!child) throw new Error(`unknown command ${[...path, token].join(" ")}`);
206
+ if (!child) throw new CommandUsageError(`unknown command ${[...path, token].join(" ")}`);
205
207
  commandIndexes.add(i);
206
208
  definition = { ...definition, ...child }; path.push(token);
207
209
  // Child metadata inherits policy, but its command children belong only to that child.
@@ -216,14 +218,19 @@ export function parseCommand(argv: readonly string[]): ParsedCommand {
216
218
  if (definition.defaultCommand && definition.commands) {
217
219
  const name = definition.defaultCommand; definition = { ...definition, ...definition.commands[name]!, commands: undefined }; path.push(name);
218
220
  }
219
- if (positionals.length > (definition.args?.length ?? 0) && !definition.args?.at(-1)?.variadic) throw new Error(`too many arguments for ${path.join(" ")}`);
221
+ if (positionals.length > (definition.args?.length ?? 0) && !definition.args?.at(-1)?.variadic) throw new CommandUsageError(`too many arguments for ${path.join(" ")}`);
220
222
  for (let i = 0; i < positionals.length; i++) {
221
223
  const argument = definition.args?.[i];
222
- if (argument?.values && !argument.values.includes(positionals[i]!)) throw new Error(`${argument.name} takes ${argument.values.join(" or ")}`);
224
+ if (argument?.values && !argument.values.includes(positionals[i]!)) throw new CommandUsageError(`${argument.name} takes ${argument.values.join(" or ")}`);
223
225
  }
224
226
  const allowed = path[0] === "version" && options["--version"] === true ? completionDefinitions()[0]!.options : completionDefinitions().find(row => row.path.join(" ") === path.join(" "))!.options;
225
- for (const name of Object.keys(options)) if (!allowed[name]) throw new Error(`unknown option ${name} for ${path.join(" ")}`);
226
- const rawArgs = [...(path[0] === "goal" ? path.slice(1) : path), ...tokens.filter((arg, index) => arg !== "--policy-free" && !commandIndexes.has(index))];
227
+ for (const name of Object.keys(options)) if (!allowed[name]) throw new CommandUsageError(`unknown option ${name} for ${path.join(" ")}`);
228
+ const outputOptionIndexes = new Set<number>();
229
+ for (let i = 0; i < tokens.length; i++) {
230
+ if (tokens[i] === "--color") { outputOptionIndexes.add(i); outputOptionIndexes.add(++i); }
231
+ else if (tokens[i] === "--ascii") outputOptionIndexes.add(i);
232
+ }
233
+ const rawArgs = [...(path[0] === "goal" ? path.slice(1) : path), ...tokens.filter((arg, index) => arg !== "--policy-free" && !commandIndexes.has(index) && !outputOptionIndexes.has(index))];
227
234
  return { path, definition, options, positionals, rawArgs };
228
235
  }
229
236
 
@@ -255,8 +262,16 @@ export function commandHelp(argv: readonly string[] = []): string {
255
262
  if (command && path[0] !== "help") {
256
263
  const lines = [`usage: amem ${usageRow(row)}`, "", command.description, "", "options:", ...described(Object.entries(row.options).map(([name, option]) => [optionLabel(name, option), option.description]))];
257
264
  if (command.commands) lines.push("", "commands:", ...described(Object.entries(command.commands).map(([name, child]) => [name, child.description])));
258
- return lines.join("\n");
265
+ return wrapReport(lines.join("\n"), 80);
259
266
  }
260
- return ["usage: amem <command> [options]", " [--help] [--version] [--json]", ...completionDefinitions().filter(row => row.path.length).map(row => ` ${usageRow(row)}`),
261
- "--policy-free: accepted and ignored; the configured privacy policy (amem.config.json in the memory home, narrowed by .amem/config) always applies.", "Agent-marked reads use the MCP privacy ceiling. Explicit apply/confirm flags do not require a terminal; review walk and the note editor remain interactive."].join("\n");
267
+ const overview = Object.entries(COMMANDS).map(([name, item]) => {
268
+ const description = item.description.split("\n")[0] ?? "";
269
+ const limit = 76 - name.length - Math.max(1, 20 - name.length);
270
+ const summary = description.length > limit ? `${description.slice(0, limit - 3).trimEnd()}...` : description;
271
+ return ` ${name.padEnd(20)} ${summary}`;
272
+ });
273
+ return ["usage: amem <command> [options]", " [--help] [--version] [--json]", "", "Commands:", ...overview,
274
+ "--policy-free is accepted and ignored; the configured privacy policy applies.",
275
+ "Agent-marked reads use the MCP privacy ceiling. Apply and confirm need no TTY;",
276
+ "review walk and the note editor remain interactive."].join("\n");
262
277
  }
package/src/mcp-memory.ts CHANGED
@@ -67,6 +67,10 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
67
67
  const currentPolicy = () => calls.getStore()?.policy ?? createStandalonePolicy(policyOptions());
68
68
  const policyRevisionForCall = () => { const revision = policyKey(policyOptions()), active = calls.getStore(); if (active && active.revision !== revision) return unavailable(); return revision; };
69
69
  const policy = currentPolicy(), release = registerReaderLease(base);
70
+ // #354: a work read's per-row and per-view screens take this call's own snapshot, so a policy tightened after the
71
+ // server started still reaches them; outside a call it stays the startup policy, exactly as before, and no policy
72
+ // is built per row.
73
+ const screenPolicy = () => calls.getStore()?.policy ?? policy;
70
74
  const closers: (() => void)[] = [release]; let closed = false;
71
75
  const close = () => { if (closed) return; closed = true; let failure: unknown; for (const closer of closers.reverse()) { try { closer(); } catch (error) { failure ??= error; } } if (failure) throw failure; };
72
76
  try {
@@ -87,7 +91,7 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
87
91
  return read.state === "ok" ? read.views : [];
88
92
  };
89
93
  const candidates = new CandidateStore({ memoryDir: base, ...(reconcile ? { reconcile } : {}) }); closers.push(() => candidates.close());
90
- const work = new WorkListStore({ base, project, aliases, briefPolicyOptions: policyOptions, policy: async row => { const permitted = await policy.screen(row); guard(); return permitted; } }); closers.push(() => work.close());
94
+ const work = new WorkListStore({ base, project, aliases, briefPolicyOptions: policyOptions, policy: async row => { const permitted = await screenPolicy().screen(row); guard(); return permitted; } }); closers.push(() => work.close());
91
95
  const fullGuard = () => {
92
96
  if (!permitted()) unavailable();
93
97
  if (closed) unavailable(); options.assertCurrent?.();
@@ -311,7 +315,7 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
311
315
  // Reduce complete views before policy: individually public appends can compose into private state.
312
316
  const result = await work.read(textOf(args, "list", true), true);
313
317
  const permitted: typeof result = [];
314
- for (const view of result) if (await policy.screen(view)) permitted.push(view);
318
+ for (const view of result) if (await screenPolicy().screen(view)) permitted.push(view);
315
319
  guard();
316
320
  return args.includeClosed === true ? permitted : permitted.filter(view => !view.closed).map(view => ({ ...view, items: view.items.filter(item => item.fields.status !== "done" && item.fields.status !== "dropped") }));
317
321
  },
@@ -381,6 +385,21 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
381
385
  throw error;
382
386
  }
383
387
  };
388
+ // #354: the work read runs the same per-call context as the read tools, so its per-row guard() takes the cheap
389
+ // path instead of verifying the whole placement once per row. It is not one of the #485 sampled read tools, so it
390
+ // takes neither the metrics sample nor the recall-source preparation; the checks around the call are the read
391
+ // wrapper's: one full guard at entry, one after, and a policy revision that moved during the call refuses.
392
+ exposed.amem_work_state_read = async args => {
393
+ fullGuard();
394
+ const configured = policyOptions(), revision = policyKey(configured), snapshot = createStandalonePolicy(configured);
395
+ if (policyKey(policyOptions()) !== revision) return unavailable();
396
+ return calls.run({ policy: snapshot, revision, configured }, async () => {
397
+ const value = await tools.amem_work_state_read(args);
398
+ fullGuard();
399
+ if (policyKey(policyOptions()) !== revision) return unavailable();
400
+ return value;
401
+ });
402
+ };
384
403
  return { tools: exposed, close, onEmitted };
385
404
  } catch (error) { close(); throw error; }
386
405
  }
@@ -1,9 +1,9 @@
1
1
  import { Database } from "bun:sqlite";
2
2
  import { indexFileName } from "./index-file.ts";
3
- import { chmodSync, existsSync, lstatSync, readdirSync } from "node:fs";
3
+ import { chmodSync, existsSync, lstatSync, readdirSync, readFileSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { memoryBase } from "./home.ts";
6
- import { effectiveAliases, readShardDescriptor, SHARDED_SCHEMA, SHARDED_V2_SCHEMA } from "./shard.ts";
6
+ import { effectiveAliases, readShardDescriptor, SHARD_SCHEMA, SHARDED_SCHEMA, SHARDED_V2_SCHEMA } from "./shard.ts";
7
7
  import { readProfileJSON, validGeneration } from "./generation.ts";
8
8
  import { captureShardStats, readCaptureConfig } from "./capture.ts";
9
9
  import { openShardStore } from "./store.ts";
@@ -102,6 +102,33 @@ export function walkShards(base: string): { hash: string; key: string; local: bo
102
102
  return out;
103
103
  }
104
104
 
105
+ /**
106
+ * #359: the catalog's project keys, in scanCatalog's order, without per-shard stats (no store open, no SQLite read, no directory sizing).
107
+ * It keeps scanCatalog's placement selection guard, so a home scanCatalog refuses is refused here too. For pickers; `amem projects`/usage keep scanCatalog.
108
+ */
109
+ export function catalogKeys(base: string): string[] {
110
+ capturedSelection(base);
111
+ // Unlike walkShards, a read failure other than absence throws: a picker cache must never keep an inventory a transient error cut short.
112
+ const projectsDir = join(base, "projects");
113
+ let hashes: string[];
114
+ try { hashes = readdirSync(projectsDir, { withFileTypes: true }).filter((e) => e.isDirectory() && /^[0-9a-f]{16}$/.test(e.name)).map((e) => e.name); }
115
+ catch (e) { if (absent(e)) return []; throw e; }
116
+ const keys: string[] = [];
117
+ for (const hash of hashes) {
118
+ // One read: a transient failure throws instead of reading as a skipped shard. Absent or readable-but-invalid stays skipped, as in walkShards.
119
+ let text: string;
120
+ try { text = readFileSync(join(projectsDir, hash, "project.json"), "utf8"); }
121
+ catch (e) { if (absent(e)) continue; throw e; }
122
+ let d: unknown;
123
+ try { d = JSON.parse(text); } catch { continue; }
124
+ const v = d as { schema?: unknown; key?: unknown; local?: unknown } | null;
125
+ if (v?.schema === SHARD_SCHEMA && typeof v.key === "string" && typeof v.local === "boolean") keys.push(v.key);
126
+ }
127
+ return keys.sort((a, b) => a.localeCompare(b));
128
+ }
129
+
130
+ const absent = (e: unknown): boolean => (e as NodeJS.ErrnoException)?.code === "ENOENT" || (e as NodeJS.ErrnoException)?.code === "ENOTDIR";
131
+
105
132
  /** What the shards and the alias log say, before anything is persisted. */
106
133
  export function scanCatalog(base: string): CatalogProject[] {
107
134
  const captured = capturedSelection(base);
@@ -1,3 +1,4 @@
1
+ import { RECAP_SCRATCH } from "./recap-scratch.ts";
1
2
  import { existsSync } from "node:fs";
2
3
  import { join } from "node:path";
3
4
  import { MemoryStore, machineId, openShardStore } from "./store.ts";
@@ -8,15 +9,16 @@ import { aliasedKeys, readShardedSelection, resolveAlias, shardDir, shardKeyHash
8
9
  * an unsplit home has one shared store (the project filter selects), a split home has one shard per project. A split home's
9
10
  * capture-only shard (no `generation.json` yet) has no curated store, and the answer is `undefined`, never an empty one made on the spot.
10
11
  */
11
- export function openCuratedForRead(base: string, key: string): MemoryStore | undefined {
12
+ export function openCuratedForRead(base: string, key: string, scratch?: typeof RECAP_SCRATCH): MemoryStore | undefined {
13
+ const internal = scratch === RECAP_SCRATCH ? { [RECAP_SCRATCH]: true as const } : {};
12
14
  const aliases = aliasedKeys(base, key), reconcile = aliases.length ? { canonical: key, aliases } : undefined;
13
15
  if (existsSync(join(base, "shards.json"))) {
14
16
  readShardedSelection(base);
15
17
  if (!existsSync(join(shardDir(base, key), "generation.json"))) return undefined;
16
- return openShardStore({ memoryDir: base, project: key, deferPromotions: true, lifecycle: "ignore", ...(reconcile ? { reconcile } : {}) });
18
+ return openShardStore({ ...internal, memoryDir: base, project: key, deferPromotions: true, lifecycle: "ignore", ...(reconcile ? { reconcile } : {}) });
17
19
  }
18
20
  if (!existsSync(join(base, "log")) && !existsSync(join(base, "local")) && !existsSync(join(base, "generations"))) return undefined;
19
- return new MemoryStore({ memoryDir: base, deferPromotions: true, ...(reconcile ? { reconcile } : {}) });
21
+ return new MemoryStore({ ...internal, memoryDir: base, deferPromotions: true, ...(reconcile ? { reconcile } : {}) });
20
22
  }
21
23
 
22
24
  /** The canonical key of `key`, refused unless a shard of it exists. */
@@ -120,7 +120,7 @@ export class DecayApplyError extends Error {
120
120
  get failed(): string { return this.report.failed; }
121
121
  get remaining(): readonly string[] { return this.report.remaining; }
122
122
  render(): string {
123
- if (this.jsonOutput) return JSON.stringify({ ok: false, ...this.report, failedMayHaveChanged: this.failedMayHaveChanged });
123
+ if (this.jsonOutput) return JSON.stringify({ ok: false, ...this.report, failedMayHaveChanged: this.failedMayHaveChanged }, null, 2);
124
124
  return `${this.message}; applied: ${this.report.applied.join(", ") || "none"}; failed: ${this.report.failed}; remaining: ${this.report.remaining.join(", ") || "none"}${this.report.expiresAt ? `; completed demotions expire: ${this.report.expiresAt}` : ""}`;
125
125
  }
126
126
  }