@staix/agent-mem 0.26.1 → 0.26.3

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,16 @@ 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 } from "./sync-progress.ts";
36
+
37
+ /**
38
+ * #417 proof scope. A complete proof (full writer-install measurement, source, policy and selector recheck) is taken
39
+ * at every effect boundary (`prove`) and may be reused by the fence checks in between (`check`) for at most this long.
40
+ * Every check still verifies mutation ownership, the active epoch, writer revisions, the cache identity and
41
+ * selectors, so a change that persists is refused at the next boundary before publication or import. Not configurable.
42
+ */
43
+ export const PLACEMENT_PROOF_REUSE_MS = 1000;
34
44
 
35
45
  export type PlacementSyncPhase = "before-plan-fsync" | "plan-fsynced" | "artifact-built" | "before-cas" | "cas-returned" | "before-ack" | "acknowledged" | "imported" | "before-receipt" | "receipt-written";
36
46
  type Phase = (phase: PlacementSyncPhase) => void | Promise<void>;
@@ -44,8 +54,8 @@ function refuse(): never { throw new Error("placement sync unavailable"); }
44
54
  function directory(file: string): void { const s = lstatSync(file); if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== process.getuid?.() || (s.mode & 0o077) !== 0) refuse(); }
45
55
  function emptyHistory(): ShardHistory { return { rows: new Map(), files: new Map(), origins: new Map(), manifests: new Map(), version: "v3" }; }
46
56
  /** 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();
57
+ export async function syncPlacementMemory(store: MemoryStore, opts: SyncOptions = {}, phase?: Phase, testOnlyError?: (error:unknown)=>void, testOnlyClock?: () => number): Promise<SyncResult> {
58
+ return new PlacementTransport(store, opts, phase, testOnlyError, testOnlyClock).run();
49
59
  }
50
60
  class PlacementTransport {
51
61
  readonly store: MemoryStore; readonly opts: SyncOptions; readonly phase?: Phase; readonly testOnlyError?: (error:unknown)=>void; readonly home: string; readonly root: string; readonly cache: string;
@@ -55,7 +65,8 @@ class PlacementTransport {
55
65
  machineId = ""; url = ""; revision = ""; accepted = false; factual = false; attempted = false; lastPolicyCheckUnixMs?: number; lastPolicyHash?: string; policyCheckSource?: "live"|"durable-intent"; attemptHash?: string;
56
66
  evaluator?: ReturnType<typeof outboundPolicyEvaluator>; applications?: ShardSyncApplications; current?: Materialized; recovered = false;
57
67
  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"); }
68
+ readonly clock: () => number; readonly progress?: SyncProgress; provedAt?: number; bound?: PlacementSyncBound; capturedPolicyVersion?: string;
69
+ 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
70
  attest(): void {
60
71
  if (!this.opts.placementAttestation || this.opts.screen && !this.opts.policyVersion) refuse();
61
72
  const value = memoryPolicySnapshot(this.opts.placementAttestation());
@@ -77,14 +88,25 @@ class PlacementTransport {
77
88
  const markers = readPlacementRuntimeMarkers(this.home), active = readActivePlacementBinding(this.home, markers.profile, markers.shards);
78
89
  if (!active || active.profile.placementHead !== this.epochHash || active.epoch.homeHash !== this.journal.epoch.homeHash) refuse();
79
90
  }
80
- check = (): void => {
91
+ verify(fresh: boolean): void {
81
92
  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";}
93
+ if (this.factual) { this.progress?.alive(); return; }
94
+ if (this.opts.signal?.aborted) refuse();
95
+ const complete = fresh || this.provedAt === undefined || this.clock() - this.provedAt >= PLACEMENT_PROOF_REUSE_MS;
96
+ if (complete) {
97
+ this.provedAt = undefined; this.attest(); this.capture?.assertUnchanged(); this.provedAt = this.clock();
98
+ if(this.capture){this.lastPolicyHash=this.capture.context.policyHash;this.lastPolicyCheckUnixMs=Date.now();this.policyCheckSource="live";}
99
+ }
100
+ // The host policy version is a cheap callback: compare it on every check, not only on complete proofs.
101
+ if (!complete && this.capture && this.opts.policyVersion && this.opts.policyVersion() !== this.capturedPolicyVersion) refuse();
102
+ this.progress?.proof(complete);
85
103
  for (const target of this.targets) for (const check of target.selectorChecks ?? []) check();
86
104
  this.metadata();
87
- };
105
+ }
106
+ /** Fence check inside a proof scope: reuses a complete proof no older than PLACEMENT_PROOF_REUSE_MS. */
107
+ check = (): void => this.verify(false);
108
+ /** Effect boundary: always a fresh complete proof. */
109
+ prove(): void { this.verify(true); }
88
110
  async call<T>(work: () => T | Promise<T>): Promise<T> { this.check(); const result = await work(); this.check(); return result; }
89
111
  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
112
  async git(args: string[]) { return this.call(() => generationSyncGit(this.root, this.args(args), this.opts.signal)); }
@@ -130,6 +152,7 @@ class PlacementTransport {
130
152
  this.url = this.opts.remote ?? await this.required(["remote", "get-url", "origin"]);
131
153
  if (!this.url || this.url.length > 4096 || this.url.startsWith("-") || /[\r\n\0]/.test(this.url)) refuse();
132
154
  if (await this.call(() => (this.opts.visibility ?? remoteVisibility)(this.url)) !== "private") refuse();
155
+ this.prove(); // a host callout ends any reusable proof
133
156
  if (!existsSync(this.root)) mkdirSync(this.root, { mode: 0o700 });
134
157
  const transport = acquireMutation(this.root); if (!transport) refuse(); this.rootMutation=transport; this.releases.push(transport);
135
158
  const sync = generationSyncLock(this.root); if (!sync) refuse(); this.releases.push(sync);
@@ -148,21 +171,21 @@ class PlacementTransport {
148
171
  if (await this.required(args) !== this.url) refuse();
149
172
  const reservation = this.journal.publicationReservation;
150
173
  const pending = reservation ? readPlacementPublication(this.home, this.epochHash, reservation.attemptHash) : undefined;
151
- if (!pending || pending.bundle.root.remoteHash === digest(this.url)) await this.fetch();
174
+ if (!pending || pending.bundle.root.remoteHash === digest(this.url)) { this.progress?.phase("remote-verification"); await this.fetch(); }
152
175
  }
153
176
  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();
177
+ // One process per object (#420): the typed SHA-1 below proves type, size and bytes, so no -t/-s preflight is needed.
178
+ if(!oid(object))refuse();
179
+ const limit=type==="commit"?65536:SHARD_PACK_MAX_BYTES;
157
180
  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();
181
+ if(result.code!==0||createHash("sha1").update(`${type} ${result.out.length}\0`).update(result.out).digest("hex")!==object)refuse();
159
182
  return Buffer.from(result.out);
160
183
  }
161
184
  async blob(object: string, path: string): Promise<Buffer> {
162
185
  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();
186
+ // The auditor proves the blob SHA-1; the output bound refuses an oversized object (#420).
164
187
  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);
188
+ if (result.code !== 0 || result.out.length < 1) refuse(); return Buffer.from(result.out);
166
189
  }
167
190
  async fetch(): Promise<void> {
168
191
  for (const target of this.targets) {
@@ -192,11 +215,12 @@ class PlacementTransport {
192
215
  startCapture(): void {
193
216
  const pending: PlacementPendingSource[] = this.targets.flatMap(target => target.pending.filter(item => !item.unclaimed).map(item => ({ realm: physical(target),
194
217
  pathHash: digest(`log/${item.row.machine}.jsonl`), offset: item.offset, prefixHash: item.prefixHash, line: item.line })));
218
+ this.capturedPolicyVersion = this.opts.policyVersion?.();
195
219
  this.capture = captureSyncPlacementContext(this.home, { attest: this.opts.placementAttestation!, ...(this.opts.policyVersion ? { policyVersion: this.opts.policyVersion } : {}) }, this.targets.map(physical), pending);
196
220
  if (this.capture.activeHead !== this.epochHash || this.capture.context.homeHash !== this.journal.epoch.homeHash
197
221
  || canonicalJSON(this.capture.context.writers) !== canonicalJSON(this.writerInventory?.writers)
198
222
  || !!this.writerInventory?.revisionSequence&&this.capture.writerInventory?.revisionHash!==this.writerInventory.revisionHash) refuse();
199
- this.check();
223
+ this.prove();
200
224
  }
201
225
  async applicationCoordinator(): Promise<ShardSyncApplications> {
202
226
  if (!this.homeMutation) refuse();
@@ -206,15 +230,16 @@ class PlacementTransport {
206
230
  assertAncestor: async (a,b,target) => { if (!await (target as Target).auditor.verifiedAncestor(a,b)) refuse(); },
207
231
  readObject: async object => {
208
232
  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();
233
+ const limit = type === "commit" ? 65536 : SHARD_PACK_MAX_BYTES; // the coordinator proves the typed SHA-1
211
234
  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 };
235
+ if (result.code !== 0) refuse(); return { type, body: result.out };
213
236
  }, afterAdvance: () => { this.capture = undefined; this.metadata(); } });
214
237
  await applications.loadExisting(); this.applications = applications; return applications;
215
238
  }
216
239
  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;
240
+ // The configured policy is read once; complete proofs on both sides bind that read to the captured policy hash.
241
+ if (!this.evaluator) { this.prove(); this.evaluator = outboundPolicyEvaluator(this.home, this.opts.screen); this.prove(); }
242
+ this.check(); const evaluate = this.evaluator, verdict = evaluate(structuredClone(value) as Record<string, unknown>); this.check(); return verdict;
218
243
  }
219
244
  nativeProofs(): Set<string> {
220
245
  const verified=new Set<string>();
@@ -236,16 +261,27 @@ class PlacementTransport {
236
261
  const materialized = await materializePlacementRows({capture,projection,generation:this.journal.epoch.generation,
237
262
  targets:this.targets.map(target=>({realm:target.realm,generation:target.generation,remote:target.remote,local:target.local,fetched:target.fetched,
238
263
  localPrunes:target.localPrunes,pruned:new Set(target.store.prunePort().snapshot().pruned??[])})),
239
- old,verifiedPrunes:verified,evaluate:value=>this.evaluate(value),createdUnixSeconds,...(frozen?{frozen}:{}),
264
+ old,verifiedPrunes:verified,evaluate:value=>this.evaluate(value),createdUnixSeconds,...(frozen?{frozen}:{}),...(this.progress?{progress:this.progress}:{}),
240
265
  readTree:(_index,head)=>this.required(["rev-parse",`${head}^{tree}`]),
241
266
  publisherLineages:(index,rows)=>{const target=this.targets[index]!;assertPublisherBoundary(target.store.profile,target.mutation!);return publisherPruneLineages(target.store.profile,target.mutation!,rows);}});
267
+ // The row-evaluation scope closes with a complete proof before any verdict is planned or made durable.
268
+ this.prove();
242
269
  for(const [index,target]of this.targets.entries())Object.assign(target,materialized.targets[index]!);
243
270
  const {decisions,plannedTargets:targets,objects}=materialized;
271
+ if(this.progress){
272
+ // Each decision lands in one bucket: policy-declined, source-local, or held for a journal/dependency reason.
273
+ const counts={permitted:0,local:0,declined:0,held:0},other=new Set(["journal-hold","related-local","unsupported-reference","unverified-prune"]);
274
+ for(const d of decisions)counts[d.eligible?"permitted":d.reason==="source-local"?"local":d.reason&&!other.has(d.reason)?"declined":"held"]++;
275
+ this.progress.counts(counts);
276
+ }
277
+ this.progress?.phase("publication-plan");
244
278
  const body={epochHash:this.epochHash,generation:this.journal.epoch.generation,homeHash:capture.context.homeHash,contextHash:placementCaptureContextHash(capture),markerHash:capture.markerHash,
245
279
  sourceHash:capture.context.sourceHash,aliasesHash:capture.context.aliasesHash,policyHash:capture.context.policyHash,remoteHash:digest(this.url),
246
280
  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
281
  let bundle=planPlacementPublication(body,{sources:capture.prefixes,decisions,objects});
248
282
  let scheduled=this.events(bundle,projection,old);
283
+ if(!frozen&&body.journal.sequence+scheduled.events.length>PLACEMENT_JOURNAL_MAX_RECORDS)
284
+ throw new PlacementSyncBoundError({phase:"publication-plan",kind:"journal-records",limit:PLACEMENT_JOURNAL_MAX_RECORDS,observed:body.journal.sequence+scheduled.events.length});
249
285
  let head=body.journal.headHash;
250
286
  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
287
  bundle=planPlacementPublication({...body,reservedRecords:lengths.length,reservedRecordBytes:lengths},{sources:capture.prefixes,decisions,objects});
@@ -297,6 +333,7 @@ class PlacementTransport {
297
333
  for(const [index,event]of events.entries()){
298
334
  const record=createPlacementRecord(this.epochHash,root.journal.sequence+index+1,head,event);head=record.seal;records.push(record);
299
335
  }
336
+ this.progress?.phase(factual?"acknowledgment":"journal","records",count);
300
337
  const consumed=read.sequence-root.journal.sequence;
301
338
  if(consumed<0||consumed>root.reservedRecords)refuse();
302
339
  for(let index=0;index<Math.min(consumed,records.length);index++)
@@ -307,8 +344,9 @@ class PlacementTransport {
307
344
  if(!record||index>=count||read.pendingRecord&&canonicalJSON(read.pendingRecord)!==canonicalJSON(record))refuse();
308
345
  appendPlacementEvent(this.home,this.epochHash,events[index]!,record.previousHash,this.storage(factual));read=readPlacementJournal(this.home,this.epochHash);
309
346
  }
347
+ this.progress?.advance(Math.max(0,Math.min(count,read.sequence-root.journal.sequence)));
310
348
  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));
349
+ const record=records[index];if(!record)refuse();appendPlacementEvent(this.home,this.epochHash,events[index]!,record.previousHash,this.storage(factual));this.progress?.advance();
312
350
  }
313
351
  }
314
352
  cacheStamp():string {
@@ -328,9 +366,6 @@ class PlacementTransport {
328
366
  async installedObjectGuard(bundle:PlacementPublicationBundle):Promise<()=>void>{
329
367
  const before=this.cacheStamp();
330
368
  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
369
  const result=await this.call(()=>generationSyncGitBytes(this.root,this.args(["cat-file",item.type,item.oid]),this.opts.signal,undefined,item.size));
335
370
  if(result.code!==0||result.out.length!==item.size||digest(result.out)!==item.sha256
336
371
  ||createHash("sha1").update(`${item.type} ${item.size}\0`).update(result.out).digest("hex")!==item.oid)refuse();
@@ -372,15 +407,16 @@ class PlacementTransport {
372
407
  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
408
  }
374
409
  async materializeObjects(bundle:PlacementPublicationBundle):Promise<void>{
410
+ this.progress?.phase("artifact-construction","objects",this.targets.reduce((sum,target)=>sum+target.objects.length,0));
375
411
  for(const target of this.targets)for(const object of target.objects){
376
412
  this.check();const file=join(this.root,`.placement-object-${randomBytes(16).toString("hex")}`);this.temporary.push(file);
377
413
  const fd=openSync(file,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,0o600);
378
414
  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();
415
+ const written=await this.required(["hash-object","-w","-t",object.type,"--no-filters","--",file]);if(written!==object.oid)refuse();this.progress?.advance();
380
416
  }
381
417
  const saved=readPlacementPublication(this.home,this.epochHash,bundle.root.seal);
382
418
  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();
419
+ await this.observe("artifact-built");this.prove();
384
420
  }
385
421
  async finish(material:Materialized,recovery=false):Promise<SyncResult>{
386
422
  this.factual=true;this.recovered=recovery;const root=material.bundle.root;
@@ -393,7 +429,7 @@ class PlacementTransport {
393
429
  target.rows = new Map(actual.rows); target.fetched = new Set(actual.rows.keys()); target.origins = new Map(actual.origins);
394
430
  } else { target.rows.clear(); target.fetched.clear(); target.candidate = emptyHistory(); }
395
431
  }
396
- this.preflight(false);
432
+ this.preflight(false);this.progress?.phase("import");
397
433
  const applications=await this.applicationCoordinator();await applications.prepare();
398
434
  for(const target of this.targets)for(const hold of target.holds)shardInstallHold(this.root,hold);
399
435
  await applications.install();
@@ -411,7 +447,7 @@ class PlacementTransport {
411
447
  if (existing.code === 1 && planned.expectedCacheHead !== null) refuse();
412
448
  await this.required(["update-ref","--no-deref",ref,planned.commit!,planned.expectedCacheHead??"0".repeat(40)]);
413
449
  }
414
- await this.observe("before-receipt");
450
+ await this.observe("before-receipt");this.progress?.phase("receipt");
415
451
  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
452
  if(!intent)refuse();
417
453
  recordPlacementPublicationPhase(this.home,this.epochHash,root.seal,"completed",{intentFactHash:intent.seal,journal:{sequence:journal.sequence,headHash:journal.headHash},
@@ -431,12 +467,27 @@ class PlacementTransport {
431
467
  }
432
468
  result(ok:boolean,outcome:"committed"|"unknown"|"not-needed",error?:string):SyncResult{
433
469
  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,
470
+ placementPublication:{...(this.attemptHash?{attemptHash:this.attemptHash}:{}),outcome,...(this.bound?{bound:this.bound}:{}),withheld:this.current?.withheld??0,exported:this.current?.exported??0,
435
471
  ...(this.lastPolicyHash?{lastPolicyHash:this.lastPolicyHash}:{}),...(this.lastPolicyCheckUnixMs!==undefined?{lastPolicyCheckUnixMs:this.lastPolicyCheckUnixMs,policyCheckSource:this.policyCheckSource??(this.recovered?"durable-intent" as const:"live" as const)}:{}),
436
472
  policyCeiling:"last-positive-check-before-in-flight-push",...(this.recovered?{recovered:true}:{})}};
437
473
  }
438
474
  async run():Promise<SyncResult>{
475
+ let result:SyncResult;
476
+ try{result=await this.execute();}finally{releasePlacementStorageCaches();} // #420 memos live for one sync only
477
+ // Success is reported only from the real receipt; a failed or stopped run can never leave a successful status.
478
+ if(result.ok)this.progress?.finish("succeeded");
479
+ else if(this.opts.signal?.aborted)this.progress?.finish("cancelled","cancelled");
480
+ else this.progress?.finish("failed",this.bound?"bound":result.placementPublication?.outcome==="unknown"?"unknown-outcome":"unavailable");
481
+ return result;
482
+ }
483
+ /** Object slots the plan and its reserved journal chunks need, checked before the first durable plan byte. */
484
+ assertPlanCapacity(bundle:PlacementPublicationBundle):void{
485
+ const objects=readPlacementPublicationMetadata(this.home,this.epochHash,io=>new Set([...io.names(),...publicationFileNames(bundle.root),...io.reservedJournalNames(bundle.root)]).size+1);
486
+ if(objects>PLACEMENT_JOURNAL_MAX_OBJECTS)throw new PlacementSyncBoundError({phase:"publication-plan",kind:"journal-objects",limit:PLACEMENT_JOURNAL_MAX_OBJECTS,observed:objects});
487
+ }
488
+ async execute():Promise<SyncResult>{
439
489
  try{
490
+ this.progress?.phase("writer-verification");
440
491
  await this.initialize();
441
492
  const reservation=this.journal.publicationReservation,retained=reservation?readPlacementPublication(this.home,this.epochHash,reservation.attemptHash):undefined;
442
493
  if(retained){
@@ -451,8 +502,9 @@ class PlacementTransport {
451
502
  this.accepted=true;return await this.finish(this.current,true);
452
503
  }
453
504
  }
505
+ this.progress?.phase("source-capture");
454
506
  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"); }
507
+ catch(error) { if(retained)return await this.terminalUnknown(retained);if(placementSyncBoundReceipt(error))throw error;throw new Error("placement source preflight unavailable"); }
456
508
  if(retained){
457
509
  const root=retained.bundle.root;
458
510
  const stable=root.contextHash===placementCaptureContextHash(this.capture!)&&root.markerHash===this.capture!.markerHash&&root.sourceHash===this.capture!.context.sourceHash
@@ -460,21 +512,25 @@ class PlacementTransport {
460
512
  if(!stable)return await this.terminalUnknown(retained);
461
513
  }
462
514
  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();
515
+ const material=await this.materialize(retained?.bundle.root.createdUnixSeconds??Math.floor(Date.now()/1000),frontier,retained?.bundle);
465
516
  const changed=material.bundle.root.targets.some((target,index)=>target.publish&&target.commit!==(this.targets[index]!.remote??null));
517
+ // Nothing durable exists for a fresh attempt yet: an epoch without room for this plan refuses here, typed.
518
+ if(!retained&&(material.events.length||changed))this.assertPlanCapacity(material.bundle);
519
+ this.current=material;this.attemptHash=material.bundle.root.seal;
520
+ const applications=await this.applicationCoordinator();await applications.prepare();
466
521
  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);
522
+ if(!retained){await this.observe("before-plan-fsync");this.prove();preparePlacementPublication(this.home,material.bundle,this.storage());await this.observe("plan-fsynced");this.prove();}
523
+ // One mutation batch: a complete proof on each side, fence checks (and at most 1 s of proof reuse) per record.
524
+ this.prove();this.appendThrough(material.bundle,material.events,material.preCount);this.prove();
469
525
  await this.materializeObjects(material.bundle);
470
526
  let read=readPlacementPublication(this.home,this.epochHash,material.bundle.root.seal);
471
527
  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";
528
+ this.prove();this.lastPolicyCheckUnixMs=Date.now();this.lastPolicyHash=material.bundle.root.policyHash;this.policyCheckSource="live";
473
529
  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
530
  ensurePlacementPublicationDurability(this.home,this.epochHash,this.storage());
475
- await this.observe("before-cas");this.check();
531
+ await this.observe("before-cas");this.progress?.phase("publication");this.prove();
476
532
  const installedGuard=await this.installedObjectGuard(material.bundle);
477
- this.check();for(const target of this.targets)for(const check of target.selectorChecks??[])check();
533
+ this.prove();for(const target of this.targets)for(const check of target.selectorChecks??[])check();
478
534
  installedGuard();
479
535
  this.lastPolicyCheckUnixMs=Date.now(); this.lastPolicyHash=material.bundle.root.policyHash;this.policyCheckSource="live";
480
536
  const participating=material.bundle.root.targets.map((target,index)=>({target,index})).filter(item=>item.target.publish);
@@ -489,6 +545,9 @@ class PlacementTransport {
489
545
  const code=Object.getOwnPropertyDescriptor(error,"code")?.value;
490
546
  if(code==="staging"||code==="pending")return this.result(false,this.attemptHash?"unknown":"not-needed",new SharedWriterRevisionError(code).message);
491
547
  }
548
+ // #419: an expected size refusal before any attempt exists keeps its phase, kind, limit and observed value.
549
+ const bound=this.attemptHash||this.journal?.publicationReservation?undefined:placementSyncBoundReceipt(error);
550
+ if(bound){this.bound=bound;return this.result(false,"not-needed",placementSyncBoundMessage(bound));}
492
551
  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.");
493
552
  }finally{
494
553
  let ownedCache=true;try{this.metadata();}catch{ownedCache=false;}
@@ -0,0 +1,192 @@
1
+ /**
2
+ * #418: advisory progress for a long-running placement sync. Telemetry only: never mutation authority, a publication
3
+ * receipt or proof of success. A snapshot carries phase names, unit counts and timestamps, never a memory body, path,
4
+ * project name, row id, policy pattern, credential or remote URL.
5
+ *
6
+ * There is no timer. Every update is a cooperative checkpoint reached by real work, so a blocked call or a starved
7
+ * event loop leaves an honest stale `lastAliveUnixMs` instead of a manufactured heartbeat.
8
+ */
9
+ import { randomBytes } from "node:crypto";
10
+ import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, opendirSync, readSync, renameSync, rmSync, writeFileSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ import { processLiveness, processSignature, type Liveness } from "./platform.ts";
13
+
14
+ export const SYNC_PROGRESS_SCHEMA = "agent-mem.sync-progress/v1", SYNC_PROGRESS_INTERVAL_MS = 1000, SYNC_PROGRESS_DIR = "sync-status";
15
+ const MAX_OPERATIONS = 8, MAX_BYTES = 4096, MAX_NAMES = 64;
16
+ const PHASES = ["writer-verification", "remote-verification", "source-capture", "policy-evaluation", "dependency-decisions", "artifact-construction",
17
+ "publication-plan", "journal", "publication", "acknowledgment", "import", "receipt"] as const;
18
+ const UNITS = ["rows", "records", "objects"] as const, STATES = ["running", "succeeded", "failed", "cancelled", "interrupted"] as const;
19
+ const CAUSES = ["bound", "unknown-outcome", "unavailable", "cancelled"] as const;
20
+ export type SyncProgressPhase = typeof PHASES[number];
21
+ export type SyncProgressUnit = typeof UNITS[number];
22
+ export type SyncProgressState = typeof STATES[number];
23
+ export type SyncProgressCause = typeof CAUSES[number];
24
+ export interface SyncProgressCounts { permitted: number; local: number; declined: number; held: number }
25
+ export interface SyncProgressSnapshot {
26
+ schema: typeof SYNC_PROGRESS_SCHEMA; operationId: string; state: SyncProgressState; phase: SyncProgressPhase;
27
+ /** How many times this operation entered this phase; completed counts are monotonic within one phase attempt. */
28
+ attempt: number;
29
+ startedUnixMs: number; elapsedMs: number; phaseElapsedMs: number;
30
+ /** Absent when the phase has no countable unit or its total is not genuinely known. No percentage or ETA is derived. */
31
+ unit?: SyncProgressUnit; completed?: number; total?: number;
32
+ counts?: SyncProgressCounts;
33
+ /** Complete writer/source proofs and cheap fence checks so far (#417 measurement counters). */
34
+ proofs: { complete: number; fence: number };
35
+ /** Advances only when a unit of work or a phase completes; `lastAliveUnixMs` is any checkpoint the process reached. */
36
+ lastWorkProgressUnixMs: number; lastAliveUnixMs: number;
37
+ cause?: SyncProgressCause;
38
+ }
39
+ export type SyncProgressSink = (snapshot: SyncProgressSnapshot) => void;
40
+ export interface SyncProgressOptions { sink: SyncProgressSink; intervalMs?: number; now?: () => number; mono?: () => number; operationId?: string }
41
+
42
+ /** Reporter shared by the CLI and the transport. A sink that throws is dropped; it can never fail or alter the sync. */
43
+ export class SyncProgress {
44
+ readonly operationId: string;
45
+ private sink?: SyncProgressSink; private readonly intervalMs: number; private readonly now: () => number; private readonly mono: () => number;
46
+ private readonly started: number; private readonly startedMono: number; private phaseMono: number; private emitted = -Infinity;
47
+ private current: SyncProgressPhase = "writer-verification"; private readonly entered = new Map<SyncProgressPhase, number>();
48
+ private unit?: SyncProgressUnit; private completed?: number; private total?: number; private outcome?: SyncProgressCounts;
49
+ private state: SyncProgressState = "running"; private cause?: SyncProgressCause; private work: number; private aliveAt: number;
50
+ private readonly proofs = { complete: 0, fence: 0 };
51
+ constructor(options: SyncProgressOptions) {
52
+ this.sink = options.sink; this.intervalMs = Math.max(0, options.intervalMs ?? SYNC_PROGRESS_INTERVAL_MS);
53
+ this.now = options.now ?? Date.now; this.mono = options.mono ?? (() => performance.now());
54
+ this.operationId = options.operationId ?? randomBytes(8).toString("hex");
55
+ this.started = this.work = this.aliveAt = this.now(); this.startedMono = this.phaseMono = this.mono(); this.emit(true);
56
+ }
57
+ snapshot(): SyncProgressSnapshot {
58
+ const mono = this.mono();
59
+ return { schema: SYNC_PROGRESS_SCHEMA, operationId: this.operationId, state: this.state, phase: this.current, attempt: this.entered.get(this.current) ?? 1,
60
+ startedUnixMs: this.started, elapsedMs: Math.round(mono - this.startedMono), phaseElapsedMs: Math.round(mono - this.phaseMono),
61
+ ...(this.unit ? { unit: this.unit, completed: this.completed ?? 0, ...(this.total !== undefined ? { total: this.total } : {}) } : {}),
62
+ ...(this.outcome ? { counts: { ...this.outcome } } : {}), proofs: { ...this.proofs },
63
+ lastWorkProgressUnixMs: this.work, lastAliveUnixMs: this.aliveAt, ...(this.cause ? { cause: this.cause } : {}) };
64
+ }
65
+ private emit(force: boolean): void {
66
+ if (!this.sink) return; const mono = this.mono();
67
+ if (!force && mono - this.emitted < this.intervalMs) return; this.emitted = mono;
68
+ try { this.sink(this.snapshot()); } catch { this.sink = undefined; }
69
+ }
70
+ /** A phase change is always reported at once, before its long work begins. */
71
+ phase(phase: SyncProgressPhase, unit?: SyncProgressUnit, total?: number): void {
72
+ if (this.state !== "running") return;
73
+ this.current = phase; this.entered.set(phase, (this.entered.get(phase) ?? 0) + 1);
74
+ this.unit = unit; this.completed = unit ? 0 : undefined; this.total = unit && total !== undefined && Number.isSafeInteger(total) && total >= 0 ? total : undefined;
75
+ this.phaseMono = this.mono(); this.work = this.aliveAt = this.now(); this.emit(true);
76
+ }
77
+ advance(count = 1): void { if (this.state !== "running" || !this.unit) return; this.completed = (this.completed ?? 0) + count; this.work = this.aliveAt = this.now(); this.emit(false); }
78
+ /** A reached checkpoint that completed no unit: it never moves completed counts or the last-work timestamp. */
79
+ alive(): void { if (this.state !== "running") return; this.aliveAt = this.now(); this.emit(false); }
80
+ proof(complete: boolean): void { this.proofs[complete ? "complete" : "fence"]++; this.alive(); }
81
+ counts(counts: SyncProgressCounts): void { this.outcome = { ...counts }; }
82
+ /** Terminal state. Success is reported only by the caller that holds the real sync receipt. */
83
+ finish(state: Exclude<SyncProgressState, "running" | "interrupted">, cause?: SyncProgressCause): void {
84
+ if (this.state !== "running") return; this.state = state; this.cause = state === "succeeded" ? undefined : cause; this.aliveAt = this.now();
85
+ if (state === "succeeded") this.work = this.aliveAt; this.emit(true);
86
+ }
87
+ }
88
+
89
+ const seconds = (ms: number) => `${Math.max(0, Math.round(ms / 1000))}s`;
90
+ /** One human line; unknown totals stay unknown and no percentage or ETA is printed. */
91
+ export function renderSyncProgress(snapshot: SyncProgressSnapshot, now = Date.now()): string {
92
+ const phase = snapshot.phase.replaceAll("-", " "), units = snapshot.unit ? `: ${snapshot.completed ?? 0}${snapshot.total !== undefined ? `/${snapshot.total}` : ""} ${snapshot.unit}` : "";
93
+ const counts = snapshot.counts ? `; permitted ${snapshot.counts.permitted}, local ${snapshot.counts.local}, declined ${snapshot.counts.declined}, held ${snapshot.counts.held}` : "";
94
+ const attempt = snapshot.attempt > 1 ? `; attempt ${snapshot.attempt}` : "";
95
+ if (snapshot.state !== "running") return `amem sync: ${snapshot.state}${snapshot.cause ? ` (${snapshot.cause})` : ""} in ${phase}${units}${counts}; elapsed ${seconds(snapshot.elapsedMs)}`;
96
+ return `amem sync: ${phase}${units}${attempt}${counts}; elapsed ${seconds(snapshot.elapsedMs)}; last work progress ${seconds(now - snapshot.lastWorkProgressUnixMs)} ago`;
97
+ }
98
+
99
+ interface Owner { pid: number; signature?: string }
100
+ function privateDirectory(dir: string): boolean {
101
+ const stat = lstatSync(dir, { throwIfNoEntry: false });
102
+ return !!stat && stat.isDirectory() && !stat.isSymbolicLink() && stat.uid === process.getuid?.() && (stat.mode & 0o077) === 0;
103
+ }
104
+ function names(dir: string): string[] {
105
+ const reader = opendirSync(dir), found: string[] = [];
106
+ try { for (;;) { const entry = reader.readSync(); if (!entry || found.length >= MAX_NAMES) break; if (/^[a-f0-9]{16}\.json$/.test(entry.name)) found.push(entry.name); } } finally { reader.closeSync(); }
107
+ return found;
108
+ }
109
+ function readBounded(file: string): Buffer | undefined {
110
+ const before = lstatSync(file, { throwIfNoEntry: false });
111
+ if (!before || !before.isFile() || before.isSymbolicLink() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.size > MAX_BYTES) return undefined;
112
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
113
+ try {
114
+ const stat = fstatSync(fd); if (!stat.isFile() || stat.size > MAX_BYTES) return undefined;
115
+ const bytes = Buffer.alloc(stat.size); let at = 0;
116
+ while (at < bytes.length) { const count = readSync(fd, bytes, at, bytes.length - at, at); if (count <= 0) return undefined; at += count; }
117
+ return bytes;
118
+ } finally { closeSync(fd); }
119
+ }
120
+ const count = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
121
+ /** Allowlisted enumerations and non-negative integers only: a tampered sidecar cannot inject text into a terminal. */
122
+ function validate(value: unknown, operationId: string): { snapshot: SyncProgressSnapshot; owner: Owner } | undefined {
123
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
124
+ const v = value as Record<string, unknown>, owner = v.owner as Record<string, unknown> | undefined, proofs = v.proofs as Record<string, unknown> | undefined, counts = v.counts as Record<string, unknown> | undefined;
125
+ if (v.schema !== SYNC_PROGRESS_SCHEMA || v.operationId !== operationId || !(STATES as readonly unknown[]).includes(v.state) || !(PHASES as readonly unknown[]).includes(v.phase)
126
+ || ![v.attempt, v.startedUnixMs, v.elapsedMs, v.phaseElapsedMs, v.lastWorkProgressUnixMs, v.lastAliveUnixMs].every(count)
127
+ || !proofs || !count(proofs.complete) || !count(proofs.fence) || !owner || !count(owner.pid) || owner.signature !== undefined && (typeof owner.signature !== "string" || owner.signature.length > 256)
128
+ || v.unit !== undefined && (!(UNITS as readonly unknown[]).includes(v.unit) || !count(v.completed)) || v.total !== undefined && !count(v.total)
129
+ || v.cause !== undefined && !(CAUSES as readonly unknown[]).includes(v.cause)
130
+ || counts !== undefined && ![counts.permitted, counts.local, counts.declined, counts.held].every(count)) return undefined;
131
+ const snapshot: SyncProgressSnapshot = { schema: SYNC_PROGRESS_SCHEMA, operationId, state: v.state as SyncProgressState, phase: v.phase as SyncProgressPhase, attempt: v.attempt as number,
132
+ startedUnixMs: v.startedUnixMs as number, elapsedMs: v.elapsedMs as number, phaseElapsedMs: v.phaseElapsedMs as number,
133
+ ...(v.unit !== undefined ? { unit: v.unit as SyncProgressUnit, completed: v.completed as number, ...(v.total !== undefined ? { total: v.total as number } : {}) } : {}),
134
+ ...(counts ? { counts: { permitted: counts.permitted as number, local: counts.local as number, declined: counts.declined as number, held: counts.held as number } } : {}),
135
+ proofs: { complete: proofs.complete as number, fence: proofs.fence as number }, lastWorkProgressUnixMs: v.lastWorkProgressUnixMs as number, lastAliveUnixMs: v.lastAliveUnixMs as number,
136
+ ...(v.cause !== undefined ? { cause: v.cause as SyncProgressCause } : {}) };
137
+ return { snapshot, owner: { pid: owner.pid as number, ...(typeof owner.signature === "string" ? { signature: owner.signature } : {}) } };
138
+ }
139
+ function load(dir: string, name: string): { snapshot: SyncProgressSnapshot; owner: Owner } | undefined {
140
+ try { const bytes = readBounded(join(dir, name)); return bytes ? validate(JSON.parse(bytes.toString("utf8")), name.slice(0, 16)) : undefined; } catch { return undefined; }
141
+ }
142
+
143
+ /**
144
+ * Telemetry sidecar under `<home>/sync-status/<operationId>.json`: outside every source, journal and proof namespace,
145
+ * one file per operation, replaced atomically at most once per reporting interval. It keeps the newest 8 operations;
146
+ * a running operation whose owner is alive is never pruned. Any failure throws into the reporter, which drops the sink.
147
+ */
148
+ export function syncProgressSidecar(home: string, owner: Owner = { pid: process.pid, ...(processSignature(process.pid) ? { signature: processSignature(process.pid)! } : {}) }): SyncProgressSink {
149
+ const dir = join(home, SYNC_PROGRESS_DIR); let ready = false;
150
+ return snapshot => {
151
+ if (!ready) {
152
+ mkdirSync(dir, { mode: 0o700, recursive: true }); if (!privateDirectory(dir)) throw new Error("sync status directory unavailable");
153
+ const kept = names(dir).filter(name => name !== `${snapshot.operationId}.json`).map(name => ({ name, mtimeMs: lstatSync(join(dir, name), { throwIfNoEntry: false })?.mtimeMs ?? 0 })).sort((a, b) => b.mtimeMs - a.mtimeMs);
154
+ for (const { name } of kept.slice(MAX_OPERATIONS - 1)) {
155
+ const old = load(dir, name);
156
+ if (!old || old.snapshot.state !== "running" || processLiveness(old.owner.pid, old.owner.signature) === "gone") rmSync(join(dir, name), { force: true });
157
+ }
158
+ ready = true;
159
+ }
160
+ const file = join(dir, `${snapshot.operationId}.json`), temporary = join(dir, `.${snapshot.operationId}.tmp`);
161
+ rmSync(temporary, { force: true }); writeFileSync(temporary, JSON.stringify({ ...snapshot, owner }) + "\n", { mode: 0o600, flag: "wx" }); renameSync(temporary, file);
162
+ };
163
+ }
164
+
165
+ export interface SyncOperationStatus extends SyncProgressSnapshot { ownerLiveness: Liveness; lastAliveAgoMs: number; lastWorkProgressAgoMs: number }
166
+ export interface SyncStatusReport { operations: SyncOperationStatus[]; malformed: number }
167
+ /**
168
+ * Read-only status for another terminal: opens no realm, takes no lock, renews no proof and writes nothing. A running
169
+ * operation whose owner is gone is reported as interrupted, never as a success; unreadable sidecars are only counted.
170
+ */
171
+ export function readSyncStatus(home: string, now = Date.now(), liveness: (pid: number, signature?: string) => Liveness = processLiveness): SyncStatusReport {
172
+ const dir = join(home, SYNC_PROGRESS_DIR), report: SyncStatusReport = { operations: [], malformed: 0 };
173
+ if (!privateDirectory(dir)) return report;
174
+ for (const name of names(dir)) {
175
+ const read = load(dir, name); if (!read) { report.malformed++; continue; }
176
+ const ownerLiveness = read.snapshot.state === "running" ? liveness(read.owner.pid, read.owner.signature) : "gone";
177
+ report.operations.push({ ...read.snapshot, ...(read.snapshot.state === "running" && ownerLiveness === "gone" ? { state: "interrupted" as const } : {}), ownerLiveness,
178
+ lastAliveAgoMs: Math.max(0, now - read.snapshot.lastAliveUnixMs), lastWorkProgressAgoMs: Math.max(0, now - read.snapshot.lastWorkProgressUnixMs) });
179
+ }
180
+ report.operations.sort((a, b) => b.startedUnixMs - a.startedUnixMs || a.operationId.localeCompare(b.operationId));
181
+ report.operations.splice(MAX_OPERATIONS); return report;
182
+ }
183
+ export function renderSyncStatus(report: SyncStatusReport, now = Date.now()): string {
184
+ if (!report.operations.length) return `no placement sync operation recorded${report.malformed ? ` (${report.malformed} unreadable status file${report.malformed === 1 ? "" : "s"} ignored)` : ""}`;
185
+ const lines = report.operations.map(row => {
186
+ const line = renderSyncProgress(row, now).replace(/^amem sync: /, "");
187
+ const tail = row.state === "running" ? `; last observed alive ${seconds(row.lastAliveAgoMs)} ago${row.ownerLiveness === "unknown" ? "; owner liveness unknown" : ""}; percentage and ETA unknown`
188
+ : row.state === "interrupted" ? `; owner process is gone; last observed alive ${seconds(row.lastAliveAgoMs)} ago; not a successful sync` : "";
189
+ return `${row.operationId} ${row.state === "interrupted" ? line.replace(/; last work progress .*$/, "").replace(/^/, "interrupted in ") : line}${tail}`;
190
+ });
191
+ return [...lines, ...(report.malformed ? [`(${report.malformed} unreadable status file${report.malformed === 1 ? "" : "s"} ignored)`] : [])].join("\n");
192
+ }
@@ -8,8 +8,12 @@ import { memoryGitArgv, memoryGitEnv, memoryGitSync, processLiveness, processSig
8
8
  import { acquireMutation } from "./mutation.ts";
9
9
  import type { MemoryStore } from "./store.ts";
10
10
  import { syncGenerationMemory } from "./generation-sync.ts";
11
+ import { loadAmemConfig } from "./config.ts";
12
+ import { memoryHome } from "./home.ts";
11
13
  import { outboundScreen, screenOutboundRows, screenOwnSegment, type RowScreen } from "./sync-screen.ts";
12
14
  import { shardSyncBinding } from "./sync-binding.ts";
15
+ import type { PlacementSyncBound } from "./sync-placement-bound.ts";
16
+ import type { SyncProgress } from "./sync-progress.ts";
13
17
 
14
18
  /**
15
19
  * #258 phase 2: hub memory between a person's machines through a git remote they configure. The memory directory is a
@@ -19,7 +23,9 @@ import { shardSyncBinding } from "./sync-binding.ts";
19
23
  export type Visibility = "public" | "private" | "unknown";
20
24
  export interface SyncResult { ok: boolean; pushed: boolean; entries: number; warning?: string; error?: string;
21
25
  placementPublication?: { attemptHash?: string; outcome: "committed" | "unknown" | "not-needed"; withheld: number; exported: number;
22
- lastPolicyHash?: string; lastPolicyCheckUnixMs?: number; policyCheckSource?: "live" | "durable-intent"; policyCeiling: "last-positive-check-before-in-flight-push"; recovered?: boolean };
26
+ lastPolicyHash?: string; lastPolicyCheckUnixMs?: number; policyCheckSource?: "live" | "durable-intent"; policyCeiling: "last-positive-check-before-in-flight-push"; recovered?: boolean;
27
+ /** #419: an expected size refusal before any publication attempt; numbers only. */
28
+ bound?: PlacementSyncBound };
23
29
  pruneApplication?: {transport:"durable"|"unconfirmed";proofComplete:number;projectionActive:number|null;nativeApplied:number|null;held:number;phase:"preflight"|"prepared"|"active"|"complete"};
24
30
  }
25
31
 
@@ -179,10 +185,13 @@ export function githubRepoOf(url: string): string | undefined {
179
185
  return match && match[2] !== "." && match[2] !== ".." ? `${match[1]}/${match[2]}` : undefined;
180
186
  }
181
187
 
182
- /** GitHub remotes are asked through `gh`, pinned to github.com; any other host, or a `gh` that cannot answer, is unknown. */
188
+ /**
189
+ * GitHub remotes are asked through `gh`, pinned to github.com. Any other URL is private only when it exactly matches the home's
190
+ * person-attested `privateRemotes` (#420); otherwise, or when `gh` cannot answer or the policy is unreadable, it is unknown.
191
+ */
183
192
  export async function remoteVisibility(url: string): Promise<Visibility> {
184
193
  const repo = githubRepoOf(url);
185
- if (!repo) return "unknown";
194
+ if (!repo) { try { return loadAmemConfig(memoryHome()).config.privateRemotes?.includes(url) ? "private" : "unknown"; } catch { return "unknown"; } }
186
195
  try {
187
196
  // GH_HOST (and the enterprise token variables) would send `gh repo view` to a different server: pin it, so the answer is about github.com's repository.
188
197
  const env: Record<string, string | undefined> = { ...process.env, GH_HOST: "github.com" };
@@ -220,6 +229,8 @@ function lock(dir: string): (() => void) | undefined {
220
229
  export interface SyncOptions {
221
230
  /** Fresh compatibility facts for an already activated v3 profile; never activates a legacy profile or bypasses policy. */
222
231
  placementAttestation?: PlacementCapturePort["attest"];
232
+ /** #418: advisory placement-sync progress reporter; never authority, and a failing sink cannot fail the sync. */
233
+ progress?: SyncProgress;
223
234
  /** Set (or replace) the remote first: a person's choice. */
224
235
  remote?: string;
225
236
  visibility?: (url: string) => Promise<Visibility>;