@staix/agent-mem 0.28.2 → 0.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +17 -11
- package/package.json +3 -2
- package/src/brief-work.ts +142 -0
- package/src/cli.ts +97 -17
- package/src/commands-table.ts +6 -0
- package/src/mcp-memory.ts +37 -9
- package/src/memory/bridge.ts +26 -1
- package/src/memory/capacity.ts +5 -2
- package/src/memory/catalog.ts +10 -1
- package/src/memory/commands.ts +5 -3
- package/src/memory/curated-cache-state.ts +10 -7
- package/src/memory/doctor.ts +32 -26
- package/src/memory/formats.ts +4 -3
- package/src/memory/generation-index.ts +79 -17
- package/src/memory/index-file.ts +2 -2
- package/src/memory/intent-brief.ts +34 -6
- package/src/memory/metrics.ts +174 -14
- package/src/memory/shard-bridge.ts +18 -6
- package/src/memory/shard-sync-format.ts +18 -0
- package/src/memory/shard-sync-history.ts +6 -0
- package/src/memory/shard-sync.ts +52 -4
- package/src/memory/shard.ts +33 -13
- package/src/memory/store.ts +147 -41
- package/src/memory/sync-placement-bound.ts +21 -4
- package/src/memory/sync-placement-cache.ts +16 -1
- package/src/memory/sync-placement-capture.ts +67 -19
- package/src/memory/sync-placement-checkpoint-format.ts +199 -0
- package/src/memory/sync-placement-checkpoint-person.ts +209 -0
- package/src/memory/sync-placement-checkpoint-prospective.ts +141 -0
- package/src/memory/sync-placement-checkpoint-storage.ts +218 -0
- package/src/memory/sync-placement-checkpoint.ts +234 -0
- package/src/memory/sync-placement-dependencies.ts +42 -9
- package/src/memory/sync-placement-effective-writers.ts +12 -6
- package/src/memory/sync-placement-git.ts +17 -7
- package/src/memory/sync-placement-guard.ts +52 -1
- package/src/memory/sync-placement-inspection-evidence.ts +1 -1
- package/src/memory/sync-placement-inventory.ts +141 -0
- package/src/memory/sync-placement-journal-format.ts +4 -1
- package/src/memory/sync-placement-journal-storage.ts +148 -28
- package/src/memory/sync-placement-journal.ts +13 -4
- package/src/memory/sync-placement-materialize.ts +47 -22
- package/src/memory/sync-placement-projection.ts +7 -1
- package/src/memory/sync-placement-publication-events.ts +42 -0
- package/src/memory/sync-placement-publication-plan.ts +26 -5
- package/src/memory/sync-placement-realm-admission-storage.ts +128 -0
- package/src/memory/sync-placement-realm-admission.ts +352 -0
- package/src/memory/sync-placement-realm-attribution.ts +23 -0
- package/src/memory/sync-placement-realm-discovery.ts +42 -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-remote-admission.ts +190 -0
- package/src/memory/sync-placement-remote-adoption-format.ts +54 -0
- package/src/memory/sync-placement-remote-materialization.ts +49 -0
- package/src/memory/sync-placement-remote-refusal.ts +21 -0
- package/src/memory/sync-placement-remote-stage.ts +275 -0
- package/src/memory/sync-placement-transport.ts +268 -79
- package/src/memory/sync-placement-writer-history.ts +75 -17
- package/src/memory/sync-placement-writer-renewal.ts +18 -10
- package/src/memory/sync-placement-writer-revision-format.ts +16 -13
- package/src/memory/sync-placement-yield.ts +44 -0
- package/src/memory/sync-progress.ts +47 -6
- package/src/memory/sync.ts +26 -1
- package/src/memory/work-lists.ts +129 -9
- package/src/session-brief.ts +34 -1
- package/src/sync-placement-writer-context.ts +5 -5
- package/src/ui/plugin.ts +1 -1
|
@@ -6,6 +6,9 @@ import { types } from "node:util";
|
|
|
6
6
|
import { canonicalJSON } from "./generation.ts";
|
|
7
7
|
import { homeIdentityMatches } from "./home-identity.ts";
|
|
8
8
|
import { realPath } from "./platform.ts";
|
|
9
|
+
import { placementWindowToken, resolvePlacementWindow, type ResolvedPlacementWindow } from "./sync-placement-checkpoint-storage.ts";
|
|
10
|
+
import { checkpointWriterGenesis } from "./sync-placement-checkpoint-format.ts";
|
|
11
|
+
import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
|
|
9
12
|
import { assertMutationHandle, type MutationHandle } from "./mutation.ts";
|
|
10
13
|
import {
|
|
11
14
|
WRITER_REVISION_MAX_BYTES, WRITER_COMMIT_MAX_BYTES, WRITER_RENEWAL_INTENT_MAX_BYTES, WRITER_REVISION_LIMIT,
|
|
@@ -19,7 +22,7 @@ export type WriterHistoryPhase = "intent-started" | "intent-written" | "intent-f
|
|
|
19
22
|
export interface WriterHistoryOptions { mutation: MutationHandle; assertCurrent(): void; phase?(phase: WriterHistoryPhase): void }
|
|
20
23
|
export interface WriterHistoryRead {
|
|
21
24
|
current?: WriterRevision; commits: WriterCommit[]; anchors: { sequence: number; headHash: string }[];
|
|
22
|
-
sequence: number; headHash: string; logBytes: number; logHash: string; pending?: WriterRenewalIntent; appendStarted: boolean; assertCurrent(): void;
|
|
25
|
+
sequence: number; headHash: string; window: number; genesis: string; logBytes: number; logHash: string; pending?: WriterRenewalIntent; appendStarted: boolean; assertCurrent(): void;
|
|
23
26
|
}
|
|
24
27
|
const encode = (value: unknown) => Buffer.from(canonicalJSON(value) + "\n");
|
|
25
28
|
const sha = (value: Uint8Array) => createHash("sha256").update(value).digest("hex");
|
|
@@ -30,7 +33,7 @@ function safe<T>(work: () => T): T {
|
|
|
30
33
|
try { return work(); } catch (error) {
|
|
31
34
|
if (error && typeof error === "object" && !types.isProxy(error) && error instanceof SharedWriterRevisionError) {
|
|
32
35
|
const code=Object.getOwnPropertyDescriptor(error,"code");
|
|
33
|
-
if(code&&"value"in code&&["invalid","bound","changed","pending","staging","cap"].includes(code.value))throw new SharedWriterRevisionError(code.value);
|
|
36
|
+
if(code&&"value"in code&&["invalid","bound","changed","pending","checkpoint-pending","staging","cap"].includes(code.value))throw new SharedWriterRevisionError(code.value);
|
|
34
37
|
}
|
|
35
38
|
return fail();
|
|
36
39
|
}
|
|
@@ -68,13 +71,49 @@ function binding(value: WriterHistoryBinding): WriterHistoryBinding {
|
|
|
68
71
|
const locator=descriptors.initialLocatorHash;if(locator){if(!("value"in locator)||!locator.enumerable||typeof locator.value!=="string"||locator.value.length!==64||!/^[a-f0-9]+$/.test(locator.value))fail();result.initialLocatorHash=locator.value;}
|
|
69
72
|
return result as unknown as WriterHistoryBinding;
|
|
70
73
|
}
|
|
71
|
-
interface Paths { home: string; epoch: string; intent: string; log: string; dirs: [string,BigIntStats][] }
|
|
74
|
+
interface Paths { home: string; epoch: string; intent: string; log: string; dirs: [string,BigIntStats][]; window: ResolvedPlacementWindow; genesis: string }
|
|
72
75
|
function paths(homeInput: string, input: WriterHistoryBinding): Paths {
|
|
73
76
|
const home=realPath(homeInput), original=checkedDir(homeInput), root=checkedDir(home);
|
|
74
77
|
if(identity(original)!==identity(root)||!homeIdentityMatches(input.homeHash,home,root))fail("changed");
|
|
78
|
+
// #288: the one window resolver names the live window; window 0 is the v1 epoch directory.
|
|
79
|
+
let window:ResolvedPlacementWindow;try{window=resolvePlacementWindow(home,input.epochHash);}catch(error){throw checkpointError(error);}
|
|
80
|
+
if(window.pending)throw new SharedWriterRevisionError("checkpoint-pending"); // A started checkpoint owns the writer chain until resume or abandon.
|
|
75
81
|
const dirs:[string,BigIntStats][]=[[home,root]];
|
|
76
|
-
|
|
77
|
-
|
|
82
|
+
for(const dir of [...window.parents.slice(1),window.dir])dirs.push([dir,checkedDir(dir)]);
|
|
83
|
+
const manifest=window.manifests.at(-1);
|
|
84
|
+
const genesis=manifest?checkpointWriterGenesis(input.epochHash,input.activationHash,manifest.seal,manifest.writer.headHash):writerInventoryGenesis(input.epochHash,input.activationHash);
|
|
85
|
+
return {home,epoch:window.dir,intent:join(home,WRITER_RENEWAL_INTENT_FILE),log:join(window.dir,WRITER_COMMIT_LOG),dirs,window,genesis};
|
|
86
|
+
}
|
|
87
|
+
/** A checkpoint pending or broken refuses writer history the same way the journal does: pending, else invalid. */
|
|
88
|
+
function checkpointError(error:unknown):SharedWriterRevisionError{
|
|
89
|
+
const code=error&&typeof error==="object"&&!types.isProxy(error)&&error instanceof SyncPlacementJournalError?Object.getOwnPropertyDescriptor(error,"code")?.value:undefined;
|
|
90
|
+
return new SharedWriterRevisionError(code==="pending"?"checkpoint-pending":code==="bound"?"bound":code==="changed"?"changed":"invalid");
|
|
91
|
+
}
|
|
92
|
+
interface ArchivedWriters { commits: WriterCommit[]; anchors: {sequence:number;headHash:string}[]; current?: WriterRevision }
|
|
93
|
+
/**
|
|
94
|
+
* Writer history of every frozen window, rechecked against each window's genesis and the manifest that froze it. Members
|
|
95
|
+
* were content-verified by the resolver; this only replays their chain. The logical chain continues across windows.
|
|
96
|
+
*/
|
|
97
|
+
function archivedWriters(p:Paths,b:WriterHistoryBinding):ArchivedWriters {
|
|
98
|
+
const out:ArchivedWriters={commits:[],anchors:[]};let genesis=writerInventoryGenesis(b.epochHash,b.activationHash),previous=0;
|
|
99
|
+
for(const [index,window] of p.window.archived.entries()){
|
|
100
|
+
const manifest=p.window.manifests[index]!,names=new Set(window.members.map(member=>member.name));
|
|
101
|
+
let head=genesis,local=0;
|
|
102
|
+
if(names.has(WRITER_COMMIT_LOG)){
|
|
103
|
+
const log=read(join(window.dir,WRITER_COMMIT_LOG),WRITER_COMMIT_MAX_BYTES)?.bytes??fail();if(!log.length||log.at(-1)!==10)fail();
|
|
104
|
+
let at=0;while(at<log.length){const end=log.indexOf(10,at);const commit=decode(log.subarray(at,end+1),validateWriterCommit);at=end+1;
|
|
105
|
+
if(++local>WRITER_REVISION_LIMIT||commit.epochHash!==b.epochHash||commit.sequence!==local||commit.previousHash!==head)fail();
|
|
106
|
+
const revision=decode(read(join(window.dir,writerRevisionFile(local)),WRITER_REVISION_MAX_BYTES)?.bytes??fail(),value=>validateWriterRevision(value,genesis));boundRevision(revision,b);
|
|
107
|
+
if(revision.previousHash!==head||canonicalJSON(createWriterCommit(revision,genesis))!==canonicalJSON(commit))fail();
|
|
108
|
+
if(out.current&&revision.initialLocatorHash!==out.current.initialLocatorHash)fail();
|
|
109
|
+
if(revision.journal.sequence<previous)fail();previous=revision.journal.sequence;
|
|
110
|
+
out.anchors.push({...revision.journal});out.commits.push(commit);out.current=revision;head=commit.seal;}
|
|
111
|
+
}
|
|
112
|
+
for(const name of names)if(name.startsWith("writer-")&&name!==WRITER_COMMIT_LOG&&!(/^writer-revision-(\d{5})\.json$/.test(name)&&Number(name.slice(16,21))<=local))fail();
|
|
113
|
+
if(manifest.writer.headHash!==head||manifest.writer.sequence!==out.commits.length)fail();
|
|
114
|
+
genesis=checkpointWriterGenesis(b.epochHash,b.activationHash,manifest.seal,head);
|
|
115
|
+
}
|
|
116
|
+
return out;
|
|
78
117
|
}
|
|
79
118
|
function manifest(p: Paths): string[] {
|
|
80
119
|
const iterator=opendirSync(p.epoch), names:string[]=[]; let count=0;
|
|
@@ -86,8 +125,17 @@ function boundRevision(revision: WriterRevision,b:WriterHistoryBinding):void {
|
|
|
86
125
|
if(revision.epochHash!==b.epochHash||revision.activationHash!==b.activationHash||revision.homeHash!==b.homeHash||revision.generation!==b.generation||b.initialLocatorHash!==undefined&&revision.initialLocatorHash!==b.initialLocatorHash)fail();
|
|
87
126
|
}
|
|
88
127
|
function intentBinding(intent:WriterRenewalIntent):WriterHistoryBinding {const r=intent.revision;return {epochHash:r.epochHash,activationHash:r.activationHash,homeHash:r.homeHash,generation:r.generation};}
|
|
128
|
+
/**
|
|
129
|
+
* #288: a window's first revision starts at that window's genesis, which only the resolver knows. Codec validation here
|
|
130
|
+
* accepts the revision's own first link; every snapshot then requires it to equal the live window's genesis (beforeHead).
|
|
131
|
+
*/
|
|
132
|
+
function intentCodec(value:unknown):WriterRenewalIntent {
|
|
133
|
+
let genesis:string|undefined;
|
|
134
|
+
try{const revision=(value as {revision?:{sequence?:unknown;previousHash?:unknown}}).revision;if(revision?.sequence===1&&typeof revision.previousHash==="string")genesis=revision.previousHash;}catch{fail();}
|
|
135
|
+
return validateWriterRenewalIntent(value,genesis);
|
|
136
|
+
}
|
|
89
137
|
/** Exact basename reserved alongside the final outside intent during atomic publication. */
|
|
90
|
-
export function writerRenewalIntentTempName(value:WriterRenewalIntent):string {return WRITER_RENEWAL_INTENT_FILE+".pending-"+sha(encode(
|
|
138
|
+
export function writerRenewalIntentTempName(value:WriterRenewalIntent):string {return WRITER_RENEWAL_INTENT_FILE+".pending-"+sha(encode(intentCodec(value)));}
|
|
91
139
|
export function isWriterRenewalIntentTempName(name:string):boolean {const match=new RegExp("^"+WRITER_RENEWAL_INTENT_FILE.replaceAll(".","\\.")+"\\.pending-[a-f0-9]{64}$").exec(name);return !!match&&match[0]===name;}
|
|
92
140
|
function intentTemps(p:Paths):string[]{
|
|
93
141
|
const iterator=opendirSync(p.home),out:string[]=[];let count=0,bytes=0;
|
|
@@ -105,7 +153,7 @@ function readIntent(p:Paths,checks:(()=>void)[],expected?:WriterRenewalIntent,ig
|
|
|
105
153
|
const file=final??staging!;
|
|
106
154
|
let intent:WriterRenewalIntent;
|
|
107
155
|
if(expected){const full=encode(expected);if(file.bytes.length>full.length||!file.bytes.equals(full.subarray(0,file.bytes.length)))fail();intent=expected;}
|
|
108
|
-
else {try{intent=decode(file.bytes,
|
|
156
|
+
else {try{intent=decode(file.bytes,intentCodec);}catch{fail("pending");}}
|
|
109
157
|
const full=encode(intent),known=join(p.home,writerRenewalIntentTempName(intent));if(temp&&temp!==known)fail();
|
|
110
158
|
if(final){if(!final.bytes.equals(full))fail();if(staging){if(final.stat.nlink!==2n||staging.stat.nlink!==2n||stamp(final.stat)!==stamp(staging.stat)||!staging.bytes.equals(full))fail();}else if(final.stat.nlink!==1n)fail();}
|
|
111
159
|
else if(staging!.stat.nlink!==1n)fail();
|
|
@@ -128,31 +176,38 @@ interface Snapshot { result:WriterHistoryRead; paths:Paths; log:Buffer; intentBy
|
|
|
128
176
|
function snapshot(home:string,b:WriterHistoryBinding,allowPending:boolean,expected?:WriterRenewalIntent,ignoreUnpublishedStaging=false):Snapshot {
|
|
129
177
|
const p=paths(home,b), checks:(()=>void)[]=[], names=manifest(p);
|
|
130
178
|
for(const [dir,stat]of p.dirs)checks.push(()=>{if(identity(checkedDir(dir))!==identity(stat))fail("changed");});
|
|
179
|
+
// A checkpoint that starts, commits or abandons between two reads leaves the old window's files untouched; its token does not.
|
|
180
|
+
checks.push(()=>{let token:string;try{token=placementWindowToken(p.home,b.epochHash);}catch{fail("changed");}if(token!==p.window.token)fail("changed");});
|
|
131
181
|
checks.push(()=>{if(canonicalJSON(manifest(p))!==canonicalJSON(names))fail("changed");});
|
|
132
182
|
const intentRead=readIntent(p,checks,expected,ignoreUnpublishedStaging),intentFile=intentRead.file;let pending=intentRead.intent;
|
|
133
183
|
if(pending){if(!allowPending)fail("pending");if(pending.home!==p.home)fail();boundRevision(pending.revision,b);}
|
|
134
184
|
else if(expected)fail("pending");
|
|
135
185
|
const logFile=read(p.log,WRITER_COMMIT_MAX_BYTES,checks), log=logFile?.bytes??Buffer.alloc(0);
|
|
136
186
|
const commits:WriterCommit[]=[],anchors:{sequence:number;headHash:string}[]=[];let current:WriterRevision|undefined;
|
|
137
|
-
|
|
187
|
+
// #288: the live window's local chain starts at its own genesis; archived windows come first in the logical chain.
|
|
188
|
+
const archived=archivedWriters(p,b);current=archived.current;
|
|
189
|
+
let head=p.genesis,previous=archived.anchors.at(-1)?.sequence??0,completeBytes=log.length;
|
|
138
190
|
const lastLF=log.lastIndexOf(10);if(lastLF!==log.length-1){if(!pending)fail("pending");completeBytes=lastLF+1;}
|
|
139
191
|
let at=0;
|
|
140
192
|
while(at<completeBytes){const end=log.indexOf(10,at);if(end<at)fail();const commit=decode(log.subarray(at,end+1),validateWriterCommit);at=end+1;
|
|
141
193
|
if(commits.length>=WRITER_REVISION_LIMIT)fail("bound");if(commit.epochHash!==b.epochHash||commit.sequence!==commits.length+1||commit.previousHash!==head)fail();
|
|
142
194
|
const file=join(p.epoch,writerRevisionFile(commit.sequence)),raw=read(file,WRITER_REVISION_MAX_BYTES,checks);if(!raw)fail();
|
|
143
|
-
const revision=decode(raw.bytes,validateWriterRevision);boundRevision(revision,b);
|
|
144
|
-
if(revision.sequence!==commit.sequence||revision.previousHash!==head||canonicalJSON(createWriterCommit(revision))!==canonicalJSON(commit))fail();
|
|
195
|
+
const revision=decode(raw.bytes,value=>validateWriterRevision(value,p.genesis));boundRevision(revision,b);
|
|
196
|
+
if(revision.sequence!==commit.sequence||revision.previousHash!==head||canonicalJSON(createWriterCommit(revision,p.genesis))!==canonicalJSON(commit))fail();
|
|
145
197
|
if(current&&revision.initialLocatorHash!==current.initialLocatorHash)fail();
|
|
146
|
-
|
|
198
|
+
const prior=anchors.at(-1)??archived.anchors.at(-1);
|
|
199
|
+
if(revision.journal.sequence<previous||revision.journal.sequence===previous&&prior&&revision.journal.headHash!==prior.headHash)fail();
|
|
147
200
|
anchors.push({...revision.journal});previous=revision.journal.sequence;commits.push(commit);current=revision;head=commit.seal;
|
|
148
201
|
}
|
|
202
|
+
// A committed checkpoint always carries its (W, 1) renewal, so a later live window is never empty.
|
|
203
|
+
if(p.window.window&&!commits.length)fail();
|
|
149
204
|
const expectedNames=new Set(commits.map(commit=>writerRevisionFile(commit.sequence)));if(logFile)expectedNames.add(WRITER_COMMIT_LOG);
|
|
150
205
|
if(pending){
|
|
151
206
|
const start=pending.previousLogBytes, next=pending.revision.sequence;
|
|
152
207
|
if(start>log.length||sha(log.subarray(0,start))!==pending.previousLogHash||start>0&&log[start-1]!==10)fail();
|
|
153
208
|
const beforeCount=commits.filter(commit=>commit.sequence<next).length;
|
|
154
209
|
if(beforeCount!==next-1||commits.length<next-1||commits.length>next)fail();
|
|
155
|
-
const beforeHead=next===1?
|
|
210
|
+
const beforeHead=next===1?p.genesis:commits[next-2]!.seal;
|
|
156
211
|
if(pending.revision.previousHash!==beforeHead||start!==committedPrefixLength(log,next-1))fail();
|
|
157
212
|
const tail=log.subarray(start),line=encode(pending.commit);if(tail.length>line.length||!tail.equals(line.subarray(0,tail.length)))fail();
|
|
158
213
|
const candidateFile=join(p.epoch,writerRevisionFile(next)),candidate=read(candidateFile,WRITER_REVISION_MAX_BYTES,checks),full=encode(pending.revision);
|
|
@@ -163,7 +218,10 @@ function snapshot(home:string,b:WriterHistoryBinding,allowPending:boolean,expect
|
|
|
163
218
|
}else if(completeBytes!==log.length||logFile&&commits.length===0)fail("pending");
|
|
164
219
|
if(canonicalJSON([...expectedNames].sort())!==canonicalJSON(names))fail();
|
|
165
220
|
const assertCurrent=()=>safe(()=>{for(const check of checks)check();});assertCurrent();
|
|
166
|
-
|
|
221
|
+
// `sequence`, `headHash` and the log describe the live window (what a renewal appends to); `commits` and `anchors` are the
|
|
222
|
+
// whole logical chain across windows, so every head a realm record or capture ever bound stays resolvable.
|
|
223
|
+
return{paths:p,log,intentBytes:intentFile?.bytes,result:{current,commits:[...archived.commits,...commits],anchors:[...archived.anchors,...anchors],sequence:commits.length,headHash:head,
|
|
224
|
+
window:p.window.window,genesis:p.genesis,logBytes:log.length,logHash:sha(log),pending,appendStarted:!!pending&&log.length>pending.previousLogBytes,assertCurrent}};
|
|
167
225
|
}
|
|
168
226
|
function committedPrefixLength(log:Buffer,count:number):number {let at=0;for(let n=0;n<count;n++){const lf=log.indexOf(10,at);if(lf<0)fail();at=lf+1;}return at;}
|
|
169
227
|
export function readWriterHistory(home:string,input:WriterHistoryBinding,options:{allowPending?:boolean}={}):WriterHistoryRead {
|
|
@@ -190,12 +248,12 @@ function complete(p:Paths,file:string,full:Buffer,max:number,opts:WriterHistoryO
|
|
|
190
248
|
}finally{closeSync(fd);}syncDir(p,dirname(file),opts);proof(p,opts);if(stamp(lstatSync(file,{bigint:true}))!==stamp(installed!))fail("changed");
|
|
191
249
|
}
|
|
192
250
|
function checkedIntent(home:string,value:WriterRenewalIntent,opts:WriterHistoryOptions):{intent:WriterRenewalIntent;snapshot:Snapshot}{
|
|
193
|
-
const intent=
|
|
251
|
+
const intent=intentCodec(value),b=intentBinding(intent),p=paths(home,b);proof(p,opts);
|
|
194
252
|
const read=snapshot(home,b,true,intent);if(!read.intentBytes)fail("pending");return{intent,snapshot:read};
|
|
195
253
|
}
|
|
196
254
|
export function writeWriterRenewalIntent(home:string,value:WriterRenewalIntent,opts:WriterHistoryOptions):void {
|
|
197
255
|
safe(()=>{
|
|
198
|
-
const intent=
|
|
256
|
+
const intent=intentCodec(value),b=intentBinding(intent),p=paths(home,b);if(intent.home!==p.home)fail();
|
|
199
257
|
if(intent.previousLogBytes+encode(intent.commit).length>WRITER_COMMIT_MAX_BYTES)fail("bound");proof(p,opts);
|
|
200
258
|
const prior=readIntent(p,[],intent).file;
|
|
201
259
|
const old=prior?snapshot(home,b,true,intent):snapshot(home,b,false);
|
|
@@ -217,7 +275,7 @@ export function appendWriterCommit(home:string,value:WriterRenewalIntent,opts:Wr
|
|
|
217
275
|
complete(read.paths,read.paths.log,full,WRITER_COMMIT_MAX_BYTES,opts,"commit-written","commit-fsync",{at:intent.previousLogBytes,phase:"commit-started"});snapshot(home,intentBinding(intent),true).result.assertCurrent();});
|
|
218
276
|
}
|
|
219
277
|
export function clearWriterRenewalIntent(home:string,value:WriterRenewalIntent,opts:WriterHistoryOptions):void {
|
|
220
|
-
safe(()=>{const intent=
|
|
278
|
+
safe(()=>{const intent=intentCodec(value),p=paths(home,intentBinding(intent));proof(p,opts);
|
|
221
279
|
const prior=readIntent(p,[],intent).file;
|
|
222
280
|
if(prior){const read=snapshot(home,intentBinding(intent),true,intent);if(!prior.bytes.equals(encode(intent))||read.result.headHash!==intent.commit.seal||read.log.length!==intent.previousLogBytes+encode(intent.commit).length)fail("pending");
|
|
223
281
|
appendWriterCommit(home,intent,opts);proof(p,opts);const now=readFileExpected(p.intent,encode(intent),WRITER_RENEWAL_INTENT_MAX_BYTES);proof(p,opts);if(stamp(lstatSync(p.intent,{bigint:true}))!==stamp(now.stat))fail("changed");unlinkSync(p.intent);opts.phase?.("intent-cleared");}
|
|
@@ -226,7 +284,7 @@ export function clearWriterRenewalIntent(home:string,value:WriterRenewalIntent,o
|
|
|
226
284
|
}
|
|
227
285
|
function readFileExpected(file:string,full:Buffer,max:number):FileRead {const value=read(file,max);if(!value||!value.bytes.equals(full))fail();return value;}
|
|
228
286
|
export function abandonWriterRenewal(home:string,value:WriterRenewalIntent,opts:WriterHistoryOptions):void {
|
|
229
|
-
safe(()=>{const intent=
|
|
287
|
+
safe(()=>{const intent=intentCodec(value),p=paths(home,intentBinding(intent));proof(p,opts);
|
|
230
288
|
if(!readIntent(p,[],intent).file){
|
|
231
289
|
const cleared=snapshot(home,intentBinding(intent),false);
|
|
232
290
|
if(cleared.result.sequence!==intent.revision.sequence-1||cleared.result.headHash!==intent.revision.previousHash||cleared.result.logBytes!==intent.previousLogBytes||cleared.result.logHash!==intent.previousLogHash)fail("changed");
|
|
@@ -10,10 +10,11 @@ import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
|
|
|
10
10
|
import { readActivePlacementBinding, type ActivePlacementBinding } from "./sync-placement-active.ts";
|
|
11
11
|
import { readInitialSyncPlacementWriterLocator } from "./sync-placement-writer-roots.ts";
|
|
12
12
|
import { readEffectiveSyncPlacementWriters } from "./sync-placement-effective-writers.ts";
|
|
13
|
-
import { readPlacementJournal, readPlacementWriterJournalAnchors, writerRenewalCapacity } from "./sync-placement-journal-storage.ts";
|
|
13
|
+
import { readPlacementJournal, readPlacementWriterJournalAnchors, writerRenewalCapacity, readPlacementPublicationMetadata, placementJournalObjectComposition, type PlacementJournalObjectComposition } from "./sync-placement-journal-storage.ts";
|
|
14
14
|
import { readWriterHistory, writeWriterRenewalIntent, writeWriterRevision, appendWriterCommit, clearWriterRenewalIntent, abandonWriterRenewal, abandonUnpublishedWriterStaging, type WriterHistoryPhase, type WriterHistoryRead } from "./sync-placement-writer-history.ts";
|
|
15
15
|
import { createWriterRevision, createWriterCommit, createWriterRenewalIntent, writerRevisionWriters, WRITER_REVISION_SCHEMA, WRITER_RENEWAL_INTENT_SCHEMA, WRITER_REVISION_LIMIT, WRITER_COMMIT_LOG, SharedWriterRevisionError, type WriterRenewalIntent } from "./sync-placement-writer-revision-format.ts";
|
|
16
16
|
import { requireWriterRenewalHomeFloor } from "./sync-placement-prerequisites.ts";
|
|
17
|
+
import { resolvePlacementWindow } from "./sync-placement-checkpoint-storage.ts";
|
|
17
18
|
import { withPlacementActivationFences } from "./sync-placement-activation-locks.ts";
|
|
18
19
|
import { assertPlacementActivationOwner, type PlacementActivationOwner } from "./sync-placement-activation-proof.ts";
|
|
19
20
|
import { previewSyncPlacementSources, previewOwnedSyncPlacementSources } from "./sync-placement-capture.ts";
|
|
@@ -43,6 +44,8 @@ const binding=(a:ActivePlacementBinding)=>({epochHash:a.profile.placementHead,ac
|
|
|
43
44
|
function list(dir:string,maximum:number):string[]{
|
|
44
45
|
const out:string[]=[],reader=opendirSync(dir);try{for(;;){const e=reader.readSync();if(!e)break;if(out.length>=maximum)throw new SharedWriterRevisionError("bound");out.push(e.name);}}finally{reader.closeSync();}return out.sort();
|
|
45
46
|
}
|
|
47
|
+
/** The fenced directories of one active placement: the home, every activated realm and every admitted project shard. */
|
|
48
|
+
export function placementFenceDirectories(home:string,a:ActivePlacementBinding):string[]{return directories(home,a);}
|
|
46
49
|
function directories(home:string,a:ActivePlacementBinding):string[]{
|
|
47
50
|
const out=[home];for(const r of a.activation.realms)out.push(r.scope==="user"?join(home,"user"):join(home,"projects",r.keyHash.slice(0,16)));
|
|
48
51
|
const checked=(dir:string)=>{const s=lstatSync(dir);if(!s.isDirectory()||s.isSymbolicLink()||s.uid!==process.getuid?.()||(s.mode&0o022)!==0)throw new WriterRenewalError("changed");};
|
|
@@ -107,12 +110,16 @@ export async function renewSyncPlacementWriters(options:PlacementActivationOptio
|
|
|
107
110
|
if(options.mode==="dry-run"){
|
|
108
111
|
if(history.pending)return{mode:options.mode,active:true,renewalSupported:true,pending:true,commitStarted:history.appendStarted,abandonable:!history.appendStarted,sequence:history.sequence,remainingRevisions:WRITER_REVISION_LIMIT-history.sequence};
|
|
109
112
|
const expected=readEffectiveSyncPlacementWriters(home);let floorReady=true;try{requireWriterRenewalHomeFloor(home);}catch{floorReady=false;}
|
|
110
|
-
let recoveryReady=true,objectSlotsRemaining:number|undefined;
|
|
111
|
-
|
|
113
|
+
let recoveryReady=true,objectSlotsRemaining:number|undefined,journalObjects:PlacementJournalObjectComposition|undefined;
|
|
114
|
+
// The preview's own composition (#288 step 1), read without a plan: `newPlan` is null here, and the epoch's one
|
|
115
|
+
// active.json slot is included exactly as the counted total includes it. A pending renewal intent lives outside the
|
|
116
|
+
// epoch directory, so `objectSlotsRemaining` can be smaller than the composition suggests.
|
|
117
|
+
try{journalClear(home,b.epochHash);pendingSources(home);objectSlotsRemaining=256-readPlacementJournal(home,b.epochHash).objects;
|
|
118
|
+
journalObjects=readPlacementPublicationMetadata(home,b.epochHash,io=>placementJournalObjectComposition({names:io.names()}));}catch{recoveryReady=false;}
|
|
112
119
|
const writers=previewActivePlacementWriters(home,options.ownRoot,options.writerRoots),remaining=WRITER_REVISION_LIMIT-history.sequence;
|
|
113
120
|
return{mode:options.mode,active:true,renewalSupported:true,forwardOnly:true,sequence:history.sequence,revisionHash:history.headHash,remainingRevisions:WRITER_REVISION_LIMIT-history.sequence,
|
|
114
121
|
quiescence:"deferred-to-apply",floorReady,requiredHomeFloor:"0.22.0",recoveryReady,...(recoveryReady?{}:{nextStep:new WriterRenewalError("pending").message}),
|
|
115
|
-
...(objectSlotsRemaining===undefined?{}:{objectSlotsRemaining}),...(remaining<=4?{capacityNotice:`${remaining} renewals remain before the 64-revision ceiling; the shared object budget may refuse earlier. Archival/checkpointing requires a separate reviewed protocol.`}:{}),
|
|
122
|
+
...(objectSlotsRemaining===undefined?{}:{objectSlotsRemaining}),...(journalObjects?{journalObjects}:{}),...(remaining<=4?{capacityNotice:`${remaining} renewals remain before the 64-revision ceiling; the shared object budget may refuse earlier. Archival/checkpointing requires a separate reviewed protocol.`}:{}),
|
|
116
123
|
writers,candidateMinimumVersion:"0.22.0",candidatesSupported:writers.complete&&writers.roots.every(r=>supported(r.version)),expectedWriterCount:expected.writers.length};
|
|
117
124
|
}
|
|
118
125
|
requireWriterRenewalHomeFloor(home);
|
|
@@ -128,8 +135,9 @@ export async function renewSyncPlacementWriters(options:PlacementActivationOptio
|
|
|
128
135
|
let intent=history.pending;
|
|
129
136
|
const cleanupOnly=!intent&&options.mode==="resume"&&!!history.current;
|
|
130
137
|
if(cleanupOnly){
|
|
131
|
-
|
|
132
|
-
|
|
138
|
+
// #288: the live window's own log: commits before it belong to frozen windows.
|
|
139
|
+
const local=history.commits.slice(history.commits.length-history.sequence),prefix=Buffer.from(local.slice(0,-1).map(row=>canonicalJSON(row)+"\n").join(""));
|
|
140
|
+
intent=createWriterRenewalIntent({schema:WRITER_RENEWAL_INTENT_SCHEMA,home,revision:history.current!,commit:history.commits.at(-1)!,previousLogBytes:prefix.length,previousLogHash:createHash("sha256").update(prefix).digest("hex")},history.genesis);
|
|
133
141
|
}
|
|
134
142
|
const locator=readInitialSyncPlacementWriterLocator(home);
|
|
135
143
|
const metadata=()=>{
|
|
@@ -148,14 +156,14 @@ export async function renewSyncPlacementWriters(options:PlacementActivationOptio
|
|
|
148
156
|
const current=readWriterHistory(home,{...b,initialLocatorHash:locator.seal});
|
|
149
157
|
if(current.sequence>=WRITER_REVISION_LIMIT)throw new SharedWriterRevisionError("cap");
|
|
150
158
|
const candidate=initialPlacementWriterContext(home,options.writerRoots,options.ownRoot);if(candidate.measurement.roots.some(r=>!supported(r.version)))throw new WriterRenewalError("candidate");
|
|
151
|
-
candidate.attest();const previous=current.current?writerRevisionWriters(current.current):initial.activation.writers;
|
|
159
|
+
candidate.attest();const previous=current.current?writerRevisionWriters(current.current,current.current.sequence===1?current.current.previousHash:undefined):initial.activation.writers;
|
|
152
160
|
if(canonicalJSON(previous)===canonicalJSON(candidate.measurement.writers))return{mode:options.mode,active:true,renewed:false,sequence:current.sequence,remainingRevisions:WRITER_REVISION_LIMIT-current.sequence};
|
|
153
161
|
const journal=readPlacementJournal(home,b.epochHash),revision=createWriterRevision({schema:WRITER_REVISION_SCHEMA,...b,initialLocatorHash:locator.seal,sequence:current.sequence+1,previousHash:current.headHash,
|
|
154
|
-
journal:{sequence:journal.sequence,headHash:journal.headHash},roots:candidate.measurement.roots,requestId:randomBytes(32).toString("hex")});
|
|
155
|
-
intent=createWriterRenewalIntent({schema:WRITER_RENEWAL_INTENT_SCHEMA,home,revision,commit:createWriterCommit(revision),previousLogBytes:current.logBytes,previousLogHash:current.logHash});
|
|
162
|
+
journal:{sequence:journal.sequence,headHash:journal.headHash},roots:candidate.measurement.roots,requestId:randomBytes(32).toString("hex")},current.genesis);
|
|
163
|
+
intent=createWriterRenewalIntent({schema:WRITER_RENEWAL_INTENT_SCHEMA,home,revision,commit:createWriterCommit(revision,current.genesis),previousLogBytes:current.logBytes,previousLogHash:current.logHash},current.genesis);
|
|
156
164
|
}
|
|
157
165
|
const fixed=intent;person(options,fixed);
|
|
158
|
-
const log=join(home,
|
|
166
|
+
const log=join(resolvePlacementWindow(home,b.epochHash).dir,WRITER_COMMIT_LOG);
|
|
159
167
|
const started=()=>{const s=lstatSync(log,{throwIfNoEntry:false});return!!s&&s.isFile()&&!s.isSymbolicLink()&&s.size>fixed.previousLogBytes;};
|
|
160
168
|
const check=()=>{
|
|
161
169
|
metadata();
|
|
@@ -5,6 +5,7 @@ import { types } from "node:util";
|
|
|
5
5
|
import { canonicalJSON, hashJSON } from "./generation.ts";
|
|
6
6
|
import { syncPlacementWriterId, type MeasuredSyncPlacementWriterRoot } from "./sync-placement-writers.ts";
|
|
7
7
|
import { PLACEMENT_FORMAT } from "./sync-placement-format.ts";
|
|
8
|
+
import { PLACEMENT_CHECKPOINT_PENDING_MESSAGE } from "./sync-placement-journal-format.ts";
|
|
8
9
|
import type { SyncPlacementWriterAttestation } from "./sync-placement-plan.ts";
|
|
9
10
|
|
|
10
11
|
export const WRITER_REVISION_MAX_BYTES=512*1024;
|
|
@@ -17,12 +18,13 @@ export const WRITER_REVISION_SCHEMA="agent-mem.sync-placement-writer-revision/v1
|
|
|
17
18
|
export const WRITER_COMMIT_SCHEMA="agent-mem.sync-placement-writer-commit/v1";
|
|
18
19
|
export const WRITER_RENEWAL_INTENT_SCHEMA="agent-mem.sync-placement-writer-renewal/v1";
|
|
19
20
|
|
|
20
|
-
export type SharedWriterRevisionErrorCode="invalid"|"bound"|"changed"|"pending"|"staging"|"cap";
|
|
21
|
+
export type SharedWriterRevisionErrorCode="invalid"|"bound"|"changed"|"pending"|"checkpoint-pending"|"staging"|"cap";
|
|
21
22
|
const messages:Record<SharedWriterRevisionErrorCode,string>={
|
|
22
23
|
invalid:"Writer renewal metadata is invalid or unsupported; have the person inspect the retained same-epoch inventory and rerun amem migrate --sync-placement --dry-run.",
|
|
23
24
|
bound:"Writer renewal metadata exceeds its supported bound; retain the existing inventory and request a separately reviewed archival/checkpoint before retrying.",
|
|
24
25
|
changed:"Writer renewal bindings changed; retain the existing inventory, inspect the same-epoch evidence and review a fresh dry-run before applying.",
|
|
25
26
|
pending:"Writer renewal is pending; preserve its exact intent and have the person run amem migrate --sync-placement --resume.",
|
|
27
|
+
"checkpoint-pending":PLACEMENT_CHECKPOINT_PENDING_MESSAGE,
|
|
26
28
|
staging:"Writer renewal has orphan staging without a registered final intent; have the person inspect it and run amem migrate --sync-placement --abandon, then amem migrate --sync-placement --dry-run before another apply.",
|
|
27
29
|
cap:"Writer revision capacity is exhausted (remaining 0); retain this epoch and request a separately reviewed archival/checkpoint before another renewal.",
|
|
28
30
|
};
|
|
@@ -88,35 +90,36 @@ export interface WriterCommitBody {schema:typeof WRITER_COMMIT_SCHEMA;epochHash:
|
|
|
88
90
|
export interface WriterCommit extends WriterCommitBody {seal:string}
|
|
89
91
|
export interface WriterRenewalIntentBody {schema:typeof WRITER_RENEWAL_INTENT_SCHEMA;home:string;revision:WriterRevision;commit:WriterCommit;previousLogBytes:number;previousLogHash:string}
|
|
90
92
|
export interface WriterRenewalIntent extends WriterRenewalIntentBody {seal:string}
|
|
91
|
-
function revision(input:unknown,sealed:boolean):WriterRevision {
|
|
93
|
+
function revision(input:unknown,sealed:boolean,genesis?:string):WriterRevision {
|
|
92
94
|
const v=object(input,["schema","epochHash","generation","homeHash","activationHash","initialLocatorHash","sequence","previousHash","journal","roots","requestId",...(sealed?["seal"]:[])]);
|
|
93
95
|
if(v.schema!==WRITER_REVISION_SCHEMA)fail();const journal=object(v.journal,["sequence","headHash"]);
|
|
94
96
|
const body:WriterRevisionBody={schema:WRITER_REVISION_SCHEMA,epochHash:hex(v.epochHash),generation:hex(v.generation,32),homeHash:hex(v.homeHash),activationHash:hex(v.activationHash),
|
|
95
97
|
initialLocatorHash:hex(v.initialLocatorHash),sequence:sequence(v.sequence),previousHash:hex(v.previousHash),journal:{sequence:integer(journal.sequence,0,20000),headHash:hex(journal.headHash)},roots:roots(v.roots),requestId:hex(v.requestId)};
|
|
96
|
-
|
|
98
|
+
// #288: window W > 0 starts from its own checkpoint genesis; window 0 keeps the epoch genesis.
|
|
99
|
+
if(body.sequence===1&&body.previousHash!==(genesis??writerInventoryGenesis(body.epochHash,body.activationHash)))fail();
|
|
97
100
|
const value={...body,seal:hashJSON(body)};if(sealed&&hex(v.seal)!==value.seal)fail();bounded(value,WRITER_REVISION_MAX_BYTES);return value;
|
|
98
101
|
}
|
|
99
|
-
export function createWriterRevision(body:WriterRevisionBody):WriterRevision {return safe(()=>revision(body,false));}
|
|
100
|
-
export function validateWriterRevision(value:unknown):WriterRevision {return safe(()=>revision(value,true));}
|
|
101
|
-
export function writerRevisionWriters(input:WriterRevision):SyncPlacementWriterAttestation[]{
|
|
102
|
-
return validateWriterRevision(input).roots.map<SyncPlacementWriterAttestation>(({writerId,version,pin})=>({writerId,version,pin,publicationFormat:PLACEMENT_FORMAT,compatible:true as const})).sort((a,b)=>a.writerId.localeCompare(b.writerId));
|
|
102
|
+
export function createWriterRevision(body:WriterRevisionBody,genesis?:string):WriterRevision {return safe(()=>revision(body,false,genesis===undefined?undefined:hex(genesis)));}
|
|
103
|
+
export function validateWriterRevision(value:unknown,genesis?:string):WriterRevision {return safe(()=>revision(value,true,genesis===undefined?undefined:hex(genesis)));}
|
|
104
|
+
export function writerRevisionWriters(input:WriterRevision,genesis?:string):SyncPlacementWriterAttestation[]{
|
|
105
|
+
return validateWriterRevision(input,genesis).roots.map<SyncPlacementWriterAttestation>(({writerId,version,pin})=>({writerId,version,pin,publicationFormat:PLACEMENT_FORMAT,compatible:true as const})).sort((a,b)=>a.writerId.localeCompare(b.writerId));
|
|
103
106
|
}
|
|
104
107
|
function commit(input:unknown,sealed:boolean):WriterCommit {
|
|
105
108
|
const v=object(input,["schema","epochHash","sequence","previousHash","revisionHash",...(sealed?["seal"]:[])]);if(v.schema!==WRITER_COMMIT_SCHEMA)fail();
|
|
106
109
|
const body:WriterCommitBody={schema:WRITER_COMMIT_SCHEMA,epochHash:hex(v.epochHash),sequence:sequence(v.sequence),previousHash:hex(v.previousHash),revisionHash:hex(v.revisionHash)};
|
|
107
110
|
const value={...body,seal:hashJSON(body)};if(sealed&&hex(v.seal)!==value.seal)fail();bounded(value,WRITER_COMMIT_MAX_BYTES);return value;
|
|
108
111
|
}
|
|
109
|
-
export function createWriterCommit(input:WriterRevision):WriterCommit {
|
|
110
|
-
const rev=validateWriterRevision(input);return safe(()=>commit({schema:WRITER_COMMIT_SCHEMA,epochHash:rev.epochHash,sequence:rev.sequence,previousHash:rev.previousHash,revisionHash:rev.seal},false));
|
|
112
|
+
export function createWriterCommit(input:WriterRevision,genesis?:string):WriterCommit {
|
|
113
|
+
const rev=validateWriterRevision(input,genesis);return safe(()=>commit({schema:WRITER_COMMIT_SCHEMA,epochHash:rev.epochHash,sequence:rev.sequence,previousHash:rev.previousHash,revisionHash:rev.seal},false));
|
|
111
114
|
}
|
|
112
115
|
export function validateWriterCommit(value:unknown):WriterCommit {return safe(()=>commit(value,true));}
|
|
113
|
-
function intent(input:unknown,sealed:boolean):WriterRenewalIntent {
|
|
116
|
+
function intent(input:unknown,sealed:boolean,genesis?:string):WriterRenewalIntent {
|
|
114
117
|
const v=object(input,["schema","home","revision","commit","previousLogBytes","previousLogHash",...(sealed?["seal"]:[])]);if(v.schema!==WRITER_RENEWAL_INTENT_SCHEMA)fail();
|
|
115
|
-
const rev=validateWriterRevision(v.revision),ack=validateWriterCommit(v.commit),previousLogBytes=integer(v.previousLogBytes,0,WRITER_COMMIT_MAX_BYTES),previousLogHash=hex(v.previousLogHash);
|
|
118
|
+
const rev=validateWriterRevision(v.revision,genesis),ack=validateWriterCommit(v.commit),previousLogBytes=integer(v.previousLogBytes,0,WRITER_COMMIT_MAX_BYTES),previousLogHash=hex(v.previousLogHash);
|
|
116
119
|
if(ack.epochHash!==rev.epochHash||ack.sequence!==rev.sequence||ack.previousHash!==rev.previousHash||ack.revisionHash!==rev.seal)fail();
|
|
117
120
|
if(rev.sequence===1&&(previousLogBytes!==0||previousLogHash!==createHash("sha256").update("").digest("hex")))fail();
|
|
118
121
|
const body:WriterRenewalIntentBody={schema:WRITER_RENEWAL_INTENT_SCHEMA,home:path(v.home),revision:rev,commit:ack,previousLogBytes,previousLogHash};
|
|
119
122
|
const value={...body,seal:hashJSON(body)};if(sealed&&hex(v.seal)!==value.seal)fail();bounded(value,WRITER_RENEWAL_INTENT_MAX_BYTES);return value;
|
|
120
123
|
}
|
|
121
|
-
export function createWriterRenewalIntent(body:WriterRenewalIntentBody):WriterRenewalIntent {return safe(()=>intent(body,false));}
|
|
122
|
-
export function validateWriterRenewalIntent(value:unknown):WriterRenewalIntent {return safe(()=>intent(value,true));}
|
|
124
|
+
export function createWriterRenewalIntent(body:WriterRenewalIntentBody,genesis?:string):WriterRenewalIntent {return safe(()=>intent(body,false,genesis));}
|
|
125
|
+
export function validateWriterRenewalIntent(value:unknown,genesis?:string):WriterRenewalIntent {return safe(()=>intent(value,true,genesis));}
|
|
@@ -0,0 +1,44 @@
|
|
|
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;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* #470: a heavy pure function is written once as a step generator and driven two ways, so the synchronous API keeps its
|
|
34
|
+
* signature and the placement sync awaits a turn between steps. `drainSteps` ignores the step boundaries;
|
|
35
|
+
* `drainStepsAsync` hands the caller's loop back at each one. A fence or proof inside the function runs in the same order
|
|
36
|
+
* either way, because only the scheduling between steps differs.
|
|
37
|
+
*/
|
|
38
|
+
export function drainSteps<T>(steps: Generator<void, T, void>): T {
|
|
39
|
+
let next = steps.next(); while (!next.done) next = steps.next(); return next.value;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function drainStepsAsync<T>(steps: Generator<void, T, void>, pause: CooperativeYield = cooperativeYield()): Promise<T> {
|
|
43
|
+
let next = steps.next(); while (!next.done) { await pause(); next = steps.next(); } return next.value;
|
|
44
|
+
}
|
|
@@ -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
|
@@ -13,6 +13,7 @@ import { memoryHome } from "./home.ts";
|
|
|
13
13
|
import { outboundScreen, screenOutboundRows, screenOwnSegment, type RowScreen } from "./sync-screen.ts";
|
|
14
14
|
import { shardSyncBinding } from "./sync-binding.ts";
|
|
15
15
|
import type { PlacementSyncBound } from "./sync-placement-bound.ts";
|
|
16
|
+
import type { PlacementJournalObjectComposition } from "./sync-placement-journal-storage.ts";
|
|
16
17
|
import type { SyncProgress, SyncProgressPhase } from "./sync-progress.ts";
|
|
17
18
|
import type { PlacementRefusalCategory } from "./sync-placement-refusal.ts";
|
|
18
19
|
|
|
@@ -22,11 +23,24 @@ import type { PlacementRefusalCategory } from "./sync-placement-refusal.ts";
|
|
|
22
23
|
* machine's history never conflicts. Pull, then push; fail-open: a failure is a result with one reason, never a throw.
|
|
23
24
|
*/
|
|
24
25
|
export type Visibility = "public" | "private" | "unknown";
|
|
26
|
+
/**
|
|
27
|
+
* #462: the closed cause class of a placement sync that did not succeed, so a host can name the next step without
|
|
28
|
+
* parsing `error` text. `bound` carries its numbers in `placementPublication.bound`; `refusal` carries its fixed
|
|
29
|
+
* category; `unavailable` is any other refusal before an attempt (activation, inventory or I/O).
|
|
30
|
+
*/
|
|
31
|
+
export const SYNC_FAILURE_CAUSES = ["bound", "refusal", "unknown-outcome", "writer-renewal", "remote", "stopped", "unavailable", "checkpoint-pending"] as const;
|
|
32
|
+
export type SyncFailureCause = typeof SYNC_FAILURE_CAUSES[number];
|
|
25
33
|
export interface SyncResult { ok: boolean; pushed: boolean; entries: number; warning?: string; error?: string;
|
|
34
|
+
/** #462: set on every failed placement sync; absent on success and on the legacy transports. */
|
|
35
|
+
failure?: { cause: SyncFailureCause; category?: PlacementRefusalCategory };
|
|
36
|
+
/** #450: per-realm outcomes of a whole-inventory placement sync, in run order (`user` or the full realm key hash). */
|
|
37
|
+
placementRealms?: { realm: string; outcome: "committed" | "not-needed" | "unknown" | "failed" | "not-run" | "not-local" | "inactive"; publication?: number }[];
|
|
26
38
|
placementPublication?: { attemptHash?: string; outcome: "committed" | "unknown" | "not-needed"; withheld: number; exported: number;
|
|
27
39
|
lastPolicyHash?: string; lastPolicyCheckUnixMs?: number; policyCheckSource?: "live" | "durable-intent"; policyCeiling: "last-positive-check-before-in-flight-push"; recovered?: boolean;
|
|
28
40
|
/** #419: an expected size refusal before any publication attempt; numbers only. */
|
|
29
41
|
bound?: PlacementSyncBound;
|
|
42
|
+
/** #288 step 1: what held the whole epoch's objects when the journal-objects bound was measured; numbers only. */
|
|
43
|
+
journalObjects?: PlacementJournalObjectComposition;
|
|
30
44
|
/** #426: the fixed category and phase of a refusal before any publication attempt; no path, row or secret. */
|
|
31
45
|
refusal?: { category: PlacementRefusalCategory; phase: SyncProgressPhase } };
|
|
32
46
|
pruneApplication?: {transport:"durable"|"unconfirmed";proofComplete:number;projectionActive:number|null;nativeApplied:number|null;held:number;phase:"preflight"|"prepared"|"active"|"complete"};
|
|
@@ -267,7 +281,18 @@ export async function syncMemory(store: MemoryStore, opts: SyncOptions = {}): Pr
|
|
|
267
281
|
assertFormatFloor(store.profile.home, "sync");
|
|
268
282
|
const placementRefusal = placementRuntimeRefusal(store.profile.home, store.profile);
|
|
269
283
|
if (placementRefusal) return { ok: false, pushed: false, entries: 0, error: placementRefusal };
|
|
270
|
-
if (store.profile.publicationFormat === "agent-mem.sync-placement/v1")
|
|
284
|
+
if (store.profile.publicationFormat === "agent-mem.sync-placement/v1") {
|
|
285
|
+
// #450: the whole activated inventory, independent of the binding that opened `store`.
|
|
286
|
+
const [{ syncPlacementInventory }, { syncPlacementMemory }, { openShardStore }] = await Promise.all([import("./sync-placement-inventory.ts"), import("./sync-placement-transport.ts"), import("./store.ts")]);
|
|
287
|
+
const home = store.profile.home, held = store.openedSyncTargets(), opened = new Set<MemoryStore>();
|
|
288
|
+
// A realm the caller already holds is reused (no second lease or fence file); others are opened and closed per publication.
|
|
289
|
+
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);
|
|
290
|
+
return syncPlacementInventory(home, opts, {
|
|
291
|
+
open: realm => reuse(realm) ?? (() => { const fresh = openShardStore({ memoryDir: home, deferPromotions: true, ...(realm.scope === "user" ? { user: true } : { project: realm.key }) }); opened.add(fresh); return fresh; })(),
|
|
292
|
+
close: item => { if (opened.delete(item)) item.close(); },
|
|
293
|
+
publish: (primary, targets, options) => syncPlacementMemory(primary, options, undefined, undefined, undefined, targets),
|
|
294
|
+
});
|
|
295
|
+
}
|
|
271
296
|
if (opts.signal?.aborted) return { ok: false, pushed: false, entries: 0, error: "stopped" };
|
|
272
297
|
if (!opts.remote) {
|
|
273
298
|
try {
|