@staix/agent-mem 0.32.1 → 0.34.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.
@@ -1,4 +1,6 @@
1
- import { planGuardNodes, planNodesIntersect } from "./plan-guard.ts";
1
+ import type { RecallStalenessReason } from "./recall-staleness.ts";
2
+ import { planGuardNodes } from "./plan-guard.ts";
3
+ import { requestedNodeMatcher } from "./intent-node-matcher.ts";
2
4
  import { memoryPolicySnapshot, type StandalonePolicy } from "./policy.ts";
3
5
  import { INTENT_PREFERENCE_SHARE, PREFERENCE_SLOT, preferenceLine } from "./preference-brief.ts";
4
6
  import type { View } from "./store.ts";
@@ -41,12 +43,17 @@ function preferenceLive(view: View, project: string, now: number): boolean {
41
43
  && (view.project === project || view.scope === "shared") && !view.supersededBy
42
44
  && (view.expiresAt === null || Number.isFinite(Date.parse(view.expiresAt)) && Date.parse(view.expiresAt) > now);
43
45
  }
44
- function staleMarker(options: IntentBriefOptions, view: View): boolean {
45
- try { return options.stale?.(structuredClone(view)) === true; } catch { return false; }
46
+ function staleMarker(options: IntentBriefOptions, view: View): RecallStalenessReason | "unknown" | undefined {
47
+ try {
48
+ const probe = options.stale as (typeof options.stale & { reason?: (view: View) => RecallStalenessReason | undefined });
49
+ const copy = structuredClone(view);
50
+ if (probe?.reason) return probe.reason(copy);
51
+ return probe?.(copy) === true ? "unknown" : undefined;
52
+ } catch { return undefined; }
46
53
  }
47
54
  /** Keep the complete JSON line valid, including multi-byte text and the visible fetch marker. */
48
- function lineOf(view: View, stale: boolean, cap: number): { line: string; clipped: boolean } | undefined {
49
- const id = `mem:${view.id}`, prefix = stale ? "(stale?) " : "", body = `${view.title ? view.title + ": " : ""}${view.text}`;
55
+ function lineOf(view: View, stale: RecallStalenessReason | "unknown" | undefined, cap: number): { line: string; clipped: boolean } | undefined {
56
+ const id = `mem:${view.id}`, prefix = stale === "missing_in_checkout" ? "(stale? missing) " : stale === "mtime_newer_than_note" ? "(stale? mtime) " : stale ? "(stale?) " : "", body = `${view.title ? view.title + ": " : ""}${view.text}`;
50
57
  const encode = (text: string) => JSON.stringify({ id, kind: view.kind, tier: view.tier, text: prefix + text });
51
58
  const full = encode(body); if (Buffer.byteLength(full) <= cap) return { line: full, clipped: false };
52
59
  const marker = ` [truncated; fetch ${id}]`, points = Array.from(body);
@@ -92,14 +99,22 @@ export async function buildIntentBrief(source: IntentBriefSource, options: Inten
92
99
  if (!view || !live(view, context.project, current()) || seen.has(view.id)) continue;
93
100
  seen.add(view.id); scanned.push(view);
94
101
  }
95
- const matches = (view: View) => nodes.length ? view.about.some(about => nodes.some(node => planNodesIntersect(node, about))) : words.some(word => `${view.title ?? ""}\n${view.text}`.toLowerCase().includes(word));
96
- const directIds = new Set(scanned.filter(matches).map(view => view.id));
97
- const byRank = (a: View, b: View) => weight(a) - weight(b) || Number(directIds.has(b.id)) - Number(directIds.has(a.id)) || b.at.localeCompare(a.at) || a.id.localeCompare(b.id);
102
+ // #542: the request-only index counts at most three matched nodes in one row-local pass. No unscreened row
103
+ // contributes to another row's score, and no matcher work is repeated by the sort comparator.
104
+ const countRequested = requestedNodeMatcher(nodes), counts = new Map<string, number>(), directIds = new Set<string>();
105
+ for (const view of scanned) {
106
+ const count = nodes.length ? countRequested(view.about) : 0;
107
+ if (count || !nodes.length && words.some(word => `${view.title ?? ""}\n${view.text}`.toLowerCase().includes(word))) {
108
+ directIds.add(view.id); counts.set(view.id, count);
109
+ }
110
+ }
111
+ const byRank = (a: View, b: View) => (counts.get(b.id) ?? 0) - (counts.get(a.id) ?? 0)
112
+ || Number(directIds.has(b.id)) - Number(directIds.has(a.id)) || weight(a) - weight(b)
113
+ || b.at.localeCompare(a.at) || a.id.localeCompare(b.id);
98
114
  const admitted = new Set<string>(), bridges = new Set<string>();
99
115
  let asked = 0, capped = false;
100
- // Direct rows first, in rank order: only a row that passed the screen may contribute the co-reference nodes that make its
101
- // neighbours candidates, exactly as before, so a private row still bridges nothing.
102
- for (const view of scanned.filter(view => directIds.has(view.id)).sort((a, b) => weight(a) - weight(b) || b.at.localeCompare(a.at) || a.id.localeCompare(b.id))) {
116
+ // Direct rows first, in rank order; only screened rows contribute bridge nodes.
117
+ for (const view of scanned.filter(view => directIds.has(view.id)).sort(byRank)) {
103
118
  if (asked === INTENT_BRIEF_SCREEN_LIMIT) { capped = true; break; }
104
119
  asked++; check();
105
120
  if (!await policy.screen(view)) { check(); continue; } check();
@@ -0,0 +1,62 @@
1
+ import { normalizeMemorySymbolInput } from "./plan-guard.ts";
2
+ import { nodePath } from "./project.ts";
3
+
4
+ type PathIndex = { exact: Map<string, number[]>; descendants: Map<string, number[]> };
5
+ const index = (): PathIndex => ({ exact: new Map(), descendants: new Map() });
6
+ function add(map: Map<string, number[]>, key: string, id: number): void {
7
+ const prior = map.get(key); if (prior) prior.push(id); else map.set(key, [id]);
8
+ }
9
+ /** Requested nodes only: no note, policy or other row contributes to this index. */
10
+ export function requestedNodeMatcher(nodes: readonly string[]): (about: readonly string[]) => number {
11
+ const literal = new Map<string, number[]>(), symbols = new Map<string, number[]>();
12
+ const paths = index(), symbolPaths = index();
13
+ for (let id = 0; id < nodes.length; id++) {
14
+ const node = nodes[id]!; add(literal, node, id);
15
+ const symbol = node.startsWith("symbol:");
16
+ if (symbol) add(symbols, normalizeMemorySymbolInput(node.slice(7)), id);
17
+ const path = nodePath(node); if (!path) continue;
18
+ const target = symbol ? symbolPaths : paths;
19
+ add(target.exact, path, id);
20
+ for (let pos = path.indexOf("/"); pos >= 0; pos = path.indexOf("/", pos + 1)) {
21
+ const prefix = path.slice(0, pos); if (prefix) add(target.descendants, prefix, id);
22
+ }
23
+ }
24
+ // ponytail: retain at most 1,024 short node lookups and 256 KiB of key text per call. A bounded LRU or a
25
+ // shared immutable query index is the upgrade if diverse large notes make this small cache ineffective.
26
+ const cache = new Map<string, readonly number[]>(); let cachedBytes = 0;
27
+ const marks = new Uint32Array(nodes.length); let epoch = 0;
28
+ const indices = (node: string): readonly number[] => {
29
+ const known = cache.get(node); if (known) return known;
30
+ const result: number[] = [];
31
+ const addIds = (ids?: readonly number[]) => { if (ids) for (const id of ids) result.push(id); };
32
+ const addPaths = (target: PathIndex, path: string) => {
33
+ addIds(target.exact.get(path)); addIds(target.descendants.get(path));
34
+ for (let pos = path.indexOf("/"); pos >= 0; pos = path.indexOf("/", pos + 1)) {
35
+ const prefix = path.slice(0, pos); if (prefix) addIds(target.exact.get(prefix));
36
+ }
37
+ };
38
+ addIds(literal.get(node));
39
+ const symbol = node.startsWith("symbol:");
40
+ if (symbol) addIds(symbols.get(normalizeMemorySymbolInput(node.slice(7))));
41
+ const path = nodePath(node); if (path) { addPaths(paths, path); if (!symbol) addPaths(symbolPaths, path); }
42
+ const bytes = node.length * 2;
43
+ if (node.length <= 512 && cache.size < 1024 && cachedBytes + bytes <= 256 * 1024) { cache.set(node, result); cachedBytes += bytes; }
44
+ return result;
45
+ };
46
+ const limit = Math.min(nodes.length, 3);
47
+ return about => {
48
+ if (!limit) return 0;
49
+ epoch++; if (epoch === 0xffffffff) { marks.fill(0); epoch = 1; }
50
+ let count = 0;
51
+ for (let at = 0; at < about.length; at++) {
52
+ const node = about[at]!;
53
+ let known = cache.get(node);
54
+ if (known === undefined) {
55
+ if (typeof node !== "string") throw Error("invalid intent node");
56
+ known = indices(node);
57
+ }
58
+ for (let i = 0; i < known.length; i++) { const id = known[i]!; if (marks[id] !== epoch) { marks[id] = epoch; if (++count === limit) return count; } }
59
+ }
60
+ return count;
61
+ };
62
+ }
@@ -52,7 +52,10 @@ 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 }
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"; /** #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
59
  const METRICS_MAX_BYTES = 64 * 1024, METRICS_KEEP = 200;
57
60
 
58
61
  /**
@@ -1,3 +1,6 @@
1
+ /** Current host-library API and the oldest host API this implementation supports. */
2
+ export const HOST_API_VERSION = 1 as const;
3
+ export const HOST_API_MIN = 1 as const;
1
4
  // Single-source platform helpers. Hub, local and Pi modules re-export these functions unchanged.
2
5
  import { lstatSync, realpathSync } from "node:fs";
3
6
  import { basename, dirname, join, resolve, sep } from "node:path";
@@ -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
  }
@@ -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 {
@@ -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.
@@ -11,7 +11,7 @@ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type Bi
11
11
  import { join } from "node:path";
12
12
  import { LOCAL_METADATA_MAX_BYTES, legacyProfileMarkerShape, type BoundProfile } from "./generation.ts";
13
13
  import { legacyShardMarkerShape } from "./shard.ts";
14
- import { PLACEMENT_PROFILE_SCHEMA, PLACEMENT_SHARDS_SCHEMA, validatePlacementProfile, validatePlacementShards } from "./sync-placement-format.ts";
14
+ import { PLACEMENT_FORMAT, PLACEMENT_PROFILE_SCHEMA, PLACEMENT_SHARDS_SCHEMA, validatePlacementProfile, validatePlacementShards } from "./sync-placement-format.ts";
15
15
  import { PLACEMENT_ACTIVATION_INTENT } from "./sync-placement-activation-path.ts";
16
16
  import { profileLockRefusal, rememberProfileLockError } from "./profile-lock-diagnostic.ts";
17
17
 
@@ -90,6 +90,21 @@ function readMarker(file: string): unknown | undefined {
90
90
  export function readPlacementRuntimeMarkers(home: string): { profile: unknown | undefined; shards: unknown | undefined } {
91
91
  return { profile: readMarker(join(home, "profile.json")), shards: readMarker(join(home, "shards.json")) };
92
92
  }
93
+ /** #551 AC2: whether a home is provably a placement home, provably not one, or unprovable from its own markers. */
94
+ export type PlacementMarkerState = "placement" | "unverified" | "not placement";
95
+ /**
96
+ * #551 AC2: a caller that decides whether placement writer verification applies reads this instead of parsing the markers
97
+ * itself. A marker that cannot be read, is unsafe or does not parse proves neither state, so it is `unverified` - never a
98
+ * home reported as one that never activated placement sync, and never a root reported as missing.
99
+ */
100
+ export function placementMarkerState(home: string): PlacementMarkerState {
101
+ let markers: { profile: unknown | undefined; shards: unknown | undefined };
102
+ try { markers = readPlacementRuntimeMarkers(home); } catch { return "unverified"; }
103
+ if (schema(markers.profile) === PLACEMENT_PROFILE_SCHEMA || schema(markers.shards) === PLACEMENT_SHARDS_SCHEMA)
104
+ return (markers.profile as { publicationFormat?: unknown } | undefined)?.publicationFormat === PLACEMENT_FORMAT ? "placement" : "unverified";
105
+ // A missing marker or a recognizable legacy one is a home that never activated placement sync; any other shape is malformed.
106
+ return legacyProfileMarkerShape(markers.profile) && legacyShardMarkerShape(markers.shards) ? "not placement" : "unverified";
107
+ }
93
108
  function schema(value: unknown): unknown {
94
109
  if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
95
110
  return Object.getOwnPropertyDescriptor(value, "schema")?.value;
@@ -9,6 +9,8 @@ import { curatedProfileBinding } from "./memory/curated-cache-state.ts";
9
9
  import { captureDisplay, displayText, recordDisplay, validCachedCapture } from "./brief-capture.ts";
10
10
  import { readWorkBrief, workLogSegments, workPolicyRevision } from "./brief-work.ts";
11
11
  import { assertFormatFloor, FormatFloorError } from "./memory/formats.ts";
12
+ import { collectBindingReads } from "./memory/binding-read-set.ts";
13
+ import { FENCE_MAX_PATHS, fenceIsComplete, homeBindingPaths, sameHomeBinding, snapshotHomeBinding, type HomeBindingSnapshot } from "./memory/home-binding-fence.ts";
12
14
  import { readSelector } from "./memory/generation.ts";
13
15
  import { memoryHome } from "./memory/home.ts";
14
16
  import { canonicalPath, realPath } from "./memory/platform.ts";
@@ -105,19 +107,57 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
105
107
  const effectivePolicy = configuredPolicyOptions(base, options.repository === false ? undefined : cwd, options.policy);
106
108
  const policy = createStandalonePolicy(effectivePolicy), release = options.measureOnly ? Object.assign(() => {}, { verify: () => {} }) : registerReaderLease(base, options.nativeSession ? { signature: options.nativeSession.signature, busyTimeoutMs: 0 } : undefined);
107
109
  closers.push(release);
108
- const selection = readSelector(base).revision;
110
+ const initial = readSelector(base), selection = initial.revision;
109
111
  const sharded = !!lstatSync(join(base, "shards.json"), { throwIfNoEntry: false });
110
112
  const shardSelection = sharded ? JSON.stringify(readShardedSelection(base)) : undefined;
111
113
  const aliases = aliasedKeys(base, project), reconcile = aliases.length ? { canonical: project, aliases } : undefined;
114
+ // #396: every value the guard compares is derived from the binding's own bytes, so the per-value fence pays for a
115
+ // full read of those bytes twice per screened row. This fence answers the same question by hashing them instead,
116
+ // and hands the call back to the full comparison whenever an input moved, could not be read safely, or the reader
117
+ // reported more paths than the caller bounds. `fenceSupported` latches off, so a home this fence cannot describe
118
+ // keeps exactly today's cost.
119
+ const fenceHome = (() => { try { return realPath(base); } catch { return undefined; } })();
120
+ const fenceSelector = initial.selector as { pruneInputSetHash?: string; placementHead?: string } | undefined;
121
+ let fenceSupported = fenceHome !== undefined, fence: HomeBindingSnapshot | undefined;
122
+ let fencePaths = homeBindingPaths(fenceHome ?? base, fenceSelector);
112
123
  let drifted = false;
113
- const guard = () => {
124
+ const compareBinding = () => {
125
+ if (resolveAlias(base, requested) !== project || aliasedKeys(base, project).join("\n") !== aliases.join("\n")
126
+ || readSelector(base).revision !== selection || projectState(base, project) !== "active") throw new BindingChanged();
127
+ const split = !!lstatSync(join(base, "shards.json"), { throwIfNoEntry: false });
128
+ if (split !== sharded || split && JSON.stringify(readShardedSelection(base)) !== shardSelection) throw new BindingChanged();
129
+ };
130
+ const guard = (full = false) => {
114
131
  try {
115
132
  if (drifted) throw new BindingChanged();
116
133
  release.verify();
117
- if (resolveAlias(base, requested) !== project || aliasedKeys(base, project).join("\n") !== aliases.join("\n")
118
- || readSelector(base).revision !== selection || projectState(base, project) !== "active") throw new BindingChanged();
119
- const split = !!lstatSync(join(base, "shards.json"), { throwIfNoEntry: false });
120
- if (split !== sharded || split && JSON.stringify(readShardedSelection(base)) !== shardSelection) throw new BindingChanged();
134
+ if (!fenceSupported) { compareBinding(); return; }
135
+ const known = fence?.paths ?? fencePaths;
136
+ if (!full && fence !== undefined && sameHomeBinding(snapshotHomeBinding(known), fence)) return;
137
+ // Adopt only over a set that did not move while it was compared, and never leave this guard on an unproven
138
+ // state: a moved or newly reported set is re-read here, and two rounds that still disagree refuse. The caller's
139
+ // bound is read on the reported list before the expanded set is ever hashed.
140
+ let paths = known, adopted: HomeBindingSnapshot | undefined;
141
+ for (let attempt = 0; attempt < 2 && adopted === undefined; attempt++) {
142
+ const before = snapshotHomeBinding(paths);
143
+ const { paths: reported } = collectBindingReads(compareBinding);
144
+ const after = snapshotHomeBinding(paths);
145
+ const next = homeBindingPaths(fenceHome!, fenceSelector, reported);
146
+ // A set this fence cannot describe keeps today's cost: the comparison inside this bracket is the proof today's
147
+ // guard offers too, and every later guard reads the binding itself.
148
+ // The comparison above ran before the unsafe or over-limit observation, so it does not cover this instant: latch
149
+ // off, then compare once more before this caller proceeds. A throw lands in the catch below and refuses.
150
+ if (next.length > FENCE_MAX_PATHS || !fenceIsComplete(before) || !fenceIsComplete(after)) {
151
+ fence = undefined; fencePaths = next; fenceSupported = false; compareBinding(); return;
152
+ }
153
+ const sameSet = next.length === paths.length && next.every((path, index) => path === paths[index]);
154
+ // Only a set that did not move while it was compared, and whose two hashes agree, is stamped. Anything else is
155
+ // re-read here, and a second round that still disagrees throws instead of handing this caller's screen a state
156
+ // no comparison covered.
157
+ if (sameSet && sameHomeBinding(before, after)) adopted = after; else paths = next;
158
+ }
159
+ if (adopted === undefined) throw new BindingChanged();
160
+ fence = adopted; fencePaths = [...adopted.paths];
121
161
  } catch { drifted = true; throw new BindingChanged(); }
122
162
  };
123
163
  // Fixed native screening has no host callback to observe intermediate rows. Buffer
@@ -412,7 +452,7 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
412
452
  emitReserved(); coverage.capture = "partial";
413
453
  }
414
454
  }
415
- guard();
455
+ guard(true);
416
456
  let context = [header(coverage, reasons), ...(candidateLine ? [candidateLine] : []), ...lines].join("\n");
417
457
  while (Buffer.byteLength(context) > maximum && lines.length) {
418
458
  const repoIndex = lines.findLastIndex(line => line.startsWith('{"section":"repo",'));
package/src/setup.ts CHANGED
@@ -16,6 +16,8 @@ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
16
16
  import { fileURLToPath } from "node:url";
17
17
  import { isDeepStrictEqual, types } from "node:util";
18
18
  import { HOOK_EVENTS } from "./hook-contract.ts";
19
+ import { readEffectiveSyncPlacementWriters } from "./memory/sync-placement-effective-writers.ts";
20
+ import { placementMarkerState } from "./memory/sync-placement-guard.ts";
19
21
  import { memoryHome } from "./memory/home.ts";
20
22
  import { label, PLAIN, singleLine, type Style } from "./memory/style.ts";
21
23
  import { canonicalPath, memoryGitEnv, memoryGitSync, processLiveness, processSignature, realPath } from "./memory/platform.ts";
@@ -52,6 +54,8 @@ export interface SetupPlan {
52
54
  targets: SetupTarget[]; mode: "preview" | "apply" | "undo"; root?: InstallRoot;
53
55
  actions: { target: SetupTarget; version?: ClientVersion; files: string[]; receipt: string; cwd?: string; registration: string[] | null; lifecycle: string; available: boolean; hooks: PlannedHook[]; removes?: { file: string; event: string; command: string }[]; mcpChange: "add" | "replace" | "restore" | "unchanged"; commands: string[][]; state: string }[];
54
56
  notes: string[];
57
+ /** #551, additive: the placement-inventory warning, repeated on the apply receipt so `--apply` shows it too. */
58
+ placementWriter?: string;
55
59
  }
56
60
  const MAX = SETUP_CONFIG_BYTES, JOURNAL_MAX = 12 * MAX;
57
61
  const digest = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
@@ -261,6 +265,24 @@ function strayCaptures(target: SetupTarget, image: Image, current: string): { ev
261
265
  } catch { return []; }
262
266
  }
263
267
  const lifecycle = (target: SetupTarget) => target === "opencode" || target === "gemini" || target === "agy" ? "MCP only; native capture unavailable" : target === "jcode" ? "post_tool and turn_end capture hooks" : target === "claude" ? "seven bounded native hooks" : target === "pi" ? "session_shutdown incremental ingest" : "SessionEnd incremental ingest";
268
+ /**
269
+ * #551 AC2: the placement writer inventory this home's sync will verify. A root the inventory provably does not hold is named
270
+ * as such with the renewal step to take first; an inventory that cannot be read is reported as unverified, never as a missing
271
+ * entry. It writes nothing, refuses nothing and returns undefined on a home that is not activated for placement sync.
272
+ */
273
+ function placementWriterInventoryNote(root: string, home: string): string | undefined {
274
+ // #551 AC2: only a proven non-placement home stays silent. Markers that cannot be read or parsed prove nothing either way,
275
+ // so they fall through to the inventory read below, which reports the state as unverified instead of as a missing root.
276
+ if (placementMarkerState(home) === "not placement") return undefined;
277
+ let roots: readonly string[] | undefined;
278
+ try { roots = readEffectiveSyncPlacementWriters(home).roots; } catch { roots = undefined; }
279
+ if (roots === undefined) return "WARNING: the active placement writer inventory could not be verified here, so this root is neither confirmed nor refused. Setup registers it exactly as previewed and changes no inventory entry; check the inventory with the person before relying on placement sync.";
280
+ let canonical: string;
281
+ try { canonical = realPath(root); } catch { return undefined; }
282
+ if (roots.includes(canonical)) return undefined;
283
+ // #551 AC2: the suggested argument is shell-quoted, so a root with a space, a quote or a shell metacharacter stays one argument.
284
+ return `WARNING: this install root is outside the active placement writer inventory, so placement sync stops in writer verification once setup registers it. Renew the inventory first with the person - amem migrate --sync-placement --dry-run --writer-root ${quote(canonical)}, then --apply - and rerun setup after that. Setup writes no inventory entry and never refuses on this alone.`;
285
+ }
264
286
  export function planSetup(target: string, mode: SetupPlan["mode"] = "preview", options: SetupContext = {}): SetupPlan {
265
287
  if (target !== "all" && !SETUP_TARGETS.includes(target as SetupTarget)) throw Error("usage: amem setup claude|codex|kimi|pi|qwen|jcode|opencode|gemini|agy|all [--apply|--undo]");
266
288
  const targets: SetupTarget[] = target === "all" ? [...SETUP_ALL_TARGETS] : [target as SetupTarget];
@@ -292,9 +314,12 @@ export function planSetup(target: string, mode: SetupPlan["mode"] = "preview", o
292
314
  if (!c.workspace.ignored) pluginNotes.push("WARNING: .agents/mcp_config.json is not Git-ignored; it contains absolute local paths. Setup will refuse it if it becomes tracked.");
293
315
  }
294
316
  if (c.root) pluginNotes.push(`Registers the install root ${c.root.path} (amem ${c.root.version}) for hooks and MCP; current registrations change only on --apply.`);
317
+ // #551: the root this plan registers may not be in the home's active placement inventory, which stops sync in writer verification.
318
+ const placementWriter = placementWriterInventoryNote(c.root?.path ?? fileURLToPath(new URL("..", import.meta.url)), dirname(c.state));
319
+ if (placementWriter) pluginNotes.push(placementWriter);
295
320
  if (target === "all") pluginNotes.push("Antigravity is repository-scoped and excluded from all; run amem setup agy explicitly inside its repository.");
296
321
  if (targets.includes("jcode")) pluginNotes.push("Launch Jcode with JCODE_DISABLE_CLAUDE_MCP=1 and without a same-name project override: imported Claude stdio entries can replace this private amem binding with a shared daemon-cwd server. Use a new workspace-bound session when changing projects.");
297
- return { targets, mode, ...(c.root ? { root: c.root } : {}), actions: targets.map(target => {
322
+ return { targets, mode, ...(c.root ? { root: c.root } : {}), ...(placementWriter ? { placementWriter } : {}), actions: targets.map(target => {
298
323
  const receipted = receipt(c, target, false), files = mode === "undo" && receipted ? receipted.changes.map(change => change.path) : c.paths[target];
299
324
  for (const file of files) read(file);
300
325
  const stale = mode !== "undo" && !!receipted && staleReceipt(target, receipted);
@@ -603,7 +628,7 @@ function prepare(c: ReturnType<typeof context>, target: SetupTarget, options: Se
603
628
  }
604
629
  function save(c: ReturnType<typeof context>, value: Receipt): void { write(journal(c, value.target), image(JSON.stringify(value) + "\n")); }
605
630
  function available(c: ReturnType<typeof context>, target: SetupTarget, options: SetupContext): boolean { return target === "agy" || !!options.native || Bun.which(target, { PATH: c.env.PATH ?? process.env.PATH }) !== null; }
606
- export interface SetupApplyResult { applied: SetupTarget[]; unchanged: SetupTarget[]; skipped?: { target: SetupTarget; reason: string }[] }
631
+ export interface SetupApplyResult { applied: SetupTarget[]; unchanged: SetupTarget[]; skipped?: { target: SetupTarget; reason: string }[]; warnings?: string[] }
607
632
  /** Claim only a directory this invocation actually created, never one merely absent at preview. */
608
633
  function prepareCreatedDirectory(c: ReturnType<typeof context>, value: Receipt): void {
609
634
  if (value.target !== "agy") return;
@@ -686,7 +711,9 @@ function withSetupLock<T>(options: SetupContext, run: () => T): T {
686
711
  export function applySetup(plan: SetupPlan, options: SetupContext = {}): SetupApplyResult {
687
712
  if (plan.targets.includes("jcode")) assertJcodeHome(options.env ?? process.env);
688
713
  if (plan.targets.includes("agy")) contextForPlan(plan, options);
689
- return withSetupLock(options, () => applyUnlocked(plan, options));
714
+ const result = withSetupLock(options, () => applyUnlocked(plan, options));
715
+ // #551 AC2: `--apply` prints only this result, so the plan's placement warning is repeated on the receipt.
716
+ return plan.placementWriter ? { ...result, warnings: [plan.placementWriter] } : result;
690
717
  }
691
718
  export function undoSetup(plan: SetupPlan, options: SetupContext = {}): { restored: SetupTarget[] } {
692
719
  if (plan.targets.includes("jcode")) assertJcodeHome(options.env ?? process.env);
@@ -730,7 +757,8 @@ export function setupPlanText(plan: SetupPlan, s: Style = PLAIN): string {
730
757
  function setupResultText(result: SetupApplyResult | { restored: SetupTarget[] }, s: Style): string {
731
758
  if ("restored" in result) return `${label(s, "ok")} restored: ${result.restored.join(", ") || "none"}`;
732
759
  return [`${label(s, "ok")} applied: ${result.applied.join(", ") || "none"}`, `${label(s, "ok")} unchanged: ${result.unchanged.join(", ") || "none"}`,
733
- ...(result.skipped ?? []).map(item => `${label(s, "skipped")} ${item.target}: ${item.reason}`)].join("\n");
760
+ ...(result.skipped ?? []).map(item => `${label(s, "skipped")} ${item.target}: ${item.reason}`),
761
+ ...(result.warnings ?? []).map(warning => `${label(s, "attention")} ${warning}`)].join("\n");
734
762
  }
735
763
 
736
764
  /** Compatibility formatter for confirmation-style callers: the raw plan under `--json`, the readable plan otherwise. */