@staix/agent-mem 0.29.0 → 0.31.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 (71) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +20 -574
  3. package/package.json +3 -2
  4. package/src/cli-agent-reads.ts +17 -2
  5. package/src/cli.ts +178 -21
  6. package/src/commands-table.ts +14 -2
  7. package/src/index.ts +1 -0
  8. package/src/ingest.ts +7 -5
  9. package/src/mcp-memory.ts +36 -8
  10. package/src/memory/bridge.ts +26 -1
  11. package/src/memory/candidates.ts +17 -1
  12. package/src/memory/capacity.ts +5 -2
  13. package/src/memory/catalog.ts +10 -1
  14. package/src/memory/commands.ts +2 -1
  15. package/src/memory/config.ts +13 -1
  16. package/src/memory/decay-review.ts +20 -0
  17. package/src/memory/doctor.ts +133 -47
  18. package/src/memory/eval-audit.ts +442 -0
  19. package/src/memory/eval.ts +66 -0
  20. package/src/memory/formats.ts +4 -3
  21. package/src/memory/intent-brief.ts +34 -6
  22. package/src/memory/metrics.ts +173 -14
  23. package/src/memory/native-roots.ts +28 -0
  24. package/src/memory/platform.ts +9 -1
  25. package/src/memory/review-targets.ts +69 -0
  26. package/src/memory/shard-bridge.ts +18 -6
  27. package/src/memory/shard-migration.ts +14 -1
  28. package/src/memory/shard-sync-format.ts +18 -0
  29. package/src/memory/shard-sync.ts +52 -4
  30. package/src/memory/shard.ts +4 -0
  31. package/src/memory/store.ts +4 -2
  32. package/src/memory/sync-placement-bound.ts +21 -4
  33. package/src/memory/sync-placement-cache.ts +16 -1
  34. package/src/memory/sync-placement-capture.ts +14 -2
  35. package/src/memory/sync-placement-checkpoint-format.ts +199 -0
  36. package/src/memory/sync-placement-checkpoint-person.ts +209 -0
  37. package/src/memory/sync-placement-checkpoint-prospective.ts +141 -0
  38. package/src/memory/sync-placement-checkpoint-storage.ts +218 -0
  39. package/src/memory/sync-placement-checkpoint.ts +234 -0
  40. package/src/memory/sync-placement-dependencies.ts +42 -9
  41. package/src/memory/sync-placement-effective-writers.ts +12 -6
  42. package/src/memory/sync-placement-git.ts +17 -7
  43. package/src/memory/sync-placement-inspection-evidence.ts +1 -1
  44. package/src/memory/sync-placement-inventory.ts +38 -11
  45. package/src/memory/sync-placement-journal-format.ts +4 -1
  46. package/src/memory/sync-placement-journal-storage.ts +129 -26
  47. package/src/memory/sync-placement-materialize.ts +33 -19
  48. package/src/memory/sync-placement-projection.ts +7 -1
  49. package/src/memory/sync-placement-publication-events.ts +42 -0
  50. package/src/memory/sync-placement-publication-plan.ts +18 -1
  51. package/src/memory/sync-placement-realm-admission.ts +20 -3
  52. package/src/memory/sync-placement-realm-discovery.ts +42 -0
  53. package/src/memory/sync-placement-remote-admission.ts +190 -0
  54. package/src/memory/sync-placement-remote-adoption-format.ts +54 -0
  55. package/src/memory/sync-placement-remote-materialization.ts +49 -0
  56. package/src/memory/sync-placement-remote-refusal.ts +21 -0
  57. package/src/memory/sync-placement-remote-stage.ts +275 -0
  58. package/src/memory/sync-placement-transport.ts +207 -53
  59. package/src/memory/sync-placement-writer-history.ts +75 -17
  60. package/src/memory/sync-placement-writer-renewal.ts +18 -10
  61. package/src/memory/sync-placement-writer-revision-format.ts +16 -13
  62. package/src/memory/sync-placement-yield.ts +14 -0
  63. package/src/memory/sync-progress.ts +1 -1
  64. package/src/memory/sync.ts +5 -2
  65. package/src/memory/use-telemetry.ts +15 -7
  66. package/src/setup-drift.ts +12 -2
  67. package/src/setup-owned.ts +42 -0
  68. package/src/setup.ts +32 -11
  69. package/src/sync-placement-writer-context.ts +5 -5
  70. package/src/ui/plugin.ts +26 -11
  71. package/src/ui/snapshot-cache.ts +24 -11
@@ -18,6 +18,8 @@ import { WRITER_RENEWAL_INTENT_FILE, WRITER_RENEWAL_INTENT_MAX_BYTES, WRITER_COM
18
18
  import { isWriterRenewalIntentTempName } from "./sync-placement-writer-history.ts";
19
19
  import { PLACEMENT_BATCH_INTENT_MAX_BYTES, planPlacementBatchIntent, validatePlacementBatchIntent, type PlacementBatchIntent } from "./sync-placement-batch-intent.ts";
20
20
  import { formatFloorAtLeast } from "./formats.ts";
21
+ import { resolvePlacementWindow, placementWindowToken, releasePlacementCheckpointCaches, type ResolvedPlacementWindow } from "./sync-placement-checkpoint-storage.ts";
22
+ import { isCheckpointSealedName, PLACEMENT_CHECKPOINT_MANIFEST_MAX_BYTES, type CheckpointMember } from "./sync-placement-checkpoint-format.ts";
21
23
 
22
24
  export type PlacementStoragePhase = "epoch-written" | "epoch-fsync" | "activation-written" | "activation-fsync" | "fence-written" | "fence-fsync"
23
25
  | "intent-written" | "intent-fsync" | "chunk-written" | "chunk-fsync" | "intent-cleared"
@@ -27,7 +29,7 @@ export interface PlacementStorageOptions { mutation: MutationHandle; assertCurre
27
29
  export interface PlacementJournalRead {
28
30
  epoch: PlacementEpoch; activation: SyncPlacementActivationPlan; records: PlacementRecord[]; headHash: string; sequence: number; objects: number; pending: boolean; pendingRecordSequence?: number; pendingRecord?: PlacementRecord; pendingBatch?: { attemptHash: string; count: number }; publicationReservation?: { attemptHash: string; reservedRecords: number; consumedRecords: number };
29
31
  }
30
- interface Paths { home: string; root: string; epochs: string; dir: string; hash: string }
32
+ interface Paths { home: string; root: string; epochs: string; dir: string; hash: string; epochDir: string; window: ResolvedPlacementWindow }
31
33
  interface Chunk { name: string; size: number; hash: string }
32
34
  interface Intent { schema: "agent-mem.sync-placement-append-intent/v1"; epochHash: string; record: PlacementRecord; chunk: string; prefixBytes: number; prefixHash: string; lineHash: string }
33
35
  interface Snapshot extends PlacementJournalRead { chunks: Chunk[]; projection: PlacementProjection; intent?: Intent; batchIntent?: PlacementBatchIntent; intentPending: boolean; fencePending: boolean }
@@ -49,8 +51,15 @@ function state(file: string, directory = false): BigIntStats | undefined {
49
51
  function paths(home: string, epochHash: string): Paths {
50
52
  if (!hex(epochHash)) return fail("invalid");
51
53
  const canonical = realPath(home); owned(lstatSync(home, { bigint: true }), true);
52
- return { home: canonical, root: join(canonical, "sync-placement"), epochs: join(canonical, "sync-placement", "epochs"), dir: join(canonical, "sync-placement", "epochs", epochHash), hash: epochHash };
54
+ // #288: the one window resolver selects the live window; epoch.json and activation.json stay in frozen window 0.
55
+ const window = resolvePlacementWindow(canonical, epochHash), epochDir = join(canonical, "sync-placement", "epochs", epochHash);
56
+ return { home: canonical, root: join(canonical, "sync-placement"), epochs: join(canonical, "sync-placement", "epochs"), dir: window.dir, hash: epochHash, epochDir, window };
53
57
  }
58
+ /** Archived journal chunks in replay order: every frozen window's `records-*` members, by their global chunk index. */
59
+ function archivedChunks(p: Paths): { dir: string; name: string; member: CheckpointMember }[] {
60
+ return p.window.archived.flatMap(window => window.members.filter(member => /^records-\d{5}\.jsonl$/.test(member.name)).map(member => ({ dir: window.dir, name: member.name, member })));
61
+ }
62
+ const checkpointMember = (name: string) => isCheckpointSealedName(name);
54
63
  function names(dir: string, maximum: number): string[] {
55
64
  const reader = opendirSync(dir), result: string[] = [];
56
65
  try { for (;;) { const entry = reader.readSync(); if (!entry) break; if (result.length >= maximum) fail("bound"); result.push(entry.name); } }
@@ -70,25 +79,28 @@ function renewalIntentObjects(home:string):{count:number;token:unknown[]} {
70
79
  }
71
80
  function inventory(p: Paths): { files: Map<string, BigIntStats>; token: string; renewalObjects:number } {
72
81
  const parents: unknown[] = [];
73
- for (const dir of [p.home, p.root, p.epochs, p.dir]) { const stat = state(dir, true); parents.push([dir, stat ? [String(stat.dev), String(stat.ino)] : null]); }
82
+ for (const dir of [p.home, p.root, p.epochs, p.epochDir, ...(p.window.window ? [p.dir] : [])]) { const stat = state(dir, true); parents.push([dir, stat ? [String(stat.dev), String(stat.ino)] : null]); }
74
83
  if (state(p.root, true)) for (const name of names(p.root, 2)) {
75
84
  if (name === "epochs") state(p.epochs, true); else if (name === "active.json") { const stat = state(join(p.root, name))!; if (stat.size > BigInt(PLACEMENT_JOURNAL_ROOT_MAX_BYTES)) fail("bound"); }
76
85
  else fail();
77
86
  }
78
- const files = new Map<string, BigIntStats>();
87
+ const files = new Map<string, BigIntStats>(), live = p.window.window > 0;
79
88
  if (state(p.dir, true)) for (const name of names(p.dir, PLACEMENT_JOURNAL_MAX_OBJECTS - 1)) {
80
89
  const chunk = /^records-\d{5}\.jsonl$/.test(name);
81
- const writerLimit=writerHistoryFileLimit(name);
82
- if (!chunk && !publicationName(name) && writerLimit===undefined && !["epoch.json", "activation.json", "append-intent.json"].includes(name)) fail();
90
+ const writerLimit=writerHistoryFileLimit(name), sealed = live && checkpointMember(name);
91
+ // Window 0 holds the epoch's own metadata; a later live window holds the checkpoint's sealed files instead.
92
+ if (!chunk && !publicationName(name) && writerLimit===undefined && !sealed && ![...(live ? [] : ["epoch.json", "activation.json"]), "append-intent.json"].includes(name)) fail();
83
93
  const stat = state(join(p.dir, name))!;
84
- if (stat.size > BigInt(writerLimit??(name === "append-intent.json" ? PLACEMENT_BATCH_INTENT_MAX_BYTES : chunk || /-chunk-\d{5}\.json$/.test(name) ? PLACEMENT_JOURNAL_CHUNK_MAX_BYTES : PLACEMENT_JOURNAL_ROOT_MAX_BYTES))) fail("bound");
94
+ if (stat.size > BigInt(writerLimit??(sealed ? PLACEMENT_CHECKPOINT_MANIFEST_MAX_BYTES : name === "append-intent.json" ? PLACEMENT_BATCH_INTENT_MAX_BYTES : chunk || /-chunk-\d{5}\.json$/.test(name) ? PLACEMENT_JOURNAL_CHUNK_MAX_BYTES : PLACEMENT_JOURNAL_ROOT_MAX_BYTES))) fail("bound");
85
95
  files.set(name, stat);
86
96
  }
87
- // One global active.json slot is always reserved, whether that fence exists yet or not.
97
+ // The frozen epoch metadata still binds every read once the live window moved on.
98
+ const metadata = live ? ["epoch.json", "activation.json"].map(name => { const stat = state(join(p.epochDir, name)); return [name, stat ? stamp(stat) : null]; }) : [];
99
+ // One global active.json slot is always reserved, whether that fence exists yet or not. Only the live window is charged (#288).
88
100
  const renewal=renewalIntentObjects(p.home);
89
101
  if (files.size + 1 + renewal.count > PLACEMENT_JOURNAL_MAX_OBJECTS) fail("bound");
90
102
  const fence = state(join(p.root, "active.json"));
91
- return { files, renewalObjects:renewal.count, token: canonicalJSON({ parents, renewal:renewal.token, files: [...files].map(([name, stat]) => [name, String(stat.dev), String(stat.ino), String(stat.size), String(stat.mtimeNs), String(stat.ctimeNs)]),
103
+ return { files, renewalObjects:renewal.count, token: canonicalJSON({ parents, renewal:renewal.token, window: placementWindowToken(p.home, p.hash), metadata, files: [...files].map(([name, stat]) => [name, String(stat.dev), String(stat.ino), String(stat.size), String(stat.mtimeNs), String(stat.ctimeNs)]),
92
104
  fence: fence ? [String(fence.dev), String(fence.ino), String(fence.size), String(fence.mtimeNs), String(fence.ctimeNs)] : null }) };
93
105
  }
94
106
  function readOwned(file: string, maximum: number): Buffer | undefined {
@@ -138,17 +150,52 @@ let journalSnapshot: { token: string; value: Snapshot } | undefined;
138
150
  /** #462: the validated batch intent by its exact bytes; a pure function of content, so a hit cannot change a result. */
139
151
  let batchIntentMemo: { key: string; value: PlacementBatchIntent } | undefined;
140
152
  /** Drop every decoded journal/publication memo; a sync calls this when it ends so a resident host never keeps a journal's records. */
141
- export function releasePlacementStorageCaches(): void { journalPrefix = undefined; journalTail = undefined; journalSnapshot = undefined; publicationBundle = undefined; reservationRoot = undefined; batchIntentMemo = undefined; reservedNamesMemo = undefined; }
153
+ export function releasePlacementStorageCaches(): void { journalPrefix = undefined; journalTail = undefined; journalSnapshot = undefined; publicationBundle = undefined; reservationRoot = undefined; batchIntentMemo = undefined; reservedNamesMemo = undefined; archiveReplay = undefined; releasePlacementCheckpointCaches(); }
142
154
  // Records are frozen and shared (the bulk); every small mutable field is a fresh copy, so a caller's mutation never reaches the memo.
143
155
  const detachSnapshot = (value: Snapshot): Snapshot => ({ ...value, records: value.records.map(freeze), chunks: value.chunks.map(chunk => ({ ...chunk })), projection: value.projection.clone(),
144
156
  epoch: structuredClone(value.epoch), activation: structuredClone(value.activation),
145
157
  ...(value.intent ? { intent: structuredClone(value.intent) } : {}), ...(value.batchIntent ? { batchIntent: freeze(value.batchIntent) } : {}), ...(value.pendingBatch ? { pendingBatch: { ...value.pendingBatch } } : {}), ...(value.pendingRecord ? { pendingRecord: structuredClone(value.pendingRecord) } : {}) });
158
+ /**
159
+ * #288: the replayed frozen windows for one committed checkpoint chain, keyed by the resolver's token and the last manifest.
160
+ * The replay is verified once against the sealed projection snapshot; later snapshots replay only the live tail.
161
+ */
162
+ let archiveReplay: { key: string; records: PlacementRecord[]; chunks: Chunk[]; projection: PlacementProjection } | undefined;
163
+ /** Archived chunks are closed: their reported size is the chunk ceiling, so no append or reservation ever reuses one. */
164
+ function replayArchive(p: Paths, epoch: PlacementEpoch): { records: PlacementRecord[]; chunks: Chunk[]; projection: PlacementProjection } | undefined {
165
+ const manifest = p.window.manifests.at(-1); if (!manifest) return undefined;
166
+ const key = canonicalJSON([p.hash, manifest.seal, p.window.token]);
167
+ if (archiveReplay?.key === key) return { records: [...archiveReplay.records], chunks: archiveReplay.chunks.map(chunk => ({ ...chunk })), projection: archiveReplay.projection.clone() };
168
+ const projection = new PlacementProjection(epoch), records: PlacementRecord[] = [], chunks: Chunk[] = [];
169
+ for (const [index, chunk] of archivedChunks(p).entries()) {
170
+ if (chunk.name !== `records-${String(index).padStart(5, "0")}.jsonl`) fail();
171
+ const bytes = readOwned(join(chunk.dir, chunk.name), PLACEMENT_JOURNAL_CHUNK_MAX_BYTES);
172
+ if (!bytes?.length || bytes.length !== chunk.member.size || digest(bytes) !== chunk.member.sha256) fail();
173
+ let start = 0;
174
+ while (start < bytes.length) {
175
+ const end = bytes.indexOf(10, start); if (end < 0 || end === start) fail();
176
+ if (records.length >= PLACEMENT_JOURNAL_MAX_RECORDS) fail("bound");
177
+ const row = decode(bytes.subarray(start, end + 1), validatePlacementRecord); projection.apply(row); records.push(freeze(row)); start = end + 1;
178
+ }
179
+ chunks.push({ name: chunk.name, size: PLACEMENT_JOURNAL_CHUNK_MAX_BYTES, hash: chunk.member.sha256 });
180
+ }
181
+ const sealed = p.window.projection;
182
+ if (chunks.length !== manifest.journal.chunks || projection.sequence !== manifest.journal.sequence || projection.headHash !== manifest.journal.headHash
183
+ || !sealed || sealed.projectionHash !== projection.digest()) fail();
184
+ archiveReplay = { key, records: [...records], chunks: chunks.map(chunk => ({ ...chunk })), projection: projection.clone() };
185
+ return { records, chunks, projection };
186
+ }
187
+ function epochMetadataStamp(p: Paths): string {
188
+ const stat = state(join(p.epochDir, "epoch.json")); if (!stat) fail("changed"); return stamp(stat);
189
+ }
146
190
  function snapshot(p: Paths): Snapshot {
191
+ // #288: a started checkpoint owns the window until resume or abandon; no journal reader treats it as settled.
192
+ if (p.window.pending) fail("checkpoint-pending");
147
193
  const before = inventory(p);
148
194
  if (journalSnapshot?.token === canonicalJSON([p.dir, before.token])) return detachSnapshot(journalSnapshot.value);
149
- const epoch = decode(readOwned(join(p.dir, "epoch.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementEpoch);
195
+ const epoch = decode(readOwned(join(p.epochDir, "epoch.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementEpoch);
150
196
  if (placementEpochHash(epoch) !== p.hash) return fail("conflict");
151
- const plan = decode(readOwned(join(p.dir, "activation.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), value => activation(epoch, p.hash, value));
197
+ const plan = decode(readOwned(join(p.epochDir, "activation.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), value => activation(epoch, p.hash, value));
198
+ if (p.window.manifests.some(manifest => manifest.activationHash !== plan.seal)) fail("conflict");
152
199
  const pendingBytes = readOwned(join(p.dir, "append-intent.json"), PLACEMENT_BATCH_INTENT_MAX_BYTES);
153
200
  const intentPending = pendingBytes !== undefined && (!pendingBytes.length || pendingBytes.at(-1) !== 10);
154
201
  let pending: Intent | undefined, batch: PlacementBatchIntent | undefined;
@@ -162,6 +209,8 @@ function snapshot(p: Paths): Snapshot {
162
209
  else { if (pendingBytes.length > PLACEMENT_JOURNAL_ROOT_MAX_BYTES) fail("bound"); pending = decode(pendingBytes, value => intent(value, p.hash)); }
163
210
  }
164
211
  let projection = new PlacementProjection(epoch); const records: PlacementRecord[] = [], chunks: Chunk[] = [];
212
+ const archive = replayArchive(p, epoch), base = archive?.chunks.length ?? 0;
213
+ if (archive) { projection = archive.projection; records.push(...archive.records); chunks.push(...archive.chunks); }
165
214
  const apply = (bytes: Buffer) => {
166
215
  let start = 0;
167
216
  while (start < bytes.length) {
@@ -171,17 +220,18 @@ function snapshot(p: Paths): Snapshot {
171
220
  }
172
221
  };
173
222
  const chunkNames = [...before.files.keys()].filter(name => /^records-\d{5}\.jsonl$/.test(name));
174
- const prefixKey = (count: number) => canonicalJSON([p.dir, stamp(before.files.get("epoch.json")!), chunkNames.slice(0, count).map(name => [name, stamp(before.files.get(name)!)])]);
223
+ const prefixKey = (count: number) => canonicalJSON([p.dir, epochMetadataStamp(p), archive ? p.window.token : null, chunkNames.slice(0, count).map(name => [name, stamp(before.files.get(name)!)])]);
175
224
  // #462: a batch only touches its own chunks, so a prefix that ends before the batch's first chunk is still exact.
176
- const batchStart = batch ? Number(batch.chunks[0]!.name.slice(8, 13)) : Infinity;
225
+ const batchStart = batch ? Number(batch.chunks[0]!.name.slice(8, 13)) - base : Infinity;
177
226
  const cached = journalPrefix && journalPrefix.count < chunkNames.length && journalPrefix.count <= batchStart && journalPrefix.key === prefixKey(journalPrefix.count) ? journalPrefix : undefined;
178
227
  let batchPartial = false;
179
228
  let prefix: typeof journalPrefix, tail: typeof journalTail;
180
- if (cached) { projection = cached.projection.clone(); records.push(...cached.records); chunks.push(...cached.chunks); }
229
+ if (cached) { projection = cached.projection.clone(); records.length = 0; records.push(...cached.records); chunks.length = 0; chunks.push(...cached.chunks); }
181
230
  for (const [index, name] of chunkNames.entries()) {
182
231
  if (index < (cached?.count ?? 0)) continue;
183
232
  if (!batch && index > 0 && index === chunkNames.length - 1) prefix = { key: prefixKey(index), count: index, records: records.map(freeze), chunks: [...chunks], projection: projection.clone() };
184
- if (name !== `records-${String(index).padStart(5, "0")}.jsonl`) fail();
233
+ // Chunk names stay global across windows: the live window continues after the archived chunks (#288).
234
+ if (name !== `records-${String(base + index).padStart(5, "0")}.jsonl`) fail();
185
235
  const bytes = readOwned(join(p.dir, name), PLACEMENT_JOURNAL_CHUNK_MAX_BYTES)!;
186
236
  const batchChunk = batch?.chunks.find(chunk => chunk.name === name);
187
237
  if (batchChunk) {
@@ -216,7 +266,7 @@ function snapshot(p: Paths): Snapshot {
216
266
  }
217
267
  if (pending) {
218
268
  const found = chunkNames.includes(pending.chunk);
219
- if (!found && (pending.chunk !== `records-${String(chunkNames.length).padStart(5, "0")}.jsonl` || pending.prefixBytes !== 0 || pending.prefixHash !== digest(Buffer.alloc(0)))) fail();
269
+ if (!found && (pending.chunk !== `records-${String(base + chunkNames.length).padStart(5, "0")}.jsonl` || pending.prefixBytes !== 0 || pending.prefixHash !== digest(Buffer.alloc(0)))) fail();
220
270
  if (!found && (projection.headHash !== pending.record.previousHash || projection.sequence + 1 !== pending.record.sequence)) fail();
221
271
  if (pending.record.sequence > PLACEMENT_JOURNAL_MAX_RECORDS) fail("bound");
222
272
  }
@@ -268,7 +318,8 @@ export function readPlacementJournal(home: string, epochHash: string): Placement
268
318
  export function placementWriterJournalToken(home:string,epochHash:string):string {
269
319
  return protectedIO(()=>{
270
320
  const p=paths(home,epochHash),dir=state(p.dir,true);if(!dir)fail("changed");
271
- const rows:unknown[]=[["directory",String(dir.dev),String(dir.ino),String(dir.mode),String(dir.uid)]];
321
+ // #288: a checkpoint commit moves the live window, so the window's own identity is part of the anchor token.
322
+ const rows:unknown[]=[["window",p.window.window,placementWindowToken(p.home,p.hash)],["directory",String(dir.dev),String(dir.ino),String(dir.mode),String(dir.uid)]];
272
323
  for(const name of names(p.dir,PLACEMENT_JOURNAL_MAX_OBJECTS-1))if(name.startsWith("records-")||name==="append-intent.json"){
273
324
  const s=state(join(p.dir,name));if(!s)fail("changed");
274
325
  rows.push([name,String(s.dev),String(s.ino),String(s.mode),String(s.uid),String(s.nlink),String(s.size),String(s.mtimeNs),String(s.ctimeNs)]);
@@ -286,6 +337,9 @@ function current(p: Paths, opts: PlacementStorageOptions, required: readonly str
286
337
  try { assertMutationHandle(opts.mutation, p.home); } catch { return fail("busy"); }
287
338
  try { opts.assertCurrent(); } catch (error) { if (knownError(error)) throw error; return fail("changed"); }
288
339
  try { assertMutationHandle(opts.mutation, p.home); } catch { return fail("busy"); }
340
+ // #288: a started checkpoint refuses every placement effect until it is resumed or abandoned; a committed one moved the window.
341
+ if (p.window.pending) fail("checkpoint-pending");
342
+ if (placementWindowToken(p.home, p.hash) !== p.window.token) fail("changed");
289
343
  const found = inventory(p), names = new Set([...found.files.keys(), ...required, ...reservedPublicationJournalNames(p)]);
290
344
  if(found.renewalObjects)fail("pending");
291
345
  if (names.size + 1 + found.renewalObjects > PLACEMENT_JOURNAL_MAX_OBJECTS) fail("bound");
@@ -350,6 +404,7 @@ export function preparePlacementEpoch(home: string, value: PlacementEpoch, activ
350
404
  const epoch = validatePlacementEpoch(value), epochHash = placementEpochHash(epoch);
351
405
  writer(home, epochHash, opts, p => {
352
406
  const plan = activation(epoch, epochHash, activationPlan), required = ["epoch.json", "activation.json"];
407
+ if (p.window.window) fail("conflict"); // A checkpointed epoch was prepared long ago; its metadata is frozen.
353
408
  current(p, opts, required); directories(p, opts, required);
354
409
  complete(p, opts, join(p.dir, "epoch.json"), line(epoch), PLACEMENT_JOURNAL_ROOT_MAX_BYTES, required, "epoch-written", "epoch-fsync");
355
410
  complete(p, opts, join(p.dir, "activation.json"), line(plan), PLACEMENT_JOURNAL_ROOT_MAX_BYTES, required, "activation-written", "activation-fsync");
@@ -469,23 +524,30 @@ export interface PlacementPublicationStored {
469
524
  /** Validated plan bundle keyed by the stat stamps of epoch.json, the root and every plan chunk (#420); same ceiling as journalPrefix. */
470
525
  let publicationBundle: { key: string; bundle: PlacementPublicationBundle } | undefined;
471
526
  function publicationRead(p: Paths, attemptHash: string): PlacementPublicationStored {
472
- const stem = `publication-${attemptHash}-`, files = inventory(p).files;
473
- const keyOf = (found: Map<string, BigIntStats>) => canonicalJSON([p.dir, attemptHash, [...found].filter(([name]) => name === "epoch.json" || name === stem + "root.json" || name.startsWith(stem + "chunk-")).map(([name, stat]) => [name, stamp(stat)])]);
527
+ // #288: a completed publication frozen by a checkpoint resolves through the sealed catalog, never the live window.
528
+ // Its members were content-verified by the resolver, so their sealed hashes stand in for the live stat stamps.
529
+ const archived = p.window.catalog.get(attemptHash);
530
+ const dir = archived?.dir ?? p.dir, stem = `publication-${attemptHash}-`;
531
+ const files: Map<string, string> = archived ? new Map(archived.members.map(member => [member.name, member.sha256]))
532
+ : new Map([...inventory(p).files].map(([name, stat]) => [name, stamp(stat)]));
533
+ const keyOf = (found: Map<string, string>) => canonicalJSON([dir, attemptHash, epochMetadataStamp(p), [...found].filter(([name]) => name === stem + "root.json" || name.startsWith(stem + "chunk-"))]);
474
534
  const key = keyOf(files);
475
535
  let bundle = publicationBundle?.key === key ? publicationBundle.bundle : undefined;
476
536
  if (!bundle) {
477
- const root = decode(readOwned(join(p.dir, stem + "root.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementPublicationRoot);
478
- const epoch = decode(readOwned(join(p.dir, "epoch.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementEpoch);
537
+ const root = decode(readOwned(join(dir, stem + "root.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementPublicationRoot);
538
+ const epoch = decode(readOwned(join(p.epochDir, "epoch.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementEpoch);
479
539
  if (root.seal !== attemptHash || root.epochHash !== p.hash || root.generation !== epoch.generation || root.homeHash !== epoch.homeHash) fail("corrupt");
480
- const chunks = root.chunks.map(c => decode(readOwned(join(p.dir, `${stem}chunk-${String(c.index).padStart(5, "0")}.json`), PLACEMENT_JOURNAL_CHUNK_MAX_BYTES), value => value));
540
+ const chunks = root.chunks.map(c => decode(readOwned(join(dir, `${stem}chunk-${String(c.index).padStart(5, "0")}.json`), PLACEMENT_JOURNAL_CHUNK_MAX_BYTES), value => value));
481
541
  bundle = freeze(validatePlacementPublicationBundle({ root, chunks }));
482
- if (keyOf(inventory(p).files) === key) publicationBundle = { key, bundle }; // Never cache bytes read across a concurrent change.
542
+ const after = archived ? files : new Map([...inventory(p).files].map(([name, stat]) => [name, stamp(stat)]));
543
+ if (keyOf(after) === key) publicationBundle = { key, bundle }; // Never cache bytes read across a concurrent change.
483
544
  }
484
545
  const root = bundle.root, allowed = new Set(publicationFileNames(root));
485
546
  for (const name of files.keys()) if (name.startsWith(stem) && !allowed.has(name)) fail("corrupt");
547
+ if (archived && [...allowed].some(name => !files.has(name))) fail("corrupt");
486
548
  const facts: PlacementPublicationFact[] = []; let phase: PlacementPublicationStored["phase"] = "prepared", pending = false, absent = false; let pendingPhase: PlacementPublicationFact["phase"] | undefined;
487
549
  for (const [index, suffix] of ["artifact", "intent", "receipt"].entries()) {
488
- const bytes = readOwned(join(p.dir, stem + suffix + ".json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES);
550
+ const bytes = readOwned(join(dir, stem + suffix + ".json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES);
489
551
  if (bytes === undefined) fail("corrupt"); // Every future phase slot was reserved before root acknowledgement.
490
552
  if (!bytes.length) { absent = true; continue; }
491
553
  if (absent && (suffix !== "receipt" || pendingPhase)) fail("corrupt");
@@ -544,6 +606,44 @@ function reservedPublicationJournalNamesUncached(p: Paths): string[] {
544
606
  for (const root of complete) names.push(...placementPublicationReservedJournalNames(root, read, sizes));
545
607
  return names;
546
608
  }
609
+ /** #288 step 1: which holders fill the journal-objects bound. Counts only, never a name, path or row. */
610
+ export interface PlacementJournalObjectComposition {
611
+ epochFixed:number; writerHistory:number; journalChunks:number;
612
+ completedPublications:{ count:number; objects:number };
613
+ newPlan:{ chunks:number; slots:number; reservedJournalChunks:number } | null;
614
+ }
615
+ /**
616
+ * Splits the objects `assertPlanCapacity` counts, over exactly the inputs it counts: the epoch directory's names, one
617
+ * planned publication and the journal names that plan reserves. Every counted name lands in one class, so the parts
618
+ * always sum to the counted total, and a name outside the known families counts as fixed - `inventory()` has already
619
+ * refused an unknown epoch member, so the remainder is the epoch's own fixed set rather than a silent fifth holder.
620
+ * `plan` is absent where nothing is planned yet (the renewal preview), which reports `newPlan: null`.
621
+ */
622
+ export function placementJournalObjectComposition(input:{ names:readonly string[]; plan?:{ root:PlacementPublicationRoot; reserved:readonly string[] } }):PlacementJournalObjectComposition {
623
+ const planned = new Set(input.plan ? publicationFileNames(input.plan.root) : []), reserved = new Set(input.plan?.reserved ?? []);
624
+ // One global active.json slot is always reserved, whether that fence exists yet or not: the counted total's `+ 1`.
625
+ const composition:PlacementJournalObjectComposition = { epochFixed:1, writerHistory:0, journalChunks:0, completedPublications:{ count:0, objects:0 },
626
+ newPlan:input.plan ? { chunks:input.plan.root.chunks.length, slots:planned.size, reservedJournalChunks:reserved.size } : null };
627
+ const sealed = new Set<string>();
628
+ for (const name of new Set([...input.names, ...planned, ...reserved])) {
629
+ if (reserved.has(name) || planned.has(name)) continue; // counted in newPlan, whether or not the file already exists
630
+ if (writerHistoryFileLimit(name) !== undefined) { composition.writerHistory++; continue; }
631
+ if (/^records-\d{5}\.jsonl$/.test(name)) { composition.journalChunks++; continue; }
632
+ const attempt = publicationName(name) ? publicationPattern.exec(name)![1]! : undefined;
633
+ if (attempt) { sealed.add(attempt); composition.completedPublications.objects++; continue; }
634
+ composition.epochFixed++; // epoch.json, activation.json and a pending append-intent.json
635
+ }
636
+ composition.completedPublications.count = sealed.size;
637
+ return composition;
638
+ }
639
+ /** The composition as one numbers-only clause for a refusal or a preview, in the counted total's own order. */
640
+ export function placementJournalObjectCompositionText(composition:PlacementJournalObjectComposition):string {
641
+ const plan = composition.newPlan ? `, new plan ${composition.newPlan.chunks} chunks/${composition.newPlan.slots} slots/${composition.newPlan.reservedJournalChunks} reserved journal chunks` : "";
642
+ const sum = composition.epochFixed + composition.writerHistory + composition.journalChunks + composition.completedPublications.objects
643
+ + (composition.newPlan ? composition.newPlan.slots + composition.newPlan.reservedJournalChunks : 0);
644
+ return `Objects by holder (${sum}): epoch fixed ${composition.epochFixed}, writer history ${composition.writerHistory}, journal chunks ${composition.journalChunks}, `
645
+ + `completed publications ${composition.completedPublications.count} (${composition.completedPublications.objects} objects)${plan}.`;
646
+ }
547
647
  /** A complete (newline-terminated) root is immutable: keep the last decoded one by its stat stamp (#420), same ceiling as journalPrefix. */
548
648
  let reservationRoot: { key: string; root: PlacementPublicationRoot } | undefined;
549
649
  function publicationRootsForReservation(p: Paths): PlacementPublicationRoot[] {
@@ -584,6 +684,8 @@ export interface PlacementPublicationMetadataIO {
584
684
  names(): string[]; read(name: string): Buffer | undefined; journal(): PlacementJournalRead;
585
685
  reservedJournalNames(root: PlacementPublicationRoot): string[];
586
686
  publication(attemptHash: string): PlacementPublicationStored;
687
+ /** #288: completed publications frozen by a checkpoint, by attempt; `publication()` resolves them through the same catalog. */
688
+ archivedPublications(): string[];
587
689
  complete(name: string, bytes: Buffer, written: PlacementStoragePhase, synced: PlacementStoragePhase): boolean;
588
690
  check(): void;
589
691
  }
@@ -593,6 +695,7 @@ function metadataIO(p: Paths, opts?: PlacementStorageOptions, required: readonly
593
695
  names: () => [...inventory(p).files.keys()], read: name => readOwned(join(p.dir, name), valid(name)), journal: () => snapshot(p),
594
696
  reservedJournalNames: root => { const read = snapshot(p); return placementPublicationReservedJournalNames(root, read, read.chunks.map(c => c.size)); },
595
697
  publication: hash => { if (!hex(hash)) fail("invalid"); return publicationRead(p, hash); },
698
+ archivedPublications: () => [...p.window.catalog.keys()].sort(),
596
699
  complete: (name, bytes, written, synced) => { const maximum = valid(name); if (!opts || !required.includes(name)) fail("invalid"); return complete(p, opts, join(p.dir, name), bytes, maximum, required, written, synced); },
597
700
  check: () => { if (opts) current(p, opts, required); else inventory(p); },
598
701
  };
@@ -609,7 +712,7 @@ export function readPlacementPublicationMetadata<T>(home: string, epochHash: str
609
712
  return capturePlacementPublicationMetadata(home, epochHash, work).value;
610
713
  }
611
714
  function assertPublicationActive(p: Paths): void {
612
- const epoch = decode(readOwned(join(p.dir, "epoch.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementEpoch);
715
+ const epoch = decode(readOwned(join(p.epochDir, "epoch.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementEpoch);
613
716
  const profile = decode(readOwned(join(p.home, "profile.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementProfile);
614
717
  decode(readOwned(join(p.home, "shards.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), value => validatePlacementShards(value, profile));
615
718
  const fence = decode(readOwned(join(p.root, "active.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementActiveFence);
@@ -4,14 +4,14 @@ import { canonicalJSON, hashJSON } from "./generation.ts";
4
4
  import type { OutboundVerdict } from "./sync-screen.ts";
5
5
  import { PLACEMENT_SOURCE_MAX_BYTES, PLACEMENT_SOURCE_MAX_ROWS, PlacementSyncBoundError } from "./sync-placement-bound.ts";
6
6
  import type { PlacementCapture } from "./sync-placement-capture.ts";
7
- import { compilePlacementDependencies, type DependencySource, type VerifiedDependencyEndpoint } from "./sync-placement-dependencies.ts";
8
- import { compilePlacementGitObjects, type PlannedGitObject } from "./sync-placement-git.ts";
7
+ import { compilePlacementDependenciesAsync, type DependencySource, type VerifiedDependencyEndpoint } from "./sync-placement-dependencies.ts";
8
+ import { compilePlacementGitObjectsAsync, type PlannedGitObject } from "./sync-placement-git.ts";
9
9
  import { PLACEMENT_DESCRIPTOR_SCHEMA, PLACEMENT_FORMAT } from "./sync-placement-format.ts";
10
10
  import { placementKeyId, type PlacementKey, type PlacementRealm } from "./sync-placement-journal-format.ts";
11
11
  import type { PlacementProjection } from "./sync-placement-projection.ts";
12
12
  import type { PlacementPublicationBundle, PlacementPublicationDecision, PlacementPublicationObject, PlacementPublicationTarget } from "./sync-placement-publication-plan.ts";
13
13
  import type { ShardHistory } from "./shard-sync-history.ts";
14
- import { decodeShardPack, encodeShardPacks, encodeShardManifest, shardSyncRef, type ShardSyncRow, type ShardSyncRealm } from "./shard-sync-format.ts";
14
+ import { decodeShardPack, encodeShardPacksAsync, encodeShardManifest, shardSyncRef, type ShardSyncRow, type ShardSyncRealm } from "./shard-sync-format.ts";
15
15
  import { cooperativeYield, type CooperativeYield } from "./sync-placement-yield.ts";
16
16
  import { verifyPublicPruneWitness, type PublicPruneWitnessV1, type PublicPruneLineage } from "./public-prune-witness.ts";
17
17
  import type { Entry } from "./store.ts";
@@ -65,7 +65,9 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
65
65
  // (and its writer proofs), so an unsupported source set refuses before any expensive per-row work (#419).
66
66
  const admitted: Omit<DependencySource, "policy">[] = [], seenSources = new Set<string>();
67
67
  const prunedByTarget = new Map(workTargets.map(target => [target, target.pruned]));
68
+ let collected = 0;
68
69
  for (const source of capture.rows.values()) {
70
+ if (++collected % 64 === 0) await pause();
69
71
  const target = workTargets.find(target => sameRealm(physical(target), source.key.realm)); if (!target) refuse();
70
72
  const pruned = prunedByTarget.get(target)!.has(source.key.id) && !target.fetched.has(source.key.id);
71
73
  if (pruned) blocked.add(placementKeyId(source.key));
@@ -78,12 +80,14 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
78
80
  // Incoming verified occurrences are selected immutable originals too. Classify them before import so a private
79
81
  // remote goal cannot temporarily authorize a new dependent, and exposure/holds are durable in this same attempt.
80
82
  for(const [index,target]of workTargets.entries())for(const row of old[index]?.rows.values()??[])if(row.op!=="prune"||row.generation===target.generation){
83
+ if (++collected % 64 === 0) await pause();
81
84
  const key=keyFor(target,row),id=placementKeyId(key);if(seenSources.has(id))continue;seenSources.add(id);
82
85
  admitted.push({key,row,sourcePlacement:"synced",held:!!projection.get(key)?.held});
83
86
  }
84
87
  // Source size, not outbound size: local and declined rows count too, because their decisions are bound in the plan.
85
88
  if (admitted.length > PLACEMENT_SOURCE_MAX_ROWS) throw new PlacementSyncBoundError({ phase: "materialization", kind: "source-rows", limit: PLACEMENT_SOURCE_MAX_ROWS, observed: admitted.length });
86
- let sourceBytes = 0; for (const source of admitted) sourceBytes += Buffer.byteLength(canonicalJSON(source.row));
89
+ let sourceBytes = 0;
90
+ for (const [at, source] of admitted.entries()) { if (at % 64 === 0) await pause(); sourceBytes += Buffer.byteLength(canonicalJSON(source.row)); }
87
91
  if (sourceBytes > PLACEMENT_SOURCE_MAX_BYTES) throw new PlacementSyncBoundError({ phase: "materialization", kind: "source-bytes", limit: PLACEMENT_SOURCE_MAX_BYTES, observed: sourceBytes });
88
92
  input.progress?.phase("policy-evaluation", "rows", admitted.length);
89
93
  for (const source of admitted) { await pause(); sources.push({ ...source, policy: input.evaluate(source.row) }); input.progress?.advance(); }
@@ -107,15 +111,18 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
107
111
  let decisions: PlacementPublicationDecision[] = [];
108
112
  for (let pass = 0; pass < 2; pass++) {
109
113
  await pause();
110
- decisions = compilePlacementDependencies({ generation: input.generation, selectedRealms: workTargets.map(physical), rows:sources, publicEndpoints:endpoints,
111
- verifiedPrunes:sources.filter(source => verified.has(placementKeyId(source.key))).map(source => source.key) }).map(decision => {
112
- const source = sourceMap.get(placementKeyId(decision.key))!;
113
- const index=workTargets.findIndex(target=>sameRealm(physical(target),decision.key.realm));
114
- const original=old[index]?.rows.get(decision.key.id), published=!!original&&hashJSON(original)===decision.key.rowHash;
115
- const reason=blocked.has(placementKeyId(decision.key)) && !projection.get(decision.key)?.held ? "related-local" : decision.reason ?? null;
116
- return { ...decision, sourcePlacement:source.sourcePlacement, reason,
117
- hold:!decision.eligible&&(reason!=="source-local"||published)&&!projection.get(decision.key)?.held };
118
- });
114
+ const compiled = await compilePlacementDependenciesAsync({ generation: input.generation, selectedRealms: workTargets.map(physical), rows:sources, publicEndpoints:endpoints,
115
+ verifiedPrunes:sources.filter(source => verified.has(placementKeyId(source.key))).map(source => source.key) }, pause);
116
+ decisions = [];
117
+ for (const [at, decision] of compiled.entries()) {
118
+ if (at % 64 === 0) await pause();
119
+ const source = sourceMap.get(placementKeyId(decision.key))!;
120
+ const index=workTargets.findIndex(target=>sameRealm(physical(target),decision.key.realm));
121
+ const original=old[index]?.rows.get(decision.key.id), published=!!original&&hashJSON(original)===decision.key.rowHash;
122
+ const reason=blocked.has(placementKeyId(decision.key)) && !projection.get(decision.key)?.held ? "related-local" : decision.reason ?? null;
123
+ decisions.push({ ...decision, sourcePlacement:source.sourcePlacement, reason,
124
+ hold:!decision.eligible&&(reason!=="source-local"||published)&&!projection.get(decision.key)?.held });
125
+ }
119
126
  let rejected = false;
120
127
  for (const [index,target] of workTargets.entries()) {
121
128
  await pause();
@@ -123,7 +130,7 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
123
130
  const publish = descriptorVerdicts[index]!.ok && (!!old[index] || eligible.size > 0); publishes[index] = publish;
124
131
  if (publish) files.set("shard.json", Buffer.from(canonicalJSON({schema:PLACEMENT_DESCRIPTOR_SCHEMA,...target.realm,publicationFormat:PLACEMENT_FORMAT})+"\n"));
125
132
  const additions = sources.filter(source => sameRealm(source.key.realm,physical(target)) && eligible.has(source.key.id) && !old[index]?.rows.has(source.key.id)).map(source => source.row as ShardSyncRow);
126
- for (const [path,bytes] of encodeShardPacks(additions)) { const prior = files.get(path); if (prior && !prior.equals(bytes)) refuse(); files.set(path,bytes); }
133
+ for (const [path,bytes] of await encodeShardPacksAsync(additions,pause)) { const prior = files.get(path); if (prior && !prior.equals(bytes)) refuse(); files.set(path,bytes); }
127
134
  const manifests = new Map(old[index]?.manifests), occurrences = new Map<string,{pack:string;blob:string}>();
128
135
  for (const [path,bytes] of files) if (path.startsWith("rows/")) {
129
136
  // #462: one Git blob id per pack, not one per row in it (was quadratic in pack size); same value.
@@ -150,7 +157,7 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
150
157
  if(pass===0&&index===0)input.progress?.phase("artifact-construction");
151
158
  if(publish){
152
159
  const previous=old[index]&&target.remote?{tree:await input.readTree(index,frozen?.root.targets[index]?.expectedRemoteHead??target.remote!),commit:frozen?.root.targets[index]?.expectedRemoteHead??target.remote!}:undefined;
153
- const objects=compilePlacementGitObjects(files,frozen?.root.targets[index]?.expectedRemoteHead??target.remote??null,createdUnixSeconds,previous);target.objects=objects.objects;target.commit=objects.commit;
160
+ const objects=await compilePlacementGitObjectsAsync(files,frozen?.root.targets[index]?.expectedRemoteHead??target.remote??null,createdUnixSeconds,previous,pause);target.objects=objects.objects;target.commit=objects.commit;
154
161
  for(const [path,manifest]of manifests)if(manifest.commit==="0".repeat(40))manifests.set(path,{...manifest,commit:objects.commit});
155
162
  }else target.commit=target.remote;
156
163
  const rows=new Map(old[index]?.rows);for(const row of additions)rows.set(row.id,row);
@@ -158,13 +165,20 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
158
165
  }
159
166
  if(!rejected)break;if(pass===1)refuse();
160
167
  }
161
- const plannedTargets:PlacementPublicationTarget[]=workTargets.map((target,index)=>{
168
+ const plannedTargets: PlacementPublicationTarget[] = [];
169
+ for (const [index, target] of workTargets.entries()) {
162
170
  const publish=publishes[index]!,descriptor=target.candidate?.files.get("shard.json");
163
- return{realm:physical(target),publish,refHash:digest(shardSyncRef(target.realm)),expectedRemoteHead:frozen?.root.targets[index]?.expectedRemoteHead??target.remote??null,
171
+ // #470: the export set hashes every row of the target; it is built in chunks so one 8,000-row target cannot hold the loop.
172
+ const exportRows: { id: string; rowHash: string }[] = [];
173
+ for (const [at, row] of [...target.candidate!.rows.values()].entries()) {
174
+ if (at % 64 === 0) await pause();
175
+ exportRows.push({ id: row.id, rowHash: hashJSON(row) });
176
+ }
177
+ plannedTargets[index]={realm:physical(target),publish,refHash:digest(shardSyncRef(target.realm)),expectedRemoteHead:frozen?.root.targets[index]?.expectedRemoteHead??target.remote??null,
164
178
  expectedCacheHead:frozen?.root.targets[index]?.expectedCacheHead??target.local??null,descriptorHash:digest(descriptor??Buffer.alloc(0)),
165
- exportSetHash:hashJSON([...target.candidate!.rows.values()].map(row=>({id:row.id,rowHash:hashJSON(row)})).sort((a,b)=>a.id.localeCompare(b.id))),
179
+ exportSetHash:hashJSON(exportRows.sort((a,b)=>a.id.localeCompare(b.id))),
166
180
  tree:publish?target.objects.find(object=>object.type==="tree"&&object.path==="")!.oid:target.remote?frozen?.root.targets[index]?.tree??null:null,commit:target.commit??null};
167
- });
181
+ }
168
182
  for(const [index,target]of workTargets.entries())if(!plannedTargets[index]!.publish&&target.remote)plannedTargets[index]!.tree=await input.readTree(index,target.remote);
169
183
  const objects:PlacementPublicationObject[]=workTargets.flatMap((target,targetIndex)=>target.objects.map(object=>({targetIndex,type:object.type,path:object.path === "" ? null : object.path,oid:object.oid,sha256:digest(object.bytes),size:object.bytes.length})));
170
184
  return {decisions,targets:workTargets.map(target=>({candidate:target.candidate!,objects:target.objects,commit:target.commit})),plannedTargets,objects};
@@ -1,5 +1,5 @@
1
1
  import { types } from "node:util";
2
- import { canonicalJSON } from "./generation.ts";
2
+ import { canonicalJSON, hashJSON } from "./generation.ts";
3
3
  import {
4
4
  SyncPlacementJournalError, PLACEMENT_JOURNAL_MAX_RECORDS, placementEpochHash, placementKeyId,
5
5
  validatePlacementEpoch, validatePlacementKey, validatePlacementRecord,
@@ -32,6 +32,12 @@ export class PlacementProjection {
32
32
  for (const [key, value] of this.#requests) out.#requests.set(key, value);
33
33
  return out;
34
34
  }
35
+ /** #288: one hash of the whole projected state (states, row identities, requests, frontier); a checkpoint seals it. */
36
+ digest(): string {
37
+ const sorted = <T>(map: Map<string, T>) => [...map].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
38
+ return hashJSON(["agent-mem.sync-placement-projection-digest/v1", this.#epochHash, this.#sequence, this.#headHash,
39
+ sorted(this.#states), sorted(this.#rowHashes), sorted(this.#requests).map(([id, record]) => [id, record.seal])]);
40
+ }
35
41
  get epochHash(): string { return this.#epochHash; }
36
42
  get sequence(): number { return this.#sequence; }
37
43
  get headHash(): string { return this.#headHash; }
@@ -0,0 +1,42 @@
1
+ /** Shared pure event scheduling for sync and read-only prospective planning. */
2
+ import { canonicalJSON, hashJSON } from "./generation.ts";
3
+ import { placementKeyId, type PlacementEvent, type PlacementHoldReason, type PlacementRealm } from "./sync-placement-journal-format.ts";
4
+ import type { PlacementProjection } from "./sync-placement-projection.ts";
5
+ import type { PlacementPublicationBundle, PlacementPublicationDecision } from "./sync-placement-publication-plan.ts";
6
+ import type { ShardHistory } from "./shard-sync-history.ts";
7
+ import { PlacementSyncRefusal } from "./sync-placement-refusal.ts";
8
+ const sameRealm = (a: PlacementRealm, b: PlacementRealm) => canonicalJSON(a) === canonicalJSON(b);
9
+ function refuse(): never { throw new PlacementSyncRefusal(); }
10
+
11
+ export function* placementPublicationEventSteps(bundle:PlacementPublicationBundle,projection:PlacementProjection,old:(ShardHistory|undefined)[]):Generator<void,{events:PlacementEvent[];preCount:number;holdCount:number},void>{
12
+ const decisions=bundle.chunks.filter(chunk=>chunk.kind==="decisions").flatMap(chunk=>chunk.items as PlacementPublicationDecision[]).sort((a,b)=>placementKeyId(a.key).localeCompare(placementKeyId(b.key)));
13
+ const holds:PlacementEvent[]=[],known:PlacementEvent[]=[],ambiguous:PlacementEvent[]=[],committed:PlacementEvent[]=[];
14
+ const root=bundle.root;
15
+ const make=(decision:PlacementPublicationDecision,kind:PlacementEvent["kind"],commit?:string):PlacementEvent=>{
16
+ const base={requestId:hashJSON({attempt:root.seal,key:decision.key,kind,commit:commit??null}),key:decision.key,sourcePlacement:decision.sourcePlacement,
17
+ effectHash:hashJSON({attempt:root.seal,context:root.contextHash,key:decision.key,kind,commit:commit??null})};
18
+ if(kind==="hold"){
19
+ const reason=decision.reason;
20
+ const hold:PlacementHoldReason=reason==="secret"||reason==="personal-data"||reason==="deny-path"||reason==="private-or-invalid"||reason==="host"||reason==="person-local"?reason:"related-local";
21
+ return{...base,kind,reason:hold};
22
+ }
23
+ const index=root.targets.findIndex(target=>sameRealm(target.realm,decision.key.realm));if(index<0)refuse();
24
+ const outcome={attemptHash:root.seal,remoteHash:root.remoteHash,refHash:root.targets[index]!.refHash};
25
+ if(kind==="publication-ambiguous")return{...base,kind,outcome};
26
+ if(kind!=="publication-committed"||!commit)refuse();
27
+ return{...base,kind,outcome:{...outcome,commit,proofHash:hashJSON({attempt:root.seal,key:decision.key,commit,remote:root.remoteHash,ref:root.targets[index]!.refHash})}};
28
+ };
29
+ let stepped=0;
30
+ for(const decision of decisions){
31
+ if(++stepped>=64){stepped=0;yield;}
32
+ const state=projection.get(decision.key);
33
+ const index=root.targets.findIndex(target=>sameRealm(target.realm,decision.key.realm)),target=root.targets[index];if(!target)refuse();
34
+ const original=old[index]?.rows.get(decision.key.id),published=original&&hashJSON(original)===decision.key.rowHash;
35
+ if(decision.hold)holds.push(make(decision,"hold"));
36
+ if(published&&state?.exposure!=="published"&&target.expectedRemoteHead)known.push(make(decision,"publication-committed",target.expectedRemoteHead));
37
+ if(decision.eligible&&target.publish&&!published){
38
+ ambiguous.push(make(decision,"publication-ambiguous"));committed.push(make(decision,"publication-committed",target.commit!));
39
+ }
40
+ }
41
+ return{events:[...holds,...known,...ambiguous,...committed],preCount:holds.length+known.length+ambiguous.length,holdCount:holds.length};
42
+ }
@@ -4,6 +4,7 @@ import { createHash } from "node:crypto";
4
4
  import { canonicalJSON, hashJSON } from "./generation.ts";
5
5
  import { validatePlacementKey, placementKeyId, SyncPlacementJournalError, PLACEMENT_JOURNAL_MAX_RECORDS, PLACEMENT_JOURNAL_MAX_OBJECTS,
6
6
  PLACEMENT_JOURNAL_CHUNK_MAX_BYTES, PLACEMENT_JOURNAL_ROOT_MAX_BYTES, type PlacementKey, type PlacementRealm, type PlacementHoldReason } from "./sync-placement-journal-format.ts";
7
+ import { drainSteps, drainStepsAsync, type CooperativeYield } from "./sync-placement-yield.ts";
7
8
 
8
9
  export const PLACEMENT_PUBLICATION_PLAN_SCHEMA = "agent-mem.sync-placement-publication-plan/v1";
9
10
  export const PLACEMENT_PUBLICATION_CHUNK_SCHEMA = "agent-mem.sync-placement-publication-chunk/v1";
@@ -150,11 +151,26 @@ export function validatePlacementPublicationBundle(input: unknown): PlacementPub
150
151
  export function planPlacementPublication(input: Omit<PlacementPublicationRoot, "schema" | "chunks" | "seal">, items: {
151
152
  sources: readonly PlacementPublicationSource[]; decisions: readonly PlacementPublicationDecision[]; objects: readonly PlacementPublicationObject[];
152
153
  }): PlacementPublicationBundle {
154
+ return drainSteps(planSteps(input, items));
155
+ }
156
+ /** #470: the same bundle, awaiting the caller's event loop between chunk items; chunk boundaries and hashes are identical. */
157
+ export async function planPlacementPublicationAsync(input: Omit<PlacementPublicationRoot, "schema" | "chunks" | "seal">, items: {
158
+ sources: readonly PlacementPublicationSource[]; decisions: readonly PlacementPublicationDecision[]; objects: readonly PlacementPublicationObject[];
159
+ }, yieldPoint?: CooperativeYield): Promise<PlacementPublicationBundle> {
160
+ return await drainStepsAsync(planSteps(input, items), yieldPoint);
161
+ }
162
+ /** Items between step boundaries: at most 64 canonicalized chunk items per uninterrupted stretch. */
163
+ const STEP_ITEMS = 64;
164
+ function* planSteps(input: Omit<PlacementPublicationRoot, "schema" | "chunks" | "seal">, items: {
165
+ sources: readonly PlacementPublicationSource[]; decisions: readonly PlacementPublicationDecision[]; objects: readonly PlacementPublicationObject[];
166
+ }): Generator<void, PlacementPublicationBundle, void> {
153
167
  const values = object(items, kinds), chunks: PlacementPublicationChunk[] = [];
168
+ let stepped = 0;
154
169
  for (const kind of kinds) {
155
170
  let selected: PlacementPublicationChunk["items"] = [], selectedBytes = 0;
156
171
  const flush = () => { if (selected.length) { chunks.push(validatePlacementPublicationChunk({ schema: PLACEMENT_PUBLICATION_CHUNK_SCHEMA, kind, index: chunks.length, items: selected })); selected = []; selectedBytes = 0; } };
157
172
  for (const value of array(values[kind], PLACEMENT_JOURNAL_MAX_RECORDS)) {
173
+ if (++stepped >= STEP_ITEMS) { stepped = 0; yield; }
158
174
  // #462: the candidate chunk's exact canonical size, summed per item instead of re-serializing the whole chunk per row
159
175
  // (quadratic). canonicalJSON of an array is its items' canonical forms joined by commas, so the sum is identical.
160
176
  const row = item(kind, value), rowBytes = Buffer.byteLength(canonicalJSON(row));
@@ -165,7 +181,8 @@ export function planPlacementPublication(input: Omit<PlacementPublicationRoot, "
165
181
  flush();
166
182
  }
167
183
  const body = { ...object(input, ["epochHash", "generation", "homeHash", "contextHash", "markerHash", "sourceHash", "aliasesHash", "policyHash", "remoteHash", "journal", "reservedRecords", "reservedRecordBytes", "createdUnixSeconds", "policySnapshotUnixMs", "targets"]), schema: PLACEMENT_PUBLICATION_PLAN_SCHEMA,
168
- chunks: chunks.map(c => ({ kind: c.kind, index: c.index, hash: publicationHash(publicationBytes(c)), count: c.items.length, bytes: publicationBytes(c).length })) };
184
+ // #470: each chunk is serialized once here; the descriptor only needs its hash and length.
185
+ chunks: chunks.map(c => { const bytes = publicationBytes(c); return { kind: c.kind, index: c.index, hash: publicationHash(bytes), count: c.items.length, bytes: bytes.length }; }) };
169
186
  const { seal: _seal, ...safeBody } = normalizedRoot({ ...body, seal: "0".repeat(64) }, false);
170
187
  return validatePlacementPublicationBundle({ root: { ...safeBody, seal: hashJSON(safeBody) }, chunks });
171
188
  }