@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,253 @@
1
+ import { isAbsolute, join, relative, sep } from "node:path";
2
+ import type { FileSignature, GitOutcome, RunGit } from "./scan-boundaries.ts";
3
+ import type { ScanFs } from "./workspace-fs.ts";
4
+ import { excludedDirectories, isSourcePath, SOURCE_FILE_MAX_BYTES } from "./source-file.ts";
5
+
6
+ /** One git process of a scan is killed at this deadline. */
7
+ const SCAN_TIMEOUT_MS = 500;
8
+ /** A scan that would stat more changed or untracked paths than this is abandoned. */
9
+ const SCAN_PATH_LIMIT = 5_000;
10
+
11
+ const STAT_BATCH = 64;
12
+ const INITIAL_HEAD = "(initial)";
13
+ /** What `git diff` compares with when the first commit was made between two scans. */
14
+ const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
15
+ const HEAD_RECORD = "# branch.oid ";
16
+
17
+ export type ScanSkipReason = "git_unavailable" | "over_budget" | "scan_failed";
18
+
19
+ /**
20
+ * The workspace's source-file candidates and their signatures: in a repository the files that differ from HEAD or are
21
+ * untracked, elsewhere every file its ignore rules leave. A candidate missing from an earlier scan was clean or absent
22
+ * then, so two scans compare without a walk of the unchanged tree.
23
+ */
24
+ export interface ScannedFiles {
25
+ readonly files: ReadonlyMap<string, FileSignature>;
26
+ readonly head: string | undefined;
27
+ /** The paths of `files` git tracks. */
28
+ readonly tracked: ReadonlySet<string>;
29
+ }
30
+
31
+ export type WorkspaceScan =
32
+ | ({ readonly kind: "files" } & ScannedFiles)
33
+ | { readonly kind: "skipped"; readonly reason: ScanSkipReason };
34
+
35
+ type ScanMode = { readonly kind: "repository"; readonly prefix: string } | { readonly kind: "plain" };
36
+
37
+ export interface WorkspaceScannerOptions {
38
+ readonly cwd: string;
39
+ /** The session's artifacts directory; files below it are the session's own, never a cell's source files. */
40
+ readonly artifactsDir: string;
41
+ readonly git: RunGit;
42
+ readonly fs: ScanFs;
43
+ readonly timeoutMs?: number;
44
+ readonly pathLimit?: number;
45
+ }
46
+
47
+ export class WorkspaceScanner {
48
+ readonly #cwd: string;
49
+ readonly #scratchDir: string;
50
+ readonly #artifactsPrefix: string | undefined;
51
+ readonly #runGit: RunGit;
52
+ readonly #fs: ScanFs;
53
+ readonly #timeoutMs: number;
54
+ readonly #pathLimit: number;
55
+ #mode: ScanMode | undefined;
56
+ #scratchReady = false;
57
+
58
+ constructor(options: WorkspaceScannerOptions) {
59
+ this.#cwd = options.cwd;
60
+ // The empty repository that lists a workspace without one under its own ignore files.
61
+ this.#scratchDir = join(options.artifactsDir, "written-files-scan");
62
+ const inside = relative(options.cwd, options.artifactsDir);
63
+ this.#artifactsPrefix =
64
+ inside === "" || inside.startsWith("..") || isAbsolute(inside) ? undefined : `${inside.split(sep).join("/")}/`;
65
+ this.#runGit = options.git;
66
+ this.#fs = options.fs;
67
+ this.#timeoutMs = options.timeoutMs ?? SCAN_TIMEOUT_MS;
68
+ this.#pathLimit = options.pathLimit ?? SCAN_PATH_LIMIT;
69
+ }
70
+
71
+ /**
72
+ * In a repository the tracked candidates of `previous` stay candidates: a file written back to its HEAD content
73
+ * leaves `git status`, and so do files committed since `previous`.
74
+ */
75
+ async scan(previous?: ScannedFiles): Promise<WorkspaceScan> {
76
+ const mode = this.#mode ?? (await this.#detectMode());
77
+ if (typeof mode === "string") return { kind: "skipped", reason: mode };
78
+ this.#mode = mode;
79
+ return mode.kind === "repository" ? this.#scanRepository(mode.prefix, previous) : this.#scanPlain();
80
+ }
81
+
82
+ async #detectMode(): Promise<ScanMode | ScanSkipReason> {
83
+ const located = await this.#git(["rev-parse", "--show-toplevel", "--show-prefix"]);
84
+ if (located.kind === "unavailable" || located.kind === "over_budget") return skipReason(located);
85
+ if (located.kind === "exit") return { kind: "plain" };
86
+ const prefix = located.stdout.split("\n")[1] ?? "";
87
+ if (prefix === "") return { kind: "repository", prefix };
88
+ // A workspace the enclosing repository ignores has no rules there: its own ignore files decide.
89
+ const ignored = await this.#git(["check-ignore", "--quiet", "."]);
90
+ if (ignored.kind === "over_budget") return "over_budget";
91
+ return ignored.kind === "ok" ? { kind: "plain" } : { kind: "repository", prefix };
92
+ }
93
+
94
+ async #scanRepository(prefix: string, previous: ScannedFiles | undefined): Promise<WorkspaceScan> {
95
+ const status = await this.#git([
96
+ "status",
97
+ "--porcelain=v2",
98
+ "--branch",
99
+ "-z",
100
+ "--untracked-files=all",
101
+ "--no-renames",
102
+ "--ignore-submodules=all",
103
+ "--",
104
+ ".",
105
+ ]);
106
+ if (status.kind !== "ok") return { kind: "skipped", reason: skipReason(status) };
107
+ const { head, untracked, tracked, untrackedFromIndex } = parseStatus(status.stdout);
108
+ const committed: string[] = [];
109
+ const previousHead = previous?.head;
110
+ if (previousHead !== undefined && head !== undefined && head !== previousHead && head !== INITIAL_HEAD) {
111
+ const since = previousHead === INITIAL_HEAD ? EMPTY_TREE : previousHead;
112
+ const diff = await this.#git(["diff", "--name-status", "-z", "--no-renames", since, head, "--", "."]);
113
+ if (diff.kind === "over_budget") return { kind: "skipped", reason: "over_budget" };
114
+ if (diff.kind === "ok") {
115
+ const { added, deleted } = parseNameStatus(diff.stdout);
116
+ committed.push(...added);
117
+ untrackedFromIndex.push(...deleted);
118
+ }
119
+ }
120
+ // Porcelain paths are relative to the repository root, the workspace may be a directory below it.
121
+ const inWorkspace = (paths: readonly string[]) =>
122
+ paths.flatMap((path) => (path.startsWith(prefix) ? [path.slice(prefix.length)] : []));
123
+ // Only tracked files are carried over: an untracked one leaves `git status` when it is deleted, committed (the
124
+ // diff above finds it) or ignored, and an ignored file is no candidate. A path deleted from the index, staged or
125
+ // committed, is untracked from then on, so neither its deletion nor an earlier scan carries it; a status record
126
+ // other than a deletion is the index as it is now and outranks both. A path that left `git status` without a
127
+ // record (`git rm --cached` of a file HEAD does not have leaves none) is carried only once the index shows it.
128
+ const gone = new Set(inWorkspace(untrackedFromIndex));
129
+ const listed = new Set(inWorkspace(tracked));
130
+ const unlisted = [...new Set([...inWorkspace(committed), ...(previous?.tracked ?? [])])].filter(
131
+ (path) => !gone.has(path) && !listed.has(path),
132
+ );
133
+ const indexed = await this.#indexed(unlisted);
134
+ if (indexed === "over_budget") return { kind: "skipped", reason: "over_budget" };
135
+ const trackedHere = [...listed, ...unlisted.filter((path) => indexed.has(path))];
136
+ return this.#signatures([...inWorkspace(untracked), ...trackedHere], head, new Set(trackedHere));
137
+ }
138
+
139
+ /** Which of the workspace-relative `paths` the index has, in one git process; none when git cannot say. */
140
+ async #indexed(paths: readonly string[]): Promise<ReadonlySet<string> | "over_budget"> {
141
+ if (paths.length === 0) return new Set();
142
+ if (paths.length > this.#pathLimit) return "over_budget";
143
+ const listed = await this.#git(["--literal-pathspecs", "ls-files", "-z", "--cached", "--", ...paths]);
144
+ if (listed.kind === "over_budget") return "over_budget";
145
+ return new Set(listed.kind === "ok" ? listed.stdout.split("\0").filter((path) => path !== "") : []);
146
+ }
147
+
148
+ async #scanPlain(): Promise<WorkspaceScan> {
149
+ if (!this.#scratchReady) {
150
+ const created = await this.#git(["init", "--quiet", this.#scratchDir]);
151
+ if (created.kind !== "ok") return { kind: "skipped", reason: skipReason(created) };
152
+ this.#scratchReady = true;
153
+ }
154
+ const listed = await this.#git([
155
+ `--git-dir=${join(this.#scratchDir, ".git")}`,
156
+ `--work-tree=${this.#cwd}`,
157
+ "ls-files",
158
+ "-z",
159
+ "--others",
160
+ "--exclude-standard",
161
+ // Without a repository nothing ignores these, and listing them is what makes a fresh project slow.
162
+ ...excludedDirectories().map((directory) => `--exclude=${directory}/`),
163
+ ]);
164
+ if (listed.kind !== "ok") return { kind: "skipped", reason: skipReason(listed) };
165
+ return this.#signatures(listed.stdout.split("\0"), undefined, new Set());
166
+ }
167
+
168
+ async #signatures(
169
+ paths: readonly string[],
170
+ head: string | undefined,
171
+ tracked: ReadonlySet<string>,
172
+ ): Promise<WorkspaceScan> {
173
+ const artifacts = this.#artifactsPrefix;
174
+ const candidates = [...new Set(paths)].filter(
175
+ (path) => isSourcePath(path) && (artifacts === undefined || !path.startsWith(artifacts)),
176
+ );
177
+ if (candidates.length > this.#pathLimit) return { kind: "skipped", reason: "over_budget" };
178
+ const files = new Map<string, FileSignature>();
179
+ for (let start = 0; start < candidates.length; start += STAT_BATCH) {
180
+ const batch = candidates.slice(start, start + STAT_BATCH);
181
+ const signatures = await Promise.all(batch.map((path) => this.#fs.stat(join(this.#cwd, path))));
182
+ batch.forEach((path, index) => {
183
+ const signature = signatures[index];
184
+ if (signature !== undefined && signature.size <= SOURCE_FILE_MAX_BYTES) files.set(path, signature);
185
+ });
186
+ }
187
+ return { kind: "files", files, head, tracked: new Set([...tracked].filter((path) => files.has(path))) };
188
+ }
189
+
190
+ #git(args: readonly string[]): Promise<GitOutcome> {
191
+ return this.#runGit(args, { cwd: this.#cwd, timeoutMs: this.#timeoutMs });
192
+ }
193
+ }
194
+
195
+ function skipReason(outcome: Exclude<GitOutcome, { kind: "ok" }>): ScanSkipReason {
196
+ if (outcome.kind === "unavailable") return "git_unavailable";
197
+ return outcome.kind === "over_budget" ? "over_budget" : "scan_failed";
198
+ }
199
+
200
+ interface StatusRecords {
201
+ head: string | undefined;
202
+ untracked: string[];
203
+ tracked: string[];
204
+ /** Deleted from the index (`git rm --cached`): the file may still be on disk, but git no longer tracks it. */
205
+ untrackedFromIndex: string[];
206
+ }
207
+
208
+ /** Reads `git status --porcelain=v2 --branch -z`: one NUL-terminated record per header and per path. */
209
+ function parseStatus(stdout: string): StatusRecords {
210
+ let head: string | undefined;
211
+ const untracked: string[] = [];
212
+ const tracked: string[] = [];
213
+ const untrackedFromIndex: string[] = [];
214
+ const records = stdout.split("\0");
215
+ for (let index = 0; index < records.length; index++) {
216
+ const record = records[index] ?? "";
217
+ if (record.startsWith(HEAD_RECORD)) head = record.slice(HEAD_RECORD.length);
218
+ else if (record.startsWith("? ")) untracked.push(record.slice(2));
219
+ // The first letter of the `XY` field is the index side: `D` there means the index no longer has the path.
220
+ else if (record.startsWith("1 D")) untrackedFromIndex.push(pathAfterFields(record, 8));
221
+ else if (record.startsWith("1 ")) tracked.push(pathAfterFields(record, 8));
222
+ else if (record.startsWith("u ")) tracked.push(pathAfterFields(record, 10));
223
+ else if (record.startsWith("2 ")) {
224
+ tracked.push(pathAfterFields(record, 9));
225
+ // A rename's source path follows as its own record.
226
+ index += 1;
227
+ }
228
+ }
229
+ return { head, untracked, tracked, untrackedFromIndex };
230
+ }
231
+
232
+ /** Reads `git diff --name-status -z --no-renames`: a status letter, then the path, each NUL-terminated. */
233
+ function parseNameStatus(stdout: string): { added: string[]; deleted: string[] } {
234
+ const added: string[] = [];
235
+ const deleted: string[] = [];
236
+ const fields = stdout.split("\0");
237
+ for (let index = 0; index + 1 < fields.length; index += 2) {
238
+ const path = fields[index + 1] ?? "";
239
+ if (fields[index] === "D") deleted.push(path);
240
+ else added.push(path);
241
+ }
242
+ return { added, deleted };
243
+ }
244
+
245
+ function pathAfterFields(record: string, fields: number): string {
246
+ let offset = 0;
247
+ for (let field = 0; field < fields; field++) {
248
+ const space = record.indexOf(" ", offset);
249
+ if (space === -1) return "";
250
+ offset = space + 1;
251
+ }
252
+ return record.slice(offset);
253
+ }
@@ -0,0 +1,155 @@
1
+ import type { ExtensionToolContext } from "@code-yeongyu/senpi";
2
+ import { capCodePoints } from "../tool/call-capture.ts";
3
+ import type { ScanFs } from "./workspace-fs.ts";
4
+ import { isSourceText, SOURCE_FILE_MAX_BYTES, SOURCE_FILE_SNIFF_BYTES } from "./source-file.ts";
5
+ import {
6
+ type ChangedFile,
7
+ type ClaimRelease,
8
+ type HookStart,
9
+ withoutCeded,
10
+ type WrittenFilesSelection,
11
+ } from "./window.ts";
12
+
13
+ /** Files listed in a cell result and sent through the write hooks; the rest are counted. */
14
+ export const WRITTEN_FILES_LIMIT = 20;
15
+
16
+ const HOOK_OUTPUT_FILE_CODE_POINTS = 2_000;
17
+ const HOOK_OUTPUT_CELL_CODE_POINTS = 12_000;
18
+ const HOOK_ERROR_CODE_POINTS = 300;
19
+ const SNIFF_BATCH = 32;
20
+
21
+ export type ReportToolResult = ExtensionToolContext["reportToolResult"];
22
+ type HookContent = NonNullable<Awaited<ReturnType<ReportToolResult>>["result"]>["content"];
23
+
24
+ export interface WrittenFilesReport {
25
+ /** Workspace-relative paths of the first {@link WRITTEN_FILES_LIMIT} source files written. */
26
+ readonly files: readonly string[];
27
+ readonly total: number;
28
+ /** How many of `files` the write hooks ran for. */
29
+ readonly hooked: number;
30
+ readonly hookOutputs: readonly { readonly path: string; readonly text: string }[];
31
+ readonly hookFailures: readonly { readonly path: string; readonly error: string }[];
32
+ }
33
+
34
+ export interface WriteHookDeps {
35
+ readonly fs: Pick<ScanFs, "read">;
36
+ /** Absent on a host that cannot run `tool_result` handlers for work already done. */
37
+ readonly report: ReportToolResult | undefined;
38
+ /** The hooks for this file returned or failed: what they left on disk is the reporting cell's. */
39
+ readonly noteHooked: (absolutePath: string) => Promise<void>;
40
+ /**
41
+ * The hooks for this listed file start now if this says `started`; `refused` when the cell may no longer start them
42
+ * (it closed), `ceded` when a model call took the file and the cell let go of it.
43
+ */
44
+ readonly start: (absolutePath: string) => HookStart;
45
+ /** The hooks for this listed file will not start: the cell lets go of it, and its change stays for a later cell. */
46
+ readonly skipped: (absolutePath: string) => ClaimRelease;
47
+ /** This listed file could not be read back: the cell lets go of it, and reports that unless a model call took it. */
48
+ readonly failed: (absolutePath: string) => ClaimRelease;
49
+ readonly signal: AbortSignal;
50
+ }
51
+
52
+ /** The changed files a cell lists and, when `hooks` is set, sends through the write hooks: its first source files. */
53
+ export async function selectWrittenFiles(
54
+ changed: readonly ChangedFile[],
55
+ fs: Pick<ScanFs, "read">,
56
+ hooks: boolean,
57
+ ): Promise<WrittenFilesSelection> {
58
+ const sources = await sourceFiles(changed, fs);
59
+ return { listed: sources.slice(0, WRITTEN_FILES_LIMIT), total: sources.length, hooks };
60
+ }
61
+
62
+ /**
63
+ * Sends the content each listed file has on disk through the `tool_result` handlers a `write` call triggers. Nothing
64
+ * is written again, so a hook sees exactly what the cell left and no change made meanwhile can be overwritten.
65
+ */
66
+ export async function reportWrittenFiles(
67
+ selection: WrittenFilesSelection,
68
+ deps: WriteHookDeps,
69
+ ): Promise<WrittenFilesReport | undefined> {
70
+ const { listed, total } = selection;
71
+ if (total === 0) return undefined;
72
+ const hookOutputs: { path: string; text: string }[] = [];
73
+ const hookFailures: { path: string; error: string }[] = [];
74
+ const fail = (path: string, error: string) =>
75
+ hookFailures.push({ path, error: capCodePoints(error, HOOK_ERROR_CODE_POINTS) });
76
+ let outputBudget = HOOK_OUTPUT_CELL_CODE_POINTS;
77
+ let hooked = 0;
78
+ const report = selection.hooks ? deps.report : undefined;
79
+ const ceded: ChangedFile[] = [];
80
+ for (const file of listed) {
81
+ // Without hooks the selection claimed nothing, so there is nothing to let go of.
82
+ if (report === undefined) break;
83
+ if (deps.signal.aborted) {
84
+ if (deps.skipped(file.absolutePath) === "ceded") ceded.push(file);
85
+ continue;
86
+ }
87
+ const bytes = await deps.fs.read(file.absolutePath, SOURCE_FILE_MAX_BYTES + 1);
88
+ // The cell may have been cancelled during the read: a hook it has not started must not start.
89
+ if (deps.signal.aborted) {
90
+ if (deps.skipped(file.absolutePath) === "ceded") ceded.push(file);
91
+ continue;
92
+ }
93
+ if (bytes === undefined || bytes.length > SOURCE_FILE_MAX_BYTES) {
94
+ // A model call may have taken the file during the read back: then the failure is not this cell's to report.
95
+ if (deps.failed(file.absolutePath) === "ceded") ceded.push(file);
96
+ else fail(file.path, "the file could not be read back for the hooks");
97
+ continue;
98
+ }
99
+ // The one dispatch point: from here the file stays this cell's until its hooks return, even if the cell closes.
100
+ // `report` is called with no await after `start`, so no model call can take the file in between.
101
+ const start = deps.start(file.absolutePath);
102
+ if (start === "ceded") ceded.push(file);
103
+ if (start === "refused") deps.skipped(file.absolutePath);
104
+ if (start !== "started") continue;
105
+ const written = `Successfully wrote to ${file.absolutePath}`;
106
+ try {
107
+ const outcome = await report({
108
+ toolName: "write",
109
+ input: { path: file.absolutePath, content: new TextDecoder().decode(bytes) },
110
+ content: [{ type: "text", text: written }],
111
+ });
112
+ hooked += 1;
113
+ for (const failure of outcome.failures) fail(file.path, `${failure.extensionPath}: ${failure.error}`);
114
+ const text = appendedText(outcome.result?.content, written);
115
+ if (text !== "") {
116
+ const shown =
117
+ outputBudget > 0
118
+ ? capCodePoints(text, Math.min(HOOK_OUTPUT_FILE_CODE_POINTS, outputBudget))
119
+ : "[hook output omitted: this cell's hook output limit was reached]";
120
+ outputBudget -= shown.length;
121
+ hookOutputs.push({ path: file.path, text: shown });
122
+ }
123
+ } catch (error) {
124
+ fail(file.path, error instanceof Error ? error.message : String(error));
125
+ }
126
+ // A hook may rewrite the file (a formatter), even one that then failed; that rewrite is not a later cell's write.
127
+ await deps.noteHooked(file.absolutePath);
128
+ }
129
+ // A file a model call took is the call's change: the cell neither lists nor counts it.
130
+ const reported = withoutCeded(selection, ceded);
131
+ if (reported.total === 0) return undefined;
132
+ const files = reported.listed.map((file) => file.path);
133
+ return { files, total: reported.total, hooked, hookOutputs, hookFailures };
134
+ }
135
+
136
+ async function sourceFiles(changed: readonly ChangedFile[], fs: Pick<ScanFs, "read">): Promise<ChangedFile[]> {
137
+ const sources: ChangedFile[] = [];
138
+ for (let start = 0; start < changed.length; start += SNIFF_BATCH) {
139
+ const batch = changed.slice(start, start + SNIFF_BATCH);
140
+ const heads = await Promise.all(batch.map((file) => fs.read(file.absolutePath, SOURCE_FILE_SNIFF_BYTES)));
141
+ batch.forEach((file, index) => {
142
+ const head = heads[index];
143
+ if (head !== undefined && isSourceText(head)) sources.push(file);
144
+ });
145
+ }
146
+ return sources;
147
+ }
148
+
149
+ /** What the handlers added to the result: its text without the line this module supplied itself. */
150
+ function appendedText(content: HookContent, written: string): string {
151
+ if (content === undefined) return "";
152
+ const texts = content.flatMap((part) => (part.type === "text" ? [part.text] : []));
153
+ if (texts[0] === written) texts.shift();
154
+ return texts.join("\n").trim();
155
+ }
@@ -0,0 +1,155 @@
1
+ import { homedir } from "node:os";
2
+ import { join, resolve } from "node:path";
3
+ import type { ExtensionToolContext } from "@code-yeongyu/senpi";
4
+ import type { TimeoutPauseHandle } from "../timeouts/idle-timeout.ts";
5
+ import type { CellWrittenFilesOutcome } from "./report.ts";
6
+ import type { FsAccess, RunGit } from "./scan-boundaries.ts";
7
+ import { WrittenFilesTracker } from "./tracker.ts";
8
+ import type { ToolCallHold } from "./window.ts";
9
+ import { type ScanFs, workspaceFs } from "./workspace-fs.ts";
10
+ import { WorkspaceScanner } from "./workspace-scan.ts";
11
+ import { reportWrittenFiles, selectWrittenFiles } from "./write-hooks.ts";
12
+
13
+ export interface CellWrittenFiles {
14
+ readonly ready: Promise<void>;
15
+ /** Never rejects: a failure here is reported in the outcome, it does not fail the cell. */
16
+ settle(signal: AbortSignal): Promise<CellWrittenFilesOutcome | undefined>;
17
+ close(): void;
18
+ }
19
+
20
+ /**
21
+ * Settles a cell's written files with its budgets paused: the scan and the hooks are host work like a bridge call, so
22
+ * they charge neither the cell's run budget nor its idle watchdog.
23
+ */
24
+ export async function settleWrittenFiles(
25
+ written: CellWrittenFiles | undefined,
26
+ signal: AbortSignal,
27
+ budgets: readonly TimeoutPauseHandle[],
28
+ ): Promise<CellWrittenFilesOutcome | undefined> {
29
+ if (written === undefined) return undefined;
30
+ for (const budget of budgets) budget.pause();
31
+ try {
32
+ return await written.settle(signal);
33
+ } finally {
34
+ for (const budget of budgets) budget.resume();
35
+ }
36
+ }
37
+
38
+ export interface WrittenFilesOptions {
39
+ readonly cwd: string;
40
+ readonly artifactsDir: string;
41
+ readonly git: RunGit;
42
+ /** Confined to `cwd` here, so nothing the check stats or reads lies outside the workspace. */
43
+ readonly fs: FsAccess;
44
+ readonly timeoutMs?: number;
45
+ readonly pathLimit?: number;
46
+ /**
47
+ * False on a hand whose loop runs elsewhere: an extension that also hooks the loop runs whole on the loop's side, and
48
+ * a result reported from here would reach this side's copy of it instead.
49
+ */
50
+ readonly hooksRunHere?: () => boolean;
51
+ }
52
+
53
+ /** The tools whose completed call means its file went through the write hooks. */
54
+ export function isHookedWriteTool(toolName: string): boolean {
55
+ return toolName === "write" || toolName === "edit";
56
+ }
57
+
58
+ /**
59
+ * Per session: what eval cells wrote in the workspace without a `write` or `edit` call, sent through the hooks such a
60
+ * call triggers and listed in the cell result (senpi#7232).
61
+ */
62
+ export class WrittenFiles {
63
+ readonly #cwd: string;
64
+ readonly #fs: ScanFs;
65
+ readonly #hooksRunHere: () => boolean;
66
+ readonly #tracker: WrittenFilesTracker;
67
+
68
+ constructor(options: WrittenFilesOptions) {
69
+ this.#cwd = options.cwd;
70
+ const fs = workspaceFs(options, options.fs);
71
+ this.#fs = fs;
72
+ this.#hooksRunHere = options.hooksRunHere ?? (() => true);
73
+ const scanner = new WorkspaceScanner({
74
+ cwd: options.cwd,
75
+ artifactsDir: options.artifactsDir,
76
+ git: options.git,
77
+ fs,
78
+ ...(options.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),
79
+ ...(options.pathLimit === undefined ? {} : { pathLimit: options.pathLimit }),
80
+ });
81
+ this.#tracker = new WrittenFilesTracker({
82
+ cwd: options.cwd,
83
+ scan: (previous) => scanner.scan(previous),
84
+ stat: (path) => fs.stat(path),
85
+ realpath: (path) => options.fs.realpath(path),
86
+ });
87
+ }
88
+
89
+ open(ctx: ExtensionToolContext): CellWrittenFiles {
90
+ const window = this.#tracker.open();
91
+ // A host older than this capability lists the files and says it cannot run the hooks.
92
+ const report =
93
+ this.#hooksRunHere() && typeof ctx.reportToolResult === "function"
94
+ ? (reported: Parameters<ExtensionToolContext["reportToolResult"]>[0]) => ctx.reportToolResult(reported)
95
+ : undefined;
96
+ return {
97
+ ready: window.ready,
98
+ settle: async (signal) => {
99
+ try {
100
+ const change = await window.settle((files) => selectWrittenFiles(files, this.#fs, report !== undefined));
101
+ if (change.kind === "off") return undefined;
102
+ if (change.kind === "unchecked") return change;
103
+ const written = await reportWrittenFiles(change.selection, {
104
+ fs: this.#fs,
105
+ report,
106
+ noteHooked: (path) => window.hooked(path),
107
+ start: (path) => window.start(path),
108
+ skipped: (path) => window.skipped(path),
109
+ failed: (path) => window.failed(path),
110
+ signal,
111
+ });
112
+ if (written === undefined) return undefined;
113
+ return { kind: "written", report: written, hooksAvailable: report !== undefined };
114
+ } catch (error) {
115
+ return { kind: "failed", message: error instanceof Error ? error.message : String(error) };
116
+ } finally {
117
+ window.release();
118
+ }
119
+ },
120
+ close: () => window.close(),
121
+ };
122
+ }
123
+
124
+ /**
125
+ * A tool call that completed through the hooks. A `write` or `edit` leaves its file accounted for, so the cell
126
+ * that made the call, or one that ran beside it, does not send that file through the hooks again.
127
+ */
128
+ async noteToolCall(toolName: string, params: unknown): Promise<void> {
129
+ const path = calledPath(toolName, params, this.#cwd);
130
+ if (path !== undefined) await this.#tracker.noteHooked(path);
131
+ }
132
+
133
+ /**
134
+ * A `write` or `edit` call starts, before it writes its file: no cell reports or hooks that file until the call
135
+ * ends, so the call's own hooks are the only ones it gets. Undefined when the call names no file in the workspace.
136
+ */
137
+ async startToolCall(toolName: string, params: unknown): Promise<ToolCallHold | undefined> {
138
+ const path = calledPath(toolName, params, this.#cwd);
139
+ return path === undefined ? undefined : await this.#tracker.holdForCall(path);
140
+ }
141
+ }
142
+
143
+ /** The absolute file a `write` or `edit` call names, if the call is one. */
144
+ function calledPath(toolName: string, params: unknown, cwd: string): string | undefined {
145
+ if (!isHookedWriteTool(toolName) || typeof params !== "object" || params === null) return undefined;
146
+ const path = "path" in params ? params.path : undefined;
147
+ return typeof path === "string" && path !== "" ? toolPath(path, cwd) : undefined;
148
+ }
149
+
150
+ /** The file a write or edit call named: the host's file tools drop a leading `@` and expand a leading `~`. */
151
+ function toolPath(named: string, cwd: string): string {
152
+ const path = named.startsWith("@") ? named.slice(1) : named;
153
+ if (path === "~") return homedir();
154
+ return path.startsWith("~/") ? join(homedir(), path.slice(2)) : resolve(cwd, path);
155
+ }