@capybara-hq/kernel 0.1.0-rc.100 → 0.1.0-rc.102

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.
@@ -18,42 +18,69 @@ const VALUE_MAX_CHARS = 8192;
18
18
  */
19
19
  export const WRITE_BASE_SETTLE_MS = 3_000;
20
20
  /**
21
- * Reads the value of one top-level string property of a JSON object streamed in fragments, without
22
- * re-reading the buffer: each {@link feed} scans only the new fragment with the carried state.
23
- * The value is known once its closing quote arrived (a half path is not a path). A property of a
24
- * nested object or array, a non-string value, a top level that is not an object, or a value
25
- * above {@link VALUE_MAX_CHARS} gives nothing.
21
+ * Reads top-level string properties of a JSON object streamed in fragments, without re-reading the
22
+ * buffer: each {@link feed} scans only the new fragment with the carried state. For each watched
23
+ * property it records when its string value opened and closed (one event counter, so the order of
24
+ * two properties is known even within one fragment), its raw head while open ({@link prefix}),
25
+ * and its value once the closing quote arrived (a half path is not a path). A property of a nested
26
+ * object or array, a non-string value, a top level that is not an object, or a value above its cap
27
+ * in `drop` mode gives nothing. The first occurrence of a key counts.
26
28
  */
27
- export class TopLevelStringProperty {
28
- prop;
29
+ export class TopLevelStrings {
29
30
  depth = 0;
30
31
  inString = false;
31
32
  escaped = false;
32
33
  /** At depth 1, the next string is a key. */
33
34
  expectKey = false;
34
- /** What the string being read is. */
35
- role = "other";
36
- /** The raw text of the key or value being read (between its quotes). */
37
- raw = "";
35
+ /** What the string being read is: a key, a watched value, or anything else. */
36
+ role = null;
37
+ /** The raw text of the key being read. */
38
+ keyRaw = "";
38
39
  /** The top-level key read last, until its `:`; null when unknown or too long. */
39
40
  key = null;
40
41
  /** The key whose value comes next at depth 1. */
41
42
  valueOf = null;
42
- result = null;
43
- done = false;
44
- constructor(prop) {
45
- this.prop = prop;
43
+ events = 0;
44
+ ended = false;
45
+ states = new Map();
46
+ constructor(props) {
47
+ for (const spec of props) {
48
+ this.states.set(spec.name, {
49
+ spec,
50
+ state: { raw: "", openedAt: 0, closedAt: 0, value: null, dead: false, cut: false },
51
+ });
52
+ }
46
53
  }
47
- /** Scans `fragment`; returns the property's value once known, null before (and when none). */
54
+ /** Scans `fragment`. */
48
55
  feed(fragment) {
49
- if (this.done)
50
- return this.result;
56
+ if (this.ended)
57
+ return;
51
58
  for (const c of fragment) {
52
59
  this.step(c);
53
- if (this.done)
60
+ if (this.ended)
54
61
  break;
55
62
  }
56
- return this.result;
63
+ }
64
+ /** The property's value once its string closed; null before (and when there is none). */
65
+ value(prop) {
66
+ return this.states.get(prop)?.state.value ?? null;
67
+ }
68
+ /** When the property's string value opened and closed (event numbers; 0: not yet). */
69
+ timing(prop) {
70
+ const s = this.states.get(prop)?.state;
71
+ return { openedAt: s?.openedAt ?? 0, closedAt: s?.closedAt ?? 0 };
72
+ }
73
+ /**
74
+ * The decoded head of the property's string value so far (open or closed), an unfinished escape
75
+ * at its end left out; null when its value never opened or is dead.
76
+ */
77
+ prefix(prop) {
78
+ const s = this.states.get(prop)?.state;
79
+ if (s === undefined || s.openedAt === 0 || s.dead)
80
+ return null;
81
+ if (s.value !== null)
82
+ return s.value;
83
+ return decodeHead(s.raw);
57
84
  }
58
85
  step(c) {
59
86
  if (this.inString) {
@@ -74,25 +101,32 @@ export class TopLevelStringProperty {
74
101
  return;
75
102
  }
76
103
  switch (c) {
77
- case '"':
104
+ case '"': {
78
105
  this.inString = true;
79
- this.raw = "";
80
- if (this.depth === 1 && this.expectKey)
81
- this.role = "key";
82
- else if (this.depth === 1 && this.valueOf === this.prop)
83
- this.role = "value";
84
- else
85
- this.role = "other";
106
+ this.role = null;
107
+ if (this.depth !== 1)
108
+ return;
109
+ if (this.expectKey) {
110
+ this.role = { kind: "key" };
111
+ this.keyRaw = "";
112
+ return;
113
+ }
114
+ const w = this.valueOf === null ? undefined : this.states.get(this.valueOf);
115
+ if (w !== undefined && w.state.openedAt === 0 && !w.state.dead) {
116
+ w.state.openedAt = ++this.events;
117
+ this.role = { kind: "value", ...w };
118
+ }
86
119
  return;
120
+ }
87
121
  case "{":
88
122
  case "[":
89
123
  // the top level must be an object
90
124
  if (this.depth === 0 && c === "[") {
91
- this.stop();
125
+ this.ended = true;
92
126
  return;
93
127
  }
94
128
  if (this.depth === 1)
95
- this.valueOf = null;
129
+ this.killValueOf();
96
130
  this.depth++;
97
131
  if (this.depth === 1)
98
132
  this.expectKey = true;
@@ -100,9 +134,8 @@ export class TopLevelStringProperty {
100
134
  case "}":
101
135
  case "]":
102
136
  this.depth--;
103
- // the object ended without the property
104
137
  if (this.depth <= 0)
105
- this.stop();
138
+ this.ended = true;
106
139
  return;
107
140
  case ":":
108
141
  if (this.depth === 1) {
@@ -118,42 +151,83 @@ export class TopLevelStringProperty {
118
151
  }
119
152
  return;
120
153
  default:
121
- // a number, literal or whitespace; a non-string value of the property ends the search
122
- if (this.depth === 1 && !isJsonSpace(c) && this.valueOf === this.prop)
123
- this.stop();
124
- else if (this.depth === 0 && !isJsonSpace(c))
125
- this.stop();
154
+ if (isJsonSpace(c))
155
+ return;
156
+ // a number or literal: a watched property with it has no string value
157
+ if (this.depth === 1)
158
+ this.killValueOf();
159
+ else if (this.depth === 0)
160
+ this.ended = true;
126
161
  }
127
162
  }
163
+ /** The value about to come at depth 1 is not a string: its property gives nothing. */
164
+ killValueOf() {
165
+ const w = this.valueOf === null ? undefined : this.states.get(this.valueOf);
166
+ if (w !== undefined && w.state.openedAt === 0)
167
+ w.state.dead = true;
168
+ this.valueOf = null;
169
+ }
128
170
  keep(c) {
129
- if (this.role === "other")
171
+ const role = this.role;
172
+ if (role === null)
173
+ return;
174
+ if (role.kind === "key") {
175
+ this.keyRaw += c;
176
+ if (this.keyRaw.length > KEY_MAX_CHARS)
177
+ this.role = null;
178
+ return;
179
+ }
180
+ const { state, spec } = role;
181
+ if (state.cut)
182
+ return;
183
+ if (state.raw.length >= (spec.maxChars ?? VALUE_MAX_CHARS)) {
184
+ if ((spec.overflow ?? "drop") === "drop") {
185
+ state.dead = true;
186
+ state.raw = "";
187
+ this.role = null;
188
+ }
189
+ else
190
+ state.cut = true;
130
191
  return;
131
- this.raw += c;
132
- if (this.role === "value" && this.raw.length > VALUE_MAX_CHARS)
133
- this.stop();
134
- else if (this.role === "key" && this.raw.length > KEY_MAX_CHARS)
135
- this.role = "other";
192
+ }
193
+ state.raw += c;
136
194
  }
137
195
  closeString() {
138
196
  this.inString = false;
139
197
  const role = this.role;
140
- this.role = "other";
198
+ this.role = null;
141
199
  if (this.depth !== 1)
142
200
  return;
143
201
  if (this.expectKey) {
144
202
  this.expectKey = false;
145
- this.key = role === "key" ? decode(this.raw) : null;
203
+ this.key = role?.kind === "key" ? decode(this.keyRaw) : null;
146
204
  return;
147
205
  }
148
- if (role === "value") {
149
- this.result = decode(this.raw);
150
- this.stop();
151
- return;
206
+ const w = this.valueOf === null ? undefined : this.states.get(this.valueOf);
207
+ // a watched value that went dead at its cap still closes (its order stays known)
208
+ if (w !== undefined && w.state.openedAt !== 0 && w.state.closedAt === 0) {
209
+ w.state.closedAt = ++this.events;
210
+ if (role?.kind === "value" && !w.state.cut)
211
+ w.state.value = decode(w.state.raw);
152
212
  }
153
213
  this.valueOf = null;
154
214
  }
155
- stop() {
156
- this.done = true;
215
+ }
216
+ /**
217
+ * Reads the value of one top-level string property of a JSON object streamed in fragments
218
+ * ({@link TopLevelStrings} watching that one property).
219
+ */
220
+ export class TopLevelStringProperty {
221
+ prop;
222
+ scan;
223
+ constructor(prop) {
224
+ this.prop = prop;
225
+ this.scan = new TopLevelStrings([{ name: prop }]);
226
+ }
227
+ /** Scans `fragment`; returns the property's value once known, null before (and when none). */
228
+ feed(fragment) {
229
+ this.scan.feed(fragment);
230
+ return this.scan.value(this.prop);
157
231
  }
158
232
  }
159
233
  /** JSON whitespace (RFC 8259): space, tab, line feed, carriage return. */
@@ -168,6 +242,18 @@ function decode(raw) {
168
242
  return null;
169
243
  }
170
244
  }
245
+ /**
246
+ * The decoded head of a JSON string body that may stop anywhere: an unfinished escape at its end
247
+ * (a lone backslash, a short `\u` sequence, half of a surrogate pair) is left out.
248
+ */
249
+ function decodeHead(raw) {
250
+ for (let cut = 0; cut <= 6 && cut <= raw.length; cut++) {
251
+ const v = decode(raw.slice(0, raw.length - cut));
252
+ if (v !== null)
253
+ return v;
254
+ }
255
+ return null;
256
+ }
171
257
  /** The value of a top-level string property once its closing quote arrived; null before. */
172
258
  export function closedStringProperty(json, prop) {
173
259
  return new TopLevelStringProperty(prop).feed(json);
@@ -183,43 +269,176 @@ export function writeBaseViewOf(tools, name) {
183
269
  return undefined;
184
270
  return t.spec.inputView?.kind === "file_write" ? t.spec.inputView : undefined;
185
271
  }
272
+ /** The most candidate files a guessed base reads (spec 2026-11-27 §4.2). */
273
+ export const WRITE_BASE_CANDIDATES = 3;
274
+ /** The non-blank complete lines of `content` after which the guess is chosen (§4.3). */
275
+ export const GUESS_PREFIX_LINES = 8;
276
+ /** The least share of the prefix's lines a candidate must contain to be guessed (§4.3). */
277
+ export const GUESS_MIN_SCORE = 0.6;
278
+ /** The least lead of the guessed candidate over the runner-up (§4.3). */
279
+ export const GUESS_MIN_MARGIN = 0.2;
280
+ /** The raw characters of `content` the scanner keeps for the guess (only its head matters). */
281
+ const CONTENT_HEAD_CHARS = 64 * 1024;
282
+ /**
283
+ * The non-blank lines (trimmed) of a streamed text's head: its complete lines, and the last one
284
+ * too once the text is `complete`.
285
+ */
286
+ export function guessLines(text, complete) {
287
+ const lines = text.split("\n");
288
+ if (!complete)
289
+ lines.pop();
290
+ return lines.map((l) => l.trim()).filter((l) => l !== "");
291
+ }
186
292
  /**
187
- * Watches one model stream attempt's tool calls (streaming tool input spec §4.1): a call whose tool
188
- * declares `inputView.kind: "file_write"` starts one base read once its path property closed, at
189
- * most one per call id, without blocking the stream. A read that resolves after `signal` aborted
190
- * (a step reset, the stream's end, the run's abort) emits nothing; a read that throws is logged
191
- * and dropped. The attempt aborts `signal` and then awaits {@link settle}, so no admission starts
192
- * after its step moves on (each read checks the signal right before its admission) and a read
193
- * still running normally ends with it. The wait is bounded ({@link WRITE_BASE_SETTLE_MS}): a read
194
- * whose provider ignores the abort is logged once and left to end in the background.
293
+ * The candidate a guessed base shows (§4.3), or null: the share of `lines` found among a
294
+ * candidate's lines (trimmed) is its score; the best wins with at least {@link GUESS_MIN_SCORE}
295
+ * and a lead of {@link GUESS_MIN_MARGIN} over the runner-up. No lines: no guess.
296
+ */
297
+ export function chooseGuess(lines, candidates) {
298
+ if (lines.length === 0)
299
+ return null;
300
+ const scored = candidates
301
+ .map((c) => {
302
+ const have = new Set(c.text.split("\n").map((l) => l.trim()));
303
+ const hits = lines.filter((l) => have.has(l)).length;
304
+ return { c, score: hits / lines.length };
305
+ })
306
+ .sort((a, b) => b.score - a.score);
307
+ const [best, next] = scored;
308
+ if (best === undefined || best.score < GUESS_MIN_SCORE)
309
+ return null;
310
+ if (next !== undefined && best.score - next.score < GUESS_MIN_MARGIN)
311
+ return null;
312
+ return best.c;
313
+ }
314
+ /**
315
+ * Watches one model stream attempt's tool calls (streaming tool input spec §4.1, the guess of spec
316
+ * 2026-11-27 §4): a call whose tool declares `inputView.kind: "file_write"` gets its base read once
317
+ * its path property closed, without blocking the stream. When the call's `content` starts before
318
+ * its path closed, the conversation's newest recorded files are read as candidates, and once
319
+ * enough of the content streamed the one it matches clearly goes out as a guessed base; when the
320
+ * path closes, a verdict confirms or withdraws it at once (a withdrawn guess is followed by the
321
+ * exact read of the real path). A read that resolves after `signal` aborted (a step reset, the
322
+ * stream's end, the run's abort) emits nothing; a read that throws is logged and dropped. The
323
+ * attempt aborts `signal` and then awaits {@link settle}, so no admission starts after its step
324
+ * moves on (each read checks the signal right before its admission) and a read still running
325
+ * normally ends with it. The wait is bounded ({@link WRITE_BASE_SETTLE_MS}): a read whose
326
+ * provider ignores the abort is logged once and left to end in the background. {@link settle}
327
+ * also logs one `write input order` line per watched call.
195
328
  */
196
329
  export function writeBaseWatcher(deps) {
197
- const watching = new Map();
330
+ const calls = new Map();
198
331
  /** The reads in flight (each removes itself when it finishes). */
199
332
  const inFlight = new Set();
200
333
  /** Call ids already seen: a repeated start never starts a second read. */
201
334
  const seen = new Set();
202
335
  let warnedStray = false;
203
- const read = async (callId, path) => {
204
- try {
205
- const base = await deps.reader.read({
206
- conversationId: deps.conversationId,
207
- path,
208
- signal: deps.signal,
209
- });
210
- if (base === null || deps.signal.aborted)
211
- return;
212
- deps.emit(callId, base);
336
+ let logged = false;
337
+ const track = (p) => {
338
+ inFlight.add(p);
339
+ void p.finally(() => inFlight.delete(p));
340
+ };
341
+ const warnFailed = (callId, err) => {
342
+ if (deps.signal.aborted)
343
+ return;
344
+ deps.log.warn("write base not shown: the read failed", {
345
+ conversationId: deps.conversationId,
346
+ callId,
347
+ err,
348
+ });
349
+ };
350
+ const readExact = (callId, path) => {
351
+ track((async () => {
352
+ try {
353
+ const base = await deps.reader.read({
354
+ conversationId: deps.conversationId,
355
+ path,
356
+ signal: deps.signal,
357
+ });
358
+ if (base === null || deps.signal.aborted)
359
+ return;
360
+ deps.emit(callId, base);
361
+ }
362
+ catch (err) {
363
+ warnFailed(callId, err);
364
+ }
365
+ })());
366
+ };
367
+ /** Chooses and emits the guess when enough content streamed and the candidates are read. */
368
+ const tryGuess = (callId, c) => {
369
+ if (c.guess !== "pending" || c.candidates === null || deps.signal.aborted)
370
+ return;
371
+ const head = c.scan.prefix(c.view.content);
372
+ if (head === null)
373
+ return;
374
+ const complete = c.scan.timing(c.view.content).closedAt !== 0;
375
+ const lines = guessLines(head, complete);
376
+ if (!complete && lines.length < GUESS_PREFIX_LINES)
377
+ return;
378
+ if (c.candidates.length === 0) {
379
+ c.guess = "no_candidates";
380
+ return;
213
381
  }
214
- catch (err) {
215
- if (deps.signal.aborted)
382
+ const pick = chooseGuess(lines.slice(0, GUESS_PREFIX_LINES), c.candidates.map((x) => ({
383
+ ...x,
384
+ text: x.base.text,
385
+ })));
386
+ if (pick === null) {
387
+ c.guess = "no_match";
388
+ return;
389
+ }
390
+ c.guessed = { path: pick.path };
391
+ c.guess = "guessed";
392
+ deps.emit(callId, {
393
+ text: pick.base.text,
394
+ sha256: pick.base.sha256,
395
+ guess: { path: pick.path },
396
+ });
397
+ };
398
+ const readCandidates = (callId, c) => {
399
+ track((async () => {
400
+ try {
401
+ const paths = await deps.reader.recentPaths({
402
+ conversationId: deps.conversationId,
403
+ limit: WRITE_BASE_CANDIDATES,
404
+ });
405
+ const read = await Promise.all(paths.map(async (path) => {
406
+ if (deps.signal.aborted)
407
+ return null;
408
+ const base = await deps.reader.read({
409
+ conversationId: deps.conversationId,
410
+ path,
411
+ signal: deps.signal,
412
+ });
413
+ return base === null ? null : { path, base };
414
+ }));
415
+ if (deps.signal.aborted)
416
+ return;
417
+ c.candidates = read.filter((x) => x !== null);
418
+ // the path may have decided while the candidates were read: then no guess
419
+ if (!c.pathDone)
420
+ tryGuess(callId, c);
421
+ }
422
+ catch (err) {
423
+ if (c.guess === "pending")
424
+ c.guess = "no_candidates";
425
+ warnFailed(callId, err);
426
+ }
427
+ })());
428
+ };
429
+ /** The call's path closed: verdict on a guess, else the exact read as without one. */
430
+ const onPath = (callId, c, rawPath) => {
431
+ c.pathDone = true;
432
+ if (c.guessed !== null) {
433
+ const confirmed = deps.reader.normalize(rawPath) === c.guessed.path;
434
+ c.guess = confirmed ? "confirmed" : "rejected";
435
+ deps.verdict(callId, confirmed);
436
+ if (confirmed)
216
437
  return;
217
- deps.log.warn("write base not shown: the read failed", {
218
- conversationId: deps.conversationId,
219
- callId,
220
- err,
221
- });
222
438
  }
439
+ else if (c.guess === "pending")
440
+ c.guess = "path_first_won";
441
+ readExact(callId, rawPath);
223
442
  };
224
443
  return {
225
444
  onStart(callId, name) {
@@ -229,26 +448,66 @@ export function writeBaseWatcher(deps) {
229
448
  const view = deps.inputViewOf(name);
230
449
  if (view?.kind !== "file_write")
231
450
  return;
232
- watching.set(callId, new TopLevelStringProperty(view.path));
451
+ calls.set(callId, {
452
+ scan: new TopLevelStrings([
453
+ { name: view.path },
454
+ { name: view.content, maxChars: CONTENT_HEAD_CHARS, overflow: "keep-head" },
455
+ ]),
456
+ view: { path: view.path, content: view.content },
457
+ order: "unknown",
458
+ pathDone: false,
459
+ guess: "none",
460
+ candidates: null,
461
+ guessed: null,
462
+ });
233
463
  },
234
464
  onInput(callId, fragment) {
235
- const scanner = watching.get(callId);
236
- if (scanner === undefined)
237
- return;
238
- if (deps.signal.aborted) {
239
- watching.delete(callId);
465
+ const c = calls.get(callId);
466
+ if (c === undefined || c.pathDone || deps.signal.aborted)
240
467
  return;
468
+ c.scan.feed(fragment);
469
+ const path = c.scan.timing(c.view.path);
470
+ const content = c.scan.timing(c.view.content);
471
+ if (c.order === "unknown") {
472
+ if (content.openedAt !== 0 && (path.closedAt === 0 || content.openedAt < path.closedAt)) {
473
+ c.order = "content_first";
474
+ c.guess = "pending";
475
+ readCandidates(callId, c);
476
+ }
477
+ else if (path.closedAt !== 0)
478
+ c.order = "path_first";
241
479
  }
242
- const path = scanner.feed(fragment);
243
- if (path === null)
480
+ if (path.closedAt !== 0) {
481
+ const raw = c.scan.value(c.view.path);
482
+ // a path too long, or not decodable: no base, as before
483
+ if (raw === null) {
484
+ c.pathDone = true;
485
+ if (c.guessed !== null) {
486
+ c.guess = "rejected";
487
+ deps.verdict(callId, false);
488
+ }
489
+ else if (c.guess === "pending")
490
+ c.guess = "path_first_won";
491
+ return;
492
+ }
493
+ onPath(callId, c, raw);
244
494
  return;
245
- // one read per call id, whatever follows
246
- watching.delete(callId);
247
- const pending = read(callId, path);
248
- inFlight.add(pending);
249
- void pending.finally(() => inFlight.delete(pending));
495
+ }
496
+ tryGuess(callId, c);
250
497
  },
251
498
  async settle() {
499
+ if (!logged) {
500
+ logged = true;
501
+ for (const c of calls.values()) {
502
+ deps.log.info("write input order", {
503
+ conversationId: deps.conversationId,
504
+ ...(deps.model !== undefined && deps.model),
505
+ order: c.order,
506
+ // a guess the stream ended on before its verdict, or one never chosen
507
+ guess: c.guess === "pending" || c.guess === "guessed" ? "unfinished" : c.guess,
508
+ });
509
+ }
510
+ }
252
511
  if (inFlight.size === 0)
253
512
  return;
254
513
  const boundMs = deps.settleMs ?? WRITE_BASE_SETTLE_MS;
@@ -18,7 +18,7 @@ export interface WriteBaseReadDeps {
18
18
  claim(): Readonly<ExecutionClaim> | undefined;
19
19
  /** The run's device and actor, or null when the run may not read one now (never binds). */
20
20
  runFacts(claim: Readonly<ExecutionClaim>): Promise<WriteBaseRunFacts | null>;
21
- eventLog: Pick<EventLog, "latestFileState">;
21
+ eventLog: Pick<EventLog, "latestFileState" | "recentFilePaths">;
22
22
  sandbox: Pick<SandboxService, "withKernelRead">;
23
23
  log: Pick<KernelLogger, "warn" | "debug">;
24
24
  }
@@ -42,6 +42,8 @@ export declare function readWriteBase(deps: WriteBaseReadDeps, input: {
42
42
  path: string;
43
43
  signal: AbortSignal;
44
44
  }): Promise<WriteBase | null>;
45
+ /** {@link normalizeWriteBasePath} that gives null instead of throwing (a guess's verdict). */
46
+ export declare function normalizeWritePath(raw: string): string | null;
45
47
  /**
46
48
  * The failures that only mean "no base now": the device's instance is not running, the read was
47
49
  * not admitted (the run moved on, the authority refused it) or its runtime cannot enforce a
@@ -65,4 +67,10 @@ export declare class WriteBaseService implements WriteBaseReader {
65
67
  path: string;
66
68
  signal: AbortSignal;
67
69
  }): Promise<WriteBase | null>;
70
+ /** The conversation's newest recorded file paths (spec 2026-11-27 §4.2); none on a failure. */
71
+ recentPaths(input: {
72
+ conversationId: string;
73
+ limit: number;
74
+ }): Promise<string[]>;
75
+ normalize(rawPath: string): string | null;
68
76
  }
@@ -38,11 +38,8 @@ import { currentExecutionClaim } from "./run-execution.js";
38
38
  export async function readWriteBase(deps, input) {
39
39
  const { conversationId, signal } = input;
40
40
  try {
41
- if (!input.path.startsWith("/"))
42
- return null;
43
- checkFilePathShape(input.path);
44
- const path = normalizeSandboxPath(checkToolPath(input.path, "file_path"));
45
- if (path === "/")
41
+ const path = normalizeWriteBasePath(input.path);
42
+ if (path === null)
46
43
  return null;
47
44
  const claim = deps.claim();
48
45
  if (!claim || claim.conversationId !== conversationId)
@@ -100,6 +97,27 @@ export async function readWriteBase(deps, input) {
100
97
  return null;
101
98
  }
102
99
  }
100
+ /**
101
+ * A model's `Write` path as a base read takes it: absolute, shaped and allowed as `Write` checks it
102
+ * (`checkFilePathShape`, `checkToolPath`), normalized; null for a relative path or the root.
103
+ * Throws the `ToolError` `Write` would refuse it with.
104
+ */
105
+ function normalizeWriteBasePath(raw) {
106
+ if (!raw.startsWith("/"))
107
+ return null;
108
+ checkFilePathShape(raw);
109
+ const path = normalizeSandboxPath(checkToolPath(raw, "file_path"));
110
+ return path === "/" ? null : path;
111
+ }
112
+ /** {@link normalizeWriteBasePath} that gives null instead of throwing (a guess's verdict). */
113
+ export function normalizeWritePath(raw) {
114
+ try {
115
+ return normalizeWriteBasePath(raw);
116
+ }
117
+ catch {
118
+ return null;
119
+ }
120
+ }
103
121
  /** `data` as UTF-8 text, or null when it is not valid UTF-8. */
104
122
  function utf8(data) {
105
123
  try {
@@ -172,6 +190,22 @@ let WriteBaseService = class WriteBaseService {
172
190
  read(input) {
173
191
  return readWriteBase(this.deps, input);
174
192
  }
193
+ /** The conversation's newest recorded file paths (spec 2026-11-27 §4.2); none on a failure. */
194
+ async recentPaths(input) {
195
+ try {
196
+ return await this.deps.eventLog.recentFilePaths(input.conversationId, input.limit);
197
+ }
198
+ catch (err) {
199
+ this.deps.log.warn("write base candidates not listed", {
200
+ conversationId: input.conversationId,
201
+ err,
202
+ });
203
+ return [];
204
+ }
205
+ }
206
+ normalize(rawPath) {
207
+ return normalizeWritePath(rawPath);
208
+ }
175
209
  };
176
210
  WriteBaseService = __decorate([
177
211
  Injectable(),
@@ -8,6 +8,6 @@ export type { ClassifierAnswer, ReviewClassifierDeps, ReviewClassifierInput, Rev
8
8
  export { boundMessages, callReviewModel, classifierMessage, fitReviewInput, fitReviewText, newReviewTag, parseReviewAnswer, personMessagesText, REVIEW_ASK_REASON, REVIEW_MAX_OUTPUT_TOKENS, REVIEW_PURPOSE, REVIEW_SYSTEM_PROMPT, REVIEW_TRUNCATED_ASK_REASON, REVIEW_TRUNCATED_MARKER, REVIEW_UNAVAILABLE_PREFIX, readPersonMessages, reviewModelLimits, reviewSystemPrompt, runClassifier, } from "./classifier.js";
9
9
  export type { CommandReview, ReviewCall, ReviewInput, ReviewVerdict } from "./review.service.js";
10
10
  export { CommandReviewService, REVIEW_REASONS, } from "./review.service.js";
11
- export { parseCommand, reviewRules, reviewWrite, writtenPaths, } from "./rules.js";
11
+ export { parseCommand, reviewRead, reviewRules, reviewWrite, writtenPaths, } from "./rules.js";
12
12
  export type { ParsedCommand, Redirect, ReviewFacts, ReviewResult, RuleHit, RuleOutcome, SimpleCommand, } from "./types.js";
13
13
  export { applySessionGrants, isSessionGrantableRule } from "./types.js";
@@ -6,5 +6,5 @@
6
6
  */
7
7
  export { boundMessages, callReviewModel, classifierMessage, fitReviewInput, fitReviewText, newReviewTag, parseReviewAnswer, personMessagesText, REVIEW_ASK_REASON, REVIEW_MAX_OUTPUT_TOKENS, REVIEW_PURPOSE, REVIEW_SYSTEM_PROMPT, REVIEW_TRUNCATED_ASK_REASON, REVIEW_TRUNCATED_MARKER, REVIEW_UNAVAILABLE_PREFIX, readPersonMessages, reviewModelLimits, reviewSystemPrompt, runClassifier, } from "./classifier.js";
8
8
  export { CommandReviewService, REVIEW_REASONS, } from "./review.service.js";
9
- export { parseCommand, reviewRules, reviewWrite, writtenPaths, } from "./rules.js";
9
+ export { parseCommand, reviewRead, reviewRules, reviewWrite, writtenPaths, } from "./rules.js";
10
10
  export { applySessionGrants, isSessionGrantableRule } from "./types.js";