@leolastforce/chalice-hashline-edit 0.0.0-stage → 4.4.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.
Files changed (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +153 -2
  3. package/index.ts +282 -0
  4. package/package.json +79 -4
  5. package/prompts/find-guidelines.md +2 -0
  6. package/prompts/find-snippet.md +1 -0
  7. package/prompts/find.md +1 -0
  8. package/prompts/grep-guidelines.md +2 -0
  9. package/prompts/grep-snippet.md +1 -0
  10. package/prompts/grep.md +1 -0
  11. package/prompts/insert-guidelines.md +1 -0
  12. package/prompts/insert-snippet.md +1 -0
  13. package/prompts/insert.md +1 -0
  14. package/prompts/read-guidelines.md +2 -0
  15. package/prompts/read-snippet.md +1 -0
  16. package/prompts/read.md +1 -0
  17. package/prompts/replace-guidelines.md +4 -0
  18. package/prompts/replace-snippet.md +1 -0
  19. package/prompts/replace.md +1 -0
  20. package/prompts/undo-last-change-guidelines.md +1 -0
  21. package/prompts/undo-last-change-snippet.md +1 -0
  22. package/prompts/undo-last-change.md +1 -0
  23. package/src/anchor-registry.ts +977 -0
  24. package/src/auto-read-all-state.ts +27 -0
  25. package/src/auto-read-all.ts +477 -0
  26. package/src/batch.ts +767 -0
  27. package/src/commit.ts +137 -0
  28. package/src/config-ui.ts +212 -0
  29. package/src/config.ts +235 -0
  30. package/src/constants.ts +26 -0
  31. package/src/edit-common.ts +206 -0
  32. package/src/file-kind.ts +191 -0
  33. package/src/file-reader.ts +135 -0
  34. package/src/find.ts +244 -0
  35. package/src/fs-write.ts +231 -0
  36. package/src/glob.ts +186 -0
  37. package/src/grep.ts +690 -0
  38. package/src/hash-store/cache.ts +18 -0
  39. package/src/hash-store/retry.ts +44 -0
  40. package/src/hash-store/validation.ts +62 -0
  41. package/src/hash-store.ts +609 -0
  42. package/src/hashline/alphabet.ts +21 -0
  43. package/src/hashline/anchor-table.json +1 -0
  44. package/src/hashline/apply.ts +297 -0
  45. package/src/hashline/hash.ts +119 -0
  46. package/src/hashline/hasher.ts +47 -0
  47. package/src/hashline/index.ts +50 -0
  48. package/src/hashline/parse.ts +84 -0
  49. package/src/hashline/resolve.ts +373 -0
  50. package/src/insert.ts +258 -0
  51. package/src/normalize.ts +27 -0
  52. package/src/paths.ts +56 -0
  53. package/src/payload-contract.ts +133 -0
  54. package/src/prompts.ts +13 -0
  55. package/src/read.ts +286 -0
  56. package/src/replace-diff.ts +610 -0
  57. package/src/replace-render.ts +390 -0
  58. package/src/replace-response.ts +166 -0
  59. package/src/replace-undo.ts +270 -0
  60. package/src/replace.ts +318 -0
  61. package/src/served.ts +36 -0
  62. package/src/utils.ts +387 -0
  63. package/src/validation.ts +45 -0
  64. package/src/write-hook.ts +53 -0
@@ -0,0 +1,27 @@
1
+ const completeSnapshots = new Map<string, Map<string, string>>();
2
+
3
+ function scopeFor(sessionKey: string | undefined): string {
4
+ return sessionKey ?? "";
5
+ }
6
+
7
+ export function recordAutoReadAllComplete(sessionKey: string | undefined, absolutePath: string, snapshotId: string): void {
8
+ const scope = scopeFor(sessionKey);
9
+ let snapshots = completeSnapshots.get(scope);
10
+ if (!snapshots) {
11
+ snapshots = new Map();
12
+ completeSnapshots.set(scope, snapshots);
13
+ }
14
+ snapshots.set(absolutePath, snapshotId);
15
+ }
16
+
17
+ export function getAutoReadAllSnapshot(sessionKey: string | undefined, absolutePath: string): string | undefined {
18
+ return completeSnapshots.get(scopeFor(sessionKey))?.get(absolutePath);
19
+ }
20
+
21
+ export function clearAutoReadAllComplete(sessionKey: string | undefined): void {
22
+ completeSnapshots.delete(scopeFor(sessionKey));
23
+ }
24
+
25
+ export function clearAllAutoReadAllComplete(): void {
26
+ completeSnapshots.clear();
27
+ }
@@ -0,0 +1,477 @@
1
+ import { execFile } from "node:child_process";
2
+ import { lstat, open, readdir } from "node:fs/promises";
3
+ import { join, relative, resolve, sep } from "node:path";
4
+ import { formatSize } from "@earendil-works/pi-coding-agent";
5
+ import {
6
+ AUTO_READ_ALL_MAX_BUDGET_BYTES,
7
+ AUTO_READ_ALL_MAX_FILE_BYTES,
8
+ AUTO_READ_ALL_MAX_FILES,
9
+ AUTO_READ_ALL_MIN_BUDGET_BYTES,
10
+ SNIFF_BYTES,
11
+ } from "./constants";
12
+ import { normalizeAutoReadAllIgnoreEntry, type AutoReadAllMode } from "./config";
13
+ import { serveRows } from "./served";
14
+ import { readNormFile, safeSnapId } from "./file-reader";
15
+ import { resolveRgPath } from "./grep";
16
+ import { globToRegex } from "./glob";
17
+ import { MAX_HASH_LINES } from "./hashline";
18
+ import { fmtReadPreview } from "./read";
19
+ import { splitLines } from "./utils";
20
+ import { recordAutoReadAllComplete } from "./auto-read-all-state";
21
+
22
+ const EXEC_TIMEOUT_MS = 20_000;
23
+ const EXEC_MAX_BYTES = 64 * 1024 * 1024;
24
+ const SCAN_CONCURRENCY = 32;
25
+ const SCAN_LIMIT_MULTIPLIER = 4;
26
+ const MAX_REPORTED_OMISSIONS = 50;
27
+ export const AUTO_READ_ALL_CHUNK_BYTES = 48 * 1024;
28
+
29
+ const HEADER =
30
+ "[hashline auto-read-all] Every non-ignored project file is attached below with live hashline anchors. Do not call read for files in [files complete: ...]. Edit directly from the attachment with replace and insert.";
31
+
32
+ const IMAGE_EXTENSIONS = new Set([
33
+ ".avif",
34
+ ".bmp",
35
+ ".gif",
36
+ ".heic",
37
+ ".heif",
38
+ ".ico",
39
+ ".jpeg",
40
+ ".jpg",
41
+ ".jxl",
42
+ ".png",
43
+ ".psd",
44
+ ".svg",
45
+ ".tif",
46
+ ".tiff",
47
+ ".webp",
48
+ ]);
49
+
50
+ export const AUTO_READ_ALL_EXCLUDED_SEGMENTS = [
51
+ "vendor",
52
+ "node_modules",
53
+ "bower_components",
54
+ "third_party",
55
+ "thirdparty",
56
+ "jspm_packages",
57
+ ".venv",
58
+ "venv",
59
+ "site-packages",
60
+ "__pycache__",
61
+ ".tox",
62
+ ".gradle",
63
+ ".terraform",
64
+ "pods",
65
+ "carthage",
66
+ "deriveddata",
67
+ "coreui",
68
+ "coreui-icons",
69
+ ];
70
+ export const AUTO_READ_ALL_EXCLUDED_NAMES = [
71
+ "package-lock.json",
72
+ "yarn.lock",
73
+ "composer.lock",
74
+ "gemfile.lock",
75
+ "cargo.lock",
76
+ "poetry.lock",
77
+ "pipfile.lock",
78
+ "go.sum",
79
+ "flake.lock",
80
+ ".eslintcache",
81
+ ];
82
+ const EXCLUDED_NAME_SET = new Set(AUTO_READ_ALL_EXCLUDED_NAMES);
83
+ const EXCLUDED_SEGMENT_SET = new Set(AUTO_READ_ALL_EXCLUDED_SEGMENTS);
84
+ function isExcludedBySegment(path: string): boolean {
85
+ for (const segment of path.split("/")) {
86
+ if (EXCLUDED_SEGMENT_SET.has(segment.toLowerCase())) return true;
87
+ }
88
+ return false;
89
+ }
90
+ function isExcludedByPattern(baseLower: string): boolean {
91
+ if (baseLower.endsWith(".min.js") || baseLower.endsWith(".min.css") || baseLower.endsWith(".min.mjs")) return true;
92
+ if (baseLower.endsWith("-min.js") || baseLower.endsWith("-min.css")) return true;
93
+ if (baseLower.includes(".bundle.") || baseLower.includes(".chunk.")) return true;
94
+ if (baseLower.endsWith(".umd.js")) return true;
95
+ if (baseLower.endsWith(".map")) return true;
96
+ if (baseLower.endsWith(".lock")) return true;
97
+ if (baseLower.includes(".generated.") || baseLower.includes(".gen.")) return true;
98
+ if (baseLower.endsWith("_pb2.py")) return true;
99
+ if (baseLower.endsWith(".pb.go")) return true;
100
+ if (baseLower.endsWith(".g.dart")) return true;
101
+ if (baseLower.endsWith(".freezed.dart")) return true;
102
+ if (baseLower.endsWith(".designer.cs")) return true;
103
+ if (baseLower.endsWith(".g.cs")) return true;
104
+ if (baseLower.endsWith(".snap")) return true;
105
+ if (baseLower.startsWith("coreui-icons.")) return true;
106
+ if (baseLower === "coreui.css") return true;
107
+ return false;
108
+ }
109
+ export function normalizeAutoReadAllIgnoreList(entries: readonly string[] | undefined): string[] {
110
+ const seen = new Set<string>();
111
+ const out: string[] = [];
112
+ for (const entry of entries ?? []) {
113
+ if (typeof entry !== "string") continue;
114
+ const cleaned = normalizeAutoReadAllIgnoreEntry(entry).toLowerCase();
115
+ if (cleaned.length === 0 || seen.has(cleaned)) continue;
116
+ seen.add(cleaned);
117
+ out.push(cleaned);
118
+ }
119
+ return out;
120
+ }
121
+ const GLOB_CHARS_RE = /[*?[\]{}]/;
122
+ const GLOB_CACHE_LIMIT = 256;
123
+ const globRegexCache = new Map<string, RegExp | null>();
124
+
125
+ function globRegexFor(entry: string): RegExp | null {
126
+ const cached = globRegexCache.get(entry);
127
+ if (cached !== undefined) return cached;
128
+ let compiled: RegExp | null;
129
+ try {
130
+ compiled = globToRegex(entry);
131
+ } catch {
132
+ compiled = null;
133
+ }
134
+ if (globRegexCache.size >= GLOB_CACHE_LIMIT) {
135
+ const oldest = globRegexCache.keys().next().value;
136
+ if (oldest !== undefined) globRegexCache.delete(oldest);
137
+ }
138
+ globRegexCache.set(entry, compiled);
139
+ return compiled;
140
+ }
141
+
142
+ export function isExcludedByCustomIgnore(path: string, customIgnore: readonly string[]): boolean {
143
+ if (customIgnore.length === 0) return false;
144
+ const lower = path.toLowerCase();
145
+ const segments = lower.split("/");
146
+ const base = segments[segments.length - 1] ?? "";
147
+ for (const entry of customIgnore) {
148
+ if (entry.length === 0) continue;
149
+ if (GLOB_CHARS_RE.test(entry)) {
150
+ const regex = globRegexFor(entry);
151
+ if (regex !== null) {
152
+ if (entry.includes("/") ? regex.test(lower) : regex.test(base)) return true;
153
+ continue;
154
+ }
155
+ }
156
+ if (!entry.includes("/")) {
157
+ if (segments.includes(entry)) return true;
158
+ } else if (lower === entry || lower.startsWith(entry + "/") || lower.includes("/" + entry + "/") || lower.endsWith("/" + entry)) return true;
159
+ }
160
+ return false;
161
+ }
162
+
163
+ const WALK_IGNORED_DIRS = new Set([
164
+ ".git",
165
+ ".hg",
166
+ ".svn",
167
+ ".tmp",
168
+ ".cache",
169
+ ".next",
170
+ ".turbo",
171
+ ".venv",
172
+ "venv",
173
+ "__pycache__",
174
+ "build",
175
+ "coverage",
176
+ "dist",
177
+ "node_modules",
178
+ "out",
179
+ "target",
180
+ "vendor",
181
+ ]);
182
+
183
+ export type AutoReadAllSource = "git" | "rg" | "walk";
184
+
185
+ export interface AutoReadAllDiscovery {
186
+ files: string[];
187
+ source: AutoReadAllSource;
188
+ discovered: number;
189
+ skippedBinary: number;
190
+ skippedLarge: number;
191
+ skippedOther: number;
192
+ skippedByName: number;
193
+ }
194
+
195
+ export interface AutoReadAllSection {
196
+ file: string;
197
+ text: string;
198
+ totalLines: number;
199
+ absolutePath: string;
200
+ }
201
+ export interface AutoReadAllInjection {
202
+ text: string;
203
+ files: number;
204
+ bytes: number;
205
+ omitted: string[];
206
+ chunks: string[];
207
+ completeFiles: number;
208
+ }
209
+
210
+ function runCommand(command: string, args: string[], cwd: string): Promise<{ stdout: string; code: number }> {
211
+ return new Promise((resolveResult) => {
212
+ execFile(command, args, { cwd, timeout: EXEC_TIMEOUT_MS, maxBuffer: EXEC_MAX_BYTES }, (error, stdout) => {
213
+ if (error === null) {
214
+ resolveResult({ stdout: stdout ?? "", code: 0 });
215
+ return;
216
+ }
217
+ const code = typeof (error as { code?: unknown }).code === "number" ? (error as { code: number }).code : 1;
218
+ resolveResult({ stdout: stdout ?? "", code });
219
+ });
220
+ });
221
+ }
222
+
223
+ async function listFromGit(cwd: string): Promise<string[] | undefined> {
224
+ const result = await runCommand("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], cwd);
225
+ if (result.code !== 0) return undefined;
226
+ return result.stdout.split("\0").filter((entry) => entry.length > 0);
227
+ }
228
+
229
+ async function listFromRg(cwd: string): Promise<string[] | undefined> {
230
+ let rgPath: string;
231
+ try {
232
+ rgPath = await resolveRgPath();
233
+ } catch {
234
+ return undefined;
235
+ }
236
+ const result = await runCommand(rgPath, ["--files", "--hidden", "--no-require-git", "--glob", "!.git", "--null"], cwd);
237
+ if (result.code === 1) return [];
238
+ if (result.code !== 0) return undefined;
239
+ return result.stdout.split("\0").filter((entry) => entry.length > 0);
240
+ }
241
+
242
+ async function walkDir(dir: string, base: string, out: string[], customIgnore: readonly string[] = []): Promise<void> {
243
+ let entries;
244
+ try {
245
+ entries = await readdir(dir, { withFileTypes: true });
246
+ } catch {
247
+ return;
248
+ }
249
+ for (const entry of entries) {
250
+ if (entry.isSymbolicLink()) continue;
251
+ const full = join(dir, entry.name);
252
+ if (entry.isDirectory()) {
253
+ if (WALK_IGNORED_DIRS.has(entry.name) || EXCLUDED_SEGMENT_SET.has(entry.name.toLowerCase())) continue;
254
+ if (customIgnore.length > 0 && isExcludedByCustomIgnore(toPosix(relative(base, full)), customIgnore)) continue;
255
+ await walkDir(full, base, out, customIgnore);
256
+ } else if (entry.isFile()) {
257
+ out.push(toPosix(relative(base, full)));
258
+ }
259
+ }
260
+ }
261
+
262
+ function toPosix(path: string): string {
263
+ return sep === "/" ? path : path.split(sep).join("/");
264
+ }
265
+
266
+ function baseNameOf(path: string): string {
267
+ return path.slice(path.lastIndexOf("/") + 1);
268
+ }
269
+
270
+ function extensionOf(path: string): string {
271
+ const base = baseNameOf(path);
272
+ const dot = base.lastIndexOf(".");
273
+ return dot <= 0 ? "" : base.slice(dot).toLowerCase();
274
+ }
275
+
276
+ async function hasNulByte(path: string): Promise<boolean | undefined> {
277
+ let handle;
278
+ try {
279
+ handle = await open(path, "r");
280
+ } catch {
281
+ return undefined;
282
+ }
283
+ try {
284
+ const buffer = Buffer.alloc(SNIFF_BYTES);
285
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
286
+ return buffer.subarray(0, bytesRead).includes(0);
287
+ } catch {
288
+ return undefined;
289
+ } finally {
290
+ await handle.close();
291
+ }
292
+ }
293
+
294
+ async function forEachLimit<T>(items: T[], limit: number, work: (item: T) => Promise<void>): Promise<void> {
295
+ let index = 0;
296
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
297
+ while (index < items.length) {
298
+ const item = items[index];
299
+ index += 1;
300
+ if (item !== undefined) await work(item);
301
+ }
302
+ });
303
+ await Promise.all(workers);
304
+ }
305
+
306
+ export async function discoverAutoReadAllFiles(cwd: string, mode: AutoReadAllMode = "on", ignoreDirs: readonly string[] = []): Promise<AutoReadAllDiscovery> {
307
+ const customIgnore = normalizeAutoReadAllIgnoreList(ignoreDirs);
308
+ let source: AutoReadAllSource = "git";
309
+ let candidates = await listFromGit(cwd);
310
+ if (candidates === undefined) {
311
+ if (mode === "git") {
312
+ return { files: [], source: "git", discovered: 0, skippedBinary: 0, skippedLarge: 0, skippedOther: 0, skippedByName: 0 };
313
+ }
314
+ candidates = await listFromRg(cwd);
315
+ source = "rg";
316
+ }
317
+ if (candidates === undefined) {
318
+ source = "walk";
319
+ const walked: string[] = [];
320
+ await walkDir(cwd, cwd, walked, customIgnore);
321
+ candidates = walked;
322
+ }
323
+
324
+ const unique = [...new Set(candidates.map(toPosix))].sort();
325
+ const includable: string[] = [];
326
+ let skippedByName = 0;
327
+ for (const file of unique) {
328
+ const baseLower = baseNameOf(file).toLowerCase();
329
+ if (EXCLUDED_NAME_SET.has(baseLower) || isExcludedBySegment(file) || isExcludedByPattern(baseLower) || isExcludedByCustomIgnore(file, customIgnore)) skippedByName += 1;
330
+ else includable.push(file);
331
+ }
332
+ const scanWindow = includable.slice(0, AUTO_READ_ALL_MAX_FILES * SCAN_LIMIT_MULTIPLIER);
333
+ const sized: string[] = [];
334
+ let skippedBinary = 0;
335
+ let skippedLarge = 0;
336
+ let skippedOther = 0;
337
+
338
+ await forEachLimit(scanWindow, SCAN_CONCURRENCY, async (file) => {
339
+ let stats;
340
+ try {
341
+ stats = await lstat(resolve(cwd, file));
342
+ } catch {
343
+ skippedOther += 1;
344
+ return;
345
+ }
346
+ if (!stats.isFile()) {
347
+ skippedOther += 1;
348
+ return;
349
+ }
350
+ if (stats.size > AUTO_READ_ALL_MAX_FILE_BYTES) {
351
+ skippedLarge += 1;
352
+ return;
353
+ }
354
+ if (IMAGE_EXTENSIONS.has(extensionOf(file))) {
355
+ skippedBinary += 1;
356
+ return;
357
+ }
358
+ sized.push(file);
359
+ });
360
+
361
+ const textual: string[] = [];
362
+ await forEachLimit(sized, SCAN_CONCURRENCY, async (file) => {
363
+ const nul = await hasNulByte(resolve(cwd, file));
364
+ if (nul === undefined) skippedOther += 1;
365
+ else if (nul) skippedBinary += 1;
366
+ else textual.push(file);
367
+ });
368
+ textual.sort();
369
+ const files = textual.slice(0, AUTO_READ_ALL_MAX_FILES);
370
+
371
+ return { files, source, discovered: unique.length, skippedBinary, skippedLarge, skippedOther, skippedByName };
372
+ }
373
+
374
+ export function chunkAutoReadAllSections(sections: string[], maxBytes: number = AUTO_READ_ALL_CHUNK_BYTES): string[] {
375
+ const chunks: string[] = [];
376
+ let current: string[] = [];
377
+ let currentBytes = 0;
378
+ for (const section of sections) {
379
+ const sectionBytes = Buffer.byteLength(section, "utf-8") + 2;
380
+ if (current.length > 0 && currentBytes + sectionBytes > maxBytes) {
381
+ chunks.push(current.join("\n\n"));
382
+ current = [];
383
+ currentBytes = 0;
384
+ }
385
+ current.push(section);
386
+ currentBytes += sectionBytes;
387
+ }
388
+ if (current.length > 0) chunks.push(current.join("\n\n"));
389
+ return chunks;
390
+ }
391
+
392
+ async function candidateFileBytes(cwd: string, file: string): Promise<number | undefined> {
393
+ try {
394
+ const stats = await lstat(resolve(cwd, file));
395
+ return stats.isFile() ? stats.size : undefined;
396
+ } catch {
397
+ return undefined;
398
+ }
399
+ }
400
+
401
+ async function renderFile(file: string, cwd: string): Promise<AutoReadAllSection | undefined> {
402
+ try {
403
+ const { normalized, fileHashes, absolutePath } = await readNormFile(file, cwd, { maxLines: MAX_HASH_LINES });
404
+ const preview = await fmtReadPreview(normalized, {}, fileHashes, absolutePath, AUTO_READ_ALL_MAX_BUDGET_BYTES, MAX_HASH_LINES);
405
+ serveRows(absolutePath, fileHashes, splitLines(normalized), preview.servedHashes);
406
+ const totalLines = fileHashes.length;
407
+ return { file, text: `=== ${file} ===\n${preview.text}`, totalLines, absolutePath };
408
+ } catch (error) {
409
+ console.error(`Auto-read all: skipped ${file}:`, error);
410
+ return undefined;
411
+ }
412
+ }
413
+
414
+ function buildFooter(attached: number, discovery: AutoReadAllDiscovery, omitted: string[]): string {
415
+ const notes: string[] = [];
416
+ const beyondCap = Math.max(
417
+ 0,
418
+ discovery.discovered - discovery.files.length - discovery.skippedBinary - discovery.skippedLarge - discovery.skippedOther - discovery.skippedByName,
419
+ );
420
+ if (beyondCap > 0) notes.push(`${beyondCap} file(s) beyond the ${AUTO_READ_ALL_MAX_FILES}-file cap skipped`);
421
+ if (discovery.skippedBinary > 0) notes.push(`${discovery.skippedBinary} binary or image file(s) skipped`);
422
+ if (discovery.skippedLarge > 0) notes.push(`${discovery.skippedLarge} file(s) over ${formatSize(AUTO_READ_ALL_MAX_FILE_BYTES)} skipped`);
423
+ if (discovery.skippedOther > 0) notes.push(`${discovery.skippedOther} unreadable path(s) skipped`);
424
+ if (discovery.skippedByName > 0) notes.push(`${discovery.skippedByName} file(s) skipped by vendor/name/pattern rules`);
425
+ const listed = omitted.slice(0, MAX_REPORTED_OMISSIONS).join(", ");
426
+ const more = omitted.length > MAX_REPORTED_OMISSIONS ? `, ... (+${omitted.length - MAX_REPORTED_OMISSIONS} more)` : "";
427
+ const omissionNote = omitted.length > 0 ? ` Not attached: ${listed}${more}. Use read for those.` : "";
428
+ const summary = notes.length > 0 ? notes.join("; ") + "." : "all discovered files attached.";
429
+ return `[hashline auto-read-all: ${attached} file(s) attached from ${discovery.source}; ${summary}${omissionNote}]`;
430
+ }
431
+
432
+ export async function buildAutoReadAllInjection(cwd: string, budgetBytes: number, mode: AutoReadAllMode = "on", ignoreDirs: readonly string[] = [], sessionKey?: string): Promise<AutoReadAllInjection | undefined> {
433
+ const discovery = await discoverAutoReadAllFiles(cwd, mode, ignoreDirs);
434
+ if (discovery.files.length === 0) return undefined;
435
+ const sections: AutoReadAllSection[] = [];
436
+ const omitted: string[] = [];
437
+ let bytes = 0;
438
+ let completeFiles = 0;
439
+ for (const file of discovery.files) {
440
+ if (sections.length > 0) {
441
+ const size = await candidateFileBytes(cwd, file);
442
+ if (size !== undefined && bytes + size > budgetBytes) {
443
+ omitted.push(file);
444
+ continue;
445
+ }
446
+ }
447
+ const section = await renderFile(file, cwd);
448
+ if (section === undefined) {
449
+ omitted.push(file);
450
+ continue;
451
+ }
452
+ const sectionBytes = Buffer.byteLength(section.text, "utf-8") + 1;
453
+ if (sections.length > 0 && bytes + sectionBytes > budgetBytes) {
454
+ omitted.push(file);
455
+ continue;
456
+ }
457
+ sections.push(section);
458
+ const snapshotId = await safeSnapId(section.absolutePath, "auto-read-all");
459
+ if (snapshotId !== undefined) recordAutoReadAllComplete(sessionKey, section.absolutePath, snapshotId);
460
+ bytes += sectionBytes;
461
+ completeFiles += 1;
462
+ }
463
+ if (sections.length === 0) return undefined;
464
+ const sectionTexts = sections.map((section) => section.text);
465
+ const chunks = chunkAutoReadAllSections(sectionTexts);
466
+ const coverage = `[coverage: ${completeFiles} complete]`;
467
+ const completeNames = sections.map((section) => section.file);
468
+ const machineList = `[files complete: ${JSON.stringify(completeNames)} omitted: ${JSON.stringify(omitted)}]`;
469
+ const text = `${HEADER}\n\n${coverage}\n${machineList}\n\n${sectionTexts.join("\n\n")}\n\n${buildFooter(sections.length, discovery, omitted)}`;
470
+ return { text, files: sections.length, bytes, omitted, chunks, completeFiles };
471
+ }
472
+
473
+ export function autoReadAllBudget(model: { contextWindow?: number } | undefined): number {
474
+ const contextWindow = typeof model?.contextWindow === "number" && model.contextWindow > 0 ? model.contextWindow : 0;
475
+ const fromContext = Math.floor(contextWindow * 1.5);
476
+ return Math.min(AUTO_READ_ALL_MAX_BUDGET_BYTES, Math.max(AUTO_READ_ALL_MIN_BUDGET_BYTES, fromContext));
477
+ }