@staix/agent-mem 0.37.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +1 -1
  3. package/package.json +1 -1
  4. package/src/brief-curated.ts +8 -4
  5. package/src/cli-agent-reads.ts +55 -4
  6. package/src/cli.ts +222 -93
  7. package/src/commands-table.ts +332 -171
  8. package/src/index.ts +5 -0
  9. package/src/memory/capacity-text.ts +100 -0
  10. package/src/memory/capacity.ts +1 -57
  11. package/src/memory/commands.ts +45 -9
  12. package/src/memory/curated-cache-state.ts +22 -3
  13. package/src/memory/doctor-text.ts +144 -0
  14. package/src/memory/doctor.ts +9 -86
  15. package/src/memory/eval-audit-text.ts +62 -0
  16. package/src/memory/eval-audit.ts +1 -34
  17. package/src/memory/eval-text.ts +32 -0
  18. package/src/memory/eval.ts +1 -14
  19. package/src/memory/formats.ts +2 -0
  20. package/src/memory/gc-text.ts +22 -0
  21. package/src/memory/gc.ts +0 -6
  22. package/src/memory/generation-index.ts +1 -1
  23. package/src/memory/index-file.ts +1 -1
  24. package/src/memory/metrics.ts +18 -10
  25. package/src/memory/migrate-text.ts +32 -0
  26. package/src/memory/migrate.ts +0 -29
  27. package/src/memory/prune-text.ts +29 -0
  28. package/src/memory/prune.ts +0 -26
  29. package/src/memory/report-text.ts +233 -0
  30. package/src/memory/shard-migration-text.ts +40 -0
  31. package/src/memory/shard-migration.ts +0 -37
  32. package/src/memory/status-text.ts +72 -29
  33. package/src/memory/store.ts +112 -17
  34. package/src/memory/style.ts +98 -1
  35. package/src/memory/sync-placement-bound.ts +2 -2
  36. package/src/memory/sync-placement-checkpoint-person.ts +1 -1
  37. package/src/memory/sync-placement-noop-cache.ts +93 -0
  38. package/src/memory/sync-placement-refusal-category.ts +18 -0
  39. package/src/memory/sync-placement-transport.ts +43 -7
  40. package/src/memory/sync-progress-text.ts +7 -0
  41. package/src/memory/sync-progress.ts +21 -7
  42. package/src/memory/sync-screen.ts +13 -0
  43. package/src/memory/work-lists.ts +6 -4
  44. package/src/setup-drift.ts +1 -1
  45. package/src/setup-writer-roots.ts +136 -0
  46. package/src/setup.ts +122 -159
  47. package/src/sync-placement-writer-context.ts +8 -3
  48. package/src/ui/plugin.ts +4 -2
  49. package/src/work-brief-preparation.ts +28 -0
package/src/cli.ts CHANGED
@@ -9,6 +9,7 @@ import { cliAttribution, withCliAttribution } from "./memory/cli-attribution.ts"
9
9
  import { createHash, randomUUID } from "node:crypto";
10
10
  import type { Writable } from "node:stream";
11
11
  import { buildIntentBrief } from "./memory/intent-brief.ts";
12
+ import { prepareWorkBriefCache } from "./work-brief-preparation.ts";
12
13
  import { proposeConsolidation } from "./memory/consolidate.ts";
13
14
  import { recordCaptureLookup, recordSourceCheck, recordWindow } from "./memory/record-candidates.ts";
14
15
  import { createIntentBriefSource, recallViewIsLive } from "./memory/recall.ts";
@@ -21,6 +22,7 @@ import { PLACEMENT_CHECKPOINT_PENDING_MESSAGE } from "./memory/sync-placement-jo
21
22
  import { MCP_TOOLS, serveMcp, writeConfirmed } from "./mcp.ts";
22
23
  import { createStandalonePolicy } from "./memory/policy.ts";
23
24
  import { configuredPolicy, configuredPolicyOptions, loadAmemConfig, repoConfigRoot } from "./memory/config.ts";
25
+ import { deterministicRowScreen } from "./memory/sync-screen.ts";
24
26
  import { vaultCandidates, vaultCandidatesText, vaultCandidatesAllText } from "./memory/vault.ts";
25
27
  import type { IngestKind, IngestReceipt } from "./ingest.ts";
26
28
  import { importClaudeMemCapture, importClaudeMemWorkState } from "./memory/import.ts";
@@ -30,47 +32,57 @@ import { fileURLToPath } from "node:url";
30
32
  import { captureSessionKey } from "./memory/capture-input.ts";
31
33
  import { originLine, originRecheck } from "./memory/candidate-origin.ts";
32
34
  import { MemoryStore, looksSecret, machineId, openShardStore, type StoreOptions } from "./memory/store.ts";
35
+ import { CLI_MEMORY_RENDER } from "./memory/style.ts";
33
36
  import { rawMemoryCommand, rawGoalCommand, claudeMemImportText } from "./memory/commands.ts";
34
37
  import { memoryProjectKey } from "./memory/project.ts";
35
38
  import { CandidateStore, candidateInputId, candidateTargetRevision, type CandidateFilter } from "./memory/candidates.ts";
36
39
  import { candidateOverlaps, candidateOverlapsBatch } from "./memory/candidate-overlaps.ts";
37
40
  import { openCuratedForRead } from "./memory/curated-read.ts";
38
41
  import { aliasedKeys, appendAlias, appendUnalias, listAliases, readShardedSelection, resolveAlias } from "./memory/shard.ts";
39
- import { capacityReport, capacityText, capacityApplyText, capacitySplitText } from "./memory/capacity.ts";
42
+ import { capacityReport } from "./memory/capacity.ts";
43
+ import { capacityText, capacityApplyText, capacitySplitText } from "./memory/capacity-text.ts";
40
44
  import { CaptureStore, readCaptureConfigFile, writeCaptureConfigFile, type CaptureConfig } from "./memory/capture.ts";
41
45
 
42
- import { COMMANDS, commandHelp, parseCommand } from "./commands-table.ts";
46
+ import { COMMANDS, CommandUsageError, commandHelp, commandPath, parseCommand, usageLine } from "./commands-table.ts";
43
47
  import { completionScript } from "./completion.ts";
44
48
  import { memoryHome, resolveMemoryHome } from "./memory/home.ts";
45
49
  import { realPath } from "./memory/platform.ts";
46
50
  import { RemoteRealmRefusal } from "./memory/sync-placement-remote-refusal.ts";
51
+ import { placementSyncBoundMessage, placementSyncBoundReceipt } from "./memory/sync-placement-bound.ts";
47
52
  import { hashJSON, readSelector, resolveProfile } from "./memory/generation.ts";
48
- import { migrate, migrationText } from "./memory/migrate.ts";
49
- import { migrateShards, shardMigrationStatus, shardMigrationText } from "./memory/shard-migration.ts";
50
- import { applyPrune, planPrune, pruneText, PRUNE_PLAN_MAX_BYTES } from "./memory/prune.ts";
53
+ import { migrate } from "./memory/migrate.ts";
54
+ import { migrationText } from "./memory/migrate-text.ts";
55
+ import { migrateShards, shardMigrationStatus } from "./memory/shard-migration.ts";
56
+ import { shardMigrationText } from "./memory/shard-migration-text.ts";
57
+ import { applyPrune, planPrune, PRUNE_PLAN_MAX_BYTES } from "./memory/prune.ts";
58
+ import { pruneText } from "./memory/prune-text.ts";
51
59
  import { readCatalogFresh } from "./memory/catalog.ts";
52
60
  import { appendLifecycle, assertProjectActive, projectState } from "./memory/lifecycle.ts";
53
- import { gcText, runGc } from "./memory/gc.ts";
61
+ import { runGc } from "./memory/gc.ts";
62
+ import { gcText } from "./memory/gc-text.ts";
54
63
  import { usageReport, usageText } from "./memory/usage.ts";
64
+ import * as reports from "./memory/report-text.ts";
55
65
  import { exportProject, type ProjectExportFormat } from "./memory/project-export.ts";
56
66
  import { importProject } from "./memory/project-import.ts";
57
67
  import { importExternalMemory, type ExternalMemorySource } from "./memory/external-import.ts";
58
68
  import { forgetNearby } from "./memory/forget-nearby.ts";
59
69
  import { searchAllProjects, vaultCandidatesAll } from "./memory/cross-project.ts";
60
70
  import { requireShard } from "./memory/curated-read.ts";
61
- import { appendGitattributes, appendRepoLine, boundRepoRoot, planGitattributes, planRepoPromotion, readRepoScope, repoLogIgnored, repoLogPath, repoReadPolicy, repoVisibility, type RepoView } from "./memory/repo-scope.ts";
71
+ import { appendGitattributes, appendRepoLine, boundRepoRoot, planGitattributes, planRepoPromotion, readRepoScope, repoLogIgnored, repoLogPath, repoReadPolicy, repoVisibility } from "./memory/repo-scope.ts";
62
72
  import type { Visibility } from "./memory/sync.ts";
63
73
  import { applySplit, previewSplit } from "./memory/capacity-split.ts";
64
- import { evalText, parseKs } from "./memory/eval.ts";
74
+ import { parseKs } from "./memory/eval.ts";
75
+ import { evalText } from "./memory/eval-text.ts";
65
76
  import { unrankedScoreDetails } from "./memory/search-score.ts";
66
77
  import { builtinSet, evalSeeded, evalStore, FIXTURE_PATH, readEvalSet } from "./memory/eval-fixture.ts";
67
78
  import { markShown, pendingSummary } from "./memory/candidate-pending.ts";
68
79
  import { buildNote, FAIL_TEMPLATE, hasFailLabel, noteAdd, parseFailTemplate, type FailFields } from "./memory/note-add.ts";
69
80
  import { runEditor } from "./memory/editor.ts";
70
- import { doctorReport, doctorText } from "./memory/doctor.ts";
81
+ import { doctorReport } from "./memory/doctor.ts";
82
+ import { doctorText } from "./memory/doctor-text.ts";
71
83
  import { statusText, type StatusView } from "./memory/status-text.ts";
72
- import { asciiMarkers, errorLine, errorSpans, EXIT, markerCell, paint, resolveColor, streamEnv } from "@staix/cli-output";
73
- import { style, wrapReport, facts, label, PLAIN, type Style } from "./memory/style.ts";
84
+ import { asciiMarkers, errorLine, errorSpans, EXIT, markerCell, paint, Report, resolveColor, streamEnv } from "@staix/cli-output";
85
+ import { style, facts, label, memoryRecordText, memoryScoresText, memoryTableText, PLAIN, singleLine, wordedKey, type Style } from "./memory/style.ts";
74
86
  import { endLikeSignal, nextSyncAt, readSyncState, recordSyncAttempt, remoteConfigured, syncDue, stopSignal, syncOutcome, usableState, SYNC_IF_DUE_DEADLINE_MS, type StopCause } from "./memory/sync-cadence.ts";
75
87
 
76
88
  const VERSION = (JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version: string }).version;
@@ -313,6 +325,18 @@ class ReadPolicyWithheld extends Error {
313
325
  constructor() { super("Memory read withheld [cause: policy_withheld]; no partial result is shown. Ask the person to check the configured policy."); }
314
326
  }
315
327
 
328
+ /** Human-only receipts; host handlers and every JSON response retain their existing bytes. */
329
+ function receiptText(output: string, parsed: ReturnType<typeof parseCommand>, context: CliContext): string {
330
+ const command = parsed.path.join(" ");
331
+ const receipts = new Set(["note", "note add", "confirm", "reject", "promote", "demote", "forget", "supersede", "rebuild", "dedupe", "consolidate", "review accept", "review reject", "review decide", "project export", "project import", "project archive", "project unarchive", "project forget", "alias add", "alias remove", "goal new", "goal state", "goal done", "goal take", "import claude-mem", "import claude-auto", "import codex", "repo attributes"]);
332
+ if (!receipts.has(command) || !output || command === "import claude-mem" || output === "Operation completed; receipt withheld by policy. Run amem status to inspect state." || output === "Operation did not complete; receipt withheld by policy. Inspect state before retrying." || command === "promote" && parsed.options["--to"] === "repo") return output;
333
+ const preview = /^preview\b/i.test(output) || command === "review decide" && parsed.options["--confirm"] !== true || command === "dedupe" && parsed.options["--apply"] !== true;
334
+ const s = outputStyle(context, parsed.options), lines = (command === "alias add" && !s.ascii ? output.replace(" -> ", " → ") : output).split("\n"), out = new Report(reportWidth(context) ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
335
+ out.bullet(preview ? "pending" : "ok", lines[0]!);
336
+ for (const line of lines.slice(1)) if (line.trim()) out.note(line);
337
+ return out.render(s.color).join("\n");
338
+ }
339
+
316
340
  /** #326: a marked score read the policy refuses names its cause class and where to check it, never the matched value. */
317
341
  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.";
318
342
 
@@ -357,7 +381,7 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
357
381
  // The command returned successfully: withholding its receipt cannot undo its effects.
358
382
  const failed = receipt !== null && typeof receipt === "object" && "ok" in receipt && receipt.ok === false;
359
383
  return parsed.options["--json"] === true ? JSON.stringify({ ok: !failed, completed: !failed, receiptWithheld: true })
360
- : failed ? "Operation did not complete; receipt withheld by policy. Inspect state before retrying." : "Operation completed; receipt withheld by policy.";
384
+ : failed ? "Operation did not complete; receipt withheld by policy. Inspect state before retrying." : "Operation completed; receipt withheld by policy. Run amem status to inspect state.";
361
385
  }
362
386
  }
363
387
  }
@@ -371,7 +395,8 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
371
395
  const safe = new DecayApplyError(error.report, undefined); safe.jsonOutput = error.jsonOutput; throw safe;
372
396
  }
373
397
  // Data-free errors (decided before any store or file is opened) keep their own message.
374
- if (marked && (error instanceof AgentUsageError || error instanceof AgentReadFailure || error instanceof AgentReadAmbiguous)) throw error;
398
+ // #590 H7: a CommandUsageError is decided from argv words before any store access, so it stays a usage error.
399
+ if (marked && (error instanceof AgentUsageError || error instanceof CommandUsageError || error instanceof AgentReadFailure || error instanceof AgentReadAmbiguous)) throw error;
375
400
  if (marked && error instanceof RemoteRealmRefusal) throw error;
376
401
  // The checkpoint pending message is a fixed data-free remedy shared by journal and writer guards.
377
402
  if (marked && error instanceof Error && error.message === PLACEMENT_CHECKPOINT_PENDING_MESSAGE) throw new Error(PLACEMENT_CHECKPOINT_PENDING_MESSAGE);
@@ -394,6 +419,10 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
394
419
  let usage: Error | undefined, parsed: ReturnType<typeof parseCommand> | undefined;
395
420
  try { parsed = parseCommand(argv); } catch (parseError) { usage = parseError as Error; }
396
421
  if (usage) throw Object.assign(new Error(usage.message), (error as { exitCode?: number }).exitCode === undefined ? {} : { exitCode: (error as { exitCode?: number }).exitCode });
422
+ if (parsed?.path[0] === "sync") {
423
+ const bound = placementSyncBoundReceipt(error);
424
+ if (bound) throw new Error(placementSyncBoundMessage(bound));
425
+ }
397
426
  const setupError = parsed && markedSetupApplyError(parsed, error);
398
427
  if (setupError) throw setupError;
399
428
  if (parsed && markedReadOnly(parsed)) {
@@ -409,8 +438,12 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
409
438
  // Preserve the value and the policy-screened result; only the JSON presentation changes.
410
439
  try {
411
440
  const parsed = parseCommand(argv);
441
+ if (parsed.options["--help"] === true || argv.includes("--help")) return output;
412
442
  if (parsed.options["--json"] === true) return JSON.stringify(JSON.parse(output), null, 2);
413
- if (parsed.path[0] === "status" || parsed.path[0] === "doctor") return wrapReport(output, reportWidth(context));
443
+ // #590: status and doctor wrap through the Report builder at the same width, so a continuation aligns under its value.
444
+ const rendered = receiptText(output, parsed, context);
445
+ if (marked && rendered !== output && !configuredPolicy(memoryHome(), context.cwd ?? process.cwd()).screenStandalone(rendered)) return "Operation completed; receipt withheld by policy. Run amem status to inspect state.";
446
+ return rendered;
414
447
  } catch { /* Help and non-JSON special commands keep their existing output. */ }
415
448
  return output;
416
449
  });
@@ -457,21 +490,28 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
457
490
  cwd: context.cwd ?? process.cwd(), base: memoryHome(context.env ?? process.env),
458
491
  ...(typeof parsed.options["--since"] === "string" ? { since: parsed.options["--since"] as string } : {}),
459
492
  });
460
- return parsed.options["--json"] === true ? JSON.stringify(result, null, 2) : ingestText(kind as IngestKind, result, outputStyle(context, parsed.options));
493
+ return parsed.options["--json"] === true ? JSON.stringify(result, null, 2) : ingestText(kind as IngestKind, result, outputStyle(context, parsed.options), reportWidth(context));
461
494
  }
462
495
  // Help and version carry no memory data.
463
496
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "version")) return `amem ${VERSION}`;
464
497
  if (argv.length === 1 && (argv[0] === "--help" || argv[0] === "help")) return commandHelp();
465
498
  if (argv[0] === "--version" || argv[0] === "version") return `amem ${VERSION}`;
466
- if (argv[0] === "help") return commandHelp(argv.slice(1));
499
+ if (argv[0] === "help") {
500
+ // #590 H7: `help <unknown>` is a usage error, not the overview.
501
+ const words = argv.slice(1).filter(word => !word.startsWith("-"));
502
+ if (words.length && commandPath(argv.slice(1)).length < words.length) throw new CommandUsageError(`unknown command ${words.join(" ")}`);
503
+ return commandHelp(argv.slice(1));
504
+ }
467
505
  if (argv[0] === "--help" || argv.includes("--help")) return commandHelp(argv);
468
506
  let parsed;
469
507
  try {
470
508
  parsed = parseCommand(argv);
509
+ // #590 H7: these groups do nothing bare (eval and capacity run their own report; spool and eval audit name their usage themselves).
510
+ if (["project", "skills", "formats", "note", "import"].includes(parsed.path.join(" "))) throw new CommandUsageError(`amem ${parsed.path.join(" ")} needs a command`);
471
511
  if (parsed.path[0] === "version") return `amem ${VERSION}`;
472
512
  if (parsed.path[0] === "manifest") return JSON.stringify(manifest(), null, parsed.options["--json"] === true ? undefined : 2);
473
513
  if (parsed.path[0] === "completion") {
474
- if (parsed.positionals.length !== 1) throw new Error("usage: amem completion zsh|bash|fish");
514
+ if (parsed.positionals.length !== 1) throw new CommandUsageError("usage: amem completion zsh|bash|fish");
475
515
  return completionScript(parsed.positionals[0]!);
476
516
  }
477
517
  } catch (error) {
@@ -509,7 +549,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
509
549
  throw new AgentUsageError("--writer-root, --abandon, --admit, --list-remote, --from-remote, --checkpoint and --plan apply only to --sync-placement; run amem migrate --sync-placement --dry-run to review the inventory.");
510
550
  }
511
551
  if (parsed.path[0] === "skills" && parsed.path[1] === "export") {
512
- if (parsed.positionals.length !== 1) throw new Error("usage: amem skills export <dir> [--json]");
552
+ if (parsed.positionals.length !== 1) throw new CommandUsageError("usage: amem skills export <dir> [--json]");
513
553
  const { exportSkills } = await import("./skills-install.ts");
514
554
  const destination = parsed.positionals[0]!;
515
555
  const report = exportSkills(destination.trim() ? resolve(context.cwd ?? process.cwd(), destination) : destination, { env: context.env ?? process.env });
@@ -519,7 +559,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
519
559
  }
520
560
  if (parsed.path[0] === "setup") {
521
561
  if (parsed.positionals.length !== 1 || options["--apply"] === true && options["--undo"] === true
522
- || options["--adopt-current"] === true && (options["--apply"] !== true || parsed.positionals[0] === "console")) throw new Error("usage: amem setup claude|codex|kimi|pi|qwen|jcode|opencode|gemini|agy|all|console [--root <abs path>] [--apply [--adopt-current]|--undo]");
562
+ || options["--adopt-current"] === true && (options["--apply"] !== true || parsed.positionals[0] === "console")) throw new CommandUsageError("usage: amem setup claude|codex|kimi|pi|qwen|jcode|opencode|gemini|agy|all|console [--root <abs path>] [--apply [--adopt-current]|--undo]");
523
563
  if (parsed.positionals[0] === "console") {
524
564
  const { consoleSetup, consoleSetupText } = await import("./setup-console.ts");
525
565
  const mode = options["--apply"] === true ? "apply" : options["--undo"] === true ? "undo" : "preview";
@@ -532,11 +572,11 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
532
572
  env: context.env ?? process.env, stdinTTY: context.stdinTTY ?? process.stdin.isTTY, cwd: context.cwd ?? process.cwd(),
533
573
  ...(typeof options["--root"] === "string" ? { root: options["--root"] } : {}),
534
574
  ...(options["--adopt-current"] === true ? { adoptCurrent: true } : {}),
535
- ...(context.setupConfirm ? { confirm: context.setupConfirm } : {}), json: options["--json"] === true, style: outputStyle(context, options),
575
+ ...(context.setupConfirm ? { confirm: context.setupConfirm } : {}), json: options["--json"] === true, style: outputStyle(context, options), columns: reportWidth(context), verbose: options["--verbose"] === true,
536
576
  });
537
577
  }
538
578
  if (identity.actor === "agent") {
539
- const read = await agentCliRead(parsed, argv, context);
579
+ const read = await agentCliRead(parsed, argv, { ...context, columns: reportWidth(context) ?? 80, style: options["--json"] === true ? PLAIN : outputStyle(context, options) });
540
580
  if (read !== undefined) return read;
541
581
  }
542
582
  const goal = parsed.path[0] === "goal", review = parsed.path[0] === "review", sub = goal || review ? parsed.path[1]! : parsed.path[0]!;
@@ -548,6 +588,15 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
548
588
  const policyCwd = context.cwd ?? process.cwd();
549
589
  const policyOf = () => configuredPolicy(memoryHome(), policyCwd); // the same home every other command here resolves
550
590
  const administrative = <T>(value: T): T => { assertAgentAdministrative(value, policyOf()); return value; };
591
+ // Reformat only after the prior human receipt passes the same whole-output screen.
592
+ const screenedLegacy = (legacy: string, formatted: string): string => actor === "agent" && !policyOf().screenStandalone(legacy) ? legacy : formatted;
593
+ // #590 task 429: a mutating command's receipt in a marked session; a denial of either text keeps the existing withheld-receipt line.
594
+ const screenedReceipt = (legacy: string, formatted: string): string =>
595
+ actor === "agent" && (!policyOf().screenStandalone(legacy) || !policyOf().screenStandalone(formatted)) ? "Operation completed; receipt withheld by policy. Run amem status to inspect state." : formatted;
596
+ const screenedReadPair = (legacy: string, formatted: string): string => {
597
+ if (actor === "agent" && (!policyOf().screenStandalone(legacy) || !policyOf().screenStandalone(formatted))) throw new ReadPolicyWithheld();
598
+ return formatted;
599
+ };
551
600
  let canonicalProject: string | undefined;
552
601
  const boundProject = () => canonicalProject ??= resolveAlias(memoryHome(), memoryProjectKey(context.cwd ?? process.cwd()));
553
602
  const commandBinding = (home: string, project: string): (() => void) => {
@@ -592,7 +641,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
592
641
  } finally { candidates?.close(); store.close(); }
593
642
  }
594
643
  if (sub === "brief") {
595
- const intent = options["--for"]; if (typeof intent !== "string" || !intent.trim() || intent.length > 1000 || parsed.positionals.length) throw Error("usage: amem brief --for <intent> [--paths <path>] [--symbols <symbol>] [--bytes N] [--json]");
644
+ const intent = options["--for"]; if (typeof intent !== "string" || !intent.trim() || intent.length > 1000 || parsed.positionals.length) throw new CommandUsageError("usage: amem brief --for <intent> [--paths <path>] [--symbols <symbol>] [--bytes N] [--json]");
596
645
  const rawBytes = options["--bytes"];
597
646
  if (rawBytes !== undefined && !/^[1-9][0-9]*$/.test(String(rawBytes))) throw Error("brief bytes must be a positive decimal integer");
598
647
  const maxBytes = rawBytes === undefined ? 2048 : Number(rawBytes); if (!Number.isSafeInteger(maxBytes) || maxBytes > 8192) throw Error("brief bytes must be 1..8192");
@@ -605,6 +654,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
605
654
  const settings = () => configuredPolicyOptions(base, policyCwd), policyKey = () => hashJSON(settings()), revision = policyKey(), snapshot = createStandalonePolicy(settings());
606
655
  const policy = () => snapshot, policyVersion = () => policyKey();
607
656
  if (policyVersion() !== revision) throw Error("brief policy changed before read");
657
+ await prepareWorkBriefCache(base, project, policyCwd);
608
658
  const result = await buildIntentBrief(createIntentBriefSource(store, project),
609
659
  { project, cwd: root, repo: project, intent, paths, symbols, maxBytes, policy, policyVersion, assertCurrent, now: () => store.readNow(), stale: createRecallStalenessProbe({ cwd: root, rootConfirmed, policy }) });
610
660
  assertCurrent(); outputReady(result.items.map(view => view.id), project);
@@ -706,12 +756,12 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
706
756
  if (mode === "deactivate") throw new Error("--deactivate is not a shard migration mode");
707
757
  if (actor === "agent" && mode !== "dry-run") administrative(await migrateShards({ ...common, mode: "dry-run" }));
708
758
  const result = await migrateShards({ ...common, mode });
709
- return options["--json"] ? JSON.stringify(result, null, 2) : shardMigrationText(result, outputStyle(context, options));
759
+ return options["--json"] ? JSON.stringify(result, null, 2) : (mode === "dry-run" ? screenedReadPair : screenedReceipt)(shardMigrationText(result, outputStyle(context, options)), reports.shardMigrateReportText(result, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
710
760
  }
711
761
  if (actor === "agent" && mode === "deactivate") administrative({ target: common.memoryDir, selector: readSelector(common.memoryDir), mode });
712
762
  else if (actor === "agent" && mode !== "dry-run") administrative(await migrate({ ...common, mode: "dry-run" }));
713
763
  const result = await migrate({ ...common, mode });
714
- return options["--json"] ? JSON.stringify(result, null, 2) : migrationText(result, outputStyle(context, options));
764
+ return options["--json"] ? JSON.stringify(result, null, 2) : (mode === "dry-run" ? screenedReadPair : screenedReceipt)(migrationText(result, outputStyle(context, options)), reports.migrateReportText(result, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
715
765
  }
716
766
  if (sub === "status") {
717
767
  // 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.
@@ -726,13 +776,13 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
726
776
  if (summary === null) return { unavailable: "candidates.db exists but cannot be read" };
727
777
  return { ...summary, ...(summary.dueWithin7Days ? { warning: `${summary.dueWithin7Days} candidate${summary.dueWithin7Days === 1 ? "" : "s"} within 7 days of expiry: run \`amem review walk\`` } : {}) }; })(),
728
778
  ...shardMigrationStatus(where.home) };
729
- return options["--json"] ? JSON.stringify(status, null, 2) : statusText(status as unknown as StatusView, outputStyle(context, options));
779
+ return options["--json"] ? JSON.stringify(status, null, 2) : statusText(status as unknown as StatusView, outputStyle(context, options), reportOptions(context, options));
730
780
  }
731
781
  if (parsed.path[0] === "formats" && parsed.path[1] === "raise") {
732
782
  const { planFormatRaise, applyFormatRaise, formatRaiseRefusal, installVersion, runningAmemRoots } = await import("./memory/formats-raise.ts");
733
783
  const { readSetupWriterRoots } = await import("./setup.ts"), { readEffectiveSyncPlacementWriterRoots } = await import("./memory/sync-placement-effective-writers.ts");
734
784
  const [surface, minReader] = parsed.positionals;
735
- if (!surface || !minReader || parsed.positionals.length !== 2) throw new Error("usage: amem formats raise <surface> <min-reader> [--confirm] [--json]");
785
+ if (!surface || !minReader || parsed.positionals.length !== 2) throw new CommandUsageError("formats raise requires a surface and minimum reader version");
736
786
  const home = realPath(memoryHome()), own = realPath(fileURLToPath(new URL("..", import.meta.url)));
737
787
  const inventory = (): import("./memory/formats-raise.ts").FormatWriterInventory => {
738
788
  const writers: import("./memory/formats-raise.ts").FormatWriter[] = [], incomplete: string[] = [], seen = new Set<string>();
@@ -757,19 +807,29 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
757
807
  if (options["--confirm"] !== true) {
758
808
  const refusal = formatRaiseRefusal(plan);
759
809
  if (options["--json"] === true) return JSON.stringify({ ...plan, refusal: refusal ?? null }, null, 2);
760
- return [`preview: append ${JSON.stringify(plan.record)} to ${plan.file}`, `existing floors: ${plan.existing.length ? plan.existing.map(floor => `${floor.surface}>=${floor.minReader}`).join(", ") : "none"}`,
761
- `writers checked (${plan.writers.length}):`, ...plan.writers.map(writer => ` ${writer.source.padEnd(14)} ${writer.version ?? "unknown"} ${writer.root}${writer.pid ? ` (pid ${writer.pid}${writer.host ? `, ${writer.host}` : ""})` : ""}`),
762
- refusal ? `refused: ${refusal}` : `ready: rerun with --confirm to append the record`].join("\n");
810
+ const s = outputStyle(context, options), out = new Report(reportWidth(context) ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
811
+ out.header("amem", "Format floor"); out.section("Preview"); out.bullet("pending", "Review the proposed floor before confirming.");
812
+ out.kv([["Surface", plan.record.surface], ["Minimum reader", plan.record.minReader], ["Since", plan.record.since], ["File", plan.file], ["Existing", plan.existing.length ? plan.existing.map(floor => `${floor.surface} >= ${floor.minReader}`).join(", ") : "none"]]);
813
+ out.section("Writers", String(plan.writers.length));
814
+ if (plan.writers.length) out.table(["SOURCE", "VERSION", "INSTALL"], plan.writers.map(writer => [writer.source, writer.version ?? "?", `${writer.root}${writer.pid ? ` (pid ${writer.pid}${writer.host ? `, ${writer.host}` : ""})` : ""}`]), 2);
815
+ else out.note("No writers found.");
816
+ if (refusal) { out.section("Attention"); out.bullet("warn", refusal); }
817
+ else out.next(`amem formats raise ${surface} ${minReader} --confirm`);
818
+ const legacy = [`preview: append ${JSON.stringify(plan.record)} to ${plan.file}`, `existing floors: ${plan.existing.length ? plan.existing.map(floor => `${floor.surface}>=${floor.minReader}`).join(", ") : "none"}`, `writers checked (${plan.writers.length}):`, ...plan.writers.map(writer => ` ${writer.source.padEnd(14)} ${writer.version ?? "unknown"} ${writer.root}${writer.pid ? ` (pid ${writer.pid}${writer.host ? `, ${writer.host}` : ""})` : ""}`), refusal ? `refused: ${refusal}` : `ready: rerun with --confirm to append the record`].join("\n");
819
+ return screenedLegacy(legacy, out.render(s.color).join("\n"));
763
820
  }
764
821
  const record = applyFormatRaise(plan, () => planFormatRaise(home, surface, minReader, inventory(), now));
765
- return options["--json"] === true ? JSON.stringify({ appended: record, file: plan.file }, null, 2) : `appended ${JSON.stringify(record)} to ${plan.file}`;
822
+ if (options["--json"] === true) return JSON.stringify({ appended: record, file: plan.file }, null, 2);
823
+ const s = outputStyle(context, options), out = new Report(reportWidth(context) ?? 80, s.ascii, { sanitize: singleLine });
824
+ out.bullet("ok", `Appended ${record.surface} minimum reader ${record.minReader} to ${plan.file}.`);
825
+ return screenedLegacy(`appended ${JSON.stringify(record)} to ${plan.file}`, out.render(s.color).join("\n"));
766
826
  }
767
827
  if (sub === "doctor") {
768
828
  // F15: one read-only report; see src/memory/doctor.ts for exactly what "read-only" covers.
769
829
  const where = resolveMemoryHome(), project = boundProject();
770
830
  const report = await doctorReport({ home: where.home, homeSource: where.source, cwd: policyCwd, project, aliases: aliasedKeys(where.home, project), now: Date.now(),
771
831
  openCurated: base => curatedStoreAt(base, project, { deferPromotions: true }) });
772
- return options["--json"] ? JSON.stringify(report, null, 2) : doctorText(report, outputStyle(context, options));
832
+ return options["--json"] ? JSON.stringify(report, null, 2) : doctorText(report, outputStyle(context, options), reportOptions(context, options));
773
833
  }
774
834
  if (sub === "prune") {
775
835
  const applying = options["--apply"] === true;
@@ -798,7 +858,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
798
858
  administrative(port.snapshot().rows.filter(source => ids.has(source.row.id)).map(source => source.row));
799
859
  }
800
860
  const result = applying ? applyPrune(port, input, auth) : plan;
801
- return options["--json"] ? JSON.stringify(result, null, 2) : pruneText(result, outputStyle(context, options));
861
+ return options["--json"] ? JSON.stringify(result, null, 2) : (applying ? screenedReceipt : screenedReadPair)(pruneText(result, outputStyle(context, options)), reports.pruneReportText(result, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
802
862
  } finally { store.close(); }
803
863
  }
804
864
  if (sub === "decay") {
@@ -830,12 +890,12 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
830
890
  const preview = administrative(decayPreview(store, project, current)), action = options["--forget"] === true ? "FORGET" : "demote";
831
891
  const display = [`${action} preview: ${preview.entries.length} notes older than ${days} days; citation history unknown (${preview.citedExemptions ?? "unknown"} observed retained-positive exemptions)${preview.truncated ? "; truncated" : ""}`,
832
892
  ...preview.entries.map(entry => `${entry.target.id} revision ${entry.target.revision} ${entry.view.at} ${entry.view.kind}: ${terminalSafe(entry.view.title ?? entry.view.text)}`)].join("\n");
833
- if (!applying) return options["--json"] ? JSON.stringify(preview, null, 2) : display;
834
- if (!preview.entries.length) return options["--json"] ? JSON.stringify({ action, ids: [] }) : "no eligible notes to apply";
893
+ if (!applying) return options["--json"] ? JSON.stringify(preview, null, 2) : screenedReadPair(display, reports.decayReportText({ kind: "preview", plan: preview, action }, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
894
+ if (!preview.entries.length) return options["--json"] ? JSON.stringify({ action, ids: [] }) : screenedReadPair("no eligible notes to apply", reports.decayReportText({ kind: "empty" }, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
835
895
  if (options["--forget"] === true) assertExactDecayForget(store, preview.entries.map(entry => entry.target.id), project);
836
896
  assertCurrent();
837
897
  const result = applyDecay(store, preview, { ...current, actor, confirmed: true, forget: options["--forget"] === true });
838
- return options["--json"] ? JSON.stringify(result, null, 2) : `${result.action}: ${result.ids.length} entries${result.expiresAt ? `; expires ${result.expiresAt}` : ""}`;
898
+ return options["--json"] ? JSON.stringify(result, null, 2) : screenedReceipt(`${result.action}: ${result.ids.length} entries${result.expiresAt ? `; expires ${result.expiresAt}` : ""}`, reports.decayReportText({ kind: "applied", ...result }, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
839
899
  } catch (error) { if (error instanceof DecayApplyError) error.jsonOutput = options["--json"] === true; throw error; }
840
900
  finally { store.close(); }
841
901
  }
@@ -874,14 +934,25 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
874
934
  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");
875
935
  const aliases = aliasedKeys(base, project), snapshot = readReviewSnapshot(base, [project, ...aliases]);
876
936
  const store = openCuratedForRead(base, project);
877
- if (!store) return options["--json"] ? "[]" : "no review targets";
937
+ if (!store) {
938
+ if (options["--json"]) return "[]";
939
+ const s = outputStyle(context, options), out = new Report(reportWidth(context) ?? 80, s.ascii, { sanitize: singleLine });
940
+ out.header("amem", "Review targets"); out.section("Entries", "0"); out.line(" No review targets.");
941
+ return screenedLegacy("no review targets", out.render(s.color).join("\n"));
942
+ }
878
943
  try {
879
944
  const policy = policyOf(), root = boundRepoRoot(policyCwd, base, project), stale = createRecallStalenessProbe({ cwd: root ?? policyCwd, rootConfirmed: root !== undefined, policy: () => policy });
880
945
  const settings = loadAmemConfig(base, repoConfigRoot(policyCwd)).config.review;
881
946
  const rows = store.withDeferredPromotions(() => store.list({ project, limit: 5000 })).filter(row => actor !== "agent" || policy.screenStandalone(row));
882
947
  const result = reviewTargets(rows, { now: store.readNow(), recheckDays: settings?.recheck_days ?? REVIEW_DEFAULTS.recheck_days, limit: Number(rawLimit), stale,
883
948
  use: row => reviewUse(snapshot, [project, ...aliases], row.id), eligibleForRecheck: (row, cutoff) => noRecentReview(snapshot, row.id, cutoff) });
884
- 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";
949
+ if (options["--json"]) return JSON.stringify(result, null, 2);
950
+ const s = outputStyle(context, options), out = new Report(reportWidth(context) ?? 80, s.ascii, { sanitize: singleLine });
951
+ out.header("amem", "Review targets"); out.section("Entries", String(result.length));
952
+ if (result.length) { out.table(["ID", "REASON", "AGE", "RENDERED", "DELIVERED", "CITED"], result.map(row => [row.id.slice(0, 16), row.reason, `${row.ageDays} d`, String(row.counts.rendered ?? "?"), String(row.counts.delivered ?? "?"), String(row.counts.cited ?? "?")]), 1); out.note("Full entries: amem show <id> or --json."); }
953
+ else out.line(" No review targets.");
954
+ const legacy = 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";
955
+ return screenedLegacy(legacy, out.render(s.color).join("\n"));
885
956
  } finally { store.close(); }
886
957
  }
887
958
  const id = parsed.positionals[0];
@@ -1073,20 +1144,20 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1073
1144
  if (sub === "vault-candidates" && (options["--all-projects"] === true || options["--project"] !== undefined)) {
1074
1145
  if (options["--all-projects"] === true && options["--project"] !== undefined) throw new Error("choose either --all-projects or --project <key>, not both");
1075
1146
  const result = await vaultCandidatesAll(memoryHome(), { policy: policyOf(), ...(options["--project"] !== undefined ? { project: resolveAlias(memoryHome(), String(options["--project"])) } : {}), ...(options["--limit"] ? { limit: Number(options["--limit"]) } : {}) });
1076
- return options["--json"] ? JSON.stringify(result, null, 2) : vaultCandidatesAllText(result, outputStyle(context, options));
1147
+ return options["--json"] ? JSON.stringify(result, null, 2) : screenedReadPair(vaultCandidatesAllText(result, outputStyle(context, options)), reports.vaultReportText(result.projects, result.crossedProjects, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
1077
1148
  }
1078
1149
  if (sub === "vault-candidates") {
1079
1150
  const project = boundProject(), store = curatedStore(project, { deferPromotions: true });
1080
1151
  try {
1081
1152
  const result = await vaultCandidates(store, { project, policy: policyOf(), ...(options["--limit"] ? { limit: Number(options["--limit"]) } : {}) });
1082
- return options["--json"] ? JSON.stringify(result, null, 2) : vaultCandidatesText(result, outputStyle(context, options));
1153
+ return options["--json"] ? JSON.stringify(result, null, 2) : screenedReadPair(vaultCandidatesText(result, outputStyle(context, options)), reports.vaultReportText(result.length ? [{ project: result[0]!.project, candidates: result }] : [], false, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
1083
1154
  } finally { store.close(); }
1084
1155
  }
1085
1156
  if (sub === "eval") {
1086
1157
  // 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.
1087
1158
  if (parsed.path[1] === "audit") {
1088
1159
  // #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.
1089
- const audit = await import("./memory/eval-audit.ts"), { MAX_AUDIT_NOTES } = await import("./memory/eval.ts");
1160
+ const audit = await import("./memory/eval-audit.ts"), auditText = await import("./memory/eval-audit-text.ts"), { MAX_AUDIT_NOTES } = await import("./memory/eval.ts");
1090
1161
  if (parsed.path[2] === "sample") {
1091
1162
  const n = options["--n"] === undefined ? 40 : Number(options["--n"]), seed = typeof options["--seed"] === "string" ? options["--seed"] : "";
1092
1163
  if (!Number.isInteger(n) || n < 1 || n > MAX_AUDIT_NOTES) throw new Error(`--n must be an integer from 1 to ${MAX_AUDIT_NOTES}`);
@@ -1108,15 +1179,15 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1108
1179
  try { sheet = audit.auditSample({ store, project, n, seed, root, asOf, screen: view => screen.screenStandalone(view) }); } finally { store.close(); }
1109
1180
  const out = typeof options["--out"] === "string" ? options["--out"] : join(memoryHome(), "eval", `audit-${project.replace(/[^A-Za-z0-9._-]+/g, "-").slice(0, 80)}-${seed}.json`);
1110
1181
  const file = audit.writeAuditSheet(out, sheet);
1111
- 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);
1182
+ 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) : screenedLegacy(auditText.auditSheetText(sheet, file), auditText.auditSheetText(sheet, file, { columns: reportWidth(context) ?? 80, style: outputStyle(context, options), ...(context.now ? { now: context.now() } : {}) }));
1112
1183
  }
1113
1184
  if (parsed.path[2] === "score") {
1114
1185
  const [sheet] = parsed.positionals;
1115
- if (!sheet) throw new Error("usage: amem eval audit score <sheet> (the file `amem eval audit sample` wrote)");
1186
+ if (!sheet) throw new CommandUsageError("usage: amem eval audit score <sheet> (the file `amem eval audit sample` wrote)");
1116
1187
  const score = audit.auditScore(audit.readAuditSheet(sheet));
1117
- return options["--json"] === true ? JSON.stringify(score, null, 2) : audit.auditScoreText(score);
1188
+ return options["--json"] === true ? JSON.stringify(score, null, 2) : screenedLegacy(auditText.auditScoreText(score), auditText.auditScoreText(score, { columns: reportWidth(context) ?? 80, style: outputStyle(context, options), ...(context.now ? { now: context.now() } : {}) }));
1118
1189
  }
1119
- throw new Error("usage: amem eval audit sample --seed <s> [--n <n>] [--project <key>] | amem eval audit score <sheet>");
1190
+ throw new CommandUsageError("usage: amem eval audit sample --seed <s> [--n <n>] [--project <key>] | amem eval audit score <sheet>");
1120
1191
  }
1121
1192
  const ks = parseKs(typeof options["--k"] === "string" ? options["--k"] : undefined);
1122
1193
  const file = typeof options["--set"] === "string" ? options["--set"] : undefined;
@@ -1128,7 +1199,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1128
1199
  const project = boundProject(), store = curatedStore(project, { deferPromotions: true });
1129
1200
  try { report = evalStore(store, project, set, ks); } finally { store.close(); }
1130
1201
  }
1131
- return options["--json"] ? JSON.stringify(report, null, 2) : evalText(report, builtin ? `built-in fixture ${file}` : file ?? "built-in fixture");
1202
+ return options["--json"] ? JSON.stringify(report, null, 2) : evalText(report, builtin ? `built-in fixture ${file}` : file ?? "built-in fixture", { columns: reportWidth(context) ?? 80, style: outputStyle(context, options) });
1132
1203
  }
1133
1204
  if (sub === "spool") {
1134
1205
  // #217 PR2. Every argument refusal runs before any home, source or store access; both actors take this guarded
@@ -1138,7 +1209,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1138
1209
  const replay = await import("./hook-spool-replay.ts");
1139
1210
  if (!apply) {
1140
1211
  const plan = administrative(await replay.planHookSpoolReplay({ base: memoryHome(), ...(typeof source === "string" ? { source } : {}) }));
1141
- return options["--json"] === true ? JSON.stringify(plan, null, 2) : replayPreviewText(plan);
1212
+ return options["--json"] === true ? JSON.stringify(plan, null, 2) : screenedReadPair(replayPreviewText(plan), reports.spoolReplayReportText(plan, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
1142
1213
  }
1143
1214
  let saved: unknown;
1144
1215
  try { saved = JSON.parse(readFileSync(planFile as string, "utf8")); }
@@ -1152,13 +1223,15 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1152
1223
  const share = options["--disk-share"];
1153
1224
  if (share !== undefined && (!Number.isFinite(Number(share)) || Number(share) <= 0 || Number(share) > 1)) throw new Error("--disk-share must be a number in (0, 1]");
1154
1225
  const report = administrative(capacityReport({ ...(share !== undefined ? { diskShare: Number(share) } : {}) }));
1155
- if (parsed.path[1] !== "apply") return options["--json"] ? JSON.stringify(report, null, 2) : capacityText(report);
1226
+ const capacityStyle = options["--json"] === true ? PLAIN : outputStyle(context, options), capacityRender = { columns: reportWidth(context) ?? 80, style: capacityStyle };
1227
+ if (parsed.path[1] !== "apply") return options["--json"] ? JSON.stringify(report, null, 2) : capacityText(report, capacityRender);
1228
+ const confirmation = ["amem", "capacity", "apply", ...(options["--split"] === true ? ["--split"] : []), ...(["--disk-share", "--cap-mb", "--retention-days"] as const).flatMap(flag => typeof options[flag] === "string" && options[flag] !== "" ? [flag, String(Number(options[flag]))] : []), "--confirm"].join(" ");
1156
1229
  if (options["--split"] === true) {
1157
1230
  // #15 D7: each shard's own share of the global budget, written to its own config. The same two steps as the home default below, bound to the shards it was made for.
1158
1231
  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");
1159
1232
  const diskShare = share !== undefined ? { diskShare: Number(share) } : {};
1160
1233
  const result = options["--confirm"] === true ? applySplit(memoryHome(), diskShare) : previewSplit(memoryHome(), diskShare);
1161
- return options["--json"] ? JSON.stringify(result, null, 2) : capacitySplitText(result, outputStyle(context, options));
1234
+ return options["--json"] ? JSON.stringify(result, null, 2) : capacitySplitText(result, capacityStyle, { ...capacityRender, next: confirmation });
1162
1235
  }
1163
1236
  // Preview first; --confirm writes the bound home default config.
1164
1237
  const file = join(memoryHome(), "capture-config.json");
@@ -1172,7 +1245,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1172
1245
  if (options["--confirm"] !== true) {
1173
1246
  writeFileSync(previewFile, JSON.stringify(preview) + "\n", { mode: 0o600 });
1174
1247
  const result = { preview, confirm: "re-run with --confirm to write" };
1175
- return options["--json"] ? JSON.stringify(result, null, 2) : capacityApplyText(result, outputStyle(context, options));
1248
+ return options["--json"] ? JSON.stringify(result, null, 2) : capacityApplyText(result, capacityStyle, { ...capacityRender, next: confirmation });
1176
1249
  }
1177
1250
  let approved: { file?: string; current?: unknown; target?: CaptureConfig };
1178
1251
  try { approved = JSON.parse(readFileSync(previewFile, "utf8")) as typeof approved; }
@@ -1184,29 +1257,30 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1184
1257
  const written = writeCaptureConfigFile(file, target);
1185
1258
  rmSync(previewFile, { force: true });
1186
1259
  const result = { preview, written: { cap_mb: written.capMb, retention_days: written.retentionDays } };
1187
- return options["--json"] ? JSON.stringify(result, null, 2) : capacityApplyText(result, outputStyle(context, options));
1260
+ return options["--json"] ? JSON.stringify(result, null, 2) : capacityApplyText(result, capacityStyle, { ...capacityRender, next: confirmation });
1188
1261
  }
1189
1262
  if (sub === "projects") {
1190
1263
  // 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.
1191
1264
  const rows = readCatalogFresh(memoryHome()).filter(project => options["--all"] === true || project.state !== "forgotten");
1192
1265
  if (options["--json"]) return JSON.stringify(rows, null, 2);
1193
- if (!rows.length) return "no project shards yet";
1266
+ if (!rows.length) return screenedReadPair("no project shards yet", reports.projectsReportText(rows, false, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
1194
1267
  const mb = (n: number) => `${(n / 1048576).toFixed(1)} MB`;
1195
1268
  // Per-project curated counts exist only after the split; before it every note is in one shared store, so the honest figure is unavailable, never 0.
1196
1269
  const split = shardStatePresent();
1197
- return rows.map(p => `${p.key} ${p.state}${p.local ? " local-only key" : ""}${p.aliases.length ? ` aliases: ${p.aliases.join(", ")}` : ""} capture ${p.captureRows} rows ${mb(p.captureBytes)} curated ${split ? p.curatedEntries ?? "unavailable" : "unavailable (home not split)"} disk ${mb(p.diskBytes)} last ${p.captureLastAt ?? "never"}`).join("\n");
1270
+ const legacy = rows.map(p => `${p.key} ${p.state}${p.local ? " local-only key" : ""}${p.aliases.length ? ` aliases: ${p.aliases.join(", ")}` : ""} capture ${p.captureRows} rows ${mb(p.captureBytes)} curated ${split ? p.curatedEntries ?? "unavailable" : "unavailable (home not split)"} disk ${mb(p.diskBytes)} last ${p.captureLastAt ?? "never"}`).join("\n");
1271
+ return screenedReadPair(legacy, reports.projectsReportText(rows, split, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
1198
1272
  }
1199
1273
  if (sub === "usage") {
1200
1274
  const limit = options["--limit"] === undefined ? undefined : Number(options["--limit"]);
1201
1275
  const report = usageReport(memoryHome(), { ...(limit !== undefined ? { limit } : {}), includeForgotten: options["--all"] === true });
1202
- return options["--json"] ? JSON.stringify(report, null, 2) : usageText(report);
1276
+ return options["--json"] ? JSON.stringify(report, null, 2) : screenedReadPair(usageText(report), reports.usageReportText(report, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
1203
1277
  }
1204
1278
  if (sub === "gc") {
1205
1279
  // A preview reads; only explicit --confirm evicts, after the administrative preflight.
1206
1280
  const batches = options["--batches"] === undefined ? undefined : Number(options["--batches"]);
1207
1281
  if (actor === "agent") administrative(runGc(memoryHome(), { dryRun: true, ...(batches !== undefined ? { maxBatchesPerShard: batches } : {}) }));
1208
1282
  const result = runGc(memoryHome(), { dryRun: options["--confirm"] !== true, ...(batches !== undefined ? { maxBatchesPerShard: batches } : {}) });
1209
- return options["--json"] ? JSON.stringify(result, null, 2) : `${result.dryRun ? "preview (nothing evicted; add --confirm):\n" : ""}${gcText(result)}`;
1283
+ return options["--json"] ? JSON.stringify(result, null, 2) : screenedLegacy(`${result.dryRun ? "preview (nothing evicted; add --confirm):\n" : ""}${gcText(result)}`, gcText(result, { columns: reportWidth(context) ?? 80, style: outputStyle(context, options), next: `amem gc --confirm${batches === undefined ? "" : ` --batches ${batches}`}` }));
1210
1284
  }
1211
1285
  if (sub === "import" && ["claude-auto", "codex"].includes(parsed.path[1] ?? "")) {
1212
1286
  for (const flag of ["--db", "--limit", "--restart", "--capture-days"]) if (options[flag] !== undefined) throw new Error(`${flag} only applies to import claude-mem`);
@@ -1234,11 +1308,14 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1234
1308
  try {
1235
1309
  const result = await importProject(store, { from: options["--from"], project: key, confirm: options["--confirm"] === true,
1236
1310
  allowShared: options["--allow-shared"] === true, policy: note => policy.screenStandalone(note) });
1237
- const counts = `sources ${JSON.stringify(result.provenance.source)}, peers ${JSON.stringify(result.provenance.peer)}, scopes ${JSON.stringify(result.provenance.scope)}, machines ${JSON.stringify(result.provenance.machine)}`;
1311
+ const describe = (values: Record<string, number>) => Object.entries(values).map(([key, value]) => `${wordedKey(key)} ${value}`).join(", ") || "none";
1312
+ const counts = `sources ${describe(result.provenance.source)}, peers ${describe(result.provenance.peer)}, scopes ${describe(result.provenance.scope)}, machines ${describe(result.provenance.machine)}`;
1238
1313
  const summary = result.applied ? `imported ${result.added} of ${result.read} curated notes into ${result.project} with their original ids`
1239
1314
  : `preview: ${result.wouldAdd} of ${result.read} curated notes can be imported into ${result.project} with their original ids (re-run with --confirm to write)`;
1240
- return options["--json"] ? JSON.stringify(result, null, 2)
1241
- : `${summary}; ${counts}; skipped ${result.skipped.invalid} invalid, ${result.skipped.policy} policy/secret and ${result.skipped.other} non-curated records. ${result.warnings.join(" ")}`;
1315
+ const formatted = `${summary}; ${counts}; skipped ${result.skipped.invalid} invalid, ${result.skipped.policy} policy/secret and ${result.skipped.other} non-curated records. ${result.warnings.join(" ")}`;
1316
+ const legacyCounts = `sources ${JSON.stringify(result.provenance.source)}, peers ${JSON.stringify(result.provenance.peer)}, scopes ${JSON.stringify(result.provenance.scope)}, machines ${JSON.stringify(result.provenance.machine)}`;
1317
+ const legacy = `${summary}; ${legacyCounts}; skipped ${result.skipped.invalid} invalid, ${result.skipped.policy} policy/secret and ${result.skipped.other} non-curated records. ${result.warnings.join(" ")}`;
1318
+ return options["--json"] ? JSON.stringify(result, null, 2) : screenedLegacy(legacy, formatted);
1242
1319
  } finally { store.close(); }
1243
1320
  }
1244
1321
  const key = administrative(requireShard(memoryHome(), requested));
@@ -1251,7 +1328,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1251
1328
  }
1252
1329
  // Only the existing cross-project capture renderer uses this; project search and agent MCP routing stay unchanged.
1253
1330
  const captureSearchText = (capture: { event: string; excerpt: string; paths: string[] }): string => {
1254
- if (capture.event !== "Record") return capture.excerpt.split("\n")[0]!.slice(0, 100);
1331
+ if (capture.event !== "Record") return capture.excerpt.split(/[\r\n]/, 1)[0]! + (/[\r\n]/.test(capture.excerpt) ? "..." : "");
1255
1332
  const parsed = parseRecordLines(capture.excerpt), record = parsed.records[0];
1256
1333
  // Historical capture can contain arbitrary event text. Never render it as a canonical Record or inject another display line.
1257
1334
  return record && parsed.records.length === 1 && Object.keys(parsed.drops).length === 0 && record.line === capture.excerpt
@@ -1261,11 +1338,15 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1261
1338
  if (options["--explain"] === true) throw new Error("--explain applies to current-project ranked search, not --all-projects");
1262
1339
  if (options["--filter"] === true) throw new Error("--filter applies to project-local search, not --all-projects");
1263
1340
  const words = parsed.positionals.join(" ");
1264
- if (!words.trim()) throw new Error("usage: amem search --all-projects <words> [--limit N] [--include-archived] [--json]");
1341
+ if (!words.trim()) throw new CommandUsageError("usage: amem search --all-projects <words> [--limit N] [--include-archived] [--json]");
1265
1342
  const result = searchAllProjects(memoryHome(), words, { ...(options["--limit"] !== undefined ? { limit: Number(options["--limit"]) } : {}), includeArchived: options["--include-archived"] === true });
1266
1343
  if (options["--json"]) return JSON.stringify(result, null, 2);
1267
- const one = (hit: (typeof result.hits)[number]) => hit.view ? `${hit.project} ${hit.view.id.slice(0, 8)} ${hit.view.kind} ${(hit.view.title ?? hit.view.text).split("\n")[0]!.slice(0, 100)}` : `${hit.project} capture ${hit.capture!.id} ${hit.capture!.event}${hit.capture!.subagent ? " subagent" : ""} ${captureSearchText(hit.capture!)}`;
1268
- return [`crossed projects: searched ${result.projects.length} (${result.projects.join(", ")})`, ...(result.hits.length ? result.hits.map(one) : ["(nothing)"])].join("\n");
1344
+ const one = (hit: (typeof result.hits)[number]) => hit.view ? `${hit.project} ${hit.view.id.slice(0, 8)} ${hit.view.kind} ${(hit.view.title ?? hit.view.text).split("\n")[0]!.slice(0, 100)}` : `${hit.project} capture ${hit.capture!.id} ${hit.capture!.event}${hit.capture!.subagent ? " subagent" : ""} ${hit.capture!.event === "Record" ? captureSearchText(hit.capture!) : hit.capture!.excerpt.split("\n")[0]!.slice(0, 100)}`;
1345
+ const legacy = [`crossed projects: searched ${result.projects.length} (${result.projects.join(", ")})`, ...(result.hits.length ? result.hits.map(one) : ["(nothing)"])].join("\n");
1346
+ const rows = result.hits.map(hit => hit.view ? { project: hit.project, id: hit.view.id, kind: hit.view.kind, tier: hit.view.tier, peer: hit.view.peer, scope: hit.view.scope, at: hit.view.at, text: `${hit.view.title ? `${hit.view.title}: ` : ""}${hit.view.text}` } : { project: hit.project, id: `capture:${hit.capture!.id}`, kind: "capture", peer: hit.capture!.agent, at: hit.capture!.at, text: `${hit.capture!.event}${hit.capture!.subagent ? " subagent" : ""}: ${captureSearchText(hit.capture!)}` });
1347
+ const width = reportWidth(context) ?? 80, displayStyle = outputStyle(context, options), projects = new Report(width, displayStyle.ascii, { sanitize: singleLine });
1348
+ projects.section("Projects", String(result.projects.length)); projects.line(`Crossed projects: ${result.projects.join(", ") || "none"}.`);
1349
+ return screenedReadPair(legacy, `${memoryTableText(rows, "Cross-project search", { columns: width, style: displayStyle, ...(context.now ? { now: context.now() } : {}) })}\n\n${projects.render(displayStyle.color).join("\n")}`);
1269
1350
  }
1270
1351
  if (sub === "search" && options["--include-archived"] === true) throw new Error("--include-archived only applies with --all-projects");
1271
1352
  if (sub === "search" && options["--explain"] === true) {
@@ -1308,13 +1389,14 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1308
1389
  const scoped = repoReadPolicy(root);
1309
1390
  const read = "reason" in scoped ? undefined : await readRepoScope(root, scoped.policy);
1310
1391
  const status = { root, file: repoLogPath(root), state: read?.state ?? "unavailable", entries: read?.views.length ?? 0, skipped: read?.skipped ?? null, ...(read?.reason ? { reason: read.reason } : {}), ...("reason" in scoped ? { reason: scoped.reason } : {}) };
1311
- return options["--json"] ? JSON.stringify(status, null, 2) : [`repo scope of ${project}: ${status.state}`, `file: ${status.file}`, `entries: ${status.entries}${read ? ` (skipped: ${read.skipped.malformed} malformed, ${read.skipped.mismatched} id mismatch, ${read.skipped.duplicate} duplicate, ${read.skipped.withheld} withheld by the screen)` : ""}`,
1312
- ...(status.reason ? [`unavailable: ${status.reason}`] : [])].join("\n");
1392
+ if (options["--json"]) return JSON.stringify(status, null, 2);
1393
+ return screenedReadPair([`repo scope of ${project}: ${status.state}`, `file: ${status.file}`, `entries: ${status.entries}${read ? ` (skipped: ${read.skipped.malformed} malformed, ${read.skipped.mismatched} id mismatch, ${read.skipped.duplicate} duplicate, ${read.skipped.withheld} withheld by the screen)` : ""}`,
1394
+ ...(status.reason ? [`unavailable: ${status.reason}`] : [])].join("\n"), reports.repoStatusReportText(status, project, outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
1313
1395
  }
1314
1396
  if (sub === "promote" && options["--to"] === undefined && (options["--confirm"] !== undefined || options["--confirm-public"] !== undefined)) throw new Error("--confirm and --confirm-public only apply with --to repo");
1315
1397
  if (sub === "promote" && options["--to"] !== undefined) {
1316
1398
  const idText = parsed.positionals[0];
1317
- if (!idText || parsed.positionals.length !== 1) throw new Error("usage: amem promote <id> --to repo --policy-free [--confirm [--confirm-public <entry id prefix>]]");
1399
+ if (!idText || parsed.positionals.length !== 1) throw new CommandUsageError("usage: amem promote <id> --to repo --policy-free [--confirm [--confirm-public <entry id prefix>]]");
1318
1400
  const project = boundProject(), root = boundRepoRoot(repoCwd, memoryHome(), project);
1319
1401
  if (!root) throw new Error("repo scope needs the working tree of the repository that is this project: run it from inside that repository");
1320
1402
  const store = curatedStore(project, { deferPromotions: true, screen: () => "skip" });
@@ -1342,9 +1424,17 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1342
1424
  administrative({ path: plan.path, line: plan.line });
1343
1425
  const preview = [`the exact line that would be appended to ${plan.path}:`, plan.text, ...(plan.droppedNodes.length ? [`(left out, private references: ${plan.droppedNodes.join(", ")})`] : []),
1344
1426
  `repository visibility: ${seen.state}${seen.remotes.length ? ` (${[...new Set(seen.remotes.map(r => `${r.name}${r.kind === "push" ? " (push)" : ""} ${r.visibility}`))].join(", ")})` : " (no remote)"}`];
1345
- if (plan.alreadyPresent) return [...preview, "already in the file: nothing to write"].join("\n");
1346
1427
  const entryPrefix = plan.line.id.slice(0, 8);
1347
- if (options["--confirm"] !== true) return [...preview, seen.state === "private" ? "nothing written; add --confirm to append it" : `NOT a verified private repository: add --confirm --confirm-public ${entryPrefix} to append this entry (per entry, never blanket)`].join("\n");
1428
+ if (plan.alreadyPresent || options["--confirm"] !== true) {
1429
+ const s = outputStyle(context, options), report = new Report(reportWidth(context) ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
1430
+ report.header("amem", "Repository promotion"); report.section("Preview");
1431
+ const targetParts = Array.from(plan.path), target = targetParts.length > 25 ? `${targetParts.slice(0, 10).join("")}...${targetParts.slice(-12).join("")}` : plan.path;
1432
+ report.kv([["Scope", "repo"], ["Kind", plan.line.kind], ["Target", target], ["Visibility", seen.state]]);
1433
+ if (plan.droppedNodes.length) report.line(`Private references omitted: ${plan.droppedNodes.join(", ")}`);
1434
+ report.line(plan.alreadyPresent ? "already in the file: nothing to write" : seen.state === "private" ? "Nothing written; add --confirm to append it." : `NOT a verified private repository: add --confirm --confirm-public ${entryPrefix} to append this entry (per entry, never blanket).`);
1435
+ // AC8 exception: the canonical line must be shown verbatim before appending to a shared repository.
1436
+ return `${report.render(s.color).join("\n")}\nLine to append:\n${plan.text}`;
1437
+ }
1348
1438
  if (seen.state !== "private") {
1349
1439
  const given = options["--confirm-public"];
1350
1440
  if (typeof given !== "string" || given.length < 8 || !/^[a-f0-9]+$/.test(given) || !plan.line.id.startsWith(given)) throw new Error(`the repository is ${seen.state === "public" ? "public" : "not verified private"}: repo scope needs your confirmation of this entry: --confirm-public ${entryPrefix} (the first 8 characters of the id in the line above)`);
@@ -1361,8 +1451,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1361
1451
  const shown = await memory.tools.amem_show({ id: parsed.positionals[0]! }) as { capture?: import("./memory/capture.ts").CaptureRow } | null;
1362
1452
  const row = shown?.capture; if (!row) throw new Error(`no capture row ${parsed.positionals[0]} in this project (capture is machine-local and expires; inspect the current project timeline and retention)`);
1363
1453
  return options["--json"] === true ? JSON.stringify(row, null, 2)
1364
- : [`capture:${row.id} ${row.event}${row.tool ? ` ${row.tool}` : ""}, ${row.at}, agent ${row.agent}, session ${row.session ?? "unavailable"}${row.subagent ? ", subagent" : ""}`,
1365
- ...(row.paths.length ? [`paths: ${row.paths.join(", ")}`] : []), "", terminalSafe(row.excerpt)].join("\n");
1454
+ : memoryRecordText({ id: `capture:${row.id}`, kind: row.event, at: row.at, text: row.excerpt }, { columns: reportWidth(context) ?? 80, style: outputStyle(context, options), ...(context.now ? { now: context.now() } : {}) }, [["Recorded at", row.at], ["Agent", row.agent], ["Session", row.session ?? "unavailable"], ...(row.tool ? [["Tool", row.tool] as [string, string]] : []), ...(row.paths.length ? [["Paths", row.paths.join(", ")] as [string, string]] : []), ...(row.subagent ? [["Subagent", "yes"] as [string, string]] : [])]);
1366
1455
  } finally { memory.close(); }
1367
1456
  }
1368
1457
  if (sub === "show" && /^repo:/.test(parsed.positionals[0] ?? "")) {
@@ -1371,8 +1460,10 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1371
1460
  const wanted = parsed.positionals[0]!.slice(5), hit = rows.filter(row => row.id === wanted || wanted.length >= 6 && row.id.startsWith(wanted));
1372
1461
  if (hit.length !== 1) throw new Error(`no repo entry ${parsed.positionals[0]} in this repository's .amem/log.jsonl`);
1373
1462
  const row = hit[0]!;
1374
- return options["--json"] ? JSON.stringify(row, null, 2) : [`repo:${row.id} ${row.kind}, repo scope, ${row.at}`, ...(row.about.length ? [`about: ${row.about.join(", ")}`] : []), "", ...(row.title ? [row.title] : []), row.text].join("\n");
1463
+ if (actor === "agent" && options["--json"] !== true) return [`repo:${row.id} ${row.kind}, repo scope, ${row.at}`, ...(row.about.length ? [`about: ${row.about.join(", ")}`] : []), "", ...(row.title ? [row.title] : []), row.text].join("\n");
1464
+ return options["--json"] ? JSON.stringify(row, null, 2) : memoryRecordText({ id: `repo:${row.id}`, kind: row.kind, at: row.at, text: `${row.title ? `${row.title}\n` : ""}${row.text}` }, { columns: reportWidth(context) ?? 80, style: outputStyle(context, options), ...(context.now ? { now: context.now() } : {}) }, [["Scope", "repo"], ...(row.about.length ? [["About", row.about.join(", ")] as [string, string]] : [])]);
1375
1465
  }
1466
+ let priorRead: string | undefined;
1376
1467
  // Recall (D4): the current project plus, when the repository IS this project, that repository's `.amem/`. Never another project's.
1377
1468
  const withRepoRows = async (output: string): Promise<string> => {
1378
1469
  if (options["--history"] === true || options["--as-of"] !== undefined) return output;
@@ -1389,10 +1480,14 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1389
1480
  && words.every(word => `${row.title ?? ""}\n${row.text}\n${row.about.join(" ")}`.toLowerCase().includes(word))).slice(0, limit);
1390
1481
  const repoDetails = explainSearch ? rows.map(row => ({ ...row, scoreDetails: unrankedScoreDetails("repo", null) })) : rows;
1391
1482
  if (options["--json"]) { try { const base = JSON.parse(output) as unknown[]; return JSON.stringify([...base, ...repoDetails], null, 2); } catch { return output; } }
1392
- const line = (row: RepoView) => `repo:${row.id.slice(0, 8)} ${row.at.slice(0, 16).replace("T", " ")} repo ${row.kind.padEnd(8)} ${`${row.title ? `${row.title}: ` : ""}${row.text}`.replace(/\s+/g, " ").slice(0, 100)}`;
1393
1483
  const note = read.state === "unsafe" ? [`(repo scope unavailable: ${read.reason})`] : read.skipped.malformed + read.skipped.mismatched + read.skipped.withheld ? [`(${read.skipped.malformed + read.skipped.mismatched} repo lines skipped as invalid, ${read.skipped.withheld} withheld by the screen)`] : [];
1484
+ const line = (row: (typeof rows)[number]) => `repo:${row.id.slice(0, 8)} ${row.at.slice(0, 16).replace("T", " ")} repo ${row.kind.padEnd(8)} ${`${row.title ? `${row.title}: ` : ""}${row.text}`.replace(/\s+/g, " ").slice(0, 100)}`;
1394
1485
  const lines = explainSearch ? rows.flatMap(row => [line(row), `score: ${JSON.stringify(unrankedScoreDetails("repo", null))}`]) : rows.map(line);
1395
- return [output, ...(rows.length ? ["repo scope (.amem/log.jsonl):", ...lines] : []), ...note].join("\n");
1486
+ const legacy = [priorRead ?? output, ...(rows.length ? ["repo scope (.amem/log.jsonl):", ...lines] : []), ...note].join("\n");
1487
+ const render = { columns: reportWidth(context) ?? 80, style: outputStyle(context, options), ...(context.now ? { now: context.now() } : {}) };
1488
+ const table = rows.length ? memoryTableText(rows.map(row => ({ id: `repo:${row.id}`, kind: row.kind, at: row.at, text: `${row.title ? `${row.title}: ` : ""}${row.text}` })), "Repository", render) : "";
1489
+ const scores = explainSearch ? memoryScoresText(rows.map(row => ({ id: `repo:${row.id}`, details: unrankedScoreDetails("repo", null) as unknown as Record<string, unknown> })), render) : "";
1490
+ return screenedReadPair(legacy, [output, ...(rows.length ? ["repo scope (.amem/log.jsonl):", table] : []), ...(scores ? ["", scores] : []), ...note].join("\n"));
1396
1491
  };
1397
1492
  const crosses = definition.policyFree === true;
1398
1493
  const cwd = context.cwd ?? process.cwd();
@@ -1429,7 +1524,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1429
1524
  // #418: read-only status from the telemetry sidecars; no realm, lock, proof, journal or schedule is touched.
1430
1525
  if (Object.keys(options).some(name => name !== "--status" && name !== "--json")) throw new Error("sync --status takes only --json");
1431
1526
  const { readSyncStatus, renderSyncStatus } = await import("./memory/sync-progress.ts"), report = readSyncStatus(syncHome);
1432
- return options["--json"] ? JSON.stringify(report, null, 2) : renderSyncStatus(report);
1527
+ return options["--json"] ? JSON.stringify(report, null, 2) : screenedReadPair(renderSyncStatus(report), reports.syncStatusReportText(report, context.now?.() ?? Date.now(), outputStyle(context, options), { columns: reportWidth(context) ?? 80, ...(context.now ? { now: context.now() } : {}) }));
1433
1528
  }
1434
1529
  if (sub === "sync") { assertFormatFloor(syncHome, "sync"); const refusal = placementRuntimeRefusal(syncHome); if (refusal) throw new Error("amem sync: " + refusal); }
1435
1530
  if (ifDue) {
@@ -1463,26 +1558,40 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1463
1558
  let output: string;
1464
1559
  let placementWriters: import("./sync-placement-writer-context.ts").PlacementWriterContext | undefined;
1465
1560
  let progress: import("./memory/sync-progress.ts").SyncProgress | undefined;
1561
+ let writerRefusal: import("./memory/sync-placement-refusal-category.ts").PlacementWriterRefusal | undefined;
1562
+ let attestPlacement: import("./sync-placement-writer-context.ts").PlacementWriterContext["attest"] | undefined;
1466
1563
  const stop = ifDue ? stopSignal(context.syncDeadlineMs ?? SYNC_IF_DUE_DEADLINE_MS, process) : undefined;
1467
1564
  try {
1468
1565
  if (sub === "sync" && (readPlacementRuntimeMarkers(syncHome).profile as { publicationFormat?:string } | undefined)?.publicationFormat === "agent-mem.sync-placement/v1") {
1469
- const { activePlacementWriterContext } = await import("./sync-placement-writer-context.ts");
1470
- progress = await placementProgress(syncHome, typeof options["--progress"] === "string" ? options["--progress"] as string : "auto", context);
1566
+ const { activePlacementWriterContext, placementWriterRefusalDetail, placementWriterRefusalText } = await import("./sync-placement-writer-context.ts");
1567
+ progress = await placementProgress(syncHome, typeof options["--progress"] === "string" ? options["--progress"] as string : "auto", context, () => writerRefusal);
1471
1568
  try { placementWriters = activePlacementWriterContext(syncHome,fileURLToPath(new URL("..",import.meta.url))); }
1472
1569
  catch (error) {
1570
+ writerRefusal = placementWriterRefusalDetail(error);
1473
1571
  // #551 AC1: a writer-context refusal is this run's own failed result, so --json reports it instead of printing one
1474
1572
  // masked line; a human run keeps the refusal's fixed text and exit 1, and every other refusal keeps its own path.
1475
- const refusal = (await import("./sync-placement-writer-context.ts")).placementWriterRefusalText(error);
1573
+ const refusal = placementWriterRefusalText(error);
1476
1574
  if (refusal === undefined || !options["--json"]) throw error;
1477
1575
  stampSync(refusal, stop?.cause());
1478
1576
  return JSON.stringify({ ok: false, pushed: false, entries: 0, failure: { cause: "refusal" }, error: refusal }, null, 2);
1479
1577
  }
1578
+ const attest = placementWriters.attest;
1579
+ attestPlacement = () => {
1580
+ try {
1581
+ const proof = attest();
1582
+ writerRefusal = undefined;
1583
+ return proof;
1584
+ } catch (error) {
1585
+ writerRefusal = placementWriterRefusalDetail(error);
1586
+ throw error;
1587
+ }
1588
+ };
1480
1589
  const markers = readPlacementRuntimeMarkers(syncHome);
1481
1590
  if (!readActivePlacementBinding(syncHome, markers.profile, markers.shards)) throw Error("sync placement activation metadata unavailable or changed; inspect the retained activation before continuing");
1482
1591
  }
1483
- output = await withRepoRows(await rawMemoryCommand(memoryArgs, cwd, { person: true, rankedSearch: !legacySearch, ...(identity.actor === "agent" ? { screenGraph: true } : {}), ...(explainSearch ? { explainSearch: true } : {}), project: boundProject(), open: sub === "sync" && placementWriters ? () => openShardStore({ memoryDir: syncHome, user: true, deferPromotions: true }) : open, readable: notes => identity.actor === "person" ? notes : notes.filter(view => view.project === boundProject() && policyOf().screenStandalone(view)), stale: createRecallStalenessProbe({ cwd: recallRoot ?? cwd, rootConfirmed, policy: () => configured }), outputReady: notes => outputReady(notes.map(view => view.id)), importPolicy: () => text => configured.declinesPersonal(text),
1592
+ output = await withRepoRows(await rawMemoryCommand(memoryArgs, cwd, { person: true, rankedSearch: !legacySearch, ...(identity.actor === "agent" ? { screenGraph: true } : {}), ...(explainSearch ? { explainSearch: true } : {}), ...(options["--json"] !== true ? { [CLI_MEMORY_RENDER]: { render: { columns: reportWidth(context) ?? 80, style: outputStyle(context, options), ...(context.now ? { now: context.now() } : {}) }, ...(actor === "agent" ? { renderLegacy: (legacy: string, formatted: string) => { priorRead = legacy; return sub === "sync" ? screenedReceipt(legacy, formatted) : screenedReadPair(legacy, formatted); } } : {}) } } : {}), project: boundProject(), open: sub === "sync" && placementWriters ? () => openShardStore({ memoryDir: syncHome, user: true, deferPromotions: true }) : open, readable: notes => identity.actor === "person" ? notes : notes.filter(view => view.project === boundProject() && policyOf().screenStandalone(view)), stale: createRecallStalenessProbe({ cwd: recallRoot ?? cwd, rootConfirmed, policy: () => configured }), outputReady: notes => outputReady(notes.map(view => view.id)), importPolicy: () => text => configured.declinesPersonal(text),
1484
1593
  // #578 Q2: the CLI sync (also --if-due) is eligible; the home opt-in still decides whether a checkpoint can run.
1485
- sync: { ...(placementWriters ? { placementAttestation:placementWriters.attest, placementCheckpoint: true } : {}), ...(progress ? { progress } : {}), screen: row => configured.screenStandalone(row), policyVersion: () => JSON.stringify(configuredPolicyOptions(memoryHome(), policyCwd)), ...(stop ? { signal: stop.signal } : {}) }, // the repository-narrowed policy binds what sync publishes too
1594
+ sync: { ...(attestPlacement ? { placementAttestation: attestPlacement, placementCheckpoint: true } : {}), ...(progress ? { progress } : {}), screen: deterministicRowScreen(configuredPolicyOptions(memoryHome(), policyCwd)), policyVersion: () => JSON.stringify(configuredPolicyOptions(memoryHome(), policyCwd)), ...(stop ? { signal: stop.signal } : {}) }, // the repository-narrowed policy binds what sync publishes too
1486
1595
  onBridgeStatus: status => { receipt.bridgeStatus = status; },
1487
1596
  // #188: ids-only listing of nearby machine-local rows; policy-refused rows are neither listed nor counted.
1488
1597
  forgetNearby: note => forgetNearby({ base: memoryHome(), project: note.project, text: note.text, title: note.title, screen: value => configured.screenStandalone(value) }) }));
@@ -1516,8 +1625,11 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1516
1625
  const policy = configured, db = options["--db"] ? { db: String(options["--db"]) } : {}, limit = options["--limit"] ? { limit: Number(options["--limit"]) } : {}, restart = options["--restart"] === true;
1517
1626
  const work = await importClaudeMemWorkState({ base: memoryHome(), project: boundProject(), policy: row => policy.screen(row), ...db, ...limit, restart });
1518
1627
  const capture = captureDays === undefined ? undefined : await importClaudeMemCapture({ base: memoryHome(), project: boundProject(), cwd, days: captureDays, ...db, ...limit, restart, policy: { host: policy } });
1519
- return options["--json"] ? JSON.stringify({ ...JSON.parse(output), work, ...(capture ? { capture } : {}) }, null, 2)
1520
- : claudeMemImportText(JSON.parse(output), work, capture, { captureDays, restart }, outputStyle(context, options));
1628
+ if (options["--json"]) return JSON.stringify({ ...JSON.parse(output), work, ...(capture ? { capture } : {}) }, null, 2);
1629
+ const s = outputStyle(context, options), notes = JSON.parse(output), source = typeof options["--db"] === "string" ? options["--db"] : undefined;
1630
+ const safe = source === undefined || !/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(source);
1631
+ const next = safe ? ["amem import claude-mem", ...(source ? [`--db '${source.replaceAll("'", "'\\''")}'`] : []), ...(limit.limit !== undefined ? [`--limit ${limit.limit}`] : []), ...(captureDays !== undefined ? [`--capture-days ${captureDays}`] : [])].join(" ") : undefined;
1632
+ return screenedLegacy(claudeMemImportText(notes, work, capture, { captureDays, restart }, s), claudeMemImportText(notes, work, capture, { captureDays, restart }, s, { columns: reportWidth(context) ?? 80, ...(next ? { next } : {}) }));
1521
1633
  }
1522
1634
  return !options["--json"] && receipt.bridgeStatus
1523
1635
  ? `${output}\n(legacy malformed lines skipped: ${receipt.bridgeStatus.skippedRows})` : output;
@@ -1528,19 +1640,26 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1528
1640
  * #418: one reporter per placement sync. The private sidecar backs `sync --status` in every mode; stderr gets human
1529
1641
  * lines or versioned JSON events. Each part fails alone and silently: telemetry never fails or alters the sync.
1530
1642
  */
1531
- async function placementProgress(home: string, mode: string, context: CliContext): Promise<import("./memory/sync-progress.ts").SyncProgress> {
1532
- const { SyncProgress, renderSyncProgress, syncProgressSidecar } = await import("./memory/sync-progress.ts");
1643
+ async function placementProgress(home: string, mode: string, context: CliContext, writerRefusal: () => import("./memory/sync-placement-refusal-category.ts").PlacementWriterRefusal | undefined): Promise<import("./memory/sync-progress.ts").SyncProgress> {
1644
+ const { SyncProgress, renderSyncProgress, syncProgressSidecar, syncStatusSnapshot } = await import("./memory/sync-progress.ts");
1533
1645
  const write = context.stderr ?? ((text: string) => { process.stderr.write(text); });
1534
1646
  const render = mode === "json" ? "json" : mode === "human" || mode === "auto" && (context.stderrTTY ?? process.stderr.isTTY) ? "human" : undefined;
1535
1647
  const parts = [syncProgressSidecar(home), ...(render ? [(snapshot: import("./memory/sync-progress.ts").SyncProgressSnapshot) => write((render === "json" ? JSON.stringify(snapshot) : renderSyncProgress(snapshot)) + "\n")] : [])];
1536
1648
  const live = new Set(parts.keys());
1537
- return new SyncProgress({ sink: snapshot => { for (const index of live) try { parts[index]!(snapshot); } catch { live.delete(index); } } });
1649
+ return new SyncProgress({ sink: snapshot => {
1650
+ const status = syncStatusSnapshot(snapshot, writerRefusal());
1651
+ for (const index of live) try { parts[index]!(status); } catch { live.delete(index); }
1652
+ } });
1538
1653
  }
1539
1654
  function outputStyle(context: CliContext, options: Record<string, string | boolean>): Style {
1540
1655
  const color = resolveColor(typeof options["--color"] === "string" ? options["--color"] : undefined, streamEnv((context.stdoutTTY ?? process.stdout.isTTY) === true, context.env ?? process.env), "amem");
1541
1656
  if (color instanceof Error) throw color;
1542
1657
  return style(options["--json"] !== true && color, asciiMarkers(context.env ?? process.env, options["--ascii"] === true));
1543
1658
  }
1659
+ function reportOptions(context: CliContext, options: Record<string, string | boolean>): { verbose: boolean; version: string; columns?: number } {
1660
+ const columns = reportWidth(context);
1661
+ return { verbose: options["--verbose"] === true, version: VERSION, ...(columns !== undefined ? { columns } : {}) };
1662
+ }
1544
1663
  function reportWidth(context: CliContext): number | undefined {
1545
1664
  const env = context.env ?? process.env, configured = Number(env.COLUMNS);
1546
1665
  if (Number.isSafeInteger(configured) && configured >= 20) return configured;
@@ -1548,7 +1667,7 @@ function reportWidth(context: CliContext): number | undefined {
1548
1667
  }
1549
1668
 
1550
1669
  /** Native ingest remains capture-only and agent-reachable; this formats only its returned receipt. */
1551
- export function ingestText(kind: IngestKind, result: IngestReceipt, s: Style = PLAIN): string {
1670
+ export function ingestText(kind: IngestKind, result: IngestReceipt, s: Style = PLAIN, columns?: number): string {
1552
1671
  const state = result.errors || result.remaining || result.spooled ? "attention" : result.files || result.read ? "complete" : "skipped";
1553
1672
  const reason: string | undefined = result.reason;
1554
1673
  const actions: Record<string, string> = {
@@ -1564,18 +1683,28 @@ export function ingestText(kind: IngestKind, result: IngestReceipt, s: Style = P
1564
1683
  : result.errors ? "review the ingest errors and supported native source contract before retrying"
1565
1684
  : result.remaining ? "run the same ingest command again to continue"
1566
1685
  : result.spooled ? "the next capture write replays rows spooled while the store was busy"
1567
- : state === "skipped" ? "open a native session in this repository before ingesting its transcript" : "none";
1568
- return [`amem ingest ${kind}: ${state}`,
1569
- `${label(s, state === "attention" ? "attention" : state === "skipped" ? "skipped" : "ok")} receipt: ${facts({ files: String(result.files), read: String(result.read), imported: String(result.imported), skipped: String(result.skipped), spooled: String(result.spooled), errors: String(result.errors) })}`,
1570
- `${label(s, result.remaining ? "attention" : "ok")} remaining: ${result.remaining ? "yes" : "no"}`,
1571
- ...(reason ? [`${label(s, "attention")} reason: ${reason}${version ? ` (version ${version})` : ""}`] : []),
1572
- `Next action: ${action}`].join("\n");
1686
+ : state === "skipped" ? "open a native session in this repository before ingesting its transcript" : undefined;
1687
+ const report = new Report(columns ?? 80, s.ascii, { sanitize: singleLine, keepTokensWhole: true });
1688
+ report.header("amem", `Ingest ${kind}`); report.section("Receipt");
1689
+ report.bullet(state === "complete" ? "ok" : state === "skipped" ? "absent" : "warn", state === "complete" ? "Ingest completed." : state === "skipped" ? "No transcript imported." : "Ingest needs attention.");
1690
+ report.kv([["State", state], ["Files", String(result.files)], ["Read", String(result.read)], ["Imported", String(result.imported)], ["Skipped", String(result.skipped)], ["Spooled", String(result.spooled)], ["Errors", String(result.errors)], ["Remaining", result.remaining ? "yes" : "no"], ...(reason ? [["Reason", reason.replace(/_/g, " ") + (version ? ` (version ${version})` : "")] as [string, string]] : [])]);
1691
+ if (action) { report.section("Attention"); report.bullet(state === "attention" ? "warn" : "absent", action); }
1692
+ if (result.remaining || reason === "cursor_busy" || reason === "scope_changed") report.next(`amem ingest ${kind}`);
1693
+ report.line(""); report.line(`Summary: ${result.imported} imported, ${result.skipped} skipped, ${result.errors} errors`);
1694
+ return report.render(s.color).join("\n");
1573
1695
  }
1574
1696
 
1575
- export function formatCliError(error: unknown, usage = false): string {
1697
+ /**
1698
+ * #590 H7: a usage error prints its message, one usage line and the help page that explains it. A message that already
1699
+ * is a `usage:` line stays the one usage line.
1700
+ */
1701
+ export function formatCliError(error: unknown, usage = false, argv: readonly string[] = []): string {
1576
1702
  if (error instanceof DecayApplyError || error instanceof CliPartialApplyError) return error.render();
1577
- const message = errorLine("amem", String((error as Error).message), "", { tty: false })[0]!;
1578
- return usage || (error as { exitCode?: number }).exitCode === 2 ? `${message}\nUsage: amem <command> [options]\nRun 'amem --help' for details.` : message;
1703
+ const raw = String((error as Error).message), message = errorLine("amem", raw, "", { tty: false })[0]!;
1704
+ if (!usage && (error as { exitCode?: number }).exitCode !== 2) return message;
1705
+ const path = commandPath(argv[0] === "help" ? [] : argv);
1706
+ const help = `Run 'amem help${path.length ? ` ${path.join(" ")}` : ""}' for details.`;
1707
+ return raw.startsWith("usage:") ? `${message}\n${help}` : `${message}\nUsage: ${usageLine(path)}\n${help}`;
1579
1708
  }
1580
1709
 
1581
1710
  /** A completed write means rendered output, never evidence of host delivery or citation. */
@@ -1597,7 +1726,7 @@ export async function main(argv = process.argv.slice(2)): Promise<void> {
1597
1726
  prefix = `${paint([{ ...marker, text: markerCell("fail", ascii) }], !argv.includes("--json") && color === true)} `;
1598
1727
  }
1599
1728
  const code = (error as { exitCode?: number }).exitCode ?? ((error as Error).message.startsWith("usage:") ? EXIT.usage : EXIT.fail);
1600
- console.error(prefix + formatCliError(error, code === 2)); process.exitCode = code;
1729
+ console.error(prefix + formatCliError(error, code === 2, argv)); process.exitCode = code;
1601
1730
  }
1602
1731
  if (personStop !== undefined) endLikeSignal(personStop); // after the report, with amem's own handlers already removed
1603
1732
  }