@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
@@ -1,6 +1,6 @@
1
1
  /** Activated placement transport. The public sync entrypoint owns dispatch; this module never activates a profile. */
2
2
  import { createHash, randomBytes } from "node:crypto";
3
- import { constants, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, rmSync, writeSync } from "node:fs";
3
+ import { constants, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, rmSync, writeSync, type BigIntStats } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { canonicalJSON, hashJSON, readSelector } from "./generation.ts";
6
6
  import { generationSyncLock } from "./generation-sync.ts";
@@ -11,32 +11,40 @@ import { memoryPolicySnapshot } from "./policy.ts";
11
11
  import { outboundPolicyEvaluator } from "./sync-screen.ts";
12
12
  import { readActivePlacementBinding } from "./sync-placement-active.ts";
13
13
  import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
14
- import { captureSyncPlacementContextAsync, placementCaptureContextHash, type PlacementCapture, type PlacementPendingSource } from "./sync-placement-capture.ts";
14
+ import { captureSyncPlacementContextAsync, placementCaptureContextHash, previewSyncPlacementSources, type PlacementCapture, type PlacementPendingSource } from "./sync-placement-capture.ts";
15
15
  import { readEffectiveSyncPlacementWriters, type EffectiveSyncPlacementWriters } from "./sync-placement-effective-writers.ts";
16
16
  import { SharedWriterRevisionError } from "./sync-placement-writer-revision-format.ts";
17
17
  import { types } from "node:util";
18
+ import { RemoteRealmRefusal, type RemoteRealmCause } from "./sync-placement-remote-refusal.ts";
18
19
  import type { PlannedGitObject } from "./sync-placement-git.ts";
19
- import { PLACEMENT_FORMAT } from "./sync-placement-format.ts";
20
- import { PLACEMENT_JOURNAL_MAX_RECORDS, PLACEMENT_JOURNAL_MAX_OBJECTS, createPlacementRecord, placementKeyId, type PlacementEvent, type PlacementRealm, type PlacementHoldReason, type PlacementRecord } from "./sync-placement-journal-format.ts";
20
+ import { PLACEMENT_FORMAT, PLACEMENT_PROFILE_SCHEMA, SyncPlacementFormatError } from "./sync-placement-format.ts";
21
+ import { PLACEMENT_JOURNAL_MAX_RECORDS, PLACEMENT_JOURNAL_MAX_OBJECTS, createPlacementRecord, placementKeyId, type PlacementEvent, type PlacementRealm, type PlacementRecord } from "./sync-placement-journal-format.ts";
21
22
  import { rebuildPlacementProjection, type PlacementProjection } from "./sync-placement-projection.ts";
22
- import { readPlacementJournal, appendPlacementEvent, appendPlacementEvents, releasePlacementStorageCaches, ensurePlacementPublicationDurability, readPlacementPublicationMetadata, type PlacementJournalRead, type PlacementStorageOptions } from "./sync-placement-journal-storage.ts";
23
+ import { readPlacementJournal, readPlacementWriterJournalAnchors, placementWriterJournalToken, appendPlacementEvent, appendPlacementEvents, releasePlacementStorageCaches, ensurePlacementPublicationDurability, readPlacementPublicationMetadata, placementJournalObjectComposition, placementJournalObjectCompositionText, type PlacementJournalObjectComposition, type PlacementJournalRead, type PlacementStorageOptions } from "./sync-placement-journal-storage.ts";
23
24
  import { formatFloorAtLeast } from "./formats.ts";
24
25
  import { preparePlacementPublication, readPlacementPublication, recordPlacementPublicationPhase, type PlacementPublicationRead } from "./sync-placement-publication-storage.ts";
25
- import { planPlacementPublication, publicationBytes, publicationFileNames, type PlacementPublicationBundle, type PlacementPublicationDecision, type PlacementPublicationObject } from "./sync-placement-publication-plan.ts";
26
+ import { planPlacementPublication, planPlacementPublicationAsync, publicationBytes, publicationFileNames, type PlacementPublicationBundle, type PlacementPublicationDecision, type PlacementPublicationObject } from "./sync-placement-publication-plan.ts";
27
+ import { placementPublicationEventSteps } from "./sync-placement-publication-events.ts";
26
28
  import { ShardHistoryAuditor, type ShardHistory } from "./shard-sync-history.ts";
27
29
  import { ShardSyncApplications } from "./shard-sync-applications.ts";
28
- import { shardSourceRows, shardProvePrunes, shardImportRows, shardSelectorRetention, shardInstallHold, shardHoldWarning, type ShardSyncApplicationTarget } from "./shard-sync.ts";
30
+ import { ShardSourceChangedError, shardSourceRowsAsync, shardProvePrunes, shardImportRows, shardSelectorRetention, shardInstallHold, shardHoldWarning, type ShardSyncApplicationTarget } from "./shard-sync.ts";
29
31
  import { shardSyncRef, SHARD_PACK_MAX_BYTES } from "./shard-sync-format.ts";
30
32
  import { assertPublisherBoundary, ensurePublisherBoundary, publisherPruneLineages } from "./prune-publisher-lineage.ts";
31
33
  import type { MemoryStore } from "./store.ts";
32
34
  import type { PruneRow } from "./prune.ts";
33
35
  import { materializePlacementRows, verifiedPlacementPrunes } from "./sync-placement-materialize.ts";
34
- import { cooperativeYield, PLACEMENT_APPEND_SLICE, yieldTurn } from "./sync-placement-yield.ts";
35
- import { placementCacheConfigStamp, placementCacheRootStamp, validatePlacementCacheConfig } from "./sync-placement-cache.ts";
36
- import { PlacementSyncBoundError, placementSyncBoundMessage, placementSyncBoundReceipt, type PlacementSyncBound } from "./sync-placement-bound.ts";
36
+ import { cooperativeYield, drainSteps, drainStepsAsync, PLACEMENT_APPEND_SLICE, yieldTurn, type CooperativeYield } from "./sync-placement-yield.ts";
37
+ import { placementCacheConfigStamp, placementCacheRootStamp, placementCacheTreePrivate, validatePlacementCacheConfig } from "./sync-placement-cache.ts";
38
+ import { PlacementSyncBoundError, placementSyncBoundDetail, placementSyncBoundMessage, placementSyncBoundReceipt, type PlacementSyncBound } from "./sync-placement-bound.ts";
39
+ import { PLACEMENT_CHECKPOINT_PENDING_MESSAGE, placementCheckpointPending } from "./sync-placement-checkpoint-storage.ts";
37
40
  import type { SyncProgress, SyncProgressPhase } from "./sync-progress.ts";
38
41
  import { PlacementSyncRefusal, placementRefusalCategoryOf, placementRefusalMessage, type PlacementRefusalCategory } from "./sync-placement-refusal.ts";
39
42
  import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
43
+ import { readEffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
44
+ import { listRemotePlacementRealms, REMOTE_REALM_ADVERTISEMENT_BYTES, type RemoteOnlyRealm } from "./sync-placement-realm-discovery.ts";
45
+ import { realPath } from "./platform.ts";
46
+ import { createRemoteAdoption, REMOTE_ADOPTION_SCHEMA, validateRemoteAdoption, type RemoteAdoption } from "./sync-placement-remote-adoption-format.ts";
47
+ import { remoteStagedPacks, selectRemoteMaterialization, type RemoteStagedPack } from "./sync-placement-remote-materialization.ts";
40
48
 
41
49
  /**
42
50
  * #417 proof scope. A complete proof (full writer-install measurement, source, policy and selector recheck) is taken
@@ -55,10 +63,20 @@ const oid = (v: unknown): v is string => typeof v === "string" && v.length === 4
55
63
  const sameRealm = (a: PlacementRealm, b: PlacementRealm) => canonicalJSON(a) === canonicalJSON(b);
56
64
  const physical = (target: Target): PlacementRealm => target.realm.scope === "user" ? { scope: "user" } : { scope: "project", keyHash: digest(target.realm.key) };
57
65
  function refuse(category: PlacementRefusalCategory = "other"): never { throw new PlacementSyncRefusal(category); }
66
+ function remoteRefusal(error: unknown, fallback: RemoteRealmCause = "other"): never {
67
+ if (error instanceof RemoteRealmRefusal) throw error;
68
+ if (error instanceof SyncPlacementFormatError || error instanceof Error && error.message === "sync placement activation metadata unavailable or changed; inspect the retained activation before continuing") throw new RemoteRealmRefusal("epoch");
69
+ const category = placementRefusalCategoryOf(error) ?? classifyPlacementError(error);
70
+ const cause: RemoteRealmCause = category === "lock" ? "lock" : category === "epoch" ? "epoch"
71
+ : category === "remote" ? "remote" : category === "size-bound" ? "bound"
72
+ : category === "source-selection" || category === "policy" || category === "writer-pin" ? "drift" : fallback;
73
+ throw new RemoteRealmRefusal(cause);
74
+ }
58
75
  /** #426: map a foreign error to a category by its class and allowlisted code only, never by its message text. */
59
76
  export function classifyPlacementError(error: unknown): PlacementRefusalCategory | undefined {
60
77
  try {
61
78
  if (!error || typeof error !== "object" || types.isProxy(error)) return undefined;
79
+ if (error instanceof ShardSourceChangedError) return "source-selection";
62
80
  if (error instanceof SharedWriterRevisionError) return "writer-pin";
63
81
  if (error instanceof SyncPlacementJournalError) { const code = Object.getOwnPropertyDescriptor(error, "code")?.value; return code === "bound" ? "size-bound" : code === "changed" ? "source-selection" : "epoch"; }
64
82
  const code = Object.getOwnPropertyDescriptor(error, "code")?.value;
@@ -72,6 +90,145 @@ function emptyHistory(): ShardHistory { return { rows: new Map(), files: new Map
72
90
  export async function syncPlacementMemory(store: MemoryStore, opts: SyncOptions = {}, phase?: Phase, testOnlyError?: (error:unknown)=>void, testOnlyClock?: () => number, targets?: readonly MemoryStore[]): Promise<SyncResult> {
73
91
  return new PlacementTransport(store, opts, phase, testOnlyError, testOnlyClock, targets).run();
74
92
  }
93
+
94
+ type RemoteReadOptions = Pick<SyncOptions, "signal" | "visibility">;
95
+ /** Shared configured-remote proof for discovery and audited read-only preview. */
96
+ async function configuredRemoteContext(homeInput: string, opts: RemoteReadOptions, requireVisibility = true) {
97
+ // Git tracing can write an arbitrary file outside the sync cache, which a read-only listing must not do.
98
+ if (Object.entries(process.env).some(([name, value]) => name.startsWith("GIT_TRACE") && !!value)) throw new RemoteRealmRefusal("environment");
99
+ const home = realPath(homeInput), markers = readPlacementRuntimeMarkers(home);
100
+ if (!markers.profile || typeof markers.profile !== "object" || Object.getOwnPropertyDescriptor(markers.profile, "schema")?.value !== PLACEMENT_PROFILE_SCHEMA) return refuse("epoch");
101
+ const active = readActivePlacementBinding(home, markers.profile, markers.shards);
102
+ if (!active) return refuse("epoch");
103
+ const inventory = readEffectiveRealmInventory(home, active), root = join(home, "shard-sync-placement"), cache = join(root, "objects.git");
104
+ let rootStamp: string, configStamp: string, initial: BigIntStats;
105
+ try { rootStamp = placementCacheRootStamp(home); configStamp = placementCacheConfigStamp(cache); initial = lstatSync(cache, { bigint: true }); }
106
+ catch { throw new RemoteRealmRefusal("cache"); }
107
+ if (!initial.isDirectory() || initial.isSymbolicLink() || initial.uid !== BigInt(process.getuid?.() ?? -1) || (initial.mode & 0o077n) !== 0n) throw new RemoteRealmRefusal("cache");
108
+ if (!placementCacheTreePrivate(cache)) throw new RemoteRealmRefusal("cache");
109
+ const forbidden = ["commondir", "shallow", "info/grafts", "objects/info/alternates", "objects/info/http-alternates", "config.worktree"];
110
+ try { if (forbidden.some(name => lstatSync(join(cache, name), { throwIfNoEntry: false }) !== undefined)) throw new RemoteRealmRefusal("cache"); }
111
+ catch { throw new RemoteRealmRefusal("cache"); }
112
+ const check = () => {
113
+ let stat: BigIntStats; try { stat = lstatSync(cache, { bigint: true }); } catch { throw new RemoteRealmRefusal("cache"); }
114
+ const nowMarkers = readPlacementRuntimeMarkers(home), now = readActivePlacementBinding(home, nowMarkers.profile, nowMarkers.shards);
115
+ if (!now || canonicalJSON(now.profile) !== canonicalJSON(active.profile) || canonicalJSON(now.shards) !== canonicalJSON(active.shards)) return refuse("source-selection");
116
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.dev !== initial.dev || stat.ino !== initial.ino
117
+ || !cacheUnchanged()) throw new RemoteRealmRefusal("cache");
118
+ try { inventory.assertCurrent(); } catch { return refuse("source-selection"); }
119
+ };
120
+ const cacheUnchanged = () => { try { return placementCacheRootStamp(home) === rootStamp && placementCacheConfigStamp(cache) === configStamp && !forbidden.some(name => lstatSync(join(cache, name), { throwIfNoEntry: false }) !== undefined); } catch { return false; } };
121
+ const args = (values: string[]) => ["--no-replace-objects", "--git-dir", cache, "-c", "maintenance.auto=false", "-c", "gc.auto=0", "-c", "core.commitGraph=false", ...values];
122
+ check();
123
+ const config = await generationSyncGitBytes(root, args(["config", "--local", "--no-includes", "--null", "--list"]), opts.signal, undefined, 65536);
124
+ check(); if (config.code !== 0) throw new RemoteRealmRefusal("cache");
125
+ let settings: ReadonlyMap<string, string>; try { settings = validatePlacementCacheConfig(new TextDecoder("utf-8", { fatal: true }).decode(config.out)); } catch { throw new RemoteRealmRefusal("cache"); }
126
+ const url = settings.get("remote.origin.url");
127
+ if (settings.get("core.bare") !== "true" || settings.has("remote.origin.pushurl") && settings.get("remote.origin.pushurl") !== url) throw new RemoteRealmRefusal("cache");
128
+ if (!url || url.length > 4096 || url.startsWith("-") || /[\r\n\0]/.test(url)) return refuse("remote");
129
+ if (requireVisibility && await (opts.visibility ?? remoteVisibility)(url) !== "private") return refuse("remote");
130
+ check();
131
+ return { home, active, inventory, root, cache, url, args, check };
132
+ }
133
+
134
+ /** Read only the configured placement remote; discovery never initializes a cache or adopts a realm. */
135
+ export async function discoverRemotePlacementRealms(homeInput: string, opts: RemoteReadOptions = {}): Promise<RemoteOnlyRealm[]> {
136
+ try {
137
+ const context = await configuredRemoteContext(homeInput, opts);
138
+ const realms = await listRemotePlacementRealms(context.inventory, async () => {
139
+ const advertised = await generationSyncGitBytes(context.root, context.args(["ls-remote", "--refs", context.url, "refs/heads/amem/p/*"]), opts.signal, undefined, REMOTE_REALM_ADVERTISEMENT_BYTES);
140
+ context.check(); if (advertised.code !== 0) return refuse("remote");
141
+ return advertised.out;
142
+ });
143
+ context.check(); return realms;
144
+ } catch (error) { return remoteRefusal(error); }
145
+ }
146
+
147
+ /** Recheck the reviewed head and configured remote immediately before staging publication. */
148
+ export async function assertRemoteAdoptionCurrent(homeInput: string, project: string, plan: RemoteAdoption, opts: RemoteReadOptions = {}): Promise<void> {
149
+ try {
150
+ plan = validateRemoteAdoption(plan);
151
+ const ctx = await configuredRemoteContext(homeInput, opts), key = createHash("sha256").update(project).digest("hex");
152
+ if (key !== plan.keyHash || ctx.active.epoch.homeHash !== plan.homeHash || ctx.active.profile.placementHead !== plan.epochHash
153
+ || ctx.active.epoch.generation !== plan.generation || createHash("sha256").update(ctx.url).digest("hex") !== plan.remoteHash) return refuse("source-selection");
154
+ const ref = shardSyncRef({ scope: "project", key: project }), result = await generationSyncGitBytes(ctx.root,
155
+ ctx.args(["ls-remote", "--refs", ctx.url, ref]), opts.signal, undefined, 256);
156
+ ctx.check(); if (result.code !== 0 || new TextDecoder("utf-8", { fatal: true }).decode(result.out) !== `${plan.remoteHead}\t${ref}\n`) return refuse("remote");
157
+ } catch (error) { return remoteRefusal(error); }
158
+ }
159
+
160
+ export interface PreparedRemoteRealm { plan: RemoteAdoption; packs: RemoteStagedPack[] }
161
+ async function auditRemoteHistory(ctx: Awaited<ReturnType<typeof configuredRemoteContext>>, project: string, head: string, opts: RemoteReadOptions): Promise<ShardHistory> {
162
+ const gitBytes = async (args: string[], max: number) => { ctx.check(); const result = await generationSyncGitBytes(ctx.root, ctx.args(args), opts.signal, undefined, max); ctx.check(); if (result.code !== 0) return refuse("remote"); return Buffer.from(result.out); };
163
+ const auditor = new ShardHistoryAuditor({ realm: { scope: "project", key: project }, generation: ctx.active.epoch.generation, placement: true, publicPrune: true,
164
+ git: async args => { ctx.check(); const result = await generationSyncGit(ctx.root, ctx.args(args), opts.signal); ctx.check(); if (result.code !== 0) return refuse("remote"); return result.out; },
165
+ blob: async (oid, path) => gitBytes(["cat-file", "blob", oid], path === "shard.json" || path.startsWith("prune-witnesses/") ? 65536 : SHARD_PACK_MAX_BYTES),
166
+ object: async (oid, type) => {
167
+ const bytes = await gitBytes(["cat-file", type, oid], type === "commit" ? 65536 : SHARD_PACK_MAX_BYTES);
168
+ if (createHash("sha1").update(`${type} ${bytes.length}\0`).update(bytes).digest("hex") !== oid) return refuse("remote"); return bytes;
169
+ },
170
+ });
171
+ return auditor.history(head);
172
+ }
173
+
174
+ /** Reconstruct frozen pack bytes from the existing cache without contacting the remote. */
175
+ export async function recoverRemoteStagedPacks(homeInput: string, project: string, plan: RemoteAdoption): Promise<RemoteStagedPack[]> {
176
+ try {
177
+ plan = validateRemoteAdoption(plan);
178
+ const ctx = await configuredRemoteContext(homeInput, {}, false), key = createHash("sha256").update(project).digest("hex");
179
+ if (key !== plan.keyHash || ctx.active.epoch.homeHash !== plan.homeHash || ctx.active.profile.placementHead !== plan.epochHash
180
+ || ctx.active.epoch.generation !== plan.generation || createHash("sha256").update(ctx.url).digest("hex") !== plan.remoteHash) return refuse("source-selection");
181
+ const selection = selectRemoteMaterialization(await auditRemoteHistory(ctx, project, plan.remoteHead, {})), packs = remoteStagedPacks(selection);
182
+ if (selection.omitted !== plan.omitted || canonicalJSON(packs.map(pack => ({ name: pack.name, bytes: pack.bytes.length }))) !== canonicalJSON(plan.packs)) return refuse("source-selection");
183
+ ctx.check(); return packs;
184
+ } catch (error) { return remoteRefusal(error, "staging"); }
185
+ }
186
+ /** Fetch and audit one explicitly named remote-only realm into the existing private cache, never the live shard. */
187
+ export async function prepareRemotePlacementRealm(homeInput: string, project: string, opts: RemoteReadOptions = {}): Promise<PreparedRemoteRealm> {
188
+ let releaseRoot: (() => void) | undefined, releaseSync: (() => void) | undefined, incoming: string | undefined;
189
+ let context: Awaited<ReturnType<typeof configuredRemoteContext>> | undefined;
190
+ try {
191
+ if (!project || Buffer.byteLength(project) > 400 || /[\r\n\0]/.test(project)) return refuse("source-selection");
192
+ context = await configuredRemoteContext(homeInput, opts);
193
+ const ctx = context, keyHash = createHash("sha256").update(project).digest("hex");
194
+ // Ref names use only 16 hex characters; a prefix already bound to another full key is never adopted as a new realm.
195
+ if (ctx.inventory.realms.some(realm => realm.scope === "project" && realm.keyHash.slice(0, 16) === keyHash.slice(0, 16))) return refuse("source-selection");
196
+ const ref = shardSyncRef({ scope: "project", key: project }), source = previewSyncPlacementSources(ctx.home);
197
+ const writers = readEffectiveSyncPlacementWriters(ctx.home), journalToken = placementWriterJournalToken(ctx.home, ctx.active.profile.placementHead);
198
+ const journal = readPlacementWriterJournalAnchors(ctx.home, ctx.active.profile.placementHead);
199
+ const journalHead = journal.sequence ? journal.records[journal.sequence - 1]!.seal : ctx.active.profile.placementHead;
200
+ const check = () => {
201
+ ctx.check();
202
+ try { writers.assertCurrent(); if (placementWriterJournalToken(ctx.home, ctx.active.profile.placementHead) !== journalToken) return refuse("source-selection"); source.assertSourcesUnchanged(); }
203
+ catch { return refuse("source-selection"); }
204
+ ctx.check();
205
+ };
206
+ check(); releaseRoot = acquireMutation(ctx.root); if (!releaseRoot) return refuse("lock");
207
+ releaseSync = generationSyncLock(ctx.root); if (!releaseSync) return refuse("lock");
208
+ const gitBytes = async (args: string[], max: number) => { check(); const result = await generationSyncGitBytes(ctx.root, ctx.args(args), opts.signal, undefined, max); check(); if (result.code !== 0) return refuse("remote"); return Buffer.from(result.out); };
209
+ const advertised = await gitBytes(["ls-remote", "--refs", ctx.url, ref], 256);
210
+ const match = /^([a-f0-9]{40})\t([^\n]+)\n$/.exec(advertised.toString("utf8"));
211
+ if (!match || match[2] !== ref) return refuse("remote");
212
+ const head = match[1]!; incoming = `refs/amem/placement-incoming/${randomBytes(16).toString("hex")}`;
213
+ await gitBytes(["fetch", "-q", "--no-tags", "--no-write-fetch-head", "--no-recurse-submodules", ctx.url, `${ref}:${incoming}`], 65536);
214
+ const fetched = (await gitBytes(["rev-parse", "--verify", incoming], 128)).toString("utf8").trim(); if (fetched !== head) return refuse("remote");
215
+ const history = await auditRemoteHistory(ctx, project, head, opts), selection = selectRemoteMaterialization(history), packs = remoteStagedPacks(selection);
216
+ if (!(await gitBytes(["ls-remote", "--refs", ctx.url, ref], 256)).equals(advertised)) return refuse("remote");
217
+ check();
218
+ const plan = createRemoteAdoption({ schema: REMOTE_ADOPTION_SCHEMA, homeHash: ctx.active.epoch.homeHash, epochHash: ctx.active.profile.placementHead,
219
+ generation: ctx.active.epoch.generation, keyHash, remoteHash: createHash("sha256").update(ctx.url).digest("hex"), remoteHead: head,
220
+ sourceHash: source.base.sourceHash, policyHash: source.base.policyHash, aliasesHash: source.base.aliasesHash,
221
+ writerHash: writers.revisionHash, inventoryHead: ctx.inventory.extensionHead, journalSequence: journal.sequence, journalHead, omitted: selection.omitted,
222
+ packs: packs.map(pack => ({ name: pack.name, bytes: pack.bytes.length })) });
223
+ check(); return { plan, packs };
224
+ } catch (error) { return remoteRefusal(error); }
225
+ finally {
226
+ if (context && incoming) try {
227
+ context.check(); await generationSyncGit(context.root, context.args(["update-ref", "--no-deref", "-d", incoming]), undefined);
228
+ } catch { /* no authoritative state uses this private cache ref */ }
229
+ releaseSync?.(); releaseRoot?.();
230
+ }
231
+ }
75
232
  class PlacementTransport {
76
233
  readonly store: MemoryStore; readonly opts: SyncOptions; readonly phase?: Phase; readonly testOnlyError?: (error:unknown)=>void; readonly home: string; readonly root: string; readonly cache: string;
77
234
  readonly releases: (() => void)[] = []; readonly temporary: string[] = []; readonly refs: string[] = [];
@@ -83,6 +240,8 @@ class PlacementTransport {
83
240
  /** #462: a closed cause the catch block identified before `result` derives the rest. */
84
241
  failureCause?: SyncFailureCause;
85
242
  readonly clock: () => number; readonly progress?: SyncProgress; provedAt?: number; bound?: PlacementSyncBound; capturedPolicyVersion?: string;
243
+ /** #288 step 1: the journal-objects bound's own composition, numbers only, set where the bound is measured. */
244
+ journalObjects?: PlacementJournalObjectComposition;
86
245
  readonly selected?: readonly MemoryStore[];
87
246
  constructor(store: MemoryStore, opts: SyncOptions, phase?: Phase, testOnlyError?: (error:unknown)=>void, clock: () => number = () => performance.now(), selected?: readonly MemoryStore[]) { this.selected=selected; this.clock=clock; this.progress=opts.progress; this.testOnlyError=testOnlyError; this.store = store; this.opts = opts; this.phase = phase; this.home = store.profile.home; this.root = join(this.home, "shard-sync-placement"); this.cache = join(this.root, "objects.git"); }
88
247
  attest(): void {
@@ -145,7 +304,7 @@ class PlacementTransport {
145
304
  }
146
305
  async independent(): Promise<boolean> {
147
306
  if (!existsSync(this.cache)) return false; directory(this.cache); const initial=lstatSync(this.cache);
148
- const walk = (dir: string): void => { for (const name of readdirSync(dir)) { const file = join(dir, name), s = lstatSync(file); if (s.isSymbolicLink() || s.uid !== process.getuid?.() || !s.isFile() && !s.isDirectory() || s.isFile() && s.nlink !== 1 || name.endsWith(".promisor")) refuse(); if (s.isDirectory()) {directory(file);walk(file);} } }; walk(this.cache);
307
+ if (!placementCacheTreePrivate(this.cache)) refuse();
149
308
  if (existsSync(join(this.cache, "commondir")) || existsSync(join(this.cache, "objects", "info", "http-alternates")) || existsSync(join(this.cache, "objects", "info", "alternates")) || existsSync(join(this.cache, "shallow")) || existsSync(join(this.cache, "info", "grafts"))) refuse();
150
309
  if (await this.required(["rev-parse", "--is-bare-repository"]) !== "true" || await this.required(["rev-parse", "--show-object-format"]) !== "sha1" || (await this.git(["config", "--get", "core.worktree"])).code !== 1) refuse();
151
310
  if((await this.git(["config","--get","extensions.partialClone"])).code !== 1
@@ -232,9 +391,11 @@ class PlacementTransport {
232
391
  target.manifests = new Map(target.remoteHistory.manifests); target.eligible = new Set([...target.manifests.values()].filter(item => item.eligible).map(item => item.row.id));
233
392
  }
234
393
  }
235
- preflight(mergeLocal = true): void {
394
+ async preflight(mergeLocal = true): Promise<void> {
395
+ // #462: the collector yields inside the wire round trip, then re-proves the source metadata it exported.
396
+ const pause = cooperativeYield();
236
397
  for (const target of this.targets) {
237
- const source = shardSourceRows(target.store, target.realm); target.sources = source.sources; target.pending = source.pending;
398
+ const source = await shardSourceRowsAsync(target.store, target.realm, pause); target.sources = source.sources; target.pending = source.pending;
238
399
  target.localPrunes = new Map([...source.rows.filter((row): row is PruneRow => row.op === "prune"), ...source.pending.map(item => item.row)].map(row => [row.id,row]));
239
400
  if (mergeLocal) for (const row of source.rows) { const old = target.rows.get(row.id); if (old && hashJSON(old) !== hashJSON(row)) refuse(); target.rows.set(row.id, row); }
240
401
  }
@@ -306,9 +467,10 @@ class PlacementTransport {
306
467
  const body={epochHash:this.epochHash,generation:this.journal.epoch.generation,homeHash:capture.context.homeHash,contextHash:placementCaptureContextHash(capture),markerHash:capture.markerHash,
307
468
  sourceHash:capture.context.sourceHash,aliasesHash:capture.context.aliasesHash,policyHash:capture.context.policyHash,remoteHash:digest(this.url),
308
469
  journal:frozen?.root.journal??{sequence:frontier.sequence,headHash:frontier.headHash},createdUnixSeconds,policySnapshotUnixMs:frozen?.root.policySnapshotUnixMs??this.lastPolicyCheckUnixMs??Date.now(),targets,reservedRecords:0,reservedRecordBytes:[] as number[]};
309
- let bundle=planPlacementPublication(body,{sources:capture.prefixes,decisions,objects});
470
+ const planPause=cooperativeYield();
471
+ let bundle=await planPlacementPublicationAsync(body,{sources:capture.prefixes,decisions,objects},planPause);
310
472
  await yieldTurn(); // #462: planning is pure; each step gets its own turn
311
- let scheduled=this.events(bundle,projection,old);
473
+ let scheduled=await this.eventsAsync(bundle,projection,old,planPause);
312
474
  await yieldTurn();
313
475
  if(!frozen&&body.journal.sequence+scheduled.events.length>PLACEMENT_JOURNAL_MAX_RECORDS)
314
476
  throw new PlacementSyncBoundError({phase:"publication-plan",kind:"journal-records",limit:PLACEMENT_JOURNAL_MAX_RECORDS,observed:body.journal.sequence+scheduled.events.length});
@@ -316,41 +478,18 @@ class PlacementTransport {
316
478
  const lengths:number[]=[],pause=cooperativeYield();
317
479
  for(const [index,event]of scheduled.events.entries()){await pause();const record=createPlacementRecord(this.epochHash,body.journal.sequence+index+1,head,event);head=record.seal;lengths.push(publicationBytes(record).length);}
318
480
  await yieldTurn();
319
- bundle=planPlacementPublication({...body,reservedRecords:lengths.length,reservedRecordBytes:lengths},{sources:capture.prefixes,decisions,objects});
481
+ bundle=await planPlacementPublicationAsync({...body,reservedRecords:lengths.length,reservedRecordBytes:lengths},{sources:capture.prefixes,decisions,objects},planPause);
320
482
  await yieldTurn();
321
- scheduled=this.events(bundle,projection,old);
483
+ scheduled=await this.eventsAsync(bundle,projection,old,planPause);
322
484
  if(frozen&&canonicalJSON(bundle)!==canonicalJSON(frozen))refuse();
323
485
  return{bundle,decisions,projection,old,...scheduled,exported:scheduled.events.filter(event=>event.kind==="publication-ambiguous").length,withheld:decisions.filter(decision=>!decision.eligible).length};
324
486
  }
325
487
  events(bundle:PlacementPublicationBundle,projection:PlacementProjection,old:(ShardHistory|undefined)[]):{events:PlacementEvent[];preCount:number;holdCount:number}{
326
- const decisions=bundle.chunks.filter(chunk=>chunk.kind==="decisions").flatMap(chunk=>chunk.items as PlacementPublicationDecision[]).sort((a,b)=>placementKeyId(a.key).localeCompare(placementKeyId(b.key)));
327
- const holds:PlacementEvent[]=[],known:PlacementEvent[]=[],ambiguous:PlacementEvent[]=[],committed:PlacementEvent[]=[];
328
- const root=bundle.root;
329
- const make=(decision:PlacementPublicationDecision,kind:PlacementEvent["kind"],commit?:string):PlacementEvent=>{
330
- const base={requestId:hashJSON({attempt:root.seal,key:decision.key,kind,commit:commit??null}),key:decision.key,sourcePlacement:decision.sourcePlacement,
331
- effectHash:hashJSON({attempt:root.seal,context:root.contextHash,key:decision.key,kind,commit:commit??null})};
332
- if(kind==="hold"){
333
- const reason=decision.reason;
334
- const hold:PlacementHoldReason=reason==="secret"||reason==="personal-data"||reason==="deny-path"||reason==="private-or-invalid"||reason==="host"||reason==="person-local"?reason:"related-local";
335
- return{...base,kind,reason:hold};
336
- }
337
- const index=root.targets.findIndex(target=>sameRealm(target.realm,decision.key.realm));if(index<0)refuse();
338
- const outcome={attemptHash:root.seal,remoteHash:root.remoteHash,refHash:root.targets[index]!.refHash};
339
- if(kind==="publication-ambiguous")return{...base,kind,outcome};
340
- if(kind!=="publication-committed"||!commit)refuse();
341
- return{...base,kind,outcome:{...outcome,commit,proofHash:hashJSON({attempt:root.seal,key:decision.key,commit,remote:root.remoteHash,ref:root.targets[index]!.refHash})}};
342
- };
343
- for(const decision of decisions){
344
- const state=projection.get(decision.key);
345
- const index=root.targets.findIndex(target=>sameRealm(target.realm,decision.key.realm)),target=root.targets[index];if(!target)refuse();
346
- const original=old[index]?.rows.get(decision.key.id),published=original&&hashJSON(original)===decision.key.rowHash;
347
- if(decision.hold)holds.push(make(decision,"hold"));
348
- if(published&&state?.exposure!=="published"&&target.expectedRemoteHead)known.push(make(decision,"publication-committed",target.expectedRemoteHead));
349
- if(decision.eligible&&target.publish&&!published){
350
- ambiguous.push(make(decision,"publication-ambiguous"));committed.push(make(decision,"publication-committed",target.commit!));
351
- }
352
- }
353
- return{events:[...holds,...known,...ambiguous,...committed],preCount:holds.length+known.length+ambiguous.length,holdCount:holds.length};
488
+ return drainSteps(placementPublicationEventSteps(bundle,projection,old));
489
+ }
490
+ /** #470: the same schedule, awaiting the caller's event loop between decisions; the event order is identical. */
491
+ eventsAsync(bundle:PlacementPublicationBundle,projection:PlacementProjection,old:(ShardHistory|undefined)[],pause?:CooperativeYield):Promise<{events:PlacementEvent[];preCount:number;holdCount:number}>{
492
+ return drainStepsAsync(placementPublicationEventSteps(bundle,projection,old),pause);
354
493
  }
355
494
  async frozenOld(bundle:PlacementPublicationBundle):(Promise<(ShardHistory|undefined)[]>){
356
495
  const values:(ShardHistory|undefined)[]=[];
@@ -495,7 +634,7 @@ class PlacementTransport {
495
634
  target.rows = new Map(actual.rows); target.fetched = new Set(actual.rows.keys()); target.origins = new Map(actual.origins);
496
635
  } else { target.rows.clear(); target.fetched.clear(); target.candidate = emptyHistory(); }
497
636
  }
498
- this.preflight(false);this.enter("import");
637
+ await this.preflight(false);this.enter("import");
499
638
  const applications=await this.applicationCoordinator();await applications.prepare();
500
639
  for(const target of this.targets)for(const hold of target.holds)shardInstallHold(this.root,hold);
501
640
  await applications.install();
@@ -536,7 +675,7 @@ class PlacementTransport {
536
675
  const cause:SyncFailureCause|undefined=ok?undefined:this.opts.signal?.aborted?"stopped":this.bound?"bound":outcome==="unknown"?"unknown-outcome":this.failureCause??(this.refusal?"refusal":"unavailable");
537
676
  return{ok,pushed:this.accepted&&(this.attempted||this.recovered&&!!this.current?.bundle.root.targets.some(target=>target.publish)),entries:this.current?.exported??0,...(error?{error}:{}),
538
677
  ...(cause?{failure:{cause,...(cause==="refusal"&&this.refusal?{category:this.refusal}:{})}}:{}),...(this.applications?{pruneApplication:{...this.applications.application}}:{}),
539
- placementPublication:{...(this.attemptHash?{attemptHash:this.attemptHash}:{}),outcome,...(this.bound?{bound:this.bound}:{}),...(this.refusal?{refusal:{category:this.refusal,phase:this.phaseNow}}:{}),withheld:this.current?.withheld??0,exported:this.current?.exported??0,
678
+ placementPublication:{...(this.attemptHash?{attemptHash:this.attemptHash}:{}),outcome,...(this.bound?{bound:this.bound}:{}),...(this.journalObjects?{journalObjects:this.journalObjects}:{}),...(this.refusal?{refusal:{category:this.refusal,phase:this.phaseNow}}:{}),withheld:this.current?.withheld??0,exported:this.current?.exported??0,
540
679
  ...(this.lastPolicyHash?{lastPolicyHash:this.lastPolicyHash}:{}),...(this.lastPolicyCheckUnixMs!==undefined?{lastPolicyCheckUnixMs:this.lastPolicyCheckUnixMs,policyCheckSource:this.policyCheckSource??(this.recovered?"durable-intent" as const:"live" as const)}:{}),
541
680
  policyCeiling:"last-positive-check-before-in-flight-push",...(this.recovered?{recovered:true}:{})}};
542
681
  }
@@ -551,8 +690,16 @@ class PlacementTransport {
551
690
  }
552
691
  /** Object slots the plan and its reserved journal chunks need, checked before the first durable plan byte. */
553
692
  assertPlanCapacity(bundle:PlacementPublicationBundle):void{
554
- const objects=readPlacementPublicationMetadata(this.home,this.epochHash,io=>new Set([...io.names(),...publicationFileNames(bundle.root),...io.reservedJournalNames(bundle.root)]).size+1);
555
- if(objects>PLACEMENT_JOURNAL_MAX_OBJECTS)throw new PlacementSyncBoundError({phase:"publication-plan",kind:"journal-objects",limit:PLACEMENT_JOURNAL_MAX_OBJECTS,observed:objects});
693
+ // The refusal's own report (#288 step 1): the same inputs the count uses, split by what holds each object.
694
+ let composition:PlacementJournalObjectComposition|undefined;
695
+ const objects=readPlacementPublicationMetadata(this.home,this.epochHash,io=>{
696
+ const planned=publicationFileNames(bundle.root),reserved=io.reservedJournalNames(bundle.root),names=io.names();
697
+ composition=placementJournalObjectComposition({names:[...names,...planned,...reserved],plan:{root:bundle.root,reserved}});
698
+ return new Set([...names,...planned,...reserved]).size+1;
699
+ });
700
+ if(composition)this.journalObjects=composition;
701
+ if(objects>PLACEMENT_JOURNAL_MAX_OBJECTS)throw new PlacementSyncBoundError({phase:"publication-plan",kind:"journal-objects",limit:PLACEMENT_JOURNAL_MAX_OBJECTS,observed:objects},
702
+ composition&&placementJournalObjectCompositionText(composition));
556
703
  }
557
704
  async execute():Promise<SyncResult>{
558
705
  try{
@@ -572,7 +719,7 @@ class PlacementTransport {
572
719
  }
573
720
  }
574
721
  this.enter("source-capture");
575
- try { await yieldTurn();this.preflight();for(const target of this.targets)if(existsSync(join(target.store.dir,"local",`publisher-boundary-${this.machineId}.json`)))assertPublisherBoundary(target.store.profile,target.mutation!);await yieldTurn();await this.startCapture(); }
722
+ try { await yieldTurn();await this.preflight();for(const target of this.targets)if(existsSync(join(target.store.dir,"local",`publisher-boundary-${this.machineId}.json`)))assertPublisherBoundary(target.store.profile,target.mutation!);await yieldTurn();await this.startCapture(); }
576
723
  catch(error) { if(retained)return await this.terminalUnknown(retained);if(placementSyncBoundReceipt(error))throw error;throw new PlacementSyncRefusal(placementRefusalCategoryOf(error)??classifyPlacementError(error)??"other"); }
577
724
  if(retained){
578
725
  const root=retained.bundle.root;
@@ -610,13 +757,17 @@ class PlacementTransport {
610
757
  this.factual=true;return await this.finish(material);
611
758
  }catch(error){
612
759
  try { this.testOnlyError?.(error); } catch { /* Test observers never alter production results. */ }
760
+ // #288 step 3: a started checkpoint pauses every placement effect with its own cause and next step.
761
+ if(this.epochHash&&placementCheckpointPending(this.home,this.epochHash)){this.failureCause="checkpoint-pending";return this.result(false,this.attemptHash?"unknown":"not-needed",PLACEMENT_CHECKPOINT_PENDING_MESSAGE);}
613
762
  if(error&&typeof error==="object"&&!types.isProxy(error)&&error instanceof SharedWriterRevisionError){
614
763
  const code=Object.getOwnPropertyDescriptor(error,"code")?.value;
615
764
  if(code==="staging"||code==="pending"){this.failureCause="writer-renewal";return this.result(false,this.attemptHash?"unknown":"not-needed",new SharedWriterRevisionError(code).message);}
616
765
  }
617
766
  // #419: an expected size refusal before any attempt exists keeps its phase, kind, limit and observed value.
618
767
  const bound=this.attemptHash||this.journal?.publicationReservation?undefined:placementSyncBoundReceipt(error);
619
- if(bound){this.bound=bound;return this.result(false,"not-needed",placementSyncBoundMessage(bound));}
768
+ // #288 step 1: the bound's own numbers-only clause is rebuilt from the receipt for the receipt's fields, so the
769
+ // thrown error's detail is carried over explicitly; the result's error is what the person reads.
770
+ if(bound){this.bound=bound;const detail=placementSyncBoundDetail(error);return this.result(false,"not-needed",placementSyncBoundMessage(bound)+(detail?` ${detail}`:""));}
620
771
  if(this.attemptHash)return this.result(false,"unknown","Placement sync stopped with a retained attempt that may have published; recheck its exact receipts before another publication.");
621
772
  if (error && typeof error === "object" && !types.isProxy(error) && error instanceof PlacementRealmRefusal && error.origin === "remote") { this.failureCause = "remote"; return this.result(false, "not-needed", error.message); }
622
773
  // #426: name the failing check by a fixed category and the phase; never the error's own text, which may carry a path.
@@ -6,6 +6,9 @@ import { types } from "node:util";
6
6
  import { canonicalJSON } from "./generation.ts";
7
7
  import { homeIdentityMatches } from "./home-identity.ts";
8
8
  import { realPath } from "./platform.ts";
9
+ import { placementWindowToken, resolvePlacementWindow, type ResolvedPlacementWindow } from "./sync-placement-checkpoint-storage.ts";
10
+ import { checkpointWriterGenesis } from "./sync-placement-checkpoint-format.ts";
11
+ import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
9
12
  import { assertMutationHandle, type MutationHandle } from "./mutation.ts";
10
13
  import {
11
14
  WRITER_REVISION_MAX_BYTES, WRITER_COMMIT_MAX_BYTES, WRITER_RENEWAL_INTENT_MAX_BYTES, WRITER_REVISION_LIMIT,
@@ -19,7 +22,7 @@ export type WriterHistoryPhase = "intent-started" | "intent-written" | "intent-f
19
22
  export interface WriterHistoryOptions { mutation: MutationHandle; assertCurrent(): void; phase?(phase: WriterHistoryPhase): void }
20
23
  export interface WriterHistoryRead {
21
24
  current?: WriterRevision; commits: WriterCommit[]; anchors: { sequence: number; headHash: string }[];
22
- sequence: number; headHash: string; logBytes: number; logHash: string; pending?: WriterRenewalIntent; appendStarted: boolean; assertCurrent(): void;
25
+ sequence: number; headHash: string; window: number; genesis: string; logBytes: number; logHash: string; pending?: WriterRenewalIntent; appendStarted: boolean; assertCurrent(): void;
23
26
  }
24
27
  const encode = (value: unknown) => Buffer.from(canonicalJSON(value) + "\n");
25
28
  const sha = (value: Uint8Array) => createHash("sha256").update(value).digest("hex");
@@ -30,7 +33,7 @@ function safe<T>(work: () => T): T {
30
33
  try { return work(); } catch (error) {
31
34
  if (error && typeof error === "object" && !types.isProxy(error) && error instanceof SharedWriterRevisionError) {
32
35
  const code=Object.getOwnPropertyDescriptor(error,"code");
33
- if(code&&"value"in code&&["invalid","bound","changed","pending","staging","cap"].includes(code.value))throw new SharedWriterRevisionError(code.value);
36
+ if(code&&"value"in code&&["invalid","bound","changed","pending","checkpoint-pending","staging","cap"].includes(code.value))throw new SharedWriterRevisionError(code.value);
34
37
  }
35
38
  return fail();
36
39
  }
@@ -68,13 +71,49 @@ function binding(value: WriterHistoryBinding): WriterHistoryBinding {
68
71
  const locator=descriptors.initialLocatorHash;if(locator){if(!("value"in locator)||!locator.enumerable||typeof locator.value!=="string"||locator.value.length!==64||!/^[a-f0-9]+$/.test(locator.value))fail();result.initialLocatorHash=locator.value;}
69
72
  return result as unknown as WriterHistoryBinding;
70
73
  }
71
- interface Paths { home: string; epoch: string; intent: string; log: string; dirs: [string,BigIntStats][] }
74
+ interface Paths { home: string; epoch: string; intent: string; log: string; dirs: [string,BigIntStats][]; window: ResolvedPlacementWindow; genesis: string }
72
75
  function paths(homeInput: string, input: WriterHistoryBinding): Paths {
73
76
  const home=realPath(homeInput), original=checkedDir(homeInput), root=checkedDir(home);
74
77
  if(identity(original)!==identity(root)||!homeIdentityMatches(input.homeHash,home,root))fail("changed");
78
+ // #288: the one window resolver names the live window; window 0 is the v1 epoch directory.
79
+ let window:ResolvedPlacementWindow;try{window=resolvePlacementWindow(home,input.epochHash);}catch(error){throw checkpointError(error);}
80
+ if(window.pending)throw new SharedWriterRevisionError("checkpoint-pending"); // A started checkpoint owns the writer chain until resume or abandon.
75
81
  const dirs:[string,BigIntStats][]=[[home,root]];
76
- let current=home;for(const part of ["sync-placement","epochs",input.epochHash]){current=join(current,part);dirs.push([current,checkedDir(current)]);}
77
- return {home,epoch:current,intent:join(home,WRITER_RENEWAL_INTENT_FILE),log:join(current,WRITER_COMMIT_LOG),dirs};
82
+ for(const dir of [...window.parents.slice(1),window.dir])dirs.push([dir,checkedDir(dir)]);
83
+ const manifest=window.manifests.at(-1);
84
+ const genesis=manifest?checkpointWriterGenesis(input.epochHash,input.activationHash,manifest.seal,manifest.writer.headHash):writerInventoryGenesis(input.epochHash,input.activationHash);
85
+ return {home,epoch:window.dir,intent:join(home,WRITER_RENEWAL_INTENT_FILE),log:join(window.dir,WRITER_COMMIT_LOG),dirs,window,genesis};
86
+ }
87
+ /** A checkpoint pending or broken refuses writer history the same way the journal does: pending, else invalid. */
88
+ function checkpointError(error:unknown):SharedWriterRevisionError{
89
+ const code=error&&typeof error==="object"&&!types.isProxy(error)&&error instanceof SyncPlacementJournalError?Object.getOwnPropertyDescriptor(error,"code")?.value:undefined;
90
+ return new SharedWriterRevisionError(code==="pending"?"checkpoint-pending":code==="bound"?"bound":code==="changed"?"changed":"invalid");
91
+ }
92
+ interface ArchivedWriters { commits: WriterCommit[]; anchors: {sequence:number;headHash:string}[]; current?: WriterRevision }
93
+ /**
94
+ * Writer history of every frozen window, rechecked against each window's genesis and the manifest that froze it. Members
95
+ * were content-verified by the resolver; this only replays their chain. The logical chain continues across windows.
96
+ */
97
+ function archivedWriters(p:Paths,b:WriterHistoryBinding):ArchivedWriters {
98
+ const out:ArchivedWriters={commits:[],anchors:[]};let genesis=writerInventoryGenesis(b.epochHash,b.activationHash),previous=0;
99
+ for(const [index,window] of p.window.archived.entries()){
100
+ const manifest=p.window.manifests[index]!,names=new Set(window.members.map(member=>member.name));
101
+ let head=genesis,local=0;
102
+ if(names.has(WRITER_COMMIT_LOG)){
103
+ const log=read(join(window.dir,WRITER_COMMIT_LOG),WRITER_COMMIT_MAX_BYTES)?.bytes??fail();if(!log.length||log.at(-1)!==10)fail();
104
+ let at=0;while(at<log.length){const end=log.indexOf(10,at);const commit=decode(log.subarray(at,end+1),validateWriterCommit);at=end+1;
105
+ if(++local>WRITER_REVISION_LIMIT||commit.epochHash!==b.epochHash||commit.sequence!==local||commit.previousHash!==head)fail();
106
+ const revision=decode(read(join(window.dir,writerRevisionFile(local)),WRITER_REVISION_MAX_BYTES)?.bytes??fail(),value=>validateWriterRevision(value,genesis));boundRevision(revision,b);
107
+ if(revision.previousHash!==head||canonicalJSON(createWriterCommit(revision,genesis))!==canonicalJSON(commit))fail();
108
+ if(out.current&&revision.initialLocatorHash!==out.current.initialLocatorHash)fail();
109
+ if(revision.journal.sequence<previous)fail();previous=revision.journal.sequence;
110
+ out.anchors.push({...revision.journal});out.commits.push(commit);out.current=revision;head=commit.seal;}
111
+ }
112
+ for(const name of names)if(name.startsWith("writer-")&&name!==WRITER_COMMIT_LOG&&!(/^writer-revision-(\d{5})\.json$/.test(name)&&Number(name.slice(16,21))<=local))fail();
113
+ if(manifest.writer.headHash!==head||manifest.writer.sequence!==out.commits.length)fail();
114
+ genesis=checkpointWriterGenesis(b.epochHash,b.activationHash,manifest.seal,head);
115
+ }
116
+ return out;
78
117
  }
79
118
  function manifest(p: Paths): string[] {
80
119
  const iterator=opendirSync(p.epoch), names:string[]=[]; let count=0;
@@ -86,8 +125,17 @@ function boundRevision(revision: WriterRevision,b:WriterHistoryBinding):void {
86
125
  if(revision.epochHash!==b.epochHash||revision.activationHash!==b.activationHash||revision.homeHash!==b.homeHash||revision.generation!==b.generation||b.initialLocatorHash!==undefined&&revision.initialLocatorHash!==b.initialLocatorHash)fail();
87
126
  }
88
127
  function intentBinding(intent:WriterRenewalIntent):WriterHistoryBinding {const r=intent.revision;return {epochHash:r.epochHash,activationHash:r.activationHash,homeHash:r.homeHash,generation:r.generation};}
128
+ /**
129
+ * #288: a window's first revision starts at that window's genesis, which only the resolver knows. Codec validation here
130
+ * accepts the revision's own first link; every snapshot then requires it to equal the live window's genesis (beforeHead).
131
+ */
132
+ function intentCodec(value:unknown):WriterRenewalIntent {
133
+ let genesis:string|undefined;
134
+ try{const revision=(value as {revision?:{sequence?:unknown;previousHash?:unknown}}).revision;if(revision?.sequence===1&&typeof revision.previousHash==="string")genesis=revision.previousHash;}catch{fail();}
135
+ return validateWriterRenewalIntent(value,genesis);
136
+ }
89
137
  /** Exact basename reserved alongside the final outside intent during atomic publication. */
90
- export function writerRenewalIntentTempName(value:WriterRenewalIntent):string {return WRITER_RENEWAL_INTENT_FILE+".pending-"+sha(encode(validateWriterRenewalIntent(value)));}
138
+ export function writerRenewalIntentTempName(value:WriterRenewalIntent):string {return WRITER_RENEWAL_INTENT_FILE+".pending-"+sha(encode(intentCodec(value)));}
91
139
  export function isWriterRenewalIntentTempName(name:string):boolean {const match=new RegExp("^"+WRITER_RENEWAL_INTENT_FILE.replaceAll(".","\\.")+"\\.pending-[a-f0-9]{64}$").exec(name);return !!match&&match[0]===name;}
92
140
  function intentTemps(p:Paths):string[]{
93
141
  const iterator=opendirSync(p.home),out:string[]=[];let count=0,bytes=0;
@@ -105,7 +153,7 @@ function readIntent(p:Paths,checks:(()=>void)[],expected?:WriterRenewalIntent,ig
105
153
  const file=final??staging!;
106
154
  let intent:WriterRenewalIntent;
107
155
  if(expected){const full=encode(expected);if(file.bytes.length>full.length||!file.bytes.equals(full.subarray(0,file.bytes.length)))fail();intent=expected;}
108
- else {try{intent=decode(file.bytes,validateWriterRenewalIntent);}catch{fail("pending");}}
156
+ else {try{intent=decode(file.bytes,intentCodec);}catch{fail("pending");}}
109
157
  const full=encode(intent),known=join(p.home,writerRenewalIntentTempName(intent));if(temp&&temp!==known)fail();
110
158
  if(final){if(!final.bytes.equals(full))fail();if(staging){if(final.stat.nlink!==2n||staging.stat.nlink!==2n||stamp(final.stat)!==stamp(staging.stat)||!staging.bytes.equals(full))fail();}else if(final.stat.nlink!==1n)fail();}
111
159
  else if(staging!.stat.nlink!==1n)fail();
@@ -128,31 +176,38 @@ interface Snapshot { result:WriterHistoryRead; paths:Paths; log:Buffer; intentBy
128
176
  function snapshot(home:string,b:WriterHistoryBinding,allowPending:boolean,expected?:WriterRenewalIntent,ignoreUnpublishedStaging=false):Snapshot {
129
177
  const p=paths(home,b), checks:(()=>void)[]=[], names=manifest(p);
130
178
  for(const [dir,stat]of p.dirs)checks.push(()=>{if(identity(checkedDir(dir))!==identity(stat))fail("changed");});
179
+ // A checkpoint that starts, commits or abandons between two reads leaves the old window's files untouched; its token does not.
180
+ checks.push(()=>{let token:string;try{token=placementWindowToken(p.home,b.epochHash);}catch{fail("changed");}if(token!==p.window.token)fail("changed");});
131
181
  checks.push(()=>{if(canonicalJSON(manifest(p))!==canonicalJSON(names))fail("changed");});
132
182
  const intentRead=readIntent(p,checks,expected,ignoreUnpublishedStaging),intentFile=intentRead.file;let pending=intentRead.intent;
133
183
  if(pending){if(!allowPending)fail("pending");if(pending.home!==p.home)fail();boundRevision(pending.revision,b);}
134
184
  else if(expected)fail("pending");
135
185
  const logFile=read(p.log,WRITER_COMMIT_MAX_BYTES,checks), log=logFile?.bytes??Buffer.alloc(0);
136
186
  const commits:WriterCommit[]=[],anchors:{sequence:number;headHash:string}[]=[];let current:WriterRevision|undefined;
137
- let head=writerInventoryGenesis(b.epochHash,b.activationHash),previous=0,completeBytes=log.length;
187
+ // #288: the live window's local chain starts at its own genesis; archived windows come first in the logical chain.
188
+ const archived=archivedWriters(p,b);current=archived.current;
189
+ let head=p.genesis,previous=archived.anchors.at(-1)?.sequence??0,completeBytes=log.length;
138
190
  const lastLF=log.lastIndexOf(10);if(lastLF!==log.length-1){if(!pending)fail("pending");completeBytes=lastLF+1;}
139
191
  let at=0;
140
192
  while(at<completeBytes){const end=log.indexOf(10,at);if(end<at)fail();const commit=decode(log.subarray(at,end+1),validateWriterCommit);at=end+1;
141
193
  if(commits.length>=WRITER_REVISION_LIMIT)fail("bound");if(commit.epochHash!==b.epochHash||commit.sequence!==commits.length+1||commit.previousHash!==head)fail();
142
194
  const file=join(p.epoch,writerRevisionFile(commit.sequence)),raw=read(file,WRITER_REVISION_MAX_BYTES,checks);if(!raw)fail();
143
- const revision=decode(raw.bytes,validateWriterRevision);boundRevision(revision,b);
144
- if(revision.sequence!==commit.sequence||revision.previousHash!==head||canonicalJSON(createWriterCommit(revision))!==canonicalJSON(commit))fail();
195
+ const revision=decode(raw.bytes,value=>validateWriterRevision(value,p.genesis));boundRevision(revision,b);
196
+ if(revision.sequence!==commit.sequence||revision.previousHash!==head||canonicalJSON(createWriterCommit(revision,p.genesis))!==canonicalJSON(commit))fail();
145
197
  if(current&&revision.initialLocatorHash!==current.initialLocatorHash)fail();
146
- if(revision.journal.sequence<previous||revision.journal.sequence===previous&&anchors.length&&revision.journal.headHash!==anchors.at(-1)!.headHash)fail();
198
+ const prior=anchors.at(-1)??archived.anchors.at(-1);
199
+ if(revision.journal.sequence<previous||revision.journal.sequence===previous&&prior&&revision.journal.headHash!==prior.headHash)fail();
147
200
  anchors.push({...revision.journal});previous=revision.journal.sequence;commits.push(commit);current=revision;head=commit.seal;
148
201
  }
202
+ // A committed checkpoint always carries its (W, 1) renewal, so a later live window is never empty.
203
+ if(p.window.window&&!commits.length)fail();
149
204
  const expectedNames=new Set(commits.map(commit=>writerRevisionFile(commit.sequence)));if(logFile)expectedNames.add(WRITER_COMMIT_LOG);
150
205
  if(pending){
151
206
  const start=pending.previousLogBytes, next=pending.revision.sequence;
152
207
  if(start>log.length||sha(log.subarray(0,start))!==pending.previousLogHash||start>0&&log[start-1]!==10)fail();
153
208
  const beforeCount=commits.filter(commit=>commit.sequence<next).length;
154
209
  if(beforeCount!==next-1||commits.length<next-1||commits.length>next)fail();
155
- const beforeHead=next===1?writerInventoryGenesis(b.epochHash,b.activationHash):commits[next-2]!.seal;
210
+ const beforeHead=next===1?p.genesis:commits[next-2]!.seal;
156
211
  if(pending.revision.previousHash!==beforeHead||start!==committedPrefixLength(log,next-1))fail();
157
212
  const tail=log.subarray(start),line=encode(pending.commit);if(tail.length>line.length||!tail.equals(line.subarray(0,tail.length)))fail();
158
213
  const candidateFile=join(p.epoch,writerRevisionFile(next)),candidate=read(candidateFile,WRITER_REVISION_MAX_BYTES,checks),full=encode(pending.revision);
@@ -163,7 +218,10 @@ function snapshot(home:string,b:WriterHistoryBinding,allowPending:boolean,expect
163
218
  }else if(completeBytes!==log.length||logFile&&commits.length===0)fail("pending");
164
219
  if(canonicalJSON([...expectedNames].sort())!==canonicalJSON(names))fail();
165
220
  const assertCurrent=()=>safe(()=>{for(const check of checks)check();});assertCurrent();
166
- return{paths:p,log,intentBytes:intentFile?.bytes,result:{current,commits,anchors,sequence:commits.length,headHash:head,logBytes:log.length,logHash:sha(log),pending,appendStarted:!!pending&&log.length>pending.previousLogBytes,assertCurrent}};
221
+ // `sequence`, `headHash` and the log describe the live window (what a renewal appends to); `commits` and `anchors` are the
222
+ // whole logical chain across windows, so every head a realm record or capture ever bound stays resolvable.
223
+ return{paths:p,log,intentBytes:intentFile?.bytes,result:{current,commits:[...archived.commits,...commits],anchors:[...archived.anchors,...anchors],sequence:commits.length,headHash:head,
224
+ window:p.window.window,genesis:p.genesis,logBytes:log.length,logHash:sha(log),pending,appendStarted:!!pending&&log.length>pending.previousLogBytes,assertCurrent}};
167
225
  }
168
226
  function committedPrefixLength(log:Buffer,count:number):number {let at=0;for(let n=0;n<count;n++){const lf=log.indexOf(10,at);if(lf<0)fail();at=lf+1;}return at;}
169
227
  export function readWriterHistory(home:string,input:WriterHistoryBinding,options:{allowPending?:boolean}={}):WriterHistoryRead {
@@ -190,12 +248,12 @@ function complete(p:Paths,file:string,full:Buffer,max:number,opts:WriterHistoryO
190
248
  }finally{closeSync(fd);}syncDir(p,dirname(file),opts);proof(p,opts);if(stamp(lstatSync(file,{bigint:true}))!==stamp(installed!))fail("changed");
191
249
  }
192
250
  function checkedIntent(home:string,value:WriterRenewalIntent,opts:WriterHistoryOptions):{intent:WriterRenewalIntent;snapshot:Snapshot}{
193
- const intent=validateWriterRenewalIntent(value),b=intentBinding(intent),p=paths(home,b);proof(p,opts);
251
+ const intent=intentCodec(value),b=intentBinding(intent),p=paths(home,b);proof(p,opts);
194
252
  const read=snapshot(home,b,true,intent);if(!read.intentBytes)fail("pending");return{intent,snapshot:read};
195
253
  }
196
254
  export function writeWriterRenewalIntent(home:string,value:WriterRenewalIntent,opts:WriterHistoryOptions):void {
197
255
  safe(()=>{
198
- const intent=validateWriterRenewalIntent(value),b=intentBinding(intent),p=paths(home,b);if(intent.home!==p.home)fail();
256
+ const intent=intentCodec(value),b=intentBinding(intent),p=paths(home,b);if(intent.home!==p.home)fail();
199
257
  if(intent.previousLogBytes+encode(intent.commit).length>WRITER_COMMIT_MAX_BYTES)fail("bound");proof(p,opts);
200
258
  const prior=readIntent(p,[],intent).file;
201
259
  const old=prior?snapshot(home,b,true,intent):snapshot(home,b,false);
@@ -217,7 +275,7 @@ export function appendWriterCommit(home:string,value:WriterRenewalIntent,opts:Wr
217
275
  complete(read.paths,read.paths.log,full,WRITER_COMMIT_MAX_BYTES,opts,"commit-written","commit-fsync",{at:intent.previousLogBytes,phase:"commit-started"});snapshot(home,intentBinding(intent),true).result.assertCurrent();});
218
276
  }
219
277
  export function clearWriterRenewalIntent(home:string,value:WriterRenewalIntent,opts:WriterHistoryOptions):void {
220
- safe(()=>{const intent=validateWriterRenewalIntent(value),p=paths(home,intentBinding(intent));proof(p,opts);
278
+ safe(()=>{const intent=intentCodec(value),p=paths(home,intentBinding(intent));proof(p,opts);
221
279
  const prior=readIntent(p,[],intent).file;
222
280
  if(prior){const read=snapshot(home,intentBinding(intent),true,intent);if(!prior.bytes.equals(encode(intent))||read.result.headHash!==intent.commit.seal||read.log.length!==intent.previousLogBytes+encode(intent.commit).length)fail("pending");
223
281
  appendWriterCommit(home,intent,opts);proof(p,opts);const now=readFileExpected(p.intent,encode(intent),WRITER_RENEWAL_INTENT_MAX_BYTES);proof(p,opts);if(stamp(lstatSync(p.intent,{bigint:true}))!==stamp(now.stat))fail("changed");unlinkSync(p.intent);opts.phase?.("intent-cleared");}
@@ -226,7 +284,7 @@ export function clearWriterRenewalIntent(home:string,value:WriterRenewalIntent,o
226
284
  }
227
285
  function readFileExpected(file:string,full:Buffer,max:number):FileRead {const value=read(file,max);if(!value||!value.bytes.equals(full))fail();return value;}
228
286
  export function abandonWriterRenewal(home:string,value:WriterRenewalIntent,opts:WriterHistoryOptions):void {
229
- safe(()=>{const intent=validateWriterRenewalIntent(value),p=paths(home,intentBinding(intent));proof(p,opts);
287
+ safe(()=>{const intent=intentCodec(value),p=paths(home,intentBinding(intent));proof(p,opts);
230
288
  if(!readIntent(p,[],intent).file){
231
289
  const cleared=snapshot(home,intentBinding(intent),false);
232
290
  if(cleared.result.sequence!==intent.revision.sequence-1||cleared.result.headHash!==intent.revision.previousHash||cleared.result.logBytes!==intent.previousLogBytes||cleared.result.logHash!==intent.previousLogHash)fail("changed");