@staix/agent-mem 0.26.2 → 0.27.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.
@@ -17,11 +17,11 @@ import { SharedWriterRevisionError } from "./sync-placement-writer-revision-form
17
17
  import { types } from "node:util";
18
18
  import type { PlannedGitObject } from "./sync-placement-git.ts";
19
19
  import { PLACEMENT_FORMAT } from "./sync-placement-format.ts";
20
- import { createPlacementRecord, placementKeyId, type PlacementEvent, type PlacementRealm, type PlacementHoldReason, type PlacementRecord } from "./sync-placement-journal-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";
21
21
  import { rebuildPlacementProjection, type PlacementProjection } from "./sync-placement-projection.ts";
22
- import { readPlacementJournal, appendPlacementEvent, ensurePlacementPublicationDurability, type PlacementJournalRead, type PlacementStorageOptions } from "./sync-placement-journal-storage.ts";
22
+ import { readPlacementJournal, appendPlacementEvent, releasePlacementStorageCaches, ensurePlacementPublicationDurability, readPlacementPublicationMetadata, type PlacementJournalRead, type PlacementStorageOptions } from "./sync-placement-journal-storage.ts";
23
23
  import { preparePlacementPublication, readPlacementPublication, recordPlacementPublicationPhase, type PlacementPublicationRead } from "./sync-placement-publication-storage.ts";
24
- import { planPlacementPublication, publicationBytes, type PlacementPublicationBundle, type PlacementPublicationDecision, type PlacementPublicationObject } from "./sync-placement-publication-plan.ts";
24
+ import { planPlacementPublication, publicationBytes, publicationFileNames, type PlacementPublicationBundle, type PlacementPublicationDecision, type PlacementPublicationObject } from "./sync-placement-publication-plan.ts";
25
25
  import { ShardHistoryAuditor, type ShardHistory } from "./shard-sync-history.ts";
26
26
  import { ShardSyncApplications } from "./shard-sync-applications.ts";
27
27
  import { shardSourceRows, shardProvePrunes, shardImportRows, shardSelectorRetention, shardInstallHold, shardHoldWarning, type ShardSyncApplicationTarget } from "./shard-sync.ts";
@@ -31,6 +31,18 @@ import type { MemoryStore } from "./store.ts";
31
31
  import type { PruneRow } from "./prune.ts";
32
32
  import { materializePlacementRows, verifiedPlacementPrunes } from "./sync-placement-materialize.ts";
33
33
  import { placementCacheConfigStamp, placementCacheRootStamp, validatePlacementCacheConfig } from "./sync-placement-cache.ts";
34
+ import { PlacementSyncBoundError, placementSyncBoundMessage, placementSyncBoundReceipt, type PlacementSyncBound } from "./sync-placement-bound.ts";
35
+ import type { SyncProgress, SyncProgressPhase } from "./sync-progress.ts";
36
+ import { PlacementSyncRefusal, placementRefusalCategoryOf, placementRefusalMessage, type PlacementRefusalCategory } from "./sync-placement-refusal.ts";
37
+ import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
38
+
39
+ /**
40
+ * #417 proof scope. A complete proof (full writer-install measurement, source, policy and selector recheck) is taken
41
+ * at every effect boundary (`prove`) and may be reused by the fence checks in between (`check`) for at most this long.
42
+ * Every check still verifies mutation ownership, the active epoch, writer revisions, the cache identity and
43
+ * selectors, so a change that persists is refused at the next boundary before publication or import. Not configurable.
44
+ */
45
+ export const PLACEMENT_PROOF_REUSE_MS = 1000;
34
46
 
35
47
  export type PlacementSyncPhase = "before-plan-fsync" | "plan-fsynced" | "artifact-built" | "before-cas" | "cas-returned" | "before-ack" | "acknowledged" | "imported" | "before-receipt" | "receipt-written";
36
48
  type Phase = (phase: PlacementSyncPhase) => void | Promise<void>;
@@ -40,12 +52,23 @@ const digest = (v: Uint8Array | string) => createHash("sha256").update(v).digest
40
52
  const oid = (v: unknown): v is string => typeof v === "string" && v.length === 40 && /^[a-f0-9]+$/.test(v);
41
53
  const sameRealm = (a: PlacementRealm, b: PlacementRealm) => canonicalJSON(a) === canonicalJSON(b);
42
54
  const physical = (target: Target): PlacementRealm => target.realm.scope === "user" ? { scope: "user" } : { scope: "project", keyHash: digest(target.realm.key) };
43
- function refuse(): never { throw new Error("placement sync unavailable"); }
55
+ function refuse(category: PlacementRefusalCategory = "other"): never { throw new PlacementSyncRefusal(category); }
56
+ /** #426: map a foreign error to a category by its class and allowlisted code only, never by its message text. */
57
+ export function classifyPlacementError(error: unknown): PlacementRefusalCategory | undefined {
58
+ try {
59
+ if (!error || typeof error !== "object" || types.isProxy(error)) return undefined;
60
+ if (error instanceof SharedWriterRevisionError) return "writer-pin";
61
+ if (error instanceof SyncPlacementJournalError) { const code = Object.getOwnPropertyDescriptor(error, "code")?.value; return code === "bound" ? "size-bound" : code === "changed" ? "source-selection" : "epoch"; }
62
+ const code = Object.getOwnPropertyDescriptor(error, "code")?.value;
63
+ if (code === "EBUSY" || code === "SQLITE_BUSY" || code === "EAGAIN") return "lock";
64
+ return undefined;
65
+ } catch { return undefined; }
66
+ }
44
67
  function directory(file: string): void { const s = lstatSync(file); if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== process.getuid?.() || (s.mode & 0o077) !== 0) refuse(); }
45
68
  function emptyHistory(): ShardHistory { return { rows: new Map(), files: new Map(), origins: new Map(), manifests: new Map(), version: "v3" }; }
46
69
  /** Internal phase observer is a fault seam, not part of SyncOptions or the package barrel. */
47
- export async function syncPlacementMemory(store: MemoryStore, opts: SyncOptions = {}, phase?: Phase, testOnlyError?: (error:unknown)=>void): Promise<SyncResult> {
48
- return new PlacementTransport(store, opts, phase, testOnlyError).run();
70
+ export async function syncPlacementMemory(store: MemoryStore, opts: SyncOptions = {}, phase?: Phase, testOnlyError?: (error:unknown)=>void, testOnlyClock?: () => number): Promise<SyncResult> {
71
+ return new PlacementTransport(store, opts, phase, testOnlyError, testOnlyClock).run();
49
72
  }
50
73
  class PlacementTransport {
51
74
  readonly store: MemoryStore; readonly opts: SyncOptions; readonly phase?: Phase; readonly testOnlyError?: (error:unknown)=>void; readonly home: string; readonly root: string; readonly cache: string;
@@ -55,13 +78,14 @@ class PlacementTransport {
55
78
  machineId = ""; url = ""; revision = ""; accepted = false; factual = false; attempted = false; lastPolicyCheckUnixMs?: number; lastPolicyHash?: string; policyCheckSource?: "live"|"durable-intent"; attemptHash?: string;
56
79
  evaluator?: ReturnType<typeof outboundPolicyEvaluator>; applications?: ShardSyncApplications; current?: Materialized; recovered = false;
57
80
  writerInventory?:EffectiveSyncPlacementWriters;
58
- constructor(store: MemoryStore, opts: SyncOptions, phase?: Phase, testOnlyError?: (error:unknown)=>void) { 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"); }
81
+ readonly clock: () => number; readonly progress?: SyncProgress; provedAt?: number; bound?: PlacementSyncBound; capturedPolicyVersion?: string;
82
+ constructor(store: MemoryStore, opts: SyncOptions, phase?: Phase, testOnlyError?: (error:unknown)=>void, clock: () => number = () => performance.now()) { 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"); }
59
83
  attest(): void {
60
- if (!this.opts.placementAttestation || this.opts.screen && !this.opts.policyVersion) refuse();
84
+ if (!this.opts.placementAttestation || this.opts.screen && !this.opts.policyVersion) refuse("policy");
61
85
  const value = memoryPolicySnapshot(this.opts.placementAttestation());
62
- if (!value || value.legacySyncQuiesced !== true || !Array.isArray(value.writers)) refuse();
86
+ if (!value || value.legacySyncQuiesced !== true || !Array.isArray(value.writers)) refuse("writer-pin");
63
87
  const writers = [...value.writers].sort((a,b) => a.writerId.localeCompare(b.writerId));
64
- if(!this.writerInventory||canonicalJSON(writers)!==canonicalJSON(this.writerInventory.writers))refuse();
88
+ if(!this.writerInventory||canonicalJSON(writers)!==canonicalJSON(this.writerInventory.writers))refuse("writer-pin");
65
89
  this.writerInventory.assertCurrent();
66
90
  }
67
91
  metadata(): void {
@@ -75,20 +99,35 @@ class PlacementTransport {
75
99
  if (this.homeMutation) assertMutationHandle(this.homeMutation, this.home);
76
100
  for (const target of this.targets) if (target.mutation) assertMutationHandle(target.mutation, target.store.dir);
77
101
  const markers = readPlacementRuntimeMarkers(this.home), active = readActivePlacementBinding(this.home, markers.profile, markers.shards);
78
- if (!active || active.profile.placementHead !== this.epochHash || active.epoch.homeHash !== this.journal.epoch.homeHash) refuse();
102
+ if (!active || active.profile.placementHead !== this.epochHash || active.epoch.homeHash !== this.journal.epoch.homeHash) refuse("epoch");
79
103
  }
80
- check = (): void => {
104
+ verify(fresh: boolean): void {
81
105
  this.metadata();
82
- if (this.factual) return;
83
- if (this.opts.signal?.aborted) refuse(); this.attest(); this.capture?.assertUnchanged();
84
- if(this.capture){this.lastPolicyHash=this.capture.context.policyHash;this.lastPolicyCheckUnixMs=Date.now();this.policyCheckSource="live";}
106
+ if (this.factual) { this.progress?.alive(); return; }
107
+ if (this.opts.signal?.aborted) refuse();
108
+ const complete = fresh || this.provedAt === undefined || this.clock() - this.provedAt >= PLACEMENT_PROOF_REUSE_MS;
109
+ if (complete) {
110
+ this.provedAt = undefined; this.attest(); this.capture?.assertUnchanged(); this.provedAt = this.clock();
111
+ if(this.capture){this.lastPolicyHash=this.capture.context.policyHash;this.lastPolicyCheckUnixMs=Date.now();this.policyCheckSource="live";}
112
+ }
113
+ // The host policy version is a cheap callback: compare it on every check, not only on complete proofs.
114
+ if (!complete && this.capture && this.opts.policyVersion && this.opts.policyVersion() !== this.capturedPolicyVersion) refuse("policy");
115
+ this.progress?.proof(complete);
85
116
  for (const target of this.targets) for (const check of target.selectorChecks ?? []) check();
86
117
  this.metadata();
87
- };
118
+ }
119
+ /** Fence check inside a proof scope: reuses a complete proof no older than PLACEMENT_PROOF_REUSE_MS. */
120
+ check = (): void => this.verify(false);
121
+ /** Effect boundary: always a fresh complete proof. */
122
+ prove(): void { this.verify(true); }
88
123
  async call<T>(work: () => T | Promise<T>): Promise<T> { this.check(); const result = await work(); this.check(); return result; }
89
124
  args(args: string[]): string[] { return ["--no-replace-objects", "--git-dir", this.cache, "-c", "maintenance.auto=false", "-c", "gc.auto=0", "-c", "core.commitGraph=false", ...args]; }
90
125
  async git(args: string[]) { return this.call(() => generationSyncGit(this.root, this.args(args), this.opts.signal)); }
91
126
  async required(args: string[]): Promise<string> { const result = await this.git(args); if (result.code !== 0) refuse(); return result.out; }
127
+ /** #426: the progress phase this run is in, kept even without a progress reporter so a refusal can name it. */
128
+ phaseNow: SyncProgressPhase = "writer-verification";
129
+ enter(...args: Parameters<SyncProgress["phase"]>): void { this.phaseNow = args[0]; this.progress?.phase(...args); }
130
+ refusal?: PlacementRefusalCategory;
92
131
  async observe(phase: PlacementSyncPhase): Promise<void> { await this.phase?.(phase); }
93
132
  storage(factual = false): PlacementStorageOptions { if (!this.homeMutation) refuse(); return { mutation: this.homeMutation, assertCurrent: factual ? () => this.metadata() : this.check, ...(this.attemptHash ? { publicationAttemptHash: this.attemptHash } : {}) }; }
94
133
  configStamp():string {
@@ -111,30 +150,31 @@ class PlacementTransport {
111
150
  }
112
151
  async initialize(): Promise<void> {
113
152
  const markers = readPlacementRuntimeMarkers(this.home), active = readActivePlacementBinding(this.home, markers.profile, markers.shards);
114
- if (!active || this.store.profile.publicationFormat !== PLACEMENT_FORMAT || this.store.profile.placementHead !== active.profile.placementHead) refuse();
153
+ if (!active || this.store.profile.publicationFormat !== PLACEMENT_FORMAT || this.store.profile.placementHead !== active.profile.placementHead) refuse("epoch");
115
154
  this.epochHash = active.profile.placementHead; this.machineId = active.shards.machine.id; this.revision = readSelector(this.home).revision; this.journal = readPlacementJournal(this.home, this.epochHash); this.writerInventory=readEffectiveSyncPlacementWriters(this.home);this.attest();
116
155
  const opened = this.store.openedSyncTargets();
117
156
  if (!opened.length || opened.length > 2 || !opened.includes(this.store) || opened.some(item => item.profile.home !== this.home || !item.profile.sharded || !item.profile.generation
118
- || !item.profile.shardUser && item.profile.shardKey !== this.store.profile.shardKey)) refuse();
157
+ || !item.profile.shardUser && item.profile.shardKey !== this.store.profile.shardKey)) refuse("source-selection");
119
158
  for (const item of opened) {
120
159
  const realm = item.profile.shardUser ? { scope: "user" as const } : { scope: "project" as const, key: item.profile.shardKey! };
121
160
  const target = { store: item, realm, generation: item.profile.generation!, rows: new Map(), fetched: new Set(), sources: [], pending: [], origins: new Map(), holds: [], manifests: new Map(), eligible: new Set(), registered: [], objects: [], localPrunes: new Map() } as unknown as Target;
122
161
  target.auditor = new ShardHistoryAuditor({ realm, generation: target.generation, placement: true, publicPrune: true,
123
162
  git: args => this.required(args), blob: (object, path) => this.blob(object, path), object: (oid,type) => this.rawHistoryObject(oid,type) }); this.targets.push(target);
124
163
  }
125
- if (new Set(this.targets.map(target => shardSyncRef(target.realm))).size !== this.targets.length) refuse();
126
- if (this.targets.some(target => target.realm.scope === "project" && isLocalKey(target.realm.key)) && this.opts.remote === undefined) refuse();
164
+ if (new Set(this.targets.map(target => shardSyncRef(target.realm))).size !== this.targets.length) refuse("source-selection");
165
+ if (this.targets.some(target => target.realm.scope === "project" && isLocalKey(target.realm.key)) && this.opts.remote === undefined) refuse("remote");
127
166
  if (existsSync(this.root)) placementCacheRootStamp(this.home);
128
167
  const existing = existsSync(this.root) ? await this.independent() : false;
129
- if (!existing && !this.opts.remote) refuse();
168
+ if (!existing && !this.opts.remote) refuse("remote");
130
169
  this.url = this.opts.remote ?? await this.required(["remote", "get-url", "origin"]);
131
- if (!this.url || this.url.length > 4096 || this.url.startsWith("-") || /[\r\n\0]/.test(this.url)) refuse();
132
- if (await this.call(() => (this.opts.visibility ?? remoteVisibility)(this.url)) !== "private") refuse();
170
+ if (!this.url || this.url.length > 4096 || this.url.startsWith("-") || /[\r\n\0]/.test(this.url)) refuse("remote");
171
+ if (await this.call(() => (this.opts.visibility ?? remoteVisibility)(this.url)) !== "private") refuse("remote");
172
+ this.prove(); // a host callout ends any reusable proof
133
173
  if (!existsSync(this.root)) mkdirSync(this.root, { mode: 0o700 });
134
- const transport = acquireMutation(this.root); if (!transport) refuse(); this.rootMutation=transport; this.releases.push(transport);
135
- const sync = generationSyncLock(this.root); if (!sync) refuse(); this.releases.push(sync);
174
+ const transport = acquireMutation(this.root); if (!transport) refuse("lock"); this.rootMutation=transport; this.releases.push(transport);
175
+ const sync = generationSyncLock(this.root); if (!sync) refuse("lock"); this.releases.push(sync);
136
176
  for (const dir of [...new Set([this.home, ...this.targets.map(target => target.store.dir)])].sort()) {
137
- const handle = acquireMutation(dir); if (!handle) refuse(); this.releases.push(handle); if (dir === this.home) this.homeMutation = handle;
177
+ const handle = acquireMutation(dir); if (!handle) refuse("lock"); this.releases.push(handle); if (dir === this.home) this.homeMutation = handle;
138
178
  for (const target of this.targets) if (target.store.dir === dir) target.mutation = handle;
139
179
  }
140
180
  this.releaseCurated = this.store.beginCuratedCacheUpdate();
@@ -145,24 +185,24 @@ class PlacementTransport {
145
185
  if (this.opts.remote) { this.cacheConfigIdentity=undefined; await this.required(previous.code === 0 ? ["remote", "set-url", "origin", this.url] : ["remote", "add", "origin", this.url]); }
146
186
  await this.bindCacheConfig();
147
187
  for (const args of [["remote", "get-url", "--all", "origin"], ["remote", "get-url", "--push", "--all", "origin"]])
148
- if (await this.required(args) !== this.url) refuse();
188
+ if (await this.required(args) !== this.url) refuse("remote");
149
189
  const reservation = this.journal.publicationReservation;
150
190
  const pending = reservation ? readPlacementPublication(this.home, this.epochHash, reservation.attemptHash) : undefined;
151
- if (!pending || pending.bundle.root.remoteHash === digest(this.url)) await this.fetch();
191
+ if (!pending || pending.bundle.root.remoteHash === digest(this.url)) { this.enter("remote-verification"); await this.fetch(); }
152
192
  }
153
193
  async rawHistoryObject(object:string,type:"commit"|"tree"):Promise<Buffer>{
154
- if(!oid(object)||await this.required(["cat-file","-t",object])!==type)refuse();
155
- const limit=type==="commit"?65536:SHARD_PACK_MAX_BYTES,size=Number(await this.required(["cat-file","-s",object]));
156
- if(!Number.isSafeInteger(size)||size<0||size>limit)refuse();
194
+ // One process per object (#420): the typed SHA-1 below proves type, size and bytes, so no -t/-s preflight is needed.
195
+ if(!oid(object))refuse();
196
+ const limit=type==="commit"?65536:SHARD_PACK_MAX_BYTES;
157
197
  const result=await this.call(()=>generationSyncGitBytes(this.root,this.args(["cat-file",type,object]),this.opts.signal,undefined,limit));
158
- if(result.code!==0||result.out.length!==size||createHash("sha1").update(`${type} ${size}\0`).update(result.out).digest("hex")!==object)refuse();
198
+ if(result.code!==0||createHash("sha1").update(`${type} ${result.out.length}\0`).update(result.out).digest("hex")!==object)refuse();
159
199
  return Buffer.from(result.out);
160
200
  }
161
201
  async blob(object: string, path: string): Promise<Buffer> {
162
202
  const limit = path === "shard.json" || path.startsWith("prune-witnesses/") ? 65536 : SHARD_PACK_MAX_BYTES;
163
- const size = Number(await this.required(["cat-file", "-s", object])); if (!Number.isSafeInteger(size) || size < 1 || size > limit) refuse();
203
+ // The auditor proves the blob SHA-1; the output bound refuses an oversized object (#420).
164
204
  const result = await this.call(() => generationSyncGitBytes(this.root, this.args(["cat-file", "blob", object]), this.opts.signal, undefined, limit));
165
- if (result.code !== 0 || result.out.length !== size) refuse(); return Buffer.from(result.out);
205
+ if (result.code !== 0 || result.out.length < 1) refuse(); return Buffer.from(result.out);
166
206
  }
167
207
  async fetch(): Promise<void> {
168
208
  for (const target of this.targets) {
@@ -192,11 +232,12 @@ class PlacementTransport {
192
232
  startCapture(): void {
193
233
  const pending: PlacementPendingSource[] = this.targets.flatMap(target => target.pending.filter(item => !item.unclaimed).map(item => ({ realm: physical(target),
194
234
  pathHash: digest(`log/${item.row.machine}.jsonl`), offset: item.offset, prefixHash: item.prefixHash, line: item.line })));
235
+ this.capturedPolicyVersion = this.opts.policyVersion?.();
195
236
  this.capture = captureSyncPlacementContext(this.home, { attest: this.opts.placementAttestation!, ...(this.opts.policyVersion ? { policyVersion: this.opts.policyVersion } : {}) }, this.targets.map(physical), pending);
196
237
  if (this.capture.activeHead !== this.epochHash || this.capture.context.homeHash !== this.journal.epoch.homeHash
197
238
  || canonicalJSON(this.capture.context.writers) !== canonicalJSON(this.writerInventory?.writers)
198
- || !!this.writerInventory?.revisionSequence&&this.capture.writerInventory?.revisionHash!==this.writerInventory.revisionHash) refuse();
199
- this.check();
239
+ || !!this.writerInventory?.revisionSequence&&this.capture.writerInventory?.revisionHash!==this.writerInventory.revisionHash) refuse("source-selection");
240
+ this.prove();
200
241
  }
201
242
  async applicationCoordinator(): Promise<ShardSyncApplications> {
202
243
  if (!this.homeMutation) refuse();
@@ -206,15 +247,16 @@ class PlacementTransport {
206
247
  assertAncestor: async (a,b,target) => { if (!await (target as Target).auditor.verifiedAncestor(a,b)) refuse(); },
207
248
  readObject: async object => {
208
249
  const type = await this.required(["cat-file", "-t", object]); if (type !== "commit" && type !== "tree" && type !== "blob") refuse();
209
- const limit = type === "commit" ? 65536 : SHARD_PACK_MAX_BYTES, size = Number(await this.required(["cat-file", "-s", object]));
210
- if (!Number.isSafeInteger(size) || size < 0 || size > limit) refuse();
250
+ const limit = type === "commit" ? 65536 : SHARD_PACK_MAX_BYTES; // the coordinator proves the typed SHA-1
211
251
  const result = await this.call(() => generationSyncGitBytes(this.root, this.args(["cat-file", type, object]), this.opts.signal, undefined, limit));
212
- if (result.code !== 0 || result.out.length !== size) refuse(); return { type, body: result.out };
252
+ if (result.code !== 0) refuse(); return { type, body: result.out };
213
253
  }, afterAdvance: () => { this.capture = undefined; this.metadata(); } });
214
254
  await applications.loadExisting(); this.applications = applications; return applications;
215
255
  }
216
256
  evaluate(value: unknown) {
217
- this.check(); const evaluate = this.evaluator ??= outboundPolicyEvaluator(this.home, this.opts.screen), verdict = evaluate(structuredClone(value) as Record<string, unknown>); this.check(); return verdict;
257
+ // The configured policy is read once; complete proofs on both sides bind that read to the captured policy hash.
258
+ if (!this.evaluator) { this.prove(); this.evaluator = outboundPolicyEvaluator(this.home, this.opts.screen); this.prove(); }
259
+ this.check(); const evaluate = this.evaluator, verdict = evaluate(structuredClone(value) as Record<string, unknown>); this.check(); return verdict;
218
260
  }
219
261
  nativeProofs(): Set<string> {
220
262
  const verified=new Set<string>();
@@ -236,16 +278,27 @@ class PlacementTransport {
236
278
  const materialized = await materializePlacementRows({capture,projection,generation:this.journal.epoch.generation,
237
279
  targets:this.targets.map(target=>({realm:target.realm,generation:target.generation,remote:target.remote,local:target.local,fetched:target.fetched,
238
280
  localPrunes:target.localPrunes,pruned:new Set(target.store.prunePort().snapshot().pruned??[])})),
239
- old,verifiedPrunes:verified,evaluate:value=>this.evaluate(value),createdUnixSeconds,...(frozen?{frozen}:{}),
281
+ old,verifiedPrunes:verified,evaluate:value=>this.evaluate(value),createdUnixSeconds,...(frozen?{frozen}:{}),progress:{phase:(name,unit,total)=>this.enter(name,unit,total),advance:()=>this.progress?.advance()},
240
282
  readTree:(_index,head)=>this.required(["rev-parse",`${head}^{tree}`]),
241
283
  publisherLineages:(index,rows)=>{const target=this.targets[index]!;assertPublisherBoundary(target.store.profile,target.mutation!);return publisherPruneLineages(target.store.profile,target.mutation!,rows);}});
284
+ // The row-evaluation scope closes with a complete proof before any verdict is planned or made durable.
285
+ this.prove();
242
286
  for(const [index,target]of this.targets.entries())Object.assign(target,materialized.targets[index]!);
243
287
  const {decisions,plannedTargets:targets,objects}=materialized;
288
+ if(this.progress){
289
+ // Each decision lands in one bucket: policy-declined, source-local, or held for a journal/dependency reason.
290
+ const counts={permitted:0,local:0,declined:0,held:0},other=new Set(["journal-hold","related-local","unsupported-reference","unverified-prune"]);
291
+ for(const d of decisions)counts[d.eligible?"permitted":d.reason==="source-local"?"local":d.reason&&!other.has(d.reason)?"declined":"held"]++;
292
+ this.progress.counts(counts);
293
+ }
294
+ this.enter("publication-plan");
244
295
  const body={epochHash:this.epochHash,generation:this.journal.epoch.generation,homeHash:capture.context.homeHash,contextHash:placementCaptureContextHash(capture),markerHash:capture.markerHash,
245
296
  sourceHash:capture.context.sourceHash,aliasesHash:capture.context.aliasesHash,policyHash:capture.context.policyHash,remoteHash:digest(this.url),
246
297
  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[]};
247
298
  let bundle=planPlacementPublication(body,{sources:capture.prefixes,decisions,objects});
248
299
  let scheduled=this.events(bundle,projection,old);
300
+ if(!frozen&&body.journal.sequence+scheduled.events.length>PLACEMENT_JOURNAL_MAX_RECORDS)
301
+ throw new PlacementSyncBoundError({phase:"publication-plan",kind:"journal-records",limit:PLACEMENT_JOURNAL_MAX_RECORDS,observed:body.journal.sequence+scheduled.events.length});
249
302
  let head=body.journal.headHash;
250
303
  const lengths=scheduled.events.map((event,index)=>{const record=createPlacementRecord(this.epochHash,body.journal.sequence+index+1,head,event);head=record.seal;return publicationBytes(record).length;});
251
304
  bundle=planPlacementPublication({...body,reservedRecords:lengths.length,reservedRecordBytes:lengths},{sources:capture.prefixes,decisions,objects});
@@ -297,6 +350,7 @@ class PlacementTransport {
297
350
  for(const [index,event]of events.entries()){
298
351
  const record=createPlacementRecord(this.epochHash,root.journal.sequence+index+1,head,event);head=record.seal;records.push(record);
299
352
  }
353
+ this.enter(factual?"acknowledgment":"journal","records",count);
300
354
  const consumed=read.sequence-root.journal.sequence;
301
355
  if(consumed<0||consumed>root.reservedRecords)refuse();
302
356
  for(let index=0;index<Math.min(consumed,records.length);index++)
@@ -307,8 +361,9 @@ class PlacementTransport {
307
361
  if(!record||index>=count||read.pendingRecord&&canonicalJSON(read.pendingRecord)!==canonicalJSON(record))refuse();
308
362
  appendPlacementEvent(this.home,this.epochHash,events[index]!,record.previousHash,this.storage(factual));read=readPlacementJournal(this.home,this.epochHash);
309
363
  }
364
+ this.progress?.advance(Math.max(0,Math.min(count,read.sequence-root.journal.sequence)));
310
365
  for(let index=read.sequence-root.journal.sequence;index<count;index++){
311
- const record=records[index];if(!record)refuse();appendPlacementEvent(this.home,this.epochHash,events[index]!,record.previousHash,this.storage(factual));
366
+ const record=records[index];if(!record)refuse();appendPlacementEvent(this.home,this.epochHash,events[index]!,record.previousHash,this.storage(factual));this.progress?.advance();
312
367
  }
313
368
  }
314
369
  cacheStamp():string {
@@ -328,9 +383,6 @@ class PlacementTransport {
328
383
  async installedObjectGuard(bundle:PlacementPublicationBundle):Promise<()=>void>{
329
384
  const before=this.cacheStamp();
330
385
  for(const chunk of bundle.chunks)if(chunk.kind==="objects")for(const item of chunk.items as PlacementPublicationObject[]){
331
- const type=await this.required(["cat-file","-t",item.oid]);
332
- const size=Number(await this.required(["cat-file","-s",item.oid]));
333
- if(type!==item.type||size!==item.size)refuse();
334
386
  const result=await this.call(()=>generationSyncGitBytes(this.root,this.args(["cat-file",item.type,item.oid]),this.opts.signal,undefined,item.size));
335
387
  if(result.code!==0||result.out.length!==item.size||digest(result.out)!==item.sha256
336
388
  ||createHash("sha1").update(`${item.type} ${item.size}\0`).update(result.out).digest("hex")!==item.oid)refuse();
@@ -372,15 +424,16 @@ class PlacementTransport {
372
424
  return this.result(false,"unknown","The retained placement attempt may have published; its frozen holds and unknown outcome were preserved. Start a fresh sync to recheck current sources.");
373
425
  }
374
426
  async materializeObjects(bundle:PlacementPublicationBundle):Promise<void>{
427
+ this.enter("artifact-construction","objects",this.targets.reduce((sum,target)=>sum+target.objects.length,0));
375
428
  for(const target of this.targets)for(const object of target.objects){
376
429
  this.check();const file=join(this.root,`.placement-object-${randomBytes(16).toString("hex")}`);this.temporary.push(file);
377
430
  const fd=openSync(file,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,0o600);
378
431
  try{let at=0;while(at<object.bytes.length){const n=writeSync(fd,object.bytes,at,object.bytes.length-at,at);if(n<=0)refuse();at+=n;}fsyncSync(fd);}finally{closeSync(fd);}
379
- const written=await this.required(["hash-object","-w","-t",object.type,"--no-filters","--",file]);if(written!==object.oid)refuse();
432
+ const written=await this.required(["hash-object","-w","-t",object.type,"--no-filters","--",file]);if(written!==object.oid)refuse();this.progress?.advance();
380
433
  }
381
434
  const saved=readPlacementPublication(this.home,this.epochHash,bundle.root.seal);
382
435
  if(!saved.facts.some(fact=>fact.phase==="artifact-built"))recordPlacementPublicationPhase(this.home,this.epochHash,bundle.root.seal,"artifact-built",{exportHash:hashJSON(bundle.root.targets.map(target=>target.exportSetHash))},this.storage());
383
- await this.observe("artifact-built");this.check();
436
+ await this.observe("artifact-built");this.prove();
384
437
  }
385
438
  async finish(material:Materialized,recovery=false):Promise<SyncResult>{
386
439
  this.factual=true;this.recovered=recovery;const root=material.bundle.root;
@@ -393,7 +446,7 @@ class PlacementTransport {
393
446
  target.rows = new Map(actual.rows); target.fetched = new Set(actual.rows.keys()); target.origins = new Map(actual.origins);
394
447
  } else { target.rows.clear(); target.fetched.clear(); target.candidate = emptyHistory(); }
395
448
  }
396
- this.preflight(false);
449
+ this.preflight(false);this.enter("import");
397
450
  const applications=await this.applicationCoordinator();await applications.prepare();
398
451
  for(const target of this.targets)for(const hold of target.holds)shardInstallHold(this.root,hold);
399
452
  await applications.install();
@@ -411,7 +464,7 @@ class PlacementTransport {
411
464
  if (existing.code === 1 && planned.expectedCacheHead !== null) refuse();
412
465
  await this.required(["update-ref","--no-deref",ref,planned.commit!,planned.expectedCacheHead??"0".repeat(40)]);
413
466
  }
414
- await this.observe("before-receipt");
467
+ await this.observe("before-receipt");this.enter("receipt");
415
468
  const read=readPlacementPublication(this.home,this.epochHash,root.seal),intent=read.facts.find(fact=>fact.phase==="publication-intent"),journal=readPlacementJournal(this.home,this.epochHash);
416
469
  if(!intent)refuse();
417
470
  recordPlacementPublicationPhase(this.home,this.epochHash,root.seal,"completed",{intentFactHash:intent.seal,journal:{sequence:journal.sequence,headHash:journal.headHash},
@@ -431,12 +484,27 @@ class PlacementTransport {
431
484
  }
432
485
  result(ok:boolean,outcome:"committed"|"unknown"|"not-needed",error?:string):SyncResult{
433
486
  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}:{}),...(this.applications?{pruneApplication:{...this.applications.application}}:{}),
434
- placementPublication:{...(this.attemptHash?{attemptHash:this.attemptHash}:{}),outcome,withheld:this.current?.withheld??0,exported:this.current?.exported??0,
487
+ 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,
435
488
  ...(this.lastPolicyHash?{lastPolicyHash:this.lastPolicyHash}:{}),...(this.lastPolicyCheckUnixMs!==undefined?{lastPolicyCheckUnixMs:this.lastPolicyCheckUnixMs,policyCheckSource:this.policyCheckSource??(this.recovered?"durable-intent" as const:"live" as const)}:{}),
436
489
  policyCeiling:"last-positive-check-before-in-flight-push",...(this.recovered?{recovered:true}:{})}};
437
490
  }
438
491
  async run():Promise<SyncResult>{
492
+ let result:SyncResult;
493
+ try{result=await this.execute();}finally{releasePlacementStorageCaches();} // #420 memos live for one sync only
494
+ // Success is reported only from the real receipt; a failed or stopped run can never leave a successful status.
495
+ if(result.ok)this.progress?.finish("succeeded");
496
+ else if(this.opts.signal?.aborted)this.progress?.finish("cancelled","cancelled");
497
+ else this.progress?.finish("failed",this.bound?"bound":result.placementPublication?.outcome==="unknown"?"unknown-outcome":"unavailable",this.bound?"size-bound":this.refusal);
498
+ return result;
499
+ }
500
+ /** Object slots the plan and its reserved journal chunks need, checked before the first durable plan byte. */
501
+ assertPlanCapacity(bundle:PlacementPublicationBundle):void{
502
+ const objects=readPlacementPublicationMetadata(this.home,this.epochHash,io=>new Set([...io.names(),...publicationFileNames(bundle.root),...io.reservedJournalNames(bundle.root)]).size+1);
503
+ if(objects>PLACEMENT_JOURNAL_MAX_OBJECTS)throw new PlacementSyncBoundError({phase:"publication-plan",kind:"journal-objects",limit:PLACEMENT_JOURNAL_MAX_OBJECTS,observed:objects});
504
+ }
505
+ async execute():Promise<SyncResult>{
439
506
  try{
507
+ this.enter("writer-verification");
440
508
  await this.initialize();
441
509
  const reservation=this.journal.publicationReservation,retained=reservation?readPlacementPublication(this.home,this.epochHash,reservation.attemptHash):undefined;
442
510
  if(retained){
@@ -451,8 +519,9 @@ class PlacementTransport {
451
519
  this.accepted=true;return await this.finish(this.current,true);
452
520
  }
453
521
  }
522
+ this.enter("source-capture");
454
523
  try { 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!);this.startCapture(); }
455
- catch { if(retained)return await this.terminalUnknown(retained);throw new Error("placement source preflight unavailable"); }
524
+ catch(error) { if(retained)return await this.terminalUnknown(retained);if(placementSyncBoundReceipt(error))throw error;throw new PlacementSyncRefusal(placementRefusalCategoryOf(error)??classifyPlacementError(error)??"other"); }
456
525
  if(retained){
457
526
  const root=retained.bundle.root;
458
527
  const stable=root.contextHash===placementCaptureContextHash(this.capture!)&&root.markerHash===this.capture!.markerHash&&root.sourceHash===this.capture!.context.sourceHash
@@ -460,21 +529,25 @@ class PlacementTransport {
460
529
  if(!stable)return await this.terminalUnknown(retained);
461
530
  }
462
531
  const frontier=retained?{...this.journal,sequence:retained.bundle.root.journal.sequence,headHash:retained.bundle.root.journal.headHash}:this.journal;
463
- const material=await this.materialize(retained?.bundle.root.createdUnixSeconds??Math.floor(Date.now()/1000),frontier,retained?.bundle);this.current=material;this.attemptHash=material.bundle.root.seal;
464
- const applications=await this.applicationCoordinator();await applications.prepare();
532
+ const material=await this.materialize(retained?.bundle.root.createdUnixSeconds??Math.floor(Date.now()/1000),frontier,retained?.bundle);
465
533
  const changed=material.bundle.root.targets.some((target,index)=>target.publish&&target.commit!==(this.targets[index]!.remote??null));
534
+ // Nothing durable exists for a fresh attempt yet: an epoch without room for this plan refuses here, typed.
535
+ if(!retained&&(material.events.length||changed))this.assertPlanCapacity(material.bundle);
536
+ this.current=material;this.attemptHash=material.bundle.root.seal;
537
+ const applications=await this.applicationCoordinator();await applications.prepare();
466
538
  if(!retained&&!material.events.length&&!changed&&!this.importsNeeded()){this.attemptHash=undefined;return this.result(true,"not-needed");}
467
- if(!retained){await this.observe("before-plan-fsync");this.check();preparePlacementPublication(this.home,material.bundle,this.storage());await this.observe("plan-fsynced");this.check();}
468
- this.appendThrough(material.bundle,material.events,material.preCount);
539
+ if(!retained){await this.observe("before-plan-fsync");this.prove();preparePlacementPublication(this.home,material.bundle,this.storage());await this.observe("plan-fsynced");this.prove();}
540
+ // One mutation batch: a complete proof on each side, fence checks (and at most 1 s of proof reuse) per record.
541
+ this.prove();this.appendThrough(material.bundle,material.events,material.preCount);this.prove();
469
542
  await this.materializeObjects(material.bundle);
470
543
  let read=readPlacementPublication(this.home,this.epochHash,material.bundle.root.seal);
471
544
  const artifact=read.facts.find(fact=>fact.phase==="artifact-built");if(!artifact)refuse();
472
- this.check();this.lastPolicyCheckUnixMs=Date.now();this.lastPolicyHash=material.bundle.root.policyHash;this.policyCheckSource="live";
545
+ this.prove();this.lastPolicyCheckUnixMs=Date.now();this.lastPolicyHash=material.bundle.root.policyHash;this.policyCheckSource="live";
473
546
  if(!read.facts.some(fact=>fact.phase==="publication-intent"))recordPlacementPublicationPhase(this.home,this.epochHash,material.bundle.root.seal,"publication-intent",{artifactFactHash:artifact.seal,policyHash:material.bundle.root.policyHash,policyCheckUnixMs:material.bundle.root.policySnapshotUnixMs},this.storage());
474
547
  ensurePlacementPublicationDurability(this.home,this.epochHash,this.storage());
475
- await this.observe("before-cas");this.check();
548
+ await this.observe("before-cas");this.enter("publication");this.prove();
476
549
  const installedGuard=await this.installedObjectGuard(material.bundle);
477
- this.check();for(const target of this.targets)for(const check of target.selectorChecks??[])check();
550
+ this.prove();for(const target of this.targets)for(const check of target.selectorChecks??[])check();
478
551
  installedGuard();
479
552
  this.lastPolicyCheckUnixMs=Date.now(); this.lastPolicyHash=material.bundle.root.policyHash;this.policyCheckSource="live";
480
553
  const participating=material.bundle.root.targets.map((target,index)=>({target,index})).filter(item=>item.target.publish);
@@ -489,7 +562,13 @@ class PlacementTransport {
489
562
  const code=Object.getOwnPropertyDescriptor(error,"code")?.value;
490
563
  if(code==="staging"||code==="pending")return this.result(false,this.attemptHash?"unknown":"not-needed",new SharedWriterRevisionError(code).message);
491
564
  }
492
- return this.result(false,this.attemptHash?"unknown":"not-needed",this.attemptHash?"Placement sync stopped with a retained attempt that may have published; recheck its exact receipts before another publication.":"Placement sync is unavailable; verify the active epoch, selected sources, policy, private remote and writer pins before retrying.");
565
+ // #419: an expected size refusal before any attempt exists keeps its phase, kind, limit and observed value.
566
+ const bound=this.attemptHash||this.journal?.publicationReservation?undefined:placementSyncBoundReceipt(error);
567
+ if(bound){this.bound=bound;return this.result(false,"not-needed",placementSyncBoundMessage(bound));}
568
+ 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.");
569
+ // #426: name the failing check by a fixed category and the phase; never the error's own text, which may carry a path.
570
+ this.refusal=placementRefusalCategoryOf(error)??classifyPlacementError(error)??"other";
571
+ return this.result(false,"not-needed",placementRefusalMessage(this.refusal,this.phaseNow));
493
572
  }finally{
494
573
  let ownedCache=true;try{this.metadata();}catch{ownedCache=false;}
495
574
  if(ownedCache){