@staix/agent-mem 0.29.0 → 0.31.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 (71) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +20 -574
  3. package/package.json +3 -2
  4. package/src/cli-agent-reads.ts +17 -2
  5. package/src/cli.ts +178 -21
  6. package/src/commands-table.ts +14 -2
  7. package/src/index.ts +1 -0
  8. package/src/ingest.ts +7 -5
  9. package/src/mcp-memory.ts +36 -8
  10. package/src/memory/bridge.ts +26 -1
  11. package/src/memory/candidates.ts +17 -1
  12. package/src/memory/capacity.ts +5 -2
  13. package/src/memory/catalog.ts +10 -1
  14. package/src/memory/commands.ts +2 -1
  15. package/src/memory/config.ts +13 -1
  16. package/src/memory/decay-review.ts +20 -0
  17. package/src/memory/doctor.ts +133 -47
  18. package/src/memory/eval-audit.ts +442 -0
  19. package/src/memory/eval.ts +66 -0
  20. package/src/memory/formats.ts +4 -3
  21. package/src/memory/intent-brief.ts +34 -6
  22. package/src/memory/metrics.ts +173 -14
  23. package/src/memory/native-roots.ts +28 -0
  24. package/src/memory/platform.ts +9 -1
  25. package/src/memory/review-targets.ts +69 -0
  26. package/src/memory/shard-bridge.ts +18 -6
  27. package/src/memory/shard-migration.ts +14 -1
  28. package/src/memory/shard-sync-format.ts +18 -0
  29. package/src/memory/shard-sync.ts +52 -4
  30. package/src/memory/shard.ts +4 -0
  31. package/src/memory/store.ts +4 -2
  32. package/src/memory/sync-placement-bound.ts +21 -4
  33. package/src/memory/sync-placement-cache.ts +16 -1
  34. package/src/memory/sync-placement-capture.ts +14 -2
  35. package/src/memory/sync-placement-checkpoint-format.ts +199 -0
  36. package/src/memory/sync-placement-checkpoint-person.ts +209 -0
  37. package/src/memory/sync-placement-checkpoint-prospective.ts +141 -0
  38. package/src/memory/sync-placement-checkpoint-storage.ts +218 -0
  39. package/src/memory/sync-placement-checkpoint.ts +234 -0
  40. package/src/memory/sync-placement-dependencies.ts +42 -9
  41. package/src/memory/sync-placement-effective-writers.ts +12 -6
  42. package/src/memory/sync-placement-git.ts +17 -7
  43. package/src/memory/sync-placement-inspection-evidence.ts +1 -1
  44. package/src/memory/sync-placement-inventory.ts +38 -11
  45. package/src/memory/sync-placement-journal-format.ts +4 -1
  46. package/src/memory/sync-placement-journal-storage.ts +129 -26
  47. package/src/memory/sync-placement-materialize.ts +33 -19
  48. package/src/memory/sync-placement-projection.ts +7 -1
  49. package/src/memory/sync-placement-publication-events.ts +42 -0
  50. package/src/memory/sync-placement-publication-plan.ts +18 -1
  51. package/src/memory/sync-placement-realm-admission.ts +20 -3
  52. package/src/memory/sync-placement-realm-discovery.ts +42 -0
  53. package/src/memory/sync-placement-remote-admission.ts +190 -0
  54. package/src/memory/sync-placement-remote-adoption-format.ts +54 -0
  55. package/src/memory/sync-placement-remote-materialization.ts +49 -0
  56. package/src/memory/sync-placement-remote-refusal.ts +21 -0
  57. package/src/memory/sync-placement-remote-stage.ts +275 -0
  58. package/src/memory/sync-placement-transport.ts +207 -53
  59. package/src/memory/sync-placement-writer-history.ts +75 -17
  60. package/src/memory/sync-placement-writer-renewal.ts +18 -10
  61. package/src/memory/sync-placement-writer-revision-format.ts +16 -13
  62. package/src/memory/sync-placement-yield.ts +14 -0
  63. package/src/memory/sync-progress.ts +1 -1
  64. package/src/memory/sync.ts +5 -2
  65. package/src/memory/use-telemetry.ts +15 -7
  66. package/src/setup-drift.ts +12 -2
  67. package/src/setup-owned.ts +42 -0
  68. package/src/setup.ts +32 -11
  69. package/src/sync-placement-writer-context.ts +5 -5
  70. package/src/ui/plugin.ts +26 -11
  71. package/src/ui/snapshot-cache.ts +24 -11
@@ -1,6 +1,7 @@
1
- import { closeSync, constants, fstatSync, openSync, readSync, appendFileSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
1
+ import { closeSync, constants, fstatSync, openSync, readSync, appendFileSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { mkdir as mkdirAsync, open as openAsync, readFile as readFileAsync, rename as renameAsync, stat as statAsync, unlink as unlinkAsync, writeFile as writeFileAsync } from "node:fs/promises";
2
3
  import type { RecordIntakeRefusal } from "../hook-record.ts";
3
- import type { HookRssSources } from "../hook-resources.ts";
4
+ import { processImageRssKB, type HookRssSources } from "../hook-resources.ts";
4
5
  import type { HookTranscriptStopReason } from "../hook-contract.ts";
5
6
  import { join } from "node:path";
6
7
 
@@ -51,37 +52,195 @@ export interface RecordVariantMetric {
51
52
  recordValidRecords?: number; recordBasisRecords?: number; recordUnverifiedRecords?: number;
52
53
  recordInstructionInvalid?: number; recordInstructionEmitted?: number; recordBriefBytes?: number;
53
54
  }
54
- export interface MetricSample extends RecordVariantMetric { at: string; kind: "hook" | "search"; brief?: BriefObservation; wallMs?: number; rssMB?: number; rawRssMB?: number; rssSources?: HookRssSources; rssScope?: "owned-images"; transcriptOffset?: number; transcriptStopReason?: HookTranscriptStopReason; /** #226: owned children killed but still alive when the hook returned (bounded reap). */ abandonedChildren?: number; /** #226: a killed worker skipped this call's drain; staged records stay pending (not a capture drop). */ drainSkipped?: number; /** #226: when the worker drain started (ms after hook start) and how many records it committed. */ drainStartMs?: number; drained?: number; idleMB?: number; recordInstructionBytes?: number; recordInstructionEstimatedTokens?: number; captureDrops?: number; captureDropReason?: CaptureDropReason }
55
+ export interface MetricSample extends RecordVariantMetric { at: string; kind: "hook" | "search"; /** #485: the read tool that completed, so a peak can be attributed; never its arguments or result. */ tool?: string; /** #485: the process peak after this call was higher than after any sample before it. */ peakRaised?: boolean; brief?: BriefObservation; wallMs?: number; rssMB?: number; rawRssMB?: number; rssSources?: HookRssSources; rssScope?: "owned-images"; transcriptOffset?: number; transcriptStopReason?: HookTranscriptStopReason; /** #226: owned children killed but still alive when the hook returned (bounded reap). */ abandonedChildren?: number; /** #226: a killed worker skipped this call's drain; staged records stay pending (not a capture drop). */ drainSkipped?: number; /** #226: when the worker drain started (ms after hook start) and how many records it committed. */ drainStartMs?: number; drained?: number; idleMB?: number; recordInstructionBytes?: number; recordInstructionEstimatedTokens?: number; captureDrops?: number; captureDropReason?: CaptureDropReason }
55
56
  const METRICS_MAX_BYTES = 64 * 1024, METRICS_KEEP = 200;
56
57
 
58
+ /**
59
+ * #485: the newest `limit` samples of each kind. Hook samples share this file with the read-tool samples a long-lived
60
+ * `amem mcp` process appends, so one kind's flood must not evict the other kind from the window.
61
+ */
62
+ function newestPerKind<T>(items: readonly T[], limit: number, kindOf: (item: T) => string): T[] {
63
+ const kept: T[] = [], seen = new Map<string, number>();
64
+ for (let index = items.length - 1; index >= 0; index--) {
65
+ const item = items[index]!, kind = kindOf(item), count = seen.get(kind) ?? 0;
66
+ if (count >= limit) continue;
67
+ seen.set(kind, count + 1); kept.push(item);
68
+ }
69
+ return kept.reverse();
70
+ }
71
+
72
+ /**
73
+ * #485: the process peak on the same basis as `scripts/budget-rss.ts` `peakRssKB` (VmHWM on Linux, rusage maxRSS
74
+ * elsewhere). `undefined` when this host cannot answer, so a read that only wanted a telemetry sample still completes.
75
+ */
76
+ export function processPeakRssKB(): number | undefined {
77
+ try { return processImageRssKB("self") ?? process.resourceUsage().maxRSS; } catch { return undefined; }
78
+ }
79
+
80
+ /** #485: one read-tool call's window; `alone` goes false as soon as another read call shares any part of it. */
81
+ export interface PeakWindow { alone: boolean }
82
+
83
+ /** A host that cannot report its peak must not turn a read into a failure, so a throwing read is `undefined`. */
84
+ const peekOnce = (read: () => number | undefined): number | undefined => { try { return read(); } catch { return undefined; } };
85
+
86
+ /**
87
+ * #485: peak attribution for the read-tool wrapper. The process peak is monotonic, so a sample that observes a peak
88
+ * above every earlier one is the sample that set it — but only when no other read call was in flight in the same
89
+ * window, because then either call could have raised it. Such a call records `false` and the peak still advances, so a
90
+ * later call is compared with what actually happened.
91
+ */
92
+ export function createPeakTracker(read: () => number | undefined = processPeakRssKB) {
93
+ const windows = new Set<PeakWindow>();
94
+ let observed = peekOnce(read);
95
+ const peek = () => peekOnce(read);
96
+ const advance = (peakKB: number) => { observed = observed === undefined ? peakKB : Math.max(observed, peakKB); };
97
+ return {
98
+ begin(): PeakWindow {
99
+ const window: PeakWindow = { alone: windows.size === 0 };
100
+ for (const other of windows) other.alone = false;
101
+ windows.add(window);
102
+ return window;
103
+ },
104
+ /** The call completed: report whether it may be credited with the peak, and the peak to record with its sample. */
105
+ end(window: PeakWindow): { peakKB?: number; raised: boolean } {
106
+ windows.delete(window);
107
+ const peakKB = peek();
108
+ if (peakKB === undefined) return { raised: false };
109
+ const raised = window.alone && (observed === undefined || peakKB > observed);
110
+ advance(peakKB);
111
+ return { peakKB, raised };
112
+ },
113
+ /** The call refused or threw: it records nothing, but the peak still advances so a later call is not miscredited. */
114
+ abort(window: PeakWindow): void {
115
+ windows.delete(window);
116
+ const peakKB = peek();
117
+ if (peakKB !== undefined) advance(peakKB);
118
+ },
119
+ };
120
+ }
121
+
57
122
  export function metricsPath(base: string): string {
58
123
  return join(base, "metrics.jsonl");
59
124
  }
60
125
 
61
- /** Append samples, trimming the rolling file when it outgrows its bound (newest samples win). */
126
+ /**
127
+ * #485: the trim replaces the file with a rename of a fully written sibling. A long-lived `amem mcp` process appends
128
+ * to this file while a hook trims it, and truncating in place let a concurrent append interleave with the rewrite
129
+ * (observed malformed JSON). A rename is atomic, so a reader sees the old file or the new one, never a half-written
130
+ * one; a sample that raced the rename is lost, which telemetry allows.
131
+ */
132
+ let trimGeneration = 0;
133
+ /** The kept text of a trim: torn lines dropped, the newest METRICS_KEEP of each kind kept, oldest first. */
134
+ function trimmedText(text: string): string {
135
+ const rows: { line: string; kind: string }[] = [];
136
+ for (const line of text.split("\n")) {
137
+ if (!line) continue;
138
+ // A line the read caught mid-append is dropped, never copied into the replacement.
139
+ try { const kind = (JSON.parse(line) as { kind?: unknown }).kind; rows.push({ line, kind: typeof kind === "string" ? kind : "other" }); } catch { /* torn tail */ }
140
+ }
141
+ return newestPerKind(rows, METRICS_KEEP, row => row.kind).map(row => row.line).join("\n") + "\n";
142
+ }
143
+
144
+ function trimMetrics(file: string): void {
145
+ const kept = trimmedText(readFileSync(file, "utf8"));
146
+ const temp = `${file}.${process.pid}.${++trimGeneration}.tmp`;
147
+ try {
148
+ writeFileSync(temp, kept, { mode: 0o600 });
149
+ renameSync(temp, file);
150
+ } catch (error) {
151
+ try { unlinkSync(temp); } catch { /* the sibling was never written, so there is nothing to remove */ }
152
+ throw error;
153
+ }
154
+ }
155
+
156
+ /**
157
+ * #485: the read path records its sample after the response is already queued, and every disk call it makes is
158
+ * asynchronous: a stalled or non-regular `metrics.jsonl` must not hold a completed read or its server. The open is
159
+ * non-blocking, so a FIFO without a reader fails it instead of waiting for one, and anything that is not a plain file
160
+ * is refused before a byte is written. One worker drains the hand-offs in call order, so the file keeps the order the
161
+ * calls completed in; a sample still in flight when the process exits is simply lost.
162
+ */
163
+ const pending: { base: string; samples: MetricSample[] }[] = [];
164
+ let draining = false;
165
+ export function appendMetricsLater(base: string, samples: MetricSample[]): void {
166
+ pending.push({ base, samples });
167
+ if (draining) return;
168
+ draining = true;
169
+ setImmediate(() => { void drainPending(); });
170
+ }
171
+
172
+ async function drainPending(): Promise<void> {
173
+ while (pending.length) {
174
+ const next = pending.shift()!;
175
+ try { await writeSamplesLater(next.base, next.samples); } catch { /* a lost sample is never a failed call */ }
176
+ }
177
+ draining = false;
178
+ }
179
+
180
+ async function writeSamplesLater(base: string, samples: MetricSample[]): Promise<void> {
181
+ await mkdirAsync(base, { recursive: true, mode: 0o700 });
182
+ const file = metricsPath(base), payload = Buffer.from(samples.map(sample => JSON.stringify(sample)).join("\n") + "\n");
183
+ const handle = await openAsync(file, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);
184
+ try {
185
+ if (!(await handle.stat()).isFile()) return;
186
+ for (let written = 0; written < payload.length;) written += (await handle.write(payload.subarray(written))).bytesWritten;
187
+ } finally { await handle.close(); }
188
+ if ((await statAsync(file)).size <= METRICS_MAX_BYTES) return;
189
+ const temp = `${file}.${process.pid}.${++trimGeneration}.tmp`;
190
+ try {
191
+ await writeFileAsync(temp, trimmedText(await readFileAsync(file, "utf8")), { mode: 0o600 });
192
+ await renameAsync(temp, file);
193
+ } catch (error) {
194
+ try { await unlinkAsync(temp); } catch { /* the sibling was never written, so there is nothing to remove */ }
195
+ throw error;
196
+ }
197
+ }
198
+
199
+ /** Append samples, trimming the rolling file when it outgrows its bound; the newest METRICS_KEEP of each kind win (#485). */
62
200
  export function appendMetrics(base: string, samples: MetricSample[]): void {
63
201
  mkdirSync(base, { recursive: true, mode: 0o700 });
64
202
  const file = metricsPath(base);
65
203
  appendFileSync(file, samples.map((s) => JSON.stringify(s)).join("\n") + "\n", { mode: 0o600 });
66
204
  try {
67
205
  if (statSync(file).size <= METRICS_MAX_BYTES) return;
68
- const lines = readFileSync(file, "utf8").split("\n").filter(Boolean).slice(-METRICS_KEEP);
69
- writeFileSync(file, lines.join("\n") + "\n", { mode: 0o600 });
70
- } catch { /* a trim failure loses nothing: the file simply stays larger */ }
206
+ trimMetrics(file);
207
+ } catch { /* a trim failure loses nothing: the file simply stays larger, and a lost sample is acceptable telemetry */ }
71
208
  }
72
209
 
73
- /** The newest samples first-preserved order (oldest to newest); malformed lines are skipped. */
210
+ /** The newest samples first-preserved order (oldest to newest), `limit` of each kind kept (#485); malformed lines are skipped. */
74
211
  export function readMetrics(base: string, limit = METRICS_KEEP): MetricSample[] {
75
- let lines: string[] = [];
76
- try { lines = readFileSync(metricsPath(base), "utf8").split("\n").filter(Boolean); } catch { return []; }
77
- const out: MetricSample[] = [];
78
- for (const line of lines.slice(-limit)) {
212
+ const text = readMetricsText(metricsPath(base));
213
+ if (text === undefined) return [];
214
+ const parsed: MetricSample[] = [];
215
+ for (const line of text.split("\n")) {
216
+ if (!line) continue;
79
217
  try {
80
218
  const s = JSON.parse(line) as MetricSample;
81
- if ((s?.kind === "hook" || s?.kind === "search") && typeof s.at === "string") out.push(s);
219
+ if ((s?.kind === "hook" || s?.kind === "search") && typeof s.at === "string") parsed.push(s);
82
220
  } catch { /* a malformed line is skipped */ }
83
221
  }
84
- return out;
222
+ return newestPerKind(parsed, limit, sample => sample.kind);
223
+ }
224
+
225
+ /**
226
+ * #485: a plain metrics file, read whole. The open is non-blocking and never follows a symlink, so a fifo that would
227
+ * hold a reader, or anything else that is not a plain file, is answered as absent instead of waited on.
228
+ */
229
+ function readMetricsText(file: string): string | undefined {
230
+ let fd: number | undefined;
231
+ try { fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); } catch { return undefined; }
232
+ try {
233
+ const stat = fstatSync(fd);
234
+ if (!stat.isFile()) return undefined;
235
+ const bytes = Buffer.alloc(stat.size);
236
+ let length = 0;
237
+ for (;;) {
238
+ const read = readSync(fd, bytes, length, bytes.length - length, length);
239
+ if (read <= 0) break;
240
+ length += read;
241
+ }
242
+ return new TextDecoder("utf-8").decode(bytes.subarray(0, length));
243
+ } catch { return undefined; } finally { closeSync(fd); }
85
244
  }
86
245
 
87
246
 
@@ -0,0 +1,28 @@
1
+ import { lstatSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { isAbsolute, join, relative, sep } from "node:path";
4
+ import { ownedUnwritableDirectory, realPath } from "./platform.ts";
5
+
6
+ export type NativeRootKind = "sessions" | "archived_sessions";
7
+ export type NativeRootStatus = { state: "ready"; path: string } | { state: "unsafe" | "unavailable" };
8
+
9
+ /** Only a symlink at the named root receives this exception; callers still refuse links beneath it. */
10
+ export function inspectNativeRoot(folder: string, home = process.env.HOME?.trim() || homedir()): NativeRootStatus {
11
+ let link = false;
12
+ try {
13
+ link = lstatSync(folder).isSymbolicLink();
14
+ const physical = realPath(folder);
15
+ if (link) {
16
+ const root = realPath(home), rel = relative(root, physical);
17
+ if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel) || !ownedUnwritableDirectory(physical)) return { state: "unsafe" };
18
+ }
19
+ return { state: "ready", path: physical };
20
+ } catch { return { state: link ? "unsafe" : "unavailable" }; }
21
+ }
22
+
23
+ export function nativeRoots(kind: "codex" | "kimi" | "pi", env: NodeJS.ProcessEnv = process.env, home = env.HOME?.trim() || homedir()): { kind: NativeRootKind; folder: string }[] {
24
+ const root = kind === "codex" ? env.CODEX_HOME?.trim() || join(home, ".codex")
25
+ : kind === "kimi" ? env.KIMI_CODE_HOME?.trim() || join(home, ".kimi-code")
26
+ : env.PI_CODING_AGENT_DIR?.trim() || join(home, ".pi", "agent");
27
+ return [{ kind: "sessions", folder: join(root, "sessions") }, ...(kind === "codex" ? [{ kind: "archived_sessions" as const, folder: join(root, "archived_sessions") }] : [])];
28
+ }
@@ -1,5 +1,5 @@
1
1
  // Single-source platform helpers. Hub, local and Pi modules re-export these functions unchanged.
2
- import { realpathSync } from "node:fs";
2
+ import { lstatSync, realpathSync } from "node:fs";
3
3
  import { basename, dirname, join, resolve, sep } from "node:path";
4
4
  import type { SpawnSyncOptions, SpawnSyncOptionsWithBufferEncoding, SpawnSyncOptionsWithStringEncoding, SpawnSyncReturns } from "node:child_process";
5
5
  import { createRequire } from "node:module";
@@ -47,6 +47,14 @@ export function realPath(path: string): string {
47
47
  return r.stdout.slice(0, -1);
48
48
  }
49
49
 
50
+ /** An existing physical directory must belong to this user and resist group/world writes. */
51
+ export function ownedUnwritableDirectory(path: string): boolean {
52
+ try {
53
+ const stat = lstatSync(path), uid = process.getuid?.();
54
+ return uid !== undefined && stat.isDirectory() && !stat.isSymbolicLink() && stat.uid === uid && (stat.mode & 0o022) === 0;
55
+ } catch { return false; }
56
+ }
57
+
50
58
  /** One denylist for core extraction, hub path guards, sandbox rules and capture. */
51
59
  // `.agenthub/archive` holds reset state directories, including task text and PII.
52
60
  export const DENY_SEGMENTS = [".maru/secrets", ".agenthub/state", ".agenthub/archive"];
@@ -0,0 +1,69 @@
1
+ import type { View } from "./store.ts";
2
+ import type { MemoryUseSummary } from "./use-telemetry.ts";
3
+ import type { Counter } from "./candidates.ts";
4
+ import { summarizeMemoryUse } from "./use-telemetry.ts";
5
+ import { Database } from "bun:sqlite";
6
+ import { lstatSync } from "node:fs";
7
+ import { join } from "node:path";
8
+
9
+ export type ReviewReason = "stale" | "rendered" | "volatile";
10
+ export interface ReviewTarget { id: string; reason: ReviewReason; ageDays: number; counts: MemoryUseSummary }
11
+ export interface ReviewTargetOptions {
12
+ now: number; recheckDays: number; limit: number;
13
+ stale: (view: View) => boolean | undefined;
14
+ use: (view: View) => MemoryUseSummary;
15
+ /** False when a retained decided candidate was created inside the window. */
16
+ eligibleForRecheck: (view: View, cutoff: number) => boolean;
17
+ }
18
+
19
+ export const REVIEW_DEFAULTS = { recheck_days: 30, unused_rendered: 20, unused_days: 30 } as const;
20
+ export interface ReviewSnapshot { counters: Counter[]; decided: { at: number; targets: string[] }[] }
21
+ /** Read the sidecar without opening the writer, pruning, or altering the schema. */
22
+ export function readReviewSnapshot(home: string, projects: readonly string[]): ReviewSnapshot {
23
+ const file = join(home, "candidates.db"), stat = lstatSync(file, { throwIfNoEntry: false });
24
+ if (!stat) return { counters: [], decided: [] };
25
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1) throw Error("review history unavailable: candidate database is not a private regular file; inspect the memory home before retrying");
26
+ const db = new Database(file, { readonly: true });
27
+ try {
28
+ db.run("PRAGMA busy_timeout = 0");
29
+ const scope = JSON.stringify(projects);
30
+ const counters = (db.query("SELECT id,payload,at,rendered,delivered,cited FROM counters WHERE project IN (SELECT value FROM json_each(?)) ORDER BY id").all(scope) as { id: string; payload: string; at: number; rendered: number | null; delivered: number | null; cited: number | null }[])
31
+ .map(row => ({ id: row.id, key: JSON.parse(row.payload), createdAt: new Date(row.at).toISOString(), rendered: row.rendered, delivered: row.delivered, cited: row.cited }));
32
+ const decided = (db.query("SELECT at,payload FROM candidates WHERE project IN (SELECT value FROM json_each(?)) AND status IN ('accepted','rejected') ORDER BY at,id").all(scope) as { at: number; payload: string }[]).map(row => {
33
+ const input = JSON.parse(row.payload) as { target?: { id?: string }; targets?: { id?: string }[] };
34
+ return { at: row.at, targets: [input.target?.id, ...(input.targets ?? []).map(target => target.id)].filter((id): id is string => typeof id === "string") };
35
+ });
36
+ return { counters, decided };
37
+ } finally { db.close(); }
38
+ }
39
+
40
+ export function reviewUse(snapshot: ReviewSnapshot, project: readonly string[], id: string, since = -Infinity): MemoryUseSummary {
41
+ return summarizeMemoryUse(snapshot.counters.filter(row => project.includes(row.key.project) && row.key.entryId === id && Date.parse(row.createdAt) >= since));
42
+ }
43
+
44
+ /** ponytail: candidate creation time approximates decision time; add a decision timestamp if over-listing proves material. */
45
+ export function noRecentReview(snapshot: ReviewSnapshot, id: string, cutoff: number): boolean {
46
+ return !snapshot.decided.some(row => row.at >= cutoff && row.targets.includes(id));
47
+ }
48
+
49
+ /** Pure selection over a caller-supplied snapshot. The caller supplies policy-screened views and read-only telemetry. */
50
+ export function reviewTargets(views: readonly View[], options: ReviewTargetOptions): ReviewTarget[] {
51
+ const { now, recheckDays, limit } = options;
52
+ if (!Number.isFinite(now) || !Number.isSafeInteger(recheckDays) || recheckDays < 1 || !Number.isSafeInteger(limit) || limit < 1 || limit > 500)
53
+ throw Error("invalid review target window or limit; use a positive recheck window and a limit from 1 to 500");
54
+ const cutoff = now - recheckDays * 86400_000;
55
+ const rows: ReviewTarget[] = [];
56
+ for (const view of views) {
57
+ const at = Date.parse(view.at);
58
+ if (!Number.isFinite(at) || at > now || view.supersededBy) continue;
59
+ const counts = options.use(view), ageDays = Math.floor((now - at) / 86400_000);
60
+ const reason: ReviewReason | undefined = options.stale(view) === true ? "stale"
61
+ : counts.rendered !== null && counts.rendered > 0 && options.eligibleForRecheck(view, cutoff) ? "rendered"
62
+ : (view.kind === "decision" || view.kind === "contract") && at < cutoff ? "volatile" : undefined;
63
+ if (reason) rows.push({ id: view.id, reason, ageDays, counts });
64
+ }
65
+ const rank: Record<ReviewReason, number> = { stale: 0, rendered: 1, volatile: 2 };
66
+ return rows.sort((a, b) => rank[a.reason] - rank[b.reason]
67
+ || (a.reason === "rendered" ? (b.counts.rendered ?? 0) - (a.counts.rendered ?? 0) : b.ageDays - a.ageDays)
68
+ || a.id.localeCompare(b.id)).slice(0, limit);
69
+ }
@@ -1,12 +1,20 @@
1
- import { inspectLegacySnapshot, readLegacySnapshot, type LegacySegmentInspector, type LegacyCheckpoint, type LegacySegment, type LegacySnapshotOptions } from "./bridge.ts";
1
+ import { inspectLegacySnapshot, legacySnapshotSteps, type LegacySegmentInspector, type LegacyCheckpoint, type LegacySegment, type LegacySnapshotOptions } from "./bridge.ts";
2
+ import { drainSteps } from "./sync-placement-yield.ts";
2
3
  import type { BoundProfile } from "./generation.ts";
3
4
 
4
5
  /** Copied bridge roots keep their original birth realm; no foreign project root is scanned. */
5
6
  export function readShardLegacySnapshot(profile: BoundProfile, options: Pick<LegacySnapshotOptions, "checkpoints" | "limits" | "reader" | "incremental">, inspect?: LegacySegmentInspector): LegacySegment[] {
7
+ return drainSteps(shardLegacySnapshotSteps(profile, options, inspect));
8
+ }
9
+ /** #462: one collector for both curated halves, so a caller that yields reads the public bridge in its own turns too. */
10
+ export function* shardLegacySnapshotSteps(profile: BoundProfile, options: Pick<LegacySnapshotOptions, "checkpoints" | "limits" | "reader" | "incremental">, inspect?: LegacySegmentInspector): Generator<void, LegacySegment[], void> {
6
11
  const local = (rows: readonly LegacyCheckpoint[] | undefined) => rows?.filter(row => row.source === "legacy-local");
7
12
  const main = (rows: readonly LegacyCheckpoint[] | undefined) => rows?.filter(row => row.source === "legacy-main").map(row => ({ ...row, source: "legacy-local", commit: undefined }));
8
- const read = (home: string, input: LegacySnapshotOptions, visitor = inspect) => visitor ? inspectLegacySnapshot(home, input, visitor) : readLegacySnapshot(home, input);
9
- const result = read(profile.legacyHome ?? profile.home, {
13
+ let result: LegacySegment[];
14
+ if (inspect) result = inspectLegacySnapshot(profile.legacyHome ?? profile.home, {
15
+ ...options, checkpoints: local(options.checkpoints), ...(options.limits ? { limits: local(options.limits) } : {}),
16
+ }, inspect);
17
+ else result = yield* legacySnapshotSteps(profile.legacyHome ?? profile.home, {
10
18
  ...options, checkpoints: local(options.checkpoints), ...(options.limits ? { limits: local(options.limits) } : {}),
11
19
  });
12
20
  if (!profile.legacyMainHome) {
@@ -17,8 +25,12 @@ export function readShardLegacySnapshot(profile: BoundProfile, options: Pick<Leg
17
25
  const result = inspect(file, { ...context, source: "legacy-main" }, prior);
18
26
  return { ...result, source: context.source };
19
27
  } : undefined;
20
- const publicRows = read(profile.legacyMainHome, {
28
+ let publicRows: LegacySegment[];
29
+ if (publicInspector) publicRows = inspectLegacySnapshot(profile.legacyMainHome, {
21
30
  ...options, checkpoints: main(options.checkpoints), ...(options.limits ? { limits: main(options.limits) } : {}),
22
- }, publicInspector).map(segment => ({ ...segment, source: "legacy-main" }));
23
- return [...result, ...publicRows];
31
+ }, publicInspector);
32
+ else publicRows = yield* legacySnapshotSteps(profile.legacyMainHome, {
33
+ ...options, checkpoints: main(options.checkpoints), ...(options.limits ? { limits: main(options.limits) } : {}),
34
+ });
35
+ return [...result, ...publicRows.map(segment => ({ ...segment, source: "legacy-main" }))];
24
36
  }
@@ -1,3 +1,6 @@
1
+ import { readActivePlacementBinding } from "./sync-placement-active.ts";
2
+ import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
3
+ import { PLACEMENT_PROFILE_SCHEMA, PLACEMENT_SHARDS_SCHEMA } from "./sync-placement-format.ts";
1
4
  import { createHash, randomBytes } from "node:crypto";
2
5
  import { appendFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
3
6
  import { dirname, join, relative } from "node:path";
@@ -469,7 +472,17 @@ const refusalSummary = (value: ShardMigrationCounts) => {
469
472
  const removalEvidence = (journal: ShardJournal | undefined) => journal?.deadLeasesRemoved?.length ? { deadLeasesRemoved: journal.deadLeasesRemoved } : {};
470
473
 
471
474
  export function shardMigrationStatus(memoryDir: string): { active: boolean; generation?: string; phase?: "captured" | "active"; pending: ShardMigrationCounts; deadLeasesRemoved?: DeadLeaseRemoval[]; refusals?: string[] } {
472
- const dir = existsSync(memoryDir) ? realPath(memoryDir) : canonicalPath(memoryDir), journal = readJournal(dir, true);
475
+ const dir = existsSync(memoryDir) ? realPath(memoryDir) : canonicalPath(memoryDir);
476
+ const marker = readProfileJSON(join(dir, JOURNAL)) as { schema?: unknown } | undefined;
477
+ // Probe only the profile schema: a legacy malformed selector keeps its original status path.
478
+ let profileSchema: unknown;
479
+ try { profileSchema = (readProfileJSON(join(dir, "profile.json")) as { schema?: unknown } | undefined)?.schema; } catch { /* Legacy status never read this selector. */ }
480
+ let journal: ShardJournal | undefined;
481
+ if (marker?.schema === PLACEMENT_SHARDS_SCHEMA || profileSchema === PLACEMENT_PROFILE_SCHEMA) {
482
+ const markers = readPlacementRuntimeMarkers(dir), active = readActivePlacementBinding(dir, markers.profile, markers.shards);
483
+ if (!active) throw new Error("sync placement activation metadata unavailable or changed; inspect the retained activation before continuing");
484
+ journal = { ...active.shards, schema: SHARDED_V2_SCHEMA };
485
+ } else journal = readJournal(dir, true);
473
486
  if (!journal) return { active: false, pending: emptyCounts() };
474
487
  const plan = route(capture(dir, journal.generation, journal), journal.sources, true);
475
488
  return { active: journal.phase === "active", phase: journal.phase, generation: journal.generation, pending: counts(plan), ...refusalSummary(plan), ...removalEvidence(journal) };
@@ -6,6 +6,7 @@ import { canonicalJSON, validGeneration } from "./generation.ts";
6
6
  import { validatePruneRow, type PruneRow } from "./prune.ts";
7
7
  import { shardKeyHash } from "./shard.ts";
8
8
  import { validatePublicPruneWitness, type PublicPruneWitnessV1 } from "./public-prune-witness.ts";
9
+ import { drainSteps, drainStepsAsync, type CooperativeYield } from "./sync-placement-yield.ts";
9
10
  import type { Entry } from "./store.ts";
10
11
 
11
12
  export type ShardSyncRealm = { scope: "project"; key: string } | { scope: "user" };
@@ -105,9 +106,24 @@ function collision(seen: Map<string, string>, row: ShardSyncRow, line: string, l
105
106
 
106
107
  /** Content-addressed immutable packs retain original attribution, ids and even repeated identical input rows. */
107
108
  export function encodeShardPacks(rows: readonly ShardSyncRow[]): Map<string, Buffer> {
109
+ return drainSteps(encodeShardPacksSteps(rows));
110
+ }
111
+
112
+ /** #470: the same packs, handing the caller's event loop back between row chunks; pack paths and bytes are identical. */
113
+ export async function encodeShardPacksAsync(rows: readonly ShardSyncRow[], yieldPoint?: CooperativeYield): Promise<Map<string, Buffer>> {
114
+ return await drainStepsAsync(encodeShardPacksSteps(rows), yieldPoint);
115
+ }
116
+
117
+ /** Rows between step boundaries: one row's own canonicalization and id check is the floor of an uninterrupted stretch. */
118
+ const SHARD_PACK_STEP_ROWS = 64;
119
+
120
+ /** #462: the step form itself, so a caller that owns a collector can drive the encoder inside its own turns. */
121
+ export function* encodeShardPacksSteps(rows: readonly ShardSyncRow[]): Generator<void, Map<string, Buffer>, void> {
108
122
  const groups = new Map<string, { id: string; line: string }[]>(), seen = new Map<string, string>();
109
123
  const label = "shard pack";
124
+ let stepped = 0;
110
125
  for (const input of rows) {
126
+ if (++stepped >= SHARD_PACK_STEP_ROWS) { stepped = 0; yield; }
111
127
  let line: string;
112
128
  if (!input || typeof input !== "object" || Array.isArray(input) || typeof input.id !== "string") throw new ShardSyncFormatError(label, "invalid public row");
113
129
  try { line = canonicalJSON(input); } catch { throw new ShardSyncFormatError(label, "invalid public row"); }
@@ -120,6 +136,7 @@ export function encodeShardPacks(rows: readonly ShardSyncRow[]): Map<string, Buf
120
136
  }
121
137
  const packs = new Map<string, Buffer>();
122
138
  for (const machine of [...groups.keys()].sort()) {
139
+ yield;
123
140
  const group = groups.get(machine)!; group.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
124
141
  let parts: string[] = [], bytes = 0;
125
142
  const publish = () => {
@@ -130,6 +147,7 @@ export function encodeShardPacks(rows: readonly ShardSyncRow[]): Map<string, Buf
130
147
  packs.set(path, body); parts = []; bytes = 0;
131
148
  };
132
149
  for (const row of group) {
150
+ if (++stepped >= SHARD_PACK_STEP_ROWS) { stepped = 0; yield; }
133
151
  const size = Buffer.byteLength(row.line);
134
152
  if (bytes + size > SHARD_PACK_MAX_BYTES) publish();
135
153
  parts.push(row.line); bytes += size;
@@ -17,7 +17,8 @@ import { acquireMutation, assertMutationHandle, type MutationHandle } from "./mu
17
17
  import { realPath } from "./platform.ts";
18
18
  import { reducePruneRows, validatePrunePlan, validatePruneRow, type PrunePlan, type PruneRow, type PruneSnapshot, type PruneSourceRow } from "./prune.ts";
19
19
  import { assertCuratedShardPaths, isLocalKey, resolveShardProfile } from "./shard.ts";
20
- import { decodeShardPack, encodeShardPacks, decodeShardDescriptor, decodeShardManifest, encodeShardManifest, isShardManifestPath, SHARD_PACK_MAX_BYTES, ShardSyncFormatError, shardSyncDescriptor, shardSyncLabel, shardSyncRef, type ShardSyncRealm, type ShardSyncRow } from "./shard-sync-format.ts";
20
+ import { decodeShardPack, encodeShardPacks, encodeShardPacksSteps, decodeShardDescriptor, decodeShardManifest, encodeShardManifest, isShardManifestPath, SHARD_PACK_MAX_BYTES, ShardSyncFormatError, shardSyncDescriptor, shardSyncLabel, shardSyncRef, type ShardSyncRealm, type ShardSyncRow } from "./shard-sync-format.ts";
21
+ import { cooperativeYield, drainSteps, drainStepsAsync, type CooperativeYield } from "./sync-placement-yield.ts";
21
22
  import { generationSyncGit, generationSyncGitBytes, remoteVisibility, shardSyncBinding, shardSyncSourceBinding, type SyncOptions, type SyncResult } from "./sync.ts";
22
23
  import type { Entry, MemoryStore } from "./store.ts";
23
24
 
@@ -36,6 +37,8 @@ type SyncManifest = { path: string; bytes: Buffer; value: unknown; row: PruneRow
36
37
  type Target = { store: MemoryStore; realm: ShardSyncRealm; rows: Map<string, ShardSyncRow>; fetched: Set<string>; sources: PruneSourceRow[]; pending: PendingPrune[]; origins: Map<string, HoldSource>; holds: Hold[]; generation: string; manifests: Map<string,SyncManifest>; eligible: Set<string>; mutation?: MutationHandle; batch?: PublicPruneInputBatch; registered: PublicPruneInputV1[]; selectorChecks?: (()=>void)[]; local?: string; remote?: string; commit?: string };
37
38
  class SyncRefusal extends Error {}
38
39
  function refuse(reason: string): never { throw new SyncRefusal(reason); }
40
+ /** #462: an authored source changed under the collector's own yield; the placement transport reports `source-selection`. */
41
+ export class ShardSourceChangedError extends SyncRefusal {}
39
42
  function directory(path: string): void {
40
43
  const stat = lstatSync(path);
41
44
  if (!stat.isDirectory() || stat.isSymbolicLink()) refuse("shard sync requires independent private directories");
@@ -255,7 +258,24 @@ function* lines(file: string, claim?: PendingPrune): Generator<string> {
255
258
  || named.dev !== before.dev || named.ino !== before.ino || offset !== before.size) refuse("shard sync authored segment changed or has an incomplete tail");
256
259
  } finally { closeSync(fd); }
257
260
  }
258
- function sourceRows(store: MemoryStore, realm: ShardSyncRealm): { rows: ShardSyncRow[]; sources: PruneSourceRow[]; pending: PendingPrune[] } {
261
+ type SourceRows = { rows: ShardSyncRow[]; sources: PruneSourceRow[]; pending: PendingPrune[] };
262
+ /** Physical identity of one authored file or directory, as native metadata only: no byte is re-read to prove it. */
263
+ const sourceStamp = (path: string): string => {
264
+ const entry = lstatSync(path, { bigint: true, throwIfNoEntry: false });
265
+ return entry ? [entry.mode, entry.dev, entry.ino, entry.size, entry.mtimeNs, entry.ctimeNs].map(String).join(":") : "";
266
+ };
267
+ /** A directory's own listing is part of its identity: a new segment changes the names, an append changes the stamp. */
268
+ const sourceListing = (path: string): string => {
269
+ const entry = lstatSync(path, { bigint: true, throwIfNoEntry: false });
270
+ return entry && entry.isDirectory() && !entry.isSymbolicLink() ? `${sourceStamp(path)}|${readdirSync(path).sort().join("\n")}` : "";
271
+ };
272
+ /**
273
+ * #462: one collector, drained synchronously by `sourceRows` and in the caller's own turns by `shardSourceRowsAsync`.
274
+ * The wire round trip is the fence that proves the exported prefix, so a drive that yields inside it re-proves the same
275
+ * authored metadata afterwards: a changed segment, listing or pending claim refuses instead of exporting rows read earlier.
276
+ */
277
+ function* sourceRowsSteps(store: MemoryStore, realm: ShardSyncRealm): Generator<void, SourceRows, void> {
278
+ yield;
259
279
  const pending = pendingPrunes(store, realm), claims = new Map(pending.filter(claim=>!claim.unclaimed).map(claim => [`${claim.row.machine}.jsonl`, claim]));
260
280
  const snapshot = store.prunePort().snapshot();
261
281
  const pruned = new Set(snapshot.pruned ?? []);
@@ -263,9 +283,28 @@ function sourceRows(store: MemoryStore, realm: ShardSyncRealm): { rows: ShardSyn
263
283
  // A local tombstone must prevent the first publication of an unwitnessed original.
264
284
  const rows: ShardSyncRow[] = snapshot.rows.filter(source => source.placement === "synced" && (source.publicWitness || !pruned.has(source.row.id))).map(source => source.row);
265
285
  const folder = join(store.dir, "log"); directory(folder);
286
+ // Every authored input the index snapshot was derived from is stamped before any yield, so the re-proof covers the
287
+ // sources of `rows` and `sources` as well as the segments this collector parses itself.
288
+ const stamps: { change: "segment" | "claim" | "listing"; read: () => string; seen: string }[] = [];
289
+ const watch = (change: "segment" | "claim" | "listing", read: () => string) => stamps.push({ change, read, seen: read() });
290
+ for (const path of [folder, join(store.dir, "local")]) {
291
+ watch("listing", () => sourceListing(path));
292
+ if (!lstatSync(path, { throwIfNoEntry: false })) continue;
293
+ for (const name of readdirSync(path)) if (name.endsWith(".jsonl")) watch("segment", () => sourceStamp(join(path, name)));
294
+ }
295
+ const plans = join(store.dir, "prune-plans");
296
+ watch("claim", () => sourceListing(plans));
297
+ if (lstatSync(plans, { throwIfNoEntry: false })) for (const name of readdirSync(plans)) watch("claim", () => sourceStamp(join(plans, name)));
298
+ const changed = () => {
299
+ const found = stamps.find(stamp => stamp.read() !== stamp.seen);
300
+ if (!found) return;
301
+ const source = found.change === "segment" ? "authored segment" : found.change === "claim" ? "pending prune" : "realm listing";
302
+ throw new ShardSourceChangedError(`${shardSyncLabel(realm)}: ${source} changed during the preflight round trip`);
303
+ };
266
304
  for (const name of readdirSync(folder).sort()) {
267
305
  if (!name.endsWith(".jsonl")) continue;
268
306
  if (!/^[A-Za-z0-9][A-Za-z0-9._-]*\.jsonl$/.test(name)) refuse(`${shardSyncLabel(realm)}: invalid authored segment name`);
307
+ yield;
269
308
  for (const line of lines(join(folder, name), claims.get(name))) {
270
309
  const value = JSON.parse(line) as { schema?: unknown; op?: unknown };
271
310
  if (value.schema === "agent-mem.prune/v1") {
@@ -276,9 +315,14 @@ function sourceRows(store: MemoryStore, realm: ShardSyncRealm): { rows: ShardSyn
276
315
  }
277
316
  }
278
317
  // Round-trip public originals through the wire validator before touching remote refs or imported rows.
279
- for (const [path, bytes] of encodeShardPacks(rows)) decodeShardPack(path, bytes, realm, store.profile.generation!);
318
+ const packs = yield* encodeShardPacksSteps(rows);
319
+ for (const [path, bytes] of packs) { yield; decodeShardPack(path, bytes, realm, store.profile.generation!); }
320
+ changed();
280
321
  return { rows, sources: [...snapshot.rows], pending };
281
322
  }
323
+ function sourceRows(store: MemoryStore, realm: ShardSyncRealm): SourceRows {
324
+ return drainSteps(sourceRowsSteps(store, realm));
325
+ }
282
326
  function provePrunes(targets: readonly Target[]): void {
283
327
  for (const target of targets) {
284
328
  for (const pending of target.pending) {
@@ -740,6 +784,10 @@ export async function syncShardedMemory(store: MemoryStore, opts: SyncOptions =
740
784
  // These are deliberately absent from the package barrel: validation and complete fetched-proof preflight stay mandatory.
741
785
  export type { Target as ShardSyncApplicationTarget, PendingPrune as ShardSyncPendingPrune, HoldSource as ShardSyncHoldSource,
742
786
  HoldReceipt as ShardSyncHoldReceipt, Hold as ShardSyncHold, SyncPhase as ShardSyncApplicationPhase,
743
- SyncManifest as ShardSyncApplicationManifest, ProveHoldSource as ShardSyncProveHoldSource };
787
+ SyncManifest as ShardSyncApplicationManifest, ProveHoldSource as ShardSyncProveHoldSource, SourceRows as ShardSyncSourceRows };
744
788
  export { sourceRows as shardSourceRows, provePrunes as shardProvePrunes, importRows as shardImportRows,
745
789
  selectorRetention as shardSelectorRetention, prepareHolds as shardPrepareHolds, installHold as shardInstallHold, holdWarning as shardHoldWarning };
790
+ /** #462: the same collector, handing the caller's event loop back between its steps; rows and refusals are identical. */
791
+ export function shardSourceRowsAsync(store: MemoryStore, realm: ShardSyncRealm, pause: CooperativeYield = cooperativeYield()): Promise<SourceRows> {
792
+ return drainStepsAsync(sourceRowsSteps(store, realm), pause);
793
+ }
@@ -35,6 +35,10 @@ export function shardKeyHash(key: string): string {
35
35
  /** A key in the no-remote path-hash form (`chain@hash8`) is this machine's only; the catalog flags it. */
36
36
  export const isLocalKey = (key: string): boolean => /.+@[0-9a-f]{8}$/.test(key);
37
37
 
38
+ export function localKeyOptInMessage(key: string): string {
39
+ return `Local project ${JSON.stringify(key)} requires an explicit amem sync --remote <url> opt-in, or run amem project archive with that project key.`;
40
+ }
41
+
38
42
  export function shardDir(base: string, key: string): string {
39
43
  return join(base, "projects", shardKeyHash(key));
40
44
  }
@@ -206,6 +206,8 @@ export type PromotionScreen = (v: View) => "promote" | "keep" | "skip";
206
206
  * went) wait for a process that has one; a person's explicit promote goes through.
207
207
  */
208
208
  export interface StoreOptions { home?: string; memoryDir?: string; ttlMs?: number; now?: () => number; log?: (line: string) => void; screen?: PromotionScreen; deferPromotions?: boolean; profile?: ProfileInput;
209
+ /** A trusted host's processSignature(process.pid) for this process, measured outside a sandbox that cannot run ps. */
210
+ readerLeaseSignature?: string;
209
211
  /** #15 T5: `openShardStore` refuses a project the person archived or forgot unless the caller says `ignore` (the catalog, `--include-archived` reads and export do, on purpose). */
210
212
  lifecycle?: "enforce" | "ignore";
211
213
  /** #27: read the `aliases` keys' curated rows as part of the `canonical` project (CLI and MCP only); the library default reads the raw key. Rows are presented under `canonical`. */
@@ -279,7 +281,7 @@ export class MemoryStore {
279
281
  this.screen = opts.screen;
280
282
  this.deferPromotions = opts.deferPromotions ?? false;
281
283
  // Announce before opening derived handles or reading rows; failed admission leaks no database handles.
282
- if (!bootstrap || bootstrap.authoring === true) this.releaseReaderLease = registerReaderLease(this.profile.home, this.profile.sharded ? {scope:"shard"} : {});
284
+ if (!bootstrap || bootstrap.authoring === true) this.releaseReaderLease = registerReaderLease(this.profile.home, { ...(this.profile.sharded ? { scope: "shard" as const } : {}), ...(opts.readerLeaseSignature === undefined ? {} : { signature: opts.readerLeaseSignature }) });
283
285
  let openedDb: Database | undefined, openedMutation: Database | undefined, openedSearch: SearchIndex | undefined;
284
286
  try {
285
287
  const indexFile = join(this.dir, indexFileName(!!this.profile.foreignPruneFormat));
@@ -1950,7 +1952,7 @@ export function openShardStore(opts: StoreOptions & { project?: string; user?: b
1950
1952
  // Lifecycle refusal must remain before admission creates any lease/fence file.
1951
1953
  if (opts.user !== true && opts.lifecycle !== "ignore") assertProjectActive(home, opts.project!);
1952
1954
  readShardedSelection(home); // validate the floor before any lazy shard initialization
1953
- const admission = registerReaderLease(home, {scope:"shard"});
1955
+ const admission = registerReaderLease(home, {scope:"shard", ...(opts.readerLeaseSignature === undefined ? {} : { signature: opts.readerLeaseSignature })});
1954
1956
  try {
1955
1957
  const dir = opts.user === true ? userShardDir(home) : shardDir(home, opts.project!);
1956
1958
  const missing = !existsSync(join(dir, "generation.json"));