@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.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +17 -11
- package/package.json +3 -2
- package/src/brief-work.ts +142 -0
- package/src/cli.ts +97 -17
- package/src/commands-table.ts +6 -0
- package/src/mcp-memory.ts +37 -9
- package/src/memory/bridge.ts +26 -1
- package/src/memory/capacity.ts +5 -2
- package/src/memory/catalog.ts +10 -1
- package/src/memory/commands.ts +5 -3
- package/src/memory/curated-cache-state.ts +10 -7
- package/src/memory/doctor.ts +32 -26
- package/src/memory/formats.ts +4 -3
- package/src/memory/generation-index.ts +79 -17
- package/src/memory/index-file.ts +2 -2
- package/src/memory/intent-brief.ts +34 -6
- package/src/memory/metrics.ts +174 -14
- package/src/memory/shard-bridge.ts +18 -6
- package/src/memory/shard-sync-format.ts +18 -0
- package/src/memory/shard-sync-history.ts +6 -0
- package/src/memory/shard-sync.ts +52 -4
- package/src/memory/shard.ts +33 -13
- package/src/memory/store.ts +147 -41
- package/src/memory/sync-placement-bound.ts +21 -4
- package/src/memory/sync-placement-cache.ts +16 -1
- package/src/memory/sync-placement-capture.ts +67 -19
- package/src/memory/sync-placement-checkpoint-format.ts +199 -0
- package/src/memory/sync-placement-checkpoint-person.ts +209 -0
- package/src/memory/sync-placement-checkpoint-prospective.ts +141 -0
- package/src/memory/sync-placement-checkpoint-storage.ts +218 -0
- package/src/memory/sync-placement-checkpoint.ts +234 -0
- package/src/memory/sync-placement-dependencies.ts +42 -9
- package/src/memory/sync-placement-effective-writers.ts +12 -6
- package/src/memory/sync-placement-git.ts +17 -7
- package/src/memory/sync-placement-guard.ts +52 -1
- package/src/memory/sync-placement-inspection-evidence.ts +1 -1
- package/src/memory/sync-placement-inventory.ts +141 -0
- package/src/memory/sync-placement-journal-format.ts +4 -1
- package/src/memory/sync-placement-journal-storage.ts +148 -28
- package/src/memory/sync-placement-journal.ts +13 -4
- package/src/memory/sync-placement-materialize.ts +47 -22
- package/src/memory/sync-placement-projection.ts +7 -1
- package/src/memory/sync-placement-publication-events.ts +42 -0
- package/src/memory/sync-placement-publication-plan.ts +26 -5
- package/src/memory/sync-placement-realm-admission-storage.ts +128 -0
- package/src/memory/sync-placement-realm-admission.ts +352 -0
- package/src/memory/sync-placement-realm-attribution.ts +23 -0
- package/src/memory/sync-placement-realm-discovery.ts +42 -0
- package/src/memory/sync-placement-realm-effective.ts +71 -0
- package/src/memory/sync-placement-realm-extension-format.ts +66 -0
- package/src/memory/sync-placement-realm-extension-storage.ts +82 -0
- package/src/memory/sync-placement-realm-intent-format.ts +55 -0
- package/src/memory/sync-placement-realm-intent-storage.ts +123 -0
- package/src/memory/sync-placement-realm-pending.ts +27 -0
- package/src/memory/sync-placement-realm-proof.ts +131 -0
- package/src/memory/sync-placement-realm-torn.ts +26 -0
- package/src/memory/sync-placement-remote-admission.ts +190 -0
- package/src/memory/sync-placement-remote-adoption-format.ts +54 -0
- package/src/memory/sync-placement-remote-materialization.ts +49 -0
- package/src/memory/sync-placement-remote-refusal.ts +21 -0
- package/src/memory/sync-placement-remote-stage.ts +275 -0
- package/src/memory/sync-placement-transport.ts +268 -79
- package/src/memory/sync-placement-writer-history.ts +75 -17
- package/src/memory/sync-placement-writer-renewal.ts +18 -10
- package/src/memory/sync-placement-writer-revision-format.ts +16 -13
- package/src/memory/sync-placement-yield.ts +44 -0
- package/src/memory/sync-progress.ts +47 -6
- package/src/memory/sync.ts +26 -1
- package/src/memory/work-lists.ts +129 -9
- package/src/session-brief.ts +34 -1
- package/src/sync-placement-writer-context.ts +5 -5
- package/src/ui/plugin.ts +1 -1
package/src/memory/store.ts
CHANGED
|
@@ -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
|
-
|
|
309
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
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
|
|
647
|
-
|
|
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
|
-
|
|
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
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
const
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
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
|
-
|
|
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,
|
|
1918
|
+
sourceHash: hashJSON([tables.generation_rows, tables.generation_prunes, tables.generation_segments, state]) };
|
|
1813
1919
|
} finally {store.close();}
|
|
1814
1920
|
}
|
|
1815
1921
|
|
|
@@ -16,14 +16,31 @@ export interface PlacementSyncBound { phase: PlacementSyncBoundPhase; kind: Plac
|
|
|
16
16
|
|
|
17
17
|
const phases: Record<PlacementSyncBoundPhase, string> = { "source-capture": "source capture", materialization: "materialization", "publication-plan": "publication planning" };
|
|
18
18
|
export function placementSyncBoundMessage(bound: PlacementSyncBound): string {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
19
|
+
// #288 step 3: a full live window is relieved by a person-reviewed checkpoint; records stay a reported bound.
|
|
20
|
+
const remedy = bound.kind === "journal-objects"
|
|
21
|
+
? "The active epoch journal cannot hold this publication; have the person preview a checkpoint with amem migrate --sync-placement --checkpoint --writer-root <install root> (repeat for every install), then confirm it and rerun amem sync."
|
|
22
|
+
: bound.kind === "journal-records"
|
|
23
|
+
? "The active epoch journal cannot hold this publication; retain the inputs and report this bound."
|
|
24
|
+
: "Retain the inputs and report this bound; no row was omitted to fit.";
|
|
22
25
|
return `Placement sync refused before any publication attempt: ${phases[bound.phase]} exceeds its supported ${bound.kind} bound (observed ${bound.observed}, limit ${bound.limit}). No source, selector, epoch, journal or remote ref was changed. ${remedy}`;
|
|
23
26
|
}
|
|
24
27
|
/** Expected input refusal before a publication attempt exists. Code stays "bound" for existing callers. */
|
|
25
28
|
export class PlacementSyncBoundError extends SyncPlacementJournalError {
|
|
26
|
-
|
|
29
|
+
/** `detail` is an optional numbers-only clause about the same measurement; the receipt never carries it. */
|
|
30
|
+
constructor(readonly bound: PlacementSyncBound, readonly detail?: string) {
|
|
31
|
+
super("bound"); this.message = placementSyncBoundMessage(bound) + (detail ? ` ${detail}` : ""); this.name = "PlacementSyncBoundError";
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* #288 step 1: the thrown error's own clause, so a caller that rebuilds the message from the receipt still reports it.
|
|
36
|
+
* Only this class' allowlisted `detail` is read; the receipt stays four fields and no raw caught text is exposed.
|
|
37
|
+
*/
|
|
38
|
+
export function placementSyncBoundDetail(error: unknown): string | undefined {
|
|
39
|
+
try {
|
|
40
|
+
if (!error || typeof error !== "object" || types.isProxy(error) || !(error instanceof PlacementSyncBoundError)) return undefined;
|
|
41
|
+
const detail = Object.getOwnPropertyDescriptor(error, "detail")?.value;
|
|
42
|
+
return typeof detail === "string" && detail.length > 0 && detail.length <= 512 ? detail : undefined;
|
|
43
|
+
} catch { return undefined; }
|
|
27
44
|
}
|
|
28
45
|
/** Only allowlisted own data properties of a journal bound error become a receipt; any other exception yields none. */
|
|
29
46
|
export function placementSyncBoundReceipt(error: unknown): PlacementSyncBound | undefined {
|
|
@@ -1,10 +1,25 @@
|
|
|
1
1
|
/** Shared private cache metadata validation. These checks never initialize, repair or publish a repository. */
|
|
2
|
-
import { lstatSync } from "node:fs";
|
|
2
|
+
import { lstatSync, readdirSync } from "node:fs";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { canonicalJSON } from "./generation.ts";
|
|
5
5
|
import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
|
|
6
6
|
|
|
7
7
|
function fail(): never { throw new SyncPlacementJournalError("corrupt"); }
|
|
8
|
+
/** The placement transport never follows cache links or accepts foreign-owned or promisor objects. */
|
|
9
|
+
export function placementCacheTreePrivate(cache: string): boolean {
|
|
10
|
+
try {
|
|
11
|
+
const walk = (dir: string): void => {
|
|
12
|
+
const parent = lstatSync(dir);
|
|
13
|
+
if (!parent.isDirectory() || parent.isSymbolicLink() || parent.uid !== process.getuid?.() || (parent.mode & 0o077) !== 0) fail();
|
|
14
|
+
for (const name of readdirSync(dir)) {
|
|
15
|
+
const file = join(dir, name), stat = lstatSync(file);
|
|
16
|
+
if (stat.isSymbolicLink() || stat.uid !== process.getuid?.() || !stat.isFile() && !stat.isDirectory() || stat.isFile() && stat.nlink !== 1 || name.endsWith(".promisor")) fail();
|
|
17
|
+
if (stat.isDirectory()) walk(file);
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
walk(cache); return true;
|
|
21
|
+
} catch { return false; }
|
|
22
|
+
}
|
|
8
23
|
export function placementCacheRootStamp(home: string): string {
|
|
9
24
|
const stat = lstatSync(join(home, "shard-sync-placement"), { bigint: true });
|
|
10
25
|
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== BigInt(process.getuid?.() ?? -1) || (stat.mode & 0o077n) !== 0n) fail();
|
|
@@ -12,7 +12,7 @@ import { realPath, DENY_NAMES, DENY_SEGMENTS } from "./platform.ts";
|
|
|
12
12
|
import { loadAmemConfig } from "./config.ts";
|
|
13
13
|
import { memoryPolicySnapshot } from "./policy.ts";
|
|
14
14
|
import { SegmentReader, SegmentReadBudgetError, checkedEntry, completeLines } from "./bridge.ts";
|
|
15
|
-
import {
|
|
15
|
+
import { shardLegacySnapshotSteps } from "./shard-bridge.ts";
|
|
16
16
|
import { coalesceGenerationSource } from "./generation-index.ts";
|
|
17
17
|
import { validatePruneRow, type PruneSourceRow, type PruneRow } from "./prune.ts";
|
|
18
18
|
import { shardKeyHash, SHARD_SCHEMA } from "./shard.ts";
|
|
@@ -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
|
|
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) {
|
|
@@ -194,13 +195,16 @@ function sourcePreview(homeInput: string, selected?: readonly PlacementRealm[],
|
|
|
194
195
|
sourceChecks.push(() => { const now=lstatSync(file,{bigint:true,throwIfNoEntry:false}); if(s ? !now||!same(s,now) : now!==undefined) fail(); });
|
|
195
196
|
}
|
|
196
197
|
}
|
|
197
|
-
|
|
198
|
+
// #462: the legacy halves are read as steps, so this collector yields between their segments.
|
|
199
|
+
const segments = yield* shardLegacySnapshotSteps(profile, { reader });
|
|
198
200
|
for (const folder of ["log", "local"]) {
|
|
201
|
+
yield;
|
|
199
202
|
directoryFact(join(dir, folder));
|
|
200
203
|
const folderPath=join(dir,folder), folderStamp=lstatSync(folderPath,{bigint:true});
|
|
201
204
|
sourceChecks.push(() => { if(!same(folderStamp,lstatSync(folderPath,{bigint:true}))) fail(); });
|
|
202
205
|
if(folder === "local") bytes(join(dir,folder,`publisher-boundary-${machine.id}.json`),true);
|
|
203
206
|
for (const name of reader.listFiles(join(dir, folder))) {
|
|
207
|
+
yield;
|
|
204
208
|
if (!name.endsWith(".jsonl")) continue;
|
|
205
209
|
if ( !/^[A-Za-z0-9][A-Za-z0-9._-]*\.jsonl$/.test(name)) fail();
|
|
206
210
|
segments.push({ ...reader.read(join(dir, folder, name), undefined, true), source: "generation", path: `${folder}/${name}`, local: folder === "local" });
|
|
@@ -214,6 +218,7 @@ function sourcePreview(homeInput: string, selected?: readonly PlacementRealm[],
|
|
|
214
218
|
special.set(row.id, { key, row, sourcePlacement: local ? "local" : "synced", intrinsicLocal: row.op === "vault_link" });
|
|
215
219
|
};
|
|
216
220
|
for (const segment of segments) {
|
|
221
|
+
yield;
|
|
217
222
|
const file = join(segment.source === "generation" ? dir : segment.source === "legacy-main" ? profile.legacyMainHome! : profile.legacyHome!, segment.path);
|
|
218
223
|
const fileStat = lstatSync(file);
|
|
219
224
|
if (!fileStat.isFile() || fileStat.isSymbolicLink() || fileStat.nlink !== 1 || fileStat.uid !== process.getuid?.() || (fileStat.mode & 0o022) !== 0) fail();
|
|
@@ -243,6 +248,7 @@ function sourcePreview(homeInput: string, selected?: readonly PlacementRealm[],
|
|
|
243
248
|
dev: physical[0] as string, ino: physical[1] as string, byteLength: sourceLength, hash: sourceHash,
|
|
244
249
|
mtimeNs: physical[3] as string, ctimeNs: physical[4] as string });
|
|
245
250
|
for (const line of completeLines(segment.bytes)) {
|
|
251
|
+
yield;
|
|
246
252
|
if (!line.length) continue;
|
|
247
253
|
const parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(line));
|
|
248
254
|
if (segment.source === "generation" && parsed?.op === "prune") {
|
|
@@ -262,11 +268,13 @@ function sourcePreview(homeInput: string, selected?: readonly PlacementRealm[],
|
|
|
262
268
|
}
|
|
263
269
|
}
|
|
264
270
|
for (const source of special.values()) {
|
|
271
|
+
yield;
|
|
265
272
|
if (presence.has(source.key.id)) fail();
|
|
266
273
|
specialRows.set(placementKeyId(source.key), source);
|
|
267
274
|
}
|
|
268
275
|
sourceRowsByRealm.set(canonicalJSON(identity), [...presence.values()]);
|
|
269
276
|
for (const source of presence.values()) {
|
|
277
|
+
yield;
|
|
270
278
|
const key = { realm: identity, id: source.row.id, rowHash: hashJSON(source.row) };
|
|
271
279
|
rows.set(placementKeyId(key), { key, row: source.row, sourcePlacement: source.placement,
|
|
272
280
|
intrinsicLocal: source.row.op === "settle" || source.row.op === "note" && source.row.tier === "short" });
|
|
@@ -274,8 +282,9 @@ function sourcePreview(homeInput: string, selected?: readonly PlacementRealm[],
|
|
|
274
282
|
const bindingHash = hashJSON(facts.slice(beforeFacts));
|
|
275
283
|
realms.push({ ...identity, bindingHash });
|
|
276
284
|
};
|
|
277
|
-
if (!selection || selection.some(item => item.scope === "user")) realm(join(home, "user"), { scope: "user" });
|
|
285
|
+
if (!selection || selection.some(item => item.scope === "user")) yield* realm(join(home, "user"), { scope: "user" });
|
|
278
286
|
for (const name of listing(join(home, "projects"), true)) {
|
|
287
|
+
yield;
|
|
279
288
|
if (!/^[a-f0-9]{16}$/.test(name)) fail();
|
|
280
289
|
if (selection && !selection.some(item => item.scope === "project" && item.keyHash.slice(0,16) === name)) continue;
|
|
281
290
|
const dir = join(home, "projects", name), project = json(join(dir, "project.json"));
|
|
@@ -284,7 +293,7 @@ function sourcePreview(homeInput: string, selected?: readonly PlacementRealm[],
|
|
|
284
293
|
if (!lstatSync(join(dir, "generation.json"), { throwIfNoEntry: false })) continue;
|
|
285
294
|
const keyHash = digest(project.key);
|
|
286
295
|
if (selection && !selection.some(item => item.scope === "project" && item.keyHash === keyHash)) fail();
|
|
287
|
-
realm(dir, { scope: "project", keyHash }, project.key);
|
|
296
|
+
yield* realm(dir, { scope: "project", keyHash }, project.key);
|
|
288
297
|
}
|
|
289
298
|
if (selection && realms.length !== selection.length) fail();
|
|
290
299
|
const defaults = memoryPolicySnapshot({ names: DENY_NAMES, segments: DENY_SEGMENTS }); if (!defaults) fail();
|
|
@@ -307,6 +316,17 @@ function sourcePreview(homeInput: string, selected?: readonly PlacementRealm[],
|
|
|
307
316
|
return { home, base: contextBase, assertSourcesUnchanged, ...(activeHead ? { activeHead } : {}), markerHash, markers,
|
|
308
317
|
directories: directories.sort(), prefixes, rows, specialRows, sourceRowsByRealm };
|
|
309
318
|
}
|
|
319
|
+
/** The synchronous activation and preview APIs drain the identical source steps without scheduling changes. */
|
|
320
|
+
function sourcePreview(home: string, selected?: readonly PlacementRealm[], pending: readonly PlacementPendingSource[] = [], policyVersion?: string, ownerProof?: PlacementActivationCaptureProof, sourceOwner?: PlacementActivationOwner): PlacementSourcePreview {
|
|
321
|
+
const steps = sourcePreviewSteps(home, selected, pending, policyVersion, ownerProof, sourceOwner);
|
|
322
|
+
let next = steps.next(); while (!next.done) next = steps.next(); return next.value;
|
|
323
|
+
}
|
|
324
|
+
/** The transport releases its caller's event loop between bounded source collection steps. */
|
|
325
|
+
async function sourcePreviewAsync(home: string, selected?: readonly PlacementRealm[], pending: readonly PlacementPendingSource[] = [], policyVersion?: string): Promise<PlacementSourcePreview> {
|
|
326
|
+
const steps = sourcePreviewSteps(home, selected, pending, policyVersion), pause = cooperativeYield();
|
|
327
|
+
let next = steps.next(); while (!next.done) { await pause(); next = steps.next(); }
|
|
328
|
+
next.value.assertSourcesUnchanged(); return next.value;
|
|
329
|
+
}
|
|
310
330
|
/** The homeHash a retained epoch (or an in-flight activation) already committed to, so a reboot-renumbered device keeps binding (#444). */
|
|
311
331
|
function pinnedHomeHash(home: string, activeHead: string | undefined, activating: boolean): string | undefined {
|
|
312
332
|
try {
|
|
@@ -319,6 +339,17 @@ function pinnedHomeHash(home: string, activeHead: string | undefined, activating
|
|
|
319
339
|
export function previewSyncPlacementSources(home: string): PlacementSourcePreview {
|
|
320
340
|
return previewSources(home);
|
|
321
341
|
}
|
|
342
|
+
/** Read-only selected source facts for an offline prospective checkpoint preview; no writer authority. */
|
|
343
|
+
export function previewSelectedSyncPlacementSources(home: string, selected: readonly PlacementRealm[]): PlacementSourcePreview {
|
|
344
|
+
try { assertPlacementRuntime(home); const preview = sourcePreview(home, selected); preview.assertSourcesUnchanged(); return preview; }
|
|
345
|
+
catch (error) {
|
|
346
|
+
if (error && typeof error === "object" && !types.isProxy(error)) {
|
|
347
|
+
if (error instanceof SyncPlacementJournalError) throw error;
|
|
348
|
+
if (error instanceof SegmentReadBudgetError) throw new PlacementSourceBoundError(inspectionBoundReceipt(error));
|
|
349
|
+
}
|
|
350
|
+
return fail();
|
|
351
|
+
}
|
|
352
|
+
}
|
|
322
353
|
/** Internal renewal inventory under the exact live home/profile/mutation owner; no marker virtualization. */
|
|
323
354
|
export function previewOwnedSyncPlacementSources(home:string,owner:PlacementActivationOwner):PlacementSourcePreview {
|
|
324
355
|
assertPlacementActivationOwner(owner,home);return previewSources(home,owner);
|
|
@@ -335,9 +366,12 @@ function previewSources(home:string,owner?:PlacementActivationOwner):PlacementSo
|
|
|
335
366
|
}
|
|
336
367
|
function capture(home: string, port: PlacementCapturePort, selected?: readonly PlacementRealm[], pending: readonly PlacementPendingSource[] = [], ownerProof?: PlacementActivationCaptureProof): Omit<PlacementCapture, "assertCurrent"> {
|
|
337
368
|
// All host callouts precede filesystem capture, including the final passive proof.
|
|
338
|
-
const attestation = memoryPolicySnapshot(port.attest()), policyVersion = port.policyVersion?.();
|
|
339
|
-
if (
|
|
369
|
+
const attestation = memoryPolicySnapshot(port.attest()) ?? fail(), policyVersion = port.policyVersion?.();
|
|
370
|
+
if (port.policyVersion && typeof policyVersion !== "string") fail();
|
|
340
371
|
const source = sourcePreview(home, selected, pending, policyVersion, ownerProof);
|
|
372
|
+
return captureFromSource(port, source, attestation, policyVersion);
|
|
373
|
+
}
|
|
374
|
+
function captureFromSource(port: PlacementCapturePort, source: PlacementSourcePreview, attestation: ReturnType<PlacementCapturePort["attest"]>, policyVersion: string | undefined): Omit<PlacementCapture, "assertCurrent"> {
|
|
341
375
|
const context: SyncPlacementActivationContext = { ...source.base, writers: attestation.writers, legacySyncQuiesced: attestation.legacySyncQuiesced };
|
|
342
376
|
const validated = planSyncPlacementActivation(context, "0".repeat(64));
|
|
343
377
|
context.writers = validated.writers; context.realms = validated.realms;
|
|
@@ -359,8 +393,7 @@ function capture(home: string, port: PlacementCapturePort, selected?: readonly P
|
|
|
359
393
|
prefixes: source.prefixes, rows: source.rows, specialRows: source.specialRows, sourceRowsByRealm: source.sourceRowsByRealm };
|
|
360
394
|
}
|
|
361
395
|
|
|
362
|
-
|
|
363
|
-
try {
|
|
396
|
+
function captureInput(selected: readonly PlacementRealm[] | undefined, pendingInput: readonly PlacementPendingSource[]) {
|
|
364
397
|
const selection = selected === undefined ? undefined : memoryPolicySnapshot(selected);
|
|
365
398
|
if (selected !== undefined && !selection) fail();
|
|
366
399
|
if (!Array.isArray(pendingInput) || types.isProxy(pendingInput) || pendingInput.length > 20000) fail("bound");
|
|
@@ -374,16 +407,31 @@ export function captureSyncPlacementContext(home: string, port: PlacementCapture
|
|
|
374
407
|
|| typeof pathHash!=="string" || pathHash.length!==64 || !/^[a-f0-9]+$/.test(pathHash) || typeof prefixHash!=="string" || prefixHash.length!==64 || !/^[a-f0-9]+$/.test(prefixHash)) fail();
|
|
375
408
|
return {realm,line,offset,pathHash,prefixHash};
|
|
376
409
|
});
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
}
|
|
385
|
-
return fail();
|
|
410
|
+
return { selection, pending };
|
|
411
|
+
}
|
|
412
|
+
function captureFailure(error: unknown): never {
|
|
413
|
+
if (error && typeof error === "object" && !types.isProxy(error)) {
|
|
414
|
+
if(error instanceof SharedWriterRevisionError){const code=Object.getOwnPropertyDescriptor(error,"code")?.value;if(code==="staging"||code==="pending")throw new SharedWriterRevisionError(code);}
|
|
415
|
+
if (error instanceof SyncPlacementJournalError) throw error;
|
|
416
|
+
if (error instanceof SegmentReadBudgetError) throw new PlacementSourceBoundError(inspectionBoundReceipt(error));
|
|
386
417
|
}
|
|
418
|
+
return fail();
|
|
419
|
+
}
|
|
420
|
+
export function captureSyncPlacementContext(home: string, port: PlacementCapturePort, selected?: readonly PlacementRealm[], pendingInput: readonly PlacementPendingSource[] = []): PlacementCapture {
|
|
421
|
+
try {
|
|
422
|
+
const { selection, pending } = captureInput(selected, pendingInput), before = capture(home, port, selection, pending);
|
|
423
|
+
return { ...before, assertCurrent: () => { try { if (capture(home, port, selection, pending).fingerprint !== before.fingerprint) fail(); } catch { fail(); } } };
|
|
424
|
+
} catch (error) { return captureFailure(error); }
|
|
425
|
+
}
|
|
426
|
+
/** Transport-only cooperative capture; host callbacks and the synchronous activation API remain unchanged. */
|
|
427
|
+
export async function captureSyncPlacementContextAsync(home: string, port: PlacementCapturePort, selected?: readonly PlacementRealm[], pendingInput: readonly PlacementPendingSource[] = []): Promise<PlacementCapture> {
|
|
428
|
+
try {
|
|
429
|
+
const { selection, pending } = captureInput(selected, pendingInput), attestation = memoryPolicySnapshot(port.attest()) ?? fail(), policyVersion = port.policyVersion?.();
|
|
430
|
+
if (port.policyVersion && typeof policyVersion !== "string") fail();
|
|
431
|
+
const source = await sourcePreviewAsync(home, selection, pending, policyVersion);
|
|
432
|
+
const before = captureFromSource(port, source, attestation, policyVersion);
|
|
433
|
+
return { ...before, assertCurrent: () => { try { if (capture(home, port, selection, pending).fingerprint !== before.fingerprint) fail(); } catch { fail(); } } };
|
|
434
|
+
} catch (error) { return captureFailure(error); }
|
|
387
435
|
}
|
|
388
436
|
|
|
389
437
|
/** Internal initial-activation capture only. Tokens require the actual profile owner, live home mutation and exact durable intent. */
|