@staix/agent-mem 0.28.2 → 0.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +11 -7
- package/package.json +1 -1
- package/src/brief-work.ts +142 -0
- package/src/cli.ts +34 -13
- package/src/commands-table.ts +2 -0
- package/src/mcp-memory.ts +1 -1
- package/src/memory/commands.ts +5 -3
- package/src/memory/curated-cache-state.ts +10 -7
- package/src/memory/doctor.ts +15 -12
- package/src/memory/generation-index.ts +79 -17
- package/src/memory/index-file.ts +2 -2
- package/src/memory/metrics.ts +1 -0
- package/src/memory/shard-sync-history.ts +6 -0
- package/src/memory/shard.ts +33 -13
- package/src/memory/store.ts +147 -41
- package/src/memory/sync-placement-capture.ts +53 -17
- package/src/memory/sync-placement-guard.ts +52 -1
- package/src/memory/sync-placement-inventory.ts +136 -0
- package/src/memory/sync-placement-journal-storage.ts +21 -4
- package/src/memory/sync-placement-journal.ts +13 -4
- package/src/memory/sync-placement-materialize.ts +14 -3
- package/src/memory/sync-placement-publication-plan.ts +8 -4
- package/src/memory/sync-placement-realm-admission-storage.ts +128 -0
- package/src/memory/sync-placement-realm-admission.ts +335 -0
- package/src/memory/sync-placement-realm-attribution.ts +23 -0
- package/src/memory/sync-placement-realm-effective.ts +71 -0
- package/src/memory/sync-placement-realm-extension-format.ts +66 -0
- package/src/memory/sync-placement-realm-extension-storage.ts +82 -0
- package/src/memory/sync-placement-realm-intent-format.ts +55 -0
- package/src/memory/sync-placement-realm-intent-storage.ts +123 -0
- package/src/memory/sync-placement-realm-pending.ts +27 -0
- package/src/memory/sync-placement-realm-proof.ts +131 -0
- package/src/memory/sync-placement-realm-torn.ts +26 -0
- package/src/memory/sync-placement-transport.ts +69 -31
- package/src/memory/sync-placement-yield.ts +30 -0
- package/src/memory/sync-progress.ts +47 -6
- package/src/memory/sync.ts +23 -1
- package/src/memory/work-lists.ts +129 -9
- package/src/session-brief.ts +34 -1
|
@@ -4,14 +4,14 @@ import { constants, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, open
|
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { canonicalJSON, hashJSON, readSelector } from "./generation.ts";
|
|
6
6
|
import { generationSyncLock } from "./generation-sync.ts";
|
|
7
|
-
import { generationSyncGit, generationSyncGitBytes, remoteVisibility, type SyncOptions, type SyncResult } from "./sync.ts";
|
|
7
|
+
import { generationSyncGit, generationSyncGitBytes, remoteVisibility, type SyncFailureCause, type SyncOptions, type SyncResult } from "./sync.ts";
|
|
8
8
|
import { acquireMutation, assertMutationHandle, type MutationHandle } from "./mutation.ts";
|
|
9
9
|
import { isLocalKey, PlacementRealmRefusal, resolveShardProfile } from "./shard.ts";
|
|
10
10
|
import { memoryPolicySnapshot } from "./policy.ts";
|
|
11
11
|
import { outboundPolicyEvaluator } from "./sync-screen.ts";
|
|
12
12
|
import { readActivePlacementBinding } from "./sync-placement-active.ts";
|
|
13
13
|
import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
|
|
14
|
-
import {
|
|
14
|
+
import { captureSyncPlacementContextAsync, placementCaptureContextHash, type PlacementCapture, type PlacementPendingSource } from "./sync-placement-capture.ts";
|
|
15
15
|
import { readEffectiveSyncPlacementWriters, type EffectiveSyncPlacementWriters } from "./sync-placement-effective-writers.ts";
|
|
16
16
|
import { SharedWriterRevisionError } from "./sync-placement-writer-revision-format.ts";
|
|
17
17
|
import { types } from "node:util";
|
|
@@ -31,6 +31,7 @@ import { assertPublisherBoundary, ensurePublisherBoundary, publisherPruneLineage
|
|
|
31
31
|
import type { MemoryStore } from "./store.ts";
|
|
32
32
|
import type { PruneRow } from "./prune.ts";
|
|
33
33
|
import { materializePlacementRows, verifiedPlacementPrunes } from "./sync-placement-materialize.ts";
|
|
34
|
+
import { cooperativeYield, PLACEMENT_APPEND_SLICE, yieldTurn } from "./sync-placement-yield.ts";
|
|
34
35
|
import { placementCacheConfigStamp, placementCacheRootStamp, validatePlacementCacheConfig } from "./sync-placement-cache.ts";
|
|
35
36
|
import { PlacementSyncBoundError, placementSyncBoundMessage, placementSyncBoundReceipt, type PlacementSyncBound } from "./sync-placement-bound.ts";
|
|
36
37
|
import type { SyncProgress, SyncProgressPhase } from "./sync-progress.ts";
|
|
@@ -68,8 +69,8 @@ export function classifyPlacementError(error: unknown): PlacementRefusalCategory
|
|
|
68
69
|
function directory(file: string): void { const s = lstatSync(file); if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== process.getuid?.() || (s.mode & 0o077) !== 0) refuse(); }
|
|
69
70
|
function emptyHistory(): ShardHistory { return { rows: new Map(), files: new Map(), origins: new Map(), manifests: new Map(), version: "v3" }; }
|
|
70
71
|
/** Internal phase observer is a fault seam, not part of SyncOptions or the package barrel. */
|
|
71
|
-
export async function syncPlacementMemory(store: MemoryStore, opts: SyncOptions = {}, phase?: Phase, testOnlyError?: (error:unknown)=>void, testOnlyClock?: () => number): Promise<SyncResult> {
|
|
72
|
-
return new PlacementTransport(store, opts, phase, testOnlyError, testOnlyClock).run();
|
|
72
|
+
export async function syncPlacementMemory(store: MemoryStore, opts: SyncOptions = {}, phase?: Phase, testOnlyError?: (error:unknown)=>void, testOnlyClock?: () => number, targets?: readonly MemoryStore[]): Promise<SyncResult> {
|
|
73
|
+
return new PlacementTransport(store, opts, phase, testOnlyError, testOnlyClock, targets).run();
|
|
73
74
|
}
|
|
74
75
|
class PlacementTransport {
|
|
75
76
|
readonly store: MemoryStore; readonly opts: SyncOptions; readonly phase?: Phase; readonly testOnlyError?: (error:unknown)=>void; readonly home: string; readonly root: string; readonly cache: string;
|
|
@@ -79,8 +80,11 @@ class PlacementTransport {
|
|
|
79
80
|
machineId = ""; url = ""; revision = ""; accepted = false; factual = false; attempted = false; lastPolicyCheckUnixMs?: number; lastPolicyHash?: string; policyCheckSource?: "live"|"durable-intent"; attemptHash?: string;
|
|
80
81
|
evaluator?: ReturnType<typeof outboundPolicyEvaluator>; applications?: ShardSyncApplications; current?: Materialized; recovered = false;
|
|
81
82
|
writerInventory?:EffectiveSyncPlacementWriters;
|
|
83
|
+
/** #462: a closed cause the catch block identified before `result` derives the rest. */
|
|
84
|
+
failureCause?: SyncFailureCause;
|
|
82
85
|
readonly clock: () => number; readonly progress?: SyncProgress; provedAt?: number; bound?: PlacementSyncBound; capturedPolicyVersion?: string;
|
|
83
|
-
|
|
86
|
+
readonly selected?: readonly MemoryStore[];
|
|
87
|
+
constructor(store: MemoryStore, opts: SyncOptions, phase?: Phase, testOnlyError?: (error:unknown)=>void, clock: () => number = () => performance.now(), selected?: readonly MemoryStore[]) { this.selected=selected; this.clock=clock; this.progress=opts.progress; this.testOnlyError=testOnlyError; this.store = store; this.opts = opts; this.phase = phase; this.home = store.profile.home; this.root = join(this.home, "shard-sync-placement"); this.cache = join(this.root, "objects.git"); }
|
|
84
88
|
attest(): void {
|
|
85
89
|
if (!this.opts.placementAttestation || this.opts.screen && !this.opts.policyVersion) refuse("policy");
|
|
86
90
|
const value = memoryPolicySnapshot(this.opts.placementAttestation());
|
|
@@ -152,10 +156,14 @@ class PlacementTransport {
|
|
|
152
156
|
async initialize(): Promise<void> {
|
|
153
157
|
const markers = readPlacementRuntimeMarkers(this.home), active = readActivePlacementBinding(this.home, markers.profile, markers.shards);
|
|
154
158
|
if (!active || this.store.profile.publicationFormat !== PLACEMENT_FORMAT || this.store.profile.placementHead !== active.profile.placementHead) refuse("epoch");
|
|
155
|
-
this.epochHash = active.profile.placementHead; this.machineId = active.shards.machine.id; this.revision = readSelector(this.home).revision; this.journal = readPlacementJournal(this.home, this.epochHash);
|
|
156
|
-
|
|
159
|
+
this.epochHash = active.profile.placementHead; this.machineId = active.shards.machine.id; this.revision = readSelector(this.home).revision; this.journal = readPlacementJournal(this.home, this.epochHash);
|
|
160
|
+
await yieldTurn(); // #462: no lock is held yet; each heavy read gets its own macrotask
|
|
161
|
+
this.writerInventory=readEffectiveSyncPlacementWriters(this.home);await yieldTurn();this.attest();
|
|
162
|
+
// #450: an inventory driver passes at most two explicitly opened realms (one unchanged publication plan); otherwise the store's own pair.
|
|
163
|
+
const opened = this.selected ?? this.store.openedSyncTargets();
|
|
157
164
|
if (!opened.length || opened.length > 2 || !opened.includes(this.store) || opened.some(item => item.profile.home !== this.home || !item.profile.sharded || !item.profile.generation
|
|
158
|
-
||
|
|
165
|
+
|| item.profile.generation !== this.store.profile.generation
|
|
166
|
+
|| !this.selected && !item.profile.shardUser && item.profile.shardKey !== this.store.profile.shardKey)) refuse("source-selection");
|
|
159
167
|
for (const item of opened) {
|
|
160
168
|
const realm = item.profile.shardUser ? { scope: "user" as const } : { scope: "project" as const, key: item.profile.shardKey! };
|
|
161
169
|
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;
|
|
@@ -170,7 +178,7 @@ class PlacementTransport {
|
|
|
170
178
|
this.url = this.opts.remote ?? await this.required(["remote", "get-url", "origin"]);
|
|
171
179
|
if (!this.url || this.url.length > 4096 || this.url.startsWith("-") || /[\r\n\0]/.test(this.url)) refuse("remote");
|
|
172
180
|
if (await this.call(() => (this.opts.visibility ?? remoteVisibility)(this.url)) !== "private") refuse("remote");
|
|
173
|
-
this.prove(); // a host callout ends any reusable proof
|
|
181
|
+
await yieldTurn(); this.prove(); // a host callout ends any reusable proof
|
|
174
182
|
if (!existsSync(this.root)) mkdirSync(this.root, { mode: 0o700 });
|
|
175
183
|
const transport = acquireMutation(this.root); if (!transport) refuse("lock"); this.rootMutation=transport; this.releases.push(transport);
|
|
176
184
|
const sync = generationSyncLock(this.root); if (!sync) refuse("lock"); this.releases.push(sync);
|
|
@@ -178,7 +186,9 @@ class PlacementTransport {
|
|
|
178
186
|
const handle = acquireMutation(dir); if (!handle) refuse("lock"); this.releases.push(handle); if (dir === this.home) this.homeMutation = handle;
|
|
179
187
|
for (const target of this.targets) if (target.store.dir === dir) target.mutation = handle;
|
|
180
188
|
}
|
|
181
|
-
|
|
189
|
+
// #450: each explicitly selected realm tracks and republishes its own curated cache.
|
|
190
|
+
const curated = (this.selected ?? [this.store]).map(item => item.beginCuratedCacheUpdate());
|
|
191
|
+
this.releaseCurated = () => { for (const release of curated.reverse()) release(); };
|
|
182
192
|
this.journal = readPlacementJournal(this.home, this.epochHash); this.revision = readSelector(this.home).revision; this.attest();
|
|
183
193
|
if (!existing) await this.required(["init", "--bare", "--template=", "--object-format=sha1", "-q", this.cache]);
|
|
184
194
|
if (!await this.independent()) refuse();
|
|
@@ -230,15 +240,15 @@ class PlacementTransport {
|
|
|
230
240
|
}
|
|
231
241
|
shardProvePrunes(this.targets);
|
|
232
242
|
}
|
|
233
|
-
startCapture(): void {
|
|
243
|
+
async startCapture(): Promise<void> {
|
|
234
244
|
const pending: PlacementPendingSource[] = this.targets.flatMap(target => target.pending.filter(item => !item.unclaimed).map(item => ({ realm: physical(target),
|
|
235
245
|
pathHash: digest(`log/${item.row.machine}.jsonl`), offset: item.offset, prefixHash: item.prefixHash, line: item.line })));
|
|
236
246
|
this.capturedPolicyVersion = this.opts.policyVersion?.();
|
|
237
|
-
this.capture =
|
|
247
|
+
this.capture = await captureSyncPlacementContextAsync(this.home, { attest: this.opts.placementAttestation!, ...(this.opts.policyVersion ? { policyVersion: this.opts.policyVersion } : {}) }, this.targets.map(physical), pending);
|
|
238
248
|
if (this.capture.activeHead !== this.epochHash || this.capture.context.homeHash !== this.journal.epoch.homeHash
|
|
239
249
|
|| canonicalJSON(this.capture.context.writers) !== canonicalJSON(this.writerInventory?.writers)
|
|
240
250
|
|| !!this.writerInventory?.revisionSequence&&this.capture.writerInventory?.revisionHash!==this.writerInventory.revisionHash) refuse("source-selection");
|
|
241
|
-
this.prove();
|
|
251
|
+
await yieldTurn(); this.prove(); // #462: the complete proof that closes capture runs in its own turn; it is the same proof
|
|
242
252
|
}
|
|
243
253
|
async applicationCoordinator(): Promise<ShardSyncApplications> {
|
|
244
254
|
if (!this.homeMutation) refuse();
|
|
@@ -297,12 +307,17 @@ class PlacementTransport {
|
|
|
297
307
|
sourceHash:capture.context.sourceHash,aliasesHash:capture.context.aliasesHash,policyHash:capture.context.policyHash,remoteHash:digest(this.url),
|
|
298
308
|
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[]};
|
|
299
309
|
let bundle=planPlacementPublication(body,{sources:capture.prefixes,decisions,objects});
|
|
310
|
+
await yieldTurn(); // #462: planning is pure; each step gets its own turn
|
|
300
311
|
let scheduled=this.events(bundle,projection,old);
|
|
312
|
+
await yieldTurn();
|
|
301
313
|
if(!frozen&&body.journal.sequence+scheduled.events.length>PLACEMENT_JOURNAL_MAX_RECORDS)
|
|
302
314
|
throw new PlacementSyncBoundError({phase:"publication-plan",kind:"journal-records",limit:PLACEMENT_JOURNAL_MAX_RECORDS,observed:body.journal.sequence+scheduled.events.length});
|
|
303
315
|
let head=body.journal.headHash;
|
|
304
|
-
const lengths=
|
|
316
|
+
const lengths:number[]=[],pause=cooperativeYield();
|
|
317
|
+
for(const [index,event]of scheduled.events.entries()){await pause();const record=createPlacementRecord(this.epochHash,body.journal.sequence+index+1,head,event);head=record.seal;lengths.push(publicationBytes(record).length);}
|
|
318
|
+
await yieldTurn();
|
|
305
319
|
bundle=planPlacementPublication({...body,reservedRecords:lengths.length,reservedRecordBytes:lengths},{sources:capture.prefixes,decisions,objects});
|
|
320
|
+
await yieldTurn();
|
|
306
321
|
scheduled=this.events(bundle,projection,old);
|
|
307
322
|
if(frozen&&canonicalJSON(bundle)!==canonicalJSON(frozen))refuse();
|
|
308
323
|
return{bundle,decisions,projection,old,...scheduled,exported:scheduled.events.filter(event=>event.kind==="publication-ambiguous").length,withheld:decisions.filter(decision=>!decision.eligible).length};
|
|
@@ -345,25 +360,36 @@ class PlacementTransport {
|
|
|
345
360
|
}
|
|
346
361
|
return values;
|
|
347
362
|
}
|
|
348
|
-
appendThrough(bundle:PlacementPublicationBundle,events:PlacementEvent[],count:number,factual=false):void{
|
|
363
|
+
async appendThrough(bundle:PlacementPublicationBundle,events:PlacementEvent[],count:number,factual=false):Promise<void>{
|
|
349
364
|
const root=bundle.root;let read=readPlacementJournal(this.home,this.epochHash),head=root.journal.headHash;
|
|
350
|
-
const records:PlacementRecord[]=[];
|
|
365
|
+
const records:PlacementRecord[]=[],pause=cooperativeYield();
|
|
351
366
|
for(const [index,event]of events.entries()){
|
|
367
|
+
await pause();
|
|
352
368
|
const record=createPlacementRecord(this.epochHash,root.journal.sequence+index+1,head,event);head=record.seal;records.push(record);
|
|
353
369
|
}
|
|
354
370
|
this.enter(factual?"acknowledgment":"journal","records",count);
|
|
355
371
|
const consumed=read.sequence-root.journal.sequence;
|
|
356
372
|
if(consumed<0||consumed>root.reservedRecords)refuse();
|
|
357
|
-
for(let index=0;index<Math.min(consumed,records.length);index++)
|
|
373
|
+
for(let index=0;index<Math.min(consumed,records.length);index++){
|
|
374
|
+
await pause();
|
|
358
375
|
if(canonicalJSON(read.records[root.journal.sequence+index])!==canonicalJSON(records[index]))refuse();
|
|
376
|
+
}
|
|
377
|
+
// #462: the journal this function compared must still be the journal it appends to after the yields above.
|
|
378
|
+
{const now=readPlacementJournal(this.home,this.epochHash);if(now.sequence!==read.sequence||now.headHash!==read.headHash||now.pending!==read.pending)refuse();read=now;}
|
|
359
379
|
if(read.pendingBatch){
|
|
360
380
|
const index=read.sequence-root.journal.sequence, end=index+read.pendingBatch.count;
|
|
361
381
|
if(read.pendingBatch.attemptHash!==root.seal || end>count || end>events.length)refuse();
|
|
362
382
|
appendPlacementEvents(this.home,this.epochHash,events.slice(index,end),read.headHash,this.storage(factual));read=readPlacementJournal(this.home,this.epochHash);
|
|
363
383
|
}else if(read.pending&&!read.pendingRecord&&formatFloorAtLeast(this.home,"sync","0.28.0")){
|
|
364
384
|
const index=read.sequence-root.journal.sequence;
|
|
365
|
-
|
|
366
|
-
|
|
385
|
+
// The storage writer compares the saved bytes against the exact canonical intent before writing.
|
|
386
|
+
// Try the current bounded batch and the unsliced batch used by older writers, in that order. A torn intent
|
|
387
|
+
// precedes every record write, so a prefix shared by both can safely complete the first slice and continue.
|
|
388
|
+
const ends=[Math.min(count,index+PLACEMENT_APPEND_SLICE),count];
|
|
389
|
+
for(const end of new Set(ends)) {
|
|
390
|
+
try { appendPlacementEvents(this.home,this.epochHash,events.slice(index,end),read.headHash,this.storage(factual));read=readPlacementJournal(this.home,this.epochHash);break; }
|
|
391
|
+
catch(error){ if(!(error instanceof SyncPlacementJournalError)||error.code!=="conflict")throw error; }
|
|
392
|
+
}
|
|
367
393
|
}
|
|
368
394
|
if(read.pending){
|
|
369
395
|
const sequence=read.pendingRecordSequence??read.sequence+1, index=sequence-root.journal.sequence-1;
|
|
@@ -374,9 +400,18 @@ class PlacementTransport {
|
|
|
374
400
|
this.progress?.advance(Math.max(0,Math.min(count,read.sequence-root.journal.sequence)));
|
|
375
401
|
const next=read.sequence-root.journal.sequence;
|
|
376
402
|
if(next<count&&formatFloorAtLeast(this.home,"sync","0.28.0")){
|
|
377
|
-
|
|
403
|
+
// #462: the same records in order, as consecutive atomic batches with a macrotask turn between them. A crash between
|
|
404
|
+
// batches leaves a durable prefix, which the `consumed` path above already resumes exactly as recorded.
|
|
405
|
+
for(let at=next;at<count;at+=PLACEMENT_APPEND_SLICE){
|
|
406
|
+
if(at>next)await yieldTurn();
|
|
407
|
+
const end=Math.min(count,at+PLACEMENT_APPEND_SLICE),from=readPlacementJournal(this.home,this.epochHash);
|
|
408
|
+
if(from.sequence!==root.journal.sequence+at)refuse();
|
|
409
|
+
appendPlacementEvents(this.home,this.epochHash,events.slice(at,end),from.headHash,this.storage(factual));this.progress?.advance(end-at);
|
|
410
|
+
}
|
|
411
|
+
return;
|
|
378
412
|
}
|
|
379
413
|
for(let index=next;index<count;index++){
|
|
414
|
+
await pause();
|
|
380
415
|
const record=records[index];if(!record)refuse();appendPlacementEvent(this.home,this.epochHash,events[index]!,record.previousHash,this.storage(factual));this.progress?.advance();
|
|
381
416
|
}
|
|
382
417
|
}
|
|
@@ -419,8 +454,8 @@ class PlacementTransport {
|
|
|
419
454
|
const old=await this.frozenOld(read.bundle),schedule=this.events(read.bundle,projection,old);
|
|
420
455
|
const sequence=before.pendingBatch ? before.sequence+before.pendingBatch.count : before.pendingRecordSequence??before.sequence+1;
|
|
421
456
|
if(!before.pendingRecord&&schedule.events[sequence-root.journal.sequence-1]?.kind!=="hold")refuse();
|
|
422
|
-
this.appendThrough(read.bundle,schedule.events,Math.max(holds.length,sequence-root.journal.sequence),true);
|
|
423
|
-
}else this.appendThrough(read.bundle,holds,holds.length,true);
|
|
457
|
+
await this.appendThrough(read.bundle,schedule.events,Math.max(holds.length,sequence-root.journal.sequence),true);
|
|
458
|
+
}else await this.appendThrough(read.bundle,holds,holds.length,true);
|
|
424
459
|
if(read.pendingPhase==="artifact-built"){
|
|
425
460
|
const guard=await this.installedObjectGuard(read.bundle);guard();
|
|
426
461
|
recordPlacementPublicationPhase(this.home,this.epochHash,root.seal,"artifact-built",{exportHash:hashJSON(root.targets.map(target=>target.exportSetHash))},this.storage(true));
|
|
@@ -451,7 +486,7 @@ class PlacementTransport {
|
|
|
451
486
|
}
|
|
452
487
|
async finish(material:Materialized,recovery=false):Promise<SyncResult>{
|
|
453
488
|
this.factual=true;this.recovered=recovery;const root=material.bundle.root;
|
|
454
|
-
await this.observe("before-ack");this.appendThrough(material.bundle,material.events,material.events.length,true);await this.observe("acknowledged");this.metadata();
|
|
489
|
+
await this.observe("before-ack");await this.appendThrough(material.bundle,material.events,material.events.length,true);await this.observe("acknowledged");this.metadata();
|
|
455
490
|
for (const [index,target] of this.targets.entries()) {
|
|
456
491
|
const planned = root.targets[index]!;
|
|
457
492
|
const head = planned.publish ? planned.commit : target.remote;
|
|
@@ -497,7 +532,10 @@ class PlacementTransport {
|
|
|
497
532
|
});
|
|
498
533
|
}
|
|
499
534
|
result(ok:boolean,outcome:"committed"|"unknown"|"not-needed",error?:string):SyncResult{
|
|
500
|
-
|
|
535
|
+
// #462: a closed cause on every failure; the most specific known fact wins.
|
|
536
|
+
const cause:SyncFailureCause|undefined=ok?undefined:this.opts.signal?.aborted?"stopped":this.bound?"bound":outcome==="unknown"?"unknown-outcome":this.failureCause??(this.refusal?"refusal":"unavailable");
|
|
537
|
+
return{ok,pushed:this.accepted&&(this.attempted||this.recovered&&!!this.current?.bundle.root.targets.some(target=>target.publish)),entries:this.current?.exported??0,...(error?{error}:{}),
|
|
538
|
+
...(cause?{failure:{cause,...(cause==="refusal"&&this.refusal?{category:this.refusal}:{})}}:{}),...(this.applications?{pruneApplication:{...this.applications.application}}:{}),
|
|
501
539
|
placementPublication:{...(this.attemptHash?{attemptHash:this.attemptHash}:{}),outcome,...(this.bound?{bound:this.bound}:{}),...(this.refusal?{refusal:{category:this.refusal,phase:this.phaseNow}}:{}),withheld:this.current?.withheld??0,exported:this.current?.exported??0,
|
|
502
540
|
...(this.lastPolicyHash?{lastPolicyHash:this.lastPolicyHash}:{}),...(this.lastPolicyCheckUnixMs!==undefined?{lastPolicyCheckUnixMs:this.lastPolicyCheckUnixMs,policyCheckSource:this.policyCheckSource??(this.recovered?"durable-intent" as const:"live" as const)}:{}),
|
|
503
541
|
policyCeiling:"last-positive-check-before-in-flight-push",...(this.recovered?{recovered:true}:{})}};
|
|
@@ -534,7 +572,7 @@ class PlacementTransport {
|
|
|
534
572
|
}
|
|
535
573
|
}
|
|
536
574
|
this.enter("source-capture");
|
|
537
|
-
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(); }
|
|
575
|
+
try { await yieldTurn();this.preflight();for(const target of this.targets)if(existsSync(join(target.store.dir,"local",`publisher-boundary-${this.machineId}.json`)))assertPublisherBoundary(target.store.profile,target.mutation!);await yieldTurn();await this.startCapture(); }
|
|
538
576
|
catch(error) { if(retained)return await this.terminalUnknown(retained);if(placementSyncBoundReceipt(error))throw error;throw new PlacementSyncRefusal(placementRefusalCategoryOf(error)??classifyPlacementError(error)??"other"); }
|
|
539
577
|
if(retained){
|
|
540
578
|
const root=retained.bundle.root;
|
|
@@ -546,13 +584,13 @@ class PlacementTransport {
|
|
|
546
584
|
const material=await this.materialize(retained?.bundle.root.createdUnixSeconds??Math.floor(Date.now()/1000),frontier,retained?.bundle);
|
|
547
585
|
const changed=material.bundle.root.targets.some((target,index)=>target.publish&&target.commit!==(this.targets[index]!.remote??null));
|
|
548
586
|
// Nothing durable exists for a fresh attempt yet: an epoch without room for this plan refuses here, typed.
|
|
549
|
-
if(!retained&&(material.events.length||changed))this.assertPlanCapacity(material.bundle);
|
|
587
|
+
await yieldTurn();if(!retained&&(material.events.length||changed))this.assertPlanCapacity(material.bundle);
|
|
550
588
|
this.current=material;this.attemptHash=material.bundle.root.seal;
|
|
551
|
-
const applications=await this.applicationCoordinator();await applications.prepare();
|
|
589
|
+
await yieldTurn();const applications=await this.applicationCoordinator();await applications.prepare();
|
|
552
590
|
if(!retained&&!material.events.length&&!changed&&!this.importsNeeded()){this.attemptHash=undefined;return this.result(true,"not-needed");}
|
|
553
|
-
if(!retained){await this.observe("before-plan-fsync");this.prove();preparePlacementPublication(this.home,material.bundle,this.storage());await this.observe("plan-fsynced");this.prove();}
|
|
591
|
+
if(!retained){await this.observe("before-plan-fsync");await yieldTurn();this.prove();preparePlacementPublication(this.home,material.bundle,this.storage());await this.observe("plan-fsynced");await yieldTurn();this.prove();}
|
|
554
592
|
// One mutation batch: a complete proof on each side, fence checks (and at most 1 s of proof reuse) per record.
|
|
555
|
-
this.prove();this.appendThrough(material.bundle,material.events,material.preCount);this.prove();
|
|
593
|
+
this.prove();await this.appendThrough(material.bundle,material.events,material.preCount);this.prove();
|
|
556
594
|
await this.materializeObjects(material.bundle);
|
|
557
595
|
let read=readPlacementPublication(this.home,this.epochHash,material.bundle.root.seal);
|
|
558
596
|
const artifact=read.facts.find(fact=>fact.phase==="artifact-built");if(!artifact)refuse();
|
|
@@ -574,13 +612,13 @@ class PlacementTransport {
|
|
|
574
612
|
try { this.testOnlyError?.(error); } catch { /* Test observers never alter production results. */ }
|
|
575
613
|
if(error&&typeof error==="object"&&!types.isProxy(error)&&error instanceof SharedWriterRevisionError){
|
|
576
614
|
const code=Object.getOwnPropertyDescriptor(error,"code")?.value;
|
|
577
|
-
if(code==="staging"||code==="pending")return this.result(false,this.attemptHash?"unknown":"not-needed",new SharedWriterRevisionError(code).message);
|
|
615
|
+
if(code==="staging"||code==="pending"){this.failureCause="writer-renewal";return this.result(false,this.attemptHash?"unknown":"not-needed",new SharedWriterRevisionError(code).message);}
|
|
578
616
|
}
|
|
579
617
|
// #419: an expected size refusal before any attempt exists keeps its phase, kind, limit and observed value.
|
|
580
618
|
const bound=this.attemptHash||this.journal?.publicationReservation?undefined:placementSyncBoundReceipt(error);
|
|
581
619
|
if(bound){this.bound=bound;return this.result(false,"not-needed",placementSyncBoundMessage(bound));}
|
|
582
620
|
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.");
|
|
583
|
-
if (error && typeof error === "object" && !types.isProxy(error) && error instanceof PlacementRealmRefusal && error.origin === "remote") return this.result(false, "not-needed", error.message);
|
|
621
|
+
if (error && typeof error === "object" && !types.isProxy(error) && error instanceof PlacementRealmRefusal && error.origin === "remote") { this.failureCause = "remote"; return this.result(false, "not-needed", error.message); }
|
|
584
622
|
// #426: name the failing check by a fixed category and the phase; never the error's own text, which may carry a path.
|
|
585
623
|
this.refusal=placementRefusalCategoryOf(error)??classifyPlacementError(error)??"other";
|
|
586
624
|
return this.result(false,"not-needed",placementRefusalMessage(this.refusal,this.phaseNow));
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #462: cooperative slicing for long synchronous placement-sync loops. A library caller (the hub daemon, the MCP
|
|
3
|
+
* server, the CLI) shares its event loop with `syncMemory`; every loop that can run per row, per object or per file
|
|
4
|
+
* awaits this between items so the caller's loop gets control back at least every `PLACEMENT_SLICE_MS` of work.
|
|
5
|
+
*
|
|
6
|
+
* Yielding never changes a result: every fence and proof check that guarded the next item still runs after the
|
|
7
|
+
* yield, exactly as before. Only scheduling changes.
|
|
8
|
+
*
|
|
9
|
+
* ponytail: the slice is checked between items, so one item's own cost (one complete writer proof, one Git history
|
|
10
|
+
* tree) is the floor of the longest stretch. Moving per-item proofs off the caller's thread is the upgrade path.
|
|
11
|
+
*/
|
|
12
|
+
export const PLACEMENT_SLICE_MS = 50;
|
|
13
|
+
|
|
14
|
+
/** A time-budgeted yield point: cheap when the slice has room left, one macrotask turn when it has run out. */
|
|
15
|
+
export type CooperativeYield = () => Promise<void>;
|
|
16
|
+
|
|
17
|
+
export function cooperativeYield(budgetMs = PLACEMENT_SLICE_MS, now: () => number = () => performance.now()): CooperativeYield {
|
|
18
|
+
let started = now();
|
|
19
|
+
return async () => {
|
|
20
|
+
if (now() - started < budgetMs) return;
|
|
21
|
+
await new Promise<void>(resolve => setImmediate(resolve));
|
|
22
|
+
started = now();
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** One unconditional macrotask turn, placed between discrete heavy steps (a journal read, a writer proof, a capture). */
|
|
27
|
+
export const yieldTurn = (): Promise<void> => new Promise<void>(resolve => setImmediate(resolve));
|
|
28
|
+
|
|
29
|
+
/** Journal records per atomic batch append before the next turn; the on-disk layout is the same as one batch (greedy chunk fill). */
|
|
30
|
+
export const PLACEMENT_APPEND_SLICE = 50;
|
|
@@ -23,6 +23,13 @@ export type SyncProgressUnit = typeof UNITS[number];
|
|
|
23
23
|
export type SyncProgressState = typeof STATES[number];
|
|
24
24
|
export type SyncProgressCause = typeof CAUSES[number];
|
|
25
25
|
export interface SyncProgressCounts { permitted: number; local: number; declined: number; held: number }
|
|
26
|
+
export interface SyncProgressInventory { publications: number; completed: number; realms: number;
|
|
27
|
+
/** Per-realm outcomes in run order: `user` or the 16-hex shard key hash, never a name. At most 32; `truncated` marks more. */
|
|
28
|
+
outcomes?: { realm: string; outcome: SyncRealmOutcome }[]; truncated?: boolean }
|
|
29
|
+
export const SYNC_REALM_OUTCOMES = ["committed", "not-needed", "unknown", "failed", "not-run", "not-local", "inactive"] as const;
|
|
30
|
+
export type SyncRealmOutcome = typeof SYNC_REALM_OUTCOMES[number];
|
|
31
|
+
const MAX_REALM_OUTCOMES = 32;
|
|
32
|
+
const realmLabel = (value: unknown): value is string => typeof value === "string" && (value === "user" || /^[a-f0-9]{16}$/.test(value));
|
|
26
33
|
export interface SyncProgressSnapshot {
|
|
27
34
|
schema: typeof SYNC_PROGRESS_SCHEMA; operationId: string; state: SyncProgressState; phase: SyncProgressPhase;
|
|
28
35
|
/** How many times this operation entered this phase; completed counts are monotonic within one phase attempt. */
|
|
@@ -35,6 +42,8 @@ export interface SyncProgressSnapshot {
|
|
|
35
42
|
proofs: { complete: number; fence: number };
|
|
36
43
|
/** Advances only when a unit of work or a phase completes; `lastAliveUnixMs` is any checkpoint the process reached. */
|
|
37
44
|
lastWorkProgressUnixMs: number; lastAliveUnixMs: number;
|
|
45
|
+
/** #450: a whole-inventory run of sequential publications; counts only, never a realm name or key. */
|
|
46
|
+
inventory?: SyncProgressInventory;
|
|
38
47
|
cause?: SyncProgressCause;
|
|
39
48
|
/** #426: for a failed placement sync, the fixed category of the check that refused (allowlisted, no text). */
|
|
40
49
|
category?: PlacementRefusalCategory;
|
|
@@ -51,6 +60,8 @@ export class SyncProgress {
|
|
|
51
60
|
private unit?: SyncProgressUnit; private completed?: number; private total?: number; private outcome?: SyncProgressCounts;
|
|
52
61
|
private state: SyncProgressState = "running"; private cause?: SyncProgressCause; private category?: PlacementRefusalCategory; private work: number; private aliveAt: number;
|
|
53
62
|
private readonly proofs = { complete: 0, fence: 0 };
|
|
63
|
+
private inventoryCounts?: SyncProgressInventory; private finishDeferred = false;
|
|
64
|
+
private pendingTerminal?: { state: "failed" | "cancelled"; cause?: SyncProgressCause; category?: PlacementRefusalCategory };
|
|
54
65
|
constructor(options: SyncProgressOptions) {
|
|
55
66
|
this.sink = options.sink; this.intervalMs = Math.max(0, options.intervalMs ?? SYNC_PROGRESS_INTERVAL_MS);
|
|
56
67
|
this.now = options.now ?? Date.now; this.mono = options.mono ?? (() => performance.now());
|
|
@@ -63,7 +74,7 @@ export class SyncProgress {
|
|
|
63
74
|
startedUnixMs: this.started, elapsedMs: Math.round(mono - this.startedMono), phaseElapsedMs: Math.round(mono - this.phaseMono),
|
|
64
75
|
...(this.unit ? { unit: this.unit, completed: this.completed ?? 0, ...(this.total !== undefined ? { total: this.total } : {}) } : {}),
|
|
65
76
|
...(this.outcome ? { counts: { ...this.outcome } } : {}), proofs: { ...this.proofs },
|
|
66
|
-
lastWorkProgressUnixMs: this.work, lastAliveUnixMs: this.aliveAt, ...(this.cause ? { cause: this.cause } : {}), ...(this.category ? { category: this.category } : {}) };
|
|
77
|
+
lastWorkProgressUnixMs: this.work, lastAliveUnixMs: this.aliveAt, ...(this.inventoryCounts ? { inventory: { ...this.inventoryCounts } } : {}), ...(this.cause ? { cause: this.cause } : {}), ...(this.category ? { category: this.category } : {}) };
|
|
67
78
|
}
|
|
68
79
|
private emit(force: boolean): void {
|
|
69
80
|
if (!this.sink) return; const mono = this.mono();
|
|
@@ -82,9 +93,30 @@ export class SyncProgress {
|
|
|
82
93
|
alive(): void { if (this.state !== "running") return; this.aliveAt = this.now(); this.emit(false); }
|
|
83
94
|
proof(complete: boolean): void { this.proofs[complete ? "complete" : "fence"]++; this.alive(); }
|
|
84
95
|
counts(counts: SyncProgressCounts): void { this.outcome = { ...counts }; }
|
|
96
|
+
/** #450: whole-inventory position. A completed publication is work progress for the run. */
|
|
97
|
+
inventory(value: SyncProgressInventory): void {
|
|
98
|
+
if (this.state !== "running" || ![value.publications, value.completed, value.realms].every(n => Number.isSafeInteger(n) && n >= 0) || value.completed > value.publications) return;
|
|
99
|
+
const outcomes = value.outcomes?.filter(item => realmLabel(item.realm) && (SYNC_REALM_OUTCOMES as readonly string[]).includes(item.outcome)) ?? [];
|
|
100
|
+
this.inventoryCounts = { publications: value.publications, completed: value.completed, realms: value.realms,
|
|
101
|
+
...(outcomes.length ? { outcomes: outcomes.slice(0, MAX_REALM_OUTCOMES).map(item => ({ ...item })) } : {}), ...(outcomes.length > MAX_REALM_OUTCOMES || value.truncated ? { truncated: true } : {}) };
|
|
102
|
+
this.work = this.aliveAt = this.now(); this.emit(true);
|
|
103
|
+
}
|
|
104
|
+
/** #450: an inventory driver records all realm outcomes before the first terminal state is emitted. */
|
|
105
|
+
deferFinish(deferred: boolean): void {
|
|
106
|
+
this.finishDeferred = deferred;
|
|
107
|
+
if (!deferred && this.pendingTerminal) {
|
|
108
|
+
const pending = this.pendingTerminal; this.pendingTerminal = undefined;
|
|
109
|
+
this.finish(pending.state, pending.cause, pending.category);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
85
112
|
/** Terminal state. Success is reported only by the caller that holds the real sync receipt. */
|
|
86
113
|
finish(state: Exclude<SyncProgressState, "running" | "interrupted">, cause?: SyncProgressCause, category?: PlacementRefusalCategory): void {
|
|
87
|
-
if (this.state !== "running") return;
|
|
114
|
+
if (this.state !== "running") return;
|
|
115
|
+
if (this.finishDeferred) {
|
|
116
|
+
if (state !== "succeeded" && !this.pendingTerminal) this.pendingTerminal = { state, cause, category };
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
this.state = state; this.cause = state === "succeeded" ? undefined : cause;
|
|
88
120
|
this.category = state === "failed" && category && (PLACEMENT_REFUSAL_CATEGORIES as readonly string[]).includes(category) ? category : undefined; this.aliveAt = this.now();
|
|
89
121
|
if (state === "succeeded") this.work = this.aliveAt; this.emit(true);
|
|
90
122
|
}
|
|
@@ -96,8 +128,10 @@ export function renderSyncProgress(snapshot: SyncProgressSnapshot, now = Date.no
|
|
|
96
128
|
const phase = snapshot.phase.replaceAll("-", " "), units = snapshot.unit ? `: ${snapshot.completed ?? 0}${snapshot.total !== undefined ? `/${snapshot.total}` : ""} ${snapshot.unit}` : "";
|
|
97
129
|
const counts = snapshot.counts ? `; permitted ${snapshot.counts.permitted}, local ${snapshot.counts.local}, declined ${snapshot.counts.declined}, held ${snapshot.counts.held}` : "";
|
|
98
130
|
const attempt = snapshot.attempt > 1 ? `; attempt ${snapshot.attempt}` : "";
|
|
99
|
-
|
|
100
|
-
|
|
131
|
+
const realmText = snapshot.inventory?.outcomes?.length ? `; realms ${snapshot.inventory.outcomes.map(item => `${item.realm}=${item.outcome}`).join(" ")}${snapshot.inventory.truncated ? " ..." : ""}` : "";
|
|
132
|
+
const inventory = snapshot.inventory ? `; publications ${snapshot.inventory.completed}/${snapshot.inventory.publications} over ${snapshot.inventory.realms} realms${realmText}` : "";
|
|
133
|
+
if (snapshot.state !== "running") return `amem sync: ${snapshot.state}${snapshot.cause ? ` (${snapshot.cause}${snapshot.category ? `, ${snapshot.category}` : ""})` : ""} in ${phase}${units}${counts}${inventory}; elapsed ${seconds(snapshot.elapsedMs)}`;
|
|
134
|
+
return `amem sync: ${phase}${units}${attempt}${counts}${inventory}; elapsed ${seconds(snapshot.elapsedMs)}; last work progress ${seconds(now - snapshot.lastWorkProgressUnixMs)} ago`;
|
|
101
135
|
}
|
|
102
136
|
|
|
103
137
|
interface Owner { pid: number; signature?: string }
|
|
@@ -125,19 +159,26 @@ const count = (value: unknown): value is number => typeof value === "number" &&
|
|
|
125
159
|
/** Allowlisted enumerations and non-negative integers only: a tampered sidecar cannot inject text into a terminal. */
|
|
126
160
|
function validate(value: unknown, operationId: string): { snapshot: SyncProgressSnapshot; owner: Owner } | undefined {
|
|
127
161
|
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
128
|
-
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;
|
|
162
|
+
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, inventory = v.inventory as Record<string, unknown> | undefined;
|
|
129
163
|
if (v.schema !== SYNC_PROGRESS_SCHEMA || v.operationId !== operationId || !(STATES as readonly unknown[]).includes(v.state) || !(PHASES as readonly unknown[]).includes(v.phase)
|
|
130
164
|
|| ![v.attempt, v.startedUnixMs, v.elapsedMs, v.phaseElapsedMs, v.lastWorkProgressUnixMs, v.lastAliveUnixMs].every(count)
|
|
131
165
|
|| !proofs || !count(proofs.complete) || !count(proofs.fence) || !owner || !count(owner.pid) || owner.signature !== undefined && (typeof owner.signature !== "string" || owner.signature.length > 256)
|
|
132
166
|
|| v.unit !== undefined && (!(UNITS as readonly unknown[]).includes(v.unit) || !count(v.completed)) || v.total !== undefined && !count(v.total)
|
|
133
167
|
|| v.cause !== undefined && !(CAUSES as readonly unknown[]).includes(v.cause)
|
|
134
168
|
|| v.category !== undefined && !(PLACEMENT_REFUSAL_CATEGORIES as readonly unknown[]).includes(v.category)
|
|
135
|
-
|| counts !== undefined && ![counts.permitted, counts.local, counts.declined, counts.held].every(count)
|
|
169
|
+
|| counts !== undefined && ![counts.permitted, counts.local, counts.declined, counts.held].every(count)
|
|
170
|
+
|| inventory !== undefined && (!inventory || typeof inventory !== "object" || ![inventory.publications, inventory.completed, inventory.realms].every(count) || (inventory.completed as number) > (inventory.publications as number)
|
|
171
|
+
|| inventory.truncated !== undefined && inventory.truncated !== true
|
|
172
|
+
|| inventory.outcomes !== undefined && (!Array.isArray(inventory.outcomes) || inventory.outcomes.length > MAX_REALM_OUTCOMES
|
|
173
|
+
|| inventory.outcomes.some((item: unknown) => !item || typeof item !== "object" || !realmLabel((item as { realm?: unknown }).realm) || !(SYNC_REALM_OUTCOMES as readonly unknown[]).includes((item as { outcome?: unknown }).outcome))))) return undefined;
|
|
136
174
|
const snapshot: SyncProgressSnapshot = { schema: SYNC_PROGRESS_SCHEMA, operationId, state: v.state as SyncProgressState, phase: v.phase as SyncProgressPhase, attempt: v.attempt as number,
|
|
137
175
|
startedUnixMs: v.startedUnixMs as number, elapsedMs: v.elapsedMs as number, phaseElapsedMs: v.phaseElapsedMs as number,
|
|
138
176
|
...(v.unit !== undefined ? { unit: v.unit as SyncProgressUnit, completed: v.completed as number, ...(v.total !== undefined ? { total: v.total as number } : {}) } : {}),
|
|
139
177
|
...(counts ? { counts: { permitted: counts.permitted as number, local: counts.local as number, declined: counts.declined as number, held: counts.held as number } } : {}),
|
|
140
178
|
proofs: { complete: proofs.complete as number, fence: proofs.fence as number }, lastWorkProgressUnixMs: v.lastWorkProgressUnixMs as number, lastAliveUnixMs: v.lastAliveUnixMs as number,
|
|
179
|
+
...(inventory ? { inventory: { publications: inventory.publications as number, completed: inventory.completed as number, realms: inventory.realms as number,
|
|
180
|
+
...(Array.isArray(inventory.outcomes) ? { outcomes: (inventory.outcomes as { realm: string; outcome: SyncRealmOutcome }[]).map(item => ({ realm: item.realm, outcome: item.outcome })) } : {}),
|
|
181
|
+
...(inventory.truncated === true ? { truncated: true } : {}) } } : {}),
|
|
141
182
|
...(v.cause !== undefined ? { cause: v.cause as SyncProgressCause } : {}), ...(v.category !== undefined ? { category: v.category as PlacementRefusalCategory } : {}) };
|
|
142
183
|
return { snapshot, owner: { pid: owner.pid as number, ...(typeof owner.signature === "string" ? { signature: owner.signature } : {}) } };
|
|
143
184
|
}
|
package/src/memory/sync.ts
CHANGED
|
@@ -22,7 +22,18 @@ import type { PlacementRefusalCategory } from "./sync-placement-refusal.ts";
|
|
|
22
22
|
* machine's history never conflicts. Pull, then push; fail-open: a failure is a result with one reason, never a throw.
|
|
23
23
|
*/
|
|
24
24
|
export type Visibility = "public" | "private" | "unknown";
|
|
25
|
+
/**
|
|
26
|
+
* #462: the closed cause class of a placement sync that did not succeed, so a host can name the next step without
|
|
27
|
+
* parsing `error` text. `bound` carries its numbers in `placementPublication.bound`; `refusal` carries its fixed
|
|
28
|
+
* category; `unavailable` is any other refusal before an attempt (activation, inventory or I/O).
|
|
29
|
+
*/
|
|
30
|
+
export const SYNC_FAILURE_CAUSES = ["bound", "refusal", "unknown-outcome", "writer-renewal", "remote", "stopped", "unavailable"] as const;
|
|
31
|
+
export type SyncFailureCause = typeof SYNC_FAILURE_CAUSES[number];
|
|
25
32
|
export interface SyncResult { ok: boolean; pushed: boolean; entries: number; warning?: string; error?: string;
|
|
33
|
+
/** #462: set on every failed placement sync; absent on success and on the legacy transports. */
|
|
34
|
+
failure?: { cause: SyncFailureCause; category?: PlacementRefusalCategory };
|
|
35
|
+
/** #450: per-realm outcomes of a whole-inventory placement sync, in run order (`user` or the full realm key hash). */
|
|
36
|
+
placementRealms?: { realm: string; outcome: "committed" | "not-needed" | "unknown" | "failed" | "not-run" | "not-local" | "inactive"; publication?: number }[];
|
|
26
37
|
placementPublication?: { attemptHash?: string; outcome: "committed" | "unknown" | "not-needed"; withheld: number; exported: number;
|
|
27
38
|
lastPolicyHash?: string; lastPolicyCheckUnixMs?: number; policyCheckSource?: "live" | "durable-intent"; policyCeiling: "last-positive-check-before-in-flight-push"; recovered?: boolean;
|
|
28
39
|
/** #419: an expected size refusal before any publication attempt; numbers only. */
|
|
@@ -267,7 +278,18 @@ export async function syncMemory(store: MemoryStore, opts: SyncOptions = {}): Pr
|
|
|
267
278
|
assertFormatFloor(store.profile.home, "sync");
|
|
268
279
|
const placementRefusal = placementRuntimeRefusal(store.profile.home, store.profile);
|
|
269
280
|
if (placementRefusal) return { ok: false, pushed: false, entries: 0, error: placementRefusal };
|
|
270
|
-
if (store.profile.publicationFormat === "agent-mem.sync-placement/v1")
|
|
281
|
+
if (store.profile.publicationFormat === "agent-mem.sync-placement/v1") {
|
|
282
|
+
// #450: the whole activated inventory, independent of the binding that opened `store`.
|
|
283
|
+
const [{ syncPlacementInventory }, { syncPlacementMemory }, { openShardStore }] = await Promise.all([import("./sync-placement-inventory.ts"), import("./sync-placement-transport.ts"), import("./store.ts")]);
|
|
284
|
+
const home = store.profile.home, held = store.openedSyncTargets(), opened = new Set<MemoryStore>();
|
|
285
|
+
// A realm the caller already holds is reused (no second lease or fence file); others are opened and closed per publication.
|
|
286
|
+
const reuse = (realm: { scope: "user" } | { scope: "project"; key: string }) => held.find(item => realm.scope === "user" ? item.profile.shardUser : !item.profile.shardUser && item.profile.shardKey === realm.key);
|
|
287
|
+
return syncPlacementInventory(home, opts, {
|
|
288
|
+
open: realm => reuse(realm) ?? (() => { const fresh = openShardStore({ memoryDir: home, deferPromotions: true, ...(realm.scope === "user" ? { user: true } : { project: realm.key }) }); opened.add(fresh); return fresh; })(),
|
|
289
|
+
close: item => { if (opened.delete(item)) item.close(); },
|
|
290
|
+
publish: (primary, targets, options) => syncPlacementMemory(primary, options, undefined, undefined, undefined, targets),
|
|
291
|
+
});
|
|
292
|
+
}
|
|
271
293
|
if (opts.signal?.aborted) return { ok: false, pushed: false, entries: 0, error: "stopped" };
|
|
272
294
|
if (!opts.remote) {
|
|
273
295
|
try {
|