@staix/agent-mem 0.33.0 → 0.35.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 (50) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +4 -2
  3. package/package.json +2 -1
  4. package/skills/_shared/amem-adapter.md +10 -0
  5. package/skills/amem-ops/SKILL.md +15 -0
  6. package/skills/amem-recall/SKILL.md +13 -0
  7. package/skills/amem-remember/SKILL.md +13 -0
  8. package/skills/amem-review/SKILL.md +14 -0
  9. package/skills/amem-status/SKILL.md +12 -0
  10. package/src/amem-read-tools.ts +20 -0
  11. package/src/cli.ts +50 -12
  12. package/src/commands-table.ts +3 -2
  13. package/src/hook-jcode-journal.ts +8 -2
  14. package/src/hook-spool.ts +5 -0
  15. package/src/hooks.ts +16 -3
  16. package/src/index.ts +2 -0
  17. package/src/mcp-memory.ts +73 -15
  18. package/src/mcp.ts +2 -2
  19. package/src/memory/binding-read-set.ts +18 -0
  20. package/src/memory/capacity.ts +7 -3
  21. package/src/memory/commands.ts +19 -7
  22. package/src/memory/doctor.ts +26 -2
  23. package/src/memory/home-binding-fence.ts +97 -0
  24. package/src/memory/intent-brief.ts +26 -11
  25. package/src/memory/intent-node-matcher.ts +62 -0
  26. package/src/memory/metrics.ts +75 -28
  27. package/src/memory/profile-lock-diagnostic.ts +5 -5
  28. package/src/memory/public-prune-input-chain.ts +4 -1
  29. package/src/memory/public-prune-view.ts +6 -1
  30. package/src/memory/recall-staleness.ts +18 -7
  31. package/src/memory/shard-sync-history.ts +27 -6
  32. package/src/memory/shard.ts +1 -1
  33. package/src/memory/sync-placement-activation.ts +2 -2
  34. package/src/memory/sync-placement-active.ts +4 -1
  35. package/src/memory/sync-placement-bound.ts +1 -1
  36. package/src/memory/sync-placement-capture.ts +17 -6
  37. package/src/memory/sync-placement-checkpoint-person.ts +26 -4
  38. package/src/memory/sync-placement-checkpoint-prospective.ts +5 -1
  39. package/src/memory/sync-placement-guard.ts +17 -2
  40. package/src/memory/sync-placement-inspection-evidence.ts +17 -6
  41. package/src/memory/sync-placement-inspection.ts +2 -2
  42. package/src/memory/sync-placement-prerequisites.ts +1 -1
  43. package/src/memory/sync-placement-refusal.ts +1 -1
  44. package/src/memory/sync-placement-writer-renewal.ts +1 -1
  45. package/src/memory/sync-placement-writer-revision-format.ts +3 -3
  46. package/src/session-brief.ts +47 -7
  47. package/src/setup.ts +62 -11
  48. package/src/skills-install.ts +241 -0
  49. package/src/sync-placement-writer-context.ts +94 -19
  50. package/src/ui/plugin.ts +1 -1
@@ -52,8 +52,13 @@ export interface RecordVariantMetric {
52
52
  recordValidRecords?: number; recordBasisRecords?: number; recordUnverifiedRecords?: number;
53
53
  recordInstructionInvalid?: number; recordInstructionEmitted?: number; recordBriefBytes?: number;
54
54
  }
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 }
56
- const METRICS_MAX_BYTES = 64 * 1024, METRICS_KEEP = 200;
55
+ /** All marks are process-local performance.now() milliseconds since the process time origin. */
56
+ export interface JcodeJournalTiming { scanStartMs?: number; scanEndMs?: number; workStartMs?: number; publishStartMs?: number; publishEndMs?: number; publishTotalMs?: number; workerSpawnStartMs?: number; workerSpawnEndMs?: number; cursorCloseStartMs?: number; cursorCloseEndMs?: number; metricSampleAtMs?: number }
57
+ export interface TranscriptTiming { killAtMs?: number; reapAtMs?: number; metricSampleAtMs: number }
58
+ export interface MetricSample extends RecordVariantMetric { jcodeJournalTiming?: JcodeJournalTiming; transcriptTiming?: TranscriptTiming; at: string; kind: "hook" | "search" | "mcp-phase"; /** #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; shared?: 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 }
59
+ const METRICS_MAX_BYTES = 128 * 1024, METRICS_KEEP = 200, MCP_PHASE_KEEP = 32;
60
+ // ponytail: reserve 17 KiB for future appends; upgrade to separate bounded files if these windows need larger guarantees.
61
+ const HOOK_BYTES = 74 * 1024, SEARCH_BYTES = 30 * 1024, PHASE_BYTES = 6 * 1024, OTHER_BYTES = 1024;
57
62
 
58
63
  /**
59
64
  * #485: the newest `limit` samples of each kind. Hook samples share this file with the read-tool samples a long-lived
@@ -63,22 +68,22 @@ function newestPerKind<T>(items: readonly T[], limit: number, kindOf: (item: T)
63
68
  const kept: T[] = [], seen = new Map<string, number>();
64
69
  for (let index = items.length - 1; index >= 0; index--) {
65
70
  const item = items[index]!, kind = kindOf(item), count = seen.get(kind) ?? 0;
66
- if (count >= limit) continue;
71
+ if (count >= (kind === "mcp-phase" ? Math.min(limit, MCP_PHASE_KEEP) : limit)) continue;
67
72
  seen.set(kind, count + 1); kept.push(item);
68
73
  }
69
74
  return kept.reverse();
70
75
  }
71
76
 
72
77
  /**
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.
78
+ * Process lifetime peak on the same basis as `scripts/budget-rss.ts`: VmHWM on Linux, maxRSS elsewhere.
79
+ * `undefined` when unavailable; telemetry never makes a call fail.
75
80
  */
76
81
  export function processPeakRssKB(): number | undefined {
77
82
  try { return processImageRssKB("self") ?? process.resourceUsage().maxRSS; } catch { return undefined; }
78
83
  }
79
84
 
80
85
  /** #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 }
86
+ export interface PeakWindow { alone: boolean; startPeak?: number; parent?: PeakWindow; gapKB?: number; gapMs?: number }
82
87
 
83
88
  /** A host that cannot report its peak must not turn a read into a failure, so a throwing read is `undefined`. */
84
89
  const peekOnce = (read: () => number | undefined): number | undefined => { try { return read(); } catch { return undefined; } };
@@ -91,34 +96,60 @@ const peekOnce = (read: () => number | undefined): number | undefined => { try {
91
96
  */
92
97
  export function createPeakTracker(read: () => number | undefined = processPeakRssKB) {
93
98
  const windows = new Set<PeakWindow>();
94
- let observed = peekOnce(read);
99
+ let observed = peekOnce(read), idleSince = performance.now();
95
100
  const peek = () => peekOnce(read);
96
101
  const advance = (peakKB: number) => { observed = observed === undefined ? peakKB : Math.max(observed, peakKB); };
97
102
  return {
98
- begin(): PeakWindow {
99
- const window: PeakWindow = { alone: windows.size === 0 };
100
- for (const other of windows) other.alone = false;
103
+ begin(parent?: PeakWindow): PeakWindow {
104
+ let gapKB: number | undefined;
105
+ if (windows.size === 0) { const current = peek(); if (current !== undefined) { if (observed !== undefined && current > observed) gapKB = current; advance(current); } }
106
+ const startPeak = windows.size === 0 ? observed : peek();
107
+ const window: PeakWindow = { alone: parent ? parent.alone && windows.size === 1 && windows.has(parent) : windows.size === 0, ...(startPeak === undefined ? {} : { startPeak }), ...(parent ? { parent } : {}), ...(gapKB === undefined ? {} : { gapKB, gapMs: Math.max(0, performance.now() - idleSince) }) };
108
+ for (const other of windows) if (other !== parent) other.alone = false;
101
109
  windows.add(window);
102
110
  return window;
103
111
  },
104
112
  /** 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 } {
113
+ end(window: PeakWindow): { peakKB?: number; raised: boolean; shared?: true } {
106
114
  windows.delete(window);
115
+ if (windows.size === 0) idleSince = performance.now();
107
116
  const peakKB = peek();
108
117
  if (peakKB === undefined) return { raised: false };
109
- const raised = window.alone && (observed === undefined || peakKB > observed);
118
+ const raised = window.alone && observed !== undefined && peakKB > observed;
119
+ const shared = !window.alone && window.startPeak !== undefined && peakKB > window.startPeak;
120
+ if (raised && window.parent) window.parent.alone = false;
110
121
  advance(peakKB);
111
- return { peakKB, raised };
122
+ return { peakKB, raised, ...(shared ? { shared: true as const } : {}) };
112
123
  },
113
124
  /** The call refused or threw: it records nothing, but the peak still advances so a later call is not miscredited. */
114
125
  abort(window: PeakWindow): void {
115
126
  windows.delete(window);
127
+ if (windows.size === 0) idleSince = performance.now();
116
128
  const peakKB = peek();
117
129
  if (peakKB !== undefined) advance(peakKB);
118
130
  },
119
131
  };
120
132
  }
121
133
 
134
+ export type McpPhaseName = "startup" | "idle-gap" | "preload" | "construct" | "on-emitted" | "recall-prepare" | "amem_work_state_read" | "amem_work_state_write" | "amem_remember" | "amem_correct" | "amem_capacity" | `failed:${"amem_search" | "amem_evidence" | "amem_show" | "amem_timeline" | "amem_graph" | "amem_brief" | "amem_vault_candidates"}`;
135
+ export const MCP_PHASE_NAMES: readonly McpPhaseName[] = ["startup", "idle-gap", "preload", "construct", "on-emitted", "recall-prepare", "amem_work_state_read", "amem_work_state_write", "amem_remember", "amem_correct", "amem_capacity", "failed:amem_search", "failed:amem_evidence", "failed:amem_show", "failed:amem_timeline", "failed:amem_graph", "failed:amem_brief", "failed:amem_vault_candidates"];
136
+ export type PeakTracker = ReturnType<typeof createPeakTracker>;
137
+ /** A lifetime peak that rose between instrumented windows cannot be assigned to a tool. */
138
+ export function recordMcpGap(base: string, peakKB: number, wallMs: number): void {
139
+ try { appendMetricsLater(base, [{ at: new Date().toISOString(), kind: "mcp-phase", tool: "idle-gap", wallMs, rssMB: peakKB / 1024, peakRaised: false }]); } catch { /* observational only */ }
140
+ }
141
+ /** Fixed phase labels and asynchronous handoff only; never retain call input or result. */
142
+ export function observeMcpPhase(base: string, peaks: PeakTracker, name: McpPhaseName, parent?: PeakWindow): () => void {
143
+ const started = performance.now(); let window: PeakWindow | undefined;
144
+ try { window = peaks.begin(parent); if (window.gapKB !== undefined) recordMcpGap(base, window.gapKB, window.gapMs ?? 0); } catch { /* observational only */ }
145
+ return () => {
146
+ try {
147
+ if (!window) return;
148
+ const ended = peaks.end(window); window = undefined;
149
+ if (ended.peakKB !== undefined && (ended.raised || ended.shared)) appendMetricsLater(base, [{ at: new Date().toISOString(), kind: "mcp-phase", tool: name, wallMs: performance.now() - started, rssMB: ended.peakKB / 1024, peakRaised: ended.raised, ...(ended.shared ? { shared: true } : {}) }]);
150
+ } catch { /* observational only */ }
151
+ };
152
+ }
122
153
  export function metricsPath(base: string): string {
123
154
  return join(base, "metrics.jsonl");
124
155
  }
@@ -132,13 +163,22 @@ export function metricsPath(base: string): string {
132
163
  let trimGeneration = 0;
133
164
  /** The kept text of a trim: torn lines dropped, the newest METRICS_KEEP of each kind kept, oldest first. */
134
165
  function trimmedText(text: string): string {
135
- const rows: { line: string; kind: string }[] = [];
166
+ const rows: { line: string; kind: string; index: number; bytes: number }[] = [];
136
167
  for (const line of text.split("\n")) {
137
168
  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 */ }
169
+ try { const kind = (JSON.parse(line) as { kind?: unknown }).kind; rows.push({ line, kind: typeof kind === "string" ? kind : "other", index: rows.length, bytes: Buffer.byteLength(line) + 1 }); } catch { /* torn tail */ }
140
170
  }
141
- return newestPerKind(rows, METRICS_KEEP, row => row.kind).map(row => row.line).join("\n") + "\n";
171
+ const selected = newestPerKind(rows, METRICS_KEEP, row => row.kind);
172
+ const bounded = (items: typeof rows, cap: number) => {
173
+ const kept: typeof rows = []; let bytes = 0;
174
+ for (let i = items.length - 1; i >= 0; i--) { const row = items[i]!; if (bytes + row.bytes <= cap) { kept.push(row); bytes += row.bytes; } }
175
+ return kept;
176
+ };
177
+ return [...bounded(selected.filter(row => row.kind === "hook"), HOOK_BYTES),
178
+ ...bounded(selected.filter(row => row.kind === "search"), SEARCH_BYTES),
179
+ ...bounded(selected.filter(row => row.kind === "mcp-phase"), PHASE_BYTES),
180
+ ...bounded(selected.filter(row => row.kind !== "hook" && row.kind !== "search" && row.kind !== "mcp-phase"), OTHER_BYTES)]
181
+ .sort((a, b) => a.index - b.index).map(row => row.line + "\n").join("");
142
182
  }
143
183
 
144
184
  function trimMetrics(file: string): void {
@@ -160,10 +200,14 @@ function trimMetrics(file: string): void {
160
200
  * is refused before a byte is written. One worker drains the hand-offs in call order, so the file keeps the order the
161
201
  * calls completed in; a sample still in flight when the process exits is simply lost.
162
202
  */
163
- const pending: { base: string; samples: MetricSample[] }[] = [];
164
- let draining = false;
203
+ const pending: { base: string; samples: MetricSample[]; phase: boolean }[] = [];
204
+ let draining = false, pendingPhases = 0;
165
205
  export function appendMetricsLater(base: string, samples: MetricSample[]): void {
166
- pending.push({ base, samples });
206
+ const phase = samples.length > 0 && samples.every(sample => sample.kind === "mcp-phase");
207
+ // ponytail: at most 32 outstanding phase writes; a bounded worker queue with per-kind fairness is the upgrade.
208
+ if (phase && pendingPhases >= MCP_PHASE_KEEP) return;
209
+ if (phase) pendingPhases++;
210
+ pending.push({ base, samples, phase });
167
211
  if (draining) return;
168
212
  draining = true;
169
213
  setImmediate(() => { void drainPending(); });
@@ -173,6 +217,7 @@ async function drainPending(): Promise<void> {
173
217
  while (pending.length) {
174
218
  const next = pending.shift()!;
175
219
  try { await writeSamplesLater(next.base, next.samples); } catch { /* a lost sample is never a failed call */ }
220
+ finally { if (next.phase) pendingPhases--; }
176
221
  }
177
222
  draining = false;
178
223
  }
@@ -216,7 +261,7 @@ export function readMetrics(base: string, limit = METRICS_KEEP): MetricSample[]
216
261
  if (!line) continue;
217
262
  try {
218
263
  const s = JSON.parse(line) as MetricSample;
219
- if ((s?.kind === "hook" || s?.kind === "search") && typeof s.at === "string") parsed.push(s);
264
+ if ((s?.kind === "hook" || s?.kind === "search" || s?.kind === "mcp-phase") && typeof s.at === "string") parsed.push(s);
220
265
  } catch { /* a malformed line is skipped */ }
221
266
  }
222
267
  return newestPerKind(parsed, limit, sample => sample.kind);
@@ -267,15 +312,17 @@ export function readCaptureDrops(base: string): { readable: true; counts: Partia
267
312
  const length = readSync(fd, bytes, 0, bytes.length, start);
268
313
  let text = new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, length));
269
314
  if (start) text = text.slice(text.indexOf("\n") + 1);
270
- const tail = text.split("\n").filter(line => line.trim() !== "").slice(-METRICS_KEEP);
315
+ const tail = text.split("\n").filter(line => line.trim() !== "");
271
316
  lines = tail.length;
317
+ const hooks: MetricSample[] = [];
272
318
  for (const line of tail) {
273
- try {
274
- const sample = JSON.parse(line) as MetricSample;
275
- if (sample.kind !== "hook" || !DROP_REASONS.includes(sample.captureDropReason!) || !Number.isSafeInteger(sample.captureDrops) || sample.captureDrops! <= 0) continue;
276
- const reason = sample.captureDropReason!;
277
- counts[reason] = (counts[reason] ?? 0) + sample.captureDrops!;
278
- } catch { malformedLines++; /* A malformed metric is never a notice; doctor reports how many were skipped. */ }
319
+ try { const sample = JSON.parse(line) as MetricSample; if (sample.kind === "hook") hooks.push(sample); }
320
+ catch { malformedLines++; /* A malformed metric is never a notice; doctor reports how many were skipped. */ }
321
+ }
322
+ for (const sample of hooks.slice(-METRICS_KEEP)) {
323
+ if (!DROP_REASONS.includes(sample.captureDropReason!) || !Number.isSafeInteger(sample.captureDrops) || sample.captureDrops! <= 0) continue;
324
+ const reason = sample.captureDropReason!;
325
+ counts[reason] = (counts[reason] ?? 0) + sample.captureDrops!;
279
326
  }
280
327
  } catch { return { readable: false, reason: "metrics.jsonl cannot be read or is not UTF-8" }; }
281
328
  finally { if (fd !== undefined) closeSync(fd); }
@@ -4,11 +4,11 @@ import { join } from "node:path";
4
4
  import { realPath } from "./platform.ts";
5
5
 
6
6
  const messages={
7
- shards:"An interrupted or still-running person shard migration retains profile.lock; have the person finish it or run amem migrate --shards --resume.",
8
- prune:"An interrupted or still-running person public-prune view migration retains profile.lock; have the person finish it or run amem migrate --public-prune-view --resume.",
9
- activation:"An interrupted or still-running person sync-placement activation retains profile.lock; have the person run amem migrate --sync-placement --resume, or amem migrate --sync-placement --abandon only while both markers retain their original v2 bytes.",
10
- renewal:"An interrupted or still-running person writer-inventory renewal retains profile.lock; have the person run amem migrate --sync-placement --resume, or amem migrate --sync-placement --abandon only before the first commit-log byte.",
11
- staging:"An interrupted or still-running person writer-inventory renewal retains profile.lock and unpublished intent staging; have the person run amem migrate --sync-placement --abandon, then amem migrate --sync-placement --dry-run before another apply.",
7
+ shards:"An interrupted or still-running shard migration retains profile.lock; wait for it to finish or run amem migrate --shards --resume.",
8
+ prune:"An interrupted or still-running public-prune view migration retains profile.lock; wait for it to finish or run amem migrate --public-prune-view --resume.",
9
+ activation:"An interrupted or still-running sync-placement activation retains profile.lock; run amem migrate --sync-placement --resume, or amem migrate --sync-placement --abandon only while both markers retain their original v2 bytes.",
10
+ renewal:"An interrupted or still-running writer-inventory renewal retains profile.lock; run amem migrate --sync-placement --resume, or amem migrate --sync-placement --abandon only before the first commit-log byte.",
11
+ staging:"An interrupted or still-running writer-inventory renewal retains profile.lock and unpublished intent staging; run amem migrate --sync-placement --abandon, then amem migrate --sync-placement --dry-run before another apply.",
12
12
  } as const;
13
13
  type Family=keyof typeof messages;
14
14
  const recognised=new WeakMap<object,string>();
@@ -1,6 +1,7 @@
1
1
  /** Metadata-only input-set ancestry for the generation reader's cold path. Never loads proof bodies. */
2
2
  import { constants, closeSync, fstatSync, lstatSync, openSync, readSync, type BigIntStats } from "node:fs";
3
3
  import { join } from "node:path";
4
+ import { reportBindingRead } from "./binding-read-set.ts";
4
5
  import { canonicalJSON, hashJSON } from "./generation.ts";
5
6
  import { realPath } from "./platform.ts";
6
7
 
@@ -40,14 +41,16 @@ const same = (a: BigIntStats, b: BigIntStats) => a.dev === b.dev && a.ino === b.
40
41
  export function readPublicPruneInputSetChain(input: { dir: string; receivingGeneration: string; inputSetHash: string }): { commitments: string[]; inputs: string[] } {
41
42
  return protectedCall(() => {
42
43
  guard(hex(input.receivingGeneration, 32) && hex(input.inputSetHash, 64));
44
+ reportBindingRead(input.dir);
43
45
  const original = lstatSync(input.dir, { bigint: true }); owned(original, true);
44
46
  const dir = realPath(input.dir), root = lstatSync(dir, { bigint: true }); owned(root, true); guard(root.dev === original.dev && root.ino === original.ino);
45
47
  const folder = join(dir, "public-prune-input-sets"), parent = lstatSync(folder, { bigint: true }); owned(parent, true);
48
+ reportBindingRead(dir); reportBindingRead(folder);
46
49
  const frontier = new Map<string, BigIntStats>(), commitments: string[] = [], seen = new Set<string>();
47
50
  let id: string | null = input.inputSetHash, later: Set<string> | undefined, inputs: string[] = [], total = 0;
48
51
  while (id !== null) {
49
52
  guard(!seen.has(id)); guard(seen.size < PUBLIC_PRUNE_MAX_SETS, true); seen.add(id); commitments.push(id);
50
- const file = join(folder, id + ".json"), before = lstatSync(file, { bigint: true }); owned(before);
53
+ const file = join(folder, id + ".json"), before = lstatSync(file, { bigint: true }); owned(before); reportBindingRead(file);
51
54
  guard(before.size > 0n && before.size <= BigInt(PUBLIC_PRUNE_INPUT_MAX_BYTES), true);
52
55
  total += Number(before.size); guard(total <= PUBLIC_PRUNE_REPLAY_MAX_BYTES, true);
53
56
  const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); let bytes: Buffer;
@@ -1,6 +1,7 @@
1
1
  /** Root selector commitment only; this module never writes or activates a profile. */
2
2
  import { constants, closeSync, fstatSync, lstatSync, openSync, readSync, type Stats } from "node:fs";
3
3
  import { join } from "node:path";
4
+ import { reportBindingRead } from "./binding-read-set.ts";
4
5
  import { canonicalJSON, hashJSON, PROFILE_LOCK_TIMEOUT_MS } from "./generation.ts";
5
6
  import { realPath } from "./platform.ts";
6
7
 
@@ -104,7 +105,7 @@ export function waitForPublicPruneWriter(home: string, absoluteDeadline?: number
104
105
  }
105
106
  /** Any unresolved intent blocks reads. Never remove it, including malformed bytes. */
106
107
  export function assertNoPublicPruneIntent(home: string, absoluteDeadline?: number): void {
107
- protectedCall(() => { waitForPublicPruneWriter(home, absoluteDeadline); guard(!gone(lstatSync(join(home, PUBLIC_PRUNE_INTENT), { throwIfNoEntry: false }))); });
108
+ protectedCall(() => { reportBindingRead(join(home, PUBLIC_PRUNE_INTENT)); waitForPublicPruneWriter(home, absoluteDeadline); guard(!gone(lstatSync(join(home, PUBLIC_PRUNE_INTENT), { throwIfNoEntry: false }))); });
108
109
  }
109
110
  function privateStat(stat: Stats, directory = false): void {
110
111
  guard(!stat.isSymbolicLink() && (directory ? stat.isDirectory() : stat.isFile() && stat.nlink === 1));
@@ -117,10 +118,14 @@ function same(left: Stats, right: Stats): boolean {
117
118
  export function readPublicPruneViewForActivation(home: string, hash: string, generation: string): PublicPruneViewV1 {
118
119
  return protectedCall(() => {
119
120
  guard(hex(hash, 64) && hex(generation, 32));
121
+ reportBindingRead(home);
120
122
  const original = lstatSync(home); privateStat(original, true);
121
123
  const root = realPath(home), rootStat = lstatSync(root); privateStat(rootStat, true); guard(rootStat.dev === original.dev && rootStat.ino === original.ino);
124
+ reportBindingRead(root);
122
125
  const directory = join(root, "public-prune-input-sets"), dirStat = lstatSync(directory); privateStat(dirStat, true);
126
+ reportBindingRead(directory);
123
127
  const file = join(directory, `${hash}.json`), before = lstatSync(file); privateStat(before); guard(before.size > 0 && before.size <= MAX_BYTES);
128
+ reportBindingRead(file);
124
129
  const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
125
130
  try {
126
131
  const opened = fstatSync(fd); privateStat(opened); guard(same(before, opened));
@@ -12,9 +12,13 @@ export interface RecallStalenessOptions {
12
12
  maxProbes?: number;
13
13
  probe?: (path: string) => Pick<Stats, "isSymbolicLink" | "isDirectory" | "mtimeMs">;
14
14
  }
15
- type PathState = { state: "present"; mtime: number } | { state: "missing" | "unknown" };
15
+ type PathState = { state: "present"; mtime: number } | { state: "missing" } | { state: "unknown" };
16
+ export type RecallStalenessReason = "missing_in_checkout" | "mtime_newer_than_note";
17
+ export type RecallStalenessProbe = ((view: Pick<View, "about" | "at">) => boolean | undefined) & {
18
+ reason(view: Pick<View, "about" | "at">): RecallStalenessReason | undefined;
19
+ };
16
20
  /** Call-scoped metadata hint only. Unknown/denied paths never become a marker or a filesystem query. */
17
- export function createRecallStalenessProbe(options: RecallStalenessOptions): (view: Pick<View, "about" | "at">) => boolean | undefined {
21
+ export function createRecallStalenessProbe(options: RecallStalenessOptions): RecallStalenessProbe {
18
22
  const root = resolve(options.cwd), cache = new Map<string, PathState>(), requested = options.maxProbes ?? 32;
19
23
  let remaining = Number.isSafeInteger(requested) && requested >= 0 ? Math.min(requested, 32) : 0;
20
24
  const allowed = (path: string): boolean => {
@@ -42,18 +46,25 @@ export function createRecallStalenessProbe(options: RecallStalenessOptions): (vi
42
46
  };
43
47
  // ponytail: same-user ancestor swaps are outside the current metadata-only fence. Descriptor-relative traversal
44
48
  // is required before treating concurrent hostile filesystem mutation as supported. No source/symbol index is stored.
45
- return view => {
49
+ const observe = (view: Pick<View, "about" | "at">): { stale: boolean; reason?: RecallStalenessReason } | undefined => {
46
50
  const at = Date.parse(view.at); if (!Number.isFinite(at)) return undefined;
47
51
  // #423: `stale` means a referenced path is gone (under a confirmed root), or every referenced path that still exists
48
52
  // changed after the note. One edited file among several a note names no longer marks it: in an active repository
49
53
  // that marked most hits and stopped separating notes worth re-checking from current ones.
50
- let present = 0, changed = 0;
54
+ let present = 0, changed = 0, missing = false, unknown = false;
51
55
  for (const node of view.about) {
52
56
  const path = nodePath(node); if (path === undefined) continue;
53
57
  const state = inspect(path);
54
- if (state.state === "missing" && options.rootConfirmed === true) return true;
55
- if (state.state === "present") { present++; if (state.mtime > at) changed++; }
58
+ if (state.state === "missing") { if (options.rootConfirmed === true) missing = true; else unknown = true; }
59
+ else if (state.state === "unknown") unknown = true;
60
+ else { present++; if (state.mtime > at) changed++; }
56
61
  }
57
- return present ? changed === present : undefined;
62
+ if (unknown) return undefined;
63
+ if (missing) return { stale: true, reason: "missing_in_checkout" };
64
+ if (!present) return undefined;
65
+ return changed === present ? { stale: true, reason: "mtime_newer_than_note" } : { stale: false };
58
66
  };
67
+ return Object.assign((view: Pick<View, "about" | "at">) => observe(view)?.stale, {
68
+ reason: (view: Pick<View, "about" | "at">) => observe(view)?.reason,
69
+ });
59
70
  }
@@ -25,20 +25,36 @@ export interface ShardHistoryAuditorOptions {
25
25
  * Body bytes, without the Git object header; the auditor verifies each requested identity itself. */
26
26
  object?(oid: string, type: "commit" | "tree"): Promise<Buffer>;
27
27
  }
28
- export type ShardHistoryCause = "unavailable" | "blob" | "forbidden-entry" | "public-prune-floor";
28
+ export type ShardHistoryCause = "unavailable" | "blob" | "bound" | "forbidden-entry" | "public-prune-floor";
29
29
  const refusals: Record<ShardHistoryCause, string> = {
30
30
  unavailable: "Shard history is unavailable, inconsistent or unsupported; retain and inspect the complete selected history before continuing.",
31
31
  blob: "Shard history blob is unavailable or its identity, bound or complete newline is invalid; retain and inspect the selected history before continuing.",
32
+ bound: "Shard history inspection exceeded its retained-history bound; retain the history and do not abandon it: a later window needs the multi-plan checkpoint work (#288).",
32
33
  "forbidden-entry": "Shard history contains a forbidden historical tree entry; retain and inspect the selected history before continuing.",
33
34
  "public-prune-floor": "Shard history requires the v2 public prune floor; activate compatible public-prune support before continuing.",
34
35
  };
36
+ export interface ShardHistoryBound { kind: string; limit: number; observed: number }
35
37
  export class ShardHistoryError extends Error {
36
38
  readonly code: ShardHistoryCause;
37
- constructor(code: ShardHistoryCause = "unavailable") {
39
+ /** #567: only for code `bound`, copied as counts from the source's own data fields; never a path or object id. */
40
+ readonly bound?: ShardHistoryBound;
41
+ constructor(code: ShardHistoryCause = "unavailable", bound?: ShardHistoryBound) {
38
42
  const safe = typeof code === "string" && Object.hasOwn(refusals, code) ? code : "unavailable";
39
43
  super(refusals[safe]); this.code = safe; this.name = "ShardHistoryError";
44
+ if (safe === "bound" && bound) this.bound = bound;
40
45
  }
41
46
  }
47
+ /** A source throw keeps `bound` only when its own data `code` says so; its kind/limit/observed survive only as finite counts. */
48
+ function sourceBound(error: unknown): ShardHistoryBound | undefined | false {
49
+ try {
50
+ if (!error || typeof error !== "object" || types.isProxy(error)) return false;
51
+ const own = (key: string) => { const d = Object.getOwnPropertyDescriptor(error, key); return d && "value" in d ? d.value as unknown : undefined; };
52
+ if (own("code") !== "bound") return false;
53
+ const kind = own("kind"), limit = own("limit"), observed = own("observed");
54
+ return typeof kind === "string" && /^[a-z-]{1,32}$/.test(kind) && Number.isSafeInteger(limit) && Number.isSafeInteger(observed)
55
+ ? { kind, limit: limit as number, observed: observed as number } : undefined;
56
+ } catch { return false; }
57
+ }
42
58
  function cause(error: unknown): ShardHistoryCause {
43
59
  try {
44
60
  if (!error || typeof error !== "object" || types.isProxy(error) || !(error instanceof ShardHistoryError)) return "unavailable";
@@ -83,18 +99,23 @@ export class ShardHistoryAuditor {
83
99
  const maximum = path === "shard.json" || isShardManifestPath(path) ? 64 * 1024 : SHARD_PACK_MAX_BYTES;
84
100
  let bytes = this.#blobs.get(object);
85
101
  if (!bytes) {
86
- const result = await this.#options.blob(object, path);
102
+ let result: Uint8Array;
103
+ try { result = await this.#options.blob(object, path); }
104
+ catch (error) { const bound = sourceBound(error); if (bound !== false) throw new ShardHistoryError("bound", bound); throw error; }
87
105
  if (!(result instanceof Uint8Array)) fail("blob"); bytes = Buffer.from(result);
88
106
  if (bytes.length < 1 || bytes.length > maximum || bytes.at(-1) !== 10
89
107
  || createHash("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex") !== object) fail("blob");
90
108
  this.#blobs.set(object, bytes);
91
109
  }
92
110
  if (bytes.length > maximum) fail("blob"); return bytes;
93
- } catch { return fail("blob"); }
111
+ } catch (error) { if (error instanceof ShardHistoryError && error.code === "bound") throw error; return fail("blob"); }
94
112
  }
95
113
  async #object(object: string, type: "commit" | "tree"): Promise<Buffer> {
96
114
  if (!this.#options.object || !oid(object)) return fail();
97
- const body = await this.#options.object(object, type);
115
+ let body: Uint8Array;
116
+ // #567: a source bound on a commit or tree read keeps cause bound with its counts, like a blob read.
117
+ try { body = await this.#options.object(object, type); }
118
+ catch (error) { const bound = sourceBound(error); if (bound !== false) throw new ShardHistoryError("bound", bound); throw error; }
98
119
  if (!(body instanceof Uint8Array) || body.length > (type === "commit" ? 65536 : SHARD_PACK_MAX_BYTES)) return fail();
99
120
  const bytes = Buffer.from(body);
100
121
  if (createHash("sha1").update(`${type} ${bytes.length}\0`).update(bytes).digest("hex") !== object) return fail();
@@ -242,7 +263,7 @@ export class ShardHistoryAuditor {
242
263
  }
243
264
  if (!latest || lines.at(-1)?.split(" ")[0] !== tip) return fail();
244
265
  this.#histories.set(tip, latest); return detached(latest);
245
- } catch (error) { return fail(cause(error)); }
266
+ } catch (error) { const code = cause(error); if (code === "bound" && error instanceof ShardHistoryError && error.bound) throw new ShardHistoryError("bound", { ...error.bound }); return fail(code); }
246
267
  finally { this.#running = false; }
247
268
  }
248
269
  }
@@ -174,7 +174,7 @@ function realmGapRemedy(gap: PlacementRealmGap | undefined): string {
174
174
  case "capture-only": return `class=capture-only; it holds capture rows and no curated memory, so capture stays readable; ${admit} if you want curated memory for it`;
175
175
  case "no-memory": return `class=no-memory; it holds no captured rows and no curated notes yet; ${admit} if you want curated memory for it, or remove it with amem project archive <project>`;
176
176
  case "curated-unadmitted": return `class=curated-unadmitted; it holds curated notes that are not part of the activated inventory, and ${admit} opens them`;
177
- case "unverified": return "class=unverified; neither its curated state nor the activated inventory could be verified safely; have the person inspect the home before changing anything";
177
+ case "unverified": return "class=unverified; neither its curated state nor the activated inventory could be verified safely; inspect the home before changing anything";
178
178
  default: return admit;
179
179
  }
180
180
  }
@@ -44,7 +44,7 @@ export class PlacementActivationError extends Error {
44
44
  }
45
45
  export class PlacementActivationInputError extends Error {
46
46
  constructor(readonly inputClass:"policy"|"source"|"aliases"|"writer root"|"receipt"|"floor"){
47
- super(`Sync placement activation frozen ${inputClass} input changed or is unavailable; restore that input and run amem migrate --sync-placement --resume. If both markers still contain their original v2 bytes, the person may run amem migrate --sync-placement --abandon, then review a fresh --dry-run and --apply. Once any v3 marker exists, only forward resume is supported.`);
47
+ super(`Sync placement activation frozen ${inputClass} input changed or is unavailable; restore that input and run amem migrate --sync-placement --resume. If both markers still contain their original v2 bytes, run amem migrate --sync-placement --abandon, then review a fresh --dry-run and --apply. Once any v3 marker exists, only forward resume is supported.`);
48
48
  this.name="PlacementActivationInputError";
49
49
  }
50
50
  }
@@ -128,7 +128,7 @@ export async function activateSyncPlacement(options:PlacementActivationOptions)
128
128
  const active=initialBase.active,dirs=active.activation.realms.map(realm=>realm.scope==="user"?join(home,"user"):join(home,"projects",realm.keyHash.slice(0,16)));
129
129
  return withPlacementActivationFences(home,dirs,(mutation,owner)=>finishCommittedActivation(home,{epoch:active.epoch,plan:active.activation},options,mutation,owner)).catch(error=>rethrowActivationFailure(error));
130
130
  }
131
- if(pending&&options.mode!=="resume")throw Error("Sync placement activation is retained; run amem migrate --sync-placement --resume, or person --abandon while both markers retain the original v2 bytes, before reviewing a new --dry-run.");
131
+ if(pending&&options.mode!=="resume")throw Error("Sync placement activation is retained; run amem migrate --sync-placement --resume, or --abandon while both markers retain the original v2 bytes, before reviewing a new --dry-run.");
132
132
  const source=pending?undefined:previewSyncPlacementSources(home);
133
133
  const writer=pending?undefined:initialPlacementWriterContext(home,options.writerRoots,options.ownRoot);
134
134
  const report=source?counts(source):undefined;
@@ -1,6 +1,7 @@
1
1
  /** Metadata-only v3 admission. Publication still requires the complete journal/source/policy proof. */
2
2
  import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type BigIntStats } from "node:fs";
3
3
  import { join } from "node:path";
4
+ import { reportBindingRead } from "./binding-read-set.ts";
4
5
  import { canonicalJSON, hashJSON } from "./generation.ts";
5
6
  import { realPath } from "./platform.ts";
6
7
  import { homeIdentityHash } from "./home-identity.ts";
@@ -52,6 +53,7 @@ export function readActivePlacementBinding(homeInput: string, profileInput: unkn
52
53
  for (const [file, isDir] of [[home, true], [join(home, "sync-placement"), true], [join(home, "sync-placement", "epochs"), true], [dir, true], [join(dir, "epoch.json"), false],
53
54
  [join(dir, "activation.json"), false], [join(home, "sync-placement", "active.json"), false], [join(home, "profile.json"), false], [join(home, "shards.json"), false]] as const) {
54
55
  const st = lstatSync(file, { bigint: true, throwIfNoEntry: false }); if (!st) return undefined; owned(st, isDir);
56
+ reportBindingRead(file);
55
57
  stamps.push([st.dev, st.ino, st.size, st.mtimeNs, st.ctimeNs].map(String).join(":"));
56
58
  }
57
59
  return canonicalJSON([home, canonicalJSON(profile), canonicalJSON(shards), stamps]);
@@ -62,11 +64,12 @@ export function readActivePlacementBinding(homeInput: string, profileInput: unkn
62
64
  }
63
65
  const checks: (() => void)[] = [() => { const now = lstatSync(home, { bigint: true }); owned(now, true); if (now.dev !== root.dev || now.ino !== root.ino) fail(); }];
64
66
  const directory = (dir: string): boolean => {
65
- const s = lstatSync(dir, { bigint: true, throwIfNoEntry: false }); if (!s) return false; owned(s, true);
67
+ const s = lstatSync(dir, { bigint: true, throwIfNoEntry: false }); if (!s) return false; owned(s, true); reportBindingRead(dir);
66
68
  checks.push(() => { const now = lstatSync(dir, { bigint: true }); owned(now, true); if (s.dev !== now.dev || s.ino !== now.ino) fail(); }); return true;
67
69
  };
68
70
  const read = (file: string): { value: unknown; text: string } | undefined => {
69
71
  const before = lstatSync(file, { bigint: true, throwIfNoEntry: false }); if (!before) return undefined;
72
+ reportBindingRead(file);
70
73
  owned(before); if (before.size <= 0n || before.size > 262144n) fail();
71
74
  const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
72
75
  try {
@@ -18,7 +18,7 @@ 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; have the person preview a checkpoint with amem migrate --sync-placement --checkpoint --writer-root <install root> (repeat for every install), then confirm it and rerun amem sync."
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."
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.";
@@ -35,7 +35,8 @@ export class PlacementSourceBoundError extends SyncPlacementJournalError {
35
35
  constructor(readonly bound?: InspectionBound) {
36
36
  super("bound");
37
37
  const detail = bound ? `${bound.kind} bound (observed ${bound.observed}, limit ${bound.limit})` : "read bound";
38
- this.message = `Sync placement source capture exceeds its supported ${detail}; no journal, marker or source was changed. This is not journal corruption; retain the inputs and report this bound.`;
38
+ this.message = `Sync placement source capture exceeds its supported ${detail}; no journal, marker or source was changed. This is not journal corruption; retain the inputs and report this bound.`
39
+ + (bound?.kind === "source-files" ? " Each project shard directory and the user realm hold at most 16 metadata objects, and the home at most 4096; no file was skipped to fit." : "");
39
40
  this.name = "PlacementSourceBoundError";
40
41
  }
41
42
  }
@@ -81,8 +82,16 @@ function ownedDirectory(dir: string): BigIntStats {
81
82
  if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== BigInt(process.getuid!()) || (s.mode & 0o022n) !== 0n) fail();
82
83
  return s;
83
84
  }
84
- /** ponytail: capture holds the whole home in memory, capped at 256 metadata objects and 64 MiB/20000 source rows
85
- * across all realms (#414 raised 8 MiB; a 23 MB/10,248-row home was refused). Larger homes need a reviewed
85
+ /** Metadata objects are counted per scope (#550): the home markers form one scope, and each project shard
86
+ * directory (its project.json reads included, an activated realm's second read too) or the user realm forms
87
+ * another. An optional file that is absent opens nothing and counts nothing. */
88
+ export const PLACEMENT_METADATA_OBJECTS_PER_SCOPE = 16;
89
+ /** Whole-home safety cap on metadata objects; the 8 MiB metadata-bytes cap below bounds the metadata file bytes read. */
90
+ export const PLACEMENT_METADATA_OBJECTS_TOTAL = 4096;
91
+ /** ponytail: capture holds the whole home in memory, capped at 16 metadata objects per scope, 4096 and 8 MiB of
92
+ * metadata across the home, 256 entries per listed directory (so at most 256 project shards and 256 selected
93
+ * realms) and 64 MiB/20000 source rows across all realms (#414 raised 8 MiB; a 23 MB/10,248-row home was refused).
94
+ * #550 measured 250 activated realms (about 2,250 objects) at 257 ms and +15 MB RSS. Larger homes need a reviewed
86
95
  * chunked/streaming activation proof; no input is silently omitted at this ceiling. */
87
96
  function* sourcePreviewSteps(homeInput: string, selected?: readonly PlacementRealm[], pending: readonly PlacementPendingSource[] = [], policyVersion?: string, ownerProof?: PlacementActivationCaptureProof, sourceOwner?:PlacementActivationOwner): Generator<void, PlacementSourcePreview, void> {
88
97
  let selection: PlacementRealm[] | undefined;
@@ -95,7 +104,7 @@ function* sourcePreviewSteps(homeInput: string, selected?: readonly PlacementRea
95
104
  }
96
105
  const home = realPath(homeInput), root = ownedDirectory(home);
97
106
  if(sourceOwner)assertPlacementActivationOwner(sourceOwner,home);
98
- let metadataObjects = 0, metadataBytes = 0;
107
+ let metadataObjects = 0, scopeObjects = 0, metadataBytes = 0;
99
108
  const facts: unknown[] = [], sourceChecks: (() => void)[] = [];
100
109
  const pendingByPath = new Map(pending.map(item => [canonicalJSON(item.realm)+":"+item.pathHash,item]));
101
110
  if (pendingByPath.size !== pending.length) fail();
@@ -106,7 +115,8 @@ function* sourcePreviewSteps(homeInput: string, selected?: readonly PlacementRea
106
115
  const bytes = (file: string, optional = false): Buffer | undefined => {
107
116
  const before = lstatSync(file, { bigint: true, throwIfNoEntry: false });
108
117
  if (!before) { if (!optional) fail(); facts.push([file, null]); sourceChecks.push(() => { if(lstatSync(file,{throwIfNoEntry:false})) fail(); }); return undefined; }
109
- if (++metadataObjects > 256) throw new PlacementSourceBoundError({ kind: "source-files", limit: 256, observed: metadataObjects });
118
+ if (++scopeObjects > PLACEMENT_METADATA_OBJECTS_PER_SCOPE) throw new PlacementSourceBoundError({ kind: "source-files", limit: PLACEMENT_METADATA_OBJECTS_PER_SCOPE, observed: scopeObjects });
119
+ if (++metadataObjects > PLACEMENT_METADATA_OBJECTS_TOTAL) throw new PlacementSourceBoundError({ kind: "source-files", limit: PLACEMENT_METADATA_OBJECTS_TOTAL, observed: metadataObjects });
110
120
  if (before.size > 262144n) throw new PlacementSourceBoundError({ kind: "metadata-bytes", limit: 262144, observed: Number(before.size) });
111
121
  if (metadataBytes + Number(before.size) > 8 * 1024 * 1024) throw new PlacementSourceBoundError({ kind: "metadata-bytes", limit: 8 * 1024 * 1024, observed: metadataBytes + Number(before.size) });
112
122
  if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1n || before.uid !== root.uid || (before.mode & 0o022n) !== 0n) fail();
@@ -282,11 +292,12 @@ function* sourcePreviewSteps(homeInput: string, selected?: readonly PlacementRea
282
292
  const bindingHash = hashJSON(facts.slice(beforeFacts));
283
293
  realms.push({ ...identity, bindingHash });
284
294
  };
285
- if (!selection || selection.some(item => item.scope === "user")) yield* realm(join(home, "user"), { scope: "user" });
295
+ if (!selection || selection.some(item => item.scope === "user")) { scopeObjects = 0; yield* realm(join(home, "user"), { scope: "user" }); }
286
296
  for (const name of listing(join(home, "projects"), true)) {
287
297
  yield;
288
298
  if (!/^[a-f0-9]{16}$/.test(name)) fail();
289
299
  if (selection && !selection.some(item => item.scope === "project" && item.keyHash.slice(0,16) === name)) continue;
300
+ scopeObjects = 0;
290
301
  const dir = join(home, "projects", name), project = json(join(dir, "project.json"));
291
302
  if (typeof project?.key !== "string" || shardKeyHash(project.key) !== name) fail();
292
303
  // Capture scaffolds are not curated realms, but their identity still binds this inventory.
@@ -26,13 +26,14 @@ import { assertPlacementActivationOwner } from "./sync-placement-activation-proo
26
26
  import { placementFenceDirectories } from "./sync-placement-writer-renewal.ts";
27
27
  import { initialPlacementWriterContext } from "../sync-placement-writer-context.ts";
28
28
  import { checkpointProspective, type CheckpointProspective } from "./sync-placement-checkpoint-prospective.ts";
29
+ import { ShardHistoryError, type ShardHistoryCause } from "./shard-sync-history.ts";
29
30
 
30
31
  export const CHECKPOINT_PREVIEW = PLACEMENT_CHECKPOINT_COMMAND;
31
32
  const RESUME = `${CHECKPOINT_PREVIEW} --resume`, ABANDON = `${CHECKPOINT_PREVIEW} --abandon`;
32
33
  const homeFloorAtLeast = (home: string, minimum: string): boolean =>
33
34
  (readFormatFloors(home) ?? []).some(floor => floor.surface === "home" && !formatVersionBelow(floor.minReader, minimum));
34
35
 
35
- export type PlacementCheckpointCause = "pending" | "commit-started" | "floor" | "writer-below-floor" | "headroom" | "obligation" | "changed" | "inactive" | "candidate";
36
+ export type PlacementCheckpointCause = "pending" | "commit-started" | "floor" | "writer-below-floor" | "headroom" | "obligation" | "changed" | "inactive" | "candidate" | "history";
36
37
  const MESSAGES: Record<PlacementCheckpointCause, string> = {
37
38
  pending: PLACEMENT_CHECKPOINT_PENDING_MESSAGE,
38
39
  "commit-started": `The placement checkpoint's commit line has started, so it can no longer be abandoned; run ${RESUME} to complete it.`,
@@ -43,13 +44,34 @@ const MESSAGES: Record<PlacementCheckpointCause, string> = {
43
44
  changed: `The placement state changed since the checkpoint plan was sealed; preview a fresh plan with ${CHECKPOINT_PREVIEW} and confirm that one.`,
44
45
  inactive: "This home has no active sync placement; activate it with amem migrate --sync-placement --dry-run first.",
45
46
  candidate: `A checkpoint carries one writer renewal: pass the complete inventory as repeatable --writer-root <install root> (every amem install sharing this home), then preview again with ${CHECKPOINT_PREVIEW}.`,
47
+ history: "",
46
48
  };
49
+ /** #567: the retained-history cause class and, for `bound`, which bound with its counts. Never a path, row or object id. */
50
+ export interface PlacementCheckpointHistoryRefusal { category: "shard history"; cause: ShardHistoryCause; kind?: string; limit?: number; observed?: number }
51
+ function historyMessage(refusal: PlacementCheckpointHistoryRefusal): string {
52
+ const exceeded = refusal.cause === "bound" && refusal.kind !== undefined ? ` (${refusal.kind}: ${refusal.observed} over the limit of ${refusal.limit})` : "";
53
+ const next = refusal.cause === "bound"
54
+ ? "Retain the history and do not abandon or edit it; a window this large needs the multi-plan checkpoint work in #288. Nothing was written."
55
+ : `Retain the selected history and inspect it with a compatible runtime, then preview again with ${CHECKPOINT_PREVIEW}. Nothing was written.`;
56
+ return `The checkpoint could not inspect retained shard history: shard history ${refusal.cause}${exceeded}. ${next}`;
57
+ }
47
58
  /** A person-facing checkpoint refusal with one cause class and its next step; never a path, row or project name. */
48
59
  export class PlacementCheckpointError extends Error {
49
- constructor(readonly causeClass: PlacementCheckpointCause, detail = "") {
50
- super(causeClass === "headroom" ? `The checkpoint would not leave room for the next sync: ${detail} A single checkpoint cannot unblock this plan; the deferred multi-plan split in #288 design item 5 is the open path. Nothing was written.` : MESSAGES[causeClass] + (detail ? ` ${detail}` : ""));
60
+ readonly history?: PlacementCheckpointHistoryRefusal;
61
+ constructor(readonly causeClass: PlacementCheckpointCause, detail = "", history?: PlacementCheckpointHistoryRefusal) {
62
+ super(causeClass === "headroom" ? `The checkpoint would not leave room for the next sync: ${detail} A single checkpoint cannot unblock this plan; the deferred multi-plan split in #288 design item 5 is the open path. Nothing was written.`
63
+ : causeClass === "history" && history ? historyMessage(history) : MESSAGES[causeClass] + (detail ? ` ${detail}` : ""));
51
64
  this.name = "PlacementCheckpointError";
65
+ if (causeClass === "history" && history) this.history = history;
66
+ }
67
+ }
68
+ /** Maps only this module's closed ShardHistoryError data to the checkpoint's history cause; anything else is rethrown. */
69
+ function historyRefusal(error: unknown): never {
70
+ if (error instanceof ShardHistoryError) {
71
+ const code = Object.getOwnPropertyDescriptor(error, "code")?.value as ShardHistoryCause, bound = code === "bound" ? error.bound : undefined;
72
+ throw new PlacementCheckpointError("history", "", { category: "shard history", cause: code, ...(bound ? { kind: bound.kind, limit: bound.limit, observed: bound.observed } : {}) });
52
73
  }
74
+ throw error;
53
75
  }
54
76
 
55
77
  function active(home: string): ActivePlacementBinding {
@@ -105,7 +127,7 @@ export async function previewPlacementCheckpoint(homeInput: string, opts: { writ
105
127
  nextStep: `${CHECKPOINT_PREVIEW} --confirm --plan <saved preview JSON> --writer-root <install root> (repeat for every install)` };
106
128
  }
107
129
  async function checkpointHeadroom(home: string, intent: CheckpointIntent): Promise<{ headroom: PlacementCheckpointHeadroom; journalObjects: PlacementJournalObjectComposition; assertCurrent(): void }> {
108
- const epochHash = intent.epochHash, prospective = await checkpointProspective(home);
130
+ const epochHash = intent.epochHash, prospective = await checkpointProspective(home).catch(historyRefusal);
109
131
  let completed = { slots: 0, reservedJournalChunks: 0 }, journalObjects!: PlacementJournalObjectComposition;
110
132
  readPlacementPublicationMetadata(home, epochHash, io => {
111
133
  journalObjects = placementJournalObjectComposition({ names: io.names() });