@staix/agent-mem 0.39.0 → 0.40.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.40.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.40.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.40.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";
@@ -536,7 +537,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
536
537
  const chosen = [options["--confirm"] === true, options["--resume"] === true, options["--abandon"] === true].filter(Boolean).length;
537
538
  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
539
  || (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.");
540
+ 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
541
  } else if (options["--plan"] !== undefined) {
541
542
  throw new AgentUsageError("--plan applies only to --sync-placement --checkpoint --confirm.");
542
543
  } else if (options["--admit"] !== undefined) {
@@ -710,7 +711,7 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
710
711
  + `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
712
  + `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
713
  + `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`;
714
+ + `next: ${preview.nextStep}\n`;
714
715
  }
715
716
  if (options["--admit"] !== undefined) {
716
717
  const { previewRealmAdmission, planRealmAbandon, applyRealmAdmission } = await import("./memory/sync-placement-realm-admission.ts");
@@ -775,7 +776,10 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
775
776
  candidates: (() => { const bound = boundProject(), summary = pendingSummary(where.home, [bound, ...aliasedKeys(where.home, bound)], Date.now(), true);
776
777
  if (summary === null) return { unavailable: "candidates.db exists but cannot be read" };
777
778
  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) };
779
+ ...shardMigrationStatus(where.home),
780
+ // #581: read-only (the SessionStart hook is the only writer of roots.jsonl); present only during a transition, so the default shape is unchanged.
781
+ ...(() => { try { const t = projectTransition(where.home, policyCwd, transitionKey(policyCwd), key => curatedCount(where.home, key, shardDir));
782
+ return t ? { projectTransition: { previousKey: t.previousKey, key: t.key, previousCuratedNotes: t.previousCuratedNotes, aliasCommand: t.aliasCommand, keepCommand: t.keepCommand } } : {}; } catch { return {}; } })() };
779
783
  return options["--json"] ? JSON.stringify(status, null, 2) : statusText(status as unknown as StatusView, outputStyle(context, options), reportOptions(context, options));
780
784
  }
781
785
  if (parsed.path[0] === "formats" && parsed.path[1] === "raise") {
@@ -1291,6 +1295,20 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1291
1295
  : result.checked ? `no ${source} memory found; checked ${result.checked.join(" and ")}`
1292
1296
  : `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
1297
  }
1298
+ if (sub === "project" && parsed.path[1] === "keep-separate") {
1299
+ // #581: end a project-key transition for this directory without joining the keys. Preview without --confirm.
1300
+ const home = memoryHome(), key = transitionKey(policyCwd);
1301
+ const transition = projectTransition(home, policyCwd, key, previous => curatedCount(home, previous, shardDir));
1302
+ 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 });
1303
+ if (options["--confirm"] !== true) {
1304
+ const preview = { preview: true, previousKey: transition.previousKey, key: transition.key, previousCuratedNotes: transition.previousCuratedNotes, file: rootsLogPath(home), confirmCommand: "amem project keep-separate --confirm" };
1305
+ return options["--json"] ? JSON.stringify(preview, null, 2)
1306
+ : `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`;
1307
+ }
1308
+ const line = recordKeepSeparate(home, policyCwd, transition);
1309
+ return options["--json"] ? JSON.stringify({ kept: { previousKey: line.prev, key: line.key, at: line.at }, file: rootsLogPath(home) }, null, 2)
1310
+ : `kept ${line.key} apart from ${line.prev} for this directory; the notice stops. To join them later: ${transition.aliasCommand}`;
1311
+ }
1294
1312
  if (sub === "project") {
1295
1313
  const op = parsed.path[1]!, [requested] = parsed.positionals;
1296
1314
  if (!requested) throw new Error(`usage: amem project ${op} <key>`);
@@ -1298,8 +1316,8 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1298
1316
  if (typeof options["--to"] !== "string") throw new Error("usage: amem project export <key> --to <file>");
1299
1317
  const format = (options["--format"] ?? "json") as ProjectExportFormat;
1300
1318
  // 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` : ""}`;
1319
+ const result = await exportProject(memoryHome(), requested, { to: options["--to"], policy: policyOf(), format, includeCapture: options["--include-capture"] === true });
1320
+ 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
1321
  }
1304
1322
  if (op === "import") {
1305
1323
  if (typeof options["--from"] !== "string") throw new Error("usage: amem project import <key> --from <file.jsonl> [--confirm] [--allow-shared]");
@@ -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"],
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,8 @@ 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.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]);
62
64
  return { text: `placement writer proof is ${section.cause ?? "unverified"} (${section.category ?? "unknown"} category)`, next: [...new Set(commands)] };
63
65
  }
64
66
 
@@ -105,6 +107,7 @@ function sectionFact(name: string, detail: Record<string, unknown>, now: number)
105
107
  ...(Array.isArray(detail.examples) && detail.examples.length ? [`examples ${(detail.examples as unknown[]).map(item => Array.isArray(item) ? item.join(" = ") : String(item)).join(", ")}`] : [])];
106
108
  if (name === "stale" && typeof detail.checked === "number") return [`${detail.checked} checked, ${detail.missingReferences ?? 0} missing`,
107
109
  ...(Array.isArray(detail.examples) && detail.examples.length ? [`examples ${(detail.examples as unknown[]).join(", ")}`] : [])];
110
+ if (name === "transition") return [`was ${detail.previousKey}${typeof detail.previousCuratedNotes === "number" ? ` (${detail.previousCuratedNotes} curated notes)` : ""}, now ${detail.key}; see Attention`];
108
111
  if (name === "masked") return [`${detail.forgets ?? 0} forgotten, ${detail.prunes ?? 0} pruned; see docs/purge.md`];
109
112
  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
113
  const { examples, note: _note, ...rest } = detail;
@@ -120,6 +123,7 @@ export function doctorText(report: DoctorReport, s: Style = PLAIN, opts: ReportT
120
123
  const findings: Finding[] = [];
121
124
  for (const [name, item] of entries) {
122
125
  if (name === "writers" && item.status === "attention") findings.push(writerFinding(item));
126
+ 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
127
  if (item.hint) findings.push(hintFinding(name, item.hint, item));
124
128
  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
129
  }
@@ -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
  }
@@ -0,0 +1,145 @@
1
+ import { createHash } from "node:crypto";
2
+ import { appendFileSync, closeSync, fstatSync, lstatSync, openSync, readFileSync, readSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { Database } from "bun:sqlite";
5
+ import { effectiveAliases } from "./aliases.ts";
6
+ import { indexFileName } from "./index-file.ts";
7
+ import { realPath } from "./platform.ts";
8
+ import { memoryProjectKey } from "./project.ts";
9
+
10
+ /**
11
+ * #581: which project key each working directory resolved to last, on this machine. `roots.jsonl` in the memory home
12
+ * holds only `sha256(realPath(dir))`, never path text, and is never synced or exported. Append-only; the latest line
13
+ * per root wins. The only writer is the native SessionStart path (first sight, and a re-bind after an alias settled a
14
+ * transition); `amem project keep-separate --confirm` appends a `keep`. Status, doctor and MCP only read it.
15
+ */
16
+ export const ROOTS_SCHEMA = "agent-mem.roots/v1";
17
+ export const ROOTS_FILE = "roots.jsonl";
18
+ const READ_BOUND = 256 * 1024;
19
+
20
+ export interface RootLine { schema: typeof ROOTS_SCHEMA; op: "bind" | "keep"; root: string; key: string; prev?: string; at: string; machine?: string }
21
+ export interface ProjectTransition { state: "project_transition"; previousKey: string; key: string; previousCuratedNotes: number | null; aliasCommand: string; keepCommand: string }
22
+
23
+ /** The key every #581 reader and writer compares: the hook's own resolution, isolated from an inherited GIT_* environment. Raw, before alias resolution. */
24
+ export function transitionKey(cwd: string): string {
25
+ return memoryProjectKey(cwd, { repositoryIsolation: true });
26
+ }
27
+
28
+ export const rootsLogPath = (home: string): string => join(home, ROOTS_FILE);
29
+
30
+ /**
31
+ * The working root a directory belongs to: the nearest ancestor holding `.git` (a directory or a worktree's file),
32
+ * found by `lstat` alone so the hook spawns no git process; without one, the directory itself.
33
+ * ponytail: a submodule or nested repository is its own root, the same boundary `git rev-parse --show-toplevel` draws;
34
+ * a repository more than 32 levels up is not found and the directory stands for itself.
35
+ */
36
+ export function workingRoot(dir: string): string {
37
+ const start = realPath(dir);
38
+ for (let current = start, depth = 0; depth < 32; current = dirname(current), depth++) {
39
+ if (lstatSync(join(current, ".git"), { throwIfNoEntry: false })) return current;
40
+ if (dirname(current) === current) break;
41
+ }
42
+ return start;
43
+ }
44
+
45
+ /** sha256 hex of the working root's real path; the path text itself is never stored. */
46
+ export function rootHash(dir: string): string {
47
+ return createHash("sha256").update(workingRoot(dir)).digest("hex");
48
+ }
49
+
50
+ /** Latest line per root, from at most the last 256 KB. Missing, unreadable or malformed input yields fewer lines, never a throw. */
51
+ export function readRootBindings(home: string, maxBytes = READ_BOUND): Map<string, RootLine> {
52
+ const latest = new Map<string, RootLine>();
53
+ let text = "";
54
+ try {
55
+ const fd = openSync(rootsLogPath(home), "r");
56
+ try {
57
+ const size = fstatSync(fd).size, start = Math.max(0, size - maxBytes), buffer = Buffer.alloc(size - start);
58
+ readSync(fd, buffer, 0, buffer.length, start);
59
+ text = buffer.toString("utf8");
60
+ if (start > 0) text = text.slice(text.indexOf("\n") + 1); // drop the cut first line
61
+ } finally { closeSync(fd); }
62
+ } catch { return latest; }
63
+ for (const raw of text.split("\n")) {
64
+ if (!raw) continue;
65
+ try {
66
+ const line = JSON.parse(raw) as RootLine;
67
+ if (line?.schema !== ROOTS_SCHEMA || (line.op !== "bind" && line.op !== "keep") || typeof line.root !== "string" || !/^[0-9a-f]{64}$/.test(line.root) || typeof line.key !== "string" || !line.key) continue;
68
+ latest.set(line.root, line);
69
+ } catch { /* a malformed line is skipped */ }
70
+ }
71
+ return latest;
72
+ }
73
+
74
+ const shellWord = (word: string) => /^[A-Za-z0-9@%+=:,./_-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`;
75
+ export const aliasCommandFor = (previousKey: string, key: string) => `amem alias add ${shellWord(previousKey)} ${shellWord(key)}`;
76
+ export const KEEP_COMMAND = "amem project keep-separate";
77
+
78
+ /** Two keys one alias hop apart (either direction, or both onto one canonical key) are already joined. */
79
+ function joined(aliases: Map<string, string>, a: string, b: string): boolean {
80
+ return (aliases.get(a) ?? a) === (aliases.get(b) ?? b);
81
+ }
82
+
83
+ /** The transition for this root, if its recorded key differs from `key` and nothing joins or keeps them apart. Never throws. */
84
+ export function projectTransition(home: string, dir: string, key: string, countCurated?: (key: string) => number | null): ProjectTransition | undefined {
85
+ try {
86
+ const line = readRootBindings(home).get(rootHash(dir));
87
+ if (!line || line.key === key) return undefined;
88
+ if (joined(effectiveAliases(home), line.key, key)) return undefined;
89
+ let previousCuratedNotes: number | null = null;
90
+ try { previousCuratedNotes = countCurated ? countCurated(line.key) : null; } catch { previousCuratedNotes = null; }
91
+ return { state: "project_transition", previousKey: line.key, key, previousCuratedNotes, aliasCommand: aliasCommandFor(line.key, key), keepCommand: KEEP_COMMAND };
92
+ } catch { return undefined; }
93
+ }
94
+
95
+ export function transitionNotice(t: ProjectTransition): string {
96
+ const count = t.previousCuratedNotes === null ? "" : ` (${t.previousCuratedNotes} curated notes)`;
97
+ return `amem: project key changed for this directory: was ${t.previousKey}${count}, now ${t.key}. Join: ${t.aliasCommand} Keep apart: ${t.keepCommand}`;
98
+ }
99
+
100
+ /** Curated notes a key holds, from its derived index read-only (busy 0); null when the index is absent, locked or unreadable. A bounded local read. */
101
+ export function curatedCount(home: string, key: string, shardDir: (home: string, key: string) => string): number | null {
102
+ // A curated shard's own index first, then a shared-v1 home's single index (which holds every project's rows).
103
+ for (const file of [indexFileName(false), indexFileName(true)].flatMap(name => [join(shardDir(home, key), name), join(home, name)])) {
104
+ let db: Database | undefined;
105
+ try {
106
+ if (!lstatSync(file, { throwIfNoEntry: false })) continue;
107
+ db = new Database(file, { readonly: true });
108
+ db.run("PRAGMA busy_timeout = 0");
109
+ return (db.query("SELECT COUNT(*) AS n FROM entries WHERE scope = 'project' AND project = ?").get(key) as { n: number }).n;
110
+ } catch { return null; } finally { db?.close(); }
111
+ }
112
+ return null;
113
+ }
114
+
115
+ function machineOf(home: string): string | undefined {
116
+ try { const id = JSON.parse(readFileSync(join(home, "machine.json"), "utf8")).id; return typeof id === "string" ? id : undefined; } catch { return undefined; }
117
+ }
118
+
119
+ function append(home: string, line: RootLine): void {
120
+ appendFileSync(rootsLogPath(home), JSON.stringify(line) + "\n", { mode: 0o600 });
121
+ }
122
+
123
+ /**
124
+ * The SessionStart writer. Appends a `bind` on first sight of a root, and a re-bind when the recorded key is already
125
+ * alias-joined to the resolved one (so a later change names the middle key). A differing, unjoined key is left alone
126
+ * so the notice persists until a person settles it. Fail-open: a write or read error yields no line and no throw.
127
+ */
128
+ export function observeRoot(home: string, dir: string, key: string, now: () => number = Date.now): "appended" | "unchanged" | "transition" | "failed" {
129
+ try {
130
+ const root = rootHash(dir), line = readRootBindings(home).get(root);
131
+ if (line?.key === key) return "unchanged";
132
+ if (line && !joined(effectiveAliases(home), line.key, key)) return "transition";
133
+ const machine = machineOf(home);
134
+ append(home, { schema: ROOTS_SCHEMA, op: "bind", root, key, at: new Date(now()).toISOString(), ...(machine ? { machine } : {}) });
135
+ return "appended";
136
+ } catch { return "failed"; }
137
+ }
138
+
139
+ /** `amem project keep-separate --confirm`: record the resolved key for this root on purpose, ending the transition without joining. */
140
+ export function recordKeepSeparate(home: string, dir: string, transition: ProjectTransition, now: () => number = Date.now): RootLine {
141
+ const machine = machineOf(home);
142
+ const line: RootLine = { schema: ROOTS_SCHEMA, op: "keep", root: rootHash(dir), key: transition.key, prev: transition.previousKey, at: new Date(now()).toISOString(), ...(machine ? { machine } : {}) };
143
+ append(home, line);
144
+ return line;
145
+ }
@@ -9,6 +9,8 @@ export interface StatusView {
9
9
  active: boolean; generation?: string; phase?: string;
10
10
  pending: Record<string, unknown> & { rows: number };
11
11
  deadLeasesRemoved?: { lease: string; at: string }[]; refusals?: string[];
12
+ /** #581: present only while this working root last resolved to a different, unjoined key. */
13
+ projectTransition?: { previousKey: string; key: string; previousCuratedNotes: number | null; aliasCommand: string; keepCommand: string };
12
14
  }
13
15
 
14
16
  /** Human rendering options (#590): `--verbose` history lines, the wrap width and the version in the context line. */
@@ -68,7 +70,9 @@ export function statusText(status: StatusView, s: Style = PLAIN, opts: ReportTex
68
70
  if (interrupted) findings.push({ text: "a shard migration stopped after capture; authoring is refused until it activates", next: ["amem migrate --shards --resume"] });
69
71
  for (const reason of refusals) findings.push({ text: `migration refusal: ${reason}`, next: [] });
70
72
  if (status.pending.rows && !interrupted) findings.push({ text: `${plural(status.pending.rows, "old-layout row")} wait for the shard migration`, next: ["amem migrate --shards --dry-run", "amem migrate --shards --resume"] });
71
- const overall: State = candidateState === "unavailable" ? "unavailable" : candidateState === "attention" || migrationState === "attention" ? "attention" : "ok";
73
+ const transition = status.projectTransition;
74
+ if (transition) findings.push({ text: `this directory resolved to ${transition.previousKey}${transition.previousCuratedNotes === null ? "" : ` (${plural(transition.previousCuratedNotes, "curated note")})`} before and to ${transition.key} now`, next: [transition.aliasCommand, transition.keepCommand] });
75
+ const overall: State = candidateState === "unavailable" ? "unavailable" : candidateState === "attention" || migrationState === "attention" || transition ? "attention" : "ok";
72
76
  const { machine, repo, denyPaths, piiPatterns, ...limits } = status.config;
73
77
  const limitFacts = Object.entries(limits).filter(([, value]) => value !== undefined && value !== null)
74
78
  .map(([key, value]) => typeof value === "number" && key.endsWith("Bytes") ? `${wordedKey(key)} ${humanBytes(value)}`
@@ -8,12 +8,14 @@ import { assertNoLiveReaders } from "./reader-lease.ts";
8
8
  import { createPlacementActivationOwner } from "./sync-placement-activation-proof.ts";
9
9
  /** #578 Q1: a checkpoint fence never refuses for readers; its `busy` means a placement sync, admission or renewal holds a lock. */
10
10
  export const PLACEMENT_CHECKPOINT_BUSY_MESSAGE = "Sync placement checkpoint is busy: a placement sync, admission or renewal holds its lock; wait for it to finish (amem sync --status shows recorded operations), then rerun the same checkpoint command.";
11
+ /** #624: only a writer renewal on an active inventory can continue through the checkpoint, which never waits for readers. */
12
+ export const PLACEMENT_RENEWAL_READERS_CONTINUATION = " To renew writers while sessions keep running, use the checkpoint instead, which does not wait for readers: %s.".replace("%s", "save the preview with (umask 077; set -C; amem migrate --sync-placement --checkpoint --writer-root <install root> --json > checkpoint-plan.json), repeating --writer-root for every install root, then run amem migrate --sync-placement --checkpoint --confirm --plan checkpoint-plan.json with the same --writer-root list");
11
13
  export class PlacementInventoryFenceError extends Error{
12
- constructor(readonly causeClass:"readers"|"busy",checkpoint=false){super(checkpoint&&causeClass==="busy"?PLACEMENT_CHECKPOINT_BUSY_MESSAGE:`Sync placement migration is ${causeClass}; close cooperating readers/writers, then run amem migrate --sync-placement --dry-run before retrying.`);this.name="PlacementInventoryFenceError";}
14
+ constructor(readonly causeClass:"readers"|"busy",checkpoint=false,renewal=false){super(checkpoint&&causeClass==="busy"?PLACEMENT_CHECKPOINT_BUSY_MESSAGE:`Sync placement migration is ${causeClass}; close cooperating readers/writers, then run amem migrate --sync-placement --dry-run before retrying.${renewal&&causeClass==="readers"?PLACEMENT_RENEWAL_READERS_CONTINUATION:""}`);this.name="PlacementInventoryFenceError";}
13
15
  }
14
16
  type FenceWork<T>=(mutation:MutationHandle,owner:ReturnType<typeof createPlacementActivationOwner>)=>Promise<T>;
15
- async function withFences<T>(home:string,directories:readonly string[],options:{readers:boolean},work:FenceWork<T>):Promise<T> {
16
- const fail=(cause:"readers"|"busy"):never=>{throw new PlacementInventoryFenceError(cause,!options.readers);};
17
+ async function withFences<T>(home:string,directories:readonly string[],options:{readers:boolean;renewal?:boolean},work:FenceWork<T>):Promise<T> {
18
+ const fail=(cause:"readers"|"busy"):never=>{throw new PlacementInventoryFenceError(cause,!options.readers,options.renewal===true);};
17
19
  return withProfileLock(home,async()=>{
18
20
  const releases:(()=>void)[]=[];
19
21
  try {
@@ -30,8 +32,8 @@ async function withFences<T>(home:string,directories:readonly string[],options:{
30
32
  });
31
33
  }
32
34
  /** Activation, renewal and admission: every live reader lease refuses, as before. */
33
- export function withPlacementActivationFences<T>(home:string,directories:readonly string[],work:FenceWork<T>):Promise<T> {
34
- return withFences(home,directories,{readers:true},work);
35
+ export function withPlacementActivationFences<T>(home:string,directories:readonly string[],work:FenceWork<T>,options:{renewal?:boolean}={}):Promise<T> {
36
+ return withFences(home,directories,{readers:true,renewal:options.renewal===true},work);
35
37
  }
36
38
  /**
37
39
  * #578 Q1: checkpoint confirm, resume and abandon exclude placement writers only (profile lock, every mutation and sync
@@ -0,0 +1,18 @@
1
+ import type { SyncOptions } from "./sync.ts";
2
+
3
+ /**
4
+ * #626, internal to one placement inventory run: the remote's advertised placement refs by remote URL, read once and
5
+ * shared by the run's publications. Kept off the public SyncOptions type (host API fixture): the inventory driver binds a
6
+ * fresh map to its own options object, and a publication reached with other options reads per run as before.
7
+ * Never authority: each publication still proves every target against it, and a publication that pushes deletes its entry.
8
+ */
9
+ const runs = new WeakMap<SyncOptions, Map<string, ReadonlyMap<string, string>>>();
10
+
11
+ export function bindPlacementAdvertisement(opts: SyncOptions): SyncOptions {
12
+ runs.set(opts, new Map());
13
+ return opts;
14
+ }
15
+
16
+ export function placementAdvertisement(opts: SyncOptions): Map<string, ReadonlyMap<string, string>> | undefined {
17
+ return runs.get(opts);
18
+ }
@@ -126,7 +126,7 @@ export async function previewPlacementCheckpoint(homeInput: string, opts: { writ
126
126
  const minReader = PLACEMENT_CHECKPOINT_MIN_READER;
127
127
  return { mode: "checkpoint-preview", window: window.window, nextWindow: intent.window, journalObjects, currentObjects: journal.objects, headroom,
128
128
  floorReady: homeFloorAtLeast(home, minReader), requiredHomeFloor: minReader, writers: roots.length, planHash: intent.seal, plan: intent,
129
- nextStep: `${CHECKPOINT_PREVIEW} --confirm --plan <saved preview JSON> --writer-root <install root> (repeat for every install)` };
129
+ nextStep: `(umask 077; set -C; ${CHECKPOINT_PREVIEW} --writer-root <install root> --json > checkpoint-plan.json), repeating --writer-root for every install, then ${CHECKPOINT_PREVIEW} --confirm --plan checkpoint-plan.json with the same --writer-root list` };
130
130
  }
131
131
  async function checkpointHeadroom(home: string, intent: CheckpointIntent): Promise<{ headroom: PlacementCheckpointHeadroom; journalObjects: PlacementJournalObjectComposition; assertCurrent(): void }> {
132
132
  const epochHash = intent.epochHash, prospective = await checkpointProspective(home).catch(historyRefusal);
@@ -22,6 +22,7 @@ import { isLocalKey, localKeyOptInMessage, readShardDescriptor, shardDir, userSh
22
22
  import { projectState } from "./lifecycle.ts";
23
23
  import { SyncPlacementJournalError, type PlacementRealm } from "./sync-placement-journal-format.ts";
24
24
  import type { SyncOptions, SyncResult } from "./sync.ts";
25
+ import { bindPlacementAdvertisement } from "./sync-placement-advertisement.ts";
25
26
  import type { MemoryStore } from "./store.ts";
26
27
 
27
28
  const digest = (value: string) => createHash("sha256").update(value).digest("hex");
@@ -98,7 +99,9 @@ function journalRefusal(error: unknown): (SyncResult & { placementRealms: Placem
98
99
  failure: { cause: code === "checkpoint-pending" ? "checkpoint-pending" : "unavailable" }, placementRealms: [] };
99
100
  }
100
101
 
101
- export async function syncPlacementInventory(home: string, opts: SyncOptions, ports: PlacementInventoryPorts): Promise<SyncResult & { placementRealms: PlacementRealmResult[] }> {
102
+ export async function syncPlacementInventory(home: string, callerOpts: SyncOptions, ports: PlacementInventoryPorts): Promise<SyncResult & { placementRealms: PlacementRealmResult[] }> {
103
+ // #626: one remote advertisement per run, shared by its publications (never one a caller passed in).
104
+ const opts: SyncOptions = bindPlacementAdvertisement({ ...callerOpts });
102
105
  let local: InventoryRealm[], missing: string[], inactive: string[], retained: string[] | undefined;
103
106
  try {
104
107
  // #288 step 3: a started checkpoint pauses every placement effect before any journal read, with its own cause and next step.
@@ -4,6 +4,7 @@ import { constants, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, open
4
4
  import { join } from "node:path";
5
5
  import { canonicalJSON, hashJSON, readSelector } from "./generation.ts";
6
6
  import { generationSyncLock } from "./generation-sync.ts";
7
+ import { placementAdvertisement } from "./sync-placement-advertisement.ts";
7
8
  import { generationSyncGit, generationSyncGitBytes, remoteVisibility, type SyncFailureCause, type SyncOptions, type SyncResult } from "./sync.ts";
8
9
  import { acquireMutation, assertMutationHandle, type MutationHandle } from "./mutation.ts";
9
10
  import { isLocalKey, localKeyOptInMessage, PlacementRealmRefusal, resolveShardProfile } from "./shard.ts";
@@ -395,17 +396,45 @@ class PlacementTransport {
395
396
  const result = await this.call(() => generationSyncGitBytes(this.root, this.args(["cat-file", "blob", object]), this.opts.signal, undefined, limit));
396
397
  if (result.code !== 0 || result.out.length < 1) refuse(); return Buffer.from(result.out);
397
398
  }
399
+ /**
400
+ * #626: the placement refs as the remote advertises them, read once per inventory run. One `ls-remote` costs a
401
+ * network round trip, and a run used to pay it once per target. The advertisement is the same read the per-ref call
402
+ * made, so each target still proves its tip against it; a ref this run's push moved is dropped from it (see finish).
403
+ */
404
+ async advertisement(): Promise<ReadonlyMap<string, string>> {
405
+ const shared = placementAdvertisement(this.opts);
406
+ const cached = shared?.get(this.url);
407
+ if (cached) return cached;
408
+ const result = await this.call(() => generationSyncGitBytes(this.root, this.args(["ls-remote", "--refs", "origin", "refs/heads/amem/u", "refs/heads/amem/p/*"]), this.opts.signal, undefined, REMOTE_REALM_ADVERTISEMENT_BYTES));
409
+ if (result.code !== 0) refuse("remote");
410
+ let text: string; try { text = new TextDecoder("utf-8", { fatal: true }).decode(result.out); } catch { return refuse("remote"); }
411
+ const refs = new Map<string, string>();
412
+ for (const line of text.split("\n")) {
413
+ if (!line) continue;
414
+ const fields = line.split("\t"); if (fields.length !== 2 || !oid(fields[0]) || !/^refs\/heads\/amem\/(?:u|p\/[0-9a-f]{16})$/.test(fields[1]!) || refs.has(fields[1]!)) refuse("remote");
415
+ refs.set(fields[1]!, fields[0]!);
416
+ }
417
+ shared?.set(this.url, refs);
418
+ return refs;
419
+ }
398
420
  async fetch(): Promise<void> {
421
+ const advertisement = await this.advertisement();
399
422
  for (const target of this.targets) {
400
423
  const ref = shardSyncRef(target.realm); if ((await this.git(["symbolic-ref", "--quiet", ref])).code !== 1) refuse();
401
424
  const cached = await this.git(["rev-parse", "--verify", "--quiet", ref]);
402
425
  if (cached.code !== 0 && cached.code !== 1 || cached.code === 0 && !oid(cached.out)) refuse(); target.local = cached.code === 0 ? cached.out : undefined;
403
- const advertised = await this.git(["ls-remote", "--exit-code", "origin", ref]);
404
- if (advertised.code === 2) { if (target.local && !this.journal.publicationReservation) refuse(); target.remote = undefined; target.remoteHistory = undefined; continue; }
405
- const fields = advertised.out.split("\t"); if (advertised.code !== 0 || fields.length !== 2 || !oid(fields[0]) || fields[1] !== ref) refuse();
406
- const incoming = `refs/amem/placement-incoming/${randomBytes(16).toString("hex")}`; this.refs.push(incoming);
407
- await this.required(["fetch", "-q", "--no-tags", "--no-write-fetch-head", "--no-recurse-submodules", "origin", `${ref}:${incoming}`]);
408
- const tip = await this.required(["rev-parse", "--verify", incoming]); if (!oid(tip) || tip !== fields[0]) refuse();
426
+ const advertised = advertisement.get(ref);
427
+ if (advertised === undefined) { if (target.local && !this.journal.publicationReservation) refuse(); target.remote = undefined; target.remoteHistory = undefined; continue; }
428
+ let tip: string;
429
+ if (target.local === advertised) {
430
+ // #626: the advertised tip is already the verified cached ref, so its objects are local; fetching it again only
431
+ // repeats a round trip. Equality with the advertisement is the same proof the fetched incoming ref gave.
432
+ tip = advertised;
433
+ } else {
434
+ const incoming = `refs/amem/placement-incoming/${randomBytes(16).toString("hex")}`; this.refs.push(incoming);
435
+ await this.required(["fetch", "-q", "--no-tags", "--no-write-fetch-head", "--no-recurse-submodules", "origin", `${ref}:${incoming}`]);
436
+ tip = await this.required(["rev-parse", "--verify", incoming]); if (!oid(tip) || tip !== advertised) refuse();
437
+ }
409
438
  if (target.local && !await target.auditor.verifiedAncestor(target.local, tip) && !this.journal.publicationReservation) refuse();
410
439
  target.remote = tip; target.remoteHistory = await target.auditor.history(tip);
411
440
  target.rows = new Map(target.remoteHistory.rows); target.fetched = new Set(target.remoteHistory.rows.keys()); target.origins = new Map(target.remoteHistory.origins);
@@ -799,6 +828,8 @@ class PlacementTransport {
799
828
  this.lastPolicyCheckUnixMs=Date.now(); this.lastPolicyHash=material.bundle.root.policyHash;this.policyCheckSource="live";
800
829
  const participating=material.bundle.root.targets.map((target,index)=>({target,index})).filter(item=>item.target.publish);
801
830
  this.attempted=participating.length>0;
831
+ // #626: a push moves advertised refs, so no later publication of this run may reuse the advertisement read before it.
832
+ if(this.attempted)placementAdvertisement(this.opts)?.delete(this.url);
802
833
  const sent=participating.length?await generationSyncGit(this.root,this.args(["push","--atomic","--no-follow-tags","-q",...participating.map(({target,index})=>`--force-with-lease=${shardSyncRef(this.targets[index]!.realm)}:${target.expectedRemoteHead??""}`),"origin",...participating.map(({target,index})=>`${target.commit}:${shardSyncRef(this.targets[index]!.realm)}`)]),this.opts.signal):{code:0};
803
834
  this.accepted=sent.code===0;await this.observe("cas-returned");
804
835
  if(!this.accepted)return this.result(false,"unknown","The placement publication outcome is unknown; retained receipts may have published. Recheck this exact attempt before retrying.");
@@ -15,7 +15,9 @@ import { readWriterHistory, writeWriterRenewalIntent, writeWriterRevision, appen
15
15
  import { createWriterRevision, createWriterCommit, createWriterRenewalIntent, writerRevisionWriters, WRITER_REVISION_SCHEMA, WRITER_RENEWAL_INTENT_SCHEMA, WRITER_REVISION_LIMIT, WRITER_COMMIT_LOG, SharedWriterRevisionError, type WriterRenewalIntent } from "./sync-placement-writer-revision-format.ts";
16
16
  import { requireWriterRenewalHomeFloor } from "./sync-placement-prerequisites.ts";
17
17
  import { resolvePlacementWindow } from "./sync-placement-checkpoint-storage.ts";
18
- import { withPlacementActivationFences } from "./sync-placement-activation-locks.ts";
18
+ import { withPlacementActivationFences as activationFences } from "./sync-placement-activation-locks.ts";
19
+ /** #624: renewal runs on an active inventory, so its readers refusal names the checkpoint continuation. */
20
+ const withPlacementActivationFences: typeof activationFences = (home, directories, work) => activationFences(home, directories, work, { renewal: true });
19
21
  import { assertPlacementActivationOwner, type PlacementActivationOwner } from "./sync-placement-activation-proof.ts";
20
22
  import { previewSyncPlacementSources, previewOwnedSyncPlacementSources } from "./sync-placement-capture.ts";
21
23
  import { captureInspectionPendingPrunes } from "./sync-placement-inspection-pending.ts";
@@ -18,6 +18,7 @@ import { createStandalonePolicy, type StandalonePolicyOptions } from "./memory/p
18
18
  import { configuredPolicyOptions, loadAmemConfig, repoConfigRoot } from "./memory/config.ts";
19
19
  import { pendingLine, pendingSummary } from "./memory/candidate-pending.ts";
20
20
  import { memoryProjectKey } from "./memory/project.ts";
21
+ import { curatedCount, projectTransition, transitionNotice } from "./memory/roots.ts";
21
22
  import { registerReaderLease } from "./memory/reader-lease.ts";
22
23
  import { type ReadRef, type ReadWindow } from "./memory/search-fts.ts";
23
24
  import { briefFailureReason } from "./memory/metrics.ts";
@@ -179,6 +180,14 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
179
180
  // F7: one line, "N candidates pending, oldest expires in D days", only when some wait, so a brief with none is byte-identical to before. It is numbers only (no candidate text),
180
181
  // read-only (no database is created, pruned or altered here, and neither the brief nor the hook ever stamps a candidate as shown: only `amem review walk` does) and reserved out of the
181
182
  // same byte budget as everything else; when it does not fit it is left out.
183
+ // #581: one notice line when this working root last resolved to a different, unjoined key. A bounded local read
184
+ // (roots.jsonl tail, aliases.jsonl, one read-only index count); any failure yields no line. Reserved first.
185
+ let transitionLine: string | undefined;
186
+ if (!options.measureOnly) {
187
+ const transition = projectTransition(base, cwd, requested, key => curatedCount(base, key, shardDir));
188
+ const notice = transition ? transitionNotice(transition) : undefined;
189
+ if (notice !== undefined && Buffer.byteLength(notice) + 1 <= remaining) { remaining -= Buffer.byteLength(notice) + 1; transitionLine = notice; }
190
+ }
182
191
  let candidateLine: string | undefined;
183
192
  const line = pendingLine(pendingSummary(base, [project, ...aliases], (options.now ?? Date.now)()));
184
193
  if (line !== undefined && Buffer.byteLength(line) + 1 <= remaining) { remaining -= Buffer.byteLength(line) + 1; candidateLine = line; }
@@ -453,15 +462,20 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
453
462
  }
454
463
  }
455
464
  guard(true);
456
- let context = [header(coverage, reasons), ...(candidateLine ? [candidateLine] : []), ...lines].join("\n");
465
+ const notices = () => [...(transitionLine ? [transitionLine] : []), ...(candidateLine ? [candidateLine] : [])];
466
+ let context = [header(coverage, reasons), ...notices(), ...lines].join("\n");
457
467
  while (Buffer.byteLength(context) > maximum && lines.length) {
458
468
  const repoIndex = lines.findLastIndex(line => line.startsWith('{"section":"repo",'));
459
469
  const removed = JSON.parse(lines.splice(repoIndex >= 0 ? repoIndex : lines.length - 1, 1)[0]!) as { section?: Section };
460
470
  if (removed.section && coverage[removed.section] === "complete") coverage[removed.section] = "partial";
461
- context = [header(coverage, reasons), ...(candidateLine ? [candidateLine] : []), ...lines].join("\n");
471
+ context = [header(coverage, reasons), ...notices(), ...lines].join("\n");
462
472
  }
463
473
  if (Buffer.byteLength(context) > maximum && candidateLine) {
464
474
  candidateLine = undefined;
475
+ context = [header(coverage, reasons), ...notices(), ...lines].join("\n");
476
+ }
477
+ if (Buffer.byteLength(context) > maximum && transitionLine) {
478
+ transitionLine = undefined;
465
479
  context = [header(coverage, reasons), ...lines].join("\n");
466
480
  }
467
481
  if (Buffer.byteLength(context) > maximum) result = unavailable();
package/src/setup.ts CHANGED
@@ -266,7 +266,7 @@ function placementWriterInventoryNote(root: string, home: string): string | unde
266
266
  try { canonical = realPath(root); } catch { return undefined; }
267
267
  if (roots.includes(canonical)) return undefined;
268
268
  // #551 AC2: the suggested argument is shell-quoted, so a root with a space, a quote or a shell metacharacter stays one argument.
269
- return `WARNING: this install root is outside the active placement writer inventory, so placement sync stops in writer verification once setup registers it. Renew the inventory first with the person - amem migrate --sync-placement --dry-run --writer-root ${quote(canonical)}, then --apply - and rerun setup after that. Setup writes no inventory entry and never refuses on this alone.`;
269
+ return `WARNING: this install root is outside the active placement writer inventory, so placement sync stops in writer verification once setup registers it. Renew the inventory first with the person, through the checkpoint while sessions keep running - save the preview with (umask 077; set -C; amem migrate --sync-placement --checkpoint --writer-root ${quote(canonical)} --json > checkpoint-plan.json), adding --writer-root for every other install root, then run amem migrate --sync-placement --checkpoint --confirm --plan checkpoint-plan.json with the same --writer-root list; only if the checkpoint preview refuses, close every amem session and run amem migrate --sync-placement --dry-run --writer-root ${quote(canonical)}, then --apply - and rerun setup after that. Setup writes no inventory entry and never refuses on this alone.`;
270
270
  }
271
271
  export function planSetup(target: string, mode: SetupPlan["mode"] = "preview", options: SetupContext = {}): SetupPlan {
272
272
  if (target !== "all" && !SETUP_TARGETS.includes(target as SetupTarget)) throw Error("usage: amem setup claude|codex|kimi|pi|qwen|jcode|opencode|gemini|agy|all [--apply|--undo]");
@@ -761,7 +761,10 @@ function setupWriterCommands(plan: SetupPlan): string[] {
761
761
  const all = [...new Set([...roots, ...readSetupWriterRoots(home), root].map(realPath))].sort();
762
762
  if (all.some(value => /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(value))) return ["amem doctor"];
763
763
  const flags = all.map(value => `--writer-root ${quote(value)}`).join(" ");
764
- return [`amem migrate --sync-placement --dry-run ${flags}`, `amem migrate --sync-placement --apply ${flags}`];
764
+ // #624: the checkpoint renews while sessions keep running. Its preview is saved as the JSON plan confirm reads, in a new
765
+ // 0600 file (umask 077, noclobber); dry-run/apply is the fallback, which needs every amem session closed.
766
+ return [`(umask 077; set -C; amem migrate --sync-placement --checkpoint ${flags} --json > checkpoint-plan.json)`, `amem migrate --sync-placement --checkpoint --confirm --plan checkpoint-plan.json ${flags}`,
767
+ `amem migrate --sync-placement --dry-run ${flags}`, `amem migrate --sync-placement --apply ${flags}`];
765
768
  } catch { return ["amem doctor"]; }
766
769
  }
767
770
 
@@ -33,7 +33,7 @@ function writerContextMessage(category:PlacementWriterRootCategory,causeClass:"m
33
33
  const receipt=category==="setup receipt"&&setupTarget?setupReceiptRemedy(setupTarget):undefined;
34
34
  if(phase==="initial")return `Sync placement initial writer proof is ${causeClass} (${category} category${cause}); ${receipt??(category==="setup receipt"?"upgrade or repair the managed amem install and its host exact pin, then rerun amem setup <target> --apply":"upgrade or repair the amem install and its host exact pin")}. Declare the complete writer roots and rerun amem migrate --sync-placement --dry-run.`;
35
35
  if(receipt)return `Sync placement writer proof is ${causeClass} (${category} category${cause}); Placement sync refused [cause: setup_receipt_missing_install]: ${receipt}; then rerun the sync.`;
36
- return `Sync placement writer proof is ${causeClass} (${category} category${cause}); restore the inventoried install, or renew it: if needed, preview amem formats raise home 0.22.0 and add --confirm after the exact command is approved; then run amem migrate --sync-placement --dry-run with the complete --writer-root inventory, and run --apply after the exact apply command is approved.`;
36
+ return `Sync placement writer proof is ${causeClass} (${category} category${cause}); restore the inventoried install, or renew it through the checkpoint while sessions keep running: save the preview with (umask 077; set -C; amem migrate --sync-placement --checkpoint --writer-root <install root> --json > checkpoint-plan.json), repeating --writer-root for every install root, then run amem migrate --sync-placement --checkpoint --confirm --plan checkpoint-plan.json with the same --writer-root list. Only if the checkpoint preview refuses (an open obligation, no headroom, or a home floor below 0.30.0), close every amem session (agent sessions, hub peers and their amem mcp servers), then, if needed, preview amem formats raise home 0.22.0 and add --confirm after the exact command is approved; then run amem migrate --sync-placement --dry-run with the complete --writer-root inventory, and run --apply after the exact apply command is approved.`;
37
37
  }
38
38
  export class PlacementWriterContextError extends Error {
39
39
  constructor(readonly category: PlacementWriterRootCategory, readonly causeClass: "missing" | "changed" | "unavailable",readonly phase:PlacementWriterContextPhase="active",readonly detail?:SyncPlacementWriterFailureDetail,readonly renewalState?:"pending"|"staging"|"checkpoint-pending",readonly setupTarget?:SetupTarget) {
package/src/ui/inbox.ts CHANGED
@@ -152,7 +152,7 @@ export interface InboxSourceState {
152
152
  }
153
153
  export interface InboxSources { paths: string[]; roots: string[]; states: Record<string, InboxSourceState>; version: string }
154
154
  const MAX_SOURCES = 16_384, MAX_TAIL_BYTES = 256 * 1024;
155
- const fixedFiles = ["amem.config.json", "capture-config.json", "formats.json", "profile.json", "shards.json", "aliases.jsonl", "lifecycle.jsonl", "profile.lock", "public-prune-view.intent.json", "candidates.db", "candidates.db-wal"];
155
+ const fixedFiles = ["amem.config.json", "capture-config.json", "formats.json", "profile.json", "shards.json", "aliases.jsonl", "lifecycle.jsonl", "roots.jsonl", "profile.lock", "public-prune-view.intent.json", "candidates.db", "candidates.db-wal"];
156
156
  const logDirectory = (value: string) => /(?:^|\/)(?:log|local)$/.test(value);
157
157
  const evidenceDirectory = (value: string) => /(?:^|\/)(?:public-prune-objects|public-prune-inputs|public-prune-input-sets|bridge-snapshots)(?:\/|$)/.test(value);
158
158
  function validPath(value: string): void {