@ftrdotdev/pi-tracker 0.6.0 → 0.7.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.
@@ -2,16 +2,30 @@ import type { JsonObject } from "@earendil-works/pi-ai";
2
2
  import { formatItemRef } from "../core/deps.ts";
3
3
  import { NEEDS_CONTEXT_LABEL, NEEDS_NONE_LABEL, type CompactionQuestion } from "./classifier.ts";
4
4
  import type { CompactionCandidate } from "./candidate.ts";
5
+ import type { DeclaredReference, ProductState, ReferenceState } from "./observations.ts";
5
6
 
6
7
  /**
7
- * The bounded classifier input: every ready candidate, each with its class and
8
- * its relationship to the completed batch, plus the batch itself as referenced
9
- * prior work. The transcript is never read.
8
+ * The bounded classifier input: every ready candidate, each with its title,
9
+ * its description, its class, its relationship to the completed batch, and its
10
+ * resolved declarations, plus the batch itself as referenced prior work. One
11
+ * survival instruction states what the item may still reach after compaction.
12
+ * The transcript is never read.
10
13
  */
11
14
 
12
15
  /** Shared prefix of the per-candidate classifier question key. */
13
16
  export const QUESTION_KEY_PREFIX = "needsCompletedContext";
14
17
 
18
+ /** The most references one candidate's digest carries. */
19
+ export const REFERENCE_CAP = 8;
20
+ /** The most products one candidate's digest carries. */
21
+ export const PRODUCT_CAP = 4;
22
+ /** Characters of a description's first paragraph the digest keeps. */
23
+ export const DESCRIPTION_LIMIT = 400;
24
+
25
+ /** What survives compaction, stated once for the whole call. */
26
+ export const SURVIVAL_INSTRUCTION =
27
+ "After compaction, each item's title and description survive, and a file that exists on disk survives. The transcript does not survive, so ask only whether the item needs a detail that its own title, its description, or an existing file does not carry.";
28
+
15
29
  /**
16
30
  * A safe, unique question id for one candidate. Cloudflare Workers AI rejects
17
31
  * any id that does not match `^[A-Za-z0-9_.-]{1,100}$`, so the item reference
@@ -25,17 +39,90 @@ const relationshipOf = (candidate: CompactionCandidate): string =>
25
39
  ? `depends on ${candidate.completed[0]?.ref ?? "the completed work"}`
26
40
  : `independent of ${candidate.completed.map((item) => item.ref).join(", ")}`;
27
41
 
28
- /**
29
- * One entry per candidate plus the completed batch once. Exactly two keys.
30
- */
31
- export const buildDigests = (candidates: readonly CompactionCandidate[]): JsonObject => ({
32
- candidates: candidates.map((candidate) => ({
42
+ /** The first paragraph of a text, then the cap with a marker naming the cut. */
43
+ const descriptionOf = (text: string): string => {
44
+ const paragraph = text.split(/\n\s*\n/)[0]?.trim() ?? "";
45
+ return paragraph.length <= DESCRIPTION_LIMIT
46
+ ? paragraph
47
+ : `${paragraph.slice(0, DESCRIPTION_LIMIT)}… [${paragraph.length - DESCRIPTION_LIMIT} more characters]`;
48
+ };
49
+
50
+ /** One declared reference with the state it resolved to. */
51
+ const referenceOf = (reference: DeclaredReference, state: ReferenceState): JsonObject =>
52
+ reference.kind === "decision"
53
+ ? { kind: "decision", topic: reference.topic, state }
54
+ : {
55
+ kind: "path",
56
+ path: reference.path,
57
+ ...(reference.symbol === undefined ? {} : { symbol: reference.symbol }),
58
+ ...(reference.span === undefined ? {} : { span: reference.span }),
59
+ state,
60
+ };
61
+
62
+ /** A bounded candidate state: title, description, relationship, declarations. */
63
+ const candidateOf = (
64
+ candidate: CompactionCandidate,
65
+ facts: {
66
+ readonly references: readonly {
67
+ readonly reference: DeclaredReference;
68
+ readonly state: ReferenceState;
69
+ }[];
70
+ readonly products: readonly {
71
+ readonly product: { readonly path: string };
72
+ readonly state: ProductState;
73
+ }[];
74
+ },
75
+ ): JsonObject => {
76
+ const references = facts.references.slice(0, REFERENCE_CAP);
77
+ const products = facts.products.slice(0, PRODUCT_CAP);
78
+ const droppedReferences = facts.references.length - references.length;
79
+ const droppedProducts = facts.products.length - products.length;
80
+ return {
33
81
  ref: formatItemRef(candidate.listName, candidate.id),
34
82
  text: candidate.text,
83
+ ...(candidate.description === undefined || candidate.description.length === 0
84
+ ? {}
85
+ : { description: descriptionOf(candidate.description) }),
35
86
  class: candidate.class,
36
87
  relationship: relationshipOf(candidate),
88
+ references: references.map((entry) => referenceOf(entry.reference, entry.state)),
89
+ products: products.map((entry) => ({ path: entry.product.path, state: entry.state })),
90
+ ...(droppedReferences === 0
91
+ ? {}
92
+ : { referenceCut: `… [${droppedReferences} more references declared]` }),
93
+ ...(droppedProducts === 0
94
+ ? {}
95
+ : { productCut: `… [${droppedProducts} more products declared]` }),
96
+ };
97
+ };
98
+
99
+ /**
100
+ * One entry per candidate plus the completed batch once, plus the survival
101
+ * instruction. The state is facts only: a title, a description, a class, a
102
+ * relationship, resolved references, resolved products, and their cut markers.
103
+ */
104
+ export const buildDigests = (
105
+ candidates: readonly CompactionCandidate[],
106
+ facts: readonly {
107
+ readonly references: readonly {
108
+ readonly reference: DeclaredReference;
109
+ readonly state: ReferenceState;
110
+ }[];
111
+ readonly products: readonly {
112
+ readonly product: { readonly path: string };
113
+ readonly state: ProductState;
114
+ }[];
115
+ }[] = [],
116
+ ): JsonObject => ({
117
+ candidates: candidates.map((candidate, index) =>
118
+ candidateOf(candidate, facts[index] ?? { references: [], products: [] }),
119
+ ),
120
+ completed: (candidates[0]?.completed ?? []).map((item) => ({
121
+ ref: item.ref,
122
+ text: item.text,
123
+ ...(item.description === undefined ? {} : { description: item.description }),
37
124
  })),
38
- completed: (candidates[0]?.completed ?? []).map((item) => ({ ref: item.ref, text: item.text })),
125
+ survival: SURVIVAL_INSTRUCTION,
39
126
  });
40
127
 
41
128
  /**
@@ -0,0 +1,135 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { Effect } from "effect";
3
+ import { fingerprintOf, type FileProbe } from "./observations.ts";
4
+ import { makeFootprintRecorder, newSideSpans, pendingOf, type ToolEvent } from "./footprint.ts";
5
+
6
+ /** A probe over a path-to-text map that records every read path. */
7
+ const countingProbe = (
8
+ files: Readonly<Record<string, string>>,
9
+ ): { readonly probe: FileProbe; readonly reads: string[] } => {
10
+ const reads: string[] = [];
11
+ return {
12
+ reads,
13
+ probe: {
14
+ read: (path) => {
15
+ reads.push(path);
16
+ return files[path];
17
+ },
18
+ findSymbol: () => [],
19
+ },
20
+ };
21
+ };
22
+
23
+ const write = (path: string, patch: string): ToolEvent => ({
24
+ phase: "end",
25
+ toolName: "write",
26
+ args: { path },
27
+ details: { patch },
28
+ });
29
+
30
+ const paths = (entries: readonly { readonly path: string }[]): readonly string[] =>
31
+ entries.map((entry) => entry.path);
32
+
33
+ // ---------------------------------------------------------------------------
34
+ // Projection
35
+ // ---------------------------------------------------------------------------
36
+
37
+ it("capture projects a write call into a path and its spans", () => {
38
+ const pending = pendingOf({
39
+ phase: "end",
40
+ toolName: "write",
41
+ args: { path: "src/a.ts" },
42
+ details: { patch: "@@ -1,2 +3,4 @@\n context" },
43
+ });
44
+ assert.deepStrictEqual(pending, { kind: "write", path: "src/a.ts", spans: ["3-6"] });
45
+ });
46
+
47
+ it("newSideSpans reads the new-side range of each hunk and caps at four", () => {
48
+ assert.deepStrictEqual(
49
+ newSideSpans({ patch: "@@ -1,0 +1,1 @@\n@@ -4,2 +8 @@\n@@ -9 +20,3 @@" }),
50
+ ["1", "8", "20-22"],
51
+ );
52
+ assert.deepStrictEqual(newSideSpans({ firstChangedLine: 12 }), ["12"]);
53
+ assert.deepStrictEqual(newSideSpans({}), []);
54
+ });
55
+
56
+ // ---------------------------------------------------------------------------
57
+ // The recorder
58
+ // ---------------------------------------------------------------------------
59
+
60
+ it.effect("capture never reads the disk", () =>
61
+ Effect.gen(function* () {
62
+ const files = Object.fromEntries(
63
+ Array.from({ length: 10 }, (_value, index) => [`src/f${index}.ts`, "one\ntwo"]),
64
+ );
65
+ const { probe, reads } = countingProbe(files);
66
+ const parts = yield* makeFootprintRecorder(probe);
67
+ for (let index = 0; index < 10; index += 1) {
68
+ yield* parts.recorder.capture(write(`src/f${index}.ts`, "@@ -1,0 +1,2 @@"));
69
+ }
70
+ assert.strictEqual(reads.length, 0);
71
+ // The snapshot is the drain: only now does the probe see a read.
72
+ yield* parts.recorder.snapshot;
73
+ assert.strictEqual(reads.length, 10);
74
+ }),
75
+ );
76
+
77
+ it.effect("repeated writes to one path coalesce into one derivation read", () =>
78
+ Effect.gen(function* () {
79
+ const { probe, reads } = countingProbe({ "src/a.ts": "1\n2\n3\n4\n5\n6\n7\n8" });
80
+ const parts = yield* makeFootprintRecorder(probe);
81
+ yield* parts.recorder.capture(write("src/a.ts", "@@ -1,1 +1,2 @@"));
82
+ yield* parts.recorder.capture(write("src/a.ts", "@@ -1,1 +3,2 @@"));
83
+ yield* parts.recorder.capture(write("src/a.ts", "@@ -1,1 +5,2 @@"));
84
+ const footprint = yield* parts.recorder.snapshot;
85
+ assert.deepStrictEqual(reads, ["src/a.ts"]);
86
+ assert.deepStrictEqual(footprint.wrote, [
87
+ { path: "src/a.ts", spans: ["5-6"], fingerprint: fingerprintOf("5\n6") },
88
+ ]);
89
+ }),
90
+ );
91
+
92
+ it.effect("parallel events for two paths derive independently", () =>
93
+ Effect.gen(function* () {
94
+ const { probe } = countingProbe({
95
+ "src/a.ts": "1\n2\n3\n4\n5\n6",
96
+ "src/b.ts": "x\n1\n2",
97
+ });
98
+ const parts = yield* makeFootprintRecorder(probe);
99
+ yield* parts.recorder.capture(write("src/a.ts", "@@ -1,2 +3,4 @@"));
100
+ yield* parts.recorder.capture(write("src/b.ts", "@@ -1,1 +1,2 @@"));
101
+ const footprint = yield* parts.recorder.snapshot;
102
+ assert.deepStrictEqual(paths(footprint.wrote), ["src/a.ts", "src/b.ts"]);
103
+ assert.deepStrictEqual(footprint.wrote[0]?.spans, ["3-6"]);
104
+ assert.deepStrictEqual(footprint.wrote[1]?.spans, ["1-2"]);
105
+ assert.strictEqual(footprint.wrote[0]?.fingerprint, fingerprintOf("3\n4\n5\n6"));
106
+ assert.strictEqual(footprint.wrote[1]?.fingerprint, fingerprintOf("x\n1"));
107
+ }),
108
+ );
109
+
110
+ it.effect("a snapshot returns only ready facts and clears on consume", () =>
111
+ Effect.gen(function* () {
112
+ const { probe } = countingProbe({ "src/a.ts": "1\n2\n3\n4\n5\n6" });
113
+ // `src/b.ts` cannot be derived: the probe throws, which leaves its fact out
114
+ // of the snapshot. The resolver abstains on the missing path.
115
+ const failing: FileProbe = {
116
+ read: (path) => {
117
+ if (path === "src/b.ts") throw new Error("not ready");
118
+ return probe.read(path);
119
+ },
120
+ findSymbol: () => [],
121
+ };
122
+ const parts = yield* makeFootprintRecorder(failing);
123
+ yield* parts.recorder.capture(write("src/a.ts", "@@ -1,1 +1,2 @@"));
124
+ yield* parts.recorder.capture(write("src/b.ts", "@@ -1,1 +1,2 @@"));
125
+
126
+ const first = yield* parts.recorder.snapshot;
127
+ assert.deepStrictEqual(paths(first.wrote), ["src/a.ts"]);
128
+
129
+ const consumed = yield* parts.recorder.consume;
130
+ assert.deepStrictEqual(paths(consumed.wrote), ["src/a.ts"]);
131
+
132
+ const second = yield* parts.recorder.snapshot;
133
+ assert.deepStrictEqual(second.wrote, []);
134
+ }),
135
+ );
@@ -0,0 +1,387 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { readFileSync, statSync } from "node:fs";
3
+ import { resolve } from "node:path";
4
+ import { Context, Effect, Layer, Queue, Ref } from "effect";
5
+ import {
6
+ emptyFootprint,
7
+ fingerprintOf,
8
+ PRODUCING_TOOLS,
9
+ spanTextOf,
10
+ type BatchFootprint,
11
+ type FileProbe,
12
+ type WrittenPath,
13
+ } from "./observations.ts";
14
+
15
+ /**
16
+ * The batch footprint recorder.
17
+ *
18
+ * The event path is hot, so `capture` does one thing: project the event into a
19
+ * small record and fold it into the pending batch. It never reads the disk and
20
+ * never yields. `snapshot` drains the pending batch, reads each written file
21
+ * once through the injected `FileProbe`, and returns the ready facts; `consume`
22
+ * returns and clears them. A later event for a path supersedes an earlier one,
23
+ * and two paths derive independently. A path the probe cannot read is absent,
24
+ * and the resolver abstains on it.
25
+ *
26
+ * Deletions and workspace-wide symbol moves are not parsed: `deleted` stays
27
+ * empty, and the resolver reports those references as unresolved, which keeps
28
+ * the context.
29
+ */
30
+
31
+ // --------------------------------------------------------------------------
32
+ // Event projection
33
+ // --------------------------------------------------------------------------
34
+
35
+ /**
36
+ * The bounded projection of one tool event. The bridge builds it from pi's
37
+ * `tool_execution_start` and `tool_execution_end` events: the args are the
38
+ * call's `path` and `command`, and `details` is the tool result's `details`
39
+ * (the object that carries the unified `patch`).
40
+ */
41
+ export interface ToolEvent {
42
+ readonly phase: "start" | "end";
43
+ readonly toolName: string;
44
+ readonly args?: {
45
+ readonly path?: string;
46
+ readonly command?: string;
47
+ };
48
+ readonly details?: unknown;
49
+ }
50
+
51
+ /** One path the batch wrote, before the file is read. */
52
+ interface PendingWrite {
53
+ readonly kind: "write";
54
+ readonly path: string;
55
+ readonly spans: readonly string[];
56
+ }
57
+
58
+ /** One path the batch read. */
59
+ interface PendingRead {
60
+ readonly kind: "read";
61
+ readonly path: string;
62
+ }
63
+
64
+ /** One command the batch ran. */
65
+ interface PendingCommand {
66
+ readonly kind: "command";
67
+ readonly command: string;
68
+ }
69
+
70
+ type Pending = PendingWrite | PendingRead | PendingCommand;
71
+
72
+ /** One new-side hunk header of a unified patch: `@@ -a,b +c,d @@`. */
73
+ const HUNK = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/;
74
+
75
+ const textOf = (value: unknown): string => (typeof value === "string" ? value : "");
76
+
77
+ /**
78
+ * The new-side line range(s) a tool result touched, e.g. `["3-6", "20"]`.
79
+ * Mirrors `evals/evidence.ts` `lineRangesOf`, since the eval record and the
80
+ * live footprint must read the same patch shape. Four ranges is the cap.
81
+ */
82
+ export const newSideSpans = (details: unknown): readonly string[] => {
83
+ const patch = textOf((details as { readonly patch?: unknown } | undefined)?.patch);
84
+ const spans: string[] = [];
85
+ for (const line of patch.split("\n")) {
86
+ const match = HUNK.exec(line);
87
+ if (match === null) continue;
88
+ const start = Number(match[1]);
89
+ const count = match[2] === undefined ? 1 : Number(match[2]);
90
+ const end = count <= 1 ? start : start + count - 1;
91
+ spans.push(start === end ? String(start) : `${start}-${end}`);
92
+ }
93
+ if (spans.length > 0) return spans.slice(0, 4);
94
+ const first = (details as { readonly firstChangedLine?: unknown } | undefined)?.firstChangedLine;
95
+ return typeof first === "number" && Number.isFinite(first) ? [String(first)] : [];
96
+ };
97
+
98
+ /**
99
+ * Project one event into the record the batch holds, or undefined when the
100
+ * event names nothing the footprint records. A producing tool contributes a
101
+ * write only at the end phase, because only then does the result carry spans.
102
+ */
103
+ export const pendingOf = (event: ToolEvent): Pending | undefined => {
104
+ const path = event.args?.path;
105
+ const command = event.args?.command;
106
+ if (path !== undefined && PRODUCING_TOOLS.has(event.toolName)) {
107
+ if (event.phase !== "end") return undefined;
108
+ return { kind: "write", path, spans: newSideSpans(event.details) };
109
+ }
110
+ if (path !== undefined && event.toolName === "read") return { kind: "read", path };
111
+ if (command !== undefined) return { kind: "command", command };
112
+ return undefined;
113
+ };
114
+
115
+ // --------------------------------------------------------------------------
116
+ // Derived facts
117
+ // --------------------------------------------------------------------------
118
+
119
+ /** The batch captured but not yet derived, keyed by path. Last write wins. */
120
+ interface PendingBatch {
121
+ readonly writes: ReadonlyMap<string, PendingWrite>;
122
+ readonly reads: ReadonlySet<string>;
123
+ readonly commands: ReadonlySet<string>;
124
+ }
125
+
126
+ const emptyPending = (): PendingBatch => ({
127
+ writes: new Map(),
128
+ reads: new Set(),
129
+ commands: new Set(),
130
+ });
131
+
132
+ /** The derived facts, keyed by path. Insertion order is the order of derivation. */
133
+ interface Facts {
134
+ readonly wrote: ReadonlyMap<string, WrittenPath>;
135
+ readonly read: ReadonlySet<string>;
136
+ readonly commands: ReadonlySet<string>;
137
+ }
138
+
139
+ const emptyFacts = (): Facts => ({ wrote: new Map(), read: new Set(), commands: new Set() });
140
+
141
+ const footprintOf = (facts: Facts): BatchFootprint => ({
142
+ ...emptyFootprint(),
143
+ wrote: [...facts.wrote.values()],
144
+ read: [...facts.read],
145
+ commands: [...facts.commands],
146
+ });
147
+
148
+ /**
149
+ * The fingerprint of a written region: the whole file when no span is known,
150
+ * the declared ranges when there are any, and no fingerprint when the file is
151
+ * shorter than the ranges. A missing fingerprint never reports drift.
152
+ */
153
+ const fingerprintOfWrite = (text: string, spans: readonly string[]): string | undefined => {
154
+ if (spans.length === 0) return fingerprintOf(text);
155
+ const region = spanTextOf(text, spans.join(","));
156
+ return region === undefined ? undefined : fingerprintOf(region);
157
+ };
158
+
159
+ /** Read each written path once and derive its spans and fingerprint. */
160
+ const deriveWrites = (
161
+ probe: FileProbe,
162
+ writes: ReadonlyMap<string, PendingWrite>,
163
+ ): readonly WrittenPath[] => {
164
+ const derived: WrittenPath[] = [];
165
+ for (const [path, entry] of writes) {
166
+ let text: string | undefined;
167
+ try {
168
+ text = probe.read(path);
169
+ } catch {
170
+ // A path the probe cannot read is not ready; the resolver abstains on it.
171
+ text = undefined;
172
+ }
173
+ if (text === undefined) continue;
174
+ const fingerprint = fingerprintOfWrite(text, entry.spans);
175
+ derived.push({
176
+ path,
177
+ spans: entry.spans,
178
+ ...(fingerprint === undefined ? {} : { fingerprint }),
179
+ });
180
+ }
181
+ return derived;
182
+ };
183
+
184
+ // --------------------------------------------------------------------------
185
+ // The recorder service
186
+ // --------------------------------------------------------------------------
187
+
188
+ /** The recorder plus its background worker, for a caller that wants one. */
189
+ export interface FootprintRecorderParts {
190
+ readonly recorder: FootprintRecorder["Service"];
191
+ /** Drains the pending batch whenever capture signals new work. */
192
+ readonly worker: Effect.Effect<never>;
193
+ }
194
+
195
+ /**
196
+ * Build the recorder and a background drain worker. A test uses the recorder
197
+ * directly and drains it with `snapshot`; the layer forks the worker so
198
+ * production derives in the background as well.
199
+ */
200
+ export const makeFootprintRecorder = (probe: FileProbe): Effect.Effect<FootprintRecorderParts> =>
201
+ Effect.gen(function* () {
202
+ const pending = yield* Ref.make<PendingBatch>(emptyPending());
203
+ const facts = yield* Ref.make<Facts>(emptyFacts());
204
+ const signal = yield* Queue.unbounded<void>();
205
+
206
+ /**
207
+ * Take the pending batch in one step and turn it into facts. Atomically
208
+ * clearing first means two concurrent drains cannot double-read a path.
209
+ */
210
+ const drain = Ref.modify(pending, (current) => [current, emptyPending()]).pipe(
211
+ Effect.flatMap((batch) =>
212
+ Effect.sync(() => deriveWrites(probe, batch.writes)).pipe(
213
+ Effect.flatMap((derived) =>
214
+ Ref.update(facts, (current) => ({
215
+ wrote: new Map([
216
+ ...current.wrote,
217
+ ...derived.map((entry) => [entry.path, entry] as const),
218
+ ]),
219
+ read: new Set([...current.read, ...batch.reads]),
220
+ commands: new Set([...current.commands, ...batch.commands]),
221
+ })).pipe(
222
+ Effect.andThen(
223
+ derived.length === 0
224
+ ? Effect.void
225
+ : Effect.logDebug(
226
+ `tracker: footprint derived ${derived
227
+ .map(
228
+ (entry) =>
229
+ `${entry.path} [${entry.spans.join(",") || "all"}] ${entry.fingerprint ?? "no-fingerprint"}`,
230
+ )
231
+ .join(", ")}`,
232
+ ),
233
+ ),
234
+ ),
235
+ ),
236
+ ),
237
+ ),
238
+ );
239
+
240
+ const drainAll = Effect.gen(function* () {
241
+ // A signal per capture may collapse into one drain; loop until the batch
242
+ // is empty so nothing captured before the last signal is left behind.
243
+ let drained = false;
244
+ do {
245
+ const before = yield* Ref.get(pending);
246
+ drained = before.writes.size > 0 || before.reads.size > 0 || before.commands.size > 0;
247
+ yield* drain;
248
+ } while (drained);
249
+ });
250
+
251
+ const capture = Effect.fnUntraced(function* (event: ToolEvent) {
252
+ const entry = pendingOf(event);
253
+ if (entry === undefined) return;
254
+ yield* Ref.update(pending, (current) => {
255
+ if (entry.kind === "write") {
256
+ return { ...current, writes: new Map([...current.writes, [entry.path, entry]]) };
257
+ }
258
+ if (entry.kind === "read") {
259
+ return { ...current, reads: new Set([...current.reads, entry.path]) };
260
+ }
261
+ return { ...current, commands: new Set([...current.commands, entry.command]) };
262
+ });
263
+ yield* Queue.offer(signal, undefined);
264
+ });
265
+
266
+ const snapshot = drainAll.pipe(Effect.andThen(Ref.get(facts)), Effect.map(footprintOf));
267
+
268
+ const consume = snapshot.pipe(
269
+ Effect.flatMap((footprint) => Ref.set(facts, emptyFacts()).pipe(Effect.as(footprint))),
270
+ );
271
+
272
+ const worker = Effect.forever(
273
+ Effect.gen(function* () {
274
+ // Extra signals collapse into an empty drain, which is harmless.
275
+ yield* Queue.take(signal);
276
+ yield* drainAll;
277
+ }),
278
+ );
279
+
280
+ return {
281
+ recorder: FootprintRecorder.of({ capture, snapshot, consume }),
282
+ worker,
283
+ };
284
+ });
285
+
286
+ /**
287
+ * The batch footprint recorder. `capture` folds an event into the batch and
288
+ * never reads the disk; `snapshot` drains and returns the ready facts;
289
+ * `consume` returns and clears them.
290
+ */
291
+ export class FootprintRecorder extends Context.Service<
292
+ FootprintRecorder,
293
+ {
294
+ readonly capture: (event: ToolEvent) => Effect.Effect<void>;
295
+ readonly snapshot: Effect.Effect<BatchFootprint>;
296
+ readonly consume: Effect.Effect<BatchFootprint>;
297
+ }
298
+ >()("tracker/FootprintRecorder") {
299
+ static readonly layer = (probe: FileProbe): Layer.Layer<FootprintRecorder> =>
300
+ Layer.effect(
301
+ FootprintRecorder,
302
+ Effect.gen(function* () {
303
+ const parts = yield* makeFootprintRecorder(probe);
304
+ yield* Effect.forkScoped(parts.worker);
305
+ return parts.recorder;
306
+ }),
307
+ );
308
+ }
309
+
310
+ // --------------------------------------------------------------------------
311
+ // The production probe
312
+ // --------------------------------------------------------------------------
313
+
314
+ /** The bounds the production probe keeps on every disk read. */
315
+ export const PROBE_DEFAULTS = {
316
+ maxReadBytes: 256 * 1024,
317
+ findSymbolTimeoutMillis: 2_000,
318
+ findSymbolMaxPaths: 64,
319
+ findSymbolMaxBufferBytes: 1024 * 1024,
320
+ } as const;
321
+
322
+ export interface ProductionProbeOptions {
323
+ /** The workspace root every relative path resolves against. Defaults to cwd. */
324
+ readonly root?: string;
325
+ readonly maxReadBytes?: number;
326
+ readonly findSymbolTimeoutMillis?: number;
327
+ readonly findSymbolMaxPaths?: number;
328
+ }
329
+
330
+ /**
331
+ * The probe the product passes: one bounded `readFileSync` per path and one
332
+ * bounded `rg --files-with-matches` per symbol. Every failure — a missing
333
+ * `rg`, a nonzero exit, a timeout, a file over the size cap — returns an empty
334
+ * result, which resolves to `unresolved` and never compacts.
335
+ */
336
+ export const productionProbe = (options: ProductionProbeOptions = {}): FileProbe => {
337
+ const root = options.root ?? process.cwd();
338
+ const maxReadBytes = options.maxReadBytes ?? PROBE_DEFAULTS.maxReadBytes;
339
+ const findSymbolTimeoutMillis =
340
+ options.findSymbolTimeoutMillis ?? PROBE_DEFAULTS.findSymbolTimeoutMillis;
341
+ const findSymbolMaxPaths = options.findSymbolMaxPaths ?? PROBE_DEFAULTS.findSymbolMaxPaths;
342
+
343
+ return {
344
+ read: (path) => {
345
+ try {
346
+ const full = resolve(root, path);
347
+ const stat = statSync(full);
348
+ if (!stat.isFile() || stat.size > maxReadBytes) return undefined;
349
+ return readFileSync(full, "utf8");
350
+ } catch {
351
+ return undefined;
352
+ }
353
+ },
354
+ findSymbol: (symbol) => {
355
+ if (symbol.trim().length === 0) return [];
356
+ try {
357
+ const output = execFileSync(
358
+ "rg",
359
+ [
360
+ "--files-with-matches",
361
+ "--fixed-strings",
362
+ "--glob",
363
+ "!**/node_modules/**",
364
+ "--",
365
+ symbol,
366
+ ".",
367
+ ],
368
+ {
369
+ cwd: root,
370
+ timeout: findSymbolTimeoutMillis,
371
+ maxBuffer: PROBE_DEFAULTS.findSymbolMaxBufferBytes,
372
+ encoding: "utf8",
373
+ stdio: ["ignore", "pipe", "ignore"],
374
+ },
375
+ );
376
+ return output
377
+ .split("\n")
378
+ .map((line) => line.trim())
379
+ .filter((line) => line.length > 0)
380
+ .map((line) => line.replace(/^\.\//, ""))
381
+ .slice(0, findSymbolMaxPaths);
382
+ } catch {
383
+ return [];
384
+ }
385
+ },
386
+ };
387
+ };