@staix/agent-mem 0.30.0 → 0.32.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staix/agent-mem",
3
- "version": "0.30.0",
3
+ "version": "0.32.0",
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",
@@ -6,10 +6,16 @@ import { memoryHome } from "./memory/home.ts";
6
6
  import type { ParsedCommand } from "./commands-table.ts";
7
7
 
8
8
  const UNAVAILABLE = "Memory operation unavailable or refused; no partial result is shown.";
9
+ export const READ_FAILURE = "Memory read failed [cause: read_failed]; no partial result is shown. Ask the person to inspect the command and memory state.";
10
+ export class AgentReadFailure extends Error { constructor() { super(READ_FAILURE); this.name = "AgentReadFailure"; } }
11
+ export class AgentReadAmbiguous extends Error {
12
+ constructor() { super("Memory read unavailable [cause: unavailable]; failure and policy withholding cannot be distinguished. Ask the person to run the same command from their own shell."); this.name = "AgentReadAmbiguous"; }
13
+ }
9
14
  const RESULT_BYTES = 262_144;
10
15
 
11
16
  /** A refusal decided from the parsed command alone, before any store or file is opened: safe to show as is. */
12
17
  export class AgentUsageError extends Error {
18
+ readonly exitCode = 2;
13
19
  constructor(message: string) { super(message); this.name = "AgentUsageError"; }
14
20
  }
15
21
  const accepts = (command: string, allowed: readonly string[]) => new AgentUsageError(allowed.length
@@ -44,18 +50,23 @@ function route(parsed: ParsedCommand, argv: readonly string[]): ReadCall | undef
44
50
  // through the person handler with its own preview/--confirm or --apply steps and policy screens.
45
51
  if (definition.mutates !== undefined) return undefined;
46
52
 
47
- 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");
48
54
  const only = (...allowed: string[]) => flags.every(flag => allowed.includes(flag));
49
55
  const limit = positiveLimit(options["--limit"]);
50
- if (options["--limit"] !== undefined && limit === undefined) throw new AgentUsageError("--limit takes a whole number from 1 to 100.");
56
+ const checkedLimit = () => {
57
+ if (options["--limit"] !== undefined && limit === undefined) throw new AgentUsageError("--limit takes a whole number from 1 to 100.");
58
+ return limit;
59
+ };
51
60
 
52
61
  if (path[0] === "search") {
53
62
  if (!only("--limit", "--since", "--explain")) return undefined;
63
+ checkedLimit();
54
64
  if (!positionals.join(" ").trim()) throw new AgentUsageError("agent-marked search needs a query.");
55
65
  return { tool: "amem_search", args: { query: positionals.join(" "), ...(limit === undefined ? {} : { limit }), ...(options["--since"] !== undefined ? { since: options["--since"] } : {}), ...(options["--explain"] === true ? { explain: true } : {}) } };
56
66
  }
57
67
  if (path[0] === "list") {
58
68
  if (!only("--limit", "--since")) return undefined;
69
+ checkedLimit();
59
70
  return { tool: "amem_timeline", args: { ...(limit === undefined ? {} : { limit }), ...(options["--since"] !== undefined ? { since: options["--since"] } : {}) } };
60
71
  }
61
72
  if (path[0] === "show") {
@@ -73,6 +84,7 @@ function route(parsed: ParsedCommand, argv: readonly string[]): ReadCall | undef
73
84
  }
74
85
  if (path[0] === "vault-candidates") {
75
86
  if (!only("--limit") || options["--all-projects"] !== undefined || options["--project"] !== undefined) return undefined;
87
+ checkedLimit();
76
88
  return { tool: "amem_vault_candidates", args: limit === undefined ? {} : { limit } };
77
89
  }
78
90
  if (path[0] === "capacity" && path.length === 1) {
@@ -106,7 +118,11 @@ export async function agentCliRead(
106
118
  return output;
107
119
  } catch (error) {
108
120
  if(safeProfileLockMessage(error))throw error;
109
- throw new Error(UNAVAILABLE);
121
+ // The MCP handler deliberately uses one refusal for policy and operational guards; do not guess which occurred.
122
+ let ambiguous = false;
123
+ try { ambiguous = error instanceof Error && Object.getOwnPropertyDescriptor(error, "message")?.value === "memory operation unavailable"; } catch { /* An opaque error remains a generic failure. */ }
124
+ if (ambiguous) throw new AgentReadAmbiguous();
125
+ throw new AgentReadFailure();
110
126
  } finally {
111
127
  try { memory?.close(); } catch { /* close failures do not expose partial reads */ }
112
128
  }
package/src/cli.ts CHANGED
@@ -3,7 +3,7 @@ import { assertFormatFloor } from "./memory/formats.ts";
3
3
  import { placementRuntimeRefusal, readPlacementRuntimeMarkers } from "./memory/sync-placement-guard.ts";
4
4
  import { readActivePlacementBinding } from "./memory/sync-placement-active.ts";
5
5
  import { activatePublicPruneView } from "./memory/public-prune-activation.ts";
6
- import { AgentUsageError, agentCliRead } from "./cli-agent-reads.ts";
6
+ import { AgentReadAmbiguous, AgentReadFailure, AgentUsageError, agentCliRead } from "./cli-agent-reads.ts";
7
7
  import { cliAttribution, withCliAttribution } from "./memory/cli-attribution.ts";
8
8
  import { createHash, randomUUID } from "node:crypto";
9
9
  import type { Writable } from "node:stream";
@@ -13,7 +13,7 @@ import { recordCaptureLookup, recordSourceCheck, recordWindow } from "./memory/r
13
13
  import { createIntentBriefSource, recallViewIsLive } from "./memory/recall.ts";
14
14
  import { createRecallStalenessProbe } from "./memory/recall-staleness.ts";
15
15
  import { recordMemoryUse } from "./memory/use-telemetry.ts";
16
- import { DecayApplyError } from "./memory/decay-review.ts";
16
+ import { DecayApplyError, UNUSED_INJECTION_REASON } from "./memory/decay-review.ts";
17
17
  import { createMemoryMcp } from "./mcp-memory.ts";
18
18
  import { safeProfileLockMessage } from "./memory/profile-lock-diagnostic.ts";
19
19
  import { PLACEMENT_CHECKPOINT_PENDING_MESSAGE } from "./memory/sync-placement-journal-format.ts";
@@ -31,7 +31,7 @@ import { originLine, originRecheck } from "./memory/candidate-origin.ts";
31
31
  import { MemoryStore, looksSecret, machineId, openShardStore, type StoreOptions } from "./memory/store.ts";
32
32
  import { rawMemoryCommand, rawGoalCommand, claudeMemImportText } from "./memory/commands.ts";
33
33
  import { memoryProjectKey } from "./memory/project.ts";
34
- import { CandidateStore, candidateTargetRevision, type CandidateFilter } from "./memory/candidates.ts";
34
+ import { CandidateStore, candidateInputId, candidateTargetRevision, type CandidateFilter } from "./memory/candidates.ts";
35
35
  import { candidateOverlaps, candidateOverlapsBatch } from "./memory/candidate-overlaps.ts";
36
36
  import { openCuratedForRead } from "./memory/curated-read.ts";
37
37
  import { aliasedKeys, appendAlias, appendUnalias, listAliases, readShardedSelection, resolveAlias } from "./memory/shard.ts";
@@ -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;
@@ -199,7 +199,7 @@ function assertAgentAdministrative(value: unknown, policy: ReturnType<typeof con
199
199
  if (cliAttribution()?.actor !== "agent") return;
200
200
  let plain: unknown;
201
201
  try { plain = JSON.parse(JSON.stringify(value)); } catch { throw Error("Memory operation unavailable or refused; no partial result is shown."); }
202
- if (!policy.screenStandalone(plain)) throw Error("Memory operation unavailable or refused; no partial result is shown.");
202
+ if (!policy.screenStandalone(plain)) throw new ReadPolicyWithheld();
203
203
  }
204
204
  function shardStatePresent(): boolean {
205
205
  try { lstatSync(join(memoryHome(), "shards.json")); return true; }
@@ -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
 
@@ -277,7 +277,7 @@ function markedSetupApplyError(parsed: ReturnType<typeof parseCommand>, error: u
277
277
  cause = "setup_receipt_orca_profile"; next = "The receipt was written from an Orca Claude profile; rerun setup from that Orca profile."; partial = false;
278
278
  } else if (text === "setup receipt is stale: its managed entries were replaced at another amem install root; rerun with --adopt-current to adopt the current wiring") {
279
279
  cause = "setup_receipt_stale"; next = "The receipt's managed entries were replaced at another amem install root outside setup; rerun with --apply --adopt-current to keep the receipt aside and adopt the current wiring, which --undo then restores."; partial = false;
280
- } else if (/^setup-owned .+ changed; refusing to overwrite it$/.test(text) || text === "Pi amem-session extension already exists and is not this setup's file"
280
+ } else if (/^setup-owned .+ changed; refusing to overwrite it$/.test(text) || text === "Pi amem-session extension already exists and is not this setup's file; inspect it, move your changes to another extension file or remove it, then rerun setup"
281
281
  || text === "previous-runtime hook settings are customized; review hook configuration before retrying setup"
282
282
  || /^setup receipt (?:does not match this installation|target mismatch|invalid|directory ownership invalid)$/.test(text)) {
283
283
  cause = "setup_ownership_conflict"; next = "Review the managed entries and saved setup receipt before retrying; keep unrelated configuration intact."; partial = false;
@@ -299,9 +299,36 @@ function markedSetupApplyError(parsed: ReturnType<typeof parseCommand>, error: u
299
299
  return safe;
300
300
  }
301
301
 
302
+ /** Some commands write files despite having no mutates entry; preserve their existing effectful error/receipt treatment. */
303
+ function markedReadOnly(parsed: ReturnType<typeof parseCommand>): boolean {
304
+ return parsed.definition.mutates === undefined && parsed.path[0] !== "setup"
305
+ && !(parsed.path[0] === "eval" && parsed.path[1] === "audit" && parsed.path[2] === "sample")
306
+ && !(parsed.path[0] === "project" && parsed.path[1] === "export");
307
+ }
308
+
309
+ class ReadPolicyWithheld extends Error {
310
+ constructor() { super("Memory read withheld [cause: policy_withheld]; no partial result is shown. Ask the person to check the configured policy."); }
311
+ }
312
+
313
+ /** #326: a marked score read the policy refuses names its cause class and where to check it, never the matched value. */
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
+
302
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];
303
330
  // Native capture and the MCP server retain their existing surfaces and attribution.
304
- 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);
305
332
  const env = context.env ?? process.env, marked = agentMarked(env);
306
333
  const peer = !marked ? "person" : env.AGENTHUB_PEER_ID !== undefined ? env.AGENTHUB_PEER_ID || "agent"
307
334
  : env.CLAUDECODE !== undefined || env.CLAUDE_CODE_SESSION_ID !== undefined ? "claude" : env.CODEX_THREAD_ID !== undefined ? "codex" : "pi";
@@ -309,7 +336,8 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
309
336
  const output = await runCliCommand(argv, context);
310
337
  if (marked && !argv.includes("--help") && !["--version", "version", "--help", "help", "completion"].includes(argv[0] ?? "")) {
311
338
  const parsed = parseCommand(argv);
312
- if (parsed.definition.mutates !== undefined || parsed.path[0] === "setup") {
339
+ // Audit outputs and review targets are screened whole for marked reads.
340
+ if (parsed.definition.mutates !== undefined || parsed.path[0] === "setup" || parsed.path[0] === "eval" && parsed.path[1] === "audit" || parsed.path[0] === "review" && parsed.path[1] === "targets") {
313
341
  let receipt: unknown = output;
314
342
  // Import receipts contain fixed counters named `pii`; they are not row privacy flags.
315
343
  // Screen the complete rendered receipt, including every key and value, as text.
@@ -317,7 +345,12 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
317
345
  try { receipt = JSON.parse(output); } catch { /* human receipts remain strings */ }
318
346
  }
319
347
  try { assertAgentAdministrative(receipt, configuredPolicy(parsed.path[0] === "setup" ? memoryHome({ ...process.env, ...env }) : memoryHome(), context.cwd ?? process.cwd())); }
320
- catch {
348
+ catch (error) {
349
+ if (markedReadOnly(parsed) && !(error instanceof ReadPolicyWithheld)) throw error;
350
+ // A score leaves nothing behind, so an output the policy refuses refuses the read; a sample has written its private sheet already, and withholding
351
+ // the receipt reports exactly that without naming the file.
352
+ if (parsed.path[0] === "eval" && parsed.path[2] === "score") throw Error(AUDIT_SCORE_REFUSED);
353
+ if (markedReadOnly(parsed)) throw new ReadPolicyWithheld();
321
354
  // The command returned successfully: withholding its receipt cannot undo its effects.
322
355
  const failed = receipt !== null && typeof receipt === "object" && "ok" in receipt && receipt.ok === false;
323
356
  return parsed.options["--json"] === true ? JSON.stringify({ ok: !failed, completed: !failed, receiptWithheld: true })
@@ -335,13 +368,21 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
335
368
  const safe = new DecayApplyError(error.report, undefined); safe.jsonOutput = error.jsonOutput; throw safe;
336
369
  }
337
370
  // Data-free errors (decided before any store or file is opened) keep their own message.
338
- if (marked && error instanceof AgentUsageError) throw error;
371
+ if (marked && (error instanceof AgentUsageError || error instanceof AgentReadFailure || error instanceof AgentReadAmbiguous)) throw error;
339
372
  if (marked && error instanceof RemoteRealmRefusal) throw error;
340
373
  // The checkpoint pending message is a fixed data-free remedy shared by journal and writer guards.
341
374
  if (marked && error instanceof Error && error.message === PLACEMENT_CHECKPOINT_PENDING_MESSAGE) throw new Error(PLACEMENT_CHECKPOINT_PENDING_MESSAGE);
375
+ // #326: the audit score refusal is a fixed cause-class string that names no matched value.
376
+ if (marked && error instanceof Error && error.message === AUDIT_SCORE_REFUSED) throw new Error(AUDIT_SCORE_REFUSED);
342
377
  // #288 step 3: checkpoint refusals are fixed cause-and-next-step strings with numbers only (no path, row or project).
343
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);
344
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
+ }
345
386
  if (marked) {
346
387
  // parseCommand is pure: when it rejects argv, the error it raised is a usage error, not memory data.
347
388
  let usage: Error | undefined, parsed: ReturnType<typeof parseCommand> | undefined;
@@ -349,10 +390,23 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
349
390
  if (usage) throw Object.assign(new Error(usage.message), (error as { exitCode?: number }).exitCode === undefined ? {} : { exitCode: (error as { exitCode?: number }).exitCode });
350
391
  const setupError = parsed && markedSetupApplyError(parsed, error);
351
392
  if (setupError) throw setupError;
393
+ if (parsed && markedReadOnly(parsed)) {
394
+ if (error instanceof ReadPolicyWithheld) throw error;
395
+ if (error instanceof Error && error.message === "Memory operation unavailable or refused; no partial result is shown.") throw Error(error.message);
396
+ throw new AgentReadFailure();
397
+ }
352
398
  }
353
399
  // Marked administrative failures must not reveal a target's private state or native errors.
354
400
  if (marked) throw Error("Memory operation unavailable or refused; no partial result is shown.");
355
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;
356
410
  });
357
411
  }
358
412
  /**
@@ -364,7 +418,8 @@ export const MCP_PRELOAD = ["./memory/store.ts", "./memory/capture.ts", "./memor
364
418
  // The boundary check admits only literal specifiers, so the list above is spelled out again here; the test compares the two.
365
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")]);
366
420
  async function runCliCommand(argv: readonly string[], context: CliContext): Promise<string> {
367
- if (argv.length === 1 && argv[0] === "mcp") {
421
+ if (argv[0] === "mcp" && !argv.includes("--help")) {
422
+ parseCommand(argv);
368
423
  await preloadMcp();
369
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.
370
425
  const env = context.env ?? process.env;
@@ -376,7 +431,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
376
431
  }
377
432
  if (argv[0] === "hook" && !argv.includes("--help")) {
378
433
  const { hookMain } = await import("./hooks.ts");
379
- return hookMain(argv.slice(1));
434
+ return hookMain(argv.some(arg => arg === "--ascii" || arg === "--color" || arg.startsWith("--color=")) ? parseCommand(argv).positionals : argv.slice(1));
380
435
  }
381
436
  if (argv[0] === "ingest") {
382
437
  // Capture-only native intake: no project/home override, policy bypass or curated write capability.
@@ -389,13 +444,14 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
389
444
  cwd: context.cwd ?? process.cwd(), base: memoryHome(context.env ?? process.env),
390
445
  ...(typeof parsed.options["--since"] === "string" ? { since: parsed.options["--since"] as string } : {}),
391
446
  });
392
- 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));
393
448
  }
394
449
  // Help and version carry no memory data.
395
450
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "version")) return `amem ${VERSION}`;
396
451
  if (argv.length === 1 && (argv[0] === "--help" || argv[0] === "help")) return commandHelp();
397
452
  if (argv[0] === "--version" || argv[0] === "version") return `amem ${VERSION}`;
398
- 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);
399
455
  let parsed;
400
456
  try {
401
457
  parsed = parseCommand(argv);
@@ -451,7 +507,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
451
507
  env: context.env ?? process.env, stdinTTY: context.stdinTTY ?? process.stdin.isTTY, cwd: context.cwd ?? process.cwd(),
452
508
  ...(typeof options["--root"] === "string" ? { root: options["--root"] } : {}),
453
509
  ...(options["--adopt-current"] === true ? { adoptCurrent: true } : {}),
454
- ...(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),
455
511
  });
456
512
  }
457
513
  if (identity.actor === "agent") {
@@ -609,12 +665,12 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
609
665
  if (mode === "deactivate") throw new Error("--deactivate is not a shard migration mode");
610
666
  if (actor === "agent" && mode !== "dry-run") administrative(await migrateShards({ ...common, mode: "dry-run" }));
611
667
  const result = await migrateShards({ ...common, mode });
612
- 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));
613
669
  }
614
670
  if (actor === "agent" && mode === "deactivate") administrative({ target: common.memoryDir, selector: readSelector(common.memoryDir), mode });
615
671
  else if (actor === "agent" && mode !== "dry-run") administrative(await migrate({ ...common, mode: "dry-run" }));
616
672
  const result = await migrate({ ...common, mode });
617
- 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));
618
674
  }
619
675
  if (sub === "status") {
620
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.
@@ -629,7 +685,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
629
685
  if (summary === null) return { unavailable: "candidates.db exists but cannot be read" };
630
686
  return { ...summary, ...(summary.dueWithin7Days ? { warning: `${summary.dueWithin7Days} candidate${summary.dueWithin7Days === 1 ? "" : "s"} within 7 days of expiry: run \`amem review walk\`` } : {}) }; })(),
631
687
  ...shardMigrationStatus(where.home) };
632
- 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));
633
689
  }
634
690
  if (parsed.path[0] === "formats" && parsed.path[1] === "raise") {
635
691
  const { planFormatRaise, applyFormatRaise, formatRaiseRefusal, installVersion, runningAmemRoots } = await import("./memory/formats-raise.ts");
@@ -672,7 +728,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
672
728
  const where = resolveMemoryHome(), project = boundProject();
673
729
  const report = await doctorReport({ home: where.home, homeSource: where.source, cwd: policyCwd, project, aliases: aliasedKeys(where.home, project), now: Date.now(),
674
730
  openCurated: base => curatedStoreAt(base, project, { deferPromotions: true }) });
675
- 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));
676
732
  }
677
733
  if (sub === "prune") {
678
734
  const applying = options["--apply"] === true;
@@ -701,17 +757,30 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
701
757
  administrative(port.snapshot().rows.filter(source => ids.has(source.row.id)).map(source => source.row));
702
758
  }
703
759
  const result = applying ? applyPrune(port, input, auth) : plan;
704
- 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));
705
761
  } finally { store.close(); }
706
762
  }
707
763
  if (sub === "decay") {
708
764
  const applying = options["--apply"] === true && options["--confirm"] === true;
709
765
  if (options["--confirm"] === true && options["--apply"] !== true) throw new Error("decay --confirm requires --apply");
710
- const { decayPreview, applyDecay, readDecayCounters, DECAY_DEFAULT_DAYS, assertExactDecayForget } = await import("./memory/decay-review.ts");
766
+ const { decayPreview, applyDecay, readDecayCounters, DECAY_DEFAULT_DAYS, assertExactDecayForget, unusedInjectionTargets } = await import("./memory/decay-review.ts");
711
767
  const project = boundProject(), base = memoryHome(), aliases = aliasedKeys(base, project);
712
768
  const store = curatedStore(project, { deferPromotions: true, screen: note => policyOf().screenStandalone(note) ? "promote" : "keep" });
713
769
  try {
714
770
  const assertCurrent = commandBinding(store.profile.home, project);
771
+ if (options["--propose"] === true) {
772
+ if (options["--apply"] || options["--confirm"] || options["--forget"] || options["--days"] || parsed.positionals.length) throw Error("decay --propose cannot be combined with apply, age or ids; run it alone to queue candidates");
773
+ const { readReviewSnapshot, REVIEW_DEFAULTS } = await import("./memory/review-targets.ts");
774
+ const settings = loadAmemConfig(base, repoConfigRoot(policyCwd)).config.review;
775
+ const candidates = new CandidateStore({ memoryDir: base, reconcile: { canonical: project, aliases } });
776
+ try {
777
+ const targets = unusedInjectionTargets(store, project, readReviewSnapshot(base, [project, ...aliases]), { now: store.readNow(), days: settings?.unused_days ?? REVIEW_DEFAULTS.unused_days, threshold: settings?.unused_rendered ?? REVIEW_DEFAULTS.unused_rendered, aliases, screen: view => policyOf().screenStandalone(view), exclude: target => candidates.get(candidateInputId({ project, kind: "decay", target, reason: UNUSED_INJECTION_REASON }), project) !== undefined });
778
+ assertCurrent();
779
+ for (const entry of targets) candidates.put({ project, kind: "decay", target: entry.target, reason: UNUSED_INJECTION_REASON }, "public");
780
+ const receipt = { unusedInjection: targets.length };
781
+ return options["--json"] ? JSON.stringify(receipt) : `queued ${targets.length} unused-injection decay candidates; review with amem review list`;
782
+ } finally { candidates.close(); }
783
+ }
715
784
  const selected = parsed.positionals.length ? parsed.positionals : undefined;
716
785
  if (options["--days"] !== undefined && !/^[1-9][0-9]*$/.test(String(options["--days"]))) throw new Error("decay days must be a positive decimal integer");
717
786
  const days = options["--days"] === undefined ? DECAY_DEFAULT_DAYS : Number(options["--days"]);
@@ -756,6 +825,24 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
756
825
  } finally { store.close(); }
757
826
  }
758
827
  if (review) {
828
+ if (sub === "targets") {
829
+ const { reviewTargets, readReviewSnapshot, reviewUse, noRecentReview, REVIEW_DEFAULTS } = await import("./memory/review-targets.ts");
830
+ const base = memoryHome(), bound = boundProject(), project = options["--project"] === undefined ? bound : resolveAlias(base, String(options["--project"]));
831
+ if (project !== bound) throw Error("review targets can screen only the current project's policy; run it from that project's checkout");
832
+ const rawLimit = options["--limit"] === undefined ? "50" : String(options["--limit"]);
833
+ if (!/^[1-9][0-9]*$/.test(rawLimit) || Number(rawLimit) > 500) throw Error("review targets --limit must be from 1 to 500; pass a limit in that range");
834
+ const aliases = aliasedKeys(base, project), snapshot = readReviewSnapshot(base, [project, ...aliases]);
835
+ const store = openCuratedForRead(base, project);
836
+ if (!store) return options["--json"] ? "[]" : "no review targets";
837
+ try {
838
+ const policy = policyOf(), root = boundRepoRoot(policyCwd, base, project), stale = createRecallStalenessProbe({ cwd: root ?? policyCwd, rootConfirmed: root !== undefined, policy: () => policy });
839
+ const settings = loadAmemConfig(base, repoConfigRoot(policyCwd)).config.review;
840
+ const rows = store.withDeferredPromotions(() => store.list({ project, limit: 5000 })).filter(row => actor !== "agent" || policy.screenStandalone(row));
841
+ const result = reviewTargets(rows, { now: store.readNow(), recheckDays: settings?.recheck_days ?? REVIEW_DEFAULTS.recheck_days, limit: Number(rawLimit), stale,
842
+ use: row => reviewUse(snapshot, [project, ...aliases], row.id), eligibleForRecheck: (row, cutoff) => noRecentReview(snapshot, row.id, cutoff) });
843
+ return options["--json"] ? JSON.stringify(result, null, 2) : result.length ? result.map(row => `${row.id} ${row.reason} ${row.ageDays}d rendered ${row.counts.rendered ?? "unknown"} delivered ${row.counts.delivered ?? "unknown"} cited ${row.counts.cited ?? "unknown"}`).join("\n") : "no review targets";
844
+ } finally { store.close(); }
845
+ }
759
846
  const id = parsed.positionals[0];
760
847
  if (sub !== "list" && sub !== "walk" && (!id || !/^[a-f0-9]{64}$/.test(id))) throw new Error(`review ${sub} requires a full 64-character candidate id`);
761
848
  if (sub === "walk" && !(context.stdinTTY ?? process.stdin.isTTY)) throw Error("review walk requires a terminal on stdin; stdout must be a terminal too");
@@ -824,7 +911,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
824
911
  const candidate = candidates.get(id!, project);
825
912
  if (!candidate || !candidatePermitted(candidate)) throw new Error("candidate unavailable");
826
913
  if (candidate.status !== "pending") throw new Error(`candidate is ${candidate.status}, not pending`);
827
- if (decision === "accept" && candidate.input.kind === "decay") throw new Error("decay candidates are listing-only; use `amem demote` or `amem forget` after review");
914
+ if (decision === "accept" && candidate.input.kind === "decay" && candidate.input.reason !== UNUSED_INJECTION_REASON) throw new Error("decay candidates are listing-only unless proposed for unused injection; use amem decay to review current eligibility");
828
915
  if (decision === "accept" && candidate.input.kind === "model-answer") throw new Error("model answers cannot be accepted; author an independent note with amem note add");
829
916
  if (options["--confirm"] !== true) {
830
917
  const shown = terminalSafe(body(candidate)), overlaps = await overlapsFor(candidate);
@@ -919,7 +1006,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
919
1006
  const candidate = candidates.get(id!, project);
920
1007
  if (!candidate) throw new Error("candidate unavailable");
921
1008
  if (options["--kind"] !== undefined && candidate.input.kind !== options["--kind"]) throw new Error("candidate kind does not match --kind");
922
- if (candidate.input.kind === "decay") throw new Error("decay candidates are listing-only; use `amem demote` or `amem forget` after review");
1009
+ if (candidate.input.kind === "decay" && candidate.input.reason !== UNUSED_INJECTION_REASON) throw new Error("decay candidates are listing-only unless proposed for unused injection; use amem decay to review current eligibility");
923
1010
  const store = curatedStore(project, { deferPromotions: true, screen: note => policyOf().screenStandalone(note) ? "promote" : "keep" });
924
1011
  try {
925
1012
  const assertCurrent = commandBinding(store.profile.home, project);
@@ -931,6 +1018,12 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
931
1018
  // #368: a Record candidate quotes capture rows, so acceptance point-reads exactly those turns of its shard,
932
1019
  // rather than the brief window a candidate can outlive.
933
1020
  recordSource: recordSourceCheck(recordCaptureLookup(realPath(store.profile.home), policyCwd)),
1021
+ unusedEligible: view => {
1022
+ const { readReviewSnapshot, REVIEW_DEFAULTS } = require("./memory/review-targets.ts") as typeof import("./memory/review-targets.ts");
1023
+ const { unusedInjectionTargets } = require("./memory/decay-review.ts") as typeof import("./memory/decay-review.ts");
1024
+ const settings = loadAmemConfig(store.profile.home, repoConfigRoot(policyCwd)).config.review;
1025
+ return unusedInjectionTargets(store, project, readReviewSnapshot(store.profile.home, [project, ...aliases]), { now: store.readNow(), days: settings?.unused_days ?? REVIEW_DEFAULTS.unused_days, threshold: settings?.unused_rendered ?? REVIEW_DEFAULTS.unused_rendered, aliases, id: view.id, screen: row => policyOf().screenStandalone(row) }).some(entry => entry.target.id === view.id);
1026
+ },
934
1027
  });
935
1028
  return options["--json"] ? JSON.stringify(result, null, 2) : `accepted candidate ${id} as ${candidate.input.kind === "promotion" ? "promoted" : "ordinary"} note ${result.noteId}`;
936
1029
  } finally { store.close(); }
@@ -939,17 +1032,51 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
939
1032
  if (sub === "vault-candidates" && (options["--all-projects"] === true || options["--project"] !== undefined)) {
940
1033
  if (options["--all-projects"] === true && options["--project"] !== undefined) throw new Error("choose either --all-projects or --project <key>, not both");
941
1034
  const result = await vaultCandidatesAll(memoryHome(), { policy: policyOf(), ...(options["--project"] !== undefined ? { project: resolveAlias(memoryHome(), String(options["--project"])) } : {}), ...(options["--limit"] ? { limit: Number(options["--limit"]) } : {}) });
942
- 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));
943
1036
  }
944
1037
  if (sub === "vault-candidates") {
945
1038
  const project = boundProject(), store = curatedStore(project, { deferPromotions: true });
946
1039
  try {
947
1040
  const result = await vaultCandidates(store, { project, policy: policyOf(), ...(options["--limit"] ? { limit: Number(options["--limit"]) } : {}) });
948
- 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));
949
1042
  } finally { store.close(); }
950
1043
  }
951
1044
  if (sub === "eval") {
952
1045
  // F13: read-only. A set with entries is scored against a throwaway store seeded with them (touches no memory home); one without scores the bound project's real entries.
1046
+ if (parsed.path[1] === "audit") {
1047
+ // #326: a private local sheet plus a content-free score. Judging happens outside amem, so nothing on this path calls a model or the network.
1048
+ const audit = await import("./memory/eval-audit.ts"), { MAX_AUDIT_NOTES } = await import("./memory/eval.ts");
1049
+ if (parsed.path[2] === "sample") {
1050
+ const n = options["--n"] === undefined ? 40 : Number(options["--n"]), seed = typeof options["--seed"] === "string" ? options["--seed"] : "";
1051
+ if (!Number.isInteger(n) || n < 1 || n > MAX_AUDIT_NOTES) throw new Error(`--n must be an integer from 1 to ${MAX_AUDIT_NOTES}`);
1052
+ if (!/^[A-Za-z0-9._-]{1,64}$/.test(seed)) throw new Error("--seed is required: 1 to 64 letters, digits, '.', '_' or '-', so the same seed and store draw the same sample");
1053
+ // Anchors are checked against this cwd's work tree, so another project's key would silently check them against the wrong repository: the audit only
1054
+ // samples the project bound here or one of its aliases, and names the checkout to run it from.
1055
+ const cwd = context.cwd ?? process.cwd(), home = memoryHome(), bound = boundProject();
1056
+ const project = options["--project"] === undefined ? bound : resolveAlias(home, String(options["--project"]));
1057
+ if (project !== bound && !aliasedKeys(home, bound).includes(project)) throw new Error(`the audit checks note anchors against the git work tree of ${cwd}, so it samples only the project bound there (${bound}); run \`amem eval audit sample\` from that project's checkout to audit that project`);
1058
+ const root = audit.auditRoot(cwd);
1059
+ // The age buckets the draw stratifies by are measured at one explicit instant, recorded in the sheet: the same seed, store and as-of draw the same sample.
1060
+ const asOf = options["--as-of"] === undefined ? Date.now() : audit.auditAsOf(String(options["--as-of"]), Date.now());
1061
+ const store = curatedStore(project, { deferPromotions: true });
1062
+ let sheet;
1063
+ // The configured policy screens each frame member before the sheet's first write, for a person and an agent-marked session alike (like `project export`).
1064
+ // It screens the complete view, not the fields the sheet copies: a denied pattern in `task`, `peer` or `source` is a denial of that note.
1065
+ // It is read once: the screen runs per frame member, and the policy reads the config files when it is built.
1066
+ const screen = policyOf();
1067
+ try { sheet = audit.auditSample({ store, project, n, seed, root, asOf, screen: view => screen.screenStandalone(view) }); } finally { store.close(); }
1068
+ const out = typeof options["--out"] === "string" ? options["--out"] : join(memoryHome(), "eval", `audit-${project.replace(/[^A-Za-z0-9._-]+/g, "-").slice(0, 80)}-${seed}.json`);
1069
+ const file = audit.writeAuditSheet(out, sheet);
1070
+ return options["--json"] === true ? JSON.stringify({ file, project: sheet.project, seed: sheet.seed, asOf: sheet.asOf, frame: sheet.frame, drawn: sheet.drawn, truncated: sheet.truncated, withheld: sheet.withheld }, null, 2) : audit.auditSheetText(sheet, file);
1071
+ }
1072
+ if (parsed.path[2] === "score") {
1073
+ const [sheet] = parsed.positionals;
1074
+ if (!sheet) throw new Error("usage: amem eval audit score <sheet> (the file `amem eval audit sample` wrote)");
1075
+ const score = audit.auditScore(audit.readAuditSheet(sheet));
1076
+ return options["--json"] === true ? JSON.stringify(score, null, 2) : audit.auditScoreText(score);
1077
+ }
1078
+ throw new Error("usage: amem eval audit sample --seed <s> [--n <n>] [--project <key>] | amem eval audit score <sheet>");
1079
+ }
953
1080
  const ks = parseKs(typeof options["--k"] === "string" ? options["--k"] : undefined);
954
1081
  const file = typeof options["--set"] === "string" ? options["--set"] : undefined;
955
1082
  const builtin = file === undefined ? undefined : builtinSet(file);
@@ -990,7 +1117,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
990
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");
991
1118
  const diskShare = share !== undefined ? { diskShare: Number(share) } : {};
992
1119
  const result = options["--confirm"] === true ? applySplit(memoryHome(), diskShare) : previewSplit(memoryHome(), diskShare);
993
- 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));
994
1121
  }
995
1122
  // Preview first; --confirm writes the bound home default config.
996
1123
  const file = join(memoryHome(), "capture-config.json");
@@ -1004,7 +1131,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1004
1131
  if (options["--confirm"] !== true) {
1005
1132
  writeFileSync(previewFile, JSON.stringify(preview) + "\n", { mode: 0o600 });
1006
1133
  const result = { preview, confirm: "re-run with --confirm to write" };
1007
- 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));
1008
1135
  }
1009
1136
  let approved: { file?: string; current?: unknown; target?: CaptureConfig };
1010
1137
  try { approved = JSON.parse(readFileSync(previewFile, "utf8")) as typeof approved; }
@@ -1016,7 +1143,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1016
1143
  const written = writeCaptureConfigFile(file, target);
1017
1144
  rmSync(previewFile, { force: true });
1018
1145
  const result = { preview, written: { cap_mb: written.capMb, retention_days: written.retentionDays } };
1019
- 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));
1020
1147
  }
1021
1148
  if (sub === "projects") {
1022
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.
@@ -1312,7 +1439,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1312
1439
  } catch (error) {
1313
1440
  if (sub === "sync") progress?.finish(stop?.cause() ? "cancelled" : "failed", stop?.cause() ? "cancelled" : "unavailable");
1314
1441
  if (sub === "sync") stampSync((error as Error).message, stop?.cause());
1315
- 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);
1316
1443
  throw error;
1317
1444
  }
1318
1445
  finally {
@@ -1340,7 +1467,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1340
1467
  const work = await importClaudeMemWorkState({ base: memoryHome(), project: boundProject(), policy: row => policy.screen(row), ...db, ...limit, restart });
1341
1468
  const capture = captureDays === undefined ? undefined : await importClaudeMemCapture({ base: memoryHome(), project: boundProject(), cwd, days: captureDays, ...db, ...limit, restart, policy: { host: policy } });
1342
1469
  return options["--json"] ? JSON.stringify({ ...JSON.parse(output), work, ...(capture ? { capture } : {}) }, null, 2)
1343
- : claudeMemImportText(JSON.parse(output), work, capture, { captureDays, restart }, outputStyle(context));
1470
+ : claudeMemImportText(JSON.parse(output), work, capture, { captureDays, restart }, outputStyle(context, options));
1344
1471
  }
1345
1472
  return !options["--json"] && receipt.bridgeStatus
1346
1473
  ? `${output}\n(legacy malformed lines skipped: ${receipt.bridgeStatus.skippedRows})` : output;
@@ -1359,7 +1486,16 @@ async function placementProgress(home: string, mode: string, context: CliContext
1359
1486
  const live = new Set(parts.keys());
1360
1487
  return new SyncProgress({ sink: snapshot => { for (const index of live) try { parts[index]!(snapshot); } catch { live.delete(index); } } });
1361
1488
  }
1362
- 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
+ }
1363
1499
 
1364
1500
  /** Native ingest remains capture-only and agent-reachable; this formats only its returned receipt. */
1365
1501
  export function ingestText(kind: IngestKind, result: IngestReceipt, s: Style = PLAIN): string {
@@ -1386,7 +1522,11 @@ export function ingestText(kind: IngestKind, result: IngestReceipt, s: Style = P
1386
1522
  `Next action: ${action}`].join("\n");
1387
1523
  }
1388
1524
 
1389
- 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
+ }
1390
1530
 
1391
1531
  /** A completed write means rendered output, never evidence of host delivery or citation. */
1392
1532
  export async function writeCliOutput(text: string, output: Writable = process.stdout): Promise<void> { await writeConfirmed(output, text); }
@@ -1396,7 +1536,16 @@ export async function main(argv = process.argv.slice(2)): Promise<void> {
1396
1536
  const receipts: CliOutputReceipt[] = [], output = await runCli(argv, { onOutputReady: receipt => receipts.push(receipt), onPersonStop: name => { personStop ??= name; } });
1397
1537
  if (output) { await writeCliOutput(output + "\n"); for (const receipt of receipts) { try { receipt.rendered(); } catch { /* telemetry stays optional */ } } }
1398
1538
  } catch (error) {
1399
- 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;
1400
1549
  }
1401
1550
  if (personStop !== undefined) endLikeSignal(personStop); // after the report, with amem's own handlers already removed
1402
1551
  }