@staix/agent-mem 0.39.0 → 0.41.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-mem",
3
- "version": "0.39.0",
3
+ "version": "0.41.0",
4
4
  "description": "Bounded project memory tools and seven deterministic capture hooks, without a resident worker.",
5
5
  "mcpServers": {
6
6
  "agent-mem": {
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  Curated memory with append-only JSONL logs, a derived SQLite index, short- and long-term tiers, a typed graph, goals with leases, and git sync between machines. Extracted from [agent-hub](https://github.com/STAIxBWLB/agent-hub), with compatible storage and entry IDs.
4
4
 
5
5
  <!-- facts:version -->
6
- Version: 0.39.0. Requires Bun 1.4.2 or later; runtime dependencies: @staix/cli-output.
6
+ Version: 0.41.0. Requires Bun 1.4.2 or later; runtime dependencies: @staix/cli-output.
7
7
  <!-- /facts:version -->
8
8
 
9
9
  ## Quick start
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staix/agent-mem",
3
- "version": "0.39.0",
3
+ "version": "0.41.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",
package/src/cli.ts CHANGED
@@ -38,7 +38,8 @@ import { memoryProjectKey } from "./memory/project.ts";
38
38
  import { CandidateStore, candidateInputId, candidateTargetRevision, type CandidateFilter } from "./memory/candidates.ts";
39
39
  import { candidateOverlaps, candidateOverlapsBatch } from "./memory/candidate-overlaps.ts";
40
40
  import { openCuratedForRead } from "./memory/curated-read.ts";
41
- import { aliasedKeys, appendAlias, appendUnalias, listAliases, readShardedSelection, resolveAlias } from "./memory/shard.ts";
41
+ import { aliasedKeys, appendAlias, appendUnalias, listAliases, readShardedSelection, resolveAlias, shardDir } from "./memory/shard.ts";
42
+ import { curatedCount, projectTransition, recordKeepSeparate, rootsLogPath, transitionKey } from "./memory/roots.ts";
42
43
  import { capacityReport } from "./memory/capacity.ts";
43
44
  import { capacityText, capacityApplyText, capacitySplitText } from "./memory/capacity-text.ts";
44
45
  import { CaptureStore, readCaptureConfigFile, writeCaptureConfigFile, type CaptureConfig } from "./memory/capture.ts";
@@ -78,6 +79,7 @@ import { builtinSet, evalSeeded, evalStore, FIXTURE_PATH, readEvalSet } from "./
78
79
  import { markShown, pendingSummary } from "./memory/candidate-pending.ts";
79
80
  import { buildNote, FAIL_TEMPLATE, hasFailLabel, noteAdd, parseFailTemplate, type FailFields } from "./memory/note-add.ts";
80
81
  import { runEditor } from "./memory/editor.ts";
82
+ import { listAgyReceiptLocations } from "./setup-drift.ts";
81
83
  import { doctorReport } from "./memory/doctor.ts";
82
84
  import { doctorText } from "./memory/doctor-text.ts";
83
85
  import { statusText, type StatusView } from "./memory/status-text.ts";
@@ -316,7 +318,7 @@ function markedSetupApplyError(parsed: ReturnType<typeof parseCommand>, error: u
316
318
 
317
319
  /** Some commands write files despite having no mutates entry; preserve their existing effectful error/receipt treatment. */
318
320
  function markedReadOnly(parsed: ReturnType<typeof parseCommand>): boolean {
319
- return parsed.definition.mutates === undefined && parsed.path[0] !== "setup"
321
+ return parsed.definition.mutates === undefined && (parsed.path[0] !== "setup" || parsed.options["--list"] === true)
320
322
  && !(parsed.path[0] === "eval" && parsed.path[1] === "audit" && parsed.path[2] === "sample")
321
323
  && !(parsed.path[0] === "project" && parsed.path[1] === "export");
322
324
  }
@@ -364,7 +366,7 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
364
366
  if (marked && !argv.includes("--help") && !["--version", "version", "--help", "help", "completion"].includes(argv[0] ?? "")) {
365
367
  const parsed = parseCommand(argv);
366
368
  // Audit outputs and review targets are screened whole for marked reads.
367
- 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") {
369
+ if (parsed.definition.mutates !== undefined || parsed.path[0] === "setup" && parsed.options["--list"] !== true || parsed.path[0] === "eval" && parsed.path[1] === "audit" || parsed.path[0] === "review" && parsed.path[1] === "targets") {
368
370
  let receipt: unknown = output;
369
371
  // Import receipts contain fixed counters named `pii`; they are not row privacy flags.
370
372
  // Screen the complete rendered receipt, including every key and value, as text.
@@ -526,6 +528,8 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
526
528
  throw new AgentUsageError("Sync placement is a home-wide forward-only migration; use only --sync-placement with --dry-run, --apply, --resume or pre-marker --abandon and the writer roots, never combine migration families or deactivate.");
527
529
  if (options["--list-remote"] === true && (modes.length || options["--admit"] !== undefined || options["--from-remote"] === true || options["--writer-root"] !== undefined || options["--confirm"] === true || options["--checkpoint"] === true || options["--plan"] !== undefined))
528
530
  throw new AgentUsageError("Remote realm listing uses only --sync-placement --list-remote and optional --json.");
531
+ if (options["--writers"] === true && (modes.length || ["--admit","--list-remote","--from-remote","--writer-root","--confirm","--checkpoint","--checkpoint-on-bound","--plan"].some(key=>options[key]!==undefined)))
532
+ throw new CommandUsageError("usage: amem migrate --sync-placement --writers [--json]");
529
533
  if (options["--from-remote"] === true && options["--admit"] === undefined)
530
534
  throw new AgentUsageError("--from-remote requires --sync-placement --admit <project>.");
531
535
  if (options["--checkpoint-on-bound"] !== undefined) {
@@ -536,7 +540,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
536
540
  const chosen = [options["--confirm"] === true, options["--resume"] === true, options["--abandon"] === true].filter(Boolean).length;
537
541
  if (options["--admit"] !== undefined || options["--list-remote"] === true || options["--from-remote"] === true || options["--apply"] === true || options["--dry-run"] === true || chosen > 1 || (options["--confirm"] === true) !== (options["--plan"] !== undefined)
538
542
  || (options["--resume"] === true || options["--abandon"] === true) && options["--writer-root"] !== undefined)
539
- throw new AgentUsageError("A placement checkpoint uses --sync-placement --checkpoint --writer-root <install root> (repeat) to preview, then --confirm --plan <saved preview JSON> with the same writer roots, or --resume / --abandon alone.");
543
+ throw new AgentUsageError("A placement checkpoint previews with --sync-placement --checkpoint --writer-root <install root> (repeat), saves the plan with (umask 077; set -C; amem migrate --sync-placement --checkpoint --writer-root <install root> --json > checkpoint-plan.json), then confirms with amem migrate --sync-placement --checkpoint --confirm --plan checkpoint-plan.json and the same writer roots, or uses --resume / --abandon alone.");
540
544
  } else if (options["--plan"] !== undefined) {
541
545
  throw new AgentUsageError("--plan applies only to --sync-placement --checkpoint --confirm.");
542
546
  } else if (options["--admit"] !== undefined) {
@@ -545,6 +549,8 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
545
549
  } else if (options["--confirm"] === true) {
546
550
  throw new AgentUsageError("--confirm applies only to --sync-placement --admit <project> --abandon or --sync-placement --checkpoint --plan <file>; other placement modes keep their own confirmation.");
547
551
  }
552
+ } else if (parsed.path[0] === "migrate" && options["--writers"] !== undefined) {
553
+ throw new CommandUsageError("usage: amem migrate --sync-placement --writers [--json]");
548
554
  } else if (parsed.path[0] === "migrate" && (options["--writer-root"] !== undefined||options["--abandon"]!==undefined||options["--admit"]!==undefined||options["--list-remote"]!==undefined||options["--from-remote"]!==undefined||options["--checkpoint"]!==undefined||options["--plan"]!==undefined)) {
549
555
  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.");
550
556
  }
@@ -558,8 +564,23 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
558
564
  return [`amem skills export: ${report.root}${report.linkedFrom ? ` (linked from ${report.linkedFrom})` : ""}`, "NAME CHANGE PATH / REASON", ...report.actions.map(a => `${a.name.padEnd(20)} ${a.change.padEnd(10)} ${a.path}${a.reason ? ` / ${a.reason}` : ""}`)].join("\n");
559
565
  }
560
566
  if (parsed.path[0] === "setup") {
567
+ if (options["--list"] === true) {
568
+ const { setupMemoryHome } = await import("./setup.ts");
569
+ const home = setupMemoryHome(context.env ?? process.env);
570
+ const result = listAgyReceiptLocations(home);
571
+ const lines = result.receipts.flatMap(receipt => [`${receipt.state}: ${receipt.workspace}`, ` ${receipt.apply}`, ` ${receipt.undo}`]);
572
+ if (result.incomplete) lines.push("Some Antigravity setup receipts could not be listed safely.");
573
+ else if (!lines.length) lines.push("No Antigravity setup receipts found.");
574
+ const output = options["--json"] === true ? JSON.stringify(result, null, 2) : lines.join("\n");
575
+ if (actor === "agent") {
576
+ const policy = configuredPolicy(home, context.cwd ?? process.cwd());
577
+ assertAgentAdministrative(result, policy);
578
+ assertAgentAdministrative(output, policy);
579
+ }
580
+ return output;
581
+ }
561
582
  if (parsed.positionals.length !== 1 || options["--apply"] === true && options["--undo"] === true
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]");
583
+ || 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] | amem setup agy --list [--json]");
563
584
  if (parsed.positionals[0] === "console") {
564
585
  const { consoleSetup, consoleSetupText } = await import("./setup-console.ts");
565
586
  const mode = options["--apply"] === true ? "apply" : options["--undo"] === true ? "undo" : "preview";
@@ -668,6 +689,11 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
668
689
  if (modes.length > 1) throw new Error("migration modes are mutually exclusive");
669
690
  const mode = options["--apply"] ? "apply" : options["--resume"] ? "resume" : options["--deactivate"] ? "deactivate" : "dry-run";
670
691
  if (options["--sync-placement"] === true) {
692
+ if (options["--writers"] === true) {
693
+ const { listPlacementWriters, placementWritersText } = await import("./memory/sync-placement-writer-listing.ts");
694
+ const listing = listPlacementWriters(memoryHome(), fileURLToPath(new URL("..", import.meta.url)));
695
+ return options["--json"] === true ? JSON.stringify(listing, null, 2) : placementWritersText(listing);
696
+ }
671
697
  if (options["--list-remote"] === true) {
672
698
  const { discoverRemotePlacementRealms } = await import("./memory/sync-placement-transport.ts");
673
699
  const realms = await discoverRemotePlacementRealms(memoryHome(), { ...(context.visibility ? { visibility: context.visibility } : {}) });
@@ -682,13 +708,25 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
682
708
  if (options["--checkpoint"] === true) {
683
709
  const person = await import("./memory/sync-placement-checkpoint-person.ts");
684
710
  const writerRoots = repeated(argv, "--writer-root"), ownRoot = fileURLToPath(new URL("..", import.meta.url));
685
- // #567: a retained-history refusal names its cause class (and, for bound, its counts) in --json as a failed result
686
- // with exit 1. Human output keeps the thrown fixed message, which already carries the cause and next step.
687
- const historyJson = (error: unknown): string => {
711
+ // Human output keeps the fixed refusal text. Classified JSON failures exit 1 and carry their safe own fields.
712
+ const checkpointRefusalJson = async (error: unknown): Promise<string> => {
688
713
  if (options["--json"] === true && error instanceof person.PlacementCheckpointError && error.causeClass === "history" && error.history) {
689
714
  context.onExitCode?.(1);
690
715
  return JSON.stringify({ ok: false, refusal: error.history, message: error.message, nextStep: error.history.cause === "bound" ? "retain the history; a window this large needs the multi-plan checkpoint work (#288)" : person.CHECKPOINT_PREVIEW }, null, 2);
691
716
  }
717
+ if (options["--json"] === true && error instanceof person.PlacementCheckpointError && error.causeClass === "writer-below-floor") {
718
+ context.onExitCode?.(1);
719
+ return JSON.stringify({ ok: false, refusal: { cause: error.causeClass }, message: error.message }, null, 2);
720
+ }
721
+ if (options["--json"] === true) {
722
+ const { placementWriterRefusalDetail, placementWriterRefusalText } = await import("./sync-placement-writer-context.ts");
723
+ const refusal = placementWriterRefusalDetail(error);
724
+ const message = refusal && placementWriterRefusalText(error);
725
+ if (refusal && message) {
726
+ context.onExitCode?.(1);
727
+ return JSON.stringify({ ok: false, refusal: { category: refusal.rootCategory, cause: refusal.causeClass }, message }, null, 2);
728
+ }
729
+ }
692
730
  throw error;
693
731
  };
694
732
  if (options["--resume"] === true) { const r = await person.resumePlacementCheckpointPerson(memoryHome()); return options["--json"] === true ? JSON.stringify(r, null, 2) : `sync placement checkpoint: ${r.resumed ? "resumed" : "nothing pending"}; window ${r.window}\nnext: ${r.nextStep}\n`; }
@@ -696,11 +734,11 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
696
734
  if (options["--confirm"] === true) {
697
735
  let saved: unknown;
698
736
  try { saved = JSON.parse(readPrunePlanFile(String(options["--plan"]), undefined, 4 * 1024 * 1024)); } catch { throw new Error("The checkpoint --plan file is unreadable or not the saved preview JSON; rerun amem migrate --sync-placement --checkpoint --json with the writer roots and save its output."); }
699
- const r = await person.confirmPlacementCheckpoint(memoryHome(), saved, { writerRoots, ownRoot }).catch(historyJson);
737
+ const r = await person.confirmPlacementCheckpoint(memoryHome(), saved, { writerRoots, ownRoot }).catch(checkpointRefusalJson);
700
738
  if (typeof r === "string") return r;
701
739
  return options["--json"] === true ? JSON.stringify(r, null, 2) : `sync placement checkpoint: committed window ${r.window} with one writer renewal (plan ${r.planHash})\nnext: ${r.nextStep}\n`;
702
740
  }
703
- const preview = await person.previewPlacementCheckpoint(memoryHome(), { writerRoots, ownRoot }).catch(historyJson);
741
+ const preview = await person.previewPlacementCheckpoint(memoryHome(), { writerRoots, ownRoot }).catch(checkpointRefusalJson);
704
742
  if (typeof preview === "string") return preview;
705
743
  if (options["--json"] === true) return JSON.stringify(preview, null, 2);
706
744
  const { placementJournalObjectCompositionText } = await import("./memory/sync-placement-journal-storage.ts"), h = preview.headroom;
@@ -710,7 +748,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
710
748
  + `completed plan: ${h.completedPlan.slots} slots + ${h.completedPlan.reservedJournalChunks} reserved journal chunks; prospective plan: ${h.prospectivePlan.state === "cache-only" ? `${h.prospectivePlan.slots} slots + ${h.prospectivePlan.reservedJournalChunks} reserved journal chunks (cache-only; remote may have changed)` : h.prospectivePlan.state === "none" ? "none" : "unavailable without current remote evidence; using completed history"}\n`
711
749
  + `headroom after checkpoint: ${h.remaining} of ${h.limit} (live ${h.liveAfter}, next renewal ${h.nextRenewal}, largest plan ${h.largestPlan.slots} + ${h.largestPlan.reservedJournalChunks} reserved journal chunks)\n`
712
750
  + `home floor ${preview.requiredHomeFloor}: ${preview.floorReady ? "ready" : `missing; preview amem formats raise home ${preview.requiredHomeFloor}, then --confirm it`}; writers ${preview.writers}; plan ${preview.planHash}\n`
713
- + `next: save this preview with --json, then ${preview.nextStep}\n`;
751
+ + `next: ${preview.nextStep}\n`;
714
752
  }
715
753
  if (options["--admit"] !== undefined) {
716
754
  const { previewRealmAdmission, planRealmAbandon, applyRealmAdmission } = await import("./memory/sync-placement-realm-admission.ts");
@@ -775,7 +813,10 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
775
813
  candidates: (() => { const bound = boundProject(), summary = pendingSummary(where.home, [bound, ...aliasedKeys(where.home, bound)], Date.now(), true);
776
814
  if (summary === null) return { unavailable: "candidates.db exists but cannot be read" };
777
815
  return { ...summary, ...(summary.dueWithin7Days ? { warning: `${summary.dueWithin7Days} candidate${summary.dueWithin7Days === 1 ? "" : "s"} within 7 days of expiry: run \`amem review walk\`` } : {}) }; })(),
778
- ...shardMigrationStatus(where.home) };
816
+ ...shardMigrationStatus(where.home),
817
+ // #581: read-only (the SessionStart hook is the only writer of roots.jsonl); present only during a transition, so the default shape is unchanged.
818
+ ...(() => { try { const t = projectTransition(where.home, policyCwd, transitionKey(policyCwd), key => curatedCount(where.home, key, shardDir));
819
+ return t ? { projectTransition: { previousKey: t.previousKey, key: t.key, previousCuratedNotes: t.previousCuratedNotes, aliasCommand: t.aliasCommand, keepCommand: t.keepCommand } } : {}; } catch { return {}; } })() };
779
820
  return options["--json"] ? JSON.stringify(status, null, 2) : statusText(status as unknown as StatusView, outputStyle(context, options), reportOptions(context, options));
780
821
  }
781
822
  if (parsed.path[0] === "formats" && parsed.path[1] === "raise") {
@@ -1291,6 +1332,20 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1291
1332
  : result.checked ? `no ${source} memory found; checked ${result.checked.join(" and ")}`
1292
1333
  : `imported ${result.added} ${source} candidates from ${result.files} files (${result.read} records, ${result.pending.count} pending); skipped ${result.skipped.rules} rule files, ${result.skipped.policy} policy/secret records, ${result.skipped.invalid} invalid records and ${result.skipped.truncated} oversized inputs${result.queueFull ? "; candidate queue is full" : result.limitReached ? "; per-run candidate cap reached" : ""}`;
1293
1334
  }
1335
+ if (sub === "project" && parsed.path[1] === "keep-separate") {
1336
+ // #581: end a project-key transition for this directory without joining the keys. Preview without --confirm.
1337
+ const home = memoryHome(), key = transitionKey(policyCwd);
1338
+ const transition = projectTransition(home, policyCwd, key, previous => curatedCount(home, previous, shardDir));
1339
+ if (!transition) throw Object.assign(new Error("no project key transition for this directory: nothing to keep apart. Run amem status to see the bound project."), { exitCode: 2 });
1340
+ if (options["--confirm"] !== true) {
1341
+ const preview = { preview: true, previousKey: transition.previousKey, key: transition.key, previousCuratedNotes: transition.previousCuratedNotes, file: rootsLogPath(home), confirmCommand: "amem project keep-separate --confirm" };
1342
+ return options["--json"] ? JSON.stringify(preview, null, 2)
1343
+ : `preview: keep ${transition.key} apart from ${transition.previousKey} for this directory. Appends one keep line to ${rootsLogPath(home)}; no key is joined and no note moves. Run: amem project keep-separate --confirm`;
1344
+ }
1345
+ const line = recordKeepSeparate(home, policyCwd, transition);
1346
+ return options["--json"] ? JSON.stringify({ kept: { previousKey: line.prev, key: line.key, at: line.at }, file: rootsLogPath(home) }, null, 2)
1347
+ : `kept ${line.key} apart from ${line.prev} for this directory; the notice stops. To join them later: ${transition.aliasCommand}`;
1348
+ }
1294
1349
  if (sub === "project") {
1295
1350
  const op = parsed.path[1]!, [requested] = parsed.positionals;
1296
1351
  if (!requested) throw new Error(`usage: amem project ${op} <key>`);
@@ -1298,8 +1353,8 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1298
1353
  if (typeof options["--to"] !== "string") throw new Error("usage: amem project export <key> --to <file>");
1299
1354
  const format = (options["--format"] ?? "json") as ProjectExportFormat;
1300
1355
  // The bundle leaves the home, so it is screened by the configured policy (secrets, personal data, the configured patterns and deny paths).
1301
- const result = await exportProject(memoryHome(), requested, { to: options["--to"], policy: policyOf(), format });
1302
- return options["--json"] ? JSON.stringify(result, null, 2) : `exported ${result.project} to ${result.file} as ${result.format}: ${result.counts.capture} capture rows, ${result.counts.curated} notes, ${result.counts.goals} goals, ${result.counts.workLists} work lists${result.withheld ? `; ${result.withheld} withheld by the screen` : ""}`;
1356
+ const result = await exportProject(memoryHome(), requested, { to: options["--to"], policy: policyOf(), format, includeCapture: options["--include-capture"] === true });
1357
+ return options["--json"] ? JSON.stringify(result, null, 2) : `exported ${result.project} to ${result.file} as ${result.format}: ${result.counts.curated} notes, ${result.counts.goals} goals, ${result.counts.workLists} work lists, ${result.counts.capture} capture rows (${result.capture === "included" ? "included" : "excluded; add --include-capture"}); ${result.withheld} withheld by the screen`;
1303
1358
  }
1304
1359
  if (op === "import") {
1305
1360
  if (typeof options["--from"] !== "string") throw new Error("usage: amem project import <key> --from <file.jsonl> [--confirm] [--allow-shared]");
@@ -48,8 +48,8 @@ export const COMMANDS: Record<string, CommandDefinition> = {
48
48
  options: { ...json("the queued candidates"), "--project": text("This project's key", "Another project is refused; run from its directory.") } },
49
49
  setup: { group: "setup", description: "Preview or apply MCP setup and capture hooks",
50
50
  details: "Covers native coding CLIs, or the acon console plugin manifest (console). Apply and undo use explicit flags.",
51
- examples: ["amem setup claude", "amem setup all --apply"],
52
- options: { ...json("the setup plan"), "--apply": flag("Apply the previewed setup"), "--undo": flag("Restore the original configuration"),
51
+ examples: ["amem setup claude", "amem setup all --apply", "amem setup agy --list"],
52
+ options: { ...json("the setup plan or receipt list"), "--list": flag("List agy receipt workspaces and repair commands", "Use only with the agy target."), "--apply": flag("Apply the previewed setup"), "--undo": flag("Restore the original configuration"),
53
53
  "--verbose": flag("Show static notes and history lines (human output only)"),
54
54
  "--root": path("Register this absolute install root", "Such as <install>/releases/<version>/, resolved to its real path, instead of the running one."),
55
55
  "--adopt-current": flag("With --apply: adopt the current wiring", "Keeps a stale setup receipt aside (its entries were replaced at another install root) and adopts the current wiring, which --undo restores.") },
@@ -121,9 +121,9 @@ export const COMMANDS: Record<string, CommandDefinition> = {
121
121
  options: { ...json("the gc result"), "--confirm": flag("Evict now; without it, preview only"), "--batches": number("Evict windows per shard (1..1000, default 1)") } },
122
122
  project: { group: "maintenance", description: "Export, import, archive or forget one project", options: json("the project receipt"), commands: {
123
123
  export: { description: "Write one project's memory to a new export file",
124
- details: "Capture, curated notes, goals and work lists, as JSON, JSONL or Markdown. Never overwrites.",
125
- examples: ["amem project export repo@1234abcd --to ./repo.json"],
126
- options: { ...json("the export receipt"), "--to": path("Destination file, outside the memory home"), "--format": { description: "Portable format (default json)", value: ["json", "jsonl", "markdown"] }, ...policy },
124
+ details: "Curated notes, goals and work lists, as JSON, JSONL or Markdown; capture only with --include-capture. Never overwrites.",
125
+ examples: ["amem project export repo@1234abcd --to ./repo.json", "amem project export repo@1234abcd --to ./repo.json --include-capture"],
126
+ options: { ...json("the export receipt"), "--to": path("Destination file, outside the memory home"), "--include-capture": flag("Also export capture rows, screened"), "--format": { description: "Portable format (default json)", value: ["json", "jsonl", "markdown"] }, ...policy },
127
127
  args: [{ name: "key" }] },
128
128
  import: { description: "Preview or re-import notes from a JSONL export", details: "Keeps the original entry ids.",
129
129
  examples: ["amem project import repo@1234abcd --from ./repo.jsonl", "amem project import repo@1234abcd --from ./repo.jsonl --confirm"],
@@ -135,6 +135,9 @@ export const COMMANDS: Record<string, CommandDefinition> = {
135
135
  options: json("the unarchive receipt"), args: [{ name: "key" }], mutates: true },
136
136
  forget: { description: "Forget one project for good", details: "An append-only op; previews without --confirm.", examples: ["amem project forget repo@1234abcd", "amem project forget repo@1234abcd --confirm"],
137
137
  options: { ...json("the forget receipt"), "--confirm": flag("Record the forget after the preview") }, args: [{ name: "key" }], mutates: "confirm" },
138
+ "keep-separate": { description: "Keep this directory's new project key apart", details: "Ends a project key transition without joining; previews without --confirm.",
139
+ examples: ["amem project keep-separate", "amem project keep-separate --confirm"],
140
+ options: { ...json("the keep-separate preview or receipt"), "--confirm": flag("Record the choice after the preview") }, mutates: "confirm" },
138
141
  } },
139
142
  show: { group: "read", description: "Show a note", examples: ["amem show abcdef12", "amem show abcdef12 --history"], options: { ...json("the note"), ...history }, args: [{ name: "id" }] },
140
143
  graph: { group: "read", description: "Show the graph around a note or node", examples: ["amem graph abcdef12", "amem graph abcdef12 --hops 2"],
@@ -234,6 +237,7 @@ export const COMMANDS: Record<string, CommandDefinition> = {
234
237
  "--public-prune-view": flag("Enable the v2 public prune view on a split", "Forward-only, on an active split."),
235
238
  "--sync-placement": flag("Activate placement sync on this memory home", "Forward-only. Previews by default and applies with --apply; no automatic migration or renewal."),
236
239
  "--list-remote": flag("List remote project refs outside the inventory", "By hash, outside the active inventory."),
240
+ "--writers": flag("List writer installs and the roots to declare", "Read-only: inventory, running install, setup receipts and the saving-preview command."),
237
241
  "--abandon": flag("Discard an interrupted placement attempt", "Pre-commit only. Initial activation requires both markers to match their original v2 bytes; realm admission requires --confirm."),
238
242
  "--admit": text("Admit one new curated project realm", "A realm that appeared after activation, into the same epoch. Previews without --apply."),
239
243
  "--from-remote": flag("Admit the named remote-only realm", "Uses the configured placement sync remote."),
@@ -338,6 +342,10 @@ export function parseCommand(argv: readonly string[]): ParsedCommand {
338
342
  const argument = definition.args?.[i];
339
343
  if (argument?.values && !argument.values.includes(positionals[i]!)) throw new CommandUsageError(`${argument.name} takes ${argument.values.join(" or ")}`);
340
344
  }
345
+ if (path[0] === "setup" && options["--list"] === true && options["--help"] !== true
346
+ && (positionals[0] !== "agy" || ["--apply", "--undo", "--root", "--adopt-current", "--verbose"].some(flag => options[flag] !== undefined))) {
347
+ throw new CommandUsageError("usage: amem setup agy --list [--json]");
348
+ }
341
349
  const allowed = path[0] === "version" && options["--version"] === true ? completionDefinitions()[0]!.options : completionDefinitions().find(row => row.path.join(" ") === path.join(" "))!.options;
342
350
  for (const name of Object.keys(options)) if (!allowed[name]) throw new CommandUsageError(`unknown option ${name} for ${path.join(" ")}`);
343
351
  const outputOptionIndexes = new Set<number>();
package/src/hooks.ts CHANGED
@@ -18,6 +18,7 @@ import { canonicalPath, realPath } from "./memory/platform.ts";
18
18
  import { createStandalonePolicy, type MemoryPolicy, type StandalonePolicyOptions } from "./memory/policy.ts";
19
19
  import { configuredPolicyOptions, loadAmemConfig, recordsEnabled, repoConfigRoot } from "./memory/config.ts";
20
20
 
21
+ import { observeRoot } from "./memory/roots.ts";
21
22
  import { HOOK_EVENTS, HOOK_INPUT_BYTES, HOOK_CONTEXT_BYTES, HOOK_OUTPUT_BYTES, isHookTranscriptProgress, type HookTranscriptProgress } from "./hook-contract.ts";
22
23
  export { HOOK_EVENTS, HOOK_INPUT_BYTES, HOOK_CONTEXT_BYTES, HOOK_OUTPUT_BYTES, type HookEvent } from "./hook-contract.ts";
23
24
  // Leave 10ms of the external 150ms R2 budget for teardown and the metrics write.
@@ -333,6 +334,9 @@ async function sessionInParent(input: unknown, options: HookOptions, base: strin
333
334
  const [identity, owner, briefModule] = metadata;
334
335
  if (identity.status !== "fulfilled" || owner.status !== "fulfilled" || briefModule.status !== "fulfilled") throw new Error("hook metadata unavailable");
335
336
  const project = resolveAlias(base, identity.value);
337
+ // #581: the one writer of roots.jsonl lines: first sight of this working root, or a re-bind once an alias joined
338
+ // its recorded key. One bounded read and at most one 0600 append; observeRoot never throws, so it cannot fail the hook.
339
+ observeRoot(base, cwd, identity.value);
336
340
  const signature = owner.value;
337
341
  const { sessionStartBrief } = briefModule.value;
338
342
  if (remaining() <= 0) return result;
@@ -13,6 +13,7 @@ const SECTION_TITLE: Record<keyof DoctorReport["sections"], string> = {
13
13
  spool: "pending hook spool",
14
14
  setup: "native setup registrations",
15
15
  masked: "forgotten or pruned entries (informational)",
16
+ transition: "project key transition",
16
17
  };
17
18
 
18
19
  /**
@@ -58,7 +59,11 @@ export function hintFinding(name: string, hint: string, section: Record<string,
58
59
  /** #590 C6: a writer refusal is one finding; each command it names is one `→` line. The fixed refusal text stays in `--json`. */
59
60
  export function writerFinding(section: Record<string, unknown>): Finding {
60
61
  const reason = String(section.reason ?? "");
61
- const commands = [...reason.matchAll(/amem (?:migrate --sync-placement --(?:dry-run|resume|abandon)|formats raise home [0-9.]+|setup [a-z]+ --(?:apply|undo))/g)].map(match => match[0]);
62
+ // #624: the checkpoint renewal comes first. Its saving preview is a subshell, so the finding names the bare checkpoint command; the reason keeps the saving form.
63
+ const commands = reason.includes("amem setup agy --list") ? ["amem setup agy --list"] : [...reason.matchAll(/amem (?:migrate --sync-placement --(?:checkpoint|dry-run|resume|abandon)|formats raise home [0-9.]+|setup [a-z]+ --(?:apply|undo))/g)].map(match => match[0]);
64
+ // #639: a renewal needs the complete root list, so the read-only listing that prints it comes first. A stale agy receipt
65
+ // (#636) is fixed first, so its single command stays alone.
66
+ if (commands.includes("amem migrate --sync-placement --checkpoint")) commands.unshift("amem migrate --sync-placement --writers");
62
67
  return { text: `placement writer proof is ${section.cause ?? "unverified"} (${section.category ?? "unknown"} category)`, next: [...new Set(commands)] };
63
68
  }
64
69
 
@@ -105,6 +110,7 @@ function sectionFact(name: string, detail: Record<string, unknown>, now: number)
105
110
  ...(Array.isArray(detail.examples) && detail.examples.length ? [`examples ${(detail.examples as unknown[]).map(item => Array.isArray(item) ? item.join(" = ") : String(item)).join(", ")}`] : [])];
106
111
  if (name === "stale" && typeof detail.checked === "number") return [`${detail.checked} checked, ${detail.missingReferences ?? 0} missing`,
107
112
  ...(Array.isArray(detail.examples) && detail.examples.length ? [`examples ${(detail.examples as unknown[]).join(", ")}`] : [])];
113
+ if (name === "transition") return [`was ${detail.previousKey}${typeof detail.previousCuratedNotes === "number" ? ` (${detail.previousCuratedNotes} curated notes)` : ""}, now ${detail.key}; see Attention`];
108
114
  if (name === "masked") return [`${detail.forgets ?? 0} forgotten, ${detail.prunes ?? 0} pruned; see docs/purge.md`];
109
115
  if (name === "candidates") return [`${detail.count ?? 0} pending${detail.unshown ? `, ${detail.unshown} never shown` : ""}${detail.oldestExpiresInDays !== null && detail.oldestExpiresInDays !== undefined ? `, oldest expires in ${detail.oldestExpiresInDays} d` : ""}`];
110
116
  const { examples, note: _note, ...rest } = detail;
@@ -120,6 +126,7 @@ export function doctorText(report: DoctorReport, s: Style = PLAIN, opts: ReportT
120
126
  const findings: Finding[] = [];
121
127
  for (const [name, item] of entries) {
122
128
  if (name === "writers" && item.status === "attention") findings.push(writerFinding(item));
129
+ if (name === "transition") findings.push({ text: `this directory resolved to ${item.previousKey} before and to ${item.key} now`, next: [String(item.aliasCommand), String(item.keepCommand)] });
123
130
  if (item.hint) findings.push(hintFinding(name, item.hint, item));
124
131
  if (name === "capture" && item.clis) for (const [cli, row] of Object.entries(item.clis as Record<string, { hint?: string }>)) if (row.hint) findings.push(captureFinding(cli, row.hint));
125
132
  }
@@ -20,6 +20,7 @@ import { processLiveness, withGitTimeout } from "./platform.ts";
20
20
  import { endLikeSignal, STOP_SIGNALS } from "./sync-cadence.ts";
21
21
  import { boundRepoRoot } from "./repo-scope.ts";
22
22
  import { aliasedKeys, shardDir } from "./shard.ts";
23
+ import { curatedCount, projectTransition, transitionKey, transitionNotice } from "./roots.ts";
23
24
  import type { MemoryStore, View } from "./store.ts";
24
25
  import { nextSyncAt, readSyncState, remoteConfigured, syncDue, usableState } from "./sync-cadence.ts";
25
26
  import { readSyncStatus } from "./sync-progress.ts";
@@ -77,6 +78,8 @@ export interface DoctorReport {
77
78
  setup?: Section;
78
79
  /** #551, additive: present on a placement home only - the writer verification the next sync performs. */
79
80
  writers?: Section;
81
+ /** #581, additive: present only when this working root last resolved to a different, unjoined key. Read-only. */
82
+ transition?: Section;
80
83
  };
81
84
  }
82
85
 
@@ -91,6 +94,13 @@ function maskedSection(curated: MemoryStore | undefined): { masked?: Section } {
91
94
  if (!forgets && !prunes) return {};
92
95
  return { masked: { status: "ok", forgets, prunes, note: "masked entries stay in the local log and in sync history; see docs/purge.md" } };
93
96
  }
97
+ /** #581: a read of roots.jsonl and aliases.jsonl only; doctor never writes a root line. */
98
+ function transitionSection(options: DoctorOptions): { transition?: Section } {
99
+ try {
100
+ const transition = projectTransition(options.home, options.cwd, transitionKey(options.cwd), key => curatedCount(options.home, key, shardDir));
101
+ return transition ? { transition: { status: "attention", ...transition, notice: transitionNotice(transition) } } : {};
102
+ } catch { return {}; }
103
+ }
94
104
  const ids = (list: string[]): string[] => list.slice(0, MAX_IDS).map(id => id.slice(0, 8));
95
105
  const regularDir = (path: string): boolean => { try { const stat = lstatSync(path); return stat.isDirectory() && !stat.isSymbolicLink(); } catch { return false; } };
96
106
  const regularFile = (path: string): boolean => { try { const stat = lstatSync(path); return stat.isFile() && !stat.isSymbolicLink(); } catch { return false; } };
@@ -633,7 +643,7 @@ async function runDoctor(options: DoctorOptions, scratch: string): Promise<Docto
633
643
  try {
634
644
  await tick();
635
645
  const writers = await writersSection(options);
636
- sections = { duplicates, stale, candidates, capture: captureSection(options), brief: await briefSection(options, curated, workBase, copyFailed), index, readers: readersSection(options), policy: policySection(options), cadence: cadenceSection(options), drops: dropsSection(options), spool: spoolSection(options), setup, ...(writers ? { writers } : {}), ...maskedSection(curated) };
646
+ sections = { duplicates, stale, candidates, capture: captureSection(options), brief: await briefSection(options, curated, workBase, copyFailed), index, readers: readersSection(options), policy: policySection(options), cadence: cadenceSection(options), drops: dropsSection(options), spool: spoolSection(options), setup, ...(writers ? { writers } : {}), ...maskedSection(curated), ...transitionSection(options) };
637
647
  await tick(); // a signal that arrived during the last synchronous stage is handled while the guard is still installed
638
648
  } finally { curated?.close(); }
639
649
  return { schema: DOCTOR_SCHEMA, status: worst(Object.values(sections).map(section => section.status)), home: { path: options.home, source: options.homeSource }, project: options.project, sections };
@@ -29,7 +29,9 @@ export const EXPORT_SCHEMA = "agent-mem.project-export/v1";
29
29
  export const exportHooks: { afterCheck?: (file: string) => void } = {};
30
30
  export type ProjectExportFormat = "json" | "jsonl" | "markdown";
31
31
  export interface ExportCounts { capture: number; curated: number; goals: number; workLists: number }
32
- export interface ExportResult { file: string; project: string; format: ProjectExportFormat; counts: ExportCounts; withheld: number }
32
+ export interface ExportResult { file: string; project: string; format: ProjectExportFormat; counts: ExportCounts; withheld: number;
33
+ /** #582: capture rows leave the home only with `--include-capture`; `counts.capture` is 0 when excluded. */
34
+ capture: "included" | "excluded" }
33
35
  type ExportSection = keyof ExportCounts;
34
36
  const PAGE = 500;
35
37
 
@@ -65,7 +67,8 @@ function markdownRecord(section: ExportSection, value: unknown): string {
65
67
  return `${lines.join("\n")}\n`;
66
68
  }
67
69
 
68
- export async function exportProject(base: string, key: string, opts: { to: string; policy?: MemoryPolicy; format?: ProjectExportFormat }): Promise<ExportResult> {
70
+ export async function exportProject(base: string, key: string, opts: { to: string; policy?: MemoryPolicy; format?: ProjectExportFormat; includeCapture?: boolean }): Promise<ExportResult> {
71
+ const includeCapture = opts.includeCapture === true;
69
72
  const project = requireShard(base, key), format = opts.format ?? "json";
70
73
  if (!["json", "jsonl", "markdown"].includes(format)) throw new Error("export format must be json, jsonl or markdown");
71
74
  if (projectState(base, project) === "forgotten") throw new Error(`project ${project} is forgotten: it cannot be exported`);
@@ -96,7 +99,9 @@ export async function exportProject(base: string, key: string, opts: { to: strin
96
99
  if (format === "jsonl") out(`${JSON.stringify({ schema: EXPORT_SCHEMA, project, exportedAt, type: "header", aliases: aliasedKeys(base, project) })}\n`);
97
100
  else if (format === "markdown") out(`# Project export ${markdownInline(JSON.stringify(project))}\n\nExported at ${exportedAt}\n`);
98
101
  begin(`{"schema":${JSON.stringify(EXPORT_SCHEMA)},"project":${JSON.stringify(project)},"exportedAt":${JSON.stringify(exportedAt)},"capture":[`, "capture", "Capture");
99
- const shard = walkShards(base).find(candidate => candidate.key === project);
102
+ // #582: capture is opt-in. Without it no capture database is opened at all; the section stays, empty.
103
+ if (!includeCapture && format === "markdown") out("excluded; add --include-capture to export capture rows\n");
104
+ const shard = includeCapture ? walkShards(base).find(candidate => candidate.key === project) : undefined;
100
105
  for (const dir of shard?.machineDirs ?? []) {
101
106
  const dbFile = join(dir, "capture.db");
102
107
  if (!existsSync(dbFile)) continue;
@@ -153,5 +158,5 @@ export async function exportProject(base: string, key: string, opts: { to: strin
153
158
  for (const store of stores) { try { store.close(); } catch { /* best effort */ } }
154
159
  }
155
160
  closeSync(fd);
156
- return { file, project, format, counts, withheld };
161
+ return { file, project, format, counts, withheld, capture: includeCapture ? "included" : "excluded" };
157
162
  }
@@ -1,5 +1,5 @@
1
1
  import { lstatSync, mkdirSync, readdirSync, rmSync } from "node:fs";
2
- import { join } from "node:path";
2
+ import { basename, join } from "node:path";
3
3
  import { readProfileJSON, writeProfileJSON } from "./generation.ts";
4
4
  import { readerAdmissionDatabase } from "./mutation.ts";
5
5
  import { processLiveness, processSignature, realPath } from "./platform.ts";
@@ -48,6 +48,40 @@ function ownedLease(memoryDir: string, file: string, signature: string, scope: L
48
48
  if (!lease || lease.pid !== process.pid || lease.signature !== signature) throw new Error("reader lease ownership is unavailable");
49
49
  }
50
50
 
51
+ /** #632: how many lease names one registration scans; later registrations clear what a large backlog leaves. */
52
+ const GONE_LEASE_SCAN_LIMIT = 256;
53
+
54
+ /** One syscall, no identity probe: only ESRCH proves the recorded process is gone. */
55
+ function pidIsGone(pid: number): boolean {
56
+ try { process.kill(pid, 0); return false; }
57
+ catch (error) { return (error as NodeJS.ErrnoException).code === "ESRCH"; }
58
+ }
59
+
60
+ /** #632: a registration clears leases of processes that are provably gone in its own scope, so doctor's
61
+ * `readers` attention state does not need a migration. The caller holds the admission fence, and each
62
+ * candidate is re-read there: a pid that exists (reused included), an unreadable or unverifiable file,
63
+ * a link or any non-regular file stays exactly as it is, and nothing here throws. Migration admission
64
+ * keeps its pid-plus-signature test, which is what clears a reused pid's lease. */
65
+ function removeGoneLeases(memoryDir: string, scope: LeaseScope, own: string): void {
66
+ const dir = join(memoryDir, leaseFolder(scope));
67
+ let names: string[];
68
+ try { names = readdirSync(dir).filter(name => name.endsWith(".json")).sort().slice(0, GONE_LEASE_SCAN_LIMIT); }
69
+ catch { return; }
70
+ for (const name of names) {
71
+ if (name === own) continue;
72
+ const file = join(dir, name);
73
+ try {
74
+ const stat = lstatSync(file, { throwIfNoEntry: false });
75
+ if (!stat || !stat.isFile()) continue;
76
+ const lease = readLease(memoryDir, file, scope);
77
+ if (!lease || !pidIsGone(lease.pid)) continue;
78
+ const again = readLease(memoryDir, file, scope);
79
+ if (!again || again.pid !== lease.pid) continue;
80
+ rmSync(file);
81
+ } catch { /* unreadable or unverifiable evidence, or a file that moved under us, stays as it is */ }
82
+ }
83
+ }
84
+
51
85
  function admitReader(memoryDir: string): void {
52
86
  // The profile lock is created under the same reader admission fence, then held across migration awaits.
53
87
  // Even a malformed or stale marker refuses admission; only the profile-lock owner may reclaim it.
@@ -89,6 +123,8 @@ export function registerReaderLease(memoryDir: string, options: { busyTimeoutMs?
89
123
  }
90
124
  const dir = checkReadersDir(memoryDir, scope);
91
125
  mkdirSync(dir, { recursive: true, mode: 0o700 });
126
+ // #632: a first registration for this file clears leases of provably gone processes; nested readers returned above.
127
+ removeGoneLeases(memoryDir, scope, basename(file));
92
128
  // A failed earlier close may have retained evidence. Never overwrite an unverifiable replacement.
93
129
  const existing = readLease(memoryDir, file, scope);
94
130
  if (existing && (existing.pid !== process.pid || existing.signature !== signature)) throw new Error("reader lease ownership is unavailable");