@staix/agent-mem 0.29.0 → 0.31.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 +20 -574
- package/package.json +3 -2
- package/src/cli-agent-reads.ts +17 -2
- package/src/cli.ts +178 -21
- package/src/commands-table.ts +14 -2
- package/src/index.ts +1 -0
- package/src/ingest.ts +7 -5
- package/src/mcp-memory.ts +36 -8
- package/src/memory/bridge.ts +26 -1
- package/src/memory/candidates.ts +17 -1
- package/src/memory/capacity.ts +5 -2
- package/src/memory/catalog.ts +10 -1
- package/src/memory/commands.ts +2 -1
- package/src/memory/config.ts +13 -1
- package/src/memory/decay-review.ts +20 -0
- package/src/memory/doctor.ts +133 -47
- package/src/memory/eval-audit.ts +442 -0
- package/src/memory/eval.ts +66 -0
- package/src/memory/formats.ts +4 -3
- package/src/memory/intent-brief.ts +34 -6
- package/src/memory/metrics.ts +173 -14
- package/src/memory/native-roots.ts +28 -0
- package/src/memory/platform.ts +9 -1
- package/src/memory/review-targets.ts +69 -0
- package/src/memory/shard-bridge.ts +18 -6
- package/src/memory/shard-migration.ts +14 -1
- package/src/memory/shard-sync-format.ts +18 -0
- package/src/memory/shard-sync.ts +52 -4
- package/src/memory/shard.ts +4 -0
- package/src/memory/store.ts +4 -2
- 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 +14 -2
- 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-inspection-evidence.ts +1 -1
- package/src/memory/sync-placement-inventory.ts +38 -11
- package/src/memory/sync-placement-journal-format.ts +4 -1
- package/src/memory/sync-placement-journal-storage.ts +129 -26
- package/src/memory/sync-placement-materialize.ts +33 -19
- 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 +18 -1
- package/src/memory/sync-placement-realm-admission.ts +20 -3
- package/src/memory/sync-placement-realm-discovery.ts +42 -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 +207 -53
- 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 +14 -0
- package/src/memory/sync-progress.ts +1 -1
- package/src/memory/sync.ts +5 -2
- package/src/memory/use-telemetry.ts +15 -7
- package/src/setup-drift.ts +12 -2
- package/src/setup-owned.ts +42 -0
- package/src/setup.ts +32 -11
- package/src/sync-placement-writer-context.ts +5 -5
- package/src/ui/plugin.ts +26 -11
- package/src/ui/snapshot-cache.ts +24 -11
|
@@ -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));}
|
|
@@ -28,3 +28,17 @@ export const yieldTurn = (): Promise<void> => new Promise<void>(resolve => setIm
|
|
|
28
28
|
|
|
29
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
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
|
+
}
|
|
@@ -26,7 +26,7 @@ export interface SyncProgressCounts { permitted: number; local: number; declined
|
|
|
26
26
|
export interface SyncProgressInventory { publications: number; completed: number; realms: number;
|
|
27
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
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;
|
|
29
|
+
export const SYNC_REALM_OUTCOMES = ["committed", "not-needed", "unknown", "failed", "not-run", "not-local", "inactive", "held"] as const;
|
|
30
30
|
export type SyncRealmOutcome = typeof SYNC_REALM_OUTCOMES[number];
|
|
31
31
|
const MAX_REALM_OUTCOMES = 32;
|
|
32
32
|
const realmLabel = (value: unknown): value is string => typeof value === "string" && (value === "user" || /^[a-f0-9]{16}$/.test(value));
|
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
|
|
|
@@ -27,17 +28,19 @@ export type Visibility = "public" | "private" | "unknown";
|
|
|
27
28
|
* parsing `error` text. `bound` carries its numbers in `placementPublication.bound`; `refusal` carries its fixed
|
|
28
29
|
* category; `unavailable` is any other refusal before an attempt (activation, inventory or I/O).
|
|
29
30
|
*/
|
|
30
|
-
export const SYNC_FAILURE_CAUSES = ["bound", "refusal", "unknown-outcome", "writer-renewal", "remote", "stopped", "unavailable"] as const;
|
|
31
|
+
export const SYNC_FAILURE_CAUSES = ["bound", "refusal", "unknown-outcome", "writer-renewal", "remote", "stopped", "unavailable", "checkpoint-pending"] as const;
|
|
31
32
|
export type SyncFailureCause = typeof SYNC_FAILURE_CAUSES[number];
|
|
32
33
|
export interface SyncResult { ok: boolean; pushed: boolean; entries: number; warning?: string; error?: string;
|
|
33
34
|
/** #462: set on every failed placement sync; absent on success and on the legacy transports. */
|
|
34
35
|
failure?: { cause: SyncFailureCause; category?: PlacementRefusalCategory };
|
|
35
36
|
/** #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 }[];
|
|
37
|
+
placementRealms?: { realm: string; outcome: "committed" | "not-needed" | "unknown" | "failed" | "not-run" | "not-local" | "inactive" | "held"; publication?: number }[];
|
|
37
38
|
placementPublication?: { attemptHash?: string; outcome: "committed" | "unknown" | "not-needed"; withheld: number; exported: number;
|
|
38
39
|
lastPolicyHash?: string; lastPolicyCheckUnixMs?: number; policyCheckSource?: "live" | "durable-intent"; policyCeiling: "last-positive-check-before-in-flight-push"; recovered?: boolean;
|
|
39
40
|
/** #419: an expected size refusal before any publication attempt; numbers only. */
|
|
40
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;
|
|
41
44
|
/** #426: the fixed category and phase of a refusal before any publication attempt; no path, row or secret. */
|
|
42
45
|
refusal?: { category: PlacementRefusalCategory; phase: SyncProgressPhase } };
|
|
43
46
|
pruneApplication?: {transport:"durable"|"unconfirmed";proofComplete:number;projectionActive:number|null;nativeApplied:number|null;held:number;phase:"preflight"|"prepared"|"active"|"complete"};
|
|
@@ -8,6 +8,20 @@ const entry = (id: string): string => { const normalized = id.replace(/^mem:/, "
|
|
|
8
8
|
const projectKey = (project: string): string => { if (typeof project !== "string" || !project.trim() || project.length > 400 || project.includes("\0")) throw Error("invalid memory use project"); return project; };
|
|
9
9
|
function guard(context: MemoryUseContext): void { if (context.allowed?.() === false) throw Error("memory use unavailable"); context.assertCurrent?.(); }
|
|
10
10
|
const count = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0;
|
|
11
|
+
/** Sum a bounded delivery snapshot without treating a missing metric as an observed zero. */
|
|
12
|
+
export function summarizeMemoryUse(rows: readonly Counter[]): MemoryUseSummary {
|
|
13
|
+
if (!rows.length) return { state: "known", records: 0, rendered: null, delivered: null, cited: null };
|
|
14
|
+
const metric = (name: keyof CounterValues): number | null => {
|
|
15
|
+
let total = 0;
|
|
16
|
+
for (const row of rows) {
|
|
17
|
+
const value = row[name];
|
|
18
|
+
if (!count(value) || !Number.isSafeInteger(total + value)) return null;
|
|
19
|
+
total += value;
|
|
20
|
+
}
|
|
21
|
+
return total;
|
|
22
|
+
};
|
|
23
|
+
return { state: "known", records: rows.length, rendered: metric("rendered"), delivered: metric("delivered"), cited: metric("cited") };
|
|
24
|
+
}
|
|
11
25
|
/** Counts are explicit per-delivery totals, never increments or inferred delivery/citation events. */
|
|
12
26
|
export function recordMemoryUse(port: MemoryUsePort, key: CounterKey, values: CounterValues, context: MemoryUseContext = {}): boolean {
|
|
13
27
|
try {
|
|
@@ -34,13 +48,7 @@ export function readMemoryUse(port: MemoryUsePort, project: string, id: string,
|
|
|
34
48
|
rows.set(row.id, row);
|
|
35
49
|
}
|
|
36
50
|
}
|
|
37
|
-
const
|
|
38
|
-
if (!rows.size) return null;
|
|
39
|
-
let total = 0;
|
|
40
|
-
for (const row of rows.values()) { const value = row[name]; if (!count(value) || !Number.isSafeInteger(total + value)) return null; total += value; }
|
|
41
|
-
return total;
|
|
42
|
-
};
|
|
43
|
-
const result: MemoryUseSummary = { state: "known", records: rows.size, rendered: metric("rendered"), delivered: metric("delivered"), cited: metric("cited") };
|
|
51
|
+
const result = summarizeMemoryUse([...rows.values()]);
|
|
44
52
|
guard(context); return result;
|
|
45
53
|
} catch { return unknown(); }
|
|
46
54
|
}
|
package/src/setup-drift.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from "node:fs";
|
|
1
|
+
import { closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readSync } from "node:fs";
|
|
2
2
|
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
4
|
import { isDeepStrictEqual } from "node:util";
|
|
5
5
|
import type { SetupTarget } from "./setup.ts";
|
|
6
6
|
import { SETUP_CONFIG_BYTES } from "./setup-toml.ts";
|
|
7
|
-
import { managedAfter, managedHookEntries, mcpRecord, type ConfigImage } from "./setup-owned.ts";
|
|
7
|
+
import { amemCaptureCommand, amemCaptureHooks, managedAfter, managedHookEntries, mcpRecord, type ConfigImage } from "./setup-owned.ts";
|
|
8
8
|
import { resolveSetupPaths, type SetupEnvironment } from "./setup-paths.ts";
|
|
9
9
|
import { HOOK_EVENTS } from "./hook-contract.ts";
|
|
10
10
|
import { realPath } from "./memory/platform.ts";
|
|
@@ -190,6 +190,16 @@ export function readSetupDrift(options: { home: string; env?: SetupEnvironment;
|
|
|
190
190
|
}
|
|
191
191
|
} catch { entries.push(entry(target, change.path, "hooks", "managed hooks could not be checked", "unavailable")); unavailable = true; }
|
|
192
192
|
}
|
|
193
|
+
// #512: an amem capture hook whose launch path is gone fails on every session end. Named by target, file and event, never its command.
|
|
194
|
+
const captureSurface = { codex: "codex:1", kimi: "kimi:1", qwen: "qwen:0", pi: "pi:1" }[target as string];
|
|
195
|
+
if (captureSurface === change.key) {
|
|
196
|
+
try {
|
|
197
|
+
for (const row of amemCaptureHooks(target, current)) {
|
|
198
|
+
const launch = amemCaptureCommand(row.command);
|
|
199
|
+
if (launch && (!existsSync(launch.entry) || !existsSync(launch.bun))) entries.push(entry(target, change.path, `hooks.${row.event}`, "managed capture hook launches an amem install that no longer exists; rerun amem setup " + target + " --apply to replace it", "drift"));
|
|
200
|
+
}
|
|
201
|
+
} catch { entries.push(entry(target, change.path, "hooks", "managed capture hooks could not be checked", "unavailable")); unavailable = true; }
|
|
202
|
+
}
|
|
193
203
|
if (target === "pi" && change.key === "pi:1" && !managedAfter(target, 1, change.before, change.after, current)) entries.push(entry(target, change.path, "session_shutdown extension", "managed hook extension is missing or changed", "drift"));
|
|
194
204
|
// #203: jcode's capture hooks are command elements in config.toml [hooks]; a pre-#203 receipt has no such change.
|
|
195
205
|
if (target === "jcode" && change.key === "jcode:1" && !managedAfter(target, 1, change.before, change.after, current)) entries.push(entry(target, change.path, "hooks", "managed hook is missing or changed", "drift"));
|
package/src/setup-owned.ts
CHANGED
|
@@ -216,3 +216,45 @@ export function managedHookEntries(target: string, before: ConfigImage, after: C
|
|
|
216
216
|
return installed.filter(row => ours.has(row.id) || expected.some(value => value.event === row.event && value.command === row.command))
|
|
217
217
|
.map(row => ({ entry: `hooks.${row.event}`, present: live.some(value => value.id === row.id) }));
|
|
218
218
|
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* #512: the one matcher for an amem capture hook command, whatever its install root:
|
|
222
|
+
* `<bun> --smol <...>/@staix/agent-mem/bin/amem.js ingest <target>[ --json]`, each path raw or single-quoted shell style.
|
|
223
|
+
* Used for Codex hooks.json, Qwen settings.json, Kimi config.toml and the Pi extension launch.
|
|
224
|
+
*/
|
|
225
|
+
export function amemCaptureCommand(command: string): { target: string; bun: string; entry: string } | undefined {
|
|
226
|
+
const tokens: string[] = [];
|
|
227
|
+
let i = 0;
|
|
228
|
+
while (i < command.length) {
|
|
229
|
+
while (command[i] === " ") i++;
|
|
230
|
+
if (i >= command.length) break;
|
|
231
|
+
let token = "";
|
|
232
|
+
while (i < command.length && command[i] !== " ") {
|
|
233
|
+
if (command[i] === "'") { const end = command.indexOf("'", i + 1); if (end < 0) return undefined; token += command.slice(i + 1, end); i = end + 1; }
|
|
234
|
+
else if (command[i] === "\\") { token += command[i + 1] ?? ""; i += 2; }
|
|
235
|
+
else if (command[i] === '"') return undefined;
|
|
236
|
+
else token += command[i++];
|
|
237
|
+
}
|
|
238
|
+
tokens.push(token);
|
|
239
|
+
}
|
|
240
|
+
const [bun, smol, entry, verb, target, json, ...rest] = tokens;
|
|
241
|
+
if (!bun || !entry || !target || smol !== "--smol" || verb !== "ingest" || rest.length || (json !== undefined && json !== "--json")) return undefined;
|
|
242
|
+
if (!bun.startsWith("/") || !entry.startsWith("/") || !entry.endsWith("/@staix/agent-mem/bin/amem.js") || !/^[a-z]+$/.test(target)) return undefined;
|
|
243
|
+
return { target, bun, entry };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** The Pi extension's launch as a capture command, or undefined when the file is not an amem setup extension. */
|
|
247
|
+
export function piExtensionCommand(image: ConfigImage): string | undefined {
|
|
248
|
+
const match = /^\/\/ amem setup managed session-end ingest;[\s\S]*?spawnSync\(("(?:[^"\\]|\\.)*"), \['--smol', ("(?:[^"\\]|\\.)*"), 'ingest', 'pi'\]/.exec(text(image));
|
|
249
|
+
if (!match) return undefined;
|
|
250
|
+
try { const q = (v: string) => "'" + v.replaceAll("'", "'\\''") + "'"; return `${q(JSON.parse(match[1]!))} --smol ${q(JSON.parse(match[2]!))} ingest pi`; } catch { return undefined; }
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Every amem capture hook of `target` in a hook surface image, with its event, in file order (#512). */
|
|
254
|
+
export function amemCaptureHooks(target: string, image: ConfigImage): { event: string; command: string }[] {
|
|
255
|
+
if (target === "pi") { const command = piExtensionCommand(image); return command ? [{ event: "session_shutdown", command }] : []; }
|
|
256
|
+
const rows = target === "kimi" ? kimiHooks(image).map(row => ({ event: String(row.event), command: typeof row.command === "string" ? row.command : "" }))
|
|
257
|
+
: hooks(json(image), target === "qwen").map(row => ({ event: row.event, command: row.command }));
|
|
258
|
+
// Only the event setup manages: a matching command under another event is not touched by apply, so it is neither removed nor diagnosed.
|
|
259
|
+
return rows.filter(row => row.event === "SessionEnd" && amemCaptureCommand(row.command)?.target === target);
|
|
260
|
+
}
|