@staix/agent-mem 0.28.1 → 0.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +11 -7
- package/package.json +1 -1
- package/src/brief-work.ts +142 -0
- package/src/cli.ts +34 -3
- package/src/commands-table.ts +2 -0
- package/src/mcp-memory.ts +1 -1
- package/src/memory/commands.ts +5 -3
- package/src/memory/curated-cache-state.ts +10 -7
- package/src/memory/doctor.ts +15 -12
- package/src/memory/generation-index.ts +79 -17
- package/src/memory/index-file.ts +2 -2
- package/src/memory/metrics.ts +1 -0
- package/src/memory/public-prune-advance.ts +2 -1
- package/src/memory/shard-sync-applications.ts +1 -1
- package/src/memory/shard-sync-history.ts +6 -0
- package/src/memory/shard.ts +41 -14
- package/src/memory/store.ts +147 -41
- package/src/memory/sync-placement-capture.ts +53 -17
- package/src/memory/sync-placement-guard.ts +52 -1
- package/src/memory/sync-placement-inventory.ts +136 -0
- package/src/memory/sync-placement-journal-storage.ts +21 -4
- package/src/memory/sync-placement-journal.ts +13 -4
- package/src/memory/sync-placement-materialize.ts +14 -3
- package/src/memory/sync-placement-publication-plan.ts +8 -4
- package/src/memory/sync-placement-realm-admission-storage.ts +128 -0
- package/src/memory/sync-placement-realm-admission.ts +335 -0
- package/src/memory/sync-placement-realm-attribution.ts +23 -0
- package/src/memory/sync-placement-realm-effective.ts +71 -0
- package/src/memory/sync-placement-realm-extension-format.ts +66 -0
- package/src/memory/sync-placement-realm-extension-storage.ts +82 -0
- package/src/memory/sync-placement-realm-intent-format.ts +55 -0
- package/src/memory/sync-placement-realm-intent-storage.ts +123 -0
- package/src/memory/sync-placement-realm-pending.ts +27 -0
- package/src/memory/sync-placement-realm-proof.ts +131 -0
- package/src/memory/sync-placement-realm-torn.ts +26 -0
- package/src/memory/sync-placement-transport.ts +70 -31
- package/src/memory/sync-placement-yield.ts +30 -0
- package/src/memory/sync-progress.ts +47 -6
- package/src/memory/sync.ts +23 -1
- package/src/memory/work-lists.ts +129 -9
- package/src/session-brief.ts +34 -1
|
@@ -109,11 +109,15 @@ export class GenerationIndex {
|
|
|
109
109
|
constructor(private readonly options: GenerationIndexOptions) {
|
|
110
110
|
this.profile = options.profile;
|
|
111
111
|
const db = options.db;
|
|
112
|
+
db.run("CREATE TABLE IF NOT EXISTS generation_state (key TEXT PRIMARY KEY, value TEXT NOT NULL)");
|
|
112
113
|
if (this.profile.foreignPruneFormat) {
|
|
113
114
|
db.run("CREATE TABLE IF NOT EXISTS generation_foreign_inputs (id TEXT PRIMARY KEY)");
|
|
114
115
|
db.run("CREATE TABLE IF NOT EXISTS generation_foreign_rows (id TEXT PRIMARY KEY, hash TEXT NOT NULL)");
|
|
115
116
|
db.run("CREATE TABLE IF NOT EXISTS generation_foreign_targets (id TEXT PRIMARY KEY)");
|
|
116
|
-
|
|
117
|
+
// #466: a stored stamp is the proof that the three tables below came from this view, so a reopen replays nothing.
|
|
118
|
+
// A missing stamp (an index written before it existed) still rebuilds once.
|
|
119
|
+
this.foreignStamp = this.persistedForeignStamp();
|
|
120
|
+
this.replayProvenance = this.foreignStamp === undefined; // persistent SQLite never supplies foreign membership by itself
|
|
117
121
|
}
|
|
118
122
|
db.run("CREATE TABLE IF NOT EXISTS generation_rows (id TEXT PRIMARY KEY, line TEXT NOT NULL, local INTEGER NOT NULL, public INTEGER NOT NULL, own INTEGER NOT NULL, legacy INTEGER NOT NULL)");
|
|
119
123
|
if (!(db.query("PRAGMA table_info(generation_rows)").all() as { name: string }[]).some(row => row.name === "legacy")) { db.run("ALTER TABLE generation_rows ADD COLUMN legacy INTEGER NOT NULL DEFAULT 0"); this.replayProvenance = true; }
|
|
@@ -122,7 +126,6 @@ export class GenerationIndex {
|
|
|
122
126
|
db.run("CREATE TABLE IF NOT EXISTS generation_targets (id TEXT PRIMARY KEY)");
|
|
123
127
|
db.run("CREATE TABLE IF NOT EXISTS generation_segments (source TEXT NOT NULL, path TEXT NOT NULL, offset INTEGER NOT NULL, hash TEXT NOT NULL, commit_id TEXT, stamp TEXT, PRIMARY KEY(source,path))");
|
|
124
128
|
if (!(db.query("PRAGMA table_info(generation_segments)").all() as { name: string }[]).some(row => row.name === "stamp")) db.run("ALTER TABLE generation_segments ADD COLUMN stamp TEXT");
|
|
125
|
-
db.run("CREATE TABLE IF NOT EXISTS generation_state (key TEXT PRIMARY KEY, value TEXT NOT NULL)");
|
|
126
129
|
}
|
|
127
130
|
private ownSegments(reader: SegmentReader = this.reader, full = this.fullCapture, inspect?: LegacySegmentInspector): LegacySegment[] {
|
|
128
131
|
const prior = sourceMetadataRows<LegacyCheckpoint & { stamp: string | null }>(this.options.db, "SELECT source,path,offset,hash,commit_id,stamp FROM generation_segments WHERE source='generation'", !!inspect);
|
|
@@ -185,7 +188,8 @@ export class GenerationIndex {
|
|
|
185
188
|
return { segments: [...legacy, ...own], ...(commit ? { commit } : {}) };
|
|
186
189
|
}
|
|
187
190
|
private index(captured: { segments: LegacySegment[]; commit?: string }): void {
|
|
188
|
-
const db = this.options.db;
|
|
191
|
+
const db = this.options.db, touched = new Set<string>();
|
|
192
|
+
let pruneInserted = false;
|
|
189
193
|
for (const segment of captured.segments) {
|
|
190
194
|
const consumed = (db.query("SELECT offset FROM generation_segments WHERE source=? AND path=?").get(segment.source, segment.path) as { offset: number } | null)?.offset ?? 0;
|
|
191
195
|
if ((segment.start ?? 0) > consumed) return fail();
|
|
@@ -195,7 +199,7 @@ export class GenerationIndex {
|
|
|
195
199
|
if (segment.source === "generation" && parsed && typeof parsed === "object" && (parsed as { op?: string }).op === "prune") {
|
|
196
200
|
const row = validatePruneRow(parsed, this.profile.generation, segment.local ? "local" : "synced");
|
|
197
201
|
if (segment.path !== `${segment.local ? "local" : "log"}/${row.machine}.jsonl`) fail();
|
|
198
|
-
db.query("INSERT OR IGNORE INTO generation_prunes VALUES (?,?,?)").run(row.id, canonicalJSON(row), Number(segment.local));
|
|
202
|
+
if (db.query("INSERT OR IGNORE INTO generation_prunes VALUES (?,?,?)").run(row.id, canonicalJSON(row), Number(segment.local)).changes > 0) pruneInserted = true;
|
|
199
203
|
continue;
|
|
200
204
|
}
|
|
201
205
|
if (segment.source === "generation" && parsed && typeof parsed === "object" && (parsed as { op?: string }).op === "vault_link") {
|
|
@@ -213,32 +217,82 @@ export class GenerationIndex {
|
|
|
213
217
|
const presence = coalesceGenerationSource(old ? { row, placement: old.local ? "local" : "synced", publicWitness: !!old.public, own: !!old.own, legacy: !!old.legacy } : undefined, row, segment);
|
|
214
218
|
db.query("INSERT INTO generation_rows VALUES (?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET local=MIN(local,excluded.local), public=MAX(public,excluded.public), own=excluded.own, legacy=excluded.legacy")
|
|
215
219
|
.run(row.id, canonical, Number(presence.placement === "local"), Number(presence.publicWitness), Number(presence.own), Number(presence.legacy));
|
|
220
|
+
touched.add(row.id);
|
|
216
221
|
}
|
|
217
222
|
db.query("INSERT INTO generation_segments VALUES (?,?,?,?,?,?) ON CONFLICT(source,path) DO UPDATE SET offset=excluded.offset,hash=excluded.hash,commit_id=excluded.commit_id,stamp=excluded.stamp")
|
|
218
223
|
.run(segment.source, segment.path, segment.offset, segment.hash, segment.commit ?? null, segment.stamp ?? null);
|
|
219
224
|
}
|
|
220
225
|
if (captured.commit) db.query("INSERT INTO generation_state VALUES ('legacyCommit',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(captured.commit);
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
226
|
+
// #466: the reduction can only move when a prune row arrived or a row it names as target or basis arrived, and
|
|
227
|
+
// the committed proof only needs re-proving when its stamp moved or an arrived row is one it names. Otherwise
|
|
228
|
+
// both are skipped: nothing they derive from changed, so the tables stay exactly where rebuild() would put them.
|
|
229
|
+
const mentioned = pruneInserted ? undefined : this.pruneMentionedIds();
|
|
230
|
+
const reductionMoved = mentioned === undefined || [...touched].some(id => mentioned.has(id));
|
|
231
|
+
const resolved: { set: string | undefined } = { set: undefined };
|
|
232
|
+
const foreignSatisfied = this.foreignBatchSatisfied([...touched], resolved);
|
|
233
|
+
// The target table holds the reduction and the proof's own targets together, so whatever re-proves the proof
|
|
234
|
+
// also re-materializes the reduction: a moved stamp would otherwise leave the previous proof's targets behind.
|
|
235
|
+
const recompute = reductionMoved || !foreignSatisfied;
|
|
236
|
+
if (recompute) {
|
|
237
|
+
const snapshot = this.snapshot(false);
|
|
238
|
+
const prunes = (db.query("SELECT line,local FROM generation_prunes ORDER BY id").all() as { line: string; local: number }[]).map(row => ({ row: JSON.parse(row.line), placement: row.local ? "local" as const : "synced" as const }));
|
|
239
|
+
const reduced = reducePruneRows(prunes, snapshot, this.profile.generation!);
|
|
240
|
+
db.run("DELETE FROM generation_targets");
|
|
241
|
+
for (const id of [...reduced.targets].sort()) db.query("INSERT INTO generation_targets VALUES (?)").run(id);
|
|
242
|
+
}
|
|
243
|
+
// Called on every batch, not only a recomputing one: the proof's files are the evidence a refusal rests on, so
|
|
244
|
+
// a deleted or altered one must still refuse an append that changes nothing. With an equal stamp this is the
|
|
245
|
+
// cached load() check plus one targets SELECT, the same work an unchanged refresh already pays.
|
|
246
|
+
this.applyForeign(!foreignSatisfied, resolved);
|
|
227
247
|
this.pruned = new Set((db.query("SELECT id FROM generation_targets").all() as {id:string}[]).map(row => row.id));
|
|
228
248
|
}
|
|
229
|
-
|
|
230
|
-
|
|
249
|
+
/**
|
|
250
|
+
* Ids a stored prune row names as a target or as that target's basis: the only ids an arriving row can move the
|
|
251
|
+
* reduction with, because reducePruneRows reads nothing else about a row. Undefined when the prune table is large
|
|
252
|
+
* enough that parsing it costs more than the recompute it would save.
|
|
253
|
+
*/
|
|
254
|
+
private pruneMentionedIds(): Set<string> | undefined {
|
|
255
|
+
const lines = this.options.db.query("SELECT line FROM generation_prunes ORDER BY id LIMIT 1025").all() as { line: string }[];
|
|
256
|
+
if (lines.length > 1024) return undefined;
|
|
257
|
+
const ids = new Set<string>();
|
|
258
|
+
for (const { line } of lines) for (const target of (JSON.parse(line) as PruneRow).targets) { ids.add(target.id); ids.add(target.basis.id); }
|
|
259
|
+
return ids;
|
|
260
|
+
}
|
|
261
|
+
/** True only when the committed proof already covers this batch, so re-proving every row would prove nothing new. */
|
|
262
|
+
private foreignBatchSatisfied(touched: readonly string[], resolved: { set: string | undefined }): boolean {
|
|
263
|
+
if (!this.profile.foreignPruneFormat) return true;
|
|
264
|
+
resolved.set = this.foreignSet();
|
|
265
|
+
if (resolved.set !== this.foreignStamp) return false;
|
|
266
|
+
// A large batch is rare and costs more to mark than to re-prove; the bounded form keeps every call's work flat.
|
|
267
|
+
if (touched.length > 64) return false;
|
|
268
|
+
if (!touched.length) return true;
|
|
269
|
+
const marks = touched.map(() => "?").join(",");
|
|
270
|
+
const hit = this.options.db.query(`SELECT 1 AS n FROM generation_foreign_rows WHERE id IN (${marks}) UNION SELECT 1 FROM generation_foreign_targets WHERE id IN (${marks}) LIMIT 1`).get(...touched, ...touched);
|
|
271
|
+
return !hit;
|
|
272
|
+
}
|
|
273
|
+
/** This shard's realm entry in the active public prune view, or undefined when the view holds none. */
|
|
274
|
+
private foreignSet(): string | undefined {
|
|
231
275
|
const profile = this.profile;
|
|
232
276
|
if (!profile.pruneInputSetHash || !profile.generation || !profile.sharded) return fail();
|
|
233
277
|
const view = (this.options.limits !== undefined ? readPublicPruneViewForActivation : readPublicPruneView)(profile.home, profile.pruneInputSetHash, profile.generation);
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
278
|
+
return view.realms[profile.shardUser ? "user" : `project:${profile.shardKey}`];
|
|
279
|
+
}
|
|
280
|
+
/** The stamp a previous index proved, so a reopen needs no replay; absent on an index written before it existed. */
|
|
281
|
+
private persistedForeignStamp(): string | undefined {
|
|
282
|
+
return (this.options.db.query("SELECT value FROM generation_state WHERE key='foreignStamp'").get() as { value: string } | null)?.value;
|
|
283
|
+
}
|
|
284
|
+
private applyForeign(validateRows = false, resolved?: { set: string | undefined }): void {
|
|
285
|
+
if (!this.profile.foreignPruneFormat) return;
|
|
286
|
+
const profile = this.profile, db = this.options.db, generation = profile.generation;
|
|
287
|
+
if (!profile.pruneInputSetHash || !generation || !profile.sharded) return fail();
|
|
288
|
+
const applied = resolved ? resolved.set : this.foreignSet();
|
|
289
|
+
if (applied === undefined) {
|
|
237
290
|
if ((db.query("SELECT COUNT(*) AS n FROM generation_foreign_inputs").get() as {n:number}).n) return fail();
|
|
238
291
|
return;
|
|
239
292
|
}
|
|
293
|
+
const set: string = applied;
|
|
240
294
|
if (!this.foreignCache || this.foreignCache.set !== set) this.foreignCache = { set, load: createPublicPruneReplayCache({ dir: profile.dir,
|
|
241
|
-
realm: profile.shardUser ? { scope: "user" } : { scope: "project", key: profile.shardKey! }, receivingGeneration:
|
|
295
|
+
realm: profile.shardUser ? { scope: "user" } : { scope: "project", key: profile.shardKey! }, receivingGeneration: generation, inputSetHash: set, ...(profile.publicationFormat ? {publicationFormat:profile.publicationFormat} : {}) }) };
|
|
242
296
|
const proof = this.foreignCache.load();
|
|
243
297
|
if (validateRows || this.foreignStamp !== set) for (const item of db.query("SELECT id,line FROM generation_rows").all() as {id:string;line:string}[]) {
|
|
244
298
|
const expected = proof.rowHashes.get(item.id); if (expected && hashJSON(JSON.parse(item.line)) !== expected) return fail();
|
|
@@ -249,10 +303,16 @@ export class GenerationIndex {
|
|
|
249
303
|
for (const [id, hash] of proof.rowHashes) db.query("INSERT INTO generation_foreign_rows VALUES (?,?)").run(id, hash);
|
|
250
304
|
for (const id of proof.targets) db.query("INSERT INTO generation_foreign_targets VALUES (?)").run(id);
|
|
251
305
|
this.foreignStamp = set;
|
|
306
|
+
// #466: written by rebuild() and by every incremental write alike, so both leave the same generation_state rows.
|
|
307
|
+
db.query("INSERT INTO generation_state VALUES ('foreignStamp',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(set);
|
|
252
308
|
}
|
|
253
309
|
const current = new Set((db.query("SELECT id FROM generation_targets").all() as {id:string}[]).map(row => row.id));
|
|
254
310
|
for (const id of proof.targets) if (!current.has(id)) db.query("INSERT INTO generation_targets VALUES (?)").run(id);
|
|
255
311
|
}
|
|
312
|
+
/** An unchanged frontier still re-proves the committed foreign inputs; only the table rewrite waits for a moved stamp. */
|
|
313
|
+
private refreshForeign(): void {
|
|
314
|
+
this.options.db.transaction(() => this.applyForeign(false, { set: this.foreignSet() })).immediate();
|
|
315
|
+
}
|
|
256
316
|
private recordSkipped(segment: LegacySegment): void {
|
|
257
317
|
this.options.db.query("INSERT INTO generation_state VALUES (?,'1') ON CONFLICT(key) DO UPDATE SET value=CAST(CAST(value AS INTEGER)+1 AS TEXT)").run(`skipped:${segment.source}:${segment.path}`);
|
|
258
318
|
}
|
|
@@ -278,7 +338,7 @@ export class GenerationIndex {
|
|
|
278
338
|
const known = db.query("SELECT source,path,offset,hash,commit_id,stamp FROM generation_segments").all() as { source: string; path: string; offset: number; hash: string; commit_id: string | null; stamp: string | null }[];
|
|
279
339
|
const currentCommit = (db.query("SELECT value FROM generation_state WHERE key='legacyCommit'").get() as { value: string } | null)?.value;
|
|
280
340
|
const unchanged = known.length === input.segments.length && currentCommit === input.commit && input.segments.every(segment => known.some(row => row.source === segment.source && row.path === segment.path && row.offset === segment.offset && row.hash === segment.hash && row.commit_id === (segment.commit ?? null) && row.stamp === (segment.stamp ?? null)));
|
|
281
|
-
if (unchanged) { if (this.profile.foreignPruneFormat)
|
|
341
|
+
if (unchanged) { if (this.profile.foreignPruneFormat) this.refreshForeign(); this.retainedTail = input.segments.some(segment => segment.tailBytes > 0); this.pruned = new Set((db.query("SELECT id FROM generation_targets").all() as { id: string }[]).map(row => row.id)); return; }
|
|
282
342
|
const committed = db.transaction(() => { if (this.frontier() !== before) return false; this.index(input); return true; }).immediate();
|
|
283
343
|
if (!committed) { if (attempt < 5) return this.refresh(attempt + 1, reader); return fail(); }
|
|
284
344
|
this.retainedTail = input.segments.some(segment => segment.tailBytes > 0);
|
|
@@ -292,6 +352,8 @@ export class GenerationIndex {
|
|
|
292
352
|
const committed = this.options.db.transaction(() => {
|
|
293
353
|
if (this.frontier() !== before) return false;
|
|
294
354
|
for (const table of ["entries", "ops", "edges", "goals", "segments", "heads", ...GENERATION_TABLES, ...(this.profile.foreignPruneFormat ? FOREIGN_TABLES : [])]) this.options.db.run(`DELETE FROM ${table}`);
|
|
355
|
+
// The stamp described the tables just deleted, so the rebuild below proves them again instead of trusting it.
|
|
356
|
+
this.foreignStamp = undefined;
|
|
295
357
|
this.index(input); return true;
|
|
296
358
|
}).immediate();
|
|
297
359
|
if (!committed) { if (attempt < 5) return this.rebuild(attempt + 1, reader); return fail(); }
|
package/src/memory/index-file.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/** Bumped when
|
|
2
|
-
export const INDEX_VERSION =
|
|
1
|
+
/** Bumped when derived index tables change; each version uses its own file, rebuilt from logs on first open. */
|
|
2
|
+
export const INDEX_VERSION = 5; // #466: isolate the persisted foreign-prune stamp from older index writers.
|
|
3
3
|
/** The version that released 0.14.0 through 0.18.0 build into the unversioned names below; it keeps them so this release shares their warm index. */
|
|
4
4
|
const SHARED_INDEX_VERSION = 3;
|
|
5
5
|
|
package/src/memory/metrics.ts
CHANGED
|
@@ -29,6 +29,7 @@ export function briefObservation(context: string): BriefObservation | undefined
|
|
|
29
29
|
const reasons = [
|
|
30
30
|
["deadline exhausted", "deadline"], ["lock busy", "lock"], ["read unavailable", "read_error"], ["generation refresh deferred", "floor"], ["curated refresh deferred", "floor"],
|
|
31
31
|
["curated floor below ", "floor"], ["curated cache missing", "cache_missing"], ["curated cache stale", "cache_stale"],
|
|
32
|
+
["work cache missing", "cache_missing"], ["work cache stale", "cache_stale"],
|
|
32
33
|
["capture cache missing", "cache_missing"], ["capture history deferred", "history_deferred"], ["floor: upgrade amem", "floor_upgrade"],
|
|
33
34
|
["floor: amem doctor", "floor_invalid"], ["repo policy unreadable", "policy_unreadable"], ["repo log is not a plain file", "invalid_log"],
|
|
34
35
|
] as const;
|
|
@@ -14,6 +14,7 @@ import { invalidateCuratedCaches } from "./curated-cache-state.ts";
|
|
|
14
14
|
export type PublicPruneAdvanceStage = "after-intent" | "after-shards" | "after-profile" | "after-remove";
|
|
15
15
|
export interface PublicPruneAdvanceOptions {
|
|
16
16
|
memoryDir: string; view: PublicPruneViewV1; expectedRevision: string; mutations?: readonly MutationHandle[];
|
|
17
|
+
origin?: "remote";
|
|
17
18
|
checkpoint?: (stage: PublicPruneAdvanceStage) => void | Promise<void>;
|
|
18
19
|
}
|
|
19
20
|
export interface PublicPruneAdvanceResult { revision: string; viewHash: string }
|
|
@@ -141,7 +142,7 @@ export async function advancePublicPruneView(options: PublicPruneAdvanceOptions)
|
|
|
141
142
|
const previousProfile=raw(join(home,"profile.json")),previousShards=raw(join(home,"shards.json")),old=readPublicPruneViewForActivation(home,profile.pruneInputSetHash,profile.generation);
|
|
142
143
|
const bindings:Binding[]=[];
|
|
143
144
|
for(const key of Object.keys(view.realms).sort())if(old.realms[key]!==view.realms[key]){
|
|
144
|
-
const bound=resolveShardProfile(home,key==="user"?{user:true}:{project:key.slice(8)}),stat=owned(bound.dir,true);
|
|
145
|
+
const bound=resolveShardProfile(home,key==="user"?{user:true}:{project:key.slice(8)}, options.origin),stat=owned(bound.dir,true);
|
|
145
146
|
bindings.push({key,dir:bound.dir,dev:stat.dev,ino:stat.ino,metadata:metadata(bound.dir)});
|
|
146
147
|
}
|
|
147
148
|
const final={...profile,pruneInputSetHash:publicPruneViewHash(view)},shards={...JSON.parse(previousShards),selectorRevision:hashJSON(final)};
|
|
@@ -141,7 +141,7 @@ export class ShardSyncApplications {
|
|
|
141
141
|
const view: PublicPruneViewV1 = { ...this.#boundView, realms };
|
|
142
142
|
if (canonicalJSON(view) !== canonicalJSON(this.#boundView)) {
|
|
143
143
|
for (const target of o.targets) shardSelectorRetention(target, true, true);
|
|
144
|
-
const result = await advancePublicPruneView({ memoryDir: o.home, view, expectedRevision: o.getRevision(), mutations: [o.homeMutation, ...o.targets.map(target => target.mutation!)] });
|
|
144
|
+
const result = await advancePublicPruneView({ memoryDir: o.home, view, expectedRevision: o.getRevision(), origin: "remote", mutations: [o.homeMutation, ...o.targets.map(target => target.mutation!)] });
|
|
145
145
|
o.setRevision(result.revision); this.#boundView = view;
|
|
146
146
|
for (const target of o.targets) target.store.refresh();
|
|
147
147
|
await o.afterAdvance();
|
|
@@ -7,6 +7,7 @@ import { verifyPublicPruneWitness } from "./public-prune-witness.ts";
|
|
|
7
7
|
import { parsePublicPruneGitTree } from "./shard-sync-graph.ts";
|
|
8
8
|
import { decodeShardDescriptor, decodePlacementTransportDescriptor, decodeShardPack, decodeShardManifest, isShardManifestPath,
|
|
9
9
|
shardSyncRef, SHARD_PACK_MAX_BYTES, type ShardSyncRealm, type ShardSyncRow } from "./shard-sync-format.ts";
|
|
10
|
+
import { cooperativeYield } from "./sync-placement-yield.ts";
|
|
10
11
|
|
|
11
12
|
export interface ShardHistoryOrigin { ref: string; commit: string; pack: string; blob: string }
|
|
12
13
|
export interface ShardHistoryManifest { path: string; bytes: Buffer; value: unknown; row: PruneRow; eligible: boolean; commit: string; blob: string }
|
|
@@ -148,6 +149,7 @@ export class ShardHistoryAuditor {
|
|
|
148
149
|
: (await this.#options.git(["ls-tree", "-r", "-z", commit])).split("\0").filter(Boolean);
|
|
149
150
|
const rows = new Map<string, ShardSyncRow>(), files = new Map<string, Buffer>(), origins = new Map<string, ShardHistoryOrigin>();
|
|
150
151
|
const objects = new Map<string, string>(), manifests = new Map<string, ShardHistoryManifest>();
|
|
152
|
+
const pause = cooperativeYield(); // #462: per-file and per-pack work yields to the caller's loop; checks are unchanged
|
|
151
153
|
for (const entry of entries) {
|
|
152
154
|
const match = /^100644 blob ([a-f0-9]{40})\t(.+)$/.exec(entry);
|
|
153
155
|
if (!match || match[0] !== entry) fail("forbidden-entry");
|
|
@@ -159,6 +161,7 @@ export class ShardHistoryAuditor {
|
|
|
159
161
|
const version = this.#options.placement ? decodePlacementTransportDescriptor(descriptor, this.#options.realm) : decodeShardDescriptor(descriptor, this.#options.realm);
|
|
160
162
|
if (version !== "v1" && !this.#options.publicPrune) fail("public-prune-floor");
|
|
161
163
|
for (const [path, bytes] of files) if (packPath(path)) {
|
|
164
|
+
await pause();
|
|
162
165
|
const object = objects.get(path)!; let pack = this.#decoded.get(object);
|
|
163
166
|
if (!pack) { pack = decodeShardPack(path, bytes, this.#options.realm, this.#options.generation); this.#decoded.set(object, pack); }
|
|
164
167
|
else if (!path.endsWith(`/${digest(bytes)}.jsonl`) || pack.some(row => path !== `rows/${digest(row.machine)}/${digest(bytes)}.jsonl`)) fail();
|
|
@@ -168,6 +171,7 @@ export class ShardHistoryAuditor {
|
|
|
168
171
|
}
|
|
169
172
|
}
|
|
170
173
|
for (const [path, bytes] of files) if (isShardManifestPath(path)) {
|
|
174
|
+
await pause();
|
|
171
175
|
if (version === "v1") fail();
|
|
172
176
|
const value = decodeShardManifest(path, bytes), candidate = value as { prune?: unknown; pruneOccurrence?: { pack: string; blob: string }; witnesses?: { pack: string; blob: string }[] };
|
|
173
177
|
const row = validatePruneRow(candidate.prune, undefined, "synced");
|
|
@@ -214,6 +218,7 @@ export class ShardHistoryAuditor {
|
|
|
214
218
|
const cached = this.#histories.get(tip); if (cached) return detached(cached);
|
|
215
219
|
const lines = (await this.#options.git(["rev-list", "--topo-order", "--reverse", "--parents", tip])).split("\n").filter(Boolean);
|
|
216
220
|
let latest: ShardHistory | undefined; const seen = new Set<string>();
|
|
221
|
+
const pause = cooperativeYield();
|
|
217
222
|
// ponytail: complete selected history still costs time and immutable selected-blob memory per invocation.
|
|
218
223
|
// Upgrade with a validated immutable commit/blob digest cache, never an arbitrary history lifetime cliff.
|
|
219
224
|
for (const line of lines) {
|
|
@@ -228,6 +233,7 @@ export class ShardHistoryAuditor {
|
|
|
228
233
|
if (!this.#audited.has(parent) || !seen.has(parent)) return fail();
|
|
229
234
|
const previous = this.#histories.get(parent) ?? await this.#tree(parent);
|
|
230
235
|
if (rank[current.version] < rank[previous.version]) fail();
|
|
236
|
+
await pause();
|
|
231
237
|
if (previous.version !== "v1") for (const [path, bytes] of previous.files)
|
|
232
238
|
if (path !== "shard.json" && !current.files.get(path)?.equals(bytes)) fail();
|
|
233
239
|
for (const row of previous.rows.values()) if (canonicalJSON(current.rows.get(row.id)) !== canonicalJSON(row)) fail();
|
package/src/memory/shard.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { readActivePlacementBinding } from "./sync-placement-active.ts";
|
|
2
|
+
import { readEffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
|
|
2
3
|
import { validatePlacementProfile, validatePlacementShards } from "./sync-placement-format.ts";
|
|
3
|
-
import { assertPlacementRuntime, SyncPlacementRuntimeError } from "./sync-placement-guard.ts";
|
|
4
|
+
import { assertPlacementRuntime, doctorScratchBinding, doctorScratchInventory, SyncPlacementRuntimeError } from "./sync-placement-guard.ts";
|
|
4
5
|
import { assertNoPublicPruneIntent, readPublicPruneView } from "./public-prune-view.ts";
|
|
5
6
|
import { indexFileName } from "./index-file.ts";
|
|
6
7
|
import { createHash, randomBytes } from "node:crypto";
|
|
@@ -153,18 +154,23 @@ export function readShardedSelection(memoryDir: string): ShardedSelection {
|
|
|
153
154
|
}catch(error){if(safeProfileLockMessage(error))throw error;throw profileLockRecoveryError(memoryDir)??error;}
|
|
154
155
|
}
|
|
155
156
|
|
|
156
|
-
/**
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
const active = readActivePlacementBinding(memoryDir, selector, readProfileJSON(join(memoryDir, "shards.json")));
|
|
164
|
-
const keyHash = opts.user ? undefined : createHash("sha256").update(opts.project!).digest("hex");
|
|
165
|
-
if (!active || !active.activation.realms.some(realm => opts.user ? realm.scope === "user" : realm.scope === "project" && realm.keyHash === keyHash))
|
|
166
|
-
throw new Error("sync placement realm is outside the activated inventory; review its activation before opening it");
|
|
157
|
+
/** Bounded identifiers only, safe to surface without exposing a project key or row. */
|
|
158
|
+
export class PlacementRealmRefusal extends Error {
|
|
159
|
+
constructor(readonly scope: "user" | "project", readonly keyHash: string | undefined, readonly origin: "cwd binding" | "remote" | "local binding") {
|
|
160
|
+
// A same-epoch extension record describes a project realm only, so the user realm is fixed by activation and has no admission command.
|
|
161
|
+
const next = scope === "user" ? "the user realm is fixed at activation; review it with amem migrate --sync-placement --dry-run"
|
|
162
|
+
: "admit it with amem migrate --sync-placement --admit <project> --dry-run, then --apply";
|
|
163
|
+
super(`sync placement realm is outside the activated inventory: scope=${scope}${keyHash ? ` keyHash=${keyHash}` : ""}; origin=${origin}; ${next}`);
|
|
167
164
|
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* The fixed layout of one curated shard, checked with `lstat` and never followed: a symlinked directory or metadata file
|
|
169
|
+
* would redirect a write out of the home. Split from `assertCuratedShardPaths` so a writer that has not yet created the
|
|
170
|
+
* shard can refuse a redirecting scaffold before it creates anything, while the inventory gate stays with the callers that
|
|
171
|
+
* open an existing one.
|
|
172
|
+
*/
|
|
173
|
+
export function assertCuratedShardLayout(memoryDir: string, opts: { project?: string; user?: boolean }): void {
|
|
168
174
|
const dir = opts.user === true ? userShardDir(memoryDir) : shardDir(memoryDir, opts.project!);
|
|
169
175
|
const check = (path: string, directory: boolean) => {
|
|
170
176
|
try {
|
|
@@ -178,11 +184,32 @@ export function assertCuratedShardPaths(memoryDir: string, opts: { project?: str
|
|
|
178
184
|
for (const name of ["project.json", "generation.json", "generation-seal.json", "migration-sources.json", "machine.json", "legacy/machine.json", "legacy-main/machine.json", "prune-translations.jsonl"]) check(join(dir, name), false);
|
|
179
185
|
for (const database of new Set(["index.db", "index-v2.db", indexFileName(false), indexFileName(true), "search.db", "mutation-lock.db"])) for (const suffix of ["", "-wal", "-shm", "-journal"]) check(join(dir, database + suffix), false);
|
|
180
186
|
}
|
|
187
|
+
/** Fixed curated paths cannot redirect writes into legacy inputs or another shard.
|
|
188
|
+
* ponytail: same-user concurrent parent replacement needs descriptor-relative opens; fixed preflight does not claim that fence.
|
|
189
|
+
*/
|
|
190
|
+
export function assertCuratedShardPaths(memoryDir: string, opts: { project?: string; user?: boolean }, origin: "cwd binding" | "remote" | "local binding" = "local binding"): void {
|
|
191
|
+
assertPlacementRuntime(memoryDir);
|
|
192
|
+
const selector = readProfileJSON(join(memoryDir, "profile.json")) as {schema?:unknown} | undefined;
|
|
193
|
+
let recheckInventory: (() => void) | undefined;
|
|
194
|
+
if (selector?.schema === "agent-mem.profile/v3") {
|
|
195
|
+
const scratch = doctorScratchBinding(memoryDir);
|
|
196
|
+
const active = scratch ?? readActivePlacementBinding(memoryDir, selector, readProfileJSON(join(memoryDir, "shards.json")));
|
|
197
|
+
const keyHash = opts.user ? undefined : createHash("sha256").update(opts.project!).digest("hex");
|
|
198
|
+
// An appended same-epoch extension is part of the inventory a curated write may open (#448); a realm it does not name stays refused.
|
|
199
|
+
const inventory = scratch ? doctorScratchInventory(memoryDir) : active ? readEffectiveRealmInventory(memoryDir, active) : undefined;
|
|
200
|
+
if (!inventory?.realms.some(realm => opts.user ? realm.scope === "user" : realm.scope === "project" && realm.keyHash === keyHash))
|
|
201
|
+
throw new PlacementRealmRefusal(opts.user ? "user" : "project", keyHash, origin);
|
|
202
|
+
inventory.assertCurrent();
|
|
203
|
+
recheckInventory = inventory.assertCurrent;
|
|
204
|
+
}
|
|
205
|
+
assertCuratedShardLayout(memoryDir, opts);
|
|
206
|
+
recheckInventory?.();
|
|
207
|
+
}
|
|
181
208
|
|
|
182
209
|
/** Open one already-sealed shard without consulting the legacy home or the catalog. */
|
|
183
|
-
export function resolveShardProfile(memoryDir: string, opts: { project?: string; user?: boolean }): BoundProfile {
|
|
210
|
+
export function resolveShardProfile(memoryDir: string, opts: { project?: string; user?: boolean }, origin?: "cwd binding" | "remote" | "local binding"): BoundProfile {
|
|
184
211
|
if (opts.user === true && opts.project !== undefined || opts.user !== true && !opts.project) throw new Error("choose exactly one project or the user shard");
|
|
185
|
-
assertCuratedShardPaths(memoryDir, opts);
|
|
212
|
+
assertCuratedShardPaths(memoryDir, opts, origin);
|
|
186
213
|
const deadline = Date.now() + PROFILE_LOCK_TIMEOUT_MS, initial = shardSnapshot(memoryDir, deadline), generation = initial.journal.generation;
|
|
187
214
|
const dir = opts.user === true ? userShardDir(memoryDir) : shardDir(memoryDir, opts.project!);
|
|
188
215
|
if (opts.project !== undefined && readShardDescriptor(memoryDir, shardKeyHash(opts.project))?.key !== opts.project) throw new Error("curated shard project identity mismatch");
|