@staix/agent-mem 0.28.2 → 0.30.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 (73) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +17 -11
  3. package/package.json +3 -2
  4. package/src/brief-work.ts +142 -0
  5. package/src/cli.ts +97 -17
  6. package/src/commands-table.ts +6 -0
  7. package/src/mcp-memory.ts +37 -9
  8. package/src/memory/bridge.ts +26 -1
  9. package/src/memory/capacity.ts +5 -2
  10. package/src/memory/catalog.ts +10 -1
  11. package/src/memory/commands.ts +5 -3
  12. package/src/memory/curated-cache-state.ts +10 -7
  13. package/src/memory/doctor.ts +32 -26
  14. package/src/memory/formats.ts +4 -3
  15. package/src/memory/generation-index.ts +79 -17
  16. package/src/memory/index-file.ts +2 -2
  17. package/src/memory/intent-brief.ts +34 -6
  18. package/src/memory/metrics.ts +174 -14
  19. package/src/memory/shard-bridge.ts +18 -6
  20. package/src/memory/shard-sync-format.ts +18 -0
  21. package/src/memory/shard-sync-history.ts +6 -0
  22. package/src/memory/shard-sync.ts +52 -4
  23. package/src/memory/shard.ts +33 -13
  24. package/src/memory/store.ts +147 -41
  25. package/src/memory/sync-placement-bound.ts +21 -4
  26. package/src/memory/sync-placement-cache.ts +16 -1
  27. package/src/memory/sync-placement-capture.ts +67 -19
  28. package/src/memory/sync-placement-checkpoint-format.ts +199 -0
  29. package/src/memory/sync-placement-checkpoint-person.ts +209 -0
  30. package/src/memory/sync-placement-checkpoint-prospective.ts +141 -0
  31. package/src/memory/sync-placement-checkpoint-storage.ts +218 -0
  32. package/src/memory/sync-placement-checkpoint.ts +234 -0
  33. package/src/memory/sync-placement-dependencies.ts +42 -9
  34. package/src/memory/sync-placement-effective-writers.ts +12 -6
  35. package/src/memory/sync-placement-git.ts +17 -7
  36. package/src/memory/sync-placement-guard.ts +52 -1
  37. package/src/memory/sync-placement-inspection-evidence.ts +1 -1
  38. package/src/memory/sync-placement-inventory.ts +141 -0
  39. package/src/memory/sync-placement-journal-format.ts +4 -1
  40. package/src/memory/sync-placement-journal-storage.ts +148 -28
  41. package/src/memory/sync-placement-journal.ts +13 -4
  42. package/src/memory/sync-placement-materialize.ts +47 -22
  43. package/src/memory/sync-placement-projection.ts +7 -1
  44. package/src/memory/sync-placement-publication-events.ts +42 -0
  45. package/src/memory/sync-placement-publication-plan.ts +26 -5
  46. package/src/memory/sync-placement-realm-admission-storage.ts +128 -0
  47. package/src/memory/sync-placement-realm-admission.ts +352 -0
  48. package/src/memory/sync-placement-realm-attribution.ts +23 -0
  49. package/src/memory/sync-placement-realm-discovery.ts +42 -0
  50. package/src/memory/sync-placement-realm-effective.ts +71 -0
  51. package/src/memory/sync-placement-realm-extension-format.ts +66 -0
  52. package/src/memory/sync-placement-realm-extension-storage.ts +82 -0
  53. package/src/memory/sync-placement-realm-intent-format.ts +55 -0
  54. package/src/memory/sync-placement-realm-intent-storage.ts +123 -0
  55. package/src/memory/sync-placement-realm-pending.ts +27 -0
  56. package/src/memory/sync-placement-realm-proof.ts +131 -0
  57. package/src/memory/sync-placement-realm-torn.ts +26 -0
  58. package/src/memory/sync-placement-remote-admission.ts +190 -0
  59. package/src/memory/sync-placement-remote-adoption-format.ts +54 -0
  60. package/src/memory/sync-placement-remote-materialization.ts +49 -0
  61. package/src/memory/sync-placement-remote-refusal.ts +21 -0
  62. package/src/memory/sync-placement-remote-stage.ts +275 -0
  63. package/src/memory/sync-placement-transport.ts +268 -79
  64. package/src/memory/sync-placement-writer-history.ts +75 -17
  65. package/src/memory/sync-placement-writer-renewal.ts +18 -10
  66. package/src/memory/sync-placement-writer-revision-format.ts +16 -13
  67. package/src/memory/sync-placement-yield.ts +44 -0
  68. package/src/memory/sync-progress.ts +47 -6
  69. package/src/memory/sync.ts +26 -1
  70. package/src/memory/work-lists.ts +129 -9
  71. package/src/session-brief.ts +34 -1
  72. package/src/sync-placement-writer-context.ts +5 -5
  73. package/src/ui/plugin.ts +1 -1
@@ -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 {
@@ -135,27 +147,70 @@ let journalPrefix: { key: string; count: number; records: PlacementRecord[]; chu
135
147
  let journalTail: { key: string; name: string; bytes: Buffer; records: PlacementRecord[]; projection: PlacementProjection } | undefined;
136
148
  /** Whole snapshot for an unchanged inventory token (every file snapshot reads is in it). Callers get fresh arrays and a projection clone. */
137
149
  let journalSnapshot: { token: string; value: Snapshot } | undefined;
150
+ /** #462: the validated batch intent by its exact bytes; a pure function of content, so a hit cannot change a result. */
151
+ let batchIntentMemo: { key: string; value: PlacementBatchIntent } | undefined;
138
152
  /** Drop every decoded journal/publication memo; a sync calls this when it ends so a resident host never keeps a journal's records. */
139
- export function releasePlacementStorageCaches(): void { journalPrefix = undefined; journalTail = undefined; journalSnapshot = undefined; publicationBundle = undefined; reservationRoot = undefined; }
153
+ export function releasePlacementStorageCaches(): void { journalPrefix = undefined; journalTail = undefined; journalSnapshot = undefined; publicationBundle = undefined; reservationRoot = undefined; batchIntentMemo = undefined; reservedNamesMemo = undefined; archiveReplay = undefined; releasePlacementCheckpointCaches(); }
140
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.
141
155
  const detachSnapshot = (value: Snapshot): Snapshot => ({ ...value, records: value.records.map(freeze), chunks: value.chunks.map(chunk => ({ ...chunk })), projection: value.projection.clone(),
142
156
  epoch: structuredClone(value.epoch), activation: structuredClone(value.activation),
143
- ...(value.intent ? { intent: structuredClone(value.intent) } : {}), ...(value.batchIntent ? { batchIntent: structuredClone(value.batchIntent) } : {}), ...(value.pendingBatch ? { pendingBatch: { ...value.pendingBatch } } : {}), ...(value.pendingRecord ? { pendingRecord: structuredClone(value.pendingRecord) } : {}) });
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
+ }
144
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");
145
193
  const before = inventory(p);
146
194
  if (journalSnapshot?.token === canonicalJSON([p.dir, before.token])) return detachSnapshot(journalSnapshot.value);
147
- 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);
148
196
  if (placementEpochHash(epoch) !== p.hash) return fail("conflict");
149
- 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");
150
199
  const pendingBytes = readOwned(join(p.dir, "append-intent.json"), PLACEMENT_BATCH_INTENT_MAX_BYTES);
151
200
  const intentPending = pendingBytes !== undefined && (!pendingBytes.length || pendingBytes.at(-1) !== 10);
152
201
  let pending: Intent | undefined, batch: PlacementBatchIntent | undefined;
153
202
  if (pendingBytes && !intentPending) {
154
203
  const parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(pendingBytes)) as { schema?: unknown };
155
- if (parsed?.schema === "agent-mem.sync-placement-append-intent/v2") batch = decode(pendingBytes, value => validatePlacementBatchIntent(value, p.hash));
204
+ if (parsed?.schema === "agent-mem.sync-placement-append-intent/v2") {
205
+ const key = canonicalJSON([p.hash, digest(pendingBytes)]);
206
+ batch = batchIntentMemo?.key === key ? batchIntentMemo.value : freeze(decode(pendingBytes, value => validatePlacementBatchIntent(value, p.hash)));
207
+ batchIntentMemo = { key, value: batch };
208
+ }
156
209
  else { if (pendingBytes.length > PLACEMENT_JOURNAL_ROOT_MAX_BYTES) fail("bound"); pending = decode(pendingBytes, value => intent(value, p.hash)); }
157
210
  }
158
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); }
159
214
  const apply = (bytes: Buffer) => {
160
215
  let start = 0;
161
216
  while (start < bytes.length) {
@@ -165,15 +220,18 @@ function snapshot(p: Paths): Snapshot {
165
220
  }
166
221
  };
167
222
  const chunkNames = [...before.files.keys()].filter(name => /^records-\d{5}\.jsonl$/.test(name));
168
- 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)!)])]);
169
- const cached = !batch && journalPrefix && journalPrefix.count < chunkNames.length && journalPrefix.key === prefixKey(journalPrefix.count) ? journalPrefix : undefined;
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)!)])]);
224
+ // #462: a batch only touches its own chunks, so a prefix that ends before the batch's first chunk is still exact.
225
+ const batchStart = batch ? Number(batch.chunks[0]!.name.slice(8, 13)) - base : Infinity;
226
+ const cached = journalPrefix && journalPrefix.count < chunkNames.length && journalPrefix.count <= batchStart && journalPrefix.key === prefixKey(journalPrefix.count) ? journalPrefix : undefined;
170
227
  let batchPartial = false;
171
228
  let prefix: typeof journalPrefix, tail: typeof journalTail;
172
- 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); }
173
230
  for (const [index, name] of chunkNames.entries()) {
174
231
  if (index < (cached?.count ?? 0)) continue;
175
232
  if (!batch && index > 0 && index === chunkNames.length - 1) prefix = { key: prefixKey(index), count: index, records: records.map(freeze), chunks: [...chunks], projection: projection.clone() };
176
- 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();
177
235
  const bytes = readOwned(join(p.dir, name), PLACEMENT_JOURNAL_CHUNK_MAX_BYTES)!;
178
236
  const batchChunk = batch?.chunks.find(chunk => chunk.name === name);
179
237
  if (batchChunk) {
@@ -208,7 +266,7 @@ function snapshot(p: Paths): Snapshot {
208
266
  }
209
267
  if (pending) {
210
268
  const found = chunkNames.includes(pending.chunk);
211
- 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();
212
270
  if (!found && (projection.headHash !== pending.record.previousHash || projection.sequence + 1 !== pending.record.sequence)) fail();
213
271
  if (pending.record.sequence > PLACEMENT_JOURNAL_MAX_RECORDS) fail("bound");
214
272
  }
@@ -260,7 +318,8 @@ export function readPlacementJournal(home: string, epochHash: string): Placement
260
318
  export function placementWriterJournalToken(home:string,epochHash:string):string {
261
319
  return protectedIO(()=>{
262
320
  const p=paths(home,epochHash),dir=state(p.dir,true);if(!dir)fail("changed");
263
- 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)]];
264
323
  for(const name of names(p.dir,PLACEMENT_JOURNAL_MAX_OBJECTS-1))if(name.startsWith("records-")||name==="append-intent.json"){
265
324
  const s=state(join(p.dir,name));if(!s)fail("changed");
266
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)]);
@@ -278,6 +337,9 @@ function current(p: Paths, opts: PlacementStorageOptions, required: readonly str
278
337
  try { assertMutationHandle(opts.mutation, p.home); } catch { return fail("busy"); }
279
338
  try { opts.assertCurrent(); } catch (error) { if (knownError(error)) throw error; return fail("changed"); }
280
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");
281
343
  const found = inventory(p), names = new Set([...found.files.keys(), ...required, ...reservedPublicationJournalNames(p)]);
282
344
  if(found.renewalObjects)fail("pending");
283
345
  if (names.size + 1 + found.renewalObjects > PLACEMENT_JOURNAL_MAX_OBJECTS) fail("bound");
@@ -342,6 +404,7 @@ export function preparePlacementEpoch(home: string, value: PlacementEpoch, activ
342
404
  const epoch = validatePlacementEpoch(value), epochHash = placementEpochHash(epoch);
343
405
  writer(home, epochHash, opts, p => {
344
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.
345
408
  current(p, opts, required); directories(p, opts, required);
346
409
  complete(p, opts, join(p.dir, "epoch.json"), line(epoch), PLACEMENT_JOURNAL_ROOT_MAX_BYTES, required, "epoch-written", "epoch-fsync");
347
410
  complete(p, opts, join(p.dir, "activation.json"), line(plan), PLACEMENT_JOURNAL_ROOT_MAX_BYTES, required, "activation-written", "activation-fsync");
@@ -461,23 +524,30 @@ export interface PlacementPublicationStored {
461
524
  /** Validated plan bundle keyed by the stat stamps of epoch.json, the root and every plan chunk (#420); same ceiling as journalPrefix. */
462
525
  let publicationBundle: { key: string; bundle: PlacementPublicationBundle } | undefined;
463
526
  function publicationRead(p: Paths, attemptHash: string): PlacementPublicationStored {
464
- const stem = `publication-${attemptHash}-`, files = inventory(p).files;
465
- 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-"))]);
466
534
  const key = keyOf(files);
467
535
  let bundle = publicationBundle?.key === key ? publicationBundle.bundle : undefined;
468
536
  if (!bundle) {
469
- const root = decode(readOwned(join(p.dir, stem + "root.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementPublicationRoot);
470
- 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);
471
539
  if (root.seal !== attemptHash || root.epochHash !== p.hash || root.generation !== epoch.generation || root.homeHash !== epoch.homeHash) fail("corrupt");
472
- 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));
473
541
  bundle = freeze(validatePlacementPublicationBundle({ root, chunks }));
474
- 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.
475
544
  }
476
545
  const root = bundle.root, allowed = new Set(publicationFileNames(root));
477
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");
478
548
  const facts: PlacementPublicationFact[] = []; let phase: PlacementPublicationStored["phase"] = "prepared", pending = false, absent = false; let pendingPhase: PlacementPublicationFact["phase"] | undefined;
479
549
  for (const [index, suffix] of ["artifact", "intent", "receipt"].entries()) {
480
- 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);
481
551
  if (bytes === undefined) fail("corrupt"); // Every future phase slot was reserved before root acknowledgement.
482
552
  if (!bytes.length) { absent = true; continue; }
483
553
  if (absent && (suffix !== "receipt" || pendingPhase)) fail("corrupt");
@@ -518,7 +588,16 @@ export function placementPublicationReservedJournalNames(root: PlacementPublicat
518
588
  if (consumed < root.reservedRecords) names.push("append-intent.json");
519
589
  return names;
520
590
  }
591
+ /** #462: reserved names for one exact inventory token. Every input (roots, receipts, chunks, intent) lives under that token, the same trust journalSnapshot uses. */
592
+ let reservedNamesMemo: { token: string; names: string[] } | undefined;
521
593
  function reservedPublicationJournalNames(p: Paths): string[] {
594
+ const token = canonicalJSON([p.dir, inventory(p).token]);
595
+ if (reservedNamesMemo?.token === token) return [...reservedNamesMemo.names];
596
+ const names = reservedPublicationJournalNamesUncached(p);
597
+ if (canonicalJSON([p.dir, inventory(p).token]) === token) reservedNamesMemo = { token, names: [...names] };
598
+ return names;
599
+ }
600
+ function reservedPublicationJournalNamesUncached(p: Paths): string[] {
522
601
  // A partial root has no acknowledgement and blocks append through checkPublicationAppend. Its exact preparer
523
602
  // passes its entire required-name reservation on every write. Complete roots enforce reservations globally.
524
603
  const complete = publicationRootsForReservation(p); if (!complete.length) return [];
@@ -527,6 +606,44 @@ function reservedPublicationJournalNames(p: Paths): string[] {
527
606
  for (const root of complete) names.push(...placementPublicationReservedJournalNames(root, read, sizes));
528
607
  return names;
529
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
+ }
530
647
  /** A complete (newline-terminated) root is immutable: keep the last decoded one by its stat stamp (#420), same ceiling as journalPrefix. */
531
648
  let reservationRoot: { key: string; root: PlacementPublicationRoot } | undefined;
532
649
  function publicationRootsForReservation(p: Paths): PlacementPublicationRoot[] {
@@ -567,6 +684,8 @@ export interface PlacementPublicationMetadataIO {
567
684
  names(): string[]; read(name: string): Buffer | undefined; journal(): PlacementJournalRead;
568
685
  reservedJournalNames(root: PlacementPublicationRoot): string[];
569
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[];
570
689
  complete(name: string, bytes: Buffer, written: PlacementStoragePhase, synced: PlacementStoragePhase): boolean;
571
690
  check(): void;
572
691
  }
@@ -576,6 +695,7 @@ function metadataIO(p: Paths, opts?: PlacementStorageOptions, required: readonly
576
695
  names: () => [...inventory(p).files.keys()], read: name => readOwned(join(p.dir, name), valid(name)), journal: () => snapshot(p),
577
696
  reservedJournalNames: root => { const read = snapshot(p); return placementPublicationReservedJournalNames(root, read, read.chunks.map(c => c.size)); },
578
697
  publication: hash => { if (!hex(hash)) fail("invalid"); return publicationRead(p, hash); },
698
+ archivedPublications: () => [...p.window.catalog.keys()].sort(),
579
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); },
580
700
  check: () => { if (opts) current(p, opts, required); else inventory(p); },
581
701
  };
@@ -592,7 +712,7 @@ export function readPlacementPublicationMetadata<T>(home: string, epochHash: str
592
712
  return capturePlacementPublicationMetadata(home, epochHash, work).value;
593
713
  }
594
714
  function assertPublicationActive(p: Paths): void {
595
- 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);
596
716
  const profile = decode(readOwned(join(p.home, "profile.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementProfile);
597
717
  decode(readOwned(join(p.home, "shards.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), value => validatePlacementShards(value, profile));
598
718
  const fence = decode(readOwned(join(p.root, "active.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementActiveFence);
@@ -1,5 +1,6 @@
1
1
  import { validatePlacementProfile, validatePlacementShards } from "./sync-placement-format.ts";
2
2
  import { assertPlacementViewAdvance } from "./sync-placement-active.ts";
3
+ import { readEffectiveRealmInventoryFor } from "./sync-placement-realm-effective.ts";
3
4
  import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
4
5
  import { types } from "node:util";
5
6
  import { randomBytes } from "node:crypto";
@@ -9,7 +10,7 @@ import { memoryPolicySnapshot } from "./policy.ts";
9
10
  import { outboundPolicyEvaluator, type RowScreen } from "./sync-screen.ts";
10
11
  import { assertPlacementRuntime } from "./sync-placement-guard.ts";
11
12
  import { PLACEMENT_FORMAT } from "./sync-placement-format.ts";
12
- import { planSyncPlacementActivation, validatePlacementPlan, validateSyncPlacementActivation, type SyncPlacementActivationPlan } from "./sync-placement-plan.ts";
13
+ import { planSyncPlacementActivation, validatePlacementPlan, validateSyncPlacementActivation, type SyncPlacementActivationPlan, type SyncPlacementRealmBinding } from "./sync-placement-plan.ts";
13
14
  import { captureSyncPlacementContext, placementCaptureContextHash, type PlacementCapturePort, type PlacementCapture } from "./sync-placement-capture.ts";
14
15
  import { PLACEMENT_EPOCH_SCHEMA, placementEpochHash, placementKeyId, validatePlacementEpoch, validatePlacementKey, validatePlacementEvent,
15
16
  SyncPlacementJournalError, type PlacementEpoch, type PlacementKey, type PlacementCommittedOutcome, type PlacementAmbiguousOutcome } from "./sync-placement-journal-format.ts";
@@ -93,13 +94,21 @@ function active(home: string, input: PlacementEffectRequest, port: PlacementCapt
93
94
  if (capture.activeHead !== input.epochHash || journal.epoch.homeHash !== capture.context.homeHash
94
95
  || journal.epoch.generation !== (capture.context.profile as { generation: string }).generation
95
96
  || journal.activation.targetProfile.placementHead !== input.epochHash
96
- || canonicalJSON(capture.context.writers) !== canonicalJSON(capture.writerInventory?.writers??journal.activation.writers)
97
- || canonicalJSON(capture.context.realms.map(({ bindingHash: _hash, ...identity }) => identity))
98
- !== canonicalJSON(journal.activation.realms.map(({ bindingHash: _hash, ...identity }) => identity))) fail("changed");
97
+ || canonicalJSON(capture.context.writers) !== canonicalJSON(capture.writerInventory?.writers??journal.activation.writers)) fail("changed");
99
98
  const markers = readPlacementRuntimeMarkers(capture.home), profile = validatePlacementProfile(markers.profile);
99
+ // #448: a capture holds the verified effective inventory, so a hold placed before an admission still validates after
100
+ // it, while an extension that no longer verifies closes the chain instead of widening what an effect may act on.
101
+ const inventory = readEffectiveRealmInventoryFor(capture.home, { epochHash: input.epochHash, activationHash: journal.activation.seal,
102
+ homeHash: journal.epoch.homeHash, generation: journal.epoch.generation, realms: journal.activation.realms });
103
+ // The two lists are ordered differently (an activation keeps `user` last, the inventory puts it first), so compare the
104
+ // realm identities as a set.
105
+ const identities = (value: readonly SyncPlacementRealmBinding[]): string[] => value
106
+ .map(item => canonicalJSON(item.scope === "user" ? { scope: "user" } : { scope: "project", keyHash: item.keyHash })).sort();
107
+ if (canonicalJSON(identities(capture.context.realms)) !== canonicalJSON(identities(inventory.realms))) fail("changed");
100
108
  assertPlacementViewAdvance(capture.home, journal.activation, profile, validatePlacementShards(markers.shards, profile));
101
109
  const projection = rebuildPlacementProjection(journal.epoch, journal.records);
102
110
  const source = capture.rows.get(placementKeyId(input.key)); if (!source) fail("changed");
111
+ inventory.assertCurrent();
103
112
  return { capture, journal, projection, source };
104
113
  }
105
114
  type Decision = { kind: "hold"; mode: "policy" | "person" } | { kind: "release" }
@@ -4,14 +4,15 @@ 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
+ import { cooperativeYield, type CooperativeYield } from "./sync-placement-yield.ts";
15
16
  import { verifyPublicPruneWitness, type PublicPruneWitnessV1, type PublicPruneLineage } from "./public-prune-witness.ts";
16
17
  import type { Entry } from "./store.ts";
17
18
  import type { PruneRow } from "./prune.ts";
@@ -27,6 +28,8 @@ export interface PlacementMaterializeInput {
27
28
  readTree(index: number, head: string): Promise<string>;
28
29
  publisherLineages(index: number, rows: readonly PruneRow[]): ReadonlyMap<string, PublicPruneLineage>;
29
30
  createdUnixSeconds: number; frozen?: PlacementPublicationBundle;
31
+ /** #462: awaited between per-row items so the caller's event loop is never held for a whole realm; defaults to a time-budgeted yield. */
32
+ yieldPoint?: CooperativeYield;
30
33
  /** Advisory telemetry only (#418): phase names and unit counts, never a row, key or verdict detail. */
31
34
  progress?: { phase(name: "policy-evaluation" | "dependency-decisions" | "artifact-construction", unit?: "rows", total?: number): void; advance(): void };
32
35
  }
@@ -55,13 +58,16 @@ export function verifiedPlacementPrunes(targets: readonly PlacementPruneProofTar
55
58
  }
56
59
  export async function materializePlacementRows(input: PlacementMaterializeInput): Promise<PlacementMaterializeResult> {
57
60
  const {capture,projection,old,frozen,createdUnixSeconds}=input;
61
+ const pause = input.yieldPoint ?? cooperativeYield();
58
62
  const workTargets = input.targets.map(target => ({...target,objects:[] as PlannedGitObject[],commit:undefined as string|undefined,candidate:undefined as ShardHistory|undefined}));
59
63
  const sources: DependencySource[] = [], blocked = new Set<string>(), verified = input.verifiedPrunes;
60
64
  // Collect every selected original first: size admission below is pure and precedes the first policy evaluation
61
65
  // (and its writer proofs), so an unsupported source set refuses before any expensive per-row work (#419).
62
66
  const admitted: Omit<DependencySource, "policy">[] = [], seenSources = new Set<string>();
63
67
  const prunedByTarget = new Map(workTargets.map(target => [target, target.pruned]));
68
+ let collected = 0;
64
69
  for (const source of capture.rows.values()) {
70
+ if (++collected % 64 === 0) await pause();
65
71
  const target = workTargets.find(target => sameRealm(physical(target), source.key.realm)); if (!target) refuse();
66
72
  const pruned = prunedByTarget.get(target)!.has(source.key.id) && !target.fetched.has(source.key.id);
67
73
  if (pruned) blocked.add(placementKeyId(source.key));
@@ -74,16 +80,19 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
74
80
  // Incoming verified occurrences are selected immutable originals too. Classify them before import so a private
75
81
  // remote goal cannot temporarily authorize a new dependent, and exposure/holds are durable in this same attempt.
76
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();
77
84
  const key=keyFor(target,row),id=placementKeyId(key);if(seenSources.has(id))continue;seenSources.add(id);
78
85
  admitted.push({key,row,sourcePlacement:"synced",held:!!projection.get(key)?.held});
79
86
  }
80
87
  // Source size, not outbound size: local and declined rows count too, because their decisions are bound in the plan.
81
88
  if (admitted.length > PLACEMENT_SOURCE_MAX_ROWS) throw new PlacementSyncBoundError({ phase: "materialization", kind: "source-rows", limit: PLACEMENT_SOURCE_MAX_ROWS, observed: admitted.length });
82
- 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)); }
83
91
  if (sourceBytes > PLACEMENT_SOURCE_MAX_BYTES) throw new PlacementSyncBoundError({ phase: "materialization", kind: "source-bytes", limit: PLACEMENT_SOURCE_MAX_BYTES, observed: sourceBytes });
84
92
  input.progress?.phase("policy-evaluation", "rows", admitted.length);
85
- for (const source of admitted) { sources.push({ ...source, policy: input.evaluate(source.row) }); input.progress?.advance(); }
93
+ for (const source of admitted) { await pause(); sources.push({ ...source, policy: input.evaluate(source.row) }); input.progress?.advance(); }
86
94
  input.progress?.phase("dependency-decisions");
95
+ await pause();
87
96
  // Strong endpoints are already in sources and current holds cannot be bypassed by past publication. Only
88
97
  // deletion/prune exceptions need a second verified occurrence fact; do not duplicate every historical body.
89
98
  const publicNeeded=new Set<string>();
@@ -101,29 +110,38 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
101
110
  const sourceMap = new Map(sources.map(source => [placementKeyId(source.key), source]));
102
111
  let decisions: PlacementPublicationDecision[] = [];
103
112
  for (let pass = 0; pass < 2; pass++) {
104
- decisions = compilePlacementDependencies({ generation: input.generation, selectedRealms: workTargets.map(physical), rows:sources, publicEndpoints:endpoints,
105
- verifiedPrunes:sources.filter(source => verified.has(placementKeyId(source.key))).map(source => source.key) }).map(decision => {
106
- const source = sourceMap.get(placementKeyId(decision.key))!;
107
- const index=workTargets.findIndex(target=>sameRealm(physical(target),decision.key.realm));
108
- const original=old[index]?.rows.get(decision.key.id), published=!!original&&hashJSON(original)===decision.key.rowHash;
109
- const reason=blocked.has(placementKeyId(decision.key)) && !projection.get(decision.key)?.held ? "related-local" : decision.reason ?? null;
110
- return { ...decision, sourcePlacement:source.sourcePlacement, reason,
111
- hold:!decision.eligible&&(reason!=="source-local"||published)&&!projection.get(decision.key)?.held };
112
- });
113
+ await pause();
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
+ }
113
126
  let rejected = false;
114
127
  for (const [index,target] of workTargets.entries()) {
128
+ await pause();
115
129
  const files = new Map(old[index]?.files), eligible = new Set(decisions.filter(decision => decision.eligible && sameRealm(decision.key.realm,physical(target))).map(decision => decision.key.id));
116
130
  const publish = descriptorVerdicts[index]!.ok && (!!old[index] || eligible.size > 0); publishes[index] = publish;
117
131
  if (publish) files.set("shard.json", Buffer.from(canonicalJSON({schema:PLACEMENT_DESCRIPTOR_SCHEMA,...target.realm,publicationFormat:PLACEMENT_FORMAT})+"\n"));
118
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);
119
- 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); }
120
134
  const manifests = new Map(old[index]?.manifests), occurrences = new Map<string,{pack:string;blob:string}>();
121
- for (const [path,bytes] of files) if (path.startsWith("rows/")) for (const row of decodeShardPack(path,bytes,target.realm,target.generation))
122
- if (!occurrences.has(row.id)) occurrences.set(row.id,{pack:path,blob:createHash("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex")});
135
+ for (const [path,bytes] of files) if (path.startsWith("rows/")) {
136
+ // #462: one Git blob id per pack, not one per row in it (was quadratic in pack size); same value.
137
+ await pause(); const blob=createHash("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex");
138
+ for (const row of decodeShardPack(path,bytes,target.realm,target.generation)) if (!occurrences.has(row.id)) occurrences.set(row.id,{pack:path,blob});
139
+ }
123
140
  const native = additions.filter((row):row is PruneRow => row.op==="prune" && row.generation===target.generation);
124
141
  if (native.length) {
125
142
  const lineages = input.publisherLineages(index,native);
126
143
  for (const row of native) {
144
+ await pause();
127
145
  const lineage = lineages.get(row.id), own = occurrences.get(row.id); if (!lineage || !own) refuse();
128
146
  const needed = new Map<string,string>(); for (const item of row.targets) for (const ref of [item,item.basis]) needed.set(ref.id,ref.rowHash);
129
147
  const witnesses = [...needed].sort(([a],[b])=>a.localeCompare(b)).map(([id,rowHash])=>{ const place=occurrences.get(id); if(!place)refuse(); return{id,rowHash,...place}; });
@@ -139,7 +157,7 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
139
157
  if(pass===0&&index===0)input.progress?.phase("artifact-construction");
140
158
  if(publish){
141
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;
142
- 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;
143
161
  for(const [path,manifest]of manifests)if(manifest.commit==="0".repeat(40))manifests.set(path,{...manifest,commit:objects.commit});
144
162
  }else target.commit=target.remote;
145
163
  const rows=new Map(old[index]?.rows);for(const row of additions)rows.set(row.id,row);
@@ -147,13 +165,20 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
147
165
  }
148
166
  if(!rejected)break;if(pass===1)refuse();
149
167
  }
150
- const plannedTargets:PlacementPublicationTarget[]=workTargets.map((target,index)=>{
168
+ const plannedTargets: PlacementPublicationTarget[] = [];
169
+ for (const [index, target] of workTargets.entries()) {
151
170
  const publish=publishes[index]!,descriptor=target.candidate?.files.get("shard.json");
152
- 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,
153
178
  expectedCacheHead:frozen?.root.targets[index]?.expectedCacheHead??target.local??null,descriptorHash:digest(descriptor??Buffer.alloc(0)),
154
- 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))),
155
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};
156
- });
181
+ }
157
182
  for(const [index,target]of workTargets.entries())if(!plannedTargets[index]!.publish&&target.remote)plannedTargets[index]!.tree=await input.readTree(index,target.remote);
158
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})));
159
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
+ }