@staix/agent-mem 0.26.3 → 0.27.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +11 -9
- package/package.json +1 -1
- package/src/brief-curated-native.ts +1 -1
- package/src/brief-curated.ts +5 -0
- package/src/cli-agent-reads.ts +11 -19
- package/src/cli.ts +85 -21
- package/src/commands-table.ts +8 -2
- package/src/hooks.ts +9 -4
- package/src/index.ts +3 -0
- package/src/mcp-memory.ts +10 -2
- package/src/mcp.ts +1 -1
- package/src/memory/cli-attribution.ts +17 -1
- package/src/memory/commands.ts +16 -6
- package/src/memory/consolidation-model.ts +2 -2
- package/src/memory/formats-raise.ts +114 -0
- package/src/memory/metrics.ts +40 -1
- package/src/memory/recall-staleness.ts +7 -4
- package/src/memory/store.ts +22 -9
- package/src/memory/sync-placement-refusal-category.ts +3 -0
- package/src/memory/sync-placement-refusal.ts +49 -0
- package/src/memory/sync-placement-transport.ts +53 -33
- package/src/memory/sync-progress.ts +11 -6
- package/src/memory/sync.ts +5 -2
- package/src/memory/task-group.ts +33 -0
- package/src/session-brief.ts +39 -13
|
@@ -32,7 +32,9 @@ import type { PruneRow } from "./prune.ts";
|
|
|
32
32
|
import { materializePlacementRows, verifiedPlacementPrunes } from "./sync-placement-materialize.ts";
|
|
33
33
|
import { placementCacheConfigStamp, placementCacheRootStamp, validatePlacementCacheConfig } from "./sync-placement-cache.ts";
|
|
34
34
|
import { PlacementSyncBoundError, placementSyncBoundMessage, placementSyncBoundReceipt, type PlacementSyncBound } from "./sync-placement-bound.ts";
|
|
35
|
-
import type { SyncProgress } from "./sync-progress.ts";
|
|
35
|
+
import type { SyncProgress, SyncProgressPhase } from "./sync-progress.ts";
|
|
36
|
+
import { PlacementSyncRefusal, placementRefusalCategoryOf, placementRefusalMessage, type PlacementRefusalCategory } from "./sync-placement-refusal.ts";
|
|
37
|
+
import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
|
|
36
38
|
|
|
37
39
|
/**
|
|
38
40
|
* #417 proof scope. A complete proof (full writer-install measurement, source, policy and selector recheck) is taken
|
|
@@ -50,7 +52,18 @@ const digest = (v: Uint8Array | string) => createHash("sha256").update(v).digest
|
|
|
50
52
|
const oid = (v: unknown): v is string => typeof v === "string" && v.length === 40 && /^[a-f0-9]+$/.test(v);
|
|
51
53
|
const sameRealm = (a: PlacementRealm, b: PlacementRealm) => canonicalJSON(a) === canonicalJSON(b);
|
|
52
54
|
const physical = (target: Target): PlacementRealm => target.realm.scope === "user" ? { scope: "user" } : { scope: "project", keyHash: digest(target.realm.key) };
|
|
53
|
-
function refuse(): never { throw new
|
|
55
|
+
function refuse(category: PlacementRefusalCategory = "other"): never { throw new PlacementSyncRefusal(category); }
|
|
56
|
+
/** #426: map a foreign error to a category by its class and allowlisted code only, never by its message text. */
|
|
57
|
+
export function classifyPlacementError(error: unknown): PlacementRefusalCategory | undefined {
|
|
58
|
+
try {
|
|
59
|
+
if (!error || typeof error !== "object" || types.isProxy(error)) return undefined;
|
|
60
|
+
if (error instanceof SharedWriterRevisionError) return "writer-pin";
|
|
61
|
+
if (error instanceof SyncPlacementJournalError) { const code = Object.getOwnPropertyDescriptor(error, "code")?.value; return code === "bound" ? "size-bound" : code === "changed" ? "source-selection" : "epoch"; }
|
|
62
|
+
const code = Object.getOwnPropertyDescriptor(error, "code")?.value;
|
|
63
|
+
if (code === "EBUSY" || code === "SQLITE_BUSY" || code === "EAGAIN") return "lock";
|
|
64
|
+
return undefined;
|
|
65
|
+
} catch { return undefined; }
|
|
66
|
+
}
|
|
54
67
|
function directory(file: string): void { const s = lstatSync(file); if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== process.getuid?.() || (s.mode & 0o077) !== 0) refuse(); }
|
|
55
68
|
function emptyHistory(): ShardHistory { return { rows: new Map(), files: new Map(), origins: new Map(), manifests: new Map(), version: "v3" }; }
|
|
56
69
|
/** Internal phase observer is a fault seam, not part of SyncOptions or the package barrel. */
|
|
@@ -68,11 +81,11 @@ class PlacementTransport {
|
|
|
68
81
|
readonly clock: () => number; readonly progress?: SyncProgress; provedAt?: number; bound?: PlacementSyncBound; capturedPolicyVersion?: string;
|
|
69
82
|
constructor(store: MemoryStore, opts: SyncOptions, phase?: Phase, testOnlyError?: (error:unknown)=>void, clock: () => number = () => performance.now()) { this.clock=clock; this.progress=opts.progress; this.testOnlyError=testOnlyError; this.store = store; this.opts = opts; this.phase = phase; this.home = store.profile.home; this.root = join(this.home, "shard-sync-placement"); this.cache = join(this.root, "objects.git"); }
|
|
70
83
|
attest(): void {
|
|
71
|
-
if (!this.opts.placementAttestation || this.opts.screen && !this.opts.policyVersion) refuse();
|
|
84
|
+
if (!this.opts.placementAttestation || this.opts.screen && !this.opts.policyVersion) refuse("policy");
|
|
72
85
|
const value = memoryPolicySnapshot(this.opts.placementAttestation());
|
|
73
|
-
if (!value || value.legacySyncQuiesced !== true || !Array.isArray(value.writers)) refuse();
|
|
86
|
+
if (!value || value.legacySyncQuiesced !== true || !Array.isArray(value.writers)) refuse("writer-pin");
|
|
74
87
|
const writers = [...value.writers].sort((a,b) => a.writerId.localeCompare(b.writerId));
|
|
75
|
-
if(!this.writerInventory||canonicalJSON(writers)!==canonicalJSON(this.writerInventory.writers))refuse();
|
|
88
|
+
if(!this.writerInventory||canonicalJSON(writers)!==canonicalJSON(this.writerInventory.writers))refuse("writer-pin");
|
|
76
89
|
this.writerInventory.assertCurrent();
|
|
77
90
|
}
|
|
78
91
|
metadata(): void {
|
|
@@ -86,7 +99,7 @@ class PlacementTransport {
|
|
|
86
99
|
if (this.homeMutation) assertMutationHandle(this.homeMutation, this.home);
|
|
87
100
|
for (const target of this.targets) if (target.mutation) assertMutationHandle(target.mutation, target.store.dir);
|
|
88
101
|
const markers = readPlacementRuntimeMarkers(this.home), active = readActivePlacementBinding(this.home, markers.profile, markers.shards);
|
|
89
|
-
if (!active || active.profile.placementHead !== this.epochHash || active.epoch.homeHash !== this.journal.epoch.homeHash) refuse();
|
|
102
|
+
if (!active || active.profile.placementHead !== this.epochHash || active.epoch.homeHash !== this.journal.epoch.homeHash) refuse("epoch");
|
|
90
103
|
}
|
|
91
104
|
verify(fresh: boolean): void {
|
|
92
105
|
this.metadata();
|
|
@@ -98,7 +111,7 @@ class PlacementTransport {
|
|
|
98
111
|
if(this.capture){this.lastPolicyHash=this.capture.context.policyHash;this.lastPolicyCheckUnixMs=Date.now();this.policyCheckSource="live";}
|
|
99
112
|
}
|
|
100
113
|
// The host policy version is a cheap callback: compare it on every check, not only on complete proofs.
|
|
101
|
-
if (!complete && this.capture && this.opts.policyVersion && this.opts.policyVersion() !== this.capturedPolicyVersion) refuse();
|
|
114
|
+
if (!complete && this.capture && this.opts.policyVersion && this.opts.policyVersion() !== this.capturedPolicyVersion) refuse("policy");
|
|
102
115
|
this.progress?.proof(complete);
|
|
103
116
|
for (const target of this.targets) for (const check of target.selectorChecks ?? []) check();
|
|
104
117
|
this.metadata();
|
|
@@ -111,6 +124,10 @@ class PlacementTransport {
|
|
|
111
124
|
args(args: string[]): string[] { return ["--no-replace-objects", "--git-dir", this.cache, "-c", "maintenance.auto=false", "-c", "gc.auto=0", "-c", "core.commitGraph=false", ...args]; }
|
|
112
125
|
async git(args: string[]) { return this.call(() => generationSyncGit(this.root, this.args(args), this.opts.signal)); }
|
|
113
126
|
async required(args: string[]): Promise<string> { const result = await this.git(args); if (result.code !== 0) refuse(); return result.out; }
|
|
127
|
+
/** #426: the progress phase this run is in, kept even without a progress reporter so a refusal can name it. */
|
|
128
|
+
phaseNow: SyncProgressPhase = "writer-verification";
|
|
129
|
+
enter(...args: Parameters<SyncProgress["phase"]>): void { this.phaseNow = args[0]; this.progress?.phase(...args); }
|
|
130
|
+
refusal?: PlacementRefusalCategory;
|
|
114
131
|
async observe(phase: PlacementSyncPhase): Promise<void> { await this.phase?.(phase); }
|
|
115
132
|
storage(factual = false): PlacementStorageOptions { if (!this.homeMutation) refuse(); return { mutation: this.homeMutation, assertCurrent: factual ? () => this.metadata() : this.check, ...(this.attemptHash ? { publicationAttemptHash: this.attemptHash } : {}) }; }
|
|
116
133
|
configStamp():string {
|
|
@@ -133,31 +150,31 @@ class PlacementTransport {
|
|
|
133
150
|
}
|
|
134
151
|
async initialize(): Promise<void> {
|
|
135
152
|
const markers = readPlacementRuntimeMarkers(this.home), active = readActivePlacementBinding(this.home, markers.profile, markers.shards);
|
|
136
|
-
if (!active || this.store.profile.publicationFormat !== PLACEMENT_FORMAT || this.store.profile.placementHead !== active.profile.placementHead) refuse();
|
|
153
|
+
if (!active || this.store.profile.publicationFormat !== PLACEMENT_FORMAT || this.store.profile.placementHead !== active.profile.placementHead) refuse("epoch");
|
|
137
154
|
this.epochHash = active.profile.placementHead; this.machineId = active.shards.machine.id; this.revision = readSelector(this.home).revision; this.journal = readPlacementJournal(this.home, this.epochHash); this.writerInventory=readEffectiveSyncPlacementWriters(this.home);this.attest();
|
|
138
155
|
const opened = this.store.openedSyncTargets();
|
|
139
156
|
if (!opened.length || opened.length > 2 || !opened.includes(this.store) || opened.some(item => item.profile.home !== this.home || !item.profile.sharded || !item.profile.generation
|
|
140
|
-
|| !item.profile.shardUser && item.profile.shardKey !== this.store.profile.shardKey)) refuse();
|
|
157
|
+
|| !item.profile.shardUser && item.profile.shardKey !== this.store.profile.shardKey)) refuse("source-selection");
|
|
141
158
|
for (const item of opened) {
|
|
142
159
|
const realm = item.profile.shardUser ? { scope: "user" as const } : { scope: "project" as const, key: item.profile.shardKey! };
|
|
143
160
|
const target = { store: item, realm, generation: item.profile.generation!, rows: new Map(), fetched: new Set(), sources: [], pending: [], origins: new Map(), holds: [], manifests: new Map(), eligible: new Set(), registered: [], objects: [], localPrunes: new Map() } as unknown as Target;
|
|
144
161
|
target.auditor = new ShardHistoryAuditor({ realm, generation: target.generation, placement: true, publicPrune: true,
|
|
145
162
|
git: args => this.required(args), blob: (object, path) => this.blob(object, path), object: (oid,type) => this.rawHistoryObject(oid,type) }); this.targets.push(target);
|
|
146
163
|
}
|
|
147
|
-
if (new Set(this.targets.map(target => shardSyncRef(target.realm))).size !== this.targets.length) refuse();
|
|
148
|
-
if (this.targets.some(target => target.realm.scope === "project" && isLocalKey(target.realm.key)) && this.opts.remote === undefined) refuse();
|
|
164
|
+
if (new Set(this.targets.map(target => shardSyncRef(target.realm))).size !== this.targets.length) refuse("source-selection");
|
|
165
|
+
if (this.targets.some(target => target.realm.scope === "project" && isLocalKey(target.realm.key)) && this.opts.remote === undefined) refuse("remote");
|
|
149
166
|
if (existsSync(this.root)) placementCacheRootStamp(this.home);
|
|
150
167
|
const existing = existsSync(this.root) ? await this.independent() : false;
|
|
151
|
-
if (!existing && !this.opts.remote) refuse();
|
|
168
|
+
if (!existing && !this.opts.remote) refuse("remote");
|
|
152
169
|
this.url = this.opts.remote ?? await this.required(["remote", "get-url", "origin"]);
|
|
153
|
-
if (!this.url || this.url.length > 4096 || this.url.startsWith("-") || /[\r\n\0]/.test(this.url)) refuse();
|
|
154
|
-
if (await this.call(() => (this.opts.visibility ?? remoteVisibility)(this.url)) !== "private") refuse();
|
|
170
|
+
if (!this.url || this.url.length > 4096 || this.url.startsWith("-") || /[\r\n\0]/.test(this.url)) refuse("remote");
|
|
171
|
+
if (await this.call(() => (this.opts.visibility ?? remoteVisibility)(this.url)) !== "private") refuse("remote");
|
|
155
172
|
this.prove(); // a host callout ends any reusable proof
|
|
156
173
|
if (!existsSync(this.root)) mkdirSync(this.root, { mode: 0o700 });
|
|
157
|
-
const transport = acquireMutation(this.root); if (!transport) refuse(); this.rootMutation=transport; this.releases.push(transport);
|
|
158
|
-
const sync = generationSyncLock(this.root); if (!sync) refuse(); this.releases.push(sync);
|
|
174
|
+
const transport = acquireMutation(this.root); if (!transport) refuse("lock"); this.rootMutation=transport; this.releases.push(transport);
|
|
175
|
+
const sync = generationSyncLock(this.root); if (!sync) refuse("lock"); this.releases.push(sync);
|
|
159
176
|
for (const dir of [...new Set([this.home, ...this.targets.map(target => target.store.dir)])].sort()) {
|
|
160
|
-
const handle = acquireMutation(dir); if (!handle) refuse(); this.releases.push(handle); if (dir === this.home) this.homeMutation = handle;
|
|
177
|
+
const handle = acquireMutation(dir); if (!handle) refuse("lock"); this.releases.push(handle); if (dir === this.home) this.homeMutation = handle;
|
|
161
178
|
for (const target of this.targets) if (target.store.dir === dir) target.mutation = handle;
|
|
162
179
|
}
|
|
163
180
|
this.releaseCurated = this.store.beginCuratedCacheUpdate();
|
|
@@ -168,10 +185,10 @@ class PlacementTransport {
|
|
|
168
185
|
if (this.opts.remote) { this.cacheConfigIdentity=undefined; await this.required(previous.code === 0 ? ["remote", "set-url", "origin", this.url] : ["remote", "add", "origin", this.url]); }
|
|
169
186
|
await this.bindCacheConfig();
|
|
170
187
|
for (const args of [["remote", "get-url", "--all", "origin"], ["remote", "get-url", "--push", "--all", "origin"]])
|
|
171
|
-
if (await this.required(args) !== this.url) refuse();
|
|
188
|
+
if (await this.required(args) !== this.url) refuse("remote");
|
|
172
189
|
const reservation = this.journal.publicationReservation;
|
|
173
190
|
const pending = reservation ? readPlacementPublication(this.home, this.epochHash, reservation.attemptHash) : undefined;
|
|
174
|
-
if (!pending || pending.bundle.root.remoteHash === digest(this.url)) { this.
|
|
191
|
+
if (!pending || pending.bundle.root.remoteHash === digest(this.url)) { this.enter("remote-verification"); await this.fetch(); }
|
|
175
192
|
}
|
|
176
193
|
async rawHistoryObject(object:string,type:"commit"|"tree"):Promise<Buffer>{
|
|
177
194
|
// One process per object (#420): the typed SHA-1 below proves type, size and bytes, so no -t/-s preflight is needed.
|
|
@@ -219,7 +236,7 @@ class PlacementTransport {
|
|
|
219
236
|
this.capture = captureSyncPlacementContext(this.home, { attest: this.opts.placementAttestation!, ...(this.opts.policyVersion ? { policyVersion: this.opts.policyVersion } : {}) }, this.targets.map(physical), pending);
|
|
220
237
|
if (this.capture.activeHead !== this.epochHash || this.capture.context.homeHash !== this.journal.epoch.homeHash
|
|
221
238
|
|| canonicalJSON(this.capture.context.writers) !== canonicalJSON(this.writerInventory?.writers)
|
|
222
|
-
|| !!this.writerInventory?.revisionSequence&&this.capture.writerInventory?.revisionHash!==this.writerInventory.revisionHash) refuse();
|
|
239
|
+
|| !!this.writerInventory?.revisionSequence&&this.capture.writerInventory?.revisionHash!==this.writerInventory.revisionHash) refuse("source-selection");
|
|
223
240
|
this.prove();
|
|
224
241
|
}
|
|
225
242
|
async applicationCoordinator(): Promise<ShardSyncApplications> {
|
|
@@ -261,7 +278,7 @@ class PlacementTransport {
|
|
|
261
278
|
const materialized = await materializePlacementRows({capture,projection,generation:this.journal.epoch.generation,
|
|
262
279
|
targets:this.targets.map(target=>({realm:target.realm,generation:target.generation,remote:target.remote,local:target.local,fetched:target.fetched,
|
|
263
280
|
localPrunes:target.localPrunes,pruned:new Set(target.store.prunePort().snapshot().pruned??[])})),
|
|
264
|
-
old,verifiedPrunes:verified,evaluate:value=>this.evaluate(value),createdUnixSeconds,...(frozen?{frozen}:{})
|
|
281
|
+
old,verifiedPrunes:verified,evaluate:value=>this.evaluate(value),createdUnixSeconds,...(frozen?{frozen}:{}),progress:{phase:(name,unit,total)=>this.enter(name,unit,total),advance:()=>this.progress?.advance()},
|
|
265
282
|
readTree:(_index,head)=>this.required(["rev-parse",`${head}^{tree}`]),
|
|
266
283
|
publisherLineages:(index,rows)=>{const target=this.targets[index]!;assertPublisherBoundary(target.store.profile,target.mutation!);return publisherPruneLineages(target.store.profile,target.mutation!,rows);}});
|
|
267
284
|
// The row-evaluation scope closes with a complete proof before any verdict is planned or made durable.
|
|
@@ -274,7 +291,7 @@ class PlacementTransport {
|
|
|
274
291
|
for(const d of decisions)counts[d.eligible?"permitted":d.reason==="source-local"?"local":d.reason&&!other.has(d.reason)?"declined":"held"]++;
|
|
275
292
|
this.progress.counts(counts);
|
|
276
293
|
}
|
|
277
|
-
this.
|
|
294
|
+
this.enter("publication-plan");
|
|
278
295
|
const body={epochHash:this.epochHash,generation:this.journal.epoch.generation,homeHash:capture.context.homeHash,contextHash:placementCaptureContextHash(capture),markerHash:capture.markerHash,
|
|
279
296
|
sourceHash:capture.context.sourceHash,aliasesHash:capture.context.aliasesHash,policyHash:capture.context.policyHash,remoteHash:digest(this.url),
|
|
280
297
|
journal:frozen?.root.journal??{sequence:frontier.sequence,headHash:frontier.headHash},createdUnixSeconds,policySnapshotUnixMs:frozen?.root.policySnapshotUnixMs??this.lastPolicyCheckUnixMs??Date.now(),targets,reservedRecords:0,reservedRecordBytes:[] as number[]};
|
|
@@ -333,7 +350,7 @@ class PlacementTransport {
|
|
|
333
350
|
for(const [index,event]of events.entries()){
|
|
334
351
|
const record=createPlacementRecord(this.epochHash,root.journal.sequence+index+1,head,event);head=record.seal;records.push(record);
|
|
335
352
|
}
|
|
336
|
-
this.
|
|
353
|
+
this.enter(factual?"acknowledgment":"journal","records",count);
|
|
337
354
|
const consumed=read.sequence-root.journal.sequence;
|
|
338
355
|
if(consumed<0||consumed>root.reservedRecords)refuse();
|
|
339
356
|
for(let index=0;index<Math.min(consumed,records.length);index++)
|
|
@@ -407,7 +424,7 @@ class PlacementTransport {
|
|
|
407
424
|
return this.result(false,"unknown","The retained placement attempt may have published; its frozen holds and unknown outcome were preserved. Start a fresh sync to recheck current sources.");
|
|
408
425
|
}
|
|
409
426
|
async materializeObjects(bundle:PlacementPublicationBundle):Promise<void>{
|
|
410
|
-
this.
|
|
427
|
+
this.enter("artifact-construction","objects",this.targets.reduce((sum,target)=>sum+target.objects.length,0));
|
|
411
428
|
for(const target of this.targets)for(const object of target.objects){
|
|
412
429
|
this.check();const file=join(this.root,`.placement-object-${randomBytes(16).toString("hex")}`);this.temporary.push(file);
|
|
413
430
|
const fd=openSync(file,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,0o600);
|
|
@@ -429,7 +446,7 @@ class PlacementTransport {
|
|
|
429
446
|
target.rows = new Map(actual.rows); target.fetched = new Set(actual.rows.keys()); target.origins = new Map(actual.origins);
|
|
430
447
|
} else { target.rows.clear(); target.fetched.clear(); target.candidate = emptyHistory(); }
|
|
431
448
|
}
|
|
432
|
-
this.preflight(false);this.
|
|
449
|
+
this.preflight(false);this.enter("import");
|
|
433
450
|
const applications=await this.applicationCoordinator();await applications.prepare();
|
|
434
451
|
for(const target of this.targets)for(const hold of target.holds)shardInstallHold(this.root,hold);
|
|
435
452
|
await applications.install();
|
|
@@ -447,7 +464,7 @@ class PlacementTransport {
|
|
|
447
464
|
if (existing.code === 1 && planned.expectedCacheHead !== null) refuse();
|
|
448
465
|
await this.required(["update-ref","--no-deref",ref,planned.commit!,planned.expectedCacheHead??"0".repeat(40)]);
|
|
449
466
|
}
|
|
450
|
-
await this.observe("before-receipt");this.
|
|
467
|
+
await this.observe("before-receipt");this.enter("receipt");
|
|
451
468
|
const read=readPlacementPublication(this.home,this.epochHash,root.seal),intent=read.facts.find(fact=>fact.phase==="publication-intent"),journal=readPlacementJournal(this.home,this.epochHash);
|
|
452
469
|
if(!intent)refuse();
|
|
453
470
|
recordPlacementPublicationPhase(this.home,this.epochHash,root.seal,"completed",{intentFactHash:intent.seal,journal:{sequence:journal.sequence,headHash:journal.headHash},
|
|
@@ -467,7 +484,7 @@ class PlacementTransport {
|
|
|
467
484
|
}
|
|
468
485
|
result(ok:boolean,outcome:"committed"|"unknown"|"not-needed",error?:string):SyncResult{
|
|
469
486
|
return{ok,pushed:this.accepted&&(this.attempted||this.recovered&&!!this.current?.bundle.root.targets.some(target=>target.publish)),entries:this.current?.exported??0,...(error?{error}:{}),...(this.applications?{pruneApplication:{...this.applications.application}}:{}),
|
|
470
|
-
placementPublication:{...(this.attemptHash?{attemptHash:this.attemptHash}:{}),outcome,...(this.bound?{bound:this.bound}:{}),withheld:this.current?.withheld??0,exported:this.current?.exported??0,
|
|
487
|
+
placementPublication:{...(this.attemptHash?{attemptHash:this.attemptHash}:{}),outcome,...(this.bound?{bound:this.bound}:{}),...(this.refusal?{refusal:{category:this.refusal,phase:this.phaseNow}}:{}),withheld:this.current?.withheld??0,exported:this.current?.exported??0,
|
|
471
488
|
...(this.lastPolicyHash?{lastPolicyHash:this.lastPolicyHash}:{}),...(this.lastPolicyCheckUnixMs!==undefined?{lastPolicyCheckUnixMs:this.lastPolicyCheckUnixMs,policyCheckSource:this.policyCheckSource??(this.recovered?"durable-intent" as const:"live" as const)}:{}),
|
|
472
489
|
policyCeiling:"last-positive-check-before-in-flight-push",...(this.recovered?{recovered:true}:{})}};
|
|
473
490
|
}
|
|
@@ -477,7 +494,7 @@ class PlacementTransport {
|
|
|
477
494
|
// Success is reported only from the real receipt; a failed or stopped run can never leave a successful status.
|
|
478
495
|
if(result.ok)this.progress?.finish("succeeded");
|
|
479
496
|
else if(this.opts.signal?.aborted)this.progress?.finish("cancelled","cancelled");
|
|
480
|
-
else this.progress?.finish("failed",this.bound?"bound":result.placementPublication?.outcome==="unknown"?"unknown-outcome":"unavailable");
|
|
497
|
+
else this.progress?.finish("failed",this.bound?"bound":result.placementPublication?.outcome==="unknown"?"unknown-outcome":"unavailable",this.bound?"size-bound":this.refusal);
|
|
481
498
|
return result;
|
|
482
499
|
}
|
|
483
500
|
/** Object slots the plan and its reserved journal chunks need, checked before the first durable plan byte. */
|
|
@@ -487,7 +504,7 @@ class PlacementTransport {
|
|
|
487
504
|
}
|
|
488
505
|
async execute():Promise<SyncResult>{
|
|
489
506
|
try{
|
|
490
|
-
this.
|
|
507
|
+
this.enter("writer-verification");
|
|
491
508
|
await this.initialize();
|
|
492
509
|
const reservation=this.journal.publicationReservation,retained=reservation?readPlacementPublication(this.home,this.epochHash,reservation.attemptHash):undefined;
|
|
493
510
|
if(retained){
|
|
@@ -502,9 +519,9 @@ class PlacementTransport {
|
|
|
502
519
|
this.accepted=true;return await this.finish(this.current,true);
|
|
503
520
|
}
|
|
504
521
|
}
|
|
505
|
-
this.
|
|
522
|
+
this.enter("source-capture");
|
|
506
523
|
try { this.preflight();for(const target of this.targets)if(existsSync(join(target.store.dir,"local",`publisher-boundary-${this.machineId}.json`)))assertPublisherBoundary(target.store.profile,target.mutation!);this.startCapture(); }
|
|
507
|
-
catch(error) { if(retained)return await this.terminalUnknown(retained);if(placementSyncBoundReceipt(error))throw error;throw new
|
|
524
|
+
catch(error) { if(retained)return await this.terminalUnknown(retained);if(placementSyncBoundReceipt(error))throw error;throw new PlacementSyncRefusal(placementRefusalCategoryOf(error)??classifyPlacementError(error)??"other"); }
|
|
508
525
|
if(retained){
|
|
509
526
|
const root=retained.bundle.root;
|
|
510
527
|
const stable=root.contextHash===placementCaptureContextHash(this.capture!)&&root.markerHash===this.capture!.markerHash&&root.sourceHash===this.capture!.context.sourceHash
|
|
@@ -528,7 +545,7 @@ class PlacementTransport {
|
|
|
528
545
|
this.prove();this.lastPolicyCheckUnixMs=Date.now();this.lastPolicyHash=material.bundle.root.policyHash;this.policyCheckSource="live";
|
|
529
546
|
if(!read.facts.some(fact=>fact.phase==="publication-intent"))recordPlacementPublicationPhase(this.home,this.epochHash,material.bundle.root.seal,"publication-intent",{artifactFactHash:artifact.seal,policyHash:material.bundle.root.policyHash,policyCheckUnixMs:material.bundle.root.policySnapshotUnixMs},this.storage());
|
|
530
547
|
ensurePlacementPublicationDurability(this.home,this.epochHash,this.storage());
|
|
531
|
-
await this.observe("before-cas");this.
|
|
548
|
+
await this.observe("before-cas");this.enter("publication");this.prove();
|
|
532
549
|
const installedGuard=await this.installedObjectGuard(material.bundle);
|
|
533
550
|
this.prove();for(const target of this.targets)for(const check of target.selectorChecks??[])check();
|
|
534
551
|
installedGuard();
|
|
@@ -548,7 +565,10 @@ class PlacementTransport {
|
|
|
548
565
|
// #419: an expected size refusal before any attempt exists keeps its phase, kind, limit and observed value.
|
|
549
566
|
const bound=this.attemptHash||this.journal?.publicationReservation?undefined:placementSyncBoundReceipt(error);
|
|
550
567
|
if(bound){this.bound=bound;return this.result(false,"not-needed",placementSyncBoundMessage(bound));}
|
|
551
|
-
return this.result(false,
|
|
568
|
+
if(this.attemptHash)return this.result(false,"unknown","Placement sync stopped with a retained attempt that may have published; recheck its exact receipts before another publication.");
|
|
569
|
+
// #426: name the failing check by a fixed category and the phase; never the error's own text, which may carry a path.
|
|
570
|
+
this.refusal=placementRefusalCategoryOf(error)??classifyPlacementError(error)??"other";
|
|
571
|
+
return this.result(false,"not-needed",placementRefusalMessage(this.refusal,this.phaseNow));
|
|
552
572
|
}finally{
|
|
553
573
|
let ownedCache=true;try{this.metadata();}catch{ownedCache=false;}
|
|
554
574
|
if(ownedCache){
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
import { randomBytes } from "node:crypto";
|
|
10
10
|
import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, opendirSync, readSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
11
11
|
import { join } from "node:path";
|
|
12
|
+
import { PLACEMENT_REFUSAL_CATEGORIES, type PlacementRefusalCategory } from "./sync-placement-refusal-category.ts";
|
|
12
13
|
import { processLiveness, processSignature, type Liveness } from "./platform.ts";
|
|
13
14
|
|
|
14
15
|
export const SYNC_PROGRESS_SCHEMA = "agent-mem.sync-progress/v1", SYNC_PROGRESS_INTERVAL_MS = 1000, SYNC_PROGRESS_DIR = "sync-status";
|
|
@@ -35,6 +36,8 @@ export interface SyncProgressSnapshot {
|
|
|
35
36
|
/** Advances only when a unit of work or a phase completes; `lastAliveUnixMs` is any checkpoint the process reached. */
|
|
36
37
|
lastWorkProgressUnixMs: number; lastAliveUnixMs: number;
|
|
37
38
|
cause?: SyncProgressCause;
|
|
39
|
+
/** #426: for a failed placement sync, the fixed category of the check that refused (allowlisted, no text). */
|
|
40
|
+
category?: PlacementRefusalCategory;
|
|
38
41
|
}
|
|
39
42
|
export type SyncProgressSink = (snapshot: SyncProgressSnapshot) => void;
|
|
40
43
|
export interface SyncProgressOptions { sink: SyncProgressSink; intervalMs?: number; now?: () => number; mono?: () => number; operationId?: string }
|
|
@@ -46,7 +49,7 @@ export class SyncProgress {
|
|
|
46
49
|
private readonly started: number; private readonly startedMono: number; private phaseMono: number; private emitted = -Infinity;
|
|
47
50
|
private current: SyncProgressPhase = "writer-verification"; private readonly entered = new Map<SyncProgressPhase, number>();
|
|
48
51
|
private unit?: SyncProgressUnit; private completed?: number; private total?: number; private outcome?: SyncProgressCounts;
|
|
49
|
-
private state: SyncProgressState = "running"; private cause?: SyncProgressCause; private work: number; private aliveAt: number;
|
|
52
|
+
private state: SyncProgressState = "running"; private cause?: SyncProgressCause; private category?: PlacementRefusalCategory; private work: number; private aliveAt: number;
|
|
50
53
|
private readonly proofs = { complete: 0, fence: 0 };
|
|
51
54
|
constructor(options: SyncProgressOptions) {
|
|
52
55
|
this.sink = options.sink; this.intervalMs = Math.max(0, options.intervalMs ?? SYNC_PROGRESS_INTERVAL_MS);
|
|
@@ -60,7 +63,7 @@ export class SyncProgress {
|
|
|
60
63
|
startedUnixMs: this.started, elapsedMs: Math.round(mono - this.startedMono), phaseElapsedMs: Math.round(mono - this.phaseMono),
|
|
61
64
|
...(this.unit ? { unit: this.unit, completed: this.completed ?? 0, ...(this.total !== undefined ? { total: this.total } : {}) } : {}),
|
|
62
65
|
...(this.outcome ? { counts: { ...this.outcome } } : {}), proofs: { ...this.proofs },
|
|
63
|
-
lastWorkProgressUnixMs: this.work, lastAliveUnixMs: this.aliveAt, ...(this.cause ? { cause: this.cause } : {}) };
|
|
66
|
+
lastWorkProgressUnixMs: this.work, lastAliveUnixMs: this.aliveAt, ...(this.cause ? { cause: this.cause } : {}), ...(this.category ? { category: this.category } : {}) };
|
|
64
67
|
}
|
|
65
68
|
private emit(force: boolean): void {
|
|
66
69
|
if (!this.sink) return; const mono = this.mono();
|
|
@@ -80,8 +83,9 @@ export class SyncProgress {
|
|
|
80
83
|
proof(complete: boolean): void { this.proofs[complete ? "complete" : "fence"]++; this.alive(); }
|
|
81
84
|
counts(counts: SyncProgressCounts): void { this.outcome = { ...counts }; }
|
|
82
85
|
/** Terminal state. Success is reported only by the caller that holds the real sync receipt. */
|
|
83
|
-
finish(state: Exclude<SyncProgressState, "running" | "interrupted">, cause?: SyncProgressCause): void {
|
|
84
|
-
if (this.state !== "running") return; this.state = state; this.cause = state === "succeeded" ? undefined : cause;
|
|
86
|
+
finish(state: Exclude<SyncProgressState, "running" | "interrupted">, cause?: SyncProgressCause, category?: PlacementRefusalCategory): void {
|
|
87
|
+
if (this.state !== "running") return; this.state = state; this.cause = state === "succeeded" ? undefined : cause;
|
|
88
|
+
this.category = state === "failed" && category && (PLACEMENT_REFUSAL_CATEGORIES as readonly string[]).includes(category) ? category : undefined; this.aliveAt = this.now();
|
|
85
89
|
if (state === "succeeded") this.work = this.aliveAt; this.emit(true);
|
|
86
90
|
}
|
|
87
91
|
}
|
|
@@ -92,7 +96,7 @@ export function renderSyncProgress(snapshot: SyncProgressSnapshot, now = Date.no
|
|
|
92
96
|
const phase = snapshot.phase.replaceAll("-", " "), units = snapshot.unit ? `: ${snapshot.completed ?? 0}${snapshot.total !== undefined ? `/${snapshot.total}` : ""} ${snapshot.unit}` : "";
|
|
93
97
|
const counts = snapshot.counts ? `; permitted ${snapshot.counts.permitted}, local ${snapshot.counts.local}, declined ${snapshot.counts.declined}, held ${snapshot.counts.held}` : "";
|
|
94
98
|
const attempt = snapshot.attempt > 1 ? `; attempt ${snapshot.attempt}` : "";
|
|
95
|
-
if (snapshot.state !== "running") return `amem sync: ${snapshot.state}${snapshot.cause ? ` (${snapshot.cause})` : ""} in ${phase}${units}${counts}; elapsed ${seconds(snapshot.elapsedMs)}`;
|
|
99
|
+
if (snapshot.state !== "running") return `amem sync: ${snapshot.state}${snapshot.cause ? ` (${snapshot.cause}${snapshot.category ? `, ${snapshot.category}` : ""})` : ""} in ${phase}${units}${counts}; elapsed ${seconds(snapshot.elapsedMs)}`;
|
|
96
100
|
return `amem sync: ${phase}${units}${attempt}${counts}; elapsed ${seconds(snapshot.elapsedMs)}; last work progress ${seconds(now - snapshot.lastWorkProgressUnixMs)} ago`;
|
|
97
101
|
}
|
|
98
102
|
|
|
@@ -127,13 +131,14 @@ function validate(value: unknown, operationId: string): { snapshot: SyncProgress
|
|
|
127
131
|
|| !proofs || !count(proofs.complete) || !count(proofs.fence) || !owner || !count(owner.pid) || owner.signature !== undefined && (typeof owner.signature !== "string" || owner.signature.length > 256)
|
|
128
132
|
|| v.unit !== undefined && (!(UNITS as readonly unknown[]).includes(v.unit) || !count(v.completed)) || v.total !== undefined && !count(v.total)
|
|
129
133
|
|| v.cause !== undefined && !(CAUSES as readonly unknown[]).includes(v.cause)
|
|
134
|
+
|| v.category !== undefined && !(PLACEMENT_REFUSAL_CATEGORIES as readonly unknown[]).includes(v.category)
|
|
130
135
|
|| counts !== undefined && ![counts.permitted, counts.local, counts.declined, counts.held].every(count)) return undefined;
|
|
131
136
|
const snapshot: SyncProgressSnapshot = { schema: SYNC_PROGRESS_SCHEMA, operationId, state: v.state as SyncProgressState, phase: v.phase as SyncProgressPhase, attempt: v.attempt as number,
|
|
132
137
|
startedUnixMs: v.startedUnixMs as number, elapsedMs: v.elapsedMs as number, phaseElapsedMs: v.phaseElapsedMs as number,
|
|
133
138
|
...(v.unit !== undefined ? { unit: v.unit as SyncProgressUnit, completed: v.completed as number, ...(v.total !== undefined ? { total: v.total as number } : {}) } : {}),
|
|
134
139
|
...(counts ? { counts: { permitted: counts.permitted as number, local: counts.local as number, declined: counts.declined as number, held: counts.held as number } } : {}),
|
|
135
140
|
proofs: { complete: proofs.complete as number, fence: proofs.fence as number }, lastWorkProgressUnixMs: v.lastWorkProgressUnixMs as number, lastAliveUnixMs: v.lastAliveUnixMs as number,
|
|
136
|
-
...(v.cause !== undefined ? { cause: v.cause as SyncProgressCause } : {}) };
|
|
141
|
+
...(v.cause !== undefined ? { cause: v.cause as SyncProgressCause } : {}), ...(v.category !== undefined ? { category: v.category as PlacementRefusalCategory } : {}) };
|
|
137
142
|
return { snapshot, owner: { pid: owner.pid as number, ...(typeof owner.signature === "string" ? { signature: owner.signature } : {}) } };
|
|
138
143
|
}
|
|
139
144
|
function load(dir: string, name: string): { snapshot: SyncProgressSnapshot; owner: Owner } | undefined {
|
package/src/memory/sync.ts
CHANGED
|
@@ -13,7 +13,8 @@ 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 { SyncProgress } from "./sync-progress.ts";
|
|
16
|
+
import type { SyncProgress, SyncProgressPhase } from "./sync-progress.ts";
|
|
17
|
+
import type { PlacementRefusalCategory } from "./sync-placement-refusal.ts";
|
|
17
18
|
|
|
18
19
|
/**
|
|
19
20
|
* #258 phase 2: hub memory between a person's machines through a git remote they configure. The memory directory is a
|
|
@@ -25,7 +26,9 @@ export interface SyncResult { ok: boolean; pushed: boolean; entries: number; war
|
|
|
25
26
|
placementPublication?: { attemptHash?: string; outcome: "committed" | "unknown" | "not-needed"; withheld: number; exported: number;
|
|
26
27
|
lastPolicyHash?: string; lastPolicyCheckUnixMs?: number; policyCheckSource?: "live" | "durable-intent"; policyCeiling: "last-positive-check-before-in-flight-push"; recovered?: boolean;
|
|
27
28
|
/** #419: an expected size refusal before any publication attempt; numbers only. */
|
|
28
|
-
bound?: PlacementSyncBound
|
|
29
|
+
bound?: PlacementSyncBound;
|
|
30
|
+
/** #426: the fixed category and phase of a refusal before any publication attempt; no path, row or secret. */
|
|
31
|
+
refusal?: { category: PlacementRefusalCategory; phase: SyncProgressPhase } };
|
|
29
32
|
pruneApplication?: {transport:"durable"|"unconfirmed";proofComplete:number;projectionActive:number|null;nativeApplied:number|null;held:number;phase:"preflight"|"prepared"|"active"|"complete"};
|
|
30
33
|
}
|
|
31
34
|
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { View } from "./store.ts";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* #423: the task a curated note belongs to, for grouping. A note's own `task` wins; otherwise the first `task:` node in
|
|
5
|
+
* `about` (sorted, so every reader picks the same one). The `@<created>` suffix is dropped so a note written with a task
|
|
6
|
+
* and a note that only mentions "task #N" in the same project fold together. Notes without a task never group, and a
|
|
7
|
+
* `shared` note never folds with a project note.
|
|
8
|
+
*/
|
|
9
|
+
export function taskGroupKey(view: Pick<View, "task" | "about" | "project"> & { scope?: View["scope"] }): string | undefined {
|
|
10
|
+
const raw = view.task ?? view.about.find(node => node.startsWith("task:"))?.slice(5);
|
|
11
|
+
if (!raw) return undefined;
|
|
12
|
+
const task = raw.includes("#") ? raw.replace(/@\d+$/, "") : `${view.project}#${raw.replace(/@\d+$/, "")}`;
|
|
13
|
+
// A shared note and a project note of one task are different audiences: never fold one into the other.
|
|
14
|
+
return view.scope === "shared" ? `shared:${task}` : task;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* #423: keep the first item of each task group, in input order (callers pass items best first), and count the items
|
|
19
|
+
* it folded in. Items with no curated view or no task are kept as they are with `folded: 0`. Read-time only: rows and
|
|
20
|
+
* the derived index are untouched.
|
|
21
|
+
*/
|
|
22
|
+
export function groupByTask<T>(items: readonly T[], view: (item: T) => (Pick<View, "task" | "about" | "project"> & { scope?: View["scope"] }) | undefined): { item: T; folded: number }[] {
|
|
23
|
+
const out: { item: T; folded: number }[] = [], leader = new Map<string, { item: T; folded: number }>();
|
|
24
|
+
for (const item of items) {
|
|
25
|
+
const v = view(item), key = v ? taskGroupKey(v) : undefined;
|
|
26
|
+
const head = key === undefined ? undefined : leader.get(key);
|
|
27
|
+
if (head) { head.folded++; continue; }
|
|
28
|
+
const entry = { item, folded: 0 };
|
|
29
|
+
if (key !== undefined) leader.set(key, entry);
|
|
30
|
+
out.push(entry);
|
|
31
|
+
}
|
|
32
|
+
return out;
|
|
33
|
+
}
|
package/src/session-brief.ts
CHANGED
|
@@ -17,10 +17,12 @@ import { pendingLine, pendingSummary } from "./memory/candidate-pending.ts";
|
|
|
17
17
|
import { memoryProjectKey } from "./memory/project.ts";
|
|
18
18
|
import { registerReaderLease } from "./memory/reader-lease.ts";
|
|
19
19
|
import { type ReadRef, type ReadWindow } from "./memory/search-fts.ts";
|
|
20
|
+
import { briefFailureReason } from "./memory/metrics.ts";
|
|
20
21
|
import { aliasedKeys, captureShardDir, readShardedSelection, resolveAlias, shardDir } from "./memory/shard.ts";
|
|
21
22
|
import { projectState } from "./memory/lifecycle.ts";
|
|
22
23
|
import { boundRepoRoot, nearestRepoRootWithLog, readRepoScope, repoLogNearby, repoLogPresent, repoReadPolicy, type RepoView } from "./memory/repo-scope.ts";
|
|
23
|
-
import type { MemoryStore } from "./memory/store.ts";
|
|
24
|
+
import type { MemoryStore, View } from "./memory/store.ts";
|
|
25
|
+
import { taskGroupKey } from "./memory/task-group.ts";
|
|
24
26
|
import { WorkListStore, type WorkListFields, type WorkListView } from "./memory/work-lists.ts";
|
|
25
27
|
|
|
26
28
|
export interface BriefOptions { cwd: string; base?: string; project?: string; maxTokens?: number; policy?: StandalonePolicyOptions;
|
|
@@ -129,8 +131,9 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
|
|
|
129
131
|
if (repoLogPresent(repoRoot)) coverage.repo = "complete";
|
|
130
132
|
const lines: string[] = [];
|
|
131
133
|
const reasons: Partial<Record<Section, string>> = {};
|
|
132
|
-
//
|
|
133
|
-
|
|
134
|
+
// Native reasons are accounted for after selection; ordinary briefs keep their existing conservative reservation.
|
|
135
|
+
const reservedHeader = options.nativeSession ? header(coverage) : header({ work: "unavailable", curated: "unavailable", capture: "unavailable", ...(coverage.repo ? { repo: "unavailable" as const } : {}) });
|
|
136
|
+
let remaining = maximum - Buffer.byteLength(reservedHeader);
|
|
134
137
|
// F7: one line, "N candidates pending, oldest expires in D days", only when some wait, so a brief with none is byte-identical to before. It is numbers only (no candidate text),
|
|
135
138
|
// read-only (no database is created, pruned or altered here, and neither the brief nor the hook ever stamps a candidate as shown: only `amem review walk` does) and reserved out of the
|
|
136
139
|
// same byte budget as everything else; when it does not fit it is left out.
|
|
@@ -155,7 +158,7 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
|
|
|
155
158
|
const deferredReason = sharded || readSelector(base).selector?.kind === "generation" ? "generation refresh deferred" : "curated refresh deferred";
|
|
156
159
|
const prepared = readCuratedBriefCache({ base, project, profile: curatedProfileBinding(base, project),
|
|
157
160
|
supportingRelease: CURATED_CACHE_MIN_READER, deferredReason, now: (options.now ?? Date.now)() });
|
|
158
|
-
if (!prepared.cache) { coverage.curated = "unavailable"; reasons.curated = prepared.reason
|
|
161
|
+
if (!prepared.cache) { coverage.curated = "unavailable"; reasons.curated = `${prepared.reason!}; use amem_brief`; }
|
|
159
162
|
else {
|
|
160
163
|
coverage.curated = prepared.cache.partial ? "partial" : "complete";
|
|
161
164
|
for (const row of prepared.cache.rows) {
|
|
@@ -189,8 +192,8 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
|
|
|
189
192
|
if (!floorReason) try { machine = JSON.parse(readFileSync(join(base, "machine.json"), "utf8")).id; } catch { /* no machine, no cache */ }
|
|
190
193
|
const cache = !floorReason && typeof machine === "string" && /^[a-f0-9]{16}$/.test(machine)
|
|
191
194
|
? readBriefCache({ directory: captureShardDir(base, project, machine), project, section: "capture" }) : undefined;
|
|
192
|
-
if (floorReason) { coverage.capture = "unavailable"; reasons.capture = floorReason; }
|
|
193
|
-
else if (!cache) { coverage.capture = "unavailable"; reasons.capture = "capture cache missing"; }
|
|
195
|
+
if (floorReason) { coverage.capture = "unavailable"; reasons.capture = `${floorReason}; use amem_search`; }
|
|
196
|
+
else if (!cache) { coverage.capture = "unavailable"; reasons.capture = "capture cache missing; use amem_search"; }
|
|
194
197
|
else {
|
|
195
198
|
coverage.capture = cache.partial ? "partial" : "complete";
|
|
196
199
|
for (const row of cache.rows) {
|
|
@@ -227,6 +230,10 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
|
|
|
227
230
|
const reservedSummary = newest && newest.size - 1 <= RECORD_BYTES && newest.size <= remaining ? newest : undefined;
|
|
228
231
|
if (reservedSummary) remaining -= reservedSummary.size;
|
|
229
232
|
else if (newest) coverage.capture = "partial";
|
|
233
|
+
const firstRecord = coverage.repo ? preparedRecords[0] : undefined;
|
|
234
|
+
const reservedRecord = firstRecord && firstRecord.size - 1 <= RECORD_BYTES && firstRecord.size <= remaining ? firstRecord : undefined;
|
|
235
|
+
if (reservedRecord) remaining -= reservedRecord.size;
|
|
236
|
+
else if (firstRecord) coverage.capture = "partial";
|
|
230
237
|
const emitPrepared = (row: PreparedCapture): boolean => {
|
|
231
238
|
if (row.size - 1 > RECORD_BYTES || row.size > remaining) { coverage.capture = "partial"; return false; }
|
|
232
239
|
lines.push(row.line); remaining -= row.size;
|
|
@@ -250,13 +257,16 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
|
|
|
250
257
|
guard();
|
|
251
258
|
// ponytail: reserve cold-store variance plus cleanup/serialization before optional work.
|
|
252
259
|
// A future paged deadline port can refine this section-level cutoff; the parent remains the hard stop.
|
|
253
|
-
if (options.timeRemaining && options.timeRemaining() < (section === "work" ? 10 : 80)) { coverage[section] = "unavailable"; if (options.nativeSession) reasons[section] =
|
|
260
|
+
if (options.timeRemaining && options.timeRemaining() < (section === "work" ? 10 : 80)) { coverage[section] = "unavailable"; if (options.nativeSession) reasons[section] = `deadline exhausted; ${section === "repo" ? "inspect repo log" : `use ${section === "work" ? "amem_work_state_read" : section === "curated" ? "amem_brief" : "amem_search"}`}`; return; }
|
|
254
261
|
await work(); guard();
|
|
255
262
|
}
|
|
256
263
|
catch (error) {
|
|
257
264
|
if (error instanceof BindingChanged || drifted) throw new BindingChanged();
|
|
258
265
|
lines.splice(firstLine); remaining = priorRemaining; coverage[section] = "unavailable";
|
|
259
|
-
if (options.nativeSession)
|
|
266
|
+
if (options.nativeSession) {
|
|
267
|
+
const cause = briefFailureReason(error, options.timeRemaining);
|
|
268
|
+
reasons[section] = `${cause}; ${section === "repo" ? "inspect repo log" : `use ${section === "work" ? "amem_work_state_read" : section === "curated" ? "amem_brief" : "amem_search"}`}`;
|
|
269
|
+
}
|
|
260
270
|
}
|
|
261
271
|
};
|
|
262
272
|
if (remaining < 0) {
|
|
@@ -279,6 +289,7 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
|
|
|
279
289
|
const recent = async <T>(section: "curated" | "capture", read: (window: ReadWindow) => { rows: T[]; next?: ReadRef },
|
|
280
290
|
display: (row: T) => { data: unknown; partial: boolean }, selectedBefore = 0, skipCaptureIds: ReadonlySet<number> = new Set()) => {
|
|
281
291
|
let after: ReadWindow["after"], selected = selectedBefore, complete = false;
|
|
292
|
+
const tasks = new Set<string>(); // #423: one curated row per task, the newest; later same-task rows take no slot
|
|
282
293
|
for (let pageNumber = 0; pageNumber < MAX_PAGES; pageNumber++) {
|
|
283
294
|
guard();
|
|
284
295
|
if (options.nativeSession && options.timeRemaining && options.timeRemaining() <= 0) throw new Error("brief deadline");
|
|
@@ -291,6 +302,9 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
|
|
|
291
302
|
// Records have their own five-row, whole-line selection before raw captures.
|
|
292
303
|
if (section === "capture" && (row as { event?: unknown }).event === "Record") continue;
|
|
293
304
|
if (!await screen(row)) continue;
|
|
305
|
+
const group = section === "curated" ? taskGroupKey(row as unknown as View) : undefined;
|
|
306
|
+
if (group !== undefined && tasks.has(group)) continue;
|
|
307
|
+
if (group !== undefined) tasks.add(group);
|
|
294
308
|
if (selected++ >= SECTION_RECORDS) { coverage[section] = "partial"; return; }
|
|
295
309
|
await add(section, display(row), section === "curated");
|
|
296
310
|
}
|
|
@@ -324,10 +338,10 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
|
|
|
324
338
|
});
|
|
325
339
|
if (coverage.repo) await run("repo", async () => {
|
|
326
340
|
const scoped = repoReadPolicy(repoRoot!, configuredPolicyOptions(base, cwd, options.policy));
|
|
327
|
-
if ("reason" in scoped) { coverage.repo = "unavailable"; reasons.repo = "repo policy unreadable"; return; }
|
|
341
|
+
if ("reason" in scoped) { coverage.repo = "unavailable"; reasons.repo = "repo policy unreadable; inspect repo policy"; return; }
|
|
328
342
|
// The newest few rows only, and never past the caller's deadline: the read stops (partial) when less than the reserve is left, so a 1 MiB log cannot spend the hook's budget.
|
|
329
343
|
const repo = await readRepoScope(repoRoot, scoped.policy, { limit: SECTION_RECORDS + 1, ...(options.timeRemaining ? { remainingMs: options.timeRemaining, reserveMs: 20 } : {}) }); guard();
|
|
330
|
-
if (repo.state === "unsafe") { coverage.repo = "unavailable"; reasons.repo = "repo log is not a plain file"; return; }
|
|
344
|
+
if (repo.state === "unsafe") { coverage.repo = "unavailable"; reasons.repo = "repo log is not a plain file; inspect repo log"; return; }
|
|
331
345
|
if (repo.partial || repo.skipped.withheld) coverage.repo = "partial";
|
|
332
346
|
let shownRepo = 0; // not `selected`: scripts/measure-hook-stages.ts anchors on that exact line once
|
|
333
347
|
for (const view of repo.views) {
|
|
@@ -336,7 +350,8 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
|
|
|
336
350
|
}
|
|
337
351
|
});
|
|
338
352
|
if (nativeCache) {
|
|
339
|
-
|
|
353
|
+
if (reservedRecord) { lines.push(reservedRecord.line); if (reservedRecord.partial) coverage.capture = "partial"; }
|
|
354
|
+
for (const row of preparedRecords.slice(reservedRecord ? 1 : 0)) emitPrepared(row);
|
|
340
355
|
emitReserved();
|
|
341
356
|
for (const row of preparedSummaries.slice(1)) emitPrepared(row);
|
|
342
357
|
} else {
|
|
@@ -365,8 +380,19 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
|
|
|
365
380
|
}
|
|
366
381
|
}
|
|
367
382
|
guard();
|
|
368
|
-
|
|
369
|
-
|
|
383
|
+
let context = [header(coverage, reasons), ...(candidateLine ? [candidateLine] : []), ...lines].join("\n");
|
|
384
|
+
while (Buffer.byteLength(context) > maximum && lines.length) {
|
|
385
|
+
const repoIndex = lines.findLastIndex(line => line.startsWith('{"section":"repo",'));
|
|
386
|
+
const removed = JSON.parse(lines.splice(repoIndex >= 0 ? repoIndex : lines.length - 1, 1)[0]!) as { section?: Section };
|
|
387
|
+
if (removed.section && coverage[removed.section] === "complete") coverage[removed.section] = "partial";
|
|
388
|
+
context = [header(coverage, reasons), ...(candidateLine ? [candidateLine] : []), ...lines].join("\n");
|
|
389
|
+
}
|
|
390
|
+
if (Buffer.byteLength(context) > maximum && candidateLine) {
|
|
391
|
+
candidateLine = undefined;
|
|
392
|
+
context = [header(coverage, reasons), ...lines].join("\n");
|
|
393
|
+
}
|
|
394
|
+
if (Buffer.byteLength(context) > maximum) result = unavailable();
|
|
395
|
+
else result = { context, tokens: Buffer.byteLength(context), partial: Object.values(coverage).some(value => value !== "complete"), coverage };
|
|
370
396
|
}
|
|
371
397
|
} catch { result = unavailable(); }
|
|
372
398
|
finally {
|