@staix/agent-mem 0.28.2 → 0.29.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 (40) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +11 -7
  3. package/package.json +1 -1
  4. package/src/brief-work.ts +142 -0
  5. package/src/cli.ts +34 -13
  6. package/src/commands-table.ts +2 -0
  7. package/src/mcp-memory.ts +1 -1
  8. package/src/memory/commands.ts +5 -3
  9. package/src/memory/curated-cache-state.ts +10 -7
  10. package/src/memory/doctor.ts +15 -12
  11. package/src/memory/generation-index.ts +79 -17
  12. package/src/memory/index-file.ts +2 -2
  13. package/src/memory/metrics.ts +1 -0
  14. package/src/memory/shard-sync-history.ts +6 -0
  15. package/src/memory/shard.ts +33 -13
  16. package/src/memory/store.ts +147 -41
  17. package/src/memory/sync-placement-capture.ts +53 -17
  18. package/src/memory/sync-placement-guard.ts +52 -1
  19. package/src/memory/sync-placement-inventory.ts +136 -0
  20. package/src/memory/sync-placement-journal-storage.ts +21 -4
  21. package/src/memory/sync-placement-journal.ts +13 -4
  22. package/src/memory/sync-placement-materialize.ts +14 -3
  23. package/src/memory/sync-placement-publication-plan.ts +8 -4
  24. package/src/memory/sync-placement-realm-admission-storage.ts +128 -0
  25. package/src/memory/sync-placement-realm-admission.ts +335 -0
  26. package/src/memory/sync-placement-realm-attribution.ts +23 -0
  27. package/src/memory/sync-placement-realm-effective.ts +71 -0
  28. package/src/memory/sync-placement-realm-extension-format.ts +66 -0
  29. package/src/memory/sync-placement-realm-extension-storage.ts +82 -0
  30. package/src/memory/sync-placement-realm-intent-format.ts +55 -0
  31. package/src/memory/sync-placement-realm-intent-storage.ts +123 -0
  32. package/src/memory/sync-placement-realm-pending.ts +27 -0
  33. package/src/memory/sync-placement-realm-proof.ts +131 -0
  34. package/src/memory/sync-placement-realm-torn.ts +26 -0
  35. package/src/memory/sync-placement-transport.ts +69 -31
  36. package/src/memory/sync-placement-yield.ts +30 -0
  37. package/src/memory/sync-progress.ts +47 -6
  38. package/src/memory/sync.ts +23 -1
  39. package/src/memory/work-lists.ts +129 -9
  40. package/src/session-brief.ts +34 -1
@@ -0,0 +1,136 @@
1
+ /**
2
+ * #450: one `amem sync` under an active placement covers the whole activated realm inventory, not only the cwd binding.
3
+ *
4
+ * The persisted publication plan still holds at most two targets (0.28.x readers validate exactly that), so the inventory
5
+ * runs as sequential publications of at most two realms each. Atomicity, journal, reservation and crash recovery are those
6
+ * of one publication, unchanged; nothing is atomic across the whole inventory. Order is deterministic: the user realm is
7
+ * in the first publication, then project realms by key hash. A publication that does not succeed stops the run before the
8
+ * next one. A retained publication reservation is resumed first, through its own realms, before any new publication.
9
+ *
10
+ * ponytail: ceil(N/2) publications. One N-target plan behind an explicitly raised `sync` floor is the upgrade path.
11
+ */
12
+ import { createHash } from "node:crypto";
13
+ import { existsSync, lstatSync } from "node:fs";
14
+ import { join } from "node:path";
15
+ import { readActivePlacementBinding } from "./sync-placement-active.ts";
16
+ import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
17
+ import { readPlacementJournal } from "./sync-placement-journal-storage.ts";
18
+ import { readPlacementPublication } from "./sync-placement-publication-storage.ts";
19
+ import { readEffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
20
+ import { readShardDescriptor, shardDir, userShardDir } from "./shard.ts";
21
+ import { projectState } from "./lifecycle.ts";
22
+ import type { PlacementRealm } from "./sync-placement-journal-format.ts";
23
+ import type { SyncOptions, SyncResult } from "./sync.ts";
24
+ import type { MemoryStore } from "./store.ts";
25
+
26
+ const digest = (value: string) => createHash("sha256").update(value).digest("hex");
27
+ const PUBLICATION_TARGETS = 2;
28
+
29
+ /** One activated realm with its local key (the project key is resolved from the local descriptor; user has none). */
30
+ export type InventoryRealm = { scope: "user" } | { scope: "project"; key: string; keyHash: string };
31
+ export type PlacementRealmOutcome = "committed" | "not-needed" | "unknown" | "failed" | "not-run" | "not-local" | "inactive";
32
+ /** Per-realm receipt: identifiers only (the user realm or the full key hash), never a project name, row or path. */
33
+ export interface PlacementRealmResult { realm: "user" | string; outcome: PlacementRealmOutcome; publication?: number }
34
+
35
+ const label = (realm: PlacementRealm | InventoryRealm): string => realm.scope === "user" ? "user" : realm.keyHash;
36
+
37
+ /** The effective activated inventory in publication order; realms without a local curated shard are reported, never opened or initialized.
38
+ * The inventory is the effective one (#448): a realm admitted after activation by an appended extension joins it exactly like an activated realm.
39
+ */
40
+ export function placementInventory(home: string): { local: InventoryRealm[]; missing: string[]; inactive: string[] } {
41
+ const markers = readPlacementRuntimeMarkers(home), active = readActivePlacementBinding(home, markers.profile, markers.shards);
42
+ if (!active) throw new Error("sync placement activation metadata unavailable or changed; inspect the retained activation before continuing");
43
+ const { realms } = readEffectiveRealmInventory(home, active);
44
+ const local: InventoryRealm[] = [], missing: string[] = [], inactive: string[] = [];
45
+ for (const realm of realms) {
46
+ if (realm.scope === "user") { if (existsSync(join(userShardDir(home), "generation.json"))) local.unshift({ scope: "user" }); else missing.push("user"); continue; }
47
+ const descriptor = readShardDescriptor(home, realm.keyHash.slice(0, 16));
48
+ if (!descriptor || digest(descriptor.key) !== realm.keyHash || !lstatSync(join(shardDir(home, descriptor.key), "generation.json"), { throwIfNoEntry: false })) { missing.push(realm.keyHash); continue; }
49
+ // An archived or forgotten project is never opened for publication; its realm is reported and left as it is.
50
+ if (projectState(home, descriptor.key) !== "active") { inactive.push(realm.keyHash); continue; }
51
+ local.push({ scope: "project", key: descriptor.key, keyHash: realm.keyHash });
52
+ }
53
+ const user = local.filter(realm => realm.scope === "user"), projects = local.filter((realm): realm is Extract<InventoryRealm, { scope: "project" }> => realm.scope === "project")
54
+ .sort((a, b) => a.keyHash < b.keyHash ? -1 : a.keyHash > b.keyHash ? 1 : 0);
55
+ return { local: [...user, ...projects], missing: missing.sort(), inactive: inactive.sort() };
56
+ }
57
+
58
+ /** Deterministic publication batches of at most two realms; the user realm is always in the first. */
59
+ export function placementInventoryBatches(realms: readonly InventoryRealm[]): InventoryRealm[][] {
60
+ const batches: InventoryRealm[][] = [];
61
+ for (let at = 0; at < realms.length; at += PUBLICATION_TARGETS) batches.push(realms.slice(at, at + PUBLICATION_TARGETS));
62
+ return batches;
63
+ }
64
+
65
+ export interface PlacementInventoryPorts {
66
+ /** Opens exactly one realm's curated shard (no user overlay, no alias stores). */
67
+ open(realm: InventoryRealm): MemoryStore;
68
+ /** Releases a store from `open`; a store the caller already held is left open. */
69
+ close(store: MemoryStore): void;
70
+ /** Runs one unchanged two-target placement publication over the given opened stores. */
71
+ publish(primary: MemoryStore, targets: readonly MemoryStore[], opts: SyncOptions): Promise<SyncResult>;
72
+ }
73
+
74
+ function sum(results: readonly SyncResult[]): Pick<SyncResult, "entries" | "pushed"> & { exported: number; withheld: number } {
75
+ return { entries: results.reduce((n, r) => n + r.entries, 0), pushed: results.some(r => r.pushed),
76
+ exported: results.reduce((n, r) => n + (r.placementPublication?.exported ?? 0), 0), withheld: results.reduce((n, r) => n + (r.placementPublication?.withheld ?? 0), 0) };
77
+ }
78
+
79
+ /** Retained publication realms (by label), when a reservation exists; resumed before any new publication. */
80
+ function retainedRealms(home: string): string[] | undefined {
81
+ const markers = readPlacementRuntimeMarkers(home), active = readActivePlacementBinding(home, markers.profile, markers.shards);
82
+ if (!active) return undefined;
83
+ const reservation = readPlacementJournal(home, active.profile.placementHead).publicationReservation;
84
+ if (!reservation) return undefined;
85
+ return readPlacementPublication(home, active.profile.placementHead, reservation.attemptHash).bundle.root.targets.map(target => label(target.realm));
86
+ }
87
+
88
+ export async function syncPlacementInventory(home: string, opts: SyncOptions, ports: PlacementInventoryPorts): Promise<SyncResult & { placementRealms: PlacementRealmResult[] }> {
89
+ const { local, missing, inactive } = placementInventory(home);
90
+ const retained = retainedRealms(home);
91
+ let order = local;
92
+ if (retained) {
93
+ // The retained plan names its own realms; it runs first, exactly as recorded, then the rest in the usual order.
94
+ const first = retained.map(name => local.find(realm => label(realm) === name));
95
+ if (first.some(realm => !realm)) throw new Error("a retained placement publication names a realm without a local curated shard; inspect it before continuing");
96
+ order = [...first as InventoryRealm[], ...local.filter(realm => !retained.includes(label(realm)))];
97
+ }
98
+ const batches = retained ? [order.slice(0, retained.length), ...placementInventoryBatches(order.slice(retained.length))] : placementInventoryBatches(order);
99
+ const realms: PlacementRealmResult[] = [...missing.map(realm => ({ realm, outcome: "not-local" as const })), ...inactive.map(realm => ({ realm, outcome: "inactive" as const }))];
100
+ const progress = opts.progress, total = batches.filter(batch => batch.length).length;
101
+ // One reporter for the whole run: each publication reports its phases, but only this driver reports the terminal state.
102
+ const report = (completed: number) => progress?.inventory({ publications: total, completed, realms: order.length,
103
+ outcomes: realms.map(item => ({ realm: item.realm === "user" ? "user" : item.realm.slice(0, 16), outcome: item.outcome })) });
104
+ progress?.deferFinish(true); report(0);
105
+ let completed = 0;
106
+ const results: SyncResult[] = [];
107
+ let stopped: SyncResult | undefined;
108
+ for (const [index, batch] of batches.entries()) {
109
+ if (!batch.length) continue;
110
+ if (stopped) { for (const realm of batch) realms.push({ realm: label(realm), outcome: "not-run" }); continue; }
111
+ if (opts.signal?.aborted) { stopped = { ok: false, pushed: false, entries: 0, error: "stopped", failure: { cause: "stopped" } }; for (const realm of batch) realms.push({ realm: label(realm), outcome: "not-run" }); continue; }
112
+ const stores: MemoryStore[] = [];
113
+ let result: SyncResult;
114
+ try {
115
+ for (const realm of batch) stores.push(ports.open(realm));
116
+ result = await ports.publish(stores[0]!, stores, opts);
117
+ } catch (error) {
118
+ result = { ok: false, pushed: false, entries: 0, error: (error as Error).message, failure: { cause: "unavailable" } };
119
+ } finally { for (const store of stores.reverse()) try { ports.close(store); } catch { /* preserve the publication result */ } }
120
+ results.push(result);
121
+ const outcome: PlacementRealmOutcome = result.ok ? result.placementPublication?.outcome ?? "not-needed" : result.placementPublication?.outcome === "unknown" ? "unknown" : "failed";
122
+ for (const realm of batch) realms.push({ realm: label(realm), outcome, publication: index + 1 });
123
+ if (!result.ok) stopped = result;
124
+ else completed++;
125
+ report(completed);
126
+ }
127
+ if (stopped) report(completed);
128
+ progress?.deferFinish(false);
129
+ if (stopped) progress?.finish(opts.signal?.aborted ? "cancelled" : "failed", opts.signal?.aborted ? "cancelled" : "unavailable");
130
+ else progress?.finish("succeeded");
131
+ const totals = sum(results), last = stopped ?? results.at(-1);
132
+ const base: SyncResult = last ? { ...last } : { ok: true, pushed: false, entries: 0 };
133
+ return { ...base, ok: !stopped, pushed: totals.pushed, entries: totals.entries,
134
+ ...(base.placementPublication ? { placementPublication: { ...base.placementPublication, exported: totals.exported, withheld: totals.withheld } } : {}),
135
+ ...(stopped?.error !== undefined ? { error: stopped.error } : {}), placementRealms: realms };
136
+ }
@@ -135,12 +135,14 @@ let journalPrefix: { key: string; count: number; records: PlacementRecord[]; chu
135
135
  let journalTail: { key: string; name: string; bytes: Buffer; records: PlacementRecord[]; projection: PlacementProjection } | undefined;
136
136
  /** Whole snapshot for an unchanged inventory token (every file snapshot reads is in it). Callers get fresh arrays and a projection clone. */
137
137
  let journalSnapshot: { token: string; value: Snapshot } | undefined;
138
+ /** #462: the validated batch intent by its exact bytes; a pure function of content, so a hit cannot change a result. */
139
+ let batchIntentMemo: { key: string; value: PlacementBatchIntent } | undefined;
138
140
  /** 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; }
141
+ export function releasePlacementStorageCaches(): void { journalPrefix = undefined; journalTail = undefined; journalSnapshot = undefined; publicationBundle = undefined; reservationRoot = undefined; batchIntentMemo = undefined; reservedNamesMemo = undefined; }
140
142
  // 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
143
  const detachSnapshot = (value: Snapshot): Snapshot => ({ ...value, records: value.records.map(freeze), chunks: value.chunks.map(chunk => ({ ...chunk })), projection: value.projection.clone(),
142
144
  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) } : {}) });
145
+ ...(value.intent ? { intent: structuredClone(value.intent) } : {}), ...(value.batchIntent ? { batchIntent: freeze(value.batchIntent) } : {}), ...(value.pendingBatch ? { pendingBatch: { ...value.pendingBatch } } : {}), ...(value.pendingRecord ? { pendingRecord: structuredClone(value.pendingRecord) } : {}) });
144
146
  function snapshot(p: Paths): Snapshot {
145
147
  const before = inventory(p);
146
148
  if (journalSnapshot?.token === canonicalJSON([p.dir, before.token])) return detachSnapshot(journalSnapshot.value);
@@ -152,7 +154,11 @@ function snapshot(p: Paths): Snapshot {
152
154
  let pending: Intent | undefined, batch: PlacementBatchIntent | undefined;
153
155
  if (pendingBytes && !intentPending) {
154
156
  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));
157
+ if (parsed?.schema === "agent-mem.sync-placement-append-intent/v2") {
158
+ const key = canonicalJSON([p.hash, digest(pendingBytes)]);
159
+ batch = batchIntentMemo?.key === key ? batchIntentMemo.value : freeze(decode(pendingBytes, value => validatePlacementBatchIntent(value, p.hash)));
160
+ batchIntentMemo = { key, value: batch };
161
+ }
156
162
  else { if (pendingBytes.length > PLACEMENT_JOURNAL_ROOT_MAX_BYTES) fail("bound"); pending = decode(pendingBytes, value => intent(value, p.hash)); }
157
163
  }
158
164
  let projection = new PlacementProjection(epoch); const records: PlacementRecord[] = [], chunks: Chunk[] = [];
@@ -166,7 +172,9 @@ function snapshot(p: Paths): Snapshot {
166
172
  };
167
173
  const chunkNames = [...before.files.keys()].filter(name => /^records-\d{5}\.jsonl$/.test(name));
168
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)!)])]);
169
- const cached = !batch && journalPrefix && journalPrefix.count < chunkNames.length && journalPrefix.key === prefixKey(journalPrefix.count) ? journalPrefix : undefined;
175
+ // #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;
177
+ const cached = journalPrefix && journalPrefix.count < chunkNames.length && journalPrefix.count <= batchStart && journalPrefix.key === prefixKey(journalPrefix.count) ? journalPrefix : undefined;
170
178
  let batchPartial = false;
171
179
  let prefix: typeof journalPrefix, tail: typeof journalTail;
172
180
  if (cached) { projection = cached.projection.clone(); records.push(...cached.records); chunks.push(...cached.chunks); }
@@ -518,7 +526,16 @@ export function placementPublicationReservedJournalNames(root: PlacementPublicat
518
526
  if (consumed < root.reservedRecords) names.push("append-intent.json");
519
527
  return names;
520
528
  }
529
+ /** #462: reserved names for one exact inventory token. Every input (roots, receipts, chunks, intent) lives under that token, the same trust journalSnapshot uses. */
530
+ let reservedNamesMemo: { token: string; names: string[] } | undefined;
521
531
  function reservedPublicationJournalNames(p: Paths): string[] {
532
+ const token = canonicalJSON([p.dir, inventory(p).token]);
533
+ if (reservedNamesMemo?.token === token) return [...reservedNamesMemo.names];
534
+ const names = reservedPublicationJournalNamesUncached(p);
535
+ if (canonicalJSON([p.dir, inventory(p).token]) === token) reservedNamesMemo = { token, names: [...names] };
536
+ return names;
537
+ }
538
+ function reservedPublicationJournalNamesUncached(p: Paths): string[] {
522
539
  // A partial root has no acknowledgement and blocks append through checkPublicationAppend. Its exact preparer
523
540
  // passes its entire required-name reservation on every write. Complete roots enforce reservations globally.
524
541
  const complete = publicationRootsForReservation(p); if (!complete.length) return [];
@@ -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" }
@@ -12,6 +12,7 @@ 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
14
  import { decodeShardPack, encodeShardPacks, 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,6 +58,7 @@ 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
@@ -82,8 +86,9 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
82
86
  let sourceBytes = 0; for (const source of admitted) sourceBytes += Buffer.byteLength(canonicalJSON(source.row));
83
87
  if (sourceBytes > PLACEMENT_SOURCE_MAX_BYTES) throw new PlacementSyncBoundError({ phase: "materialization", kind: "source-bytes", limit: PLACEMENT_SOURCE_MAX_BYTES, observed: sourceBytes });
84
88
  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(); }
89
+ for (const source of admitted) { await pause(); sources.push({ ...source, policy: input.evaluate(source.row) }); input.progress?.advance(); }
86
90
  input.progress?.phase("dependency-decisions");
91
+ await pause();
87
92
  // Strong endpoints are already in sources and current holds cannot be bypassed by past publication. Only
88
93
  // deletion/prune exceptions need a second verified occurrence fact; do not duplicate every historical body.
89
94
  const publicNeeded=new Set<string>();
@@ -101,6 +106,7 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
101
106
  const sourceMap = new Map(sources.map(source => [placementKeyId(source.key), source]));
102
107
  let decisions: PlacementPublicationDecision[] = [];
103
108
  for (let pass = 0; pass < 2; pass++) {
109
+ await pause();
104
110
  decisions = compilePlacementDependencies({ generation: input.generation, selectedRealms: workTargets.map(physical), rows:sources, publicEndpoints:endpoints,
105
111
  verifiedPrunes:sources.filter(source => verified.has(placementKeyId(source.key))).map(source => source.key) }).map(decision => {
106
112
  const source = sourceMap.get(placementKeyId(decision.key))!;
@@ -112,18 +118,23 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
112
118
  });
113
119
  let rejected = false;
114
120
  for (const [index,target] of workTargets.entries()) {
121
+ await pause();
115
122
  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
123
  const publish = descriptorVerdicts[index]!.ok && (!!old[index] || eligible.size > 0); publishes[index] = publish;
117
124
  if (publish) files.set("shard.json", Buffer.from(canonicalJSON({schema:PLACEMENT_DESCRIPTOR_SCHEMA,...target.realm,publicationFormat:PLACEMENT_FORMAT})+"\n"));
118
125
  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
126
  for (const [path,bytes] of encodeShardPacks(additions)) { const prior = files.get(path); if (prior && !prior.equals(bytes)) refuse(); files.set(path,bytes); }
120
127
  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")});
128
+ for (const [path,bytes] of files) if (path.startsWith("rows/")) {
129
+ // #462: one Git blob id per pack, not one per row in it (was quadratic in pack size); same value.
130
+ await pause(); const blob=createHash("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex");
131
+ for (const row of decodeShardPack(path,bytes,target.realm,target.generation)) if (!occurrences.has(row.id)) occurrences.set(row.id,{pack:path,blob});
132
+ }
123
133
  const native = additions.filter((row):row is PruneRow => row.op==="prune" && row.generation===target.generation);
124
134
  if (native.length) {
125
135
  const lineages = input.publisherLineages(index,native);
126
136
  for (const row of native) {
137
+ await pause();
127
138
  const lineage = lineages.get(row.id), own = occurrences.get(row.id); if (!lineage || !own) refuse();
128
139
  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
140
  const witnesses = [...needed].sort(([a],[b])=>a.localeCompare(b)).map(([id,rowHash])=>{ const place=occurrences.get(id); if(!place)refuse(); return{id,rowHash,...place}; });
@@ -152,11 +152,15 @@ export function planPlacementPublication(input: Omit<PlacementPublicationRoot, "
152
152
  }): PlacementPublicationBundle {
153
153
  const values = object(items, kinds), chunks: PlacementPublicationChunk[] = [];
154
154
  for (const kind of kinds) {
155
- let selected: PlacementPublicationChunk["items"] = [];
156
- const flush = () => { if (selected.length) { chunks.push(validatePlacementPublicationChunk({ schema: PLACEMENT_PUBLICATION_CHUNK_SCHEMA, kind, index: chunks.length, items: selected })); selected = []; } };
155
+ let selected: PlacementPublicationChunk["items"] = [], selectedBytes = 0;
156
+ const flush = () => { if (selected.length) { chunks.push(validatePlacementPublicationChunk({ schema: PLACEMENT_PUBLICATION_CHUNK_SCHEMA, kind, index: chunks.length, items: selected })); selected = []; selectedBytes = 0; } };
157
157
  for (const value of array(values[kind], PLACEMENT_JOURNAL_MAX_RECORDS)) {
158
- const row = item(kind, value), candidate = { schema: PLACEMENT_PUBLICATION_CHUNK_SCHEMA, kind, index: chunks.length, items: [...selected, row] };
159
- if (publicationBytes(candidate).length > PLACEMENT_JOURNAL_CHUNK_MAX_BYTES) flush(); selected.push(row);
158
+ // #462: the candidate chunk's exact canonical size, summed per item instead of re-serializing the whole chunk per row
159
+ // (quadratic). canonicalJSON of an array is its items' canonical forms joined by commas, so the sum is identical.
160
+ const row = item(kind, value), rowBytes = Buffer.byteLength(canonicalJSON(row));
161
+ const empty = publicationBytes({ schema: PLACEMENT_PUBLICATION_CHUNK_SCHEMA, kind, index: chunks.length, items: [] }).length;
162
+ if (empty + selectedBytes + (selected.length ? 1 : 0) + rowBytes > PLACEMENT_JOURNAL_CHUNK_MAX_BYTES) flush();
163
+ selectedBytes += (selected.length ? 1 : 0) + rowBytes; selected.push(row);
160
164
  }
161
165
  flush();
162
166
  }
@@ -0,0 +1,128 @@
1
+ /** The two fenced writes of a person-reviewed realm admission: empty curated metadata, then the extension record. */
2
+ import { createHash } from "node:crypto";
3
+ import { closeSync, constants, fstatSync, fsyncSync, ftruncateSync, lstatSync, mkdirSync, openSync, unlinkSync, writeSync, type BigIntStats } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { canonicalJSON, fsyncDirectory, generationDescriptor, hashJSON, readProfileJSON, writeProfileJSON } from "./generation.ts";
6
+ import { ensureShardDescriptor, assertCuratedShardLayout, shardDir } from "./shard.ts";
7
+ import { attributeTornRealmAppend } from "./sync-placement-realm-attribution.ts";
8
+ import { REALM_EXTENSION_LIMIT, REALM_EXTENSION_LOG_MAX_BYTES, RealmExtensionFormatError, type RealmExtension } from "./sync-placement-realm-extension-format.ts";
9
+ import { readRealmExtensionHistory, REALM_EXTENSION_LOG, type RealmExtensionBinding } from "./sync-placement-realm-extension-storage.ts";
10
+ import { retainedAdmissionCoversEmptyLog } from "./sync-placement-realm-effective.ts";
11
+ import type { RealmIntent } from "./sync-placement-realm-intent-format.ts";
12
+ import type { RealmIntentProof } from "./sync-placement-realm-intent-storage.ts";
13
+ import { verifyTornRealmAppend } from "./sync-placement-realm-torn.ts";
14
+
15
+ const fail = (): never => { throw new RealmExtensionFormatError(); };
16
+ const digest = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex");
17
+ const stamp = (stat: BigIntStats) => [stat.dev, stat.ino, stat.uid, stat.mode, stat.nlink, stat.size, stat.mtimeNs, stat.ctimeNs].map(String).join(":");
18
+ const owned = (stat: BigIntStats): void => {
19
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1n || stat.uid !== BigInt(process.getuid?.() ?? -1) || (stat.mode & 0o777n) !== 0o600n) fail();
20
+ };
21
+
22
+ /**
23
+ * Empty curated metadata at the fixed shard path, written so that every interruption leaves the realm `not-local`.
24
+ * `generation.json` is last: capture, 0.28.2 and the #450 inventory all read a project without it as a scaffold, so a
25
+ * crash after any earlier file creates nothing anyone acts on. The immutable source-proof companion (empty
26
+ * `migration-sources.json` plus `generation-seal.json`) precedes it for the same reason: a realm is never visible
27
+ * with `generation.json` but without the provenance capture revalidates.
28
+ */
29
+ export function ensureCuratedRealmMetadata(home: string, project: string, generation: string, machine: { id: string; label?: string }): { created: boolean } {
30
+ // Validate the fixed scaffold before the first write: a restored or received directory holding a symlinked `legacy` (or any
31
+ // other fixed path) must refuse here instead of receiving machine.json and generation.json in the symlink's destination
32
+ // ahead of a source-capture refusal. These are the same no-follow checks curated writes already apply; the inventory gate
33
+ // they usually sit behind belongs to the caller, because a realm being admitted is not in the inventory until it commits.
34
+ assertCuratedShardLayout(home, { project });
35
+ const dir = shardDir(home, project);
36
+ if (readProfileJSON(join(dir, "generation.json")) !== undefined) return { created: false };
37
+ ensureShardDescriptor(home, project);
38
+ for (const folder of ["log", "local", "legacy/log", "legacy/local", "legacy-main/log", "legacy-main/local"]) mkdirSync(join(dir, folder), { recursive: true, mode: 0o700 });
39
+ const identity = { id: machine.id, label: typeof machine.label === "string" ? machine.label : machine.id };
40
+ for (const path of ["machine.json", "legacy/machine.json", "legacy-main/machine.json"]) {
41
+ const file = join(dir, path), prior = readProfileJSON(file) as { id?: unknown } | undefined;
42
+ if (prior === undefined) writeProfileJSON(file, identity);
43
+ else if (prior?.id !== identity.id) fail();
44
+ }
45
+ const sources: unknown[] = [], sourceFile = join(dir, "migration-sources.json"), sourceValue = { schema: "agent-mem.migration-sources/v1", sources };
46
+ const sourcePrior = readProfileJSON(sourceFile);
47
+ if (sourcePrior === undefined) writeProfileJSON(sourceFile, sourceValue);
48
+ else if (canonicalJSON(sourcePrior) !== canonicalJSON(sourceValue)) fail();
49
+ const descriptor = generationDescriptor(generation), sealFile = join(dir, "generation-seal.json");
50
+ const sealValue = { schema: "agent-mem.generation-seal/v1", generation, descriptorHash: hashJSON(descriptor), sourceDigest: hashJSON({ sources, legacyCommit: undefined }) };
51
+ const sealPrior = readProfileJSON(sealFile);
52
+ if (sealPrior === undefined) writeProfileJSON(sealFile, sealValue);
53
+ else if (canonicalJSON(sealPrior) !== canonicalJSON(sealValue)) fail();
54
+ writeProfileJSON(join(dir, "generation.json"), descriptor);
55
+ fsyncDirectory(dir); fsyncDirectory(join(dir, ".."));
56
+ return { created: true };
57
+ }
58
+
59
+ /**
60
+ * Append the frozen record, completing an interrupted byte prefix of itself when one is attributed to `intent`.
61
+ * Nothing else may occupy the next position: the prefix hash and length are the intent's own independent evidence.
62
+ */
63
+ export function appendRealmExtension(home: string, binding: RealmExtensionBinding, intent: RealmIntent, record: RealmExtension, options: RealmIntentProof): void {
64
+ const file = join(home, REALM_EXTENSION_LOG), history = readRealmExtensionHistory(home, binding, { allowEmptyLog: retainedAdmissionCoversEmptyLog(home, binding.epochHash, binding.activationHash), attributeTorn: () => true });
65
+ const bytes = Buffer.concat([history.logBytes, history.torn]);
66
+ if (history.records.length + 1 !== intent.sequence || history.headHash !== intent.previousHash) fail();
67
+ let remainder: Buffer;
68
+ const line = Buffer.from(canonicalJSON(record) + "\n");
69
+ if (history.torn.length) {
70
+ // verifyTornRealmAppend re-derives the prefix from the intent itself, so it never trusts the tail it completes.
71
+ if (!verifyTornRealmAppend(bytes, intent, record).equals(history.logBytes)) fail();
72
+ remainder = line.subarray(history.torn.length);
73
+ } else {
74
+ if (history.logBytes.length !== intent.previousLogBytes || digest(history.logBytes) !== intent.previousLogHash) fail();
75
+ remainder = line;
76
+ }
77
+ if (bytes.length + remainder.length > REALM_EXTENSION_LOG_MAX_BYTES || history.records.length + 1 > REALM_EXTENSION_LIMIT) fail();
78
+ history.assertCurrent(); options.assertCurrent();
79
+ const before = lstatSync(file, { bigint: true, throwIfNoEntry: false });
80
+ if (before) { owned(before); if (Number(before.size) !== bytes.length) fail(); }
81
+ const fd = before ? openSync(file, constants.O_WRONLY | constants.O_APPEND | constants.O_NOFOLLOW)
82
+ : openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_APPEND | constants.O_NOFOLLOW, 0o600);
83
+ try {
84
+ const opened = fstatSync(fd, { bigint: true }); owned(opened);
85
+ if (before ? stamp(opened) !== stamp(before) : Number(opened.size) !== 0) fail();
86
+ for (let at = 0; at < remainder.length;) at += writeSync(fd, remainder, at, remainder.length - at);
87
+ fsyncSync(fd);
88
+ if (Number(fstatSync(fd, { bigint: true }).size) !== bytes.length + remainder.length) fail();
89
+ } finally { closeSync(fd); }
90
+ fsyncDirectory(home); options.assertCurrent();
91
+ const installed = readRealmExtensionHistory(home, binding);
92
+ if (installed.torn.length || installed.records.length !== intent.sequence || installed.records.at(-1)?.seal !== record.seal) fail();
93
+ }
94
+
95
+ /**
96
+ * Cut back only an incomplete append this intent authorized, when a person abandons before it committed.
97
+ * The retained evidence names the exact prefix and the incomplete bytes are no line any reader folds; a tail that
98
+ * cannot be attributed to this intent refuses instead of being removed.
99
+ */
100
+ export function discardRealmExtensionTail(home: string, binding: RealmExtensionBinding, intent: RealmIntent, options: RealmIntentProof): { discarded: number } {
101
+ const file = join(home, REALM_EXTENSION_LOG), history = readRealmExtensionHistory(home, binding, { allowEmptyLog: retainedAdmissionCoversEmptyLog(home, binding.epochHash, binding.activationHash), attributeTorn: () => true });
102
+ if (history.records.length + 1 !== intent.sequence || history.headHash !== intent.previousHash
103
+ || history.logBytes.length !== intent.previousLogBytes || digest(history.logBytes) !== intent.previousLogHash) fail();
104
+ // Clearing the intent withdraws the only evidence that reads a zero-byte log as this epoch's pre-write chain, so an
105
+ // abandoned admission that never wrote a byte removes the file it created instead of leaving every realm unreadable.
106
+ const tail = history.torn.length;
107
+ if (!tail && intent.previousLogBytes !== 0) return { discarded: 0 };
108
+ if (tail && !attributeTornRealmAppend(home, binding, { prefix: history.logBytes, tail: history.torn, sequence: intent.sequence, headHash: history.headHash })) fail();
109
+ options.assertCurrent();
110
+ const before = lstatSync(file, { bigint: true, throwIfNoEntry: false });
111
+ // A stop before the file existed has nothing to remove; a damaged chain must still be there to be cut back.
112
+ if (!before) { if (tail) fail(); return { discarded: 0 }; }
113
+ owned(before);
114
+ if (Number(before.size) !== history.logBytes.length + tail) fail();
115
+ const fd = openSync(file, constants.O_WRONLY | constants.O_NOFOLLOW);
116
+ try {
117
+ const opened = fstatSync(fd, { bigint: true }); owned(opened); if (stamp(opened) !== stamp(before)) fail();
118
+ // A zero-length log file is itself a refusal, so an emptied chain keeps no file instead of an empty one.
119
+ if (intent.previousLogBytes === 0) unlinkSync(file); else ftruncateSync(fd, intent.previousLogBytes);
120
+ fsyncSync(fd);
121
+ } finally { closeSync(fd); }
122
+ fsyncDirectory(home); options.assertCurrent();
123
+ const after = lstatSync(file, { bigint: true, throwIfNoEntry: false });
124
+ if (intent.previousLogBytes === 0 ? after !== undefined : !after || Number(after.size) !== intent.previousLogBytes) fail();
125
+ const installed = readRealmExtensionHistory(home, binding);
126
+ if (installed.torn.length || installed.records.length + 1 !== intent.sequence) fail();
127
+ return { discarded: tail };
128
+ }