@code-yeongyu/senpi-codemode 2026.11.26 → 2026.11.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +87 -0
  3. package/package.json +5 -5
  4. package/src/bridge/reserved.ts +2 -0
  5. package/src/config/feature-settings.ts +19 -0
  6. package/src/config/settings.ts +8 -0
  7. package/src/extension/eval-status-ticker.ts +5 -2
  8. package/src/extension/runtime-factory.ts +31 -5
  9. package/src/extension/session-manager.ts +4 -1
  10. package/src/index.ts +14 -6
  11. package/src/kernels/js/babel-ast.ts +64 -0
  12. package/src/kernels/js/binding-patterns.js +166 -0
  13. package/src/kernels/js/cell-run-context.js +8 -0
  14. package/src/kernels/js/declaration-extent.js +157 -0
  15. package/src/kernels/js/erase-types.ts +174 -0
  16. package/src/kernels/js/js-source-scan.js +181 -0
  17. package/src/kernels/js/kernel-contract.ts +2 -0
  18. package/src/kernels/js/last-expression.js +207 -0
  19. package/src/kernels/js/local-module-loader.ts +7 -2
  20. package/src/kernels/js/persist-declarations.js +233 -0
  21. package/src/kernels/js/rewrite-imports.ts +3 -60
  22. package/src/kernels/js/typescript-cell.ts +39 -0
  23. package/src/kernels/js/worker-core.js +1 -0
  24. package/src/kernels/js/worker-indirect-eval.js +4 -860
  25. package/src/kernels/js/worker-runtime.js +2 -0
  26. package/src/kernels/js/worker-scope.js +71 -0
  27. package/src/kernels/js/worker-startup.ts +1 -0
  28. package/src/prompt/eval-prompt-template.ts +4 -2
  29. package/src/prompt/eval-prompt.ts +4 -0
  30. package/src/skill/bun/SKILL.md +1 -0
  31. package/src/tool/cell-handler.ts +17 -1
  32. package/src/tool/detached-cell-manager.ts +42 -4
  33. package/src/tool/detached-notification-queue.ts +48 -7
  34. package/src/tool/detached-settling.ts +26 -0
  35. package/src/tool/eval-tool-options.ts +5 -1
  36. package/src/tool/eval-tool.ts +3 -1
  37. package/src/tool/js-cell-parse-message.ts +11 -3
  38. package/src/tool/managed-cell.ts +3 -0
  39. package/src/tool/run-eval-cell.ts +36 -11
  40. package/src/tool/scoped-watches.ts +53 -0
  41. package/src/tool/types.ts +14 -0
  42. package/src/written-files/model-writes.ts +55 -0
  43. package/src/written-files/ownership.ts +73 -0
  44. package/src/written-files/report.ts +63 -0
  45. package/src/written-files/scan-boundaries.ts +164 -0
  46. package/src/written-files/source-file.ts +31 -0
  47. package/src/written-files/tracker.ts +361 -0
  48. package/src/written-files/window.ts +92 -0
  49. package/src/written-files/workspace-fs.ts +104 -0
  50. package/src/written-files/workspace-scan.ts +253 -0
  51. package/src/written-files/write-hooks.ts +155 -0
  52. package/src/written-files/written-files.ts +155 -0
@@ -0,0 +1,361 @@
1
+ import { basename, dirname, join, relative, sep } from "node:path";
2
+ import { type FileSignature, type FsAccess, sameSignature } from "./scan-boundaries.ts";
3
+ import { type Claim, FileOwnership, type Owner } from "./ownership.ts";
4
+ import {
5
+ type ChangedFile,
6
+ type ClaimRelease,
7
+ offWindow,
8
+ type ToolCallHold,
9
+ withoutCeded,
10
+ type WrittenFilesChange,
11
+ type WrittenFilesSelection,
12
+ type WrittenFilesWindow,
13
+ } from "./window.ts";
14
+ import { escapesWorkspace, type ScanFs } from "./workspace-fs.ts";
15
+ import type { ScanSkipReason, ScannedFiles, WorkspaceScan } from "./workspace-scan.ts";
16
+
17
+ export interface WrittenFilesTrackerOptions {
18
+ readonly cwd: string;
19
+ readonly scan: (previous?: ScannedFiles) => Promise<WorkspaceScan>;
20
+ readonly stat: ScanFs["stat"];
21
+ /** The real location of a path, as a scan names it: on-disk case, links resolved. */
22
+ readonly realpath: FsAccess["realpath"];
23
+ }
24
+
25
+ /**
26
+ * Scans in a row that fail or run over budget before the check turns itself off for the session. Three, not one: the
27
+ * first scans of a session can meet a cold file cache, and a cell spends two (before it starts and when it settles).
28
+ */
29
+ const SKIPS_BEFORE_OFF = 3;
30
+
31
+ /**
32
+ * Finds the files eval cells wrote by comparing the workspace before and after them. One baseline is shared by every
33
+ * cell that is live at the same time: it is recorded before the first of them starts and advanced at each settlement,
34
+ * so a change is reported exactly once, by the first cell to settle after it. Cells that overlap cannot be told
35
+ * apart; a cell that runs alone is charged only with what changed while it ran.
36
+ *
37
+ * A settlement owns the files it will send through the write hooks until those hooks return: a hook (a formatter) may
38
+ * rewrite a file, and that rewrite is the reporting cell's. A changed file it only counts (past the limit, not source)
39
+ * or will not hook (no hooks on this host) stays unowned, so a later scan still reports a change made to it. Ownership
40
+ * is taken inside the settling scan, so no later scan can run between the report and the claim, and a scan that finds
41
+ * an owned file changed leaves it and its baseline alone. No lock is held over the hooks: a hook may itself call
42
+ * `write` or run an eval cell, whose scans then queue behind nothing of this cell's.
43
+ *
44
+ * The baseline advances, file by file, only for a change that is reported: a settlement that claims a file and then
45
+ * ends the claim without starting its hooks puts that file's baseline back, so the next settlement reports the change.
46
+ *
47
+ * A claim is pending until the cell starts that file's hooks (`start`, the one dispatch point) and started after.
48
+ * - Settlement selects files with hooks on, cell open: claims exactly the listed files, pending.
49
+ * - Cell closed before its selection returns: claims nothing, `start` refuses, so nothing is dispatched, and the
50
+ * listed files keep their baseline (no one reads that list).
51
+ * - Hooks stop at the limit, or no hooks here: the files past it, or all, are never claimed.
52
+ * - Cancelled before a file's dispatch, or `start` refused: `skipped` ends that pending claim now and puts the file's
53
+ * baseline back, unless a later settlement has reported a newer change to it meanwhile.
54
+ * - The file is unreadable: `failed` ends the pending claim; the failure is reported, so the baseline stays advanced.
55
+ * - `start` while open: the claim becomes started; `start` after close, or without a claim, refuses.
56
+ * - Hook returns, throws, or the host's handler deadline ends it: `hooked` records the state left and ends the claim.
57
+ * - Settlement done (`release`): ends every claim left, none started, and puts their baselines back.
58
+ * - Cell closes (normally, cancelled before or during dispatch): ends its pending claims, putting their baselines
59
+ * back, and keeps a started one until its `hooked`, so a cancelled cell's running formatter owns its rewrite.
60
+ * - A nested cell a hook starts: settles normally and skips the files the outer cell owns.
61
+ * - A model `write` or `edit` call starts (`holdForCall`): its file is held from before the call writes it until the
62
+ * call ends, so a settlement in between skips it and keeps its baseline; the call's own hooks are the only ones.
63
+ * The call's end records the state it left and lets go; two calls on one file hold it until both end.
64
+ * A model call never waits for a settlement, and a settlement never waits for a call: whoever took the file last at a
65
+ * transition point owns it. The transition points are the first look (the scan), the selection commit (right after
66
+ * `select`, synchronously with the claims) and the dispatch (`start`, synchronously with the report call). In order:
67
+ * - Model holds first (the call started before the first look): the file is skipped and keeps its baseline (above).
68
+ * - Model arrives during the scan: the first look skips the file as if it were held, even if the call has ended.
69
+ * - Model arrives during `select`: at the selection commit the cell cedes the file, even if the call has ended by
70
+ * then: no claim, not listed, not counted, baseline kept. A file past the limit was never claimed, so it is
71
+ * still counted and never hooked; the call's end records its state.
72
+ * - Model arrives between the claim and the dispatch (the read back included): the claim is contested, and `start`
73
+ * cedes it: no hook, the claim ends with the baseline put back, and the file leaves the cell's list and count.
74
+ * - Model arrives during the settlement's hook (started claim): both chains run, each for its own write (the cell's
75
+ * bytes were read before the call wrote). The contested claim records nothing at `hooked`: what is on disk is the
76
+ * call's, recorded by its end if it succeeded and otherwise reported by the next settlement.
77
+ * - Settlement claims first and its hooks return before the call starts: a plain sequence, one chain each.
78
+ * A claim lasts until the whole `tool_result` handler chain for its file returns, not until one handler's deadline:
79
+ * the host moves on to the next handler when one times out. A write that lands after the claim ended (a handler that
80
+ * outlived its deadline) is a change like any other, reported by whichever cell settles next.
81
+ */
82
+ export class WrittenFilesTracker {
83
+ readonly #cwd: string;
84
+ readonly #scan: WrittenFilesTrackerOptions["scan"];
85
+ readonly #stat: ScanFs["stat"];
86
+ readonly #realpath: FsAccess["realpath"];
87
+ readonly #hooked = new Map<string, FileSignature>();
88
+ readonly #ownership = new FileOwnership();
89
+ #queue: Promise<void> = Promise.resolve();
90
+ #baseline: ScannedFiles | undefined;
91
+ #skipped: ScanSkipReason | undefined;
92
+ #skips = 0;
93
+ #live = 0;
94
+ #disabled = false;
95
+
96
+ constructor(options: WrittenFilesTrackerOptions) {
97
+ this.#cwd = options.cwd;
98
+ this.#scan = options.scan;
99
+ this.#stat = options.stat;
100
+ this.#realpath = options.realpath;
101
+ }
102
+
103
+ open(): WrittenFilesWindow {
104
+ if (this.#disabled) return offWindow();
105
+ this.#live += 1;
106
+ // A later cell also waits for the scan in flight, so its first writes are not swept into that scan.
107
+ const ready = this.#live === 1 ? this.#enqueue(() => this.#recordBaseline()) : this.#queue;
108
+ const owner: Owner = { closed: false };
109
+ const claimOf = (absolutePath: string) => {
110
+ const path = this.#workspacePath(absolutePath);
111
+ const claim = path === undefined ? undefined : this.#ownership.claimOf(path, owner);
112
+ return claim === undefined || path === undefined ? undefined : { path, claim };
113
+ };
114
+ const release = (keepStarted: boolean) => {
115
+ for (const [path, claim] of this.#ownership.claimsOf(owner))
116
+ if (!(keepStarted && claim.started)) this.#endClaim(path, claim, false);
117
+ };
118
+ // A file a model call took is the call's however this cell lets go of it: its baseline is kept, not advanced.
119
+ const releaseFile = (absolutePath: string, reported: boolean): ClaimRelease => {
120
+ const owned = claimOf(absolutePath);
121
+ if (owned === undefined) return "released";
122
+ const ceded = owned.claim.contested;
123
+ this.#endClaim(owned.path, owned.claim, reported && !ceded);
124
+ return ceded ? "ceded" : "released";
125
+ };
126
+ return {
127
+ ready,
128
+ settle: (select) => this.#enqueue(() => this.#report(owner, select)),
129
+ start: (absolutePath) => {
130
+ const owned = claimOf(absolutePath);
131
+ if (owned === undefined || owner.closed) return "refused";
132
+ // The dispatch point, checked and marked with no await between: a model call took the file since the claim.
133
+ if (owned.claim.contested) {
134
+ this.#endClaim(owned.path, owned.claim, false);
135
+ return "ceded";
136
+ }
137
+ owned.claim.started = true;
138
+ return "started";
139
+ },
140
+ hooked: async (absolutePath) => {
141
+ const claim = claimOf(absolutePath)?.claim;
142
+ try {
143
+ // What a model call that took the file during the hooks leaves is the call's to record when it ends.
144
+ await this.#record(absolutePath, () => claim?.contested !== true);
145
+ } finally {
146
+ releaseFile(absolutePath, true);
147
+ }
148
+ },
149
+ skipped: (absolutePath) => releaseFile(absolutePath, false),
150
+ failed: (absolutePath) => releaseFile(absolutePath, true),
151
+ release: () => release(false),
152
+ close: () => {
153
+ if (owner.closed) return;
154
+ owner.closed = true;
155
+ // A hook already running keeps its file: what it leaves is still this cell's (`hooked` ends that claim).
156
+ release(true);
157
+ this.#live -= 1;
158
+ if (this.#live > 0) return;
159
+ this.#baseline = undefined;
160
+ this.#skipped = undefined;
161
+ this.#hooked.clear();
162
+ },
163
+ };
164
+ }
165
+
166
+ /** A write or edit call took this file through the hooks: its present state is not a cell's unhooked write. */
167
+ async noteHooked(absolutePath: string): Promise<void> {
168
+ await this.#record(absolutePath, () => true);
169
+ }
170
+
171
+ /** Records the file's present state as hooked, if `still` holds once it is read. */
172
+ async #record(absolutePath: string, still: () => boolean): Promise<void> {
173
+ if (this.#live === 0) return;
174
+ const path = this.#workspacePath(absolutePath);
175
+ if (path === undefined) return;
176
+ const signature = await this.#stat(absolutePath);
177
+ if (signature !== undefined && this.#live > 0 && still()) this.#hooked.set(path, signature);
178
+ }
179
+
180
+ /**
181
+ * A model `write` or `edit` call is about to write this file and run its hooks: no settlement reports or hooks the
182
+ * file until `end`. A path outside the workspace is not held.
183
+ */
184
+ async holdForCall(absolutePath: string): Promise<ToolCallHold | undefined> {
185
+ const path = this.#workspacePath(absolutePath);
186
+ if (path === undefined) return undefined;
187
+ const letGo = [this.#ownership.holdForCall(path)];
188
+ const named = [absolutePath];
189
+ // A scan names the file as it lies on disk, which the call's spelling need not be (another case on a
190
+ // case-insensitive filesystem, a symlinked alias): the hold covers the file's real location too, before it is written.
191
+ const real = await this.#realWorkspacePath(absolutePath);
192
+ if (real !== undefined && real !== path) {
193
+ letGo.push(this.#ownership.holdForCall(real));
194
+ named.push(join(this.#cwd, real));
195
+ }
196
+ let held = true;
197
+ return {
198
+ end: async (hooked) => {
199
+ if (!held) return;
200
+ held = false;
201
+ try {
202
+ if (hooked) await Promise.all(named.map((file) => this.noteHooked(file)));
203
+ } finally {
204
+ for (const release of letGo) release();
205
+ }
206
+ },
207
+ };
208
+ }
209
+
210
+ /** The workspace path of the file's real location, or of its directory's for a file not written yet. */
211
+ async #realWorkspacePath(absolutePath: string): Promise<string | undefined> {
212
+ const [root, file, directory] = await Promise.all([
213
+ this.#realpath(this.#cwd),
214
+ this.#realpath(absolutePath),
215
+ this.#realpath(dirname(absolutePath)),
216
+ ]);
217
+ const located = file ?? (directory === undefined ? undefined : join(directory, basename(absolutePath)));
218
+ if (root === undefined || located === undefined) return undefined;
219
+ const inside = relative(root, located);
220
+ return inside === "" || escapesWorkspace(inside) ? undefined : inside.split(sep).join("/");
221
+ }
222
+
223
+ /** Ends a claim; one that ends without its hooks started or its failure reported puts the file's baseline back. */
224
+ #endClaim(path: string, claim: Claim, reported: boolean): void {
225
+ this.#ownership.endClaim(path);
226
+ if (reported || claim.started) return;
227
+ // Queued, so it lands after any settlement already running, which compared this file with the advanced baseline,
228
+ // and before the baseline a later first cell records (closing the last cell drops this one first).
229
+ void this.#enqueue(async () => {
230
+ const baseline = this.#baseline;
231
+ const now = baseline?.files.get(path);
232
+ // A later settlement that reported a newer change has moved the baseline on: that change is reported already.
233
+ if (baseline === undefined || now === undefined || !sameSignature(now, claim.advanced)) return;
234
+ const files = new Map(baseline.files);
235
+ setEntry(files, path, claim.before);
236
+ this.#baseline = { ...baseline, files };
237
+ });
238
+ }
239
+
240
+ /** The workspace-relative POSIX path of a file inside the workspace. */
241
+ #workspacePath(absolutePath: string): string | undefined {
242
+ const inside = relative(this.#cwd, absolutePath);
243
+ return inside === "" || escapesWorkspace(inside) ? undefined : inside.split(sep).join("/");
244
+ }
245
+
246
+ async #recordBaseline(): Promise<void> {
247
+ const scan = await this.#safeScan(undefined);
248
+ if (this.#live === 0) return;
249
+ if (scan.kind === "skipped") {
250
+ this.#baseline = undefined;
251
+ this.#skip(scan.reason);
252
+ return;
253
+ }
254
+ this.#skips = 0;
255
+ this.#skipped = undefined;
256
+ this.#baseline = { files: new Map(scan.files), head: scan.head, tracked: scan.tracked };
257
+ }
258
+
259
+ async #report(owner: Owner, select: Select): Promise<WrittenFilesChange> {
260
+ // From the settlement's first look at a file until it claims it, a model call may take it.
261
+ const holds = this.#ownership.watchHolds();
262
+ try {
263
+ return await this.#compare(owner, select, holds.taken);
264
+ } finally {
265
+ holds.stop();
266
+ }
267
+ }
268
+
269
+ async #compare(owner: Owner, select: Select, taken: ReadonlySet<string>): Promise<WrittenFilesChange> {
270
+ const baseline = this.#baseline;
271
+ if (baseline === undefined) {
272
+ const reason = this.#skipped ?? "scan_failed";
273
+ // The cells still running are compared from here on; a cell that ran alone spends no second scan.
274
+ if (!this.#disabled && this.#live > 1) await this.#recordBaseline();
275
+ return { kind: "unchecked", reason, disabled: this.#disabled };
276
+ }
277
+ const scan = await this.#safeScan(baseline);
278
+ if (scan.kind === "skipped") {
279
+ this.#baseline = undefined;
280
+ this.#skip(scan.reason);
281
+ return { kind: "unchecked", reason: scan.reason, disabled: this.#disabled };
282
+ }
283
+ this.#skips = 0;
284
+ const next = new Map(scan.files);
285
+ const files: ChangedFile[] = [];
286
+ for (const [path, signature] of scan.files) {
287
+ const before = baseline.files.get(path);
288
+ if (before !== undefined && sameSignature(before, signature)) continue;
289
+ if (this.#ownership.owned(path) || taken.has(path)) {
290
+ // Another settlement's hooks, or a model write's, are on it: what they leave is theirs, compared with later.
291
+ setEntry(next, path, before);
292
+ continue;
293
+ }
294
+ const absolutePath = join(this.#cwd, path);
295
+ const hooked = this.#hooked.get(path);
296
+ if (hooked !== undefined) {
297
+ this.#hooked.delete(path);
298
+ if (sameSignature(hooked, signature)) continue;
299
+ // The scan may predate that call, so only a state the call did not leave counts as a change.
300
+ const current = await this.#stat(absolutePath);
301
+ if (current === undefined) {
302
+ next.delete(path);
303
+ continue;
304
+ }
305
+ next.set(path, current);
306
+ if (sameSignature(hooked, current)) continue;
307
+ }
308
+ files.push({ path, absolutePath });
309
+ }
310
+ files.sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0));
311
+ const selected = await select(files);
312
+ // The selection commit, with no await from here to the claims: a listed file a model call took while the selection
313
+ // ran is the call's, so the cell cedes it, neither listing nor counting it, and it keeps its baseline.
314
+ const ceded = selected.listed.filter((file) => taken.has(file.path) || this.#ownership.owned(file.path));
315
+ const selection = withoutCeded(selected, ceded);
316
+ // A cell that closed while the selection read its files lists them to no one and hooks nothing: it claims nothing,
317
+ // and their changes stay for the next settlement.
318
+ for (const file of owner.closed ? selected.listed : ceded)
319
+ setEntry(next, file.path, baseline.files.get(file.path));
320
+ this.#baseline = { files: next, head: scan.head, tracked: scan.tracked };
321
+ if (selection.hooks && !owner.closed)
322
+ for (const file of selection.listed) {
323
+ const advanced = next.get(file.path);
324
+ if (advanced === undefined) continue;
325
+ const before = baseline.files.get(file.path);
326
+ this.#ownership.claim(file.path, { owner, started: false, contested: false, before, advanced });
327
+ }
328
+ return { kind: "changed", selection };
329
+ }
330
+
331
+ #skip(reason: ScanSkipReason): void {
332
+ this.#skipped = reason;
333
+ this.#skips += 1;
334
+ if (reason === "git_unavailable" || this.#skips >= SKIPS_BEFORE_OFF) this.#disabled = true;
335
+ }
336
+
337
+ async #safeScan(previous: ScannedFiles | undefined): Promise<WorkspaceScan> {
338
+ try {
339
+ return await this.#scan(previous);
340
+ } catch {
341
+ return { kind: "skipped", reason: "scan_failed" };
342
+ }
343
+ }
344
+
345
+ /** Scans and baseline updates run one at a time, in the order they were asked for. */
346
+ #enqueue<Result>(task: () => Promise<Result>): Promise<Result> {
347
+ const run = this.#queue.then(task);
348
+ this.#queue = run.then(
349
+ () => undefined,
350
+ () => undefined,
351
+ );
352
+ return run;
353
+ }
354
+ }
355
+
356
+ type Select = (changed: readonly ChangedFile[]) => Promise<WrittenFilesSelection>;
357
+
358
+ function setEntry(files: Map<string, FileSignature>, path: string, signature: FileSignature | undefined): void {
359
+ if (signature === undefined) files.delete(path);
360
+ else files.set(path, signature);
361
+ }
@@ -0,0 +1,92 @@
1
+ import type { ScanSkipReason } from "./workspace-scan.ts";
2
+
3
+ export interface ChangedFile {
4
+ /** Workspace-relative POSIX path. */
5
+ readonly path: string;
6
+ readonly absolutePath: string;
7
+ }
8
+
9
+ /** What a settling cell does with the files that changed: the one choice both its claim and its hooks follow. */
10
+ export interface WrittenFilesSelection {
11
+ /** The changed files the cell lists, in path order; it sends them through the write hooks when `hooks` is set. */
12
+ readonly listed: readonly ChangedFile[];
13
+ /** How many changed files the cell counts as written, listed or not. */
14
+ readonly total: number;
15
+ readonly hooks: boolean;
16
+ }
17
+
18
+ /** The selection without the listed files a model call took from the cell: it neither lists nor counts them. */
19
+ export function withoutCeded(selection: WrittenFilesSelection, ceded: readonly ChangedFile[]): WrittenFilesSelection {
20
+ if (ceded.length === 0) return selection;
21
+ const listed = selection.listed.filter((file) => !ceded.includes(file));
22
+ return { listed, total: selection.total - ceded.length, hooks: selection.hooks };
23
+ }
24
+
25
+ export type WrittenFilesChange =
26
+ | { readonly kind: "changed"; readonly selection: WrittenFilesSelection }
27
+ /** The cell's writes could not be compared; `disabled` says the check is now off for the session. */
28
+ | { readonly kind: "unchecked"; readonly reason: ScanSkipReason; readonly disabled: boolean }
29
+ | { readonly kind: "off" };
30
+
31
+ /**
32
+ * What `start` decided for a file: `started`, the hooks run now; `refused`, the cell no longer owns the file or has
33
+ * closed, so it must not start them; `ceded`, a model `write` or `edit` call holds the file, so the cell let go of it,
34
+ * the change is the call's, and the cell neither hooks nor lists nor counts it.
35
+ */
36
+ export type HookStart = "started" | "refused" | "ceded";
37
+
38
+ /**
39
+ * How a cell let go of a file it owned without hooking it: `ceded` when a model `write` or `edit` call took the file,
40
+ * so the change is the call's and the cell neither reports nor counts it; `released` otherwise.
41
+ */
42
+ export type ClaimRelease = "released" | "ceded";
43
+
44
+ /** A cell's view of the written-files check, from before its code starts until its write hooks are done. */
45
+ export interface WrittenFilesWindow {
46
+ /** Resolves once the cell's code may start: the state its writes are compared with is recorded. */
47
+ readonly ready: Promise<void>;
48
+ /**
49
+ * After the cell's code finished: the files that changed since the last report, sorted, go through `select` inside
50
+ * the settling scan, and the cell owns the listed files it will hook until it lets go of them. The returned
51
+ * selection leaves out a file a model call took meanwhile.
52
+ */
53
+ settle(select: (changed: readonly ChangedFile[]) => Promise<WrittenFilesSelection>): Promise<WrittenFilesChange>;
54
+ /**
55
+ * Whether the cell starts the write hooks for a file now: only `started` lets it. From there the claim lasts until
56
+ * `hooked`, even past `close`.
57
+ */
58
+ start(absolutePath: string): HookStart;
59
+ /** The write hooks this cell ran for a file it reported returned: the state they left is this cell's, and it lets go. */
60
+ hooked(absolutePath: string): Promise<void>;
61
+ /**
62
+ * This cell will not run the write hooks for a file it owns (cancelled, or `start` refused): it lets go of it now, and
63
+ * the file's change stays for the next settlement to report.
64
+ */
65
+ skipped(absolutePath: string): ClaimRelease;
66
+ /** This cell reports that it could not read a file it owns back for the hooks: it lets go, and the change is reported. */
67
+ failed(absolutePath: string): ClaimRelease;
68
+ /** This cell's hooks are done: it lets go of every file it still owns. */
69
+ release(): void;
70
+ /** Ends the window and lets go of the files whose hooks have not started; safe to call more than once. */
71
+ close(): void;
72
+ }
73
+
74
+ /** A `write` or `edit` call's hold on its file, from before the call writes it until the call ends. */
75
+ export interface ToolCallHold {
76
+ /** The call ended; `hooked` when it completed through the hooks, so the state it left is not a cell's write. */
77
+ end(hooked: boolean): Promise<void>;
78
+ }
79
+
80
+ /** The window of a session whose check has turned itself off. */
81
+ export function offWindow(): WrittenFilesWindow {
82
+ return {
83
+ ready: Promise.resolve(),
84
+ settle: async () => ({ kind: "off" }),
85
+ start: () => "refused",
86
+ hooked: async () => {},
87
+ skipped: () => "released",
88
+ failed: () => "released",
89
+ release: () => {},
90
+ close: () => {},
91
+ };
92
+ }
@@ -0,0 +1,104 @@
1
+ import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
2
+ import type { FileSignature, FsAccess } from "./scan-boundaries.ts";
3
+ import { excludedDirectories, isSourcePath } from "./source-file.ts";
4
+
5
+ /** The workspace's source-file locations: a path whose real location is not one does not exist here. */
6
+ export interface ScanFs {
7
+ /** The signature of a regular file; undefined for anything else, a symlink and a missing path included. */
8
+ stat(path: string): Promise<FileSignature | undefined>;
9
+ /** At most `limit` leading bytes of a file; undefined when it cannot be read. */
10
+ read(path: string, limit: number): Promise<Uint8Array | undefined>;
11
+ }
12
+
13
+ export interface WorkspaceRoots {
14
+ readonly cwd: string;
15
+ /** The session's artifacts directory, wherever it lies. */
16
+ readonly artifactsDir: string;
17
+ }
18
+
19
+ /**
20
+ * The one place that decides whether a path the scan was given may be stat'd and read: git names paths lexically, and
21
+ * a directory in one can be a symlink to anywhere. A path qualifies when its real location, directories resolved, lies
22
+ * inside the real workspace, outside every excluded directory and the session's artifacts, and the stat and the read
23
+ * reach that location without following its last entry.
24
+ *
25
+ * An excluded directory is found by what it is, not only by how it is spelled: a segment that differs from an
26
+ * excluded name only in case is excluded when the filesystem resolves both spellings to the same directory, which a
27
+ * case-insensitive one does and a case-sensitive one does not. Only confirmed absence of either spelling shows the
28
+ * two apart; a lookup that could not tell (permission, I/O, a link loop) excludes the segment.
29
+ *
30
+ * A read takes bytes only from the regular file the stat just saw (same device and inode), and only after the open
31
+ * shows the path still names that file at the same real location, its last entry not a link: a platform that cannot
32
+ * refuse to follow a last entry may have opened a link to the checked file moved out of the workspace. What remains:
33
+ * the checks bracket the open, not the read, so a file moved out after them is read through the descriptor opened
34
+ * while it was inside; and a directory swapped away and back between two checks is not seen.
35
+ */
36
+ export function workspaceFs(roots: WorkspaceRoots, access: FsAccess): ScanFs {
37
+ /** False only when the two spellings are shown to be distinct directories. */
38
+ const maybeSameDirectory = async (spelled: string, named: string): Promise<boolean> => {
39
+ const [left, right] = await Promise.all([access.identity(spelled), access.identity(named)]);
40
+ if (left.kind === "unknown" || right.kind === "unknown") return true;
41
+ if (left.kind === "absent" || right.kind === "absent") return false;
42
+ // Without an inode two existing directories cannot be told apart, so the spelled one counts as excluded.
43
+ return left.ino === 0 || right.ino === 0 || (left.dev === right.dev && left.ino === right.ino);
44
+ };
45
+ const excludedAlias = async (root: string, segments: readonly string[]): Promise<boolean> => {
46
+ const checks = segments.flatMap((segment, index) =>
47
+ excludedDirectories()
48
+ .filter((name) => segment !== name && segment.toUpperCase() === name.toUpperCase())
49
+ .map((name) => {
50
+ const parent = join(root, ...segments.slice(0, index));
51
+ return maybeSameDirectory(join(parent, segment), join(parent, name));
52
+ }),
53
+ );
54
+ return (await Promise.all(checks)).includes(true);
55
+ };
56
+ const locate = async (path: string): Promise<string | undefined> => {
57
+ const [root, artifacts, directory] = await Promise.all([
58
+ access.realpath(roots.cwd),
59
+ access.realpath(roots.artifactsDir),
60
+ access.realpath(dirname(path)),
61
+ ]);
62
+ if (root === undefined || directory === undefined) return undefined;
63
+ const located = join(directory, basename(path));
64
+ const inside = relative(root, located);
65
+ const segments = inside.split(sep);
66
+ if (escapesWorkspace(inside) || !isSourcePath(segments.join("/")) || (await excludedAlias(root, segments)))
67
+ return undefined;
68
+ return artifacts === undefined || escapesWorkspace(relative(artifacts, located)) ? located : undefined;
69
+ };
70
+ return {
71
+ stat: async (path) => {
72
+ const located = await locate(path);
73
+ return located === undefined ? undefined : await access.lstat(located);
74
+ },
75
+ read: async (path, limit) => {
76
+ const located = await locate(path);
77
+ if (located === undefined) return undefined;
78
+ const checked = await access.lstat(located);
79
+ // Without an inode the opened file cannot be shown to be the checked one.
80
+ if (checked === undefined || checked.ino === 0) return undefined;
81
+ return await access.read(located, limit, async (opened) => {
82
+ if (!sameFile(opened, checked)) return false;
83
+ const [again, real, entry] = await Promise.all([
84
+ locate(path),
85
+ access.realpath(located),
86
+ access.lstat(located),
87
+ ]);
88
+ return again === located && real === located && entry !== undefined && sameFile(entry, checked);
89
+ });
90
+ },
91
+ };
92
+ }
93
+
94
+ function sameFile(left: FileSignature, right: FileSignature): boolean {
95
+ return left.dev === right.dev && left.ino === right.ino;
96
+ }
97
+
98
+ /**
99
+ * Whether a path relative to a directory leaves it: the parent segment, a path below it, or another root. A name that
100
+ * only begins with two dots (`..draft.ts`) stays inside.
101
+ */
102
+ export function escapesWorkspace(inside: string): boolean {
103
+ return inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside);
104
+ }