@staix/agent-mem 0.29.0 → 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 (50) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +9 -7
  3. package/package.json +3 -2
  4. package/src/cli.ts +69 -10
  5. package/src/commands-table.ts +4 -0
  6. package/src/mcp-memory.ts +36 -8
  7. package/src/memory/bridge.ts +26 -1
  8. package/src/memory/capacity.ts +5 -2
  9. package/src/memory/catalog.ts +10 -1
  10. package/src/memory/doctor.ts +17 -14
  11. package/src/memory/formats.ts +4 -3
  12. package/src/memory/intent-brief.ts +34 -6
  13. package/src/memory/metrics.ts +173 -14
  14. package/src/memory/shard-bridge.ts +18 -6
  15. package/src/memory/shard-sync-format.ts +18 -0
  16. package/src/memory/shard-sync.ts +52 -4
  17. package/src/memory/sync-placement-bound.ts +21 -4
  18. package/src/memory/sync-placement-cache.ts +16 -1
  19. package/src/memory/sync-placement-capture.ts +14 -2
  20. package/src/memory/sync-placement-checkpoint-format.ts +199 -0
  21. package/src/memory/sync-placement-checkpoint-person.ts +209 -0
  22. package/src/memory/sync-placement-checkpoint-prospective.ts +141 -0
  23. package/src/memory/sync-placement-checkpoint-storage.ts +218 -0
  24. package/src/memory/sync-placement-checkpoint.ts +234 -0
  25. package/src/memory/sync-placement-dependencies.ts +42 -9
  26. package/src/memory/sync-placement-effective-writers.ts +12 -6
  27. package/src/memory/sync-placement-git.ts +17 -7
  28. package/src/memory/sync-placement-inspection-evidence.ts +1 -1
  29. package/src/memory/sync-placement-inventory.ts +5 -0
  30. package/src/memory/sync-placement-journal-format.ts +4 -1
  31. package/src/memory/sync-placement-journal-storage.ts +129 -26
  32. package/src/memory/sync-placement-materialize.ts +33 -19
  33. package/src/memory/sync-placement-projection.ts +7 -1
  34. package/src/memory/sync-placement-publication-events.ts +42 -0
  35. package/src/memory/sync-placement-publication-plan.ts +18 -1
  36. package/src/memory/sync-placement-realm-admission.ts +20 -3
  37. package/src/memory/sync-placement-realm-discovery.ts +42 -0
  38. package/src/memory/sync-placement-remote-admission.ts +190 -0
  39. package/src/memory/sync-placement-remote-adoption-format.ts +54 -0
  40. package/src/memory/sync-placement-remote-materialization.ts +49 -0
  41. package/src/memory/sync-placement-remote-refusal.ts +21 -0
  42. package/src/memory/sync-placement-remote-stage.ts +275 -0
  43. package/src/memory/sync-placement-transport.ts +202 -51
  44. package/src/memory/sync-placement-writer-history.ts +75 -17
  45. package/src/memory/sync-placement-writer-renewal.ts +18 -10
  46. package/src/memory/sync-placement-writer-revision-format.ts +16 -13
  47. package/src/memory/sync-placement-yield.ts +14 -0
  48. package/src/memory/sync.ts +4 -1
  49. package/src/sync-placement-writer-context.ts +5 -5
  50. package/src/ui/plugin.ts +1 -1
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Pure placement checkpoint codecs (#288 step 2). A checkpoint freezes the live placement window of one epoch and opens a
3
+ * new one outside the v1 epoch directory, so only the live window is charged against the 256-object allowance.
4
+ * Valid data and seals are neither person authority nor fresh install proof.
5
+ */
6
+ import { createHash } from "node:crypto";
7
+ import { types } from "node:util";
8
+ import { canonicalJSON, hashJSON } from "./generation.ts";
9
+ import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
10
+ import { createWriterCommit, validateWriterCommit, validateWriterRevision, type WriterCommit, type WriterRevision } from "./sync-placement-writer-revision-format.ts";
11
+
12
+ export const PLACEMENT_CHECKPOINT_DIR = "sync-placement-checkpoints";
13
+ export const PLACEMENT_CHECKPOINT_COMMITS = "commits.jsonl";
14
+ export const PLACEMENT_CHECKPOINT_INTENT = "intent.json";
15
+ export const PLACEMENT_CHECKPOINT_WINDOWS = "windows";
16
+ export const PLACEMENT_CHECKPOINT_MANIFEST = "checkpoint-manifest.json";
17
+ export const PLACEMENT_CHECKPOINT_PROJECTION = "checkpoint-projection.json";
18
+ /** First minor whose readers resolve checkpoint windows; the person raises the floor (only `amem formats raise` records a floor). */
19
+ export const PLACEMENT_CHECKPOINT_MIN_READER = "0.30.0";
20
+ export const PLACEMENT_CHECKPOINT_LIMIT = 256;
21
+ export const PLACEMENT_CHECKPOINT_PAGE_MAX_BYTES = 64 * 1024;
22
+ export const PLACEMENT_CHECKPOINT_MANIFEST_MAX_BYTES = 256 * 1024;
23
+ export const PLACEMENT_CHECKPOINT_COMMITS_MAX_BYTES = PLACEMENT_CHECKPOINT_LIMIT * 1024;
24
+ export const PLACEMENT_CHECKPOINT_INTENT_MAX_BYTES = 1024 * 1024;
25
+ /** Archive bounds from the task 174 design: members of all frozen windows together. */
26
+ export const PLACEMENT_CHECKPOINT_ARCHIVE_MAX_MEMBERS = 65_536;
27
+ export const PLACEMENT_CHECKPOINT_ARCHIVE_MAX_BYTES = 8 * 1024 ** 3;
28
+ export const PLACEMENT_CHECKPOINT_MANIFEST_SCHEMA = "agent-mem.sync-placement-checkpoint-manifest/v1";
29
+ export const PLACEMENT_CHECKPOINT_CATALOG_SCHEMA = "agent-mem.sync-placement-checkpoint-catalog/v1";
30
+ export const PLACEMENT_CHECKPOINT_PROJECTION_SCHEMA = "agent-mem.sync-placement-checkpoint-projection/v1";
31
+ export const PLACEMENT_CHECKPOINT_COMMIT_SCHEMA = "agent-mem.sync-placement-checkpoint-commit/v1";
32
+ export const PLACEMENT_CHECKPOINT_INTENT_SCHEMA = "agent-mem.sync-placement-checkpoint-intent/v1";
33
+
34
+ export interface CheckpointMember { name: string; size: number; sha256: string }
35
+ export interface CheckpointCatalogEntry { attemptHash: string; window: number; members: CheckpointMember[] }
36
+ export interface CheckpointCatalogPage { schema: typeof PLACEMENT_CHECKPOINT_CATALOG_SCHEMA; epochHash: string; window: number; page: number; entries: CheckpointCatalogEntry[] }
37
+ export interface CheckpointProjectionDigest {
38
+ schema: typeof PLACEMENT_CHECKPOINT_PROJECTION_SCHEMA; epochHash: string; window: number;
39
+ journal: { sequence: number; headHash: string }; projectionHash: string;
40
+ }
41
+ export interface CheckpointManifestBody {
42
+ schema: typeof PLACEMENT_CHECKPOINT_MANIFEST_SCHEMA; epochHash: string; activationHash: string; window: number;
43
+ previousManifestHash: string | null;
44
+ /** Every member of the window this checkpoint freezes (window - 1), with exact size and content hash. */
45
+ archived: { window: number; members: CheckpointMember[] };
46
+ journal: { sequence: number; headHash: string; chunks: number };
47
+ /** The logical writer head and count the frozen windows end at; the new window's genesis binds this manifest and head. */
48
+ writer: { sequence: number; headHash: string };
49
+ catalog: CheckpointMember[];
50
+ projection: CheckpointMember;
51
+ }
52
+ export interface CheckpointManifest extends CheckpointManifestBody { seal: string }
53
+ export interface CheckpointCommitBody {
54
+ schema: typeof PLACEMENT_CHECKPOINT_COMMIT_SCHEMA; epochHash: string; window: number; previousHash: string;
55
+ manifestHash: string; writerRevisionHash: string; writerCommitHash: string;
56
+ }
57
+ export interface CheckpointCommit extends CheckpointCommitBody { seal: string }
58
+ export interface CheckpointIntentBody {
59
+ schema: typeof PLACEMENT_CHECKPOINT_INTENT_SCHEMA; epochHash: string; window: number;
60
+ previousLogBytes: number; previousLogHash: string;
61
+ manifest: CheckpointManifest; commit: CheckpointCommit;
62
+ /** The exact staged content: resume rewrites these bytes only, abandon removes only these names. */
63
+ pages: CheckpointCatalogPage[]; projection: CheckpointProjectionDigest;
64
+ writerRevision: WriterRevision; writerCommit: WriterCommit;
65
+ }
66
+ export interface CheckpointIntent extends CheckpointIntentBody { seal: string }
67
+
68
+ function fail(code: "invalid" | "bound" = "invalid"): never { throw new SyncPlacementJournalError(code); }
69
+ function object(input: unknown, keys: readonly string[]): Record<string, unknown> {
70
+ if (!input || typeof input !== "object" || types.isProxy(input) || Array.isArray(input) || ![Object.prototype, null].includes(Object.getPrototypeOf(input))
71
+ || Object.getOwnPropertySymbols(input).length) fail();
72
+ const names = Object.getOwnPropertyNames(input); if (names.length !== keys.length) fail();
73
+ const out: Record<string, unknown> = Object.create(null);
74
+ for (const key of keys) { const d = Object.getOwnPropertyDescriptor(input, key); if (!d || !("value" in d) || !d.enumerable) fail(); out[key] = d.value; }
75
+ return out;
76
+ }
77
+ function array(input: unknown, maximum: number, minimum = 0): unknown[] {
78
+ if (!input || typeof input !== "object" || types.isProxy(input) || !Array.isArray(input) || Object.getPrototypeOf(input) !== Array.prototype || Object.getOwnPropertySymbols(input).length) fail();
79
+ const length = input.length; if (length > maximum) fail("bound"); if (length < minimum) fail();
80
+ if (Object.getOwnPropertyNames(input).length !== length + 1) fail();
81
+ const out: unknown[] = [];
82
+ for (let i = 0; i < length; i++) { const d = Object.getOwnPropertyDescriptor(input, String(i)); if (!d || !("value" in d) || !d.enumerable) fail(); out.push(d.value); }
83
+ return out;
84
+ }
85
+ const hex = (input: unknown): string => { if (typeof input !== "string" || input.length !== 64 || !/^[a-f0-9]+$/.test(input)) fail(); return input; };
86
+ const integer = (input: unknown, minimum: number, maximum: number): number => {
87
+ if (typeof input !== "number" || !Number.isSafeInteger(input) || input < minimum || input > maximum) fail(); return input;
88
+ };
89
+ /** Member names never carry a separator; window members are the v1 families plus the checkpoint's own sealed files. */
90
+ export function checkpointMemberName(name: unknown): string {
91
+ if (typeof name !== "string" || name.length > 128 || !/^[a-z0-9][a-z0-9.-]*$/.test(name) || name.includes("..")) fail(); return name;
92
+ }
93
+ export const checkpointWindowName = (window: number): string => String(integer(window, 1, PLACEMENT_CHECKPOINT_LIMIT)).padStart(5, "0");
94
+ export const checkpointCatalogName = (page: number): string => `checkpoint-catalog-${String(integer(page, 0, 4095)).padStart(5, "0")}.json`;
95
+ export const isCheckpointSealedName = (name: string): boolean =>
96
+ name === PLACEMENT_CHECKPOINT_MANIFEST || name === PLACEMENT_CHECKPOINT_PROJECTION || /^checkpoint-catalog-\d{5}\.json$/.test(name);
97
+ function member(input: unknown): CheckpointMember {
98
+ const v = object(input, ["name", "size", "sha256"]);
99
+ return { name: checkpointMemberName(v.name), size: integer(v.size, 0, PLACEMENT_CHECKPOINT_MANIFEST_MAX_BYTES * 4), sha256: hex(v.sha256) };
100
+ }
101
+ function members(input: unknown, maximum: number, minimum = 0): CheckpointMember[] {
102
+ const out = array(input, maximum, minimum).map(member);
103
+ for (let i = 1; i < out.length; i++) if (out[i - 1]!.name >= out[i]!.name) fail();
104
+ return out;
105
+ }
106
+ const bounded = (value: unknown, maximum: number) => { if (Buffer.byteLength(canonicalJSON(value) + "\n") > maximum) fail("bound"); };
107
+ function sealed<T extends object>(body: T, v: Record<string, unknown> | undefined, maximum: number): T & { seal: string } {
108
+ const value = { ...body, seal: hashJSON(body) }; if (v && hex(v.seal) !== value.seal) fail(); bounded(value, maximum); return value;
109
+ }
110
+
111
+ /** The new window's writer genesis: domain-separated from the epoch genesis and bound to the manifest and the frozen head. */
112
+ export function checkpointWriterGenesis(epochHash: string, activationHash: string, manifestHash: string, previousHead: string): string {
113
+ return hashJSON(["agent-mem.sync-placement-writer-window-genesis/v1", hex(epochHash), hex(activationHash), hex(manifestHash), hex(previousHead)]);
114
+ }
115
+ export function checkpointCommitGenesis(epochHash: string): string { return hashJSON(["agent-mem.sync-placement-checkpoint-genesis/v1", hex(epochHash)]); }
116
+
117
+ function catalogPage(input: unknown): CheckpointCatalogPage {
118
+ const v = object(input, ["schema", "epochHash", "window", "page", "entries"]); if (v.schema !== PLACEMENT_CHECKPOINT_CATALOG_SCHEMA) fail();
119
+ const window = integer(v.window, 1, PLACEMENT_CHECKPOINT_LIMIT), entries = array(v.entries, 4096).map(item => {
120
+ const e = object(item, ["attemptHash", "window", "members"]);
121
+ return { attemptHash: hex(e.attemptHash), window: integer(e.window, 0, window - 1), members: members(e.members, 4096, 1) };
122
+ });
123
+ for (let i = 1; i < entries.length; i++) if (entries[i - 1]!.attemptHash >= entries[i]!.attemptHash) fail();
124
+ const page = { schema: PLACEMENT_CHECKPOINT_CATALOG_SCHEMA, epochHash: hex(v.epochHash), window, page: integer(v.page, 0, 4095), entries } as const;
125
+ bounded(page, PLACEMENT_CHECKPOINT_PAGE_MAX_BYTES); return page;
126
+ }
127
+ export function validateCheckpointCatalogPage(value: unknown): CheckpointCatalogPage { return catalogPage(value); }
128
+ export function validateCheckpointProjection(input: unknown): CheckpointProjectionDigest {
129
+ const v = object(input, ["schema", "epochHash", "window", "journal", "projectionHash"]); if (v.schema !== PLACEMENT_CHECKPOINT_PROJECTION_SCHEMA) fail();
130
+ const journal = object(v.journal, ["sequence", "headHash"]);
131
+ const value = { schema: PLACEMENT_CHECKPOINT_PROJECTION_SCHEMA, epochHash: hex(v.epochHash), window: integer(v.window, 1, PLACEMENT_CHECKPOINT_LIMIT),
132
+ journal: { sequence: integer(journal.sequence, 0, 20_000), headHash: hex(journal.headHash) }, projectionHash: hex(v.projectionHash) } as const;
133
+ bounded(value, PLACEMENT_CHECKPOINT_PAGE_MAX_BYTES); return value;
134
+ }
135
+ function manifest(input: unknown, isSealed: boolean): CheckpointManifest {
136
+ const v = object(input, ["schema", "epochHash", "activationHash", "window", "previousManifestHash", "archived", "journal", "writer", "catalog", "projection", ...(isSealed ? ["seal"] : [])]);
137
+ if (v.schema !== PLACEMENT_CHECKPOINT_MANIFEST_SCHEMA) fail();
138
+ const window = integer(v.window, 1, PLACEMENT_CHECKPOINT_LIMIT), archived = object(v.archived, ["window", "members"]);
139
+ const journal = object(v.journal, ["sequence", "headHash", "chunks"]), writer = object(v.writer, ["sequence", "headHash"]);
140
+ const previous = v.previousManifestHash === null ? null : hex(v.previousManifestHash);
141
+ if ((window === 1) !== (previous === null)) fail();
142
+ const body: CheckpointManifestBody = { schema: PLACEMENT_CHECKPOINT_MANIFEST_SCHEMA, epochHash: hex(v.epochHash), activationHash: hex(v.activationHash), window,
143
+ previousManifestHash: previous, archived: { window: integer(archived.window, 0, window - 1), members: members(archived.members, 4096, 1) },
144
+ journal: { sequence: integer(journal.sequence, 0, 20_000), headHash: hex(journal.headHash), chunks: integer(journal.chunks, 0, 99_999) },
145
+ writer: { sequence: integer(writer.sequence, 0, 64 * (PLACEMENT_CHECKPOINT_LIMIT + 1)), headHash: hex(writer.headHash) },
146
+ catalog: members(v.catalog, 4096), projection: member(v.projection) };
147
+ if (body.archived.window !== window - 1 || body.projection.name !== PLACEMENT_CHECKPOINT_PROJECTION
148
+ || body.catalog.some((page, index) => page.name !== checkpointCatalogName(index))) fail();
149
+ return sealed(body, isSealed ? v : undefined, PLACEMENT_CHECKPOINT_MANIFEST_MAX_BYTES);
150
+ }
151
+ export function createCheckpointManifest(body: CheckpointManifestBody): CheckpointManifest { return manifest(body, false); }
152
+ export function validateCheckpointManifest(value: unknown): CheckpointManifest { return manifest(value, true); }
153
+ function commit(input: unknown, isSealed: boolean): CheckpointCommit {
154
+ const v = object(input, ["schema", "epochHash", "window", "previousHash", "manifestHash", "writerRevisionHash", "writerCommitHash", ...(isSealed ? ["seal"] : [])]);
155
+ if (v.schema !== PLACEMENT_CHECKPOINT_COMMIT_SCHEMA) fail();
156
+ const body: CheckpointCommitBody = { schema: PLACEMENT_CHECKPOINT_COMMIT_SCHEMA, epochHash: hex(v.epochHash), window: integer(v.window, 1, PLACEMENT_CHECKPOINT_LIMIT),
157
+ previousHash: hex(v.previousHash), manifestHash: hex(v.manifestHash), writerRevisionHash: hex(v.writerRevisionHash), writerCommitHash: hex(v.writerCommitHash) };
158
+ return sealed(body, isSealed ? v : undefined, 1024);
159
+ }
160
+ export function createCheckpointCommit(body: CheckpointCommitBody): CheckpointCommit { return commit(body, false); }
161
+ export function validateCheckpointCommit(value: unknown): CheckpointCommit { return commit(value, true); }
162
+ function intent(input: unknown, isSealed: boolean): CheckpointIntent {
163
+ const v = object(input, ["schema", "epochHash", "window", "previousLogBytes", "previousLogHash", "manifest", "commit", "pages", "projection", "writerRevision", "writerCommit", ...(isSealed ? ["seal"] : [])]);
164
+ if (v.schema !== PLACEMENT_CHECKPOINT_INTENT_SCHEMA) fail();
165
+ const manifest = validateCheckpointManifest(v.manifest), genesis = checkpointWriterGenesis(manifest.epochHash, manifest.activationHash, manifest.seal, manifest.writer.headHash);
166
+ let writerRevision: WriterRevision, writerCommit: WriterCommit;
167
+ try { writerRevision = validateWriterRevision(v.writerRevision, genesis); writerCommit = validateWriterCommit(v.writerCommit); } catch { return fail(); }
168
+ const body: CheckpointIntentBody = { schema: PLACEMENT_CHECKPOINT_INTENT_SCHEMA, epochHash: hex(v.epochHash), window: integer(v.window, 1, PLACEMENT_CHECKPOINT_LIMIT),
169
+ previousLogBytes: integer(v.previousLogBytes, 0, PLACEMENT_CHECKPOINT_COMMITS_MAX_BYTES), previousLogHash: hex(v.previousLogHash),
170
+ manifest, commit: validateCheckpointCommit(v.commit), pages: array(v.pages, 4096).map(catalogPage), projection: validateCheckpointProjection(v.projection), writerRevision, writerCommit };
171
+ // Every staged file is bound to the manifest by name, size and hash, and the (W, 1) revision to the commit line.
172
+ const digestOf = (value: unknown) => { const bytes = Buffer.from(canonicalJSON(value) + "\n"); return { size: bytes.length, sha256: createHash("sha256").update(bytes).digest("hex") }; };
173
+ const pageOk = (page: CheckpointCatalogPage, index: number) => { const m = manifest.catalog[index], d = digestOf(page); return !!m && m.size === d.size && m.sha256 === d.sha256; };
174
+ const projection = digestOf(body.projection);
175
+ if (manifest.epochHash !== body.epochHash || manifest.window !== body.window || body.commit.epochHash !== body.epochHash || body.commit.window !== body.window
176
+ || body.commit.manifestHash !== manifest.seal || body.pages.length !== manifest.catalog.length || !body.pages.every(pageOk)
177
+ || manifest.projection.size !== projection.size || manifest.projection.sha256 !== projection.sha256
178
+ || body.projection.window !== body.window || body.projection.epochHash !== body.epochHash
179
+ || writerRevision.sequence !== 1 || writerRevision.epochHash !== body.epochHash || writerRevision.activationHash !== manifest.activationHash
180
+ || writerRevision.journal.sequence !== manifest.journal.sequence || writerRevision.journal.headHash !== manifest.journal.headHash
181
+ || canonicalJSON(createWriterCommit(writerRevision, genesis)) !== canonicalJSON(writerCommit)
182
+ || body.commit.writerRevisionHash !== writerRevision.seal || body.commit.writerCommitHash !== writerCommit.seal) fail();
183
+ return sealed(body, isSealed ? v : undefined, PLACEMENT_CHECKPOINT_INTENT_MAX_BYTES);
184
+ }
185
+ export function createCheckpointIntent(body: CheckpointIntentBody): CheckpointIntent { return intent(body, false); }
186
+ export function validateCheckpointIntent(value: unknown): CheckpointIntent { return intent(value, true); }
187
+ /** Catalog entries split into sealed 64 KiB pages in attempt order; pages carry no cross-page state. */
188
+ export function paginateCheckpointCatalog(epochHash: string, window: number, entries: readonly CheckpointCatalogEntry[]): CheckpointCatalogPage[] {
189
+ const sorted = [...entries].sort((a, b) => a.attemptHash.localeCompare(b.attemptHash)), pages: CheckpointCatalogPage[] = [];
190
+ let current: CheckpointCatalogEntry[] = [];
191
+ const close = () => { pages.push(catalogPage({ schema: PLACEMENT_CHECKPOINT_CATALOG_SCHEMA, epochHash, window, page: pages.length, entries: current })); current = []; };
192
+ for (const entry of sorted) {
193
+ const next = [...current, entry];
194
+ if (current.length && Buffer.byteLength(canonicalJSON({ schema: PLACEMENT_CHECKPOINT_CATALOG_SCHEMA, epochHash, window, page: pages.length, entries: next }) + "\n") > PLACEMENT_CHECKPOINT_PAGE_MAX_BYTES) close();
195
+ current.push(entry);
196
+ }
197
+ if (current.length || !pages.length) close();
198
+ return pages;
199
+ }
@@ -0,0 +1,209 @@
1
+ /**
2
+ * Person surface of the placement checkpoint (#288 step 3): a readonly preview, confirm of one exact sealed plan, resume
3
+ * and abandon. Never automatic and never on the capture or hook path. Code never raises a floor: confirm only reads the
4
+ * person-written floor record (`amem formats raise` is the one writer).
5
+ */
6
+ import { randomBytes } from "node:crypto";
7
+ import { types } from "node:util";
8
+ import { memoryPolicySnapshot } from "./policy.ts";
9
+ import { realPath } from "./platform.ts";
10
+ import { canonicalJSON } from "./generation.ts";
11
+ import { assertFormatFloor, formatVersionBelow, readFormatFloors } from "./formats.ts";
12
+ import { installVersion } from "./formats-raise.ts";
13
+ import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
14
+ import { PLACEMENT_JOURNAL_CHUNK_MAX_BYTES, PLACEMENT_JOURNAL_MAX_OBJECTS } from "./sync-placement-journal-format.ts";
15
+ import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
16
+ import { readActivePlacementBinding, type ActivePlacementBinding } from "./sync-placement-active.ts";
17
+ import { readInitialSyncPlacementWriterLocator } from "./sync-placement-writer-roots.ts";
18
+ import { readEffectiveSyncPlacementWriters } from "./sync-placement-effective-writers.ts";
19
+ import { readPlacementJournal, readPlacementPublicationMetadata, placementJournalObjectComposition, releasePlacementStorageCaches, type PlacementJournalObjectComposition } from "./sync-placement-journal-storage.ts";
20
+ import { publicationFileNames } from "./sync-placement-publication-plan.ts";
21
+ import { PLACEMENT_CHECKPOINT_COMMAND, PLACEMENT_CHECKPOINT_PENDING_MESSAGE, placementCheckpointPending, resolvePlacementWindow } from "./sync-placement-checkpoint-storage.ts";
22
+ import { abandonPlacementCheckpoint, applyPlacementCheckpoint, planPlacementCheckpoint, resumePlacementCheckpoint, type PlacementCheckpointInput, type PlacementCheckpointPhase } from "./sync-placement-checkpoint.ts";
23
+ import { PLACEMENT_CHECKPOINT_MIN_READER, validateCheckpointIntent, type CheckpointIntent } from "./sync-placement-checkpoint-format.ts";
24
+ import { withPlacementActivationFences } from "./sync-placement-activation-locks.ts";
25
+ import { assertPlacementActivationOwner } from "./sync-placement-activation-proof.ts";
26
+ import { placementFenceDirectories } from "./sync-placement-writer-renewal.ts";
27
+ import { initialPlacementWriterContext } from "../sync-placement-writer-context.ts";
28
+ import { checkpointProspective, type CheckpointProspective } from "./sync-placement-checkpoint-prospective.ts";
29
+
30
+ export const CHECKPOINT_PREVIEW = PLACEMENT_CHECKPOINT_COMMAND;
31
+ const RESUME = `${CHECKPOINT_PREVIEW} --resume`, ABANDON = `${CHECKPOINT_PREVIEW} --abandon`;
32
+ const homeFloorAtLeast = (home: string, minimum: string): boolean =>
33
+ (readFormatFloors(home) ?? []).some(floor => floor.surface === "home" && !formatVersionBelow(floor.minReader, minimum));
34
+
35
+ export type PlacementCheckpointCause = "pending" | "commit-started" | "floor" | "writer-below-floor" | "headroom" | "obligation" | "changed" | "inactive" | "candidate";
36
+ const MESSAGES: Record<PlacementCheckpointCause, string> = {
37
+ pending: PLACEMENT_CHECKPOINT_PENDING_MESSAGE,
38
+ "commit-started": `The placement checkpoint's commit line has started, so it can no longer be abandoned; run ${RESUME} to complete it.`,
39
+ floor: `Confirming a placement checkpoint requires the person-written home floor of ${PLACEMENT_CHECKPOINT_MIN_READER} or later; preview it with amem formats raise home ${PLACEMENT_CHECKPOINT_MIN_READER}, confirm it with --confirm, then rerun the confirm (amem never raises a floor itself).`,
40
+ "writer-below-floor": `A writer sharing this home is below the recorded home or sync format floor; inspect formats.json and upgrade it, then preview again with ${CHECKPOINT_PREVIEW} --writer-root <install root> for every install.`,
41
+ headroom: "",
42
+ obligation: "The placement journal has an unfinished append, publication, reservation, renewal or source recovery; finish it with amem sync (or the pending renewal with amem migrate --sync-placement --resume), then preview the checkpoint again.",
43
+ changed: `The placement state changed since the checkpoint plan was sealed; preview a fresh plan with ${CHECKPOINT_PREVIEW} and confirm that one.`,
44
+ inactive: "This home has no active sync placement; activate it with amem migrate --sync-placement --dry-run first.",
45
+ candidate: `A checkpoint carries one writer renewal: pass the complete inventory as repeatable --writer-root <install root> (every amem install sharing this home), then preview again with ${CHECKPOINT_PREVIEW}.`,
46
+ };
47
+ /** A person-facing checkpoint refusal with one cause class and its next step; never a path, row or project name. */
48
+ export class PlacementCheckpointError extends Error {
49
+ constructor(readonly causeClass: PlacementCheckpointCause, detail = "") {
50
+ super(causeClass === "headroom" ? `The checkpoint would not leave room for the next sync: ${detail} A single checkpoint cannot unblock this plan; the deferred multi-plan split in #288 design item 5 is the open path. Nothing was written.` : MESSAGES[causeClass] + (detail ? ` ${detail}` : ""));
51
+ this.name = "PlacementCheckpointError";
52
+ }
53
+ }
54
+
55
+ function active(home: string): ActivePlacementBinding {
56
+ const markers = readPlacementRuntimeMarkers(home), value = readActivePlacementBinding(home, markers.profile, markers.shards);
57
+ if (!value) throw new PlacementCheckpointError("inactive"); return value;
58
+ }
59
+ function input(home: string, a: ActivePlacementBinding, roots: PlacementCheckpointInput["roots"], requestId: string): PlacementCheckpointInput {
60
+ const locator = readInitialSyncPlacementWriterLocator(home);
61
+ return { binding: { epochHash: a.profile.placementHead, activationHash: a.activation.seal, homeHash: a.epoch.homeHash, generation: a.epoch.generation, initialLocatorHash: locator.seal }, roots, requestId };
62
+ }
63
+ function measured(home: string, writerRoots: readonly string[], ownRoot: string): PlacementCheckpointInput["roots"] {
64
+ if (!writerRoots.length) throw new PlacementCheckpointError("candidate");
65
+ try { return initialPlacementWriterContext(home, writerRoots, ownRoot).measurement.roots; } catch { throw new PlacementCheckpointError("candidate"); }
66
+ }
67
+ function plan(home: string, epochHash: string, value: PlacementCheckpointInput): CheckpointIntent {
68
+ if (placementCheckpointPending(home, epochHash)) throw new PlacementCheckpointError("pending");
69
+ try { return planPlacementCheckpoint(home, epochHash, value); }
70
+ catch (error) {
71
+ const code = error instanceof SyncPlacementJournalError ? Object.getOwnPropertyDescriptor(error, "code")?.value : undefined;
72
+ if (code === "pending") throw new PlacementCheckpointError("obligation");
73
+ if (code === "changed") throw new PlacementCheckpointError("changed");
74
+ throw error;
75
+ }
76
+ }
77
+ /** Journal chunk names a fresh plan reserves in an empty window: the same chunking `placementPublicationReservedJournalNames` uses. */
78
+ function freshReservedChunks(reservedRecordBytes: readonly number[]): number {
79
+ let count = 0, size = 0;
80
+ for (const bytes of reservedRecordBytes) { if (!count || size + bytes > PLACEMENT_JOURNAL_CHUNK_MAX_BYTES) { count++; size = 0; } size += bytes; }
81
+ return count + (reservedRecordBytes.length ? 1 : 0); // + append-intent.json while the reservation is open
82
+ }
83
+ export interface PlacementCheckpointHeadroom {
84
+ limit: number; liveAfter: number; nextRenewal: number; completedPlan: { slots: number; reservedJournalChunks: number }; prospectivePlan: CheckpointProspective;
85
+ largestPlan: { slots: number; reservedJournalChunks: number }; required: number; remaining: number;
86
+ }
87
+ export interface PlacementCheckpointPreview {
88
+ mode: "checkpoint-preview"; window: number; nextWindow: number; journalObjects: PlacementJournalObjectComposition; currentObjects: number;
89
+ headroom: PlacementCheckpointHeadroom; floorReady: boolean; requiredHomeFloor: string; writers: number; planHash: string; plan: CheckpointIntent; nextStep: string;
90
+ }
91
+ /**
92
+ * Readonly preview: validates complete history and publication closure through the planner, prints the composition and the
93
+ * headroom after the checkpoint. The headroom covers one next renewal plus the largest observed plan and its reserved journal
94
+ * chunks; a checkpoint that cannot unblock the next sync refuses with the exact shortfall.
95
+ */
96
+ export async function previewPlacementCheckpoint(homeInput: string, opts: { writerRoots: readonly string[]; ownRoot: string }): Promise<PlacementCheckpointPreview> {
97
+ const home = realPath(homeInput), a = active(home), epochHash = a.profile.placementHead;
98
+ const roots = measured(home, opts.writerRoots, opts.ownRoot), intent = plan(home, epochHash, input(home, a, roots, randomBytes(32).toString("hex")));
99
+ const journal = readPlacementJournal(home, epochHash), window = resolvePlacementWindow(home, epochHash);
100
+ const { headroom, journalObjects, assertCurrent } = await checkpointHeadroom(home, intent);
101
+ assertCurrent();
102
+ const minReader = PLACEMENT_CHECKPOINT_MIN_READER;
103
+ return { mode: "checkpoint-preview", window: window.window, nextWindow: intent.window, journalObjects, currentObjects: journal.objects, headroom,
104
+ floorReady: homeFloorAtLeast(home, minReader), requiredHomeFloor: minReader, writers: roots.length, planHash: intent.seal, plan: intent,
105
+ nextStep: `${CHECKPOINT_PREVIEW} --confirm --plan <saved preview JSON> --writer-root <install root> (repeat for every install)` };
106
+ }
107
+ async function checkpointHeadroom(home: string, intent: CheckpointIntent): Promise<{ headroom: PlacementCheckpointHeadroom; journalObjects: PlacementJournalObjectComposition; assertCurrent(): void }> {
108
+ const epochHash = intent.epochHash, prospective = await checkpointProspective(home);
109
+ let completed = { slots: 0, reservedJournalChunks: 0 }, journalObjects!: PlacementJournalObjectComposition;
110
+ readPlacementPublicationMetadata(home, epochHash, io => {
111
+ journalObjects = placementJournalObjectComposition({ names: io.names() });
112
+ const attempts = new Set([...io.names().flatMap(name => /^publication-([a-f0-9]{64})-root\.json$/.exec(name)?.[1] ?? []), ...io.archivedPublications()]);
113
+ for (const attempt of attempts) {
114
+ const root = io.publication(attempt).bundle.root, candidate = { slots: publicationFileNames(root).length, reservedJournalChunks: freshReservedChunks(root.reservedRecordBytes) };
115
+ if (candidate.slots + candidate.reservedJournalChunks > completed.slots + completed.reservedJournalChunks) completed = candidate;
116
+ }
117
+ });
118
+ const headroom = checkpointHeadroomFor(intent.pages.length, completed, prospective.value);
119
+ return { headroom, journalObjects, assertCurrent: prospective.assertCurrent };
120
+ }
121
+ /** Shared arithmetic for both offline preview and confirm revalidation; never invent a missing plan. */
122
+ export function checkpointHeadroomFor(pages: number, completed: { slots: number; reservedJournalChunks: number }, prospective: CheckpointProspective): PlacementCheckpointHeadroom {
123
+ const largest = prospective.state === "cache-only" && prospective.slots + prospective.reservedJournalChunks > completed.slots + completed.reservedJournalChunks
124
+ ? { slots: prospective.slots, reservedJournalChunks: prospective.reservedJournalChunks } : completed;
125
+ const liveAfter = pages + 4 + 1, nextRenewal = 1, required = liveAfter + nextRenewal + largest.slots + largest.reservedJournalChunks;
126
+ const result: PlacementCheckpointHeadroom = { limit: PLACEMENT_JOURNAL_MAX_OBJECTS, liveAfter, nextRenewal, completedPlan: completed, prospectivePlan: prospective,
127
+ largestPlan: largest, required, remaining: PLACEMENT_JOURNAL_MAX_OBJECTS - required };
128
+ if (result.remaining < 0) throw new PlacementCheckpointError("headroom",
129
+ `the new window needs ${required} of ${PLACEMENT_JOURNAL_MAX_OBJECTS} objects (${liveAfter} after the checkpoint, ${nextRenewal} for the next renewal, ${largest.slots} for the largest observed plan and ${largest.reservedJournalChunks} for its reserved journal chunks), ${-result.remaining} over the limit.`);
130
+ return result;
131
+ }
132
+ /** The saved preview must include both its sealed intent and the reviewed headroom. */
133
+ export function checkpointPlanFrom(value: unknown): CheckpointIntent {
134
+ if (!value || typeof value !== "object" || Array.isArray(value) || types.isProxy(value)) throw new PlacementCheckpointError("changed");
135
+ const field = Object.getOwnPropertyDescriptor(value, "plan");
136
+ if (!field || !("value" in field)) throw new PlacementCheckpointError("changed");
137
+ try { return validateCheckpointIntent(field.value); } catch { throw new PlacementCheckpointError("changed"); }
138
+ }
139
+ function reviewedHeadroom(value: unknown): unknown {
140
+ if (!value || typeof value !== "object" || Array.isArray(value) || types.isProxy(value)) throw new PlacementCheckpointError("changed");
141
+ const field = Object.getOwnPropertyDescriptor(value, "headroom");
142
+ const detached = field && "value" in field ? memoryPolicySnapshot(field.value) : undefined;
143
+ if (!detached) throw new PlacementCheckpointError("changed");
144
+ return detached;
145
+ }
146
+ function checkFloor(home: string, roots: PlacementCheckpointInput["roots"] | undefined, minReader: string): void {
147
+ if (!homeFloorAtLeast(home, minReader)) throw new PlacementCheckpointError("floor");
148
+ // This reader itself below the recorded floor cannot measure anything: name the writer cause, not the inventory.
149
+ try { assertFormatFloor(home, "sync"); } catch { throw new PlacementCheckpointError("writer-below-floor"); }
150
+ if (!roots) return;
151
+ const effective = readEffectiveSyncPlacementWriters(home).roots ?? [];
152
+ const versions = [...roots.map(root => root.version), ...effective.map(root => installVersion(root))];
153
+ const floors = (readFormatFloors(home) ?? []).filter(floor => floor.surface === "home" || floor.surface === "sync");
154
+ if (versions.some(version => version === null || floors.some(floor => formatVersionBelow(version, floor.minReader)))) throw new PlacementCheckpointError("writer-below-floor");
155
+ }
156
+ /**
157
+ * Confirm one exact sealed plan under the profile, sync and home/realm fences: the floor first, then the planner's own
158
+ * revalidation (fresh install, journal and history must reproduce the sealed bytes), then intent, staging and the commit line.
159
+ */
160
+ export async function confirmPlacementCheckpoint(homeInput: string, value: unknown, opts: { writerRoots: readonly string[]; ownRoot: string; phase?: (phase: PlacementCheckpointPhase) => void }): Promise<{ window: number; renewed: true; planHash: string; nextStep: string }> {
161
+ const home = realPath(homeInput), intent = checkpointPlanFrom(value), a = active(home), minReader = PLACEMENT_CHECKPOINT_MIN_READER;
162
+ if (intent.epochHash !== a.profile.placementHead) throw new PlacementCheckpointError("changed");
163
+ checkFloor(home, undefined, minReader); checkFloor(home, measured(home, opts.writerRoots, opts.ownRoot), minReader);
164
+ const prospective = await checkpointHeadroom(home, intent);
165
+ if (canonicalJSON(reviewedHeadroom(value)) !== canonicalJSON(prospective.headroom)) throw new PlacementCheckpointError("changed");
166
+ return withPlacementActivationFences(home, placementFenceDirectories(home, a), async (mutation, owner) => {
167
+ const now = active(home), roots = measured(home, opts.writerRoots, opts.ownRoot);
168
+ if (canonicalJSON(now) !== canonicalJSON(a)) throw new PlacementCheckpointError("changed");
169
+ prospective.assertCurrent();
170
+ checkFloor(home, roots, minReader);
171
+ const floorSnapshot = canonicalJSON(readFormatFloors(home));
172
+ if (placementCheckpointPending(home, intent.epochHash)) throw new PlacementCheckpointError("pending");
173
+ const value = input(home, now, roots, intent.writerRevision.requestId);
174
+ const assertCurrent = () => { assertPlacementActivationOwner(owner); if (canonicalJSON(readFormatFloors(home)) !== floorSnapshot) throw new PlacementCheckpointError("floor"); };
175
+ try { return { ...applyPlacementCheckpoint(home, intent, value, { mutation, assertCurrent, ...(opts.phase ? { phase: opts.phase } : {}) }), renewed: true as const, planHash: intent.seal, nextStep: "amem sync" }; }
176
+ catch (error) {
177
+ const code = error instanceof SyncPlacementJournalError ? Object.getOwnPropertyDescriptor(error, "code")?.value : undefined;
178
+ if (code === "changed" && !placementCheckpointPending(home, intent.epochHash)) throw new PlacementCheckpointError("changed");
179
+ throw error;
180
+ } finally { releasePlacementStorageCaches(); }
181
+ });
182
+ }
183
+ /** Resume completes only the frozen bytes of the recorded intent: metadata only, no fresh install, policy or source check. */
184
+ export async function resumePlacementCheckpointPerson(homeInput: string): Promise<{ window: number; resumed: boolean; nextStep: string }> {
185
+ const home = realPath(homeInput), a = active(home), epochHash = a.profile.placementHead;
186
+ return withPlacementActivationFences(home, placementFenceDirectories(home, a), async (mutation, owner) => {
187
+ try {
188
+ const done = resumePlacementCheckpoint(home, epochHash, { mutation, assertCurrent: () => assertPlacementActivationOwner(owner) });
189
+ return done ? { window: done.window, resumed: true, nextStep: "amem sync" } : { window: resolvePlacementWindow(home, epochHash).window, resumed: false, nextStep: "amem sync" };
190
+ } catch (error) {
191
+ // A torn intent never staged anything: only abandon removes it.
192
+ if (error instanceof SyncPlacementJournalError && Object.getOwnPropertyDescriptor(error, "code")?.value === "pending") throw new PlacementCheckpointError("pending", `The recorded intent is incomplete; run ${ABANDON}.`);
193
+ throw error;
194
+ } finally { releasePlacementStorageCaches(); }
195
+ });
196
+ }
197
+ /** Abandon removes only intent-owned staging before the first commit byte; after it, refuses and names resume. */
198
+ export async function abandonPlacementCheckpointPerson(homeInput: string): Promise<{ removed: number; abandoned: boolean; nextStep: string }> {
199
+ const home = realPath(homeInput), a = active(home), epochHash = a.profile.placementHead;
200
+ return withPlacementActivationFences(home, placementFenceDirectories(home, a), async (mutation, owner) => {
201
+ try {
202
+ const pending = placementCheckpointPending(home, epochHash), done = abandonPlacementCheckpoint(home, epochHash, { mutation, assertCurrent: () => assertPlacementActivationOwner(owner) });
203
+ return { removed: done.removed, abandoned: pending, nextStep: CHECKPOINT_PREVIEW };
204
+ } catch (error) {
205
+ if (error instanceof SyncPlacementJournalError && Object.getOwnPropertyDescriptor(error, "code")?.value === "pending") throw new PlacementCheckpointError("commit-started");
206
+ throw error;
207
+ } finally { releasePlacementStorageCaches(); }
208
+ });
209
+ }
@@ -0,0 +1,141 @@
1
+ /** Offline, effect-free prospective publication sizing for checkpoint headroom. */
2
+ import { createHash } from "node:crypto";
3
+ import { existsSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { canonicalJSON, hashJSON, readProfileJSON } from "./generation.ts";
6
+ import { readEffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
7
+ import { readActivePlacementBinding } from "./sync-placement-active.ts";
8
+ import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
9
+ import { previewSelectedSyncPlacementSources } from "./sync-placement-capture.ts";
10
+ import { placementInventory, placementInventoryBatches, type InventoryRealm } from "./sync-placement-inventory.ts";
11
+ import { captureInspectionJournal, inspectRetainedPublicationHistories, PlacementInspectionObjects } from "./sync-placement-inspection-evidence.ts";
12
+ import { createPlacementRecord, SyncPlacementJournalError, PLACEMENT_JOURNAL_CHUNK_MAX_BYTES, type PlacementRealm } from "./sync-placement-journal-format.ts";
13
+ import { materializePlacementRows, verifiedPlacementPrunes } from "./sync-placement-materialize.ts";
14
+ import { planPlacementPublicationAsync, publicationBytes, publicationFileNames } from "./sync-placement-publication-plan.ts";
15
+ import { placementPublicationEventSteps } from "./sync-placement-publication-events.ts";
16
+ import { drainSteps } from "./sync-placement-yield.ts";
17
+ import { outboundPolicyEvaluator } from "./sync-screen.ts";
18
+ import { resolveShardProfile } from "./shard.ts";
19
+ import { readPublicPruneViewForActivation } from "./public-prune-view.ts";
20
+ import { reducePublicPruneInputs } from "./public-prune-inputs.ts";
21
+ import { reducePruneRows, type PruneRow } from "./prune.ts";
22
+ import { explicitExpirySnapshot } from "./generation-index.ts";
23
+ import { inspectPublisherPruneLineages } from "./prune-publisher-lineage.ts";
24
+ import type { ShardSyncRealm, ShardSyncRow } from "./shard-sync-format.ts";
25
+
26
+ export type CheckpointProspective = { state: "none" } | { state: "cache-only"; slots: number; reservedJournalChunks: number }
27
+ | { state: "unavailable"; reason: "cache-or-remote-evidence-unavailable" };
28
+ const realm = (item: InventoryRealm): PlacementRealm => item.scope === "user" ? { scope: "user" } : { scope: "project", keyHash: item.keyHash };
29
+ const shard = (item: InventoryRealm): ShardSyncRealm => item.scope === "user" ? { scope: "user" } : { scope: "project", key: item.key };
30
+ const same = (a: PlacementRealm, b: PlacementRealm) => canonicalJSON(a) === canonicalJSON(b);
31
+ const sha = (s: string) => createHash("sha256").update(s).digest("hex");
32
+ const slots = (value: { slots: number; reservedJournalChunks: number }) => value.slots + value.reservedJournalChunks;
33
+ function reserve(lengths: readonly number[]): number {
34
+ let chunks = 0, size = 0;
35
+ for (const bytes of lengths) { if (!chunks || size + bytes > PLACEMENT_JOURNAL_CHUNK_MAX_BYTES) { chunks++; size = 0; } size += bytes; }
36
+ return chunks + (lengths.length ? 1 : 0);
37
+ }
38
+ /** Only fixed local Git reads; missing cached refs/objects cannot establish a current remote plan without network. */
39
+ export async function checkpointProspective(home: string): Promise<{ value: CheckpointProspective; assertCurrent(): void }> {
40
+ const markers = readPlacementRuntimeMarkers(home), active = readActivePlacementBinding(home, markers.profile, markers.shards);
41
+ if (!active) throw new Error("sync placement unavailable");
42
+ const inventory = placementInventory(home), inventoryHash = hashJSON(inventory), effective = readEffectiveRealmInventory(home, active);
43
+ const batches = placementInventoryBatches(inventory.local), sourceChecks: (() => void)[] = [];
44
+ const checkInventory = () => { effective.assertCurrent(); if (hashJSON(placementInventory(home)) !== inventoryHash) throw new Error("placement inventory changed"); };
45
+ if (!batches.length) return { value: { state: "none" }, assertCurrent: checkInventory };
46
+ const cache = join(home, "shard-sync-placement", "objects.git");
47
+ if (!existsSync(cache)) return { value: { state: "unavailable", reason: "cache-or-remote-evidence-unavailable" },
48
+ assertCurrent: () => { checkInventory(); if (existsSync(cache)) throw new Error("placement cache changed"); } };
49
+ const journal = captureInspectionJournal(home, active.profile.placementHead);
50
+ let objects: PlacementInspectionObjects;
51
+ try { objects = new PlacementInspectionObjects(home, () => { checkInventory(); journal.assertCurrent(); }); }
52
+ catch {
53
+ // A changed journal or inventory is not a missing remote: never turn a concurrent drift into the fallback.
54
+ checkInventory(); journal.assertCurrent();
55
+ return { value: { state: "unavailable", reason: "cache-or-remote-evidence-unavailable" }, assertCurrent: () => { checkInventory(); journal.assertCurrent(); } };
56
+ }
57
+ const view = readPublicPruneViewForActivation(home, active.profile.pruneInputSetHash, active.profile.generation);
58
+ let largest: { slots: number; reservedJournalChunks: number } | undefined;
59
+ for (const batch of batches) {
60
+ const selected = batch.map(realm), source = previewSelectedSyncPlacementSources(home, selected);
61
+ const targets = batch.map(item => ({ realm: shard(item), profile: resolveShardProfile(home, item.scope === "user" ? { user: true } : { project: item.key }) }));
62
+ let heads: (string | undefined)[];
63
+ try { heads = targets.map(target => objects.ref(target.realm)); }
64
+ catch (error) {
65
+ if (error instanceof SyncPlacementJournalError && (error.code === "corrupt" || error.code === "bound"))
66
+ return { value: { state: "unavailable", reason: "cache-or-remote-evidence-unavailable" },
67
+ assertCurrent: () => { checkInventory(); source.assertSourcesUnchanged(); journal.assertCurrent(); } };
68
+ throw error;
69
+ }
70
+ // A missing cache ref is usable only when the latest retained completed publication for this remote and realm
71
+ // observed an absent ref. With no such receipt it could be an unfetched remote, so never invent an empty history.
72
+ const publications = [...journal.publications.values()].filter(item => item.phase === "completed" && item.bundle.root.remoteHash === objects.remoteHash
73
+ && item.facts.some(fact => fact.phase === "completed" && fact.outcome === "committed"))
74
+ .sort((a, b) => a.bundle.root.journal.sequence - b.bundle.root.journal.sequence);
75
+ const knownEmpty = (identity: PlacementRealm) => {
76
+ const matching = publications.flatMap(item => item.bundle.root.targets.filter(target => same(target.realm, identity)));
77
+ const last = matching.at(-1); return !!last && !last.publish && last.expectedRemoteHead === null && last.commit === null;
78
+ };
79
+ if (heads.some((head, index) => head === undefined && !knownEmpty(selected[index]!)))
80
+ return { value: { state: "unavailable", reason: "cache-or-remote-evidence-unavailable" },
81
+ assertCurrent: () => { checkInventory(); source.assertSourcesUnchanged(); journal.assertCurrent(); } };
82
+ // A mutable cache ref is not a remote receipt: retain only the head verified through the publication journal.
83
+ let histories: Awaited<ReturnType<typeof inspectRetainedPublicationHistories>>;
84
+ try { histories = await inspectRetainedPublicationHistories(journal, targets.map(target => ({ realm: target.realm, generation: active.profile.generation })), objects); }
85
+ catch (error) {
86
+ if (error instanceof SyncPlacementJournalError && (error.code === "corrupt" || error.code === "bound"))
87
+ return { value: { state: "unavailable", reason: "cache-or-remote-evidence-unavailable" },
88
+ assertCurrent: () => { checkInventory(); source.assertSourcesUnchanged(); journal.assertCurrent(); } };
89
+ throw error;
90
+ }
91
+ if (heads.some((head, index) => head !== histories.tips[index]))
92
+ return { value: { state: "unavailable", reason: "cache-or-remote-evidence-unavailable" },
93
+ assertCurrent: () => { checkInventory(); source.assertSourcesUnchanged(); journal.assertCurrent(); } };
94
+ const old = histories.old;
95
+ const planned = targets.map((target, index) => {
96
+ const identity = selected[index]!, id = canonicalJSON(identity), sources = source.sourceRowsByRealm.get(id);
97
+ if (!sources) throw new Error("selected placement source unavailable");
98
+ const prunes = [...source.specialRows.values()].filter(row => same(row.key.realm, identity) && row.row.op === "prune");
99
+ const reduced = reducePruneRows(prunes.map(row => ({ row: row.row as PruneRow, placement: row.sourcePlacement })), { rows: sources, expiries: explicitExpirySnapshot(sources) }, active.profile.generation);
100
+ if (reduced.invalid || reduced.pending.length) throw new Error("placement prune proof unavailable");
101
+ const inputHash = view.realms[target.realm.scope === "user" ? "user" : `project:${target.realm.key}`];
102
+ const pruned = inputHash ? reducePublicPruneInputs({ dir: target.profile.dir, realm: target.realm, receivingGeneration: active.profile.generation, inputSetHash: inputHash,
103
+ publicationFormat: active.profile.publicationFormat, nativeTargets: [...reduced.targets], ordinary: sources.map(row => row.row) }).targets : reduced.targets;
104
+ return { realm: target.realm, generation: active.profile.generation, remote: heads[index], local: heads[index], fetched: new Set(old[index]?.rows.keys() ?? []),
105
+ localPrunes: new Map(prunes.filter(row => row.sourcePlacement === "synced").map(row => [row.key.id, row.row as PruneRow])), pruned };
106
+ });
107
+ const lineages = targets.map((target, index) => {
108
+ const rows = new Map<string, ShardSyncRow>(old[index]?.rows);
109
+ for (const value of [...source.rows.values(), ...source.specialRows.values()]) if (same(value.key.realm, selected[index]!) && value.row.op !== "vault_link") {
110
+ const prior = rows.get(value.key.id); if (prior && hashJSON(prior) !== value.key.rowHash) throw new Error("placement row mismatch"); rows.set(value.key.id, value.row);
111
+ }
112
+ const candidates = [...rows.values()].filter((row): row is PruneRow => row.op === "prune" && row.generation === active.profile.generation);
113
+ const machine = readProfileJSON(join(target.profile.dir, "machine.json")) as { id: string };
114
+ const boundary = join(target.profile.dir, "local", `publisher-boundary-${machine.id}.json`);
115
+ return { rows, proof: candidates.length && existsSync(boundary) ? inspectPublisherPruneLineages(target.profile, candidates) : new Map() };
116
+ });
117
+ const verified = verifiedPlacementPrunes(targets.map((target, index) => ({ realm: target.realm, generation: active.profile.generation, rows: lineages[index]!.rows,
118
+ fetched: planned[index]!.fetched, lineageIds: new Set<string>(lineages[index]!.proof.keys()) })));
119
+ const evaluate = outboundPolicyEvaluator(home), now = Date.now(), materialized = await materializePlacementRows({ capture: source, projection: journal.projection,
120
+ generation: active.profile.generation, targets: planned, old, verifiedPrunes: verified, evaluate, createdUnixSeconds: Math.floor(now / 1000),
121
+ readTree: async (_index, head) => objects.tree(head), publisherLineages: (index, rows) => inspectPublisherPruneLineages(targets[index]!.profile, rows) });
122
+ const body = { epochHash: active.profile.placementHead, generation: active.profile.generation, homeHash: source.base.homeHash,
123
+ contextHash: sha("checkpoint-preview"), markerHash: source.markerHash, sourceHash: source.base.sourceHash, aliasesHash: source.base.aliasesHash,
124
+ policyHash: source.base.policyHash, remoteHash: objects.remoteHash, journal: { sequence: journal.journal.sequence, headHash: journal.journal.headHash },
125
+ createdUnixSeconds: Math.floor(now / 1000), policySnapshotUnixMs: now, targets: materialized.plannedTargets, reservedRecords: 0, reservedRecordBytes: [] as number[] };
126
+ const items = { sources: source.prefixes, decisions: materialized.decisions, objects: materialized.objects };
127
+ let bundle = await planPlacementPublicationAsync(body, items);
128
+ const scheduled = drainSteps(placementPublicationEventSteps(bundle, journal.projection, old));
129
+ let head = body.journal.headHash;
130
+ const lengths = scheduled.events.map((event, index) => { const record = createPlacementRecord(body.epochHash, body.journal.sequence + index + 1, head, event); head = record.seal; return publicationBytes(record).length; });
131
+ bundle = await planPlacementPublicationAsync({ ...body, reservedRecords: lengths.length, reservedRecordBytes: lengths }, items);
132
+ const changed = bundle.root.targets.some((target, index) => target.publish && target.commit !== heads[index]);
133
+ if (scheduled.events.length || changed) {
134
+ const candidate = { slots: publicationFileNames(bundle.root).length, reservedJournalChunks: reserve(lengths) };
135
+ if (!largest || slots(candidate) > slots(largest)) largest = candidate;
136
+ }
137
+ source.assertSourcesUnchanged(); journal.assertCurrent(); objects.assertRetained(); sourceChecks.push(source.assertSourcesUnchanged);
138
+ }
139
+ return { value: largest ? { state: "cache-only", ...largest } : { state: "none" },
140
+ assertCurrent: () => { checkInventory(); for (const check of sourceChecks) check(); journal.assertCurrent(); objects.assertRetained(); } };
141
+ }