@staix/agent-mem 0.41.0 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +2 -2
  3. package/package.json +4 -3
  4. package/src/cli.ts +161 -27
  5. package/src/commands-table.ts +17 -6
  6. package/src/index.ts +4 -1
  7. package/src/ingest-hosts.ts +440 -0
  8. package/src/mcp-bounds.ts +3 -0
  9. package/src/mcp-memory.ts +64 -10
  10. package/src/mcp.ts +36 -121
  11. package/src/memory/candidates.ts +33 -5
  12. package/src/memory/capture.ts +23 -0
  13. package/src/memory/commands.ts +6 -3
  14. package/src/memory/config.ts +26 -0
  15. package/src/memory/consolidation-clusters.ts +13 -2
  16. package/src/memory/doctor-text.ts +4 -1
  17. package/src/memory/doctor.ts +8 -5
  18. package/src/memory/formats-raise.ts +37 -16
  19. package/src/memory/formats.ts +37 -10
  20. package/src/memory/generation-sync.ts +1 -1
  21. package/src/memory/home-binding-fence.ts +2 -1
  22. package/src/memory/live-state.ts +85 -0
  23. package/src/memory/migrate.ts +3 -3
  24. package/src/memory/mutation.ts +6 -3
  25. package/src/memory/profile-marker-cache.ts +45 -0
  26. package/src/memory/public-prune-activation.ts +1 -1
  27. package/src/memory/public-prune-advance.ts +1 -1
  28. package/src/memory/public-prune-inputs.ts +1 -1
  29. package/src/memory/purge-intent.ts +27 -0
  30. package/src/memory/purge-matcher.ts +101 -0
  31. package/src/memory/purge-plan.ts +90 -0
  32. package/src/memory/read-curated-entries.ts +244 -0
  33. package/src/memory/reader-lease.ts +3 -0
  34. package/src/memory/search-fts.ts +55 -27
  35. package/src/memory/shard-migration.ts +3 -3
  36. package/src/memory/shard-sync.ts +3 -3
  37. package/src/memory/shard.ts +17 -14
  38. package/src/memory/store.ts +9 -72
  39. package/src/memory/sync-cadence.ts +8 -4
  40. package/src/memory/sync-placement-activation-locks.ts +39 -22
  41. package/src/memory/sync-placement-active.ts +69 -19
  42. package/src/memory/sync-placement-advertisement.ts +25 -3
  43. package/src/memory/sync-placement-checkpoint-person.ts +8 -14
  44. package/src/memory/sync-placement-effective-writers.ts +4 -3
  45. package/src/memory/sync-placement-guard.ts +31 -11
  46. package/src/memory/sync-placement-inventory.ts +20 -4
  47. package/src/memory/sync-placement-journal.ts +1 -1
  48. package/src/memory/sync-placement-realm-admission.ts +16 -11
  49. package/src/memory/sync-placement-refusal.ts +7 -0
  50. package/src/memory/sync-placement-remote-admission.ts +31 -13
  51. package/src/memory/sync-placement-remote-refusal.ts +1 -1
  52. package/src/memory/sync-placement-remote-stage.ts +1 -1
  53. package/src/memory/sync-placement-transport.ts +36 -15
  54. package/src/memory/sync-placement-writer-listing.ts +38 -13
  55. package/src/memory/sync-placement-writer-renewal.ts +5 -7
  56. package/src/memory/sync.ts +3 -2
  57. package/src/memory/topic.ts +14 -0
  58. package/src/setup-console.ts +49 -23
  59. package/src/setup-drift.ts +35 -4
  60. package/src/setup-owned.ts +9 -1
  61. package/src/setup-writer-roots.ts +1 -1
  62. package/src/setup.ts +102 -16
  63. package/src/sync-placement-writer-context.ts +1 -1
@@ -1,9 +1,9 @@
1
- import { readActivePlacementBinding } from "./sync-placement-active.ts";
1
+ import { provePlacementShards, readActivePlacementBinding } from "./sync-placement-active.ts";
2
2
  import { readEffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
3
- import { validatePlacementProfile, validatePlacementShards } from "./sync-placement-format.ts";
4
- import { assertPlacementRuntime, doctorScratchBinding, doctorScratchInventory, SyncPlacementRuntimeError } from "./sync-placement-guard.ts";
3
+ import { assertPlacementRuntime, doctorScratchBinding, doctorScratchInventory, readPlacementV3Marker, SyncPlacementRuntimeError } from "./sync-placement-guard.ts";
5
4
  import { assertNoPublicPruneIntent, readPublicPruneView } from "./public-prune-view.ts";
6
5
  import { indexFileName } from "./index-file.ts";
6
+ import { searchFileName } from "./search-fts.ts";
7
7
  import { createHash, randomBytes } from "node:crypto";
8
8
  import { existsSync, linkSync, lstatSync, mkdirSync, opendirSync, readFileSync, rmSync, writeFileSync, type Dir } from "node:fs";
9
9
  import { join } from "node:path";
@@ -116,11 +116,14 @@ export function legacyShardMarkerShape(value: unknown): boolean {
116
116
  && typeof row.phase === "string" && ["captured", "active"].includes(row.phase) && typeof row.selectorRevision === "string"
117
117
  && (row.schema !== SHARDED_V2_SCHEMA || !Object.keys(row).some(key => !(SHARDED_V2_FIELDS as readonly string[]).includes(key)));
118
118
  }
119
+ function readShardMarker(path: string): Record<string, unknown> | undefined {
120
+ return readPlacementV3Marker(path) ?? (readProfileJSON(path) as Record<string, unknown> | undefined);
121
+ }
122
+
119
123
  function shardJournal(memoryDir: string): ShardedJournal {
120
- const value = readProfileJSON(join(memoryDir, "shards.json")) as Record<string, unknown> | undefined;
124
+ const value = readShardMarker(join(memoryDir, "shards.json"));
121
125
  if (value?.schema === "agent-mem.shards/v3") {
122
- const profile = validatePlacementProfile(readProfileJSON(join(memoryDir, "profile.json")));
123
- return validatePlacementShards(value, profile) as unknown as ShardedJournal;
126
+ return provePlacementShards(value, readShardMarker(join(memoryDir, "profile.json"))).shards as unknown as ShardedJournal;
124
127
  }
125
128
  if (!value || (value.schema !== SHARDED_SCHEMA && value.schema !== SHARDED_V2_SCHEMA) || !validGeneration(value.generation) || value.phase !== "active" || typeof value.selectorRevision !== "string") throw new Error("no active curated shard migration");
126
129
  if (value.schema === SHARDED_V2_SCHEMA && Object.keys(value).some(key => !(SHARDED_V2_FIELDS as readonly string[]).includes(key))) throw new Error("unsupported curated shard view");
@@ -148,7 +151,7 @@ function shardSnapshot(memoryDir: string, deadline: number) {
148
151
  journal = current; continue;
149
152
  }
150
153
  const current = shardJournal(memoryDir);
151
- if (canonicalJSON(current) !== canonicalJSON(journal)) {
154
+ if (current !== journal && canonicalJSON(current) !== canonicalJSON(journal)) {
152
155
  if (!compatibleShardAdvance(journal, current)) throw new Error("curated shard selector changed");
153
156
  journal = current; continue;
154
157
  }
@@ -206,18 +209,18 @@ export function assertCuratedShardLayout(memoryDir: string, opts: { project?: st
206
209
  check(dir, true);
207
210
  for (const folder of ["log", "local", "legacy", "legacy/log", "legacy/local", "legacy-main", "legacy-main/log", "legacy-main/local"]) check(join(dir, folder), true);
208
211
  for (const name of ["project.json", "generation.json", "generation-seal.json", "migration-sources.json", "machine.json", "legacy/machine.json", "legacy-main/machine.json", "prune-translations.jsonl"]) check(join(dir, name), false);
209
- for (const database of new Set(["index.db", "index-v2.db", indexFileName(false), indexFileName(true), "search.db", "mutation-lock.db"])) for (const suffix of ["", "-wal", "-shm", "-journal"]) check(join(dir, database + suffix), false);
212
+ for (const database of new Set(["index.db", "index-v2.db", indexFileName(false), indexFileName(true), "search.db", searchFileName(), "mutation-lock.db"])) for (const suffix of ["", "-wal", "-shm", "-journal"]) check(join(dir, database + suffix), false);
210
213
  }
211
214
  /** Fixed curated paths cannot redirect writes into legacy inputs or another shard.
212
215
  * ponytail: same-user concurrent parent replacement needs descriptor-relative opens; fixed preflight does not claim that fence.
213
216
  */
214
217
  export function assertCuratedShardPaths(memoryDir: string, opts: { project?: string; user?: boolean }, origin: "cwd binding" | "remote" | "local binding" = "local binding"): void {
215
218
  assertPlacementRuntime(memoryDir);
216
- const selector = readProfileJSON(join(memoryDir, "profile.json")) as {schema?:unknown} | undefined;
219
+ const selector = readShardMarker(join(memoryDir, "profile.json"));
217
220
  let recheckInventory: (() => void) | undefined;
218
221
  if (selector?.schema === "agent-mem.profile/v3") {
219
222
  const scratch = doctorScratchBinding(memoryDir);
220
- const active = scratch ?? readActivePlacementBinding(memoryDir, selector, readProfileJSON(join(memoryDir, "shards.json")));
223
+ const active = scratch ?? readActivePlacementBinding(memoryDir, selector, readShardMarker(join(memoryDir, "shards.json")));
221
224
  const keyHash = opts.user ? undefined : createHash("sha256").update(opts.project!).digest("hex");
222
225
  // An appended same-epoch extension is part of the inventory a curated write may open (#448); a realm it does not name stays refused.
223
226
  const inventory = scratch ? doctorScratchInventory(memoryDir) : active ? readEffectiveRealmInventory(memoryDir, active) : undefined;
@@ -246,13 +249,13 @@ function inventoryView(inventory: RealmInventory | undefined): PlacementRealmVie
246
249
  export type PlacementRealmView = { readonly kind: "none" } | { readonly kind: "inventory"; admitted(keyHash: string): boolean; assertCurrent(): void };
247
250
 
248
251
  export function placementRealmView(base: string): PlacementRealmView | undefined {
249
- let selector: { schema?: unknown } | undefined;
250
- try { selector = readProfileJSON(join(base, "profile.json")) as { schema?: unknown } | undefined; } catch { return undefined; }
252
+ let selector: Record<string, unknown> | undefined;
253
+ try { selector = readShardMarker(join(base, "profile.json")); } catch { return undefined; }
251
254
  if (selector?.schema !== "agent-mem.profile/v3") return { kind: "none" };
252
255
  // No fallback to `none` here: a malformed v3 home is unproved, not ungated.
253
256
  try {
254
257
  const scratch = doctorScratchBinding(base);
255
- const active = scratch ?? readActivePlacementBinding(base, selector, readProfileJSON(join(base, "shards.json")));
258
+ const active = scratch ?? readActivePlacementBinding(base, selector, readShardMarker(join(base, "shards.json")));
256
259
  return inventoryView(scratch ? doctorScratchInventory(base) : active ? readEffectiveRealmInventory(base, active) : undefined);
257
260
  } catch { return undefined; }
258
261
  }
@@ -360,7 +363,7 @@ export function resolveShardProfile(memoryDir: string, opts: { project?: string;
360
363
  const shardMachine = readProfileJSON(join(dir, "machine.json"), 4096) as { id?: unknown } | undefined;
361
364
  if (typeof rootMachine?.id !== "string" || !/^[a-f0-9]{16}$/.test(rootMachine.id) || rootMachine.id !== shardMachine?.id) throw new Error("curated shard machine identity mismatch");
362
365
  const final = shardSnapshot(memoryDir, deadline), selector = final.selector;
363
- if (canonicalJSON(final.journal) !== canonicalJSON(initial.journal) && !compatibleShardAdvance(initial.journal, final.journal)
366
+ if (final.journal !== initial.journal && canonicalJSON(final.journal) !== canonicalJSON(initial.journal) && !compatibleShardAdvance(initial.journal, final.journal)
364
367
  || selector.revision !== final.journal.selectorRevision) throw new Error("curated shard selector changed; resume or inspect migration state");
365
368
  if (selector.selector?.schema === "agent-mem.profile/v2" || selector.selector?.schema === "agent-mem.profile/v3") readPublicPruneView(memoryDir, selector.selector.pruneInputSetHash, generation, deadline);
366
369
  const legacyMainHome = join(dir, "legacy-main");
@@ -1,3 +1,4 @@
1
+ import { assertNoPendingPurge } from "./purge-intent.ts";
1
2
  import { RECAP_SCRATCH } from "./recap-scratch.ts";
2
3
  import { buildCuratedBriefCache, buildPreferenceBriefCache } from "../brief-curated.ts";
3
4
  import { PREFERENCE_SLOT } from "./preference-brief.ts";
@@ -22,7 +23,7 @@ import { assertProjectActive, lifecycleResolver } from "./lifecycle.ts";
22
23
  export { machineId, type Machine } from "./machine.ts";
23
24
  import { rankedScore, rankedScoreDetails, unrankedScoreDetails, type SearchScoreDetails } from "./search-score.ts";
24
25
  export type { SearchScoreDetails } from "./search-score.ts";
25
- import { readWindowSql, readRef, type ReadWindow, type ReadRef, SearchIndex, captureSearch } from "./search-fts.ts";
26
+ import { readWindowSql, readRef, type ReadWindow, type ReadRef, SearchIndex, captureSearch, searchFileName } from "./search-fts.ts";
26
27
  import { assertCuratedShardPaths, ensureShardDescriptor, readShardDescriptor, readShardedSelection, aliasedKeys, effectiveAliases, resolveAlias, resolveShardProfile, shardDir, shardKeyHash, shardMachineDir, userShardDir } from "./shard.ts";
27
28
  import { readCaptureConfig, type CaptureRow } from "./capture.ts";
28
29
  import { assertSharedV1Op } from "./ops-contract.ts";
@@ -35,6 +36,7 @@ import { isDeepStrictEqual } from "node:util";
35
36
  import { registerReaderLease, type ReaderLease } from "./reader-lease.ts";
36
37
  import { recordBriefPublicationFailure } from "./metrics.ts";
37
38
  import { groupByTask, taskGroupKey } from "./task-group.ts";
39
+ import { foldLiveState } from "./live-state.ts";
38
40
 
39
41
  /**
40
42
  * #258: the hub's own memory. Append-only JSONL logs are the truth: `log/<machine>.jsonl` holds long-term entries and
@@ -323,8 +325,10 @@ export class MemoryStore {
323
325
  db.run("CREATE INDEX IF NOT EXISTS ops_settlement ON ops(target) WHERE op = 'settle'");
324
326
  this.db = db;
325
327
  this.mutationDb = openedMutation = mutationDatabase(this.dir);
326
- // One derived FTS copy per profile: a generation handle and a shared-v1 handle on one home never resync-fight.
327
- this.searchIndex = openedSearch = new SearchIndex(this.recapScratch ? ":memory:" : this.profile.sharded ? join(this.dir, "search.db") : join(home, this.profile.kind === "generation" ? `search-${this.profile.generation}.db` : "search.db"));
328
+ // One derived FTS copy per profile and schema. Other generations and older readers keep their own files.
329
+ const searchDir = this.profile.sharded ? this.dir : home;
330
+ const searchGeneration = this.profile.kind === "generation" && !this.profile.sharded ? this.profile.generation : undefined;
331
+ this.searchIndex = openedSearch = new SearchIndex(this.recapScratch ? ":memory:" : join(searchDir, searchFileName(searchGeneration)));
328
332
  this.memoryBaseDir = home;
329
333
  try { chmodSync(indexFile, 0o600); } catch { /* best effort */ }
330
334
  if (this.profile.kind === "generation") this.generationIndex = new GenerationIndex({ profile: this.profile, db, now: this.now,
@@ -432,7 +436,7 @@ export class MemoryStore {
432
436
 
433
437
  private withMutation<T>(work: () => T): T {
434
438
  const release = this.deferCuratedPublication();
435
- try { return this.mutationDb.transaction(work).immediate(); }
439
+ try { return this.mutationDb.transaction(() => { assertNoPendingPurge(this.profile.home); return work(); }).immediate(); }
436
440
  finally { release(); }
437
441
  }
438
442
 
@@ -1213,74 +1217,7 @@ export class MemoryStore {
1213
1217
  : "SELECT * FROM entries") as Record<string, string | null>[];
1214
1218
  const ops = projection?.ops ?? this.readRows("SELECT id, op, at, target, by FROM ops ORDER BY at, id") as { id: string; op: string; at: string; target: string; by: string | null }[];
1215
1219
  const realms = projection ? projection.realms : this.generationIndex ? new Map((this.readRows("SELECT id,own,legacy FROM generation_rows") as { id: string; own: number; legacy: number }[]).map(row => [row.id, row])) : undefined;
1216
- const born = realms ? new Set([...realms.values()].filter(row => row.own).map(row => row.id)) : undefined;
1217
- const forgotten = new Set([...ops.filter((o) => o.op === "forget").map((o) => o.target), ...(projection?.forgotten ?? [])]);
1218
- // Deadlines were fixed when the entries were written, so every process (whatever its own TTL) prunes the same rows.
1219
- const deadline = (o: { at: string; by: string | null }) => o.by && !Number.isNaN(Date.parse(o.by)) ? o.by : new Date(Date.parse(o.at) + this.ttl).toISOString();
1220
- const demoted = new Map(ops.filter((o) => o.op === "demote").map((o) => [o.target, deadline(o)]));
1221
- const settled = new Map<string, string>();
1222
- const settlementKey = (id: string, task: string) => born ? `${born.has(id)}:${task}` : task;
1223
- for (const o of ops) if (o.op === "settle") {
1224
- const source = realms?.get(o.id);
1225
- const keys = !realms ? [o.target] : [
1226
- ...(source?.own ? [`true:${o.target}`] : []),
1227
- ...(source?.legacy || !source?.own ? [`false:${o.target}`] : []),
1228
- ];
1229
- for (const key of keys) if (!settled.has(key)) settled.set(key, deadline(o));
1230
- }
1231
- const superseded = new Map<string, string>(), supersededAt = new Map<string, string>();
1232
- // Relations from ops and from notes' own `supersedes` fold together by write time (then id): the latest intent wins.
1233
- const relate = (old: string, newer: string, when: string) => { if (!(when < (supersededAt.get(old) ?? ""))) { superseded.set(old, newer); supersededAt.set(old, when); } };
1234
- for (const o of ops) if (o.op === "supersede" && o.by) relate(o.target, o.by, `${o.at} ${o.by}`);
1235
- const promoted = new Set<string>();
1236
- for (const r of rows) { if (r.supersedes) relate(r.supersedes, r.id!, `${r.at} ${r.id}`); if (r.promoted_from) promoted.add(r.promoted_from); }
1237
- const expiry = (r: Record<string, string | null>): string | null => {
1238
- const id = r.id!;
1239
- if ((demoted.has(id) ? "short" : r.tier) !== "short") return null;
1240
- // A decision, contract or fail of a settled task not yet copied to long-term waits for its promotion, never expires
1241
- // first; a note saved short-term after the settlement carries its own deadline and stays short-term.
1242
- // A superseded one is held too: if its replacement goes, it shows again, and a rebuild must find it the same way.
1243
- const taskDeadline = r.task ? settled.get(settlementKey(id, r.task)) : undefined;
1244
- if (r.tier === "short" && !demoted.has(id) && !r.expires && taskDeadline && PROMOTED_KINDS.includes(r.kind as Kind)) return null;
1245
- // A deadline written into the note (no task, a late note, an explicit short horizon) is its own, whatever the task does.
1246
- return demoted.get(id) ?? r.expires ?? (r.task ? taskDeadline ?? new Date(Date.parse(r.at!) + UNSETTLED_MS).toISOString() : new Date(Date.parse(r.at!) + this.ttl).toISOString());
1247
- };
1248
- // A newer entry that was forgotten, expired or pruned no longer replaces anything: the older one shows again. A
1249
- // promoted source lives on as its copy.
1250
- const byId = new Map(rows.map((r) => [r.id!, r]));
1251
- const copyOf = new Map(rows.filter((r) => r.promoted_from).map((r) => [r.promoted_from!, r.id!]));
1252
- const gone = (id: string): boolean => {
1253
- if (pruned?.has(id)) return true;
1254
- const r = byId.get(id);
1255
- if (!r || forgotten.has(id) || (r.promoted_from && forgotten.has(r.promoted_from))) return true;
1256
- const copy = copyOf.get(id);
1257
- if (copy) return gone(copy);
1258
- const e = expiry(r);
1259
- return e !== null && Date.parse(e) <= now;
1260
- };
1261
- // A promoted entry lives on as its copy, on either side of a relation: a promoted replacement still replaces, and a
1262
- // promoted entry that was replaced stays replaced.
1263
- const last = (id: string) => { let to = id; for (let c = copyOf.get(to); c; c = copyOf.get(to)) to = c; return to; };
1264
- for (const [old, newer] of [...superseded]) {
1265
- superseded.set(old, last(newer));
1266
- const copy = last(old);
1267
- if (copy !== old && !superseded.has(copy)) { superseded.set(copy, last(newer)); supersededAt.set(copy, supersededAt.get(old)!); }
1268
- }
1269
- for (const [old, newer] of superseded) if (gone(newer)) superseded.delete(old);
1270
- // Supersessions made apart (two processes, two machines) can close a cycle that would hide every entry in it: the
1271
- // earliest relation in the cycle gives way, so the latest intent stands, the same in every process. Each entry has
1272
- // one replacement, so a chain holds at most one cycle.
1273
- const when = (id: string) => `${supersededAt.get(id) ?? ""} ${id}`; // write time, then ids: the same in every process
1274
- for (const start of [...superseded.keys()]) {
1275
- const seen: string[] = [];
1276
- for (let at: string | undefined = start; at !== undefined && superseded.has(at); at = superseded.get(at)) {
1277
- const i = seen.indexOf(at);
1278
- if (i >= 0) { superseded.delete(seen.slice(i).reduce((x, y) => (when(y) < when(x) ? y : x))); break; }
1279
- seen.push(at);
1280
- }
1281
- }
1282
- const supersedes = new Map<string, string[]>(); // the reverse: what each newer entry replaced
1283
- for (const [old, newer] of superseded) supersedes.set(newer, [...(supersedes.get(newer) ?? []), old]);
1220
+ const { forgotten, demoted, promoted, superseded, supersedes, expiry } = foldLiveState({ now, ttl: this.ttl, unsettledMs: UNSETTLED_MS, promotedKinds: PROMOTED_KINDS, rows, ops, realms, pruned, ...(projection ? { forgotten: projection.forgotten } : {}) });
1284
1221
  let candidates = rows;
1285
1222
  if (selecting) {
1286
1223
  const hidden: string[] = [], expiredIds: string[] = [];
@@ -131,15 +131,19 @@ const LOCAL = /^(usage:|another (sync|memory mutation|generation|shard sync)|no
131
131
  export function syncOutcome(error: string | undefined, cause?: StopCause): SyncOutcome {
132
132
  if (error === undefined) return "ok";
133
133
  // A run its person ended (Ctrl-C, a closing terminal) is not a failure of the remote: the same Ctrl-C reads "fetch failed" or "stopped" depending on which step it hit, so the cause,
134
- // not the text, decides. Only the deadline (a remote that did not answer in time) stays a failure to back off from.
134
+ // not the text, decides. Only the deadline stays a failure to back off from, and the CLI holds it at one step (recordSyncAttempt `hold`).
135
135
  if (cause === "person") return "local";
136
136
  return LOCAL.test(error.replace(/^amem sync: /, "")) ? "local" : "failed";
137
137
  }
138
138
 
139
- /** Records one attempt. A stamp that cannot be written never fails the sync it describes. */
140
- export function recordSyncAttempt(home: string, ok: boolean, at: number): SyncState {
139
+ /**
140
+ * Records one attempt. A stamp that cannot be written never fails the sync it describes. `hold` (#657) is a run the `--if-due` deadline
141
+ * stopped: it waits at least one backoff step (15 minutes) but never doubles the wait, so a slow local run is not treated as a failing remote.
142
+ */
143
+ export function recordSyncAttempt(home: string, ok: boolean, at: number, hold = false): SyncState {
141
144
  const prior = readSyncState(home), when = new Date(at).toISOString();
142
- const next: SyncState = { lastAttemptAt: when, lastOkAt: ok ? when : prior.lastOkAt, failures: ok ? 0 : Math.min(prior.failures + 1, MAX_FAILURES) };
145
+ const failures = ok ? 0 : hold ? Math.max(prior.failures, 1) : Math.min(prior.failures + 1, MAX_FAILURES);
146
+ const next: SyncState = { lastAttemptAt: when, lastOkAt: ok ? when : prior.lastOkAt, failures };
143
147
  const file = join(home, SYNC_STATE_FILE), temp = `${file}.${process.pid}.tmp`;
144
148
  try {
145
149
  mkdirSync(home, { recursive: true, mode: 0o700 });
@@ -1,29 +1,38 @@
1
+ import { PURGE_PUBLICATION_BLOCK_FILE, purgePending } from "./purge-intent.ts";
1
2
  /** Shared person-migration fences. No serialized value grants ownership. */
2
3
  import { lstatSync } from "node:fs";
3
4
  import { join } from "node:path";
4
- import { withProfileLock } from "./generation.ts";
5
- import { acquireMutation, type MutationHandle } from "./mutation.ts";
5
+ import { withProfileLock, writeProfileJSON } from "./generation.ts";
6
+ import { acquireMutation, assertMutationHandle, type MutationHandle } from "./mutation.ts";
6
7
  import { generationSyncLock } from "./generation-sync.ts";
7
8
  import { assertNoLiveReaders } from "./reader-lease.ts";
8
9
  import { createPlacementActivationOwner } from "./sync-placement-activation-proof.ts";
9
10
  /** #578 Q1: a checkpoint fence never refuses for readers; its `busy` means a placement sync, admission or renewal holds a lock. */
10
11
  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");
13
- export class PlacementInventoryFenceError extends Error{
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";}
12
+ type PlacementMutationSurface = "checkpoint" | "admit" | "renewal";
13
+ export class PlacementInventoryFenceError extends Error {
14
+ constructor(readonly causeClass: "readers" | "busy", surface?: PlacementMutationSurface) {
15
+ const message = causeClass === "readers"
16
+ ? "Sync placement migration is blocked by live readers; close cooperating readers/writers, then run amem migrate --sync-placement --dry-run before retrying."
17
+ : surface === "checkpoint" ? PLACEMENT_CHECKPOINT_BUSY_MESSAGE
18
+ : surface === "admit" ? "Sync placement realm admission is busy; wait for the operation holding its lock (amem sync --status), then run amem migrate --sync-placement --admit <project> --dry-run."
19
+ : surface === "renewal" ? "Sync placement writer renewal is busy; wait for the operation holding its lock (amem sync --status), then run amem migrate --sync-placement --dry-run before retrying."
20
+ : "Sync placement migration is busy; close cooperating readers/writers, then run amem migrate --sync-placement --dry-run before retrying.";
21
+ super(message);
22
+ this.name = "PlacementInventoryFenceError";
23
+ }
15
24
  }
16
- type FenceWork<T>=(mutation:MutationHandle,owner:ReturnType<typeof createPlacementActivationOwner>)=>Promise<T>;
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);};
25
+ type FenceWork<T> = (mutation: MutationHandle, owner: ReturnType<typeof createPlacementActivationOwner>) => Promise<T>;
26
+ async function withFences<T>(home: string, directories: readonly string[], work: FenceWork<T>, surface?: PlacementMutationSurface): Promise<T> {
27
+ const fail = (cause: "readers" | "busy"): never => { throw new PlacementInventoryFenceError(cause, surface); };
19
28
  return withProfileLock(home,async()=>{
20
29
  const releases:(()=>void)[]=[];
21
30
  try {
22
31
  const transports=["shard-sync","shard-sync-placement"].map(name=>join(home,name)).filter(dir=>lstatSync(dir,{throwIfNoEntry:false})!==undefined);
23
32
  const dirs=[...new Set([home,...directories,...transports])].sort();let mutation:MutationHandle|undefined;
24
33
  for(const dir of dirs){
25
- if(options.readers){try{assertNoLiveReaders(dir,{includeShards:true});}catch{fail("readers");}}
26
- const handle=acquireMutation(dir);if(!handle)fail("busy");releases.push(handle!);if(dir===home)mutation=handle!;
34
+ if(surface === undefined){try{assertNoLiveReaders(dir,{includeShards:true});}catch{fail("readers");}}
35
+ const handle=acquireMutation(dir, home);if(!handle)fail("busy");releases.push(handle!);if(dir===home)mutation=handle!;
27
36
  }
28
37
  if(!mutation)fail("busy");
29
38
  for(const dir of [home,...transports]){const release=generationSyncLock(dir);if(!release)fail("busy");releases.push(release!);}
@@ -31,16 +40,24 @@ async function withFences<T>(home:string,directories:readonly string[],options:{
31
40
  }finally{for(const release of releases.reverse())release();}
32
41
  });
33
42
  }
34
- /** Activation, renewal and admission: every live reader lease refuses, as before. */
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);
43
+ /** Initial activation changes the markers that readers bind to when opening a store. */
44
+ export function withPlacementActivationFences<T>(home: string, directories: readonly string[], work: FenceWork<T>): Promise<T> {
45
+ return withFences(home, directories, work);
37
46
  }
38
- /**
39
- * #578 Q1: checkpoint confirm, resume and abandon exclude placement writers only (profile lock, every mutation and sync
40
- * lock). Live curated readers keep running: the checkpoint writes only under `sync-placement-checkpoints/`, never the
41
- * binding markers, and an extension-log reader fails closed (`checkpoint-pending`, then `changed`). The held profile
42
- * lock still refuses new reader admission for the duration.
43
- */
44
- export function withPlacementCheckpointFences<T>(home:string,directories:readonly string[],work:FenceWork<T>):Promise<T> {
45
- return withFences(home,directories,{readers:false},work);
47
+
48
+ /** Active placement mutations leave store bindings intact. The profile lock still blocks new readers. */
49
+ export function withPlacementMutationFences<T>(home: string, directories: readonly string[], work: FenceWork<T>, options: { surface: PlacementMutationSurface }): Promise<T> {
50
+ return withFences(home, directories, work, options.surface);
51
+ }
52
+
53
+ export function withPlacementCheckpointFences<T>(home: string, directories: readonly string[], work: FenceWork<T>): Promise<T> {
54
+ return withPlacementMutationFences(home, directories, work, { surface: "checkpoint" });
55
+ }
56
+
57
+
58
+ /** Install before admitting the successor. The home-wide block survives intent cleanup. */
59
+ export function writePurgePublicationBlock(home: string, mutation: MutationHandle): void {
60
+ assertMutationHandle(mutation, home);
61
+ if (!purgePending(home)) throw new Error("Purge publication block requires a pending local cut; use amem doctor to check the home before retrying.");
62
+ writeProfileJSON(join(home, PURGE_PUBLICATION_BLOCK_FILE), { schema: "agent-mem.purge-publication-block/v1" });
46
63
  }
@@ -1,7 +1,9 @@
1
+ import { assertNoPendingPurge } from "./purge-intent.ts";
2
+ import { freezeMetadata, isMetadataSnapshot, sameMetadataStamp } from "./profile-marker-cache.ts";
1
3
  /** Metadata-only v3 admission. Publication still requires the complete journal/source/policy proof. */
2
4
  import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type BigIntStats } from "node:fs";
3
5
  import { join } from "node:path";
4
- import { reportBindingRead } from "./binding-read-set.ts";
6
+ import { collectBindingReads, reportBindingRead } from "./binding-read-set.ts";
5
7
  import { canonicalJSON, hashJSON } from "./generation.ts";
6
8
  import { realPath } from "./platform.ts";
7
9
  import { homeIdentityHash } from "./home-identity.ts";
@@ -14,7 +16,6 @@ import { shardDir, userShardDir } from "./shard.ts";
14
16
 
15
17
  export interface ActivePlacementBinding { profile: PlacementProfile; shards: PlacementShards; epoch: PlacementEpoch; activation: SyncPlacementActivationPlan }
16
18
  function fail(): never { throw new Error("sync placement activation metadata unavailable or changed; inspect the retained activation before continuing"); }
17
- const same = (a: BigIntStats, b: BigIntStats) => a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs;
18
19
  function owned(s: BigIntStats, directory = false): void {
19
20
  if (s.uid !== BigInt(process.getuid?.() ?? -1) || (s.mode & 0o077n) !== 0n || s.isSymbolicLink()
20
21
  || (directory ? !s.isDirectory() : !s.isFile() || s.nlink !== 1n)) fail();
@@ -26,7 +27,35 @@ export function assertPlacementViewAdvance(home: string, activation: SyncPlaceme
26
27
  if (canonicalJSON(before) !== canonicalJSON(after)) fail();
27
28
  const initialShards = { ...shards, selectorRevision: hashJSON(initial) };
28
29
  if (hashJSON(initialShards) !== activation.targetShardsHash) fail();
30
+ assertLivePruneAdvance(home, initial, profile);
31
+ }
32
+ function assertLivePruneAdvance(home: string, initial: PlacementProfile, profile: PlacementProfile): void {
29
33
  if (initial.pruneInputSetHash === profile.pruneInputSetHash) return;
34
+ // #656: a fence check runs this per row. Reuse a positive answer only while every file and directory the full check read
35
+ // keeps its dev:ino:size:mtimeNs:ctimeNs stamp; a stat error or any change takes the full check again. Only a reused-proof
36
+ // fence check (inside withPlacementFenceMemo) uses the memo: every other reader, the brief fence included, reads in full.
37
+ if (fenceMemoDepth === 0) { assertLivePruneAdvanceUncached(home, initial, profile); return; }
38
+ const key = JSON.stringify([home, initial.pruneInputSetHash, profile.pruneInputSetHash, profile.generation]), cached = pruneAdvanceMemo.get(key);
39
+ if (cached && pathStamps(cached.paths) === cached.stamps) return;
40
+ pruneAdvanceMemo.delete(key);
41
+ const { paths } = collectBindingReads(() => assertLivePruneAdvanceUncached(home, initial, profile));
42
+ const stamps = pathStamps(paths);
43
+ // The stamps are taken after the read, so the check runs once more under them: a change between the read and the stamp is never memoized.
44
+ if (stamps !== undefined) assertLivePruneAdvanceUncached(home, initial, profile);
45
+ if (stamps !== undefined && pathStamps(paths) === stamps) { if (pruneAdvanceMemo.size >= 32) pruneAdvanceMemo.delete(pruneAdvanceMemo.keys().next().value!); pruneAdvanceMemo.set(key, { paths, stamps }); }
46
+ }
47
+ // ponytail: 32 entries across homes, keyed by resolved home; same-size in-place rewrites within one stat tick are not seen (profile-marker-cache ceiling).
48
+ const pruneAdvanceMemo = new Map<string, { paths: string[]; stamps: string }>();
49
+ let fenceMemoDepth = 0;
50
+ /** #656: run a cheap fence check whose prune-advance answer may be reused while its files keep their stamps. */
51
+ export function withPlacementFenceMemo<T>(work: () => T): T { fenceMemoDepth++; try { return work(); } finally { fenceMemoDepth--; } }
52
+ function pathStamps(paths: readonly string[]): string | undefined {
53
+ const out: string[] = [];
54
+ try { for (const path of paths) { const s = lstatSync(path, { bigint: true, throwIfNoEntry: false }); if (!s) return undefined; out.push([s.dev, s.ino, s.mode, s.size, s.mtimeNs, s.ctimeNs].map(String).join(":")); } }
55
+ catch { return undefined; }
56
+ return JSON.stringify(out);
57
+ }
58
+ function assertLivePruneAdvanceUncached(home: string, initial: PlacementProfile, profile: PlacementProfile): void {
30
59
  const oldView = readPublicPruneViewForActivation(home, initial.pruneInputSetHash, profile.generation);
31
60
  const nextView = readPublicPruneViewForActivation(home, profile.pruneInputSetHash, profile.generation);
32
61
  if (!Object.keys(oldView.realms).every(key => Object.hasOwn(nextView.realms, key))) fail();
@@ -37,16 +66,27 @@ export function assertPlacementViewAdvance(home: string, activation: SyncPlaceme
37
66
  if (old !== undefined && !chain.commitments.includes(old)) fail();
38
67
  }
39
68
  }
40
- /**
41
- * Last verified binding keyed by the lstat stamps of every object the full read checks (#420). A sync calls this several
42
- * times per fence check; an unchanged stamp is the same identity the full read already accepts between its own reads.
43
- * ponytail: one entry per process; drop it if a same-size rewrite inside one timestamp tick must be caught across calls.
44
- */
45
- const freeze = <T>(value: T): T => { if (value && typeof value === "object" && !Object.isFrozen(value)) { for (const inner of Object.values(value)) freeze(inner); Object.freeze(value); } return value; };
46
- let bindingMemo: { key: string; value: Pick<ActivePlacementBinding, "epoch" | "activation"> } | undefined;
69
+ // Only file-reader snapshots have stable identity. Arbitrary caller objects always take the full validator.
70
+ const shardProofs = new WeakMap<object, { input: object; proof: { profile: PlacementProfile; shards: PlacementShards } }>();
71
+ export function provePlacementShards(value: unknown, profileInput: unknown): { profile: PlacementProfile; shards: PlacementShards } {
72
+ const cached = isMetadataSnapshot(value) ? shardProofs.get(value) : undefined;
73
+ if (cached && cached.input === profileInput) return cached.proof;
74
+ const profile = validatePlacementProfile(profileInput);
75
+ const proof = { profile, shards: validatePlacementShards(value, profile) };
76
+ if (isMetadataSnapshot(value) && isMetadataSnapshot(profileInput)) {
77
+ shardProofs.set(value, { input: profileInput, proof: freezeMetadata(proof) });
78
+ }
79
+ return proof;
80
+ }
81
+
82
+ type BindingProof = Pick<ActivePlacementBinding, "epoch" | "activation">;
83
+ // ponytail: only one proof per parsed shard snapshot (bounded by the marker caches), plus one for arbitrary inputs.
84
+ const snapshotBindings = new WeakMap<object, { key: string; profileInput: object; value: BindingProof }>();
85
+ let valueBinding: { key: string; value: BindingProof } | undefined;
47
86
  /** No mutation/reader registration/index open. Missing preparation is distinct from malformed retained evidence. */
48
87
  export function readActivePlacementBinding(homeInput: string, profileInput: unknown, shardsInput: unknown): ActivePlacementBinding | undefined {
49
- const profile = validatePlacementProfile(profileInput), shards = validatePlacementShards(shardsInput, profile);
88
+ assertNoPendingPurge(homeInput);
89
+ const { profile, shards } = provePlacementShards(shardsInput, profileInput);
50
90
  const home = realPath(homeInput), root = lstatSync(home, { bigint: true }); owned(root, true);
51
91
  const stampKey = () => {
52
92
  const dir = join(home, "sync-placement", "epochs", profile.placementHead), stamps: string[] = [];
@@ -56,11 +96,17 @@ export function readActivePlacementBinding(homeInput: string, profileInput: unkn
56
96
  reportBindingRead(file);
57
97
  stamps.push([st.dev, st.ino, st.size, st.mtimeNs, st.ctimeNs].map(String).join(":"));
58
98
  }
59
- return canonicalJSON([home, canonicalJSON(profile), canonicalJSON(shards), stamps]);
99
+ return JSON.stringify([home, stamps]);
60
100
  }, memoKey = stampKey();
61
- if (memoKey !== undefined && bindingMemo?.key === memoKey) {
62
- assertPlacementViewAdvance(home, bindingMemo.value.activation, profile, shards);
63
- return { profile, shards, epoch: bindingMemo.value.epoch, activation: bindingMemo.value.activation };
101
+ const snapshot = isMetadataSnapshot(profileInput) && isMetadataSnapshot(shardsInput) ? { profileInput, shardsInput } : undefined;
102
+ const previous = snapshot && snapshotBindings.get(snapshot.shardsInput);
103
+ const valueKey = !snapshot && memoKey !== undefined ? canonicalJSON([memoKey, profile, shards]) : undefined;
104
+ const cached = previous && previous.key === memoKey && previous.profileInput === profileInput ? previous.value
105
+ : valueKey !== undefined && valueBinding?.key === valueKey ? valueBinding.value : undefined;
106
+ if (cached) {
107
+ // The binding stamps cover the static commitments. Prune artifacts can change independently.
108
+ assertLivePruneAdvance(home, cached.activation.targetProfile, profile);
109
+ return { profile: { ...profile }, shards: snapshot ? structuredClone(shards) : shards, ...cached };
64
110
  }
65
111
  const checks: (() => void)[] = [() => { const now = lstatSync(home, { bigint: true }); owned(now, true); if (now.dev !== root.dev || now.ino !== root.ino) fail(); }];
66
112
  const directory = (dir: string): boolean => {
@@ -73,13 +119,13 @@ export function readActivePlacementBinding(homeInput: string, profileInput: unkn
73
119
  owned(before); if (before.size <= 0n || before.size > 262144n) fail();
74
120
  const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
75
121
  try {
76
- const s = fstatSync(fd, { bigint: true }); owned(s); if (!same(before, s)) fail();
122
+ const s = fstatSync(fd, { bigint: true }); owned(s); if (!sameMetadataStamp(before, s)) fail();
77
123
  const bytes = Buffer.alloc(Number(s.size) + 1); let at = 0;
78
124
  while (at < bytes.length) { const n = readSync(fd, bytes, at, bytes.length - at, at); if (!n) break; at += n; }
79
- if (at !== Number(s.size) || !same(s, fstatSync(fd, { bigint: true })) || !same(s, lstatSync(file, { bigint: true }))) fail();
125
+ if (at !== Number(s.size) || !sameMetadataStamp(s, fstatSync(fd, { bigint: true })) || !sameMetadataStamp(s, lstatSync(file, { bigint: true }))) fail();
80
126
  const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, at)), value: unknown = JSON.parse(text);
81
127
  if (canonicalJSON(value) + "\n" !== text) fail();
82
- checks.push(() => { const now = lstatSync(file, { bigint: true }); owned(now); if (!same(s, now)) fail(); }); return { value, text };
128
+ checks.push(() => { const now = lstatSync(file, { bigint: true }); owned(now); if (!sameMetadataStamp(s, now)) fail(); }); return { value, text };
83
129
  } finally { closeSync(fd); }
84
130
  };
85
131
  if (!directory(join(home, "sync-placement")) || !directory(join(home, "sync-placement", "epochs"))) return undefined;
@@ -95,6 +141,10 @@ export function readActivePlacementBinding(homeInput: string, profileInput: unkn
95
141
  if (read(join(home, "profile.json"))?.text !== canonicalJSON(profile) + "\n" || read(join(home, "shards.json"))?.text !== canonicalJSON(shards) + "\n") fail();
96
142
  assertPlacementViewAdvance(home, activation, profile, shards);
97
143
  for (const check of checks) check();
98
- if (memoKey !== undefined && stampKey() === memoKey) bindingMemo = { key: memoKey, value: { epoch: freeze(epoch), activation: freeze(activation) } };
99
- return { profile, shards, epoch, activation };
144
+ if (memoKey !== undefined && stampKey() === memoKey) {
145
+ const value = { epoch: freezeMetadata(epoch), activation: freezeMetadata(activation) };
146
+ if (snapshot) snapshotBindings.set(snapshot.shardsInput, { key: memoKey, profileInput: snapshot.profileInput, value });
147
+ else if (valueKey !== undefined) valueBinding = { key: valueKey, value };
148
+ }
149
+ return { profile: { ...profile }, shards: snapshot ? structuredClone(shards) : shards, epoch, activation };
100
150
  }
@@ -5,14 +5,36 @@ import type { SyncOptions } from "./sync.ts";
5
5
  * shared by the run's publications. Kept off the public SyncOptions type (host API fixture): the inventory driver binds a
6
6
  * fresh map to its own options object, and a publication reached with other options reads per run as before.
7
7
  * Never authority: each publication still proves every target against it, and a publication that pushes deletes its entry.
8
+ *
9
+ * #656: the same run scope also holds the remote visibility answer by exact URL (one `gh repo view` per run, not per
10
+ * batch), and tells a publication to leave the placement storage memos for the driver to release in its finally.
8
11
  */
9
- const runs = new WeakMap<SyncOptions, Map<string, ReadonlyMap<string, string>>>();
12
+ interface PlacementRun { advertisement: Map<string, ReadonlyMap<string, string>>; visibility: Map<string, Promise<string>> }
13
+ const runs = new WeakMap<SyncOptions, PlacementRun>();
10
14
 
11
15
  export function bindPlacementAdvertisement(opts: SyncOptions): SyncOptions {
12
- runs.set(opts, new Map());
16
+ runs.set(opts, { advertisement: new Map(), visibility: new Map() });
13
17
  return opts;
14
18
  }
15
19
 
20
+ /** Ends the run scope: later publications with these options read visibility and release storage memos on their own again. */
21
+ export function releasePlacementRun(opts: SyncOptions): void { runs.delete(opts); }
22
+
16
23
  export function placementAdvertisement(opts: SyncOptions): Map<string, ReadonlyMap<string, string>> | undefined {
17
- return runs.get(opts);
24
+ return runs.get(opts)?.advertisement;
25
+ }
26
+
27
+ /** Whether a publication with these options runs inside an inventory run that releases the storage memos itself. */
28
+ export function placementStorageCacheScope(opts: SyncOptions): boolean { return runs.has(opts); }
29
+
30
+ /**
31
+ * Remote visibility, read once per exact URL inside one inventory run. Only a "private" answer is kept: any other answer or a
32
+ * failed read is dropped, so the next publication asks again and the refusal stays before any lock or fetch.
33
+ */
34
+ export function placementVisibility(opts: SyncOptions, url: string, read: (url: string) => Promise<string>): Promise<string> {
35
+ const run = runs.get(opts); if (!run) return read(url);
36
+ const known = run.visibility.get(url); if (known) return known;
37
+ const pending = read(url).then(value => { if (value !== "private") run.visibility.delete(url); return value; },
38
+ error => { run.visibility.delete(url); throw error; });
39
+ run.visibility.set(url, pending); return pending;
18
40
  }
@@ -4,14 +4,13 @@
4
4
  * person-written floor record (`amem formats raise` is the one writer).
5
5
  */
6
6
  import { randomBytes } from "node:crypto";
7
- import { lstatSync } from "node:fs";
8
7
  import { fileURLToPath } from "node:url";
9
8
  import { types } from "node:util";
10
9
  import { memoryPolicySnapshot } from "./policy.ts";
11
10
  import { realPath } from "./platform.ts";
12
11
  import { canonicalJSON } from "./generation.ts";
13
12
  import { assertFormatFloor, formatVersionBelow, readFormatFloors } from "./formats.ts";
14
- import { installVersion } from "./formats-raise.ts";
13
+ import { installAbsent, installVersion } from "./formats-raise.ts";
15
14
  import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
16
15
  import { PLACEMENT_JOURNAL_CHUNK_MAX_BYTES, PLACEMENT_JOURNAL_MAX_OBJECTS } from "./sync-placement-journal-format.ts";
17
16
  import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
@@ -46,7 +45,7 @@ const MESSAGES: Record<PlacementCheckpointCause, string> = {
46
45
  obligation: "The placement journal has an unfinished append, publication, reservation, renewal or source recovery; finish it with amem sync (or the pending renewal with amem migrate --sync-placement --resume), then preview the checkpoint again.",
47
46
  changed: `The placement state changed since the checkpoint plan was sealed; preview a fresh plan with ${CHECKPOINT_PREVIEW} and confirm that one.`,
48
47
  inactive: "This home has no active sync placement; activate it with amem migrate --sync-placement --dry-run first.",
49
- candidate: `A checkpoint carries one writer renewal: list the inventory and the roots to declare with amem migrate --sync-placement --writers, then pass the complete inventory as repeatable --writer-root <install root> (every amem install sharing this home), then preview again with ${CHECKPOINT_PREVIEW}.`,
48
+ candidate: `A checkpoint carries one writer renewal: list the inventory and the roots to declare with amem migrate --sync-placement --writers, then pass the complete inventory as repeatable --writer-root <install root> (every amem install sharing this home) or use --discovered-writers, then preview again with ${CHECKPOINT_PREVIEW}.`,
50
49
  history: "",
51
50
  "writer-missing": "",
52
51
  };
@@ -138,7 +137,7 @@ export async function previewPlacementCheckpoint(homeInput: string, opts: { writ
138
137
  const minReader = PLACEMENT_CHECKPOINT_MIN_READER;
139
138
  return { mode: "checkpoint-preview", window: window.window, nextWindow: intent.window, journalObjects, currentObjects: journal.objects, headroom,
140
139
  floorReady: homeFloorAtLeast(home, minReader), requiredHomeFloor: minReader, writers: roots.length, planHash: intent.seal, plan: intent,
141
- 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` };
140
+ nextStep: `${CHECKPOINT_PREVIEW} --writer-root <install root> --out checkpoint-plan.json, repeating --writer-root for every install (or --discovered-writers), then ${CHECKPOINT_PREVIEW} --confirm --plan checkpoint-plan.json` };
142
141
  }
143
142
  async function checkpointHeadroom(home: string, intent: CheckpointIntent): Promise<{ headroom: PlacementCheckpointHeadroom; journalObjects: PlacementJournalObjectComposition; assertCurrent(): void }> {
144
143
  const epochHash = intent.epochHash, prospective = await checkpointProspective(home).catch(historyRefusal);
@@ -179,15 +178,8 @@ function reviewedHeadroom(value: unknown): unknown {
179
178
  if (!detached) throw new PlacementCheckpointError("changed");
180
179
  return detached;
181
180
  }
182
- /**
183
- * #634: an install whose root no longer exists (ENOENT or ENOTDIR on the root itself). An existing root with a missing or
184
- * unreadable package.json is not absent: it can still run, so the floor check keeps refusing it.
185
- */
186
- function installAbsent(root: string): boolean {
187
- try { lstatSync(root); return false; } catch (error) { const code = (error as NodeJS.ErrnoException).code; return code === "ENOENT" || code === "ENOTDIR"; }
188
- }
189
181
  function missingWriterMessage(root: string): string {
190
- return `The install at ${root} no longer exists; drop that --writer-root, then save the preview again with (umask 077; set -C; ${CHECKPOINT_PREVIEW} --writer-root <install root> --json > checkpoint-plan.json), repeating --writer-root for every remaining install, and confirm it with ${CHECKPOINT_PREVIEW} --confirm --plan checkpoint-plan.json with the same --writer-root list.`;
182
+ return `The install at ${root} no longer exists; drop that --writer-root, then save the preview again with ${CHECKPOINT_PREVIEW} --writer-root <install root> --out checkpoint-plan.json, repeating --writer-root for every remaining install, and confirm it with ${CHECKPOINT_PREVIEW} --confirm --plan checkpoint-plan.json.`;
191
183
  }
192
184
  function checkFloor(home: string, roots: PlacementCheckpointInput["roots"] | undefined, minReader: string): void {
193
185
  if (!homeFloorAtLeast(home, minReader)) throw new PlacementCheckpointError("floor");
@@ -211,12 +203,14 @@ function checkWriterVersions(home: string, roots: PlacementCheckpointInput["root
211
203
  */
212
204
  export async function confirmPlacementCheckpoint(homeInput: string, value: unknown, opts: { writerRoots: readonly string[]; ownRoot: string; phase?: (phase: PlacementCheckpointPhase) => void }): Promise<{ window: number; renewed: true; planHash: string; nextStep: string }> {
213
205
  const home = realPath(homeInput), intent = checkpointPlanFrom(value), a = active(home), minReader = PLACEMENT_CHECKPOINT_MIN_READER;
206
+ // #660: without --writer-root the sealed plan names the roots; every one is still measured fresh here and under the fences.
207
+ const writerRoots = opts.writerRoots.length ? opts.writerRoots : intent.writerRevision.roots.map(root => root.root);
214
208
  if (intent.epochHash !== a.profile.placementHead) throw new PlacementCheckpointError("changed");
215
- checkFloor(home, undefined, minReader); checkFloor(home, measured(home, opts.writerRoots, opts.ownRoot), minReader);
209
+ checkFloor(home, undefined, minReader); checkFloor(home, measured(home, writerRoots, opts.ownRoot), minReader);
216
210
  const prospective = await checkpointHeadroom(home, intent);
217
211
  if (canonicalJSON(reviewedHeadroom(value)) !== canonicalJSON(prospective.headroom)) throw new PlacementCheckpointError("changed");
218
212
  return withPlacementCheckpointFences(home, placementFenceDirectories(home, a), async (mutation, owner) => {
219
- const now = active(home), roots = measured(home, opts.writerRoots, opts.ownRoot);
213
+ const now = active(home), roots = measured(home, writerRoots, opts.ownRoot);
220
214
  if (canonicalJSON(now) !== canonicalJSON(a)) throw new PlacementCheckpointError("changed");
221
215
  prospective.assertCurrent();
222
216
  checkFloor(home, roots, minReader);