@staix/agent-mem 0.28.2 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +17 -11
  3. package/package.json +3 -2
  4. package/src/brief-work.ts +142 -0
  5. package/src/cli.ts +97 -17
  6. package/src/commands-table.ts +6 -0
  7. package/src/mcp-memory.ts +37 -9
  8. package/src/memory/bridge.ts +26 -1
  9. package/src/memory/capacity.ts +5 -2
  10. package/src/memory/catalog.ts +10 -1
  11. package/src/memory/commands.ts +5 -3
  12. package/src/memory/curated-cache-state.ts +10 -7
  13. package/src/memory/doctor.ts +32 -26
  14. package/src/memory/formats.ts +4 -3
  15. package/src/memory/generation-index.ts +79 -17
  16. package/src/memory/index-file.ts +2 -2
  17. package/src/memory/intent-brief.ts +34 -6
  18. package/src/memory/metrics.ts +174 -14
  19. package/src/memory/shard-bridge.ts +18 -6
  20. package/src/memory/shard-sync-format.ts +18 -0
  21. package/src/memory/shard-sync-history.ts +6 -0
  22. package/src/memory/shard-sync.ts +52 -4
  23. package/src/memory/shard.ts +33 -13
  24. package/src/memory/store.ts +147 -41
  25. package/src/memory/sync-placement-bound.ts +21 -4
  26. package/src/memory/sync-placement-cache.ts +16 -1
  27. package/src/memory/sync-placement-capture.ts +67 -19
  28. package/src/memory/sync-placement-checkpoint-format.ts +199 -0
  29. package/src/memory/sync-placement-checkpoint-person.ts +209 -0
  30. package/src/memory/sync-placement-checkpoint-prospective.ts +141 -0
  31. package/src/memory/sync-placement-checkpoint-storage.ts +218 -0
  32. package/src/memory/sync-placement-checkpoint.ts +234 -0
  33. package/src/memory/sync-placement-dependencies.ts +42 -9
  34. package/src/memory/sync-placement-effective-writers.ts +12 -6
  35. package/src/memory/sync-placement-git.ts +17 -7
  36. package/src/memory/sync-placement-guard.ts +52 -1
  37. package/src/memory/sync-placement-inspection-evidence.ts +1 -1
  38. package/src/memory/sync-placement-inventory.ts +141 -0
  39. package/src/memory/sync-placement-journal-format.ts +4 -1
  40. package/src/memory/sync-placement-journal-storage.ts +148 -28
  41. package/src/memory/sync-placement-journal.ts +13 -4
  42. package/src/memory/sync-placement-materialize.ts +47 -22
  43. package/src/memory/sync-placement-projection.ts +7 -1
  44. package/src/memory/sync-placement-publication-events.ts +42 -0
  45. package/src/memory/sync-placement-publication-plan.ts +26 -5
  46. package/src/memory/sync-placement-realm-admission-storage.ts +128 -0
  47. package/src/memory/sync-placement-realm-admission.ts +352 -0
  48. package/src/memory/sync-placement-realm-attribution.ts +23 -0
  49. package/src/memory/sync-placement-realm-discovery.ts +42 -0
  50. package/src/memory/sync-placement-realm-effective.ts +71 -0
  51. package/src/memory/sync-placement-realm-extension-format.ts +66 -0
  52. package/src/memory/sync-placement-realm-extension-storage.ts +82 -0
  53. package/src/memory/sync-placement-realm-intent-format.ts +55 -0
  54. package/src/memory/sync-placement-realm-intent-storage.ts +123 -0
  55. package/src/memory/sync-placement-realm-pending.ts +27 -0
  56. package/src/memory/sync-placement-realm-proof.ts +131 -0
  57. package/src/memory/sync-placement-realm-torn.ts +26 -0
  58. package/src/memory/sync-placement-remote-admission.ts +190 -0
  59. package/src/memory/sync-placement-remote-adoption-format.ts +54 -0
  60. package/src/memory/sync-placement-remote-materialization.ts +49 -0
  61. package/src/memory/sync-placement-remote-refusal.ts +21 -0
  62. package/src/memory/sync-placement-remote-stage.ts +275 -0
  63. package/src/memory/sync-placement-transport.ts +268 -79
  64. package/src/memory/sync-placement-writer-history.ts +75 -17
  65. package/src/memory/sync-placement-writer-renewal.ts +18 -10
  66. package/src/memory/sync-placement-writer-revision-format.ts +16 -13
  67. package/src/memory/sync-placement-yield.ts +44 -0
  68. package/src/memory/sync-progress.ts +47 -6
  69. package/src/memory/sync.ts +26 -1
  70. package/src/memory/work-lists.ts +129 -9
  71. package/src/session-brief.ts +34 -1
  72. package/src/sync-placement-writer-context.ts +5 -5
  73. package/src/ui/plugin.ts +1 -1
package/src/mcp-memory.ts CHANGED
@@ -14,6 +14,7 @@ import { capacityReport } from "./memory/capacity.ts";
14
14
  import { CaptureStore, type CaptureRow } from "./memory/capture.ts";
15
15
  import { hashJSON, readSelector } from "./memory/generation.ts";
16
16
  import { memoryHome } from "./memory/home.ts";
17
+ import { appendMetricsLater, createPeakTracker } from "./memory/metrics.ts";
17
18
  import { canonicalPath, realPath } from "./memory/platform.ts";
18
19
  import { createStandalonePolicy, type StandalonePolicy, type StandalonePolicyOptions } from "./memory/policy.ts";
19
20
  import { configuredPolicyOptions } from "./memory/config.ts";
@@ -86,7 +87,7 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
86
87
  return read.state === "ok" ? read.views : [];
87
88
  };
88
89
  const candidates = new CandidateStore({ memoryDir: base, ...(reconcile ? { reconcile } : {}) }); closers.push(() => candidates.close());
89
- const work = new WorkListStore({ base, project, aliases, policy: async row => { const permitted = await policy.screen(row); guard(); return permitted; } }); closers.push(() => work.close());
90
+ const work = new WorkListStore({ base, project, aliases, briefPolicyOptions: policyOptions, policy: async row => { const permitted = await policy.screen(row); guard(); return permitted; } }); closers.push(() => work.close());
90
91
  const fullGuard = () => {
91
92
  if (!permitted()) unavailable();
92
93
  if (closed) unavailable(); options.assertCurrent?.();
@@ -341,17 +342,44 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
341
342
  };
342
343
  const exposed = { ...tools };
343
344
  const readTools = ["amem_search", "amem_evidence", "amem_show", "amem_timeline", "amem_graph", "amem_brief", "amem_vault_candidates"] as const;
345
+ // #485: the process peak is monotonic, so a call can be credited with raising it only when no other read call was
346
+ // in flight while it grew; the tracker owns that rule and the observed baseline.
347
+ const peaks = createPeakTracker();
344
348
  for (const name of readTools) exposed[name] = async args => {
345
- fullGuard();
346
- const configured = policyOptions(), revision = policyKey(configured), snapshot = createStandalonePolicy(configured);
347
- const sourceCurrent = store.beginRecallRead();
348
- if (policyKey(policyOptions()) !== revision) return unavailable();
349
- return calls.run({ policy: snapshot, revision, configured }, async () => {
350
- const result = await tools[name](args);
351
- fullGuard(); sourceCurrent();
349
+ // #485: the sample measures the served span, so the clock and the peak window open at entry, before the guard, the
350
+ // policy snapshot and `beginRecallRead()` - whose preparation (an index refresh, a prune) the caller waits for.
351
+ const started = performance.now();
352
+ let window: ReturnType<typeof peaks.begin> | undefined;
353
+ try { window = peaks.begin(); } catch { /* telemetry is an observation, never a precondition */ }
354
+ // One bounded sample per completed call: the tool name, the wall time and the process peak. Never the arguments,
355
+ // the query text, an id or a result. It is handed off, not written: the response is queued first and the write is
356
+ // asynchronous, so telemetry can neither fail, refuse, delay nor block a completed call on disk.
357
+ const recorded = (): void => {
358
+ try {
359
+ const ended = window === undefined ? undefined : peaks.end(window);
360
+ window = undefined;
361
+ if (ended?.peakKB === undefined) return;
362
+ appendMetricsLater(base, [{ at: new Date().toISOString(), kind: "search", tool: name, wallMs: performance.now() - started, rssMB: ended.peakKB / 1024, peakRaised: ended.raised }]);
363
+ } catch { /* a lost telemetry sample is never a failed call */ }
364
+ };
365
+ try {
366
+ fullGuard();
367
+ const configured = policyOptions(), revision = policyKey(configured), snapshot = createStandalonePolicy(configured);
368
+ const sourceCurrent = store.beginRecallRead();
352
369
  if (policyKey(policyOptions()) !== revision) return unavailable();
370
+ const result = await calls.run({ policy: snapshot, revision, configured }, async () => {
371
+ const value = await tools[name](args);
372
+ fullGuard(); sourceCurrent();
373
+ if (policyKey(policyOptions()) !== revision) return unavailable();
374
+ return value;
375
+ });
376
+ recorded();
353
377
  return result;
354
- });
378
+ } catch (error) {
379
+ // A refused or failed call records nothing, but the peak it may have raised still advances the baseline.
380
+ try { if (window !== undefined) peaks.abort(window); } catch { /* nothing recorded, nothing to correct */ }
381
+ throw error;
382
+ }
355
383
  };
356
384
  return { tools: exposed, close, onEmitted };
357
385
  } catch (error) { close(); throw error; }
@@ -4,6 +4,7 @@ import { closeSync, constants, fstatSync, fsyncSync, linkSync, lstatSync, mkdirS
4
4
  import { basename, dirname, join } from "node:path";
5
5
  import { isDeepStrictEqual } from "node:util";
6
6
  import { memoryGitArgv, memoryGitEnv, realPath } from "./platform.ts";
7
+ import { drainSteps } from "./sync-placement-yield.ts";
7
8
  import { canonicalJSON, fsyncDirectory, readProfileJSON, writeProfileJSON } from "./generation.ts";
8
9
  import { OP_CONTRACTS } from "./ops-contract.ts";
9
10
  import type { InspectionBound } from "./inspection-bound.ts";
@@ -193,10 +194,20 @@ export function* completeLines(bytes: Buffer): Generator<Buffer> {
193
194
 
194
195
  /** Preserve original IDs; row order and JSON key order never produce duplicate evidence. */
195
196
  export function legacyEntries(segments: readonly LegacySegment[], options: { strict?: boolean; onMalformed?: () => void } = {}): Entry[] {
197
+ return drainSteps(legacyEntrySteps(segments, options));
198
+ }
199
+
200
+ /** Rows between step boundaries: one row's own canonicalisation and id check is the floor of an uninterrupted stretch. */
201
+ const LEGACY_ENTRY_STEP_LINES = 512;
202
+
203
+ /** #462: the same validation, handing the caller's event loop back every few hundred rows instead of once per read. */
204
+ export function* legacyEntrySteps(segments: readonly LegacySegment[], options: { strict?: boolean; onMalformed?: () => void } = {}): Generator<void, Entry[], void> {
196
205
  const rows = new Map<string, Entry>();
206
+ let stepped = 0;
197
207
  for (const segment of segments) {
198
208
  if (segment.bytes.length !== segment.offset || digest(segment.bytes) !== segment.hash || segment.offset && segment.bytes.at(-1) !== 10) failure();
199
209
  for (const bytes of completeLines(segment.bytes)) {
210
+ if (++stepped >= LEGACY_ENTRY_STEP_LINES) { stepped = 0; yield; }
200
211
  let row: Entry;
201
212
  try {
202
213
  let line: string;
@@ -225,6 +236,13 @@ function inspectArchivedSegment(inspect: LegacySegmentInspector, file: string, c
225
236
 
226
237
  /** Raw authoritative inputs only: never constructs a legacy store, opens its index or performs network I/O. */
227
238
  function snapshot(homeM: string, options: LegacySnapshotOptions, inspect?: LegacySegmentInspector): LegacySegment[] {
239
+ return drainSteps(snapshotSteps(homeM, options, inspect));
240
+ }
241
+ /**
242
+ * #462: the same read, written once as steps so a caller that owns a collector yields between legacy segments instead of
243
+ * inside one call. Every fence, receipt check and row validation stays in the same order.
244
+ */
245
+ function* snapshotSteps(homeM: string, options: LegacySnapshotOptions, inspect?: LegacySegmentInspector): Generator<void, LegacySegment[], void> {
228
246
  const root = realPath(homeM);
229
247
  directory(root);
230
248
  if (inspect && (options.incremental || options.limits)) failure();
@@ -248,6 +266,7 @@ function snapshot(homeM: string, options: LegacySnapshotOptions, inspect?: Legac
248
266
  const machineId = (machine as { id?: unknown } | undefined)?.id;
249
267
  if (typeof machineId !== "string" || !/^[a-f0-9]{16}$/.test(machineId)) failure();
250
268
  for (const folder of ["log", "local"]) {
269
+ yield;
251
270
  const dir = join(root, folder);
252
271
  if (!directory(dir, true)) continue;
253
272
  for (const name of options.reader ? options.reader.listFiles(dir) : readdirSync(dir).sort()) {
@@ -255,6 +274,7 @@ function snapshot(homeM: string, options: LegacySnapshotOptions, inspect?: Legac
255
274
  const path = `${folder}/${name}`;
256
275
  if (!segmentPath(path)) failure();
257
276
  if (folder === "local" && name !== `${machineId}.jsonl`) continue;
277
+ yield;
258
278
  if (inspect) {
259
279
  result.push(inspect(join(dir, name), { source: diskSource, path, local: folder === "local" }, checkpoints.get(`${diskSource}:${path}`)));
260
280
  continue;
@@ -275,6 +295,7 @@ function snapshot(homeM: string, options: LegacySnapshotOptions, inspect?: Legac
275
295
  directory(join(archiveDir(root, options.generation, commit), "log"));
276
296
  for (const prior of new Set([...(options.previousCommit ? [options.previousCommit] : []), ...[...checkpoints.values()].filter(row => row.source === remoteSource).map(row => row.commit!)])) if (!archivedAncestor(root, options.generation, prior, commit, options.reader?.sourceByteLimit)) failure();
277
297
  for (const segment of manifest.segments) {
298
+ yield;
278
299
  if (inspect) {
279
300
  result.push(inspectArchivedSegment(inspect, join(archiveDir(root, options.generation, commit), segment.path),
280
301
  { source: remoteSource, path: segment.path, local: false, commit }, checkpoints.get(`${remoteSource}:${segment.path}`), segment));
@@ -298,7 +319,7 @@ function snapshot(homeM: string, options: LegacySnapshotOptions, inspect?: Legac
298
319
  const bytes = segment.bytes.subarray(Math.max(0, start - (segment.start ?? 0)));
299
320
  return { ...segment, bytes, offset: bytes.length, hash: digest(bytes) };
300
321
  });
301
- legacyEntries(suffixes, { onMalformed: options.onMalformed });
322
+ yield* legacyEntrySteps(suffixes, { onMalformed: options.onMalformed });
302
323
  return result;
303
324
  }
304
325
 
@@ -350,6 +371,10 @@ function head(homeM: string, generation: string, maximumArchiveBytes?: number, m
350
371
  export function readLegacySnapshot(homeM: string, options: LegacySnapshotOptions = {}): LegacySegment[] {
351
372
  try { return snapshot(homeM, options); } catch (error) { if (error instanceof SegmentReadBudgetError) throw error; return failure(); }
352
373
  }
374
+ /** #462: the same snapshot as steps, so the transport's capture yields between legacy segments instead of inside one read. */
375
+ export function* legacySnapshotSteps(homeM: string, options: LegacySnapshotOptions = {}): Generator<void, LegacySegment[], void> {
376
+ try { return yield* snapshotSteps(homeM, options); } catch (error) { if (error instanceof SegmentReadBudgetError) throw error; return failure(); }
377
+ }
353
378
  /** Read-only enumeration reuses the legacy frontier checks without retaining source bodies or refreshing an index. */
354
379
  export function inspectLegacySnapshot(homeM: string, options: LegacySnapshotOptions, inspect: LegacySegmentInspector): LegacySegment[] {
355
380
  return snapshot(homeM, options, inspect);
@@ -212,8 +212,11 @@ export function capacityReport(opts: {
212
212
  const samples = opts.inject?.metrics ?? readMetrics(base);
213
213
  const hookWalls = samples.filter((s) => s.kind === "hook" && typeof s.wallMs === "number").map((s) => s.wallMs!);
214
214
  const hookRss = samples.filter((s) => s.kind === "hook" && typeof s.rssMB === "number").map((s) => s.rssMB!);
215
- const searchWalls = samples.filter((s) => s.kind === "search" && typeof s.wallMs === "number").map((s) => s.wallMs!);
216
- const searchRss = samples.filter((s) => s.kind === "search" && typeof s.rssMB === "number").map((s) => s.rssMB!);
215
+ // #485: every completed read-tool call appends a `search` sample carrying its tool name; R3's reading is `amem_search`'s.
216
+ // A sample without a tool name counts as a search reading, so a hand-written or pre-#485 sample is still read.
217
+ const searchSamples = samples.filter((s) => s.kind === "search" && (s.tool === undefined || s.tool === "amem_search"));
218
+ const searchWalls = searchSamples.filter((s) => typeof s.wallMs === "number").map((s) => s.wallMs!);
219
+ const searchRss = searchSamples.filter((s) => typeof s.rssMB === "number").map((s) => s.rssMB!);
217
220
  const metrics = { samples: samples.length, hookP95Ms: p95(hookWalls), hookRssMB: p95(hookRss), searchP95Ms: p95(searchWalls), searchRssMB: p95(searchRss) };
218
221
 
219
222
  const homeConfig = readCaptureConfigFile(join(base, "capture-config.json"));
@@ -8,6 +8,7 @@ import { readProfileJSON, validGeneration } from "./generation.ts";
8
8
  import { captureShardStats, readCaptureConfig } from "./capture.ts";
9
9
  import { openShardStore } from "./store.ts";
10
10
  import { lifecycleResolver, type LifecycleState } from "./lifecycle.ts";
11
+ import { placementSelectorRefusal } from "./sync-placement-guard.ts";
11
12
 
12
13
  /**
13
14
  * #15 D3 (storage part only): the user-level catalog of project shards. `catalog.db` in the memory home is derived
@@ -35,7 +36,15 @@ const fromRow = (r: CatalogRow): CatalogProject => ({ hash: r.hash, key: r.key,
35
36
 
36
37
  /** Interrupted splits expose capture facts, but cannot authorize any curated store open or initialization. */
37
38
  function capturedSelection(base: string): boolean {
38
- const value = readProfileJSON(join(base, "shards.json")) as { schema?: unknown; generation?: unknown; phase?: unknown; selectorRevision?: unknown } | undefined;
39
+ let value: { schema?: unknown; generation?: unknown; phase?: unknown; selectorRevision?: unknown } | undefined, shardError: unknown;
40
+ try { value = readProfileJSON(join(base, "shards.json")) as typeof value; } catch (error) { shardError = error; }
41
+ let profile: { schema?: unknown } | undefined;
42
+ try { profile = readProfileJSON(join(base, "profile.json")) as typeof profile; } catch { /* Legacy selector diagnostics remain with their original reader. */ }
43
+ if (value?.schema === "agent-mem.shards/v3" || profile?.schema === "agent-mem.profile/v3") {
44
+ const refusal = placementSelectorRefusal(base); if (refusal) throw new Error(refusal);
45
+ return false;
46
+ }
47
+ if (shardError !== undefined) throw shardError;
39
48
  if (value === undefined) return false;
40
49
  if (!value || (value.schema !== SHARDED_SCHEMA && value.schema !== SHARDED_V2_SCHEMA) || !validGeneration(value.generation) || (value.phase !== "captured" && value.phase !== "active") || typeof value.selectorRevision !== "string") throw new Error("curated shard selection is unavailable or invalid");
41
50
  return value.phase === "captured";
@@ -215,13 +215,15 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
215
215
  if (rest.length) fail(`usage: ${names.memory} sync [--remote <private git url>]`);
216
216
  const r = await syncMemory(store, { ...opts.sync, ...(remote ? { remote } : {}) });
217
217
  if (json) return JSON.stringify(r, null, 2);
218
- if (!r.ok) fail(`${names.memory} sync: ${r.error}`);
219
218
  const placement = r.placementPublication, placementText = placement ? `; placement ${placement.outcome}, ${placement.exported} exported, ${placement.withheld} withheld this attempt` : "";
219
+ // #450: one line per activated realm (`user` or a key hash; never a project name).
220
+ const realmLines = r.placementRealms?.length ? `\n${r.placementRealms.map(item => `realm ${item.realm === "user" ? "user" : item.realm.slice(0, 16)}: ${item.outcome}${item.publication ? ` (publication ${item.publication})` : ""}`).join("\n")}` : "";
221
+ if (!r.ok) fail(`${names.memory} sync: ${r.error}${realmLines}`);
220
222
  if (r.pruneApplication) {
221
223
  const a = r.pruneApplication;
222
- return `synced${r.pushed ? " and pushed" : ""}: ${r.entries} long-term entries transported; ${a.proofComplete} prune proofs complete, ${a.projectionActive ?? "pending"} foreign projections active, ${a.nativeApplied ?? "pending"} native prunes applied, ${a.held} held${placementText}${r.warning ? `\nnote: ${r.warning}` : ""}`;
224
+ return `synced${r.pushed ? " and pushed" : ""}: ${r.entries} long-term entries transported; ${a.proofComplete} prune proofs complete, ${a.projectionActive ?? "pending"} foreign projections active, ${a.nativeApplied ?? "pending"} native prunes applied, ${a.held} held${placementText}${r.warning ? `\nnote: ${r.warning}` : ""}${realmLines}`;
223
225
  }
224
- return `synced${r.pushed ? " and pushed" : ""}: ${r.entries} long-term entries visible here${placementText}${r.warning ? `\nnote: ${r.warning}` : ""}`;
226
+ return `synced${r.pushed ? " and pushed" : ""}: ${r.entries} long-term entries visible here${placementText}${r.warning ? `\nnote: ${r.warning}` : ""}${realmLines}`;
225
227
  }
226
228
  case "dedupe": {
227
229
  const apply = rest.includes("--apply");
@@ -1,7 +1,7 @@
1
1
  import { existsSync, lstatSync, readdirSync, rmSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { readSelector } from "./generation.ts";
4
- import { aliasedKeys, readShardDescriptor, readShardedSelection } from "./shard.ts";
4
+ import { aliasedKeys, readShardDescriptor, readShardedSelection, resolveAlias, shardKeyHash } from "./shard.ts";
5
5
 
6
6
  /** Small selected-profile binding only; never a generation/source refresh. */
7
7
  export function curatedProfileBinding(base: string, project: string): string {
@@ -9,12 +9,15 @@ export function curatedProfileBinding(base: string, project: string): string {
9
9
  shards: existsSync(join(base, "shards.json")) ? readShardedSelection(base) : null,
10
10
  aliases: aliasedKeys(base, project) });
11
11
  }
12
- /** Off-hook conservative invalidation: derived directories only, never enumerate authoritative logs. */
13
- export function invalidateCuratedCaches(base: string): string[] {
14
- const projects = new Set<string>(), root = join(base, "projects");
12
+ /** Off-hook conservative invalidation: derived directories only, never enumerate authoritative logs.
13
+ * #424: `projects` limits removal to those projects' cache directories (an alias resolves to its canonical directory),
14
+ * so one project's write keeps every other project's prebuilt brief. Omitted, every project is invalidated. */
15
+ export function invalidateCuratedCaches(base: string, projects?: readonly string[]): string[] {
16
+ const invalidated = new Set<string>(), root = join(base, "projects");
15
17
  if (!existsSync(root)) return [];
18
+ const only = projects && new Set(projects.flatMap(project => [shardKeyHash(project), shardKeyHash(resolveAlias(base, project))]));
16
19
  for (const hash of readdirSync(root)) {
17
- if (!/^[a-f0-9]{16}$/.test(hash)) continue;
20
+ if (!/^[a-f0-9]{16}$/.test(hash) || only && !only.has(hash)) continue;
18
21
  const directory = join(root, hash), stat = lstatSync(directory);
19
22
  if (!stat.isDirectory() || stat.isSymbolicLink()) continue;
20
23
  const descriptor = readShardDescriptor(base, hash);
@@ -29,8 +32,8 @@ export function invalidateCuratedCaches(base: string): string[] {
29
32
  const files = ["brief-curated.json", "brief-preferences.json"].map(name => join(scope, name));
30
33
  if (!files.some(file => lstatSync(file, { throwIfNoEntry: false }))) continue;
31
34
  for (const file of files) rmSync(file, { force: true });
32
- if (descriptor) projects.add(descriptor.key);
35
+ if (descriptor) invalidated.add(descriptor.key);
33
36
  }
34
37
  }
35
- return [...projects];
38
+ return [...invalidated];
36
39
  }
@@ -1,4 +1,5 @@
1
- import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
1
+ import { placementRuntimeRefusal, withDoctorPlacementScratch } from "./sync-placement-guard.ts";
2
+ import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
2
3
  import { indexFileName } from "./index-file.ts";
3
4
  import { assertFormatFloor } from "./formats.ts";
4
5
  import { tmpdir } from "node:os";
@@ -141,7 +142,7 @@ function copyCurated(options: Pick<DoctorOptions, "home" | "project" | "aliases"
141
142
  observedCopy(join(home, name), join(scratch, name), budget);
142
143
  }
143
144
  const selected = readSelector(home).selector;
144
- if (selected?.schema === "agent-mem.profile/v2") {
145
+ if (selected?.schema === "agent-mem.profile/v2" || selected?.schema === "agent-mem.profile/v3") {
145
146
  const name = `${selected.pruneInputSetHash}.json`, source = join(home, "public-prune-input-sets", name), stat = lstatSync(source);
146
147
  if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1) throw new Error("the committed public prune view is not a plain file");
147
148
  const directory = join(scratch, "public-prune-input-sets"); mkdirSync(directory, { mode: 0o700 });
@@ -176,7 +177,6 @@ function copyWork(options: Pick<DoctorOptions, "home" | "project" | "aliases">,
176
177
  /** Reuse doctor's bounded private inputs for an on-demand brief, never a live store or reader lease. */
177
178
  export async function withBriefSnapshot<T>(home: string, project: string, read: (inputs: NonNullable<BriefOptions["measureOnly"]>) => Promise<T>): Promise<T> {
178
179
  const aliases = aliasedKeys(home, project), selection = readSelector(home).revision, layout = layoutOf(home), guard = guardScratch();
179
- let scratch: string | undefined, curated: MemoryStore | undefined;
180
180
  const budget: CopyBudget = { bytes: 0, verify: [] };
181
181
  const inputDirectories = [join(home, "projects"), ...(layout === "split" ? [join(home, "user")] : [join(home, "log"), join(home, "local")]),
182
182
  ...(layout === "generation" ? [join(home, "generations")] : []),
@@ -191,22 +191,26 @@ export async function withBriefSnapshot<T>(home: string, project: string, read:
191
191
  };
192
192
  try {
193
193
  checkDirectories();
194
- scratch = mkdtempSync(join(tmpdir(), `amem-doctor-${process.pid}-`)); chmodSync(scratch, 0o700); guard.adopt(scratch);
195
- const options = { home, project, aliases }, workBase = join(scratch, "work-base"); mkdirSync(workBase, { mode: 0o700 });
196
- copyWork(options, workBase, budget);
197
- if (curatedPresent(home, project, layout)) {
198
- const copy = join(scratch, "home"); mkdirSync(copy, { mode: 0o700 }); copyCurated(options, layout, copy, budget);
199
- curated = openCuratedForRead(copy, project);
200
- if (!curated) throw Error("recap curated snapshot unavailable");
201
- }
202
- check();
203
- const result = await read({ ...(curated ? { curated } : {}), workBase });
204
- check(); return result;
194
+ return await withDoctorPlacementScratch(home, guard.adopt, async scratch => {
195
+ let curated: MemoryStore | undefined;
196
+ try {
197
+ const options = { home, project, aliases }, workBase = join(scratch, "work-base"); mkdirSync(workBase, { mode: 0o700 });
198
+ copyWork(options, workBase, budget);
199
+ if (curatedPresent(home, project, layout)) {
200
+ const copy = join(scratch, "home"); copyCurated(options, layout, copy, budget);
201
+ curated = openCuratedForRead(copy, project);
202
+ if (!curated) throw Error("recap curated snapshot unavailable");
203
+ }
204
+ check();
205
+ const result = await read({ ...(curated ? { curated } : {}), workBase });
206
+ check(); return result;
207
+ } finally { curated?.close(); }
208
+ });
205
209
  } catch (error) {
206
210
  if (error instanceof TooBig) throw Error("recap snapshot exceeds the 64 MiB copy limit");
207
211
  throw error;
208
212
  } finally {
209
- try { curated?.close(); } finally { try { if (scratch) rmSync(scratch, { recursive: true, force: true }); } finally { guard.release(); } }
213
+ guard.release();
210
214
  }
211
215
  }
212
216
 
@@ -252,7 +256,9 @@ function duplicatesAndStale(options: DoctorOptions, rows: View[], store: MemoryS
252
256
 
253
257
  /** The incremental index, as a reader would refresh it from the snapshot of the live one, against a full rebuild of the same logs. Both live in the scratch copy. */
254
258
  function indexSection(store: MemoryStore, layout: Layout, snapshotted: boolean): Section {
255
- if (layout !== "shared-v1") return skipped("a curated split or generation home builds and seals its index when it is created; amem rebuild repeats it");
259
+ if (layout !== "shared-v1") return skipped(store.profile.publicationFormat === "agent-mem.sync-placement/v1"
260
+ ? "the live placement index cannot be compared without rebuilding it on open; run amem rebuild to rebuild the index"
261
+ : "a curated split or generation home builds and seals its index when it is created; amem rebuild repeats it");
256
262
  try {
257
263
  store.list({ limit: 1 }); // brings the snapshot level with the logs, as the next reader would
258
264
  const incremental = store.dump(); store.rebuild();
@@ -464,21 +470,21 @@ export const DOCTOR_GIT_TIMEOUT_MS = 5_000;
464
470
  export function doctorReport(options: DoctorOptions): Promise<DoctorReport> {
465
471
  // Doctor reads every surface below, live or through a scratch copy: a floor on any of them refuses the whole report before anything is read (#199 AC5).
466
472
  for (const surface of ["curated", "capture", "candidates", "work-lists", "hook-spool"] as const) assertFormatFloor(options.home, surface);
467
- return withGitTimeout(DOCTOR_GIT_TIMEOUT_MS, () => runDoctor(options));
473
+ return withGitTimeout(DOCTOR_GIT_TIMEOUT_MS, async () => {
474
+ const guard = guardScratch();
475
+ try { return await withDoctorPlacementScratch(options.home, guard.adopt, scratch => runDoctor(options, scratch)); }
476
+ finally { guard.release(); }
477
+ });
468
478
  }
469
- async function runDoctor(options: DoctorOptions): Promise<DoctorReport> {
470
- let scratch: string | undefined, unguard: (() => void) | undefined;
479
+ async function runDoctor(options: DoctorOptions, scratch: string): Promise<DoctorReport> {
471
480
  let duplicates: Section, stale: Section, index: Section;
472
481
  let curated: MemoryStore | undefined, workBase: string | undefined, copyFailed: string | undefined;
473
482
  try {
474
483
  let layout: Layout | undefined;
475
484
  try { layout = layoutOf(options.home); } catch (error) { throw new Error(`the memory profile cannot be read: ${message(error)}`); }
485
+ const refusal = placementRuntimeRefusal(options.home);
486
+ if (refusal) throw Error(refusal);
476
487
  sweepStaleScratch();
477
- // The guard is installed BEFORE the directory exists and told its name afterwards: a signal in the few microseconds between `mkdtemp` and a guard installed after it would
478
- // meet no handler, take the default action and strand the directory (measured: 4 of 60 runs when a signal lands the instant it appears).
479
- const guard = guardScratch(); unguard = guard.release;
480
- scratch = mkdtempSync(join(tmpdir(), `amem-doctor-${process.pid}-`)); // a scratch directory, never inside the home: a home nobody used stays absent
481
- guard.adopt(scratch);
482
488
  options.afterScratch?.(scratch);
483
489
  const budget = { bytes: 0 };
484
490
  try {
@@ -487,7 +493,7 @@ async function runDoctor(options: DoctorOptions): Promise<DoctorReport> {
487
493
  if (!curatedPresent(options.home, options.project, layout)) {
488
494
  duplicates = stale = index = skipped("no curated notes for this project yet");
489
495
  } else {
490
- const home = join(scratch, "home"); mkdirSync(home, { mode: 0o700 });
496
+ const home = join(scratch, "home");
491
497
  copyCurated(options, layout, home, budget);
492
498
  const snapshotted = layout === "shared-v1" && snapshotIndex(options.home, join(home, indexFileName(false)));
493
499
  curated = options.openCurated(home);
@@ -518,7 +524,7 @@ async function runDoctor(options: DoctorOptions): Promise<DoctorReport> {
518
524
  await tick();
519
525
  sections = { duplicates, stale, candidates, capture: captureSection(options), brief: await briefSection(options, curated, workBase, copyFailed), index, readers: readersSection(options), policy: policySection(options), cadence: cadenceSection(options), drops: dropsSection(options), spool: spoolSection(options), setup, ...maskedSection(curated) };
520
526
  await tick(); // a signal that arrived during the last synchronous stage is handled while the guard is still installed
521
- } finally { try { curated?.close(); } finally { try { if (scratch) rmSync(scratch, { recursive: true, force: true }); } finally { unguard?.(); } } }
527
+ } finally { curated?.close(); }
522
528
  return { schema: DOCTOR_SCHEMA, status: worst(Object.values(sections).map(section => section.status)), home: { path: options.home, source: options.homeSource }, project: options.project, sections };
523
529
  }
524
530
 
@@ -32,7 +32,8 @@ const READER_VERSION: string | undefined = (() => {
32
32
  catch { return undefined; }
33
33
  })();
34
34
  const parts = (version: string) => SEMVER.exec(version)!.slice(1, 4).map(Number);
35
- function below(reader: string, floor: string): boolean {
35
+ /** Compare versions accepted by format-floor records, using their numeric release components. */
36
+ export function formatVersionBelow(reader: string, floor: string): boolean {
36
37
  const a = parts(reader), b = parts(floor);
37
38
  for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i]! < b[i]!;
38
39
  return false;
@@ -65,7 +66,7 @@ export function assertFormatFloor(home: string, surface: FormatSurface): void {
65
66
  const floors = readFormatFloors(home);
66
67
  if (!floors) return;
67
68
  const reader = READER_VERSION ?? "unknown";
68
- for (const floor of floors) if ((floor.surface === surface || floor.surface === "home") && (READER_VERSION === undefined || below(READER_VERSION, floor.minReader))) {
69
+ for (const floor of floors) if ((floor.surface === surface || floor.surface === "home") && (READER_VERSION === undefined || formatVersionBelow(READER_VERSION, floor.minReader))) {
69
70
  throw new FormatFloorError("format_floor", `amem ${reader} is below the ${surface} format floor ${floor.minReader} (since ${floor.since}) recorded in ${join(home, FORMATS_FILE)}; nothing was read or written. Upgrade amem to ${floor.minReader} or later.`, { ...floor, reader });
70
71
  }
71
72
  }
@@ -73,7 +74,7 @@ export function assertFormatFloor(home: string, surface: FormatSurface): void {
73
74
  /** A person opts into a capability only by an applicable floor, never by this code writing one. */
74
75
  export function formatFloorAtLeast(home: string, surface: FormatSurface, minimum: string): boolean {
75
76
  if (!SEMVER.test(minimum)) return false;
76
- return (readFormatFloors(home) ?? []).some(floor => (floor.surface === surface || floor.surface === "home") && !below(floor.minReader, minimum));
77
+ return (readFormatFloors(home) ?? []).some(floor => (floor.surface === surface || floor.surface === "home") && !formatVersionBelow(floor.minReader, minimum));
77
78
  }
78
79
 
79
80
  /**
@@ -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
- this.replayProvenance = true; // persistent SQLite never supplies foreign membership
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
- const snapshot = this.snapshot(false);
222
- 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 }));
223
- const reduced = reducePruneRows(prunes, snapshot, this.profile.generation!);
224
- db.run("DELETE FROM generation_targets");
225
- for (const id of [...reduced.targets].sort()) db.query("INSERT INTO generation_targets VALUES (?)").run(id);
226
- this.applyForeign(true);
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
- private applyForeign(validateRows = false): void {
230
- if (!this.profile.foreignPruneFormat) return;
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
- const key = profile.shardUser ? "user" : `project:${profile.shardKey}`, set = view.realms[key];
235
- const db = this.options.db;
236
- if (!set) {
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: profile.generation, inputSetHash: set, ...(profile.publicationFormat ? {publicationFormat:profile.publicationFormat} : {}) }) };
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) db.transaction(() => this.applyForeign()).deferred(); 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; }
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(); }
@@ -1,5 +1,5 @@
1
- /** Bumped when the index's tables change: an index with another version is dropped and rebuilt from the logs. */
2
- export const INDEX_VERSION = 4; // 4: the preference kind (an older index skipped such notes)
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