@staix/agent-mem 0.38.0 → 0.40.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 (57) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +1 -1
  3. package/package.json +1 -1
  4. package/src/brief-curated.ts +8 -4
  5. package/src/cli-agent-reads.ts +2 -1
  6. package/src/cli.ts +82 -32
  7. package/src/commands-table.ts +6 -3
  8. package/src/hooks.ts +4 -0
  9. package/src/index.ts +5 -0
  10. package/src/memory/capacity-text.ts +100 -0
  11. package/src/memory/capacity.ts +0 -92
  12. package/src/memory/commands.ts +6 -1
  13. package/src/memory/curated-cache-state.ts +22 -3
  14. package/src/memory/doctor-text.ts +148 -0
  15. package/src/memory/doctor.ts +19 -141
  16. package/src/memory/eval-audit-text.ts +62 -0
  17. package/src/memory/eval-audit.ts +0 -57
  18. package/src/memory/eval-text.ts +32 -0
  19. package/src/memory/eval.ts +0 -28
  20. package/src/memory/formats.ts +2 -0
  21. package/src/memory/gc-text.ts +22 -0
  22. package/src/memory/gc.ts +0 -19
  23. package/src/memory/generation-index.ts +1 -1
  24. package/src/memory/index-file.ts +1 -1
  25. package/src/memory/metrics.ts +18 -10
  26. package/src/memory/migrate-text.ts +32 -0
  27. package/src/memory/migrate.ts +0 -29
  28. package/src/memory/project-export.ts +9 -4
  29. package/src/memory/prune-text.ts +29 -0
  30. package/src/memory/prune.ts +0 -26
  31. package/src/memory/report-text.ts +2 -0
  32. package/src/memory/roots.ts +145 -0
  33. package/src/memory/shard-migration-text.ts +40 -0
  34. package/src/memory/shard-migration.ts +0 -37
  35. package/src/memory/status-text.ts +5 -1
  36. package/src/memory/store.ts +112 -17
  37. package/src/memory/sync-placement-activation-locks.ts +7 -5
  38. package/src/memory/sync-placement-advertisement.ts +18 -0
  39. package/src/memory/sync-placement-bound.ts +2 -2
  40. package/src/memory/sync-placement-checkpoint-person.ts +2 -2
  41. package/src/memory/sync-placement-inventory.ts +4 -1
  42. package/src/memory/sync-placement-noop-cache.ts +93 -0
  43. package/src/memory/sync-placement-refusal-category.ts +18 -0
  44. package/src/memory/sync-placement-transport.ts +80 -13
  45. package/src/memory/sync-placement-writer-renewal.ts +3 -1
  46. package/src/memory/sync-progress-text.ts +7 -0
  47. package/src/memory/sync-progress.ts +21 -7
  48. package/src/memory/sync-screen.ts +13 -0
  49. package/src/memory/work-lists.ts +6 -4
  50. package/src/session-brief.ts +16 -2
  51. package/src/setup-drift.ts +1 -1
  52. package/src/setup-writer-roots.ts +136 -0
  53. package/src/setup.ts +8 -118
  54. package/src/sync-placement-writer-context.ts +9 -4
  55. package/src/ui/inbox.ts +1 -1
  56. package/src/ui/plugin.ts +4 -2
  57. package/src/work-brief-preparation.ts +28 -0
@@ -0,0 +1,145 @@
1
+ import { createHash } from "node:crypto";
2
+ import { appendFileSync, closeSync, fstatSync, lstatSync, openSync, readFileSync, readSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { Database } from "bun:sqlite";
5
+ import { effectiveAliases } from "./aliases.ts";
6
+ import { indexFileName } from "./index-file.ts";
7
+ import { realPath } from "./platform.ts";
8
+ import { memoryProjectKey } from "./project.ts";
9
+
10
+ /**
11
+ * #581: which project key each working directory resolved to last, on this machine. `roots.jsonl` in the memory home
12
+ * holds only `sha256(realPath(dir))`, never path text, and is never synced or exported. Append-only; the latest line
13
+ * per root wins. The only writer is the native SessionStart path (first sight, and a re-bind after an alias settled a
14
+ * transition); `amem project keep-separate --confirm` appends a `keep`. Status, doctor and MCP only read it.
15
+ */
16
+ export const ROOTS_SCHEMA = "agent-mem.roots/v1";
17
+ export const ROOTS_FILE = "roots.jsonl";
18
+ const READ_BOUND = 256 * 1024;
19
+
20
+ export interface RootLine { schema: typeof ROOTS_SCHEMA; op: "bind" | "keep"; root: string; key: string; prev?: string; at: string; machine?: string }
21
+ export interface ProjectTransition { state: "project_transition"; previousKey: string; key: string; previousCuratedNotes: number | null; aliasCommand: string; keepCommand: string }
22
+
23
+ /** The key every #581 reader and writer compares: the hook's own resolution, isolated from an inherited GIT_* environment. Raw, before alias resolution. */
24
+ export function transitionKey(cwd: string): string {
25
+ return memoryProjectKey(cwd, { repositoryIsolation: true });
26
+ }
27
+
28
+ export const rootsLogPath = (home: string): string => join(home, ROOTS_FILE);
29
+
30
+ /**
31
+ * The working root a directory belongs to: the nearest ancestor holding `.git` (a directory or a worktree's file),
32
+ * found by `lstat` alone so the hook spawns no git process; without one, the directory itself.
33
+ * ponytail: a submodule or nested repository is its own root, the same boundary `git rev-parse --show-toplevel` draws;
34
+ * a repository more than 32 levels up is not found and the directory stands for itself.
35
+ */
36
+ export function workingRoot(dir: string): string {
37
+ const start = realPath(dir);
38
+ for (let current = start, depth = 0; depth < 32; current = dirname(current), depth++) {
39
+ if (lstatSync(join(current, ".git"), { throwIfNoEntry: false })) return current;
40
+ if (dirname(current) === current) break;
41
+ }
42
+ return start;
43
+ }
44
+
45
+ /** sha256 hex of the working root's real path; the path text itself is never stored. */
46
+ export function rootHash(dir: string): string {
47
+ return createHash("sha256").update(workingRoot(dir)).digest("hex");
48
+ }
49
+
50
+ /** Latest line per root, from at most the last 256 KB. Missing, unreadable or malformed input yields fewer lines, never a throw. */
51
+ export function readRootBindings(home: string, maxBytes = READ_BOUND): Map<string, RootLine> {
52
+ const latest = new Map<string, RootLine>();
53
+ let text = "";
54
+ try {
55
+ const fd = openSync(rootsLogPath(home), "r");
56
+ try {
57
+ const size = fstatSync(fd).size, start = Math.max(0, size - maxBytes), buffer = Buffer.alloc(size - start);
58
+ readSync(fd, buffer, 0, buffer.length, start);
59
+ text = buffer.toString("utf8");
60
+ if (start > 0) text = text.slice(text.indexOf("\n") + 1); // drop the cut first line
61
+ } finally { closeSync(fd); }
62
+ } catch { return latest; }
63
+ for (const raw of text.split("\n")) {
64
+ if (!raw) continue;
65
+ try {
66
+ const line = JSON.parse(raw) as RootLine;
67
+ if (line?.schema !== ROOTS_SCHEMA || (line.op !== "bind" && line.op !== "keep") || typeof line.root !== "string" || !/^[0-9a-f]{64}$/.test(line.root) || typeof line.key !== "string" || !line.key) continue;
68
+ latest.set(line.root, line);
69
+ } catch { /* a malformed line is skipped */ }
70
+ }
71
+ return latest;
72
+ }
73
+
74
+ const shellWord = (word: string) => /^[A-Za-z0-9@%+=:,./_-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`;
75
+ export const aliasCommandFor = (previousKey: string, key: string) => `amem alias add ${shellWord(previousKey)} ${shellWord(key)}`;
76
+ export const KEEP_COMMAND = "amem project keep-separate";
77
+
78
+ /** Two keys one alias hop apart (either direction, or both onto one canonical key) are already joined. */
79
+ function joined(aliases: Map<string, string>, a: string, b: string): boolean {
80
+ return (aliases.get(a) ?? a) === (aliases.get(b) ?? b);
81
+ }
82
+
83
+ /** The transition for this root, if its recorded key differs from `key` and nothing joins or keeps them apart. Never throws. */
84
+ export function projectTransition(home: string, dir: string, key: string, countCurated?: (key: string) => number | null): ProjectTransition | undefined {
85
+ try {
86
+ const line = readRootBindings(home).get(rootHash(dir));
87
+ if (!line || line.key === key) return undefined;
88
+ if (joined(effectiveAliases(home), line.key, key)) return undefined;
89
+ let previousCuratedNotes: number | null = null;
90
+ try { previousCuratedNotes = countCurated ? countCurated(line.key) : null; } catch { previousCuratedNotes = null; }
91
+ return { state: "project_transition", previousKey: line.key, key, previousCuratedNotes, aliasCommand: aliasCommandFor(line.key, key), keepCommand: KEEP_COMMAND };
92
+ } catch { return undefined; }
93
+ }
94
+
95
+ export function transitionNotice(t: ProjectTransition): string {
96
+ const count = t.previousCuratedNotes === null ? "" : ` (${t.previousCuratedNotes} curated notes)`;
97
+ return `amem: project key changed for this directory: was ${t.previousKey}${count}, now ${t.key}. Join: ${t.aliasCommand} Keep apart: ${t.keepCommand}`;
98
+ }
99
+
100
+ /** Curated notes a key holds, from its derived index read-only (busy 0); null when the index is absent, locked or unreadable. A bounded local read. */
101
+ export function curatedCount(home: string, key: string, shardDir: (home: string, key: string) => string): number | null {
102
+ // A curated shard's own index first, then a shared-v1 home's single index (which holds every project's rows).
103
+ for (const file of [indexFileName(false), indexFileName(true)].flatMap(name => [join(shardDir(home, key), name), join(home, name)])) {
104
+ let db: Database | undefined;
105
+ try {
106
+ if (!lstatSync(file, { throwIfNoEntry: false })) continue;
107
+ db = new Database(file, { readonly: true });
108
+ db.run("PRAGMA busy_timeout = 0");
109
+ return (db.query("SELECT COUNT(*) AS n FROM entries WHERE scope = 'project' AND project = ?").get(key) as { n: number }).n;
110
+ } catch { return null; } finally { db?.close(); }
111
+ }
112
+ return null;
113
+ }
114
+
115
+ function machineOf(home: string): string | undefined {
116
+ try { const id = JSON.parse(readFileSync(join(home, "machine.json"), "utf8")).id; return typeof id === "string" ? id : undefined; } catch { return undefined; }
117
+ }
118
+
119
+ function append(home: string, line: RootLine): void {
120
+ appendFileSync(rootsLogPath(home), JSON.stringify(line) + "\n", { mode: 0o600 });
121
+ }
122
+
123
+ /**
124
+ * The SessionStart writer. Appends a `bind` on first sight of a root, and a re-bind when the recorded key is already
125
+ * alias-joined to the resolved one (so a later change names the middle key). A differing, unjoined key is left alone
126
+ * so the notice persists until a person settles it. Fail-open: a write or read error yields no line and no throw.
127
+ */
128
+ export function observeRoot(home: string, dir: string, key: string, now: () => number = Date.now): "appended" | "unchanged" | "transition" | "failed" {
129
+ try {
130
+ const root = rootHash(dir), line = readRootBindings(home).get(root);
131
+ if (line?.key === key) return "unchanged";
132
+ if (line && !joined(effectiveAliases(home), line.key, key)) return "transition";
133
+ const machine = machineOf(home);
134
+ append(home, { schema: ROOTS_SCHEMA, op: "bind", root, key, at: new Date(now()).toISOString(), ...(machine ? { machine } : {}) });
135
+ return "appended";
136
+ } catch { return "failed"; }
137
+ }
138
+
139
+ /** `amem project keep-separate --confirm`: record the resolved key for this root on purpose, ending the transition without joining. */
140
+ export function recordKeepSeparate(home: string, dir: string, transition: ProjectTransition, now: () => number = Date.now): RootLine {
141
+ const machine = machineOf(home);
142
+ const line: RootLine = { schema: ROOTS_SCHEMA, op: "keep", root: rootHash(dir), key: transition.key, prev: transition.previousKey, at: new Date(now()).toISOString(), ...(machine ? { machine } : {}) };
143
+ append(home, line);
144
+ return line;
145
+ }
@@ -0,0 +1,40 @@
1
+ import { label, PLAIN, singleLine, type Style } from "./style.ts";
2
+ import type { ShardMigrationResult } from "./shard-migration.ts";
3
+
4
+ /** #592: the human shard-migration report, kept out of shard-migration.ts so the write path never imports the output package. */
5
+ /** Render a shard migration result for a person; JSON output remains owned by the CLI. */
6
+ export function shardMigrationText(result: ShardMigrationResult, s: Style = PLAIN): string {
7
+ const counts = result.counts;
8
+ const groupRows = (name: string, value: Record<string, number>) => Object.entries(value).sort(([a], [b]) => a.localeCompare(b))
9
+ .map(([key, count]) => `${label(s, "ok")} ${name} ${singleLine(key)} ${count}`);
10
+ const countRows = [
11
+ ["rows", counts.rows], ["skipped", counts.skippedRows], ["userRows", counts.userRows], ["tailBytes", counts.tailBytes],
12
+ ["legacyRows", counts.legacyRows], ["generationRows", counts.generationRows], ["generationLocalRows", counts.generationLocalRows],
13
+ ["legacyLocalRows", counts.legacyLocalRows], ["legacyMainRows", counts.legacyMainRows], ["pruneRows", counts.pruneRows],
14
+ ["translatedPruneRows", counts.translatedPruneRows], ["refusedRows", counts.refusedRows],
15
+ ["sharedSupersededByPrivate", counts.sharedSupersededByPrivate], ["crossPrivateReplacement", counts.crossPrivateReplacement],
16
+ ["danglingRows", counts.danglingRows],
17
+ ].map(([key, value]) => {
18
+ const flagged = key === "refusedRows" && counts.refusedRows > 0 || key === "sharedSupersededByPrivate" && counts.sharedSupersededByPrivate > 0
19
+ || key === "crossPrivateReplacement" && counts.crossPrivateReplacement > 0 || key === "danglingRows" && counts.danglingRows > 0;
20
+ return `${label(s, flagged ? "attention" : "ok")} ${key} ${value}`;
21
+ });
22
+ const warnings = result.refusals ?? [];
23
+ const attention = warnings.length > 0 || counts.refusedRows > 0 || counts.danglingRows > 0 || (!result.active && result.mode === "resume");
24
+ const state = attention ? "attention" : result.mode === "dry-run" ? "preview" : result.active ? "complete" : "attention";
25
+ const action = warnings.length || counts.refusedRows > 0 || counts.danglingRows > 0 ? "resolve the listed refusals or flagged rows before retrying"
26
+ : result.mode === "dry-run" && (!result.active || counts.rows > 0) ? "apply shard migration: amem migrate --shards --apply"
27
+ : result.mode === "resume" && !result.active ? "resume shard migration: amem migrate --shards --resume"
28
+ : "none";
29
+ return [
30
+ `${s.bold("amem migrate --shards:")} ${state}${result.alreadyActive ? " (already active)" : ""}`,
31
+ `${label(s, "ok")} generation ${result.generation.slice(0, 8)}`,
32
+ ...countRows,
33
+ ...groupRows("shard rows", counts.byShard),
34
+ ...groupRows("project rows", counts.byProject),
35
+ ...(result.deadLeasesRemoved?.length ? [`${label(s, "ok")} dead reader leases removed ${result.deadLeasesRemoved.length}`] : []),
36
+ ...(warnings.length ? ["Refusals:", ...warnings.map(reason => ` ${label(s, "attention")} ${singleLine(reason)}`)] : []),
37
+ `${label(s, "ok")} effect ${singleLine(result.consequence)}`,
38
+ `Next action: ${action}`,
39
+ ].join("\n");
40
+ }
@@ -15,7 +15,6 @@ import { assertCuratedShardPaths, ensureShardDescriptor, shardDir, SHARDED_SCHEM
15
15
  import { buildGenerationIndex, type Entry } from "./store.ts";
16
16
  import { invalidateCuratedCaches } from "./curated-cache-state.ts";
17
17
  import { readMigrationSources, type SourcePrefix } from "./migrate.ts";
18
- import { label, PLAIN, singleLine, type Style } from "./style.ts";
19
18
 
20
19
  const USER = Symbol("shared-user-shard");
21
20
  type Destination = string | typeof USER;
@@ -579,39 +578,3 @@ export async function migrateShards(options: ShardMigrationOptions): Promise<Sha
579
578
  return result;
580
579
  }
581
580
 
582
- /** Render a shard migration result for a person; JSON output remains owned by the CLI. */
583
- export function shardMigrationText(result: ShardMigrationResult, s: Style = PLAIN): string {
584
- const counts = result.counts;
585
- const groupRows = (name: string, value: Record<string, number>) => Object.entries(value).sort(([a], [b]) => a.localeCompare(b))
586
- .map(([key, count]) => `${label(s, "ok")} ${name} ${singleLine(key)} ${count}`);
587
- const countRows = [
588
- ["rows", counts.rows], ["skipped", counts.skippedRows], ["userRows", counts.userRows], ["tailBytes", counts.tailBytes],
589
- ["legacyRows", counts.legacyRows], ["generationRows", counts.generationRows], ["generationLocalRows", counts.generationLocalRows],
590
- ["legacyLocalRows", counts.legacyLocalRows], ["legacyMainRows", counts.legacyMainRows], ["pruneRows", counts.pruneRows],
591
- ["translatedPruneRows", counts.translatedPruneRows], ["refusedRows", counts.refusedRows],
592
- ["sharedSupersededByPrivate", counts.sharedSupersededByPrivate], ["crossPrivateReplacement", counts.crossPrivateReplacement],
593
- ["danglingRows", counts.danglingRows],
594
- ].map(([key, value]) => {
595
- const flagged = key === "refusedRows" && counts.refusedRows > 0 || key === "sharedSupersededByPrivate" && counts.sharedSupersededByPrivate > 0
596
- || key === "crossPrivateReplacement" && counts.crossPrivateReplacement > 0 || key === "danglingRows" && counts.danglingRows > 0;
597
- return `${label(s, flagged ? "attention" : "ok")} ${key} ${value}`;
598
- });
599
- const warnings = result.refusals ?? [];
600
- const attention = warnings.length > 0 || counts.refusedRows > 0 || counts.danglingRows > 0 || (!result.active && result.mode === "resume");
601
- const state = attention ? "attention" : result.mode === "dry-run" ? "preview" : result.active ? "complete" : "attention";
602
- const action = warnings.length || counts.refusedRows > 0 || counts.danglingRows > 0 ? "resolve the listed refusals or flagged rows before retrying"
603
- : result.mode === "dry-run" && (!result.active || counts.rows > 0) ? "apply shard migration: amem migrate --shards --apply"
604
- : result.mode === "resume" && !result.active ? "resume shard migration: amem migrate --shards --resume"
605
- : "none";
606
- return [
607
- `${s.bold("amem migrate --shards:")} ${state}${result.alreadyActive ? " (already active)" : ""}`,
608
- `${label(s, "ok")} generation ${result.generation.slice(0, 8)}`,
609
- ...countRows,
610
- ...groupRows("shard rows", counts.byShard),
611
- ...groupRows("project rows", counts.byProject),
612
- ...(result.deadLeasesRemoved?.length ? [`${label(s, "ok")} dead reader leases removed ${result.deadLeasesRemoved.length}`] : []),
613
- ...(warnings.length ? ["Refusals:", ...warnings.map(reason => ` ${label(s, "attention")} ${singleLine(reason)}`)] : []),
614
- `${label(s, "ok")} effect ${singleLine(result.consequence)}`,
615
- `Next action: ${action}`,
616
- ].join("\n");
617
- }
@@ -9,6 +9,8 @@ export interface StatusView {
9
9
  active: boolean; generation?: string; phase?: string;
10
10
  pending: Record<string, unknown> & { rows: number };
11
11
  deadLeasesRemoved?: { lease: string; at: string }[]; refusals?: string[];
12
+ /** #581: present only while this working root last resolved to a different, unjoined key. */
13
+ projectTransition?: { previousKey: string; key: string; previousCuratedNotes: number | null; aliasCommand: string; keepCommand: string };
12
14
  }
13
15
 
14
16
  /** Human rendering options (#590): `--verbose` history lines, the wrap width and the version in the context line. */
@@ -68,7 +70,9 @@ export function statusText(status: StatusView, s: Style = PLAIN, opts: ReportTex
68
70
  if (interrupted) findings.push({ text: "a shard migration stopped after capture; authoring is refused until it activates", next: ["amem migrate --shards --resume"] });
69
71
  for (const reason of refusals) findings.push({ text: `migration refusal: ${reason}`, next: [] });
70
72
  if (status.pending.rows && !interrupted) findings.push({ text: `${plural(status.pending.rows, "old-layout row")} wait for the shard migration`, next: ["amem migrate --shards --dry-run", "amem migrate --shards --resume"] });
71
- const overall: State = candidateState === "unavailable" ? "unavailable" : candidateState === "attention" || migrationState === "attention" ? "attention" : "ok";
73
+ const transition = status.projectTransition;
74
+ if (transition) findings.push({ text: `this directory resolved to ${transition.previousKey}${transition.previousCuratedNotes === null ? "" : ` (${plural(transition.previousCuratedNotes, "curated note")})`} before and to ${transition.key} now`, next: [transition.aliasCommand, transition.keepCommand] });
75
+ const overall: State = candidateState === "unavailable" ? "unavailable" : candidateState === "attention" || migrationState === "attention" || transition ? "attention" : "ok";
72
76
  const { machine, repo, denyPaths, piiPatterns, ...limits } = status.config;
73
77
  const limitFacts = Object.entries(limits).filter(([, value]) => value !== undefined && value !== null)
74
78
  .map(([key, value]) => typeof value === "number" && key.endsWith("Bytes") ? `${wordedKey(key)} ${humanBytes(value)}`
@@ -1,7 +1,7 @@
1
1
  import { RECAP_SCRATCH } from "./recap-scratch.ts";
2
2
  import { buildCuratedBriefCache, buildPreferenceBriefCache } from "../brief-curated.ts";
3
3
  import { PREFERENCE_SLOT } from "./preference-brief.ts";
4
- import { curatedProfileBinding, invalidateCuratedCaches } from "./curated-cache-state.ts";
4
+ import { curatedProfileBinding, invalidateCuratedCaches, type CuratedCacheCandidate } from "./curated-cache-state.ts";
5
5
  import { assertPlacementRuntime, placementSelectorRefusal, SyncPlacementRuntimeError } from "./sync-placement-guard.ts";
6
6
  import { assertFormatFloor, floorRaiseHint, formatFloorAtLeast, PREFERENCE_MIN_READER } from "./formats.ts";
7
7
  import { readPublicPruneView } from "./public-prune-view.ts";
@@ -18,12 +18,12 @@ import { looksSecret } from "./screen.ts";
18
18
  import { mutationDatabase } from "./mutation.ts";
19
19
  import { memoryHome } from "./home.ts";
20
20
  import { machineId, type Machine } from "./machine.ts";
21
- import { assertProjectActive } from "./lifecycle.ts";
21
+ import { assertProjectActive, lifecycleResolver } from "./lifecycle.ts";
22
22
  export { machineId, type Machine } from "./machine.ts";
23
23
  import { rankedScore, rankedScoreDetails, unrankedScoreDetails, type SearchScoreDetails } from "./search-score.ts";
24
24
  export type { SearchScoreDetails } from "./search-score.ts";
25
25
  import { readWindowSql, readRef, type ReadWindow, type ReadRef, SearchIndex, captureSearch } from "./search-fts.ts";
26
- import { assertCuratedShardPaths, ensureShardDescriptor, readShardDescriptor, readShardedSelection, aliasedKeys, resolveAlias, resolveShardProfile, shardDir, shardKeyHash, shardMachineDir, userShardDir } from "./shard.ts";
26
+ import { assertCuratedShardPaths, ensureShardDescriptor, readShardDescriptor, readShardedSelection, aliasedKeys, effectiveAliases, resolveAlias, resolveShardProfile, shardDir, shardKeyHash, shardMachineDir, userShardDir } from "./shard.ts";
27
27
  import { readCaptureConfig, type CaptureRow } from "./capture.ts";
28
28
  import { assertSharedV1Op } from "./ops-contract.ts";
29
29
  import { generationDescriptor, generationDir, fsyncDirectory, canonicalJSON, hashJSON, readProfileJSON, resolveProfile, writeProfileJSON, readSelector, type BoundProfile, type ProfileInput, validateVaultLinkRow, vaultLinkId, type VaultLink, type VaultLinkRow, rebindPublicPruneProfile } from "./generation.ts";
@@ -33,6 +33,7 @@ import { readMigrationSources } from "./migrate.ts";
33
33
  import type { PruneSourceRow, PruneStorePort } from "./prune.ts";
34
34
  import { isDeepStrictEqual } from "node:util";
35
35
  import { registerReaderLease, type ReaderLease } from "./reader-lease.ts";
36
+ import { recordBriefPublicationFailure } from "./metrics.ts";
36
37
  import { groupByTask, taskGroupKey } from "./task-group.ts";
37
38
 
38
39
  /**
@@ -143,6 +144,11 @@ const oneLine = (text: string): string => text.replace(/\s+/g, " ").trim().slice
143
144
 
144
145
  /** A board task's key in hub memory: unique across `ahub reset --all`, which restarts the ids. */
145
146
  export const taskKey = (project: string, task: { id: number; created: number }): string => `${project}#${task.id}@${task.created}`;
147
+ /** The board namespace in a task key can itself contain '#'. */
148
+ function taskProject(task: string): string | null {
149
+ const separator = task.lastIndexOf("#");
150
+ return separator > 0 ? task.slice(0, separator) : null;
151
+ }
146
152
 
147
153
  /** A person's name for this machine, shown beside its id. */
148
154
  export function setMachineLabel(dir: string, label: string): Machine {
@@ -222,6 +228,9 @@ interface BootstrapBinding { token: typeof MIGRATION_BOOTSTRAP; profile: BoundPr
222
228
  // Defer publication until the outermost source fence in this process has released.
223
229
  const curatedDepth = new Map<string, number>();
224
230
  const curatedPending = new Map<string, Map<MemoryStore, Set<string>>>();
231
+ const curatedRecovery = new Map<string, CuratedCacheCandidate[]>();
232
+ // ponytail: two extra project preparations per fence release. An explicit bulk maintenance command is the upgrade for a large cold home.
233
+ const CURATED_RECOVERY_LIMIT = 2;
225
234
  /** #424: a project-scope, non-preference row appears only in its own project's prebuilt curated brief (the preference slot also reads shared rows). */
226
235
  const curatedLocal = (row: { scope?: string; kind?: string }): boolean => row.scope === "project" && row.kind !== "preference";
227
236
  let publishingCurated = false;
@@ -297,7 +306,7 @@ export class MemoryStore {
297
306
  db.run(`PRAGMA busy_timeout = ${MEMORY_DB_BUSY_TIMEOUT_MS}`);
298
307
  db.run("PRAGMA journal_mode = WAL");
299
308
  if ((db.query("PRAGMA user_version").get() as { user_version: number }).user_version !== INDEX_VERSION) {
300
- for (const t of ["segments", "heads", "entries", "ops", "edges", "goals"]) db.run(`DROP TABLE IF EXISTS ${t}`);
309
+ for (const t of ["segments", "heads", "entries", "ops", "edges", "goals", "unsettled_tasks"]) db.run(`DROP TABLE IF EXISTS ${t}`);
301
310
  db.run(`PRAGMA user_version = ${INDEX_VERSION}`);
302
311
  }
303
312
  db.run("CREATE TABLE IF NOT EXISTS segments (file TEXT PRIMARY KEY, offset INTEGER NOT NULL)");
@@ -309,6 +318,9 @@ export class MemoryStore {
309
318
  db.run("CREATE TABLE IF NOT EXISTS ops (id TEXT PRIMARY KEY, op TEXT NOT NULL, at TEXT NOT NULL, machine TEXT NOT NULL, target TEXT NOT NULL, by TEXT, actor TEXT NOT NULL)");
310
319
  db.run("CREATE TABLE IF NOT EXISTS edges (src TEXT NOT NULL, dst TEXT NOT NULL, PRIMARY KEY (src, dst))");
311
320
  db.run("CREATE INDEX IF NOT EXISTS edges_dst ON edges (dst)");
321
+ db.run("CREATE TABLE IF NOT EXISTS unsettled_tasks (project TEXT NOT NULL, task TEXT NOT NULL, PRIMARY KEY(project, task)) WITHOUT ROWID");
322
+ db.run("CREATE INDEX IF NOT EXISTS entries_task ON entries(task) WHERE task IS NOT NULL");
323
+ db.run("CREATE INDEX IF NOT EXISTS ops_settlement ON ops(target) WHERE op = 'settle'");
312
324
  this.db = db;
313
325
  this.mutationDb = openedMutation = mutationDatabase(this.dir);
314
326
  // One derived FTS copy per profile: a generation handle and a shared-v1 handle on one home never resync-fight.
@@ -319,7 +331,7 @@ export class MemoryStore {
319
331
  apply: (line, source) => this.apply(line, source), withMutation: work => this.withMutation(work), beforeCuratedWrite: targets => {
320
332
  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 }[];
321
333
  // #424: only the touched projects' prebuilt briefs; a shared or preference row (or an unknown target) can reach every project's slot.
322
- 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);
334
+ this.invalidateCuratedForPublication(rows.length === targets.length && rows.every(row => curatedLocal(row)) && rows.every(row => this.curatedChangeLocal(row.project, targets)) ? rows.map(row => row.project) : undefined);
323
335
  this.queueCuratedProjects(rows.map(row => row.project));
324
336
  },
325
337
  ...(bootstrap ? { limits: bootstrap.limits } : {}), ...(bootstrap?.commit ? { commit: bootstrap.commit } : {}) });
@@ -424,7 +436,7 @@ export class MemoryStore {
424
436
  finally { release(); }
425
437
  }
426
438
 
427
- private deferCuratedPublication(): () => void {
439
+ private deferCuratedPublication(recover = true): () => void {
428
440
  const home = this.profile.home;
429
441
  curatedDepth.set(home, (curatedDepth.get(home) ?? 0) + 1);
430
442
  return () => {
@@ -433,11 +445,26 @@ export class MemoryStore {
433
445
  curatedDepth.delete(home);
434
446
  if (publishingCurated) return;
435
447
  const pending = curatedPending.get(home); curatedPending.delete(home);
436
- if (!pending) return;
448
+ const recovery = curatedRecovery.get(home); curatedRecovery.delete(home);
449
+ if (!pending && !recovery) return;
437
450
  publishingCurated = true;
438
451
  // #466: a project's own handle publishes its brief instead of a second handle indexing the same shard.
439
- try { for (const [store, projects] of pending) store.publishCurated(projects, store, true); }
440
- finally { publishingCurated = false; }
452
+ try {
453
+ for (const [store, projects] of pending ?? []) store.publishCurated(projects, store, true);
454
+ if (recover && recovery?.length) {
455
+ try {
456
+ const aliases = effectiveAliases(home);
457
+ const touched = new Set(Array.from(pending?.values() ?? []).flatMap(projects => [...projects].map(project => aliases.get(project) ?? project)));
458
+ const state = lifecycleResolver(home);
459
+ const candidates = recovery.filter(({ project }) => !touched.has(project) && !aliases.has(project) && state(project) === "active")
460
+ .sort((a, b) => b.activity - a.activity || a.project.localeCompare(b.project));
461
+ // Resume after the previous warm cohort. Reusing the removed set would always pick the same projects.
462
+ const start = candidates.findLastIndex(candidate => candidate.warm) + 1;
463
+ const additional = [...candidates.slice(start), ...candidates.slice(0, start)].slice(0, CURATED_RECOVERY_LIMIT);
464
+ if (additional.length) this.publishCurated(new Set(additional.map(candidate => candidate.project)));
465
+ } catch { recordBriefPublicationFailure(home, "curated", "source_unavailable"); }
466
+ }
467
+ } finally { publishingCurated = false; }
441
468
  };
442
469
  }
443
470
 
@@ -490,10 +517,23 @@ export class MemoryStore {
490
517
  if (this.curatedRelations.size > 8192) this.curatedRelations = null;
491
518
  }
492
519
 
520
+ private invalidateCuratedForPublication(projects?: readonly string[]): void {
521
+ const home = this.profile.home;
522
+ if (projects || !this.profile.sharded || publishingCurated || curatedRecovery.has(home)) {
523
+ invalidateCuratedCaches(home, projects);
524
+ return;
525
+ }
526
+ const candidates: CuratedCacheCandidate[] = [];
527
+ invalidateCuratedCaches(home, undefined, {
528
+ machine: this.machine.id, now: Date.now(), candidate: candidate => candidates.push(candidate),
529
+ });
530
+ curatedRecovery.set(home, candidates);
531
+ }
532
+
493
533
  /** #424: `local` means the change is visible only in `project`'s prebuilt brief; otherwise every project's cache is invalidated. */
494
534
  private markCuratedChange(project?: string, local = false): void {
495
535
  if (this.bootstrapOnly) return;
496
- invalidateCuratedCaches(this.profile.home, project && local ? [project] : undefined);
536
+ this.invalidateCuratedForPublication(project && local ? [project] : undefined);
497
537
  this.queueCuratedProjects(project ? [project] : []);
498
538
  }
499
539
 
@@ -522,7 +562,7 @@ export class MemoryStore {
522
562
  beginCuratedCacheUpdate(): () => void {
523
563
  const release = this.deferCuratedPublication();
524
564
  let before: Map<string, string>;
525
- try { before = this.curatedProjectRevisions(); invalidateCuratedCaches(this.profile.home); }
565
+ try { before = this.curatedProjectRevisions(); this.invalidateCuratedForPublication(); }
526
566
  catch (error) { release(); throw error; }
527
567
  return () => {
528
568
  try {
@@ -537,7 +577,7 @@ export class MemoryStore {
537
577
  /** Off-hook preparation; callers never invoke this from native SessionStart. */
538
578
  prepareCuratedBriefs(projects?: readonly string[]): void {
539
579
  try { this.curatedRebuildAll = projects === undefined; this.publishCurated(new Set(projects ?? []), projects?.length === 1 ? this : undefined); }
540
- catch { /* An off-hook read still succeeds when its optional derived cache cannot be prepared. */ }
580
+ catch { recordBriefPublicationFailure(this.profile.home, "curated", "source_unavailable"); }
541
581
  }
542
582
 
543
583
  private publishCurated(input: ReadonlySet<string>, opened?: MemoryStore, openOnMiss = false): void {
@@ -550,6 +590,7 @@ export class MemoryStore {
550
590
  }
551
591
  for (const raw of projects) {
552
592
  let view: MemoryStore | undefined;
593
+ let failure: "source_unavailable" | "binding_changed" | "write_failed" = "source_unavailable";
553
594
  try {
554
595
  const project = resolveAlias(this.profile.home, raw), aliases = aliasedKeys(this.profile.home, project);
555
596
  const common = { memoryDir: this.profile.home, deferPromotions: true, now: this.now, ...(aliases.length ? { reconcile: { canonical: project, aliases } } : {}) };
@@ -570,6 +611,7 @@ export class MemoryStore {
570
611
  view.curatedPublication = true;
571
612
  try {
572
613
  view.withStoreFences(() => {
614
+ failure = "binding_changed";
573
615
  const selected = readSelector(this.profile.home);
574
616
  const shards = sharded ? readShardedSelection(this.profile.home) : null;
575
617
  if (view!.profile.selectorRevision !== selected.revision || view!.profile.kind !== (shards ? "generation" : selected.selector?.kind ?? "shared-v1")
@@ -581,15 +623,20 @@ export class MemoryStore {
581
623
  }
582
624
  // Stamp the source handle's inputs, never a newer metadata read that it did not open.
583
625
  const binding = JSON.stringify({ selector: selected.revision, shards, aliases });
626
+ failure = "write_failed";
584
627
  ensureShardDescriptor(this.profile.home, project);
585
628
  const directory = shardMachineDir(this.profile.home, project, machineId(this.profile.home).id);
586
629
  mkdirSync(directory, { recursive: true, mode: 0o700 });
587
630
  buildCuratedBriefCache(view!, { base: this.profile.home, project, directory, binding, now: this.now });
588
631
  buildPreferenceBriefCache(view!, { base: this.profile.home, project, directory, binding, now: this.now });
589
- if (curatedProfileBinding(this.profile.home, project) !== binding) for (const name of ["brief-curated.json", "brief-preferences.json"]) rmSync(join(directory, name), { force: true });
632
+ failure = "binding_changed";
633
+ if (curatedProfileBinding(this.profile.home, project) !== binding) {
634
+ for (const name of ["brief-curated.json", "brief-preferences.json"]) rmSync(join(directory, name), { force: true });
635
+ recordBriefPublicationFailure(this.profile.home, "curated", failure);
636
+ }
590
637
  });
591
638
  } finally { view.curatedPublication = false; }
592
- } catch { /* Failed derived publication leaves the invalidated cache unavailable; a later mutation retries. */ }
639
+ } catch { recordBriefPublicationFailure(this.profile.home, "curated", failure); }
593
640
  finally { try { if (view !== opened) view?.close(); } catch { /* Preserve the authoritative mutation result. */ } }
594
641
  }
595
642
  }
@@ -906,7 +953,7 @@ export class MemoryStore {
906
953
  // #466: the settle rows and every promotion they release land before one publication runs, and `promoting` covers
907
954
  // this handle, its user overlay and its alias shards for the whole call.
908
955
  return this.withDeferredPromotions(() => {
909
- const release = this.deferCuratedPublication();
956
+ const release = this.deferCuratedPublication(false);
910
957
  try {
911
958
  const entry = { op: "settle", target: task, actor, by: this.until() } as const;
912
959
  const at = new Date(this.now()).toISOString();
@@ -931,6 +978,37 @@ export class MemoryStore {
931
978
  }
932
979
  /** Whether any entry was saved against the task. */
933
980
  hasTask(task: string): boolean { this.ensureFresh(); return this.readRows("SELECT 1 FROM entries WHERE task = ?", task).length > 0; }
981
+ /** A live page of task keys in this exact namespace without any visible settlement, including legacy. */
982
+ unsettledTaskKeys(project: string, options: { after?: string; limit?: number } = {}): { keys: string[]; next?: string } {
983
+ const { after, limit = 64 } = options;
984
+ if (typeof project !== "string" || !project.trim()) throw Error("Task discovery requires a non-empty project. Pass the board's project key.");
985
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 256) throw Error("Task discovery limit must be an integer from 1 to 256. Omit limit to use 64.");
986
+ if (after !== undefined && (typeof after !== "string" || taskProject(after) !== project))
987
+ throw Error("Invalid task discovery cursor. Use the next cursor returned for the same project, or omit after to start a new sweep.");
988
+ this.withDeferredPromotions(() => this.ensureFresh());
989
+ const stores = this.readStores(), candidates = new Set<string>();
990
+ for (const store of stores) {
991
+ if (store.stale) throw Error("Task discovery could not refresh a readable store. Another process may hold its index lock, or a segment may be unreadable. Retry the sweep later. If this persists, run amem doctor.");
992
+ const rows = store.db.query("SELECT task FROM unsettled_tasks WHERE project = ? AND task > ? ORDER BY task LIMIT ?")
993
+ .all(project, after ?? "", limit + 1) as { task: string }[];
994
+ for (const row of rows) candidates.add(row.task);
995
+ }
996
+ // SQLite BINARY orders UTF-8 bytes. Keep exactly that order when merging store frontiers.
997
+ const ordered = [...candidates].sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b)));
998
+ const examined = ordered.slice(0, limit);
999
+ const next = ordered.length > limit ? examined[limit - 1] : undefined;
1000
+ if (stores.length === 1 || !examined.length) return { keys: examined, ...(next ? { next } : {}) };
1001
+
1002
+ // A settlement may live only in another readable store. One indexed existence probe per key
1003
+ // and store suffices, even if many settle rows name the same key. Advance past keys settled in other stores too.
1004
+ const visibleSettlements = new Set<string>(), batch = JSON.stringify(examined);
1005
+ for (const store of stores) {
1006
+ const rows = store.db.query(`SELECT value AS task FROM json_each(?) AS candidate
1007
+ WHERE EXISTS (SELECT 1 FROM ops WHERE op = 'settle' AND target = candidate.value)`).all(batch) as { task: string }[];
1008
+ for (const row of rows) visibleSettlements.add(row.task);
1009
+ }
1010
+ return { keys: examined.filter(key => !visibleSettlements.has(key)), ...(next ? { next } : {}) };
1011
+ }
934
1012
  private promoting = false;
935
1013
  private readonly screen?: PromotionScreen;
936
1014
  /**
@@ -1024,7 +1102,7 @@ export class MemoryStore {
1024
1102
  // One transaction: no reader sees the index empty, and no other process commits an offset in between.
1025
1103
  this.rebuildingSearch = true;
1026
1104
  try {
1027
- this.db.transaction(() => { for (const t of ["segments", "heads", "entries", "ops", "edges", "goals"]) this.db.run(`DELETE FROM ${t}`); this.refresh(); }).immediate();
1105
+ this.db.transaction(() => { for (const t of ["segments", "heads", "entries", "ops", "edges", "goals", "unsettled_tasks"]) this.db.run(`DELETE FROM ${t}`); this.refresh(); }).immediate();
1028
1106
  } finally { this.rebuildingSearch = false; }
1029
1107
  this.syncSearchIndex(); // one batched derived write, not one search.db transaction per rebuilt entry
1030
1108
  }
@@ -1053,6 +1131,14 @@ export class MemoryStore {
1053
1131
  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)
1054
1132
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(id, e.at, e.machine, e.project, e.scope === "shared" ? "shared" : "project", e.tier === "long" ? "long" : "short",
1055
1133
  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;
1134
+ // The board namespace belongs to the task key, independently of the note's owning project.
1135
+ // INSERT OR IGNORE makes duplicate replay idempotent, and the indexed probe handles settle-before-note.
1136
+ if (e.task) {
1137
+ const project = taskProject(e.task);
1138
+ if (project !== null) this.db.query(`INSERT OR IGNORE INTO unsettled_tasks(project, task)
1139
+ SELECT ?, ? WHERE NOT EXISTS (SELECT 1 FROM ops WHERE op = 'settle' AND target = ?)`)
1140
+ .run(project, e.task, e.task);
1141
+ }
1056
1142
  this.rememberCuratedRelation(id, [e.supersedes, e.promotedFrom].filter((value): value is string => !!value));
1057
1143
  // The FTS copy follows the committed row. `changes` is only a hint here (bun:sqlite misreports it for ignored
1058
1144
  // inserts inside a transaction): addCurated is idempotent by entry id, and a missed hint becomes a count drift
@@ -1068,6 +1154,8 @@ export class MemoryStore {
1068
1154
  const dated = !["demote", "settle", "lease", "lease_force"].includes(e.op) || (typeof e.by === "string" && !Number.isNaN(Date.parse(e.by)));
1069
1155
  if (!str(e.target, 400) || !opt(e.by) || !opt(e.actor) || !dated) { this.log(`memory segment ${segment}: a malformed entry was skipped`); return; }
1070
1156
  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 ?? "");
1157
+ if (e.op === "settle") this.db.query("DELETE FROM unsettled_tasks WHERE project = ? AND task = ?")
1158
+ .run(taskProject(e.target), e.target);
1071
1159
  if (e.op === "supersede" && e.by) this.rememberCuratedRelation(e.target, [e.by]);
1072
1160
  }
1073
1161
  }
@@ -1256,7 +1344,14 @@ export class MemoryStore {
1256
1344
  const gone = new Set<string>();
1257
1345
  for (const v of expired) for (let id: string | undefined = v.id; id && !gone.has(id); id = parent.get(id)) gone.add(id);
1258
1346
  if (!gone.size) return 0;
1259
- this.db.transaction(() => { for (const id of gone) { this.db.query("DELETE FROM entries WHERE id = ?").run(id); this.db.query("DELETE FROM edges WHERE src = ?").run(id); } }).immediate();
1347
+ this.db.transaction(() => {
1348
+ for (const id of gone) {
1349
+ const row = this.db.query("DELETE FROM entries WHERE id = ? RETURNING task").get(id) as { task: string | null } | null;
1350
+ if (row?.task) this.db.query(`DELETE FROM unsettled_tasks WHERE project = ? AND task = ?
1351
+ AND NOT EXISTS (SELECT 1 FROM entries WHERE task = ?)`).run(taskProject(row.task), row.task, row.task);
1352
+ this.db.query("DELETE FROM edges WHERE src = ?").run(id);
1353
+ }
1354
+ }).immediate();
1260
1355
  this.searchIndex.markDirty(); // FTS cannot subtract rows incrementally: the next search resyncs it
1261
1356
  return gone.size;
1262
1357
  }
@@ -8,12 +8,14 @@ import { assertNoLiveReaders } from "./reader-lease.ts";
8
8
  import { createPlacementActivationOwner } from "./sync-placement-activation-proof.ts";
9
9
  /** #578 Q1: a checkpoint fence never refuses for readers; its `busy` means a placement sync, admission or renewal holds a lock. */
10
10
  export const PLACEMENT_CHECKPOINT_BUSY_MESSAGE = "Sync placement checkpoint is busy: a placement sync, admission or renewal holds its lock; wait for it to finish (amem sync --status shows recorded operations), then rerun the same checkpoint command.";
11
+ /** #624: only a writer renewal on an active inventory can continue through the checkpoint, which never waits for readers. */
12
+ export const PLACEMENT_RENEWAL_READERS_CONTINUATION = " To renew writers while sessions keep running, use the checkpoint instead, which does not wait for readers: %s.".replace("%s", "save the preview with (umask 077; set -C; amem migrate --sync-placement --checkpoint --writer-root <install root> --json > checkpoint-plan.json), repeating --writer-root for every install root, then run amem migrate --sync-placement --checkpoint --confirm --plan checkpoint-plan.json with the same --writer-root list");
11
13
  export class PlacementInventoryFenceError extends Error{
12
- constructor(readonly causeClass:"readers"|"busy",checkpoint=false){super(checkpoint&&causeClass==="busy"?PLACEMENT_CHECKPOINT_BUSY_MESSAGE:`Sync placement migration is ${causeClass}; close cooperating readers/writers, then run amem migrate --sync-placement --dry-run before retrying.`);this.name="PlacementInventoryFenceError";}
14
+ constructor(readonly causeClass:"readers"|"busy",checkpoint=false,renewal=false){super(checkpoint&&causeClass==="busy"?PLACEMENT_CHECKPOINT_BUSY_MESSAGE:`Sync placement migration is ${causeClass}; close cooperating readers/writers, then run amem migrate --sync-placement --dry-run before retrying.${renewal&&causeClass==="readers"?PLACEMENT_RENEWAL_READERS_CONTINUATION:""}`);this.name="PlacementInventoryFenceError";}
13
15
  }
14
16
  type FenceWork<T>=(mutation:MutationHandle,owner:ReturnType<typeof createPlacementActivationOwner>)=>Promise<T>;
15
- async function withFences<T>(home:string,directories:readonly string[],options:{readers:boolean},work:FenceWork<T>):Promise<T> {
16
- const fail=(cause:"readers"|"busy"):never=>{throw new PlacementInventoryFenceError(cause,!options.readers);};
17
+ async function withFences<T>(home:string,directories:readonly string[],options:{readers:boolean;renewal?:boolean},work:FenceWork<T>):Promise<T> {
18
+ const fail=(cause:"readers"|"busy"):never=>{throw new PlacementInventoryFenceError(cause,!options.readers,options.renewal===true);};
17
19
  return withProfileLock(home,async()=>{
18
20
  const releases:(()=>void)[]=[];
19
21
  try {
@@ -30,8 +32,8 @@ async function withFences<T>(home:string,directories:readonly string[],options:{
30
32
  });
31
33
  }
32
34
  /** Activation, renewal and admission: every live reader lease refuses, as before. */
33
- export function withPlacementActivationFences<T>(home:string,directories:readonly string[],work:FenceWork<T>):Promise<T> {
34
- return withFences(home,directories,{readers:true},work);
35
+ export function withPlacementActivationFences<T>(home:string,directories:readonly string[],work:FenceWork<T>,options:{renewal?:boolean}={}):Promise<T> {
36
+ return withFences(home,directories,{readers:true,renewal:options.renewal===true},work);
35
37
  }
36
38
  /**
37
39
  * #578 Q1: checkpoint confirm, resume and abandon exclude placement writers only (profile lock, every mutation and sync
@@ -0,0 +1,18 @@
1
+ import type { SyncOptions } from "./sync.ts";
2
+
3
+ /**
4
+ * #626, internal to one placement inventory run: the remote's advertised placement refs by remote URL, read once and
5
+ * shared by the run's publications. Kept off the public SyncOptions type (host API fixture): the inventory driver binds a
6
+ * fresh map to its own options object, and a publication reached with other options reads per run as before.
7
+ * Never authority: each publication still proves every target against it, and a publication that pushes deletes its entry.
8
+ */
9
+ const runs = new WeakMap<SyncOptions, Map<string, ReadonlyMap<string, string>>>();
10
+
11
+ export function bindPlacementAdvertisement(opts: SyncOptions): SyncOptions {
12
+ runs.set(opts, new Map());
13
+ return opts;
14
+ }
15
+
16
+ export function placementAdvertisement(opts: SyncOptions): Map<string, ReadonlyMap<string, string>> | undefined {
17
+ return runs.get(opts);
18
+ }
@@ -18,11 +18,11 @@ const phases: Record<PlacementSyncBoundPhase, string> = { "source-capture": "sou
18
18
  export function placementSyncBoundMessage(bound: PlacementSyncBound): string {
19
19
  // #288 step 3: a full live window is relieved by a person-reviewed checkpoint; records stay a reported bound.
20
20
  const remedy = bound.kind === "journal-objects"
21
- ? "The active epoch journal cannot hold this publication; preview a checkpoint with amem migrate --sync-placement --checkpoint --writer-root <install root> (repeat for every install), then confirm it after the exact command is approved and rerun amem sync."
21
+ ? "The active epoch journal cannot hold this publication. Save a new private preview with (umask 077; set -C; amem migrate --sync-placement --checkpoint --writer-root <install root> --json > checkpoint-plan.json). Repeat --writer-root for every install. After reviewing and approving the saved plan, run amem migrate --sync-placement --checkpoint --writer-root <install root> --confirm --plan checkpoint-plan.json with the same roots, then rerun amem sync."
22
22
  : bound.kind === "journal-records"
23
23
  ? "The active epoch journal cannot hold this publication; retain the inputs and report this bound."
24
24
  : "Retain the inputs and report this bound; no row was omitted to fit.";
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}`;
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 by this publication. ${remedy}`;
26
26
  }
27
27
  /** Expected input refusal before a publication attempt exists. Code stays "bound" for existing callers. */
28
28
  export class PlacementSyncBoundError extends SyncPlacementJournalError {