@staix/agent-mem 0.28.2 → 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.
Files changed (40) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +11 -7
  3. package/package.json +1 -1
  4. package/src/brief-work.ts +142 -0
  5. package/src/cli.ts +34 -13
  6. package/src/commands-table.ts +2 -0
  7. package/src/mcp-memory.ts +1 -1
  8. package/src/memory/commands.ts +5 -3
  9. package/src/memory/curated-cache-state.ts +10 -7
  10. package/src/memory/doctor.ts +15 -12
  11. package/src/memory/generation-index.ts +79 -17
  12. package/src/memory/index-file.ts +2 -2
  13. package/src/memory/metrics.ts +1 -0
  14. package/src/memory/shard-sync-history.ts +6 -0
  15. package/src/memory/shard.ts +33 -13
  16. package/src/memory/store.ts +147 -41
  17. package/src/memory/sync-placement-capture.ts +53 -17
  18. package/src/memory/sync-placement-guard.ts +52 -1
  19. package/src/memory/sync-placement-inventory.ts +136 -0
  20. package/src/memory/sync-placement-journal-storage.ts +21 -4
  21. package/src/memory/sync-placement-journal.ts +13 -4
  22. package/src/memory/sync-placement-materialize.ts +14 -3
  23. package/src/memory/sync-placement-publication-plan.ts +8 -4
  24. package/src/memory/sync-placement-realm-admission-storage.ts +128 -0
  25. package/src/memory/sync-placement-realm-admission.ts +335 -0
  26. package/src/memory/sync-placement-realm-attribution.ts +23 -0
  27. package/src/memory/sync-placement-realm-effective.ts +71 -0
  28. package/src/memory/sync-placement-realm-extension-format.ts +66 -0
  29. package/src/memory/sync-placement-realm-extension-storage.ts +82 -0
  30. package/src/memory/sync-placement-realm-intent-format.ts +55 -0
  31. package/src/memory/sync-placement-realm-intent-storage.ts +123 -0
  32. package/src/memory/sync-placement-realm-pending.ts +27 -0
  33. package/src/memory/sync-placement-realm-proof.ts +131 -0
  34. package/src/memory/sync-placement-realm-torn.ts +26 -0
  35. package/src/memory/sync-placement-transport.ts +69 -31
  36. package/src/memory/sync-placement-yield.ts +30 -0
  37. package/src/memory/sync-progress.ts +47 -6
  38. package/src/memory/sync.ts +23 -1
  39. package/src/memory/work-lists.ts +129 -9
  40. package/src/session-brief.ts +34 -1
@@ -43,6 +43,11 @@ import { groupByTask, taskGroupKey } from "./task-group.ts";
43
43
  */
44
44
  export const MEMORY_SCHEMA = "agent-hub.memory/v1";
45
45
  export const MEMORY_DB_BUSY_TIMEOUT_MS = 3000;
46
+ /** SQLite's own lock refusal: a concurrent writer caused it, and a later read retries it. */
47
+ function lockedDatabase(error: unknown): boolean {
48
+ const code = (error as { code?: unknown } | null)?.code;
49
+ return (typeof code === "string" && code.startsWith("SQLITE_BUSY")) || /database is locked|SQLITE_BUSY/i.test(`${(error as Error | null)?.message ?? error}`);
50
+ }
46
51
  export const KINDS = ["decision", "finding", "contract", "fail", "preference"] as const;
47
52
  export type Kind = (typeof KINDS)[number];
48
53
  /** Kinds that move to long-term when their task is approved; findings stay short-term unless a person promotes them. */
@@ -214,6 +219,8 @@ interface BootstrapBinding { token: typeof MIGRATION_BOOTSTRAP; profile: BoundPr
214
219
  // Defer publication until the outermost source fence in this process has released.
215
220
  const curatedDepth = new Map<string, number>();
216
221
  const curatedPending = new Map<string, Map<MemoryStore, Set<string>>>();
222
+ /** #424: a project-scope, non-preference row appears only in its own project's prebuilt curated brief (the preference slot also reads shared rows). */
223
+ const curatedLocal = (row: { scope?: string; kind?: string }): boolean => row.scope === "project" && row.kind !== "preference";
217
224
  let publishingCurated = false;
218
225
 
219
226
  export class MemoryStore {
@@ -305,8 +312,9 @@ export class MemoryStore {
305
312
  try { chmodSync(indexFile, 0o600); } catch { /* best effort */ }
306
313
  if (this.profile.kind === "generation") this.generationIndex = new GenerationIndex({ profile: this.profile, db, now: this.now,
307
314
  apply: (line, source) => this.apply(line, source), withMutation: work => this.withMutation(work), beforeCuratedWrite: targets => {
308
- invalidateCuratedCaches(this.profile.home);
309
- const rows = this.db.query("SELECT DISTINCT project FROM entries WHERE id IN (SELECT value FROM json_each(?))").all(JSON.stringify(targets)) as { project: string }[];
315
+ const rows = this.db.query("SELECT project, scope, kind FROM entries WHERE id IN (SELECT value FROM json_each(?))").all(JSON.stringify(targets)) as { project: string; scope: string; kind: string }[];
316
+ // #424: only the touched projects' prebuilt briefs; a shared or preference row (or an unknown target) can reach every project's slot.
317
+ invalidateCuratedCaches(this.profile.home, rows.length === targets.length && rows.every(row => curatedLocal(row)) && rows.every(row => this.curatedChangeLocal(row.project, targets)) ? rows.map(row => row.project) : undefined);
310
318
  this.queueCuratedProjects(rows.map(row => row.project));
311
319
  },
312
320
  ...(bootstrap ? { limits: bootstrap.limits } : {}), ...(bootstrap?.commit ? { commit: bootstrap.commit } : {}) });
@@ -422,14 +430,65 @@ export class MemoryStore {
422
430
  const pending = curatedPending.get(home); curatedPending.delete(home);
423
431
  if (!pending) return;
424
432
  publishingCurated = true;
425
- try { for (const [store, projects] of pending) store.publishCurated(projects); }
433
+ // #466: a project's own handle publishes its brief instead of a second handle indexing the same shard.
434
+ try { for (const [store, projects] of pending) store.publishCurated(projects, store, true); }
426
435
  finally { publishingCurated = false; }
427
436
  };
428
437
  }
429
438
 
430
- private markCuratedChange(project?: string): void {
439
+ // ponytail: retain at most 4096 relation rows per store; above that, invalidate home-wide. Upgrade to a bounded indexed relation lookup if this ceiling becomes common.
440
+ private curatedRelations: Set<string> | null | undefined;
441
+ private curatedRelationsVersion: number | undefined;
442
+ private hasCuratedRelation(id: string): boolean {
443
+ try {
444
+ if (this.stale || (!this.generationIndex && this.shape() !== this.seen)) { this.curatedRelations = undefined; return true; }
445
+ if (this.generationIndex) {
446
+ if (!this.profile.sharded) return true; // This handle cannot prove the full multi-project generation frontier is current.
447
+ return !!this.db.query("SELECT 1 FROM entries WHERE supersedes=? OR promoted_from=? LIMIT 1").get(id, id)
448
+ || !!this.db.query("SELECT 1 FROM ops WHERE op='supersede' AND (target=? OR by=?) LIMIT 1").get(id, id);
449
+ }
450
+ const version = (this.db.query("PRAGMA data_version").get() as { data_version: number }).data_version;
451
+ if (this.curatedRelationsVersion !== version) { this.curatedRelations = undefined; this.curatedRelationsVersion = undefined; }
452
+ if (this.curatedRelations === null) return true;
453
+ if (!this.curatedRelations) {
454
+ const notes = this.db.query("SELECT id, supersedes, promoted_from FROM entries WHERE supersedes IS NOT NULL OR promoted_from IS NOT NULL LIMIT 4097").all() as { id: string; supersedes: string | null; promoted_from: string | null }[];
455
+ const ops = this.db.query("SELECT target, by FROM ops WHERE op='supersede' LIMIT 4097").all() as { target: string; by: string | null }[];
456
+ if ((this.db.query("PRAGMA data_version").get() as { data_version: number }).data_version !== version) return true;
457
+ this.curatedRelationsVersion = version;
458
+ if (notes.length + ops.length > 4096) { this.curatedRelations = null; return true; }
459
+ const ids = new Set<string>();
460
+ for (const row of notes) for (const value of [row.id, row.supersedes, row.promoted_from]) if (value) ids.add(value);
461
+ for (const row of ops) for (const value of [row.target, row.by]) if (value) ids.add(value);
462
+ this.curatedRelations = ids;
463
+ }
464
+ return this.curatedRelations.has(id);
465
+ } catch { this.curatedRelations = undefined; return true; }
466
+ }
467
+
468
+ /** Relations can hide or revive a note in another project. Unresolved or already-related targets fall back to home-wide. */
469
+ private curatedChangeLocal(project: string, targets: readonly string[]): boolean {
470
+ if (!targets.length || this.generationIndex && !this.profile.sharded) return false;
471
+ try {
472
+ for (const id of targets) {
473
+ const row = this.db.query("SELECT project, scope, kind, supersedes, promoted_from FROM entries WHERE id=?").get(id) as
474
+ { project: string; scope: string; kind: string; supersedes: string | null; promoted_from: string | null } | null;
475
+ if (!row || row.project !== project || !curatedLocal(row) || row.supersedes || row.promoted_from) return false;
476
+ if (this.hasCuratedRelation(id)) return false;
477
+ }
478
+ return true;
479
+ } catch { return false; }
480
+ }
481
+
482
+ private rememberCuratedRelation(id: string, targets: readonly string[]): void {
483
+ if (!targets.length || !this.curatedRelations) return;
484
+ this.curatedRelations.add(id); for (const target of targets) this.curatedRelations.add(target);
485
+ if (this.curatedRelations.size > 8192) this.curatedRelations = null;
486
+ }
487
+
488
+ /** #424: `local` means the change is visible only in `project`'s prebuilt brief; otherwise every project's cache is invalidated. */
489
+ private markCuratedChange(project?: string, local = false): void {
431
490
  if (this.bootstrapOnly) return;
432
- invalidateCuratedCaches(this.profile.home);
491
+ invalidateCuratedCaches(this.profile.home, project && local ? [project] : undefined);
433
492
  this.queueCuratedProjects(project ? [project] : []);
434
493
  }
435
494
 
@@ -476,7 +535,7 @@ export class MemoryStore {
476
535
  catch { /* An off-hook read still succeeds when its optional derived cache cannot be prepared. */ }
477
536
  }
478
537
 
479
- private publishCurated(input: ReadonlySet<string>, opened?: MemoryStore): void {
538
+ private publishCurated(input: ReadonlySet<string>, opened?: MemoryStore, openOnMiss = false): void {
480
539
  const projects = new Set(input);
481
540
  if (this.curatedRebuildAll) {
482
541
  this.curatedRebuildAll = false;
@@ -495,27 +554,36 @@ export class MemoryStore {
495
554
  if (sharded && !existsSync(join(shardDir(this.profile.home, project), "generation.json"))) continue;
496
555
  const reusable = opened && (!sharded || opened.profile.shardKey === project)
497
556
  && (aliases.length ? opened.reconcile?.canonical === project && opened.reconcile.aliases.join("\n") === aliases.join("\n") : !opened.reconcile);
498
- if (opened && !reusable) continue; // Explicit single-project preparation never retries with a second store.
557
+ if (opened && !reusable && !openOnMiss) continue; // Explicit single-project preparation never retries with a second store.
499
558
  view = reusable ? opened! : sharded ? openShardStore({ ...common, project }) : new MemoryStore(common);
500
- view.withStoreFences(() => {
501
- const selected = readSelector(this.profile.home);
502
- const shards = sharded ? readShardedSelection(this.profile.home) : null;
503
- if (view!.profile.selectorRevision !== selected.revision || view!.profile.kind !== (shards ? "generation" : selected.selector?.kind ?? "shared-v1")
504
- || view!.profile.generation !== (shards?.generation ?? selected.selector?.generation) || resolveAlias(this.profile.home, raw) !== project
505
- || shards && (shards.selectorRevision !== selected.revision || shards.generation !== view!.profile.generation)
506
- || aliasedKeys(this.profile.home, project).join("\n") !== aliases.join("\n")
507
- || (view!.reconcile?.aliases.join("\n") ?? "") !== aliases.join("\n")) {
508
- throw Error("curated snapshot source binding changed; retry an off-hook amem brief");
509
- }
510
- // Stamp the source handle's inputs, never a newer metadata read that it did not open.
511
- const binding = JSON.stringify({ selector: selected.revision, shards, aliases });
512
- ensureShardDescriptor(this.profile.home, project);
513
- const directory = shardMachineDir(this.profile.home, project, machineId(this.profile.home).id);
514
- mkdirSync(directory, { recursive: true, mode: 0o700 });
515
- buildCuratedBriefCache(view!, { base: this.profile.home, project, directory, binding, now: this.now });
516
- buildPreferenceBriefCache(view!, { base: this.profile.home, project, directory, binding, now: this.now });
517
- if (curatedProfileBinding(this.profile.home, project) !== binding) for (const name of ["brief-curated.json", "brief-preferences.json"]) rmSync(join(directory, name), { force: true });
518
- });
559
+ // #466 review (codex-connector P1): a derived publication may only republish an index this handle has updated.
560
+ // One attempt outside the publication flag, so a lock that is still held leaves the invalidated cache missing
561
+ // instead of republishing rows that predate the change (a forgotten note served for up to 24 h).
562
+ if (view.stale) view.ensureFresh();
563
+ if (view.stale) throw Error("curated snapshot source is unavailable; a later mutation retries");
564
+ // #466: a publication that already failed to index waits on the writer once, not once per derived read.
565
+ view.curatedPublication = true;
566
+ try {
567
+ view.withStoreFences(() => {
568
+ const selected = readSelector(this.profile.home);
569
+ const shards = sharded ? readShardedSelection(this.profile.home) : null;
570
+ if (view!.profile.selectorRevision !== selected.revision || view!.profile.kind !== (shards ? "generation" : selected.selector?.kind ?? "shared-v1")
571
+ || view!.profile.generation !== (shards?.generation ?? selected.selector?.generation) || resolveAlias(this.profile.home, raw) !== project
572
+ || shards && (shards.selectorRevision !== selected.revision || shards.generation !== view!.profile.generation)
573
+ || aliasedKeys(this.profile.home, project).join("\n") !== aliases.join("\n")
574
+ || (view!.reconcile?.aliases.join("\n") ?? "") !== aliases.join("\n")) {
575
+ throw Error("curated snapshot source binding changed; retry an off-hook amem brief");
576
+ }
577
+ // Stamp the source handle's inputs, never a newer metadata read that it did not open.
578
+ const binding = JSON.stringify({ selector: selected.revision, shards, aliases });
579
+ ensureShardDescriptor(this.profile.home, project);
580
+ const directory = shardMachineDir(this.profile.home, project, machineId(this.profile.home).id);
581
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
582
+ buildCuratedBriefCache(view!, { base: this.profile.home, project, directory, binding, now: this.now });
583
+ buildPreferenceBriefCache(view!, { base: this.profile.home, project, directory, binding, now: this.now });
584
+ if (curatedProfileBinding(this.profile.home, project) !== binding) for (const name of ["brief-curated.json", "brief-preferences.json"]) rmSync(join(directory, name), { force: true });
585
+ });
586
+ } finally { view.curatedPublication = false; }
519
587
  } catch { /* Failed derived publication leaves the invalidated cache unavailable; a later mutation retries. */ }
520
588
  finally { try { if (view !== opened) view?.close(); } catch { /* Preserve the authoritative mutation result. */ } }
521
589
  }
@@ -643,8 +711,21 @@ export class MemoryStore {
643
711
  return this.withMutation(() => {
644
712
  this.generationIndex?.assertAppendable(local, this.machine.id);
645
713
  const id = entryId(body);
646
- const affected = "project" in body ? String(body.project) : "target" in body && typeof body.target === "string" ? (this.db.query("SELECT project FROM entries WHERE id=? OR task=?").get(body.target, body.target) as { project: string } | null)?.project : undefined;
647
- if (body.op !== "goal" && body.op !== "goal_state" && body.op !== "goal_link") this.markCuratedChange(affected);
714
+ const owner = "project" in body ? body as { project: string; scope?: string; kind?: string } : "target" in body && typeof body.target === "string" ? this.db.query("SELECT project, scope, kind FROM entries WHERE id=? OR task=?").get(body.target, body.target) as { project: string; scope: string; kind: string } | null : undefined;
715
+ const affected = owner ? String(owner.project) : undefined;
716
+ if (body.op !== "goal" && body.op !== "goal_state" && body.op !== "goal_link") {
717
+ let localChange = false;
718
+ if (body.op === "note") {
719
+ const references = ["supersedes" in body ? body.supersedes : undefined, "promotedFrom" in body ? body.promotedFrom : undefined]
720
+ .filter((value): value is string => typeof value === "string" && value.length > 0);
721
+ localChange = !!owner && !!affected && curatedLocal(owner) && !this.hasCuratedRelation(id)
722
+ && (!references.length || this.curatedChangeLocal(affected, references));
723
+ } else if (body.op !== "settle" && owner && affected && "target" in body && typeof body.target === "string") {
724
+ const targets = [body.target, ...(body.op === "supersede" && "by" in body && typeof body.by === "string" ? [body.by] : [])];
725
+ localChange = this.curatedChangeLocal(affected, targets);
726
+ }
727
+ this.markCuratedChange(affected, localChange);
728
+ }
648
729
  appendFileSync(join(this.dir, local ? "local" : "log", `${this.machine.id}.jsonl`), JSON.stringify({ ...body, id }) + "\n", { mode: 0o600 });
649
730
  // The line is durable even if indexing fails; the next refresh catches up from the authoritative log.
650
731
  try { this.refresh(); } catch (e) { this.stale = true; this.log(`hub memory index not updated yet: ${(e as Error).message}`); }
@@ -693,7 +774,9 @@ export class MemoryStore {
693
774
  if (known) return { id: known.id, added: false };
694
775
  // The second own-segment writer after `appendBody`; an import of a row already present above refuses nothing because it writes nothing.
695
776
  this.assertPreferenceWritable(body);
696
- this.markCuratedChange(n.project);
777
+ const references = [n.supersedes, n.promotedFrom].filter((value): value is string => !!value);
778
+ const localChange = curatedLocal(n) && !this.hasCuratedRelation(id) && (!references.length || this.curatedChangeLocal(n.project, references));
779
+ this.markCuratedChange(n.project, localChange);
697
780
  appendFileSync(join(this.dir, n.tier === "short" ? "local" : "log", `${this.machine.id}.jsonl`), JSON.stringify({ ...body, id }) + "\n", { mode: 0o600 });
698
781
  return { id, added: true };
699
782
  });
@@ -815,16 +898,20 @@ export class MemoryStore {
815
898
  * long-term. Returns how many moved.
816
899
  */
817
900
  settle(task: string, actor: string): number {
818
- this.promoting = true; // promoted here, in the settling actor's name, not after each read
819
- try {
820
- const entry = { op: "settle", target: task, actor, by: this.until() } as const;
821
- const at = new Date(this.now()).toISOString();
822
- // #27: a task key `<key>#...` belongs to the shard of `<key>`. In a reconciled sharded store that can be an aliased key's shard, which refuses a settlement of any other key.
823
- const owner = this.aliasStores.find(store => store.profile.shardKey !== undefined && task.startsWith(`${store.profile.shardKey}#`));
824
- (owner ?? this).append(entry, true, at, owner ? this.machine.id : undefined);
825
- if (this.userOverlay) this.userOverlay.append(entry, true, at, this.machine.id);
826
- return this.promoteSettled(task, actor) + (this.userOverlay?.promoteSettled(task, actor) ?? 0) + this.aliasStores.reduce((n, store) => n + store.promoteSettled(task, actor), 0);
827
- } finally { this.promoting = false; }
901
+ // #466: the settle rows and every promotion they release land before one publication runs, and `promoting` covers
902
+ // this handle, its user overlay and its alias shards for the whole call.
903
+ return this.withDeferredPromotions(() => {
904
+ const release = this.deferCuratedPublication();
905
+ try {
906
+ const entry = { op: "settle", target: task, actor, by: this.until() } as const;
907
+ const at = new Date(this.now()).toISOString();
908
+ // #27: a task key `<key>#...` belongs to the shard of `<key>`. In a reconciled sharded store that can be an aliased key's shard, which refuses a settlement of any other key.
909
+ const owner = this.aliasStores.find(store => store.profile.shardKey !== undefined && task.startsWith(`${store.profile.shardKey}#`));
910
+ (owner ?? this).append(entry, true, at, owner ? this.machine.id : undefined);
911
+ if (this.userOverlay) this.userOverlay.append(entry, true, at, this.machine.id);
912
+ return this.promoteSettled(task, actor) + (this.userOverlay?.promoteSettled(task, actor) ?? 0) + this.aliasStores.reduce((n, store) => n + store.promoteSettled(task, actor), 0);
913
+ } finally { release(); }
914
+ });
828
915
  }
829
916
  private promoteSettled(task: string, actor: string): number {
830
917
  // Only the notes held for promotion (no deadline): one saved short-term after the settlement stays short-term.
@@ -926,6 +1013,7 @@ export class MemoryStore {
926
1013
 
927
1014
  /** Drop the index and read every segment again: the same rows as the incremental index. */
928
1015
  rebuild(): void {
1016
+ this.curatedRelations = undefined; this.curatedRelationsVersion = undefined;
929
1017
  this.searchIndex.reset();
930
1018
  if (this.generationIndex) { this.generationIndex.rebuild(); return; }
931
1019
  // One transaction: no reader sees the index empty, and no other process commits an offset in between.
@@ -960,6 +1048,7 @@ export class MemoryStore {
960
1048
  const inserted = this.db.query(`INSERT OR IGNORE INTO entries (id, at, machine, project, scope, tier, kind, peer, title, text, task, about, supersedes, promoted_from, source, expires)
961
1049
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(id, e.at, e.machine, e.project, e.scope === "shared" ? "shared" : "project", e.tier === "long" ? "long" : "short",
962
1050
  e.kind, e.peer, e.title ?? null, e.text, e.task ?? null, JSON.stringify(e.about.map(String)), e.supersedes ?? null, e.promotedFrom ?? null, e.source ?? "hub", typeof e.expires === "string" ? e.expires : null).changes;
1051
+ this.rememberCuratedRelation(id, [e.supersedes, e.promotedFrom].filter((value): value is string => !!value));
963
1052
  // The FTS copy follows the committed row. `changes` is only a hint here (bun:sqlite misreports it for ignored
964
1053
  // inserts inside a transaction): addCurated is idempotent by entry id, and a missed hint becomes a count drift
965
1054
  // the next search resyncs.
@@ -974,6 +1063,7 @@ export class MemoryStore {
974
1063
  const dated = !["demote", "settle", "lease", "lease_force"].includes(e.op) || (typeof e.by === "string" && !Number.isNaN(Date.parse(e.by)));
975
1064
  if (!str(e.target, 400) || !opt(e.by) || !opt(e.actor) || !dated) { this.log(`memory segment ${segment}: a malformed entry was skipped`); return; }
976
1065
  this.db.query("INSERT OR IGNORE INTO ops (id, op, at, machine, target, by, actor) VALUES (?, ?, ?, ?, ?, ?, ?)").run(id, e.op, e.at, e.machine, e.target, e.by ?? null, e.actor ?? "");
1066
+ if (e.op === "supersede" && e.by) this.rememberCuratedRelation(e.target, [e.by]);
977
1067
  }
978
1068
  }
979
1069
 
@@ -1172,8 +1262,19 @@ export class MemoryStore {
1172
1262
  if (!this.bootstrapOnly) rebindPublicPruneProfile(this.profile);
1173
1263
  this.userOverlay?.ensureFresh();
1174
1264
  for (const store of this.aliasStores) store.ensureFresh();
1175
- if (this.generationIndex) { this.generationIndex.refresh(); return; }
1265
+ // #466: a generation index that cannot take its writer keeps the rows it already has and retries on the next read,
1266
+ // exactly as the legacy path below does; any other failure still reaches the caller.
1267
+ if (this.generationIndex) {
1268
+ if (this.stale && this.curatedPublication) return; // one refusal is enough inside a derived publication
1269
+ try { this.generationIndex.refresh(); this.stale = false; }
1270
+ catch (error) {
1271
+ if (!lockedDatabase(error)) throw error;
1272
+ this.stale = true; this.log(`hub memory index not updated yet: ${(error as Error).message}`);
1273
+ }
1274
+ return;
1275
+ }
1176
1276
  // Another process (a CLI, another project's hub, a sync) may have written since this one last read the segments.
1277
+ if (this.stale && this.curatedPublication) return; // one refusal is enough inside a derived publication
1177
1278
  if (this.stale || this.shape() !== this.seen) try { this.stale = false; this.refresh(); } catch { this.stale = true; /* still busy: the next read tries again */ }
1178
1279
  }
1179
1280
 
@@ -1187,6 +1288,8 @@ export class MemoryStore {
1187
1288
  }
1188
1289
  /** A write whose index update failed: the next read refreshes first. */
1189
1290
  private stale = false;
1291
+ /** This handle is publishing a derived brief: a write lock already refused once is not re-waited on per derived read. */
1292
+ private curatedPublication = false;
1190
1293
 
1191
1294
  /** Entries visible from `project` (its own, and `shared` ones of any project), newest first, filtered. */
1192
1295
  list(f: Filter = {}): View[] {
@@ -1808,8 +1911,11 @@ export function buildPublicPruneIndex(profile: BoundProfile): {targets:string[];
1808
1911
  try {
1809
1912
  const before = store.derivedTables(); store.rebuild(); const tables = store.derivedTables();
1810
1913
  if (!isDeepStrictEqual(before, tables)) throw new Error("public prune view rebuild differs from incremental index");
1914
+ // #466: the foreign witness stamp proves the projected view's membership, so activating or advancing a view writes one
1915
+ // by design and it is not a source row; the equality above still holds it to what `rebuild()` produces.
1916
+ const state = (tables.generation_state as { key: string }[] | undefined)?.filter(row => row.key !== "foreignStamp");
1811
1917
  return { targets: (tables.generation_targets as {id:string}[]).map(row=>row.id).sort(),
1812
- sourceHash: hashJSON([tables.generation_rows, tables.generation_prunes, tables.generation_segments, tables.generation_state]) };
1918
+ sourceHash: hashJSON([tables.generation_rows, tables.generation_prunes, tables.generation_segments, state]) };
1813
1919
  } finally {store.close();}
1814
1920
  }
1815
1921
 
@@ -26,6 +26,7 @@ import { readEffectiveSyncPlacementWriters, writerBoundPlacementContextHash, wri
26
26
  import { SharedWriterRevisionError } from "./sync-placement-writer-revision-format.ts";
27
27
  import { inspectionBoundReceipt, type InspectionBound } from "./inspection-bound.ts";
28
28
  import { PLACEMENT_SOURCE_MAX_BYTES, PLACEMENT_SOURCE_MAX_ROWS } from "./sync-placement-bound.ts";
29
+ import { cooperativeYield } from "./sync-placement-yield.ts";
29
30
 
30
31
  /** Home-wide source capture ceilings. Every file is read twice (bytes, then a stable recheck), so the read budget is 2x. */
31
32
  export const PLACEMENT_CAPTURE_MAX_SOURCE_BYTES = PLACEMENT_SOURCE_MAX_BYTES, PLACEMENT_CAPTURE_MAX_ROWS = PLACEMENT_SOURCE_MAX_ROWS;
@@ -83,7 +84,7 @@ function ownedDirectory(dir: string): BigIntStats {
83
84
  /** ponytail: capture holds the whole home in memory, capped at 256 metadata objects and 64 MiB/20000 source rows
84
85
  * across all realms (#414 raised 8 MiB; a 23 MB/10,248-row home was refused). Larger homes need a reviewed
85
86
  * chunked/streaming activation proof; no input is silently omitted at this ceiling. */
86
- function sourcePreview(homeInput: string, selected?: readonly PlacementRealm[], pending: readonly PlacementPendingSource[] = [], policyVersion?: string, ownerProof?: PlacementActivationCaptureProof, sourceOwner?:PlacementActivationOwner): PlacementSourcePreview {
87
+ function* sourcePreviewSteps(homeInput: string, selected?: readonly PlacementRealm[], pending: readonly PlacementPendingSource[] = [], policyVersion?: string, ownerProof?: PlacementActivationCaptureProof, sourceOwner?:PlacementActivationOwner): Generator<void, PlacementSourcePreview, void> {
87
88
  let selection: PlacementRealm[] | undefined;
88
89
  if (selected !== undefined) {
89
90
  if (!Array.isArray(selected) || types.isProxy(selected)) fail();
@@ -171,7 +172,7 @@ function sourcePreview(homeInput: string, selected?: readonly PlacementRealm[],
171
172
  finally { iterator.closeSync(); }
172
173
  names.sort(); facts.push([dir, names]); return names;
173
174
  };
174
- const realm = (dir: string, identity: PlacementKey["realm"], project?: string) => {
175
+ const realm = function* (dir: string, identity: PlacementKey["realm"], project?: string): Generator<void, void, void> {
175
176
  directories.push(dir);
176
177
  const beforeFacts = facts.length; directoryFact(dir);
177
178
  if (project !== undefined) {
@@ -196,11 +197,13 @@ function sourcePreview(homeInput: string, selected?: readonly PlacementRealm[],
196
197
  }
197
198
  const segments = readShardLegacySnapshot(profile, { reader });
198
199
  for (const folder of ["log", "local"]) {
200
+ yield;
199
201
  directoryFact(join(dir, folder));
200
202
  const folderPath=join(dir,folder), folderStamp=lstatSync(folderPath,{bigint:true});
201
203
  sourceChecks.push(() => { if(!same(folderStamp,lstatSync(folderPath,{bigint:true}))) fail(); });
202
204
  if(folder === "local") bytes(join(dir,folder,`publisher-boundary-${machine.id}.json`),true);
203
205
  for (const name of reader.listFiles(join(dir, folder))) {
206
+ yield;
204
207
  if (!name.endsWith(".jsonl")) continue;
205
208
  if ( !/^[A-Za-z0-9][A-Za-z0-9._-]*\.jsonl$/.test(name)) fail();
206
209
  segments.push({ ...reader.read(join(dir, folder, name), undefined, true), source: "generation", path: `${folder}/${name}`, local: folder === "local" });
@@ -214,6 +217,7 @@ function sourcePreview(homeInput: string, selected?: readonly PlacementRealm[],
214
217
  special.set(row.id, { key, row, sourcePlacement: local ? "local" : "synced", intrinsicLocal: row.op === "vault_link" });
215
218
  };
216
219
  for (const segment of segments) {
220
+ yield;
217
221
  const file = join(segment.source === "generation" ? dir : segment.source === "legacy-main" ? profile.legacyMainHome! : profile.legacyHome!, segment.path);
218
222
  const fileStat = lstatSync(file);
219
223
  if (!fileStat.isFile() || fileStat.isSymbolicLink() || fileStat.nlink !== 1 || fileStat.uid !== process.getuid?.() || (fileStat.mode & 0o022) !== 0) fail();
@@ -243,6 +247,7 @@ function sourcePreview(homeInput: string, selected?: readonly PlacementRealm[],
243
247
  dev: physical[0] as string, ino: physical[1] as string, byteLength: sourceLength, hash: sourceHash,
244
248
  mtimeNs: physical[3] as string, ctimeNs: physical[4] as string });
245
249
  for (const line of completeLines(segment.bytes)) {
250
+ yield;
246
251
  if (!line.length) continue;
247
252
  const parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(line));
248
253
  if (segment.source === "generation" && parsed?.op === "prune") {
@@ -262,11 +267,13 @@ function sourcePreview(homeInput: string, selected?: readonly PlacementRealm[],
262
267
  }
263
268
  }
264
269
  for (const source of special.values()) {
270
+ yield;
265
271
  if (presence.has(source.key.id)) fail();
266
272
  specialRows.set(placementKeyId(source.key), source);
267
273
  }
268
274
  sourceRowsByRealm.set(canonicalJSON(identity), [...presence.values()]);
269
275
  for (const source of presence.values()) {
276
+ yield;
270
277
  const key = { realm: identity, id: source.row.id, rowHash: hashJSON(source.row) };
271
278
  rows.set(placementKeyId(key), { key, row: source.row, sourcePlacement: source.placement,
272
279
  intrinsicLocal: source.row.op === "settle" || source.row.op === "note" && source.row.tier === "short" });
@@ -274,8 +281,9 @@ function sourcePreview(homeInput: string, selected?: readonly PlacementRealm[],
274
281
  const bindingHash = hashJSON(facts.slice(beforeFacts));
275
282
  realms.push({ ...identity, bindingHash });
276
283
  };
277
- if (!selection || selection.some(item => item.scope === "user")) realm(join(home, "user"), { scope: "user" });
284
+ if (!selection || selection.some(item => item.scope === "user")) yield* realm(join(home, "user"), { scope: "user" });
278
285
  for (const name of listing(join(home, "projects"), true)) {
286
+ yield;
279
287
  if (!/^[a-f0-9]{16}$/.test(name)) fail();
280
288
  if (selection && !selection.some(item => item.scope === "project" && item.keyHash.slice(0,16) === name)) continue;
281
289
  const dir = join(home, "projects", name), project = json(join(dir, "project.json"));
@@ -284,7 +292,7 @@ function sourcePreview(homeInput: string, selected?: readonly PlacementRealm[],
284
292
  if (!lstatSync(join(dir, "generation.json"), { throwIfNoEntry: false })) continue;
285
293
  const keyHash = digest(project.key);
286
294
  if (selection && !selection.some(item => item.scope === "project" && item.keyHash === keyHash)) fail();
287
- realm(dir, { scope: "project", keyHash }, project.key);
295
+ yield* realm(dir, { scope: "project", keyHash }, project.key);
288
296
  }
289
297
  if (selection && realms.length !== selection.length) fail();
290
298
  const defaults = memoryPolicySnapshot({ names: DENY_NAMES, segments: DENY_SEGMENTS }); if (!defaults) fail();
@@ -307,6 +315,17 @@ function sourcePreview(homeInput: string, selected?: readonly PlacementRealm[],
307
315
  return { home, base: contextBase, assertSourcesUnchanged, ...(activeHead ? { activeHead } : {}), markerHash, markers,
308
316
  directories: directories.sort(), prefixes, rows, specialRows, sourceRowsByRealm };
309
317
  }
318
+ /** The synchronous activation and preview APIs drain the identical source steps without scheduling changes. */
319
+ function sourcePreview(home: string, selected?: readonly PlacementRealm[], pending: readonly PlacementPendingSource[] = [], policyVersion?: string, ownerProof?: PlacementActivationCaptureProof, sourceOwner?: PlacementActivationOwner): PlacementSourcePreview {
320
+ const steps = sourcePreviewSteps(home, selected, pending, policyVersion, ownerProof, sourceOwner);
321
+ let next = steps.next(); while (!next.done) next = steps.next(); return next.value;
322
+ }
323
+ /** The transport releases its caller's event loop between bounded source collection steps. */
324
+ async function sourcePreviewAsync(home: string, selected?: readonly PlacementRealm[], pending: readonly PlacementPendingSource[] = [], policyVersion?: string): Promise<PlacementSourcePreview> {
325
+ const steps = sourcePreviewSteps(home, selected, pending, policyVersion), pause = cooperativeYield();
326
+ let next = steps.next(); while (!next.done) { await pause(); next = steps.next(); }
327
+ next.value.assertSourcesUnchanged(); return next.value;
328
+ }
310
329
  /** The homeHash a retained epoch (or an in-flight activation) already committed to, so a reboot-renumbered device keeps binding (#444). */
311
330
  function pinnedHomeHash(home: string, activeHead: string | undefined, activating: boolean): string | undefined {
312
331
  try {
@@ -335,9 +354,12 @@ function previewSources(home:string,owner?:PlacementActivationOwner):PlacementSo
335
354
  }
336
355
  function capture(home: string, port: PlacementCapturePort, selected?: readonly PlacementRealm[], pending: readonly PlacementPendingSource[] = [], ownerProof?: PlacementActivationCaptureProof): Omit<PlacementCapture, "assertCurrent"> {
337
356
  // All host callouts precede filesystem capture, including the final passive proof.
338
- const attestation = memoryPolicySnapshot(port.attest()), policyVersion = port.policyVersion?.();
339
- if (!attestation || port.policyVersion && typeof policyVersion !== "string") fail();
357
+ const attestation = memoryPolicySnapshot(port.attest()) ?? fail(), policyVersion = port.policyVersion?.();
358
+ if (port.policyVersion && typeof policyVersion !== "string") fail();
340
359
  const source = sourcePreview(home, selected, pending, policyVersion, ownerProof);
360
+ return captureFromSource(port, source, attestation, policyVersion);
361
+ }
362
+ function captureFromSource(port: PlacementCapturePort, source: PlacementSourcePreview, attestation: ReturnType<PlacementCapturePort["attest"]>, policyVersion: string | undefined): Omit<PlacementCapture, "assertCurrent"> {
341
363
  const context: SyncPlacementActivationContext = { ...source.base, writers: attestation.writers, legacySyncQuiesced: attestation.legacySyncQuiesced };
342
364
  const validated = planSyncPlacementActivation(context, "0".repeat(64));
343
365
  context.writers = validated.writers; context.realms = validated.realms;
@@ -359,8 +381,7 @@ function capture(home: string, port: PlacementCapturePort, selected?: readonly P
359
381
  prefixes: source.prefixes, rows: source.rows, specialRows: source.specialRows, sourceRowsByRealm: source.sourceRowsByRealm };
360
382
  }
361
383
 
362
- export function captureSyncPlacementContext(home: string, port: PlacementCapturePort, selected?: readonly PlacementRealm[], pendingInput: readonly PlacementPendingSource[] = []): PlacementCapture {
363
- try {
384
+ function captureInput(selected: readonly PlacementRealm[] | undefined, pendingInput: readonly PlacementPendingSource[]) {
364
385
  const selection = selected === undefined ? undefined : memoryPolicySnapshot(selected);
365
386
  if (selected !== undefined && !selection) fail();
366
387
  if (!Array.isArray(pendingInput) || types.isProxy(pendingInput) || pendingInput.length > 20000) fail("bound");
@@ -374,16 +395,31 @@ export function captureSyncPlacementContext(home: string, port: PlacementCapture
374
395
  || typeof pathHash!=="string" || pathHash.length!==64 || !/^[a-f0-9]+$/.test(pathHash) || typeof prefixHash!=="string" || prefixHash.length!==64 || !/^[a-f0-9]+$/.test(prefixHash)) fail();
375
396
  return {realm,line,offset,pathHash,prefixHash};
376
397
  });
377
- const before = capture(home, port, selection, pending);
378
- return { ...before, assertCurrent: () => { try { if (capture(home, port, selection, pending).fingerprint !== before.fingerprint) fail(); } catch { fail(); } } };
379
- } catch (error) {
380
- if (error && typeof error === "object" && !types.isProxy(error)) {
381
- if(error instanceof SharedWriterRevisionError){const code=Object.getOwnPropertyDescriptor(error,"code")?.value;if(code==="staging"||code==="pending")throw new SharedWriterRevisionError(code);}
382
- if (error instanceof SyncPlacementJournalError) throw error;
383
- if (error instanceof SegmentReadBudgetError) throw new PlacementSourceBoundError(inspectionBoundReceipt(error));
384
- }
385
- return fail();
398
+ return { selection, pending };
399
+ }
400
+ function captureFailure(error: unknown): never {
401
+ if (error && typeof error === "object" && !types.isProxy(error)) {
402
+ if(error instanceof SharedWriterRevisionError){const code=Object.getOwnPropertyDescriptor(error,"code")?.value;if(code==="staging"||code==="pending")throw new SharedWriterRevisionError(code);}
403
+ if (error instanceof SyncPlacementJournalError) throw error;
404
+ if (error instanceof SegmentReadBudgetError) throw new PlacementSourceBoundError(inspectionBoundReceipt(error));
386
405
  }
406
+ return fail();
407
+ }
408
+ export function captureSyncPlacementContext(home: string, port: PlacementCapturePort, selected?: readonly PlacementRealm[], pendingInput: readonly PlacementPendingSource[] = []): PlacementCapture {
409
+ try {
410
+ const { selection, pending } = captureInput(selected, pendingInput), before = capture(home, port, selection, pending);
411
+ return { ...before, assertCurrent: () => { try { if (capture(home, port, selection, pending).fingerprint !== before.fingerprint) fail(); } catch { fail(); } } };
412
+ } catch (error) { return captureFailure(error); }
413
+ }
414
+ /** Transport-only cooperative capture; host callbacks and the synchronous activation API remain unchanged. */
415
+ export async function captureSyncPlacementContextAsync(home: string, port: PlacementCapturePort, selected?: readonly PlacementRealm[], pendingInput: readonly PlacementPendingSource[] = []): Promise<PlacementCapture> {
416
+ try {
417
+ const { selection, pending } = captureInput(selected, pendingInput), attestation = memoryPolicySnapshot(port.attest()) ?? fail(), policyVersion = port.policyVersion?.();
418
+ if (port.policyVersion && typeof policyVersion !== "string") fail();
419
+ const source = await sourcePreviewAsync(home, selection, pending, policyVersion);
420
+ const before = captureFromSource(port, source, attestation, policyVersion);
421
+ return { ...before, assertCurrent: () => { try { if (capture(home, port, selection, pending).fingerprint !== before.fingerprint) fail(); } catch { fail(); } } };
422
+ } catch (error) { return captureFailure(error); }
387
423
  }
388
424
 
389
425
  /** Internal initial-activation capture only. Tokens require the actual profile owner, live home mutation and exact durable intent. */
@@ -1,4 +1,10 @@
1
- import { readActivePlacementBinding } from "./sync-placement-active.ts";
1
+ import { readActivePlacementBinding, type ActivePlacementBinding } from "./sync-placement-active.ts";
2
+ import { readEffectiveRealmInventory, type EffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
3
+ import { AsyncLocalStorage } from "node:async_hooks";
4
+ import { tmpdir } from "node:os";
5
+ import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
6
+ import { canonicalJSON } from "./generation.ts";
7
+ import { realPath } from "./platform.ts";
2
8
  import { types } from "node:util";
3
9
  /** Closed activation metadata admits v3 readers; publication still requires full journal/source/policy proof. */
4
10
  import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type BigIntStats } from "node:fs";
@@ -9,6 +15,49 @@ import { PLACEMENT_PROFILE_SCHEMA, PLACEMENT_SHARDS_SCHEMA, validatePlacementPro
9
15
  import { PLACEMENT_ACTIVATION_INTENT } from "./sync-placement-activation-path.ts";
10
16
  import { profileLockRefusal, rememberProfileLockError } from "./profile-lock-diagnostic.ts";
11
17
 
18
+ // The capability can only name the fresh scratch home made below, never a caller-supplied directory.
19
+ const doctorContext = new AsyncLocalStorage<{ home: string; dev: bigint; ino: bigint; realHome: string; binding?: ActivePlacementBinding }>();
20
+ export async function withDoctorPlacementScratch<T>(realHome: string, adopt: (dir: string) => void, run: (scratch: string) => Promise<T>): Promise<T> {
21
+ const scratch = mkdtempSync(join(tmpdir(), `amem-doctor-${process.pid}-`));
22
+ try {
23
+ adopt(scratch);
24
+ const directory = join(scratch, "home"); mkdirSync(directory, { mode: 0o700 });
25
+ const home = realPath(directory);
26
+ const stat = lstatSync(home, { bigint: true });
27
+ let binding: ActivePlacementBinding | undefined;
28
+ try {
29
+ if (!placementRuntimeRefusal(realHome)) {
30
+ const markers = readPlacementRuntimeMarkers(realHome);
31
+ if (schema(markers.profile) === PLACEMENT_PROFILE_SCHEMA) binding = readActivePlacementBinding(realHome, markers.profile, markers.shards);
32
+ }
33
+ } catch { /* A changed real binding leaves scratch unadmitted; doctor reports its real-home refusal. */ }
34
+ return await doctorContext.run({ home, dev: stat.dev, ino: stat.ino, realHome, binding }, () => run(scratch));
35
+ } finally { rmSync(scratch, { recursive: true, force: true }); }
36
+ }
37
+ /** A scratch binding is valid only while the original v3 home and both copied markers still match. */
38
+ export function doctorScratchBinding(home: string): ActivePlacementBinding | undefined {
39
+ const context = doctorContext.getStore();
40
+ if (!context?.binding) return undefined;
41
+ try {
42
+ if (realPath(home) !== context.home) return undefined;
43
+ const stat = lstatSync(home, { bigint: true });
44
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.dev !== context.dev || stat.ino !== context.ino) return undefined;
45
+ const real = readPlacementRuntimeMarkers(context.realHome), copy = readPlacementRuntimeMarkers(home);
46
+ if (placementRuntimeRefusal(context.realHome) || canonicalJSON(real) !== canonicalJSON(copy)) return undefined;
47
+ return readActivePlacementBinding(context.realHome, real.profile, real.shards);
48
+ } catch { return undefined; }
49
+ }
50
+
51
+ /** Only the private doctor scratch capability can borrow the real home's freshly verified inventory. */
52
+ export function doctorScratchInventory(home: string): EffectiveRealmInventory | undefined {
53
+ const binding = doctorScratchBinding(home), context = doctorContext.getStore();
54
+ if (!binding || !context) return undefined;
55
+ const inventory = readEffectiveRealmInventory(context.realHome, binding);
56
+ if (!doctorScratchBinding(home)) return undefined;
57
+ inventory.assertCurrent();
58
+ return inventory;
59
+ }
60
+
12
61
  export const PLACEMENT_STAGE1_REFUSAL = "sync placement v3 requires matching durable activation metadata; keep the current compatible profile active until person-authorized activation is complete";
13
62
  export const PLACEMENT_MARKER_REFUSAL = "sync placement metadata is invalid or unsupported; person inspection and a compatible reader are required before continuing";
14
63
  export const PLACEMENT_ACTIVATION_PENDING = "sync placement activation is pending or incomplete; have the person inspect retained evidence and run amem migrate --sync-placement --resume, or --abandon only while both markers retain their original v2 bytes";
@@ -66,6 +115,7 @@ export function placementMarkerRefusal(profile: unknown, shards: unknown): strin
66
115
  /** Selector preflight only recognizes v3. Legacy malformed/split metadata must retain its existing reader/recovery path. */
67
116
  // This narrow probe is not a data/transport gate; effects must still use the full runtime guard.
68
117
  export function placementSelectorRefusal(home: string): string | undefined {
118
+ if (doctorScratchBinding(home)) return undefined;
69
119
  const refusal=selectorRefusal(home);return refusal?profileLockRefusal(home)??refusal:undefined;
70
120
  }
71
121
  function selectorRefusal(home:string):string|undefined {
@@ -92,6 +142,7 @@ function placementFencePresent(home: string): boolean {
92
142
  /** Bounded activation/view metadata only; no data/index open, cache mutation, lock or child/network call.
93
143
  * The v3 publication coordinator separately proves the complete journal, selected sources and policy. */
94
144
  export function placementRuntimeRefusal(home: string, bound?: Pick<BoundProfile,"kind"|"sharded"|"generation"|"publicationFormat"|"placementHead">): string | undefined {
145
+ if (doctorScratchBinding(home)) return undefined;
95
146
  try { const fenced = placementFencePresent(home), pending = placementActivationPending(home), markers = readPlacementRuntimeMarkers(home);
96
147
  const refusal = placementMarkerRefusal(markers.profile, markers.shards);
97
148
  if (refusal === PLACEMENT_STAGE1_REFUSAL) {