dsh-better-edit 1.2.3 → 1.2.5

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 (105) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +39 -20
  3. package/README.zh.md +39 -31
  4. package/lib/contract.js +53 -22
  5. package/lib/domain-errors.js +18 -10
  6. package/lib/edit-mode.js +11 -0
  7. package/lib/encoding.js +2 -0
  8. package/lib/file-encoding-state.js +138 -44
  9. package/lib/file-view.js +26 -205
  10. package/lib/fs-bridge.js +53 -71
  11. package/lib/hashline/anchor-pipeline.js +8 -499
  12. package/lib/hashline/hash-assign.js +55 -4
  13. package/lib/hashline/index.js +5 -2
  14. package/lib/hashline/served-evidence.js +531 -0
  15. package/lib/index.js +177 -33
  16. package/lib/mutation/engine.js +19 -61
  17. package/lib/mutation.js +63 -105
  18. package/lib/noop-guard.js +24 -38
  19. package/lib/paths.js +9 -5
  20. package/lib/preset-toolset.js +144 -0
  21. package/lib/prompts.js +3 -3
  22. package/lib/read-and-serve.js +51 -53
  23. package/lib/reclaim.js +65 -0
  24. package/lib/self-heal.js +14 -13
  25. package/lib/session-view.js +79 -49
  26. package/lib/store/index.js +14 -14
  27. package/lib/store-config.js +4 -5
  28. package/lib/store-lifecycle.js +1 -1
  29. package/lib/tool-edit.js +14 -56
  30. package/lib/tool-read.js +2 -8
  31. package/lib/tool-str-replace-editor.js +34 -18
  32. package/lib/tool-undo.js +42 -24
  33. package/lib/types/contract.d.ts +11 -20
  34. package/lib/types/domain-errors.d.ts +14 -10
  35. package/lib/types/edit-mode.d.ts +11 -0
  36. package/lib/types/encoding.d.ts +1 -0
  37. package/lib/types/file-encoding-state.d.ts +51 -14
  38. package/lib/types/file-view.d.ts +18 -56
  39. package/lib/types/fs-bridge.d.ts +0 -1
  40. package/lib/types/hashline/anchor-pipeline.d.ts +6 -128
  41. package/lib/types/hashline/hash-assign.d.ts +40 -0
  42. package/lib/types/hashline/index.d.ts +6 -4
  43. package/lib/types/hashline/served-evidence.d.ts +152 -0
  44. package/lib/types/mutation/engine.d.ts +4 -12
  45. package/lib/types/mutation.d.ts +10 -58
  46. package/lib/types/noop-guard.d.ts +2 -33
  47. package/lib/types/paths.d.ts +0 -1
  48. package/lib/types/preset-toolset.d.ts +61 -0
  49. package/lib/types/reclaim.d.ts +36 -0
  50. package/lib/types/self-heal.d.ts +9 -3
  51. package/lib/types/session-view.d.ts +38 -8
  52. package/lib/types/store/index.d.ts +12 -11
  53. package/lib/types/store-config.d.ts +1 -1
  54. package/lib/types/store-lifecycle.d.ts +12 -2
  55. package/lib/types/tool-edit.d.ts +2 -4
  56. package/lib/types/tool-read.d.ts +0 -5
  57. package/lib/types/tool-str-replace-editor.d.ts +0 -6
  58. package/lib/types/tool-undo.d.ts +0 -5
  59. package/package.json +3 -2
  60. package/lib/drift.js +0 -5
  61. package/lib/dsh-context.js +0 -5
  62. package/lib/edit-engine.js +0 -7
  63. package/lib/edit-normalize.js +0 -9
  64. package/lib/edit-pipeline.js +0 -6
  65. package/lib/file-kind.js +0 -6
  66. package/lib/file-reader.js +0 -6
  67. package/lib/guidance/index.js +0 -8
  68. package/lib/hashline/alphabet.js +0 -2
  69. package/lib/hashline/apply.js +0 -2
  70. package/lib/hashline/hasher.js +0 -2
  71. package/lib/hashline/parse.js +0 -2
  72. package/lib/hashline/pure.js +0 -2
  73. package/lib/hashline/resolve.js +0 -3
  74. package/lib/hashline/served.js +0 -2
  75. package/lib/preview-controller.js +0 -65
  76. package/lib/read-render.js +0 -6
  77. package/lib/schema.js +0 -24
  78. package/lib/served-store.js +0 -5
  79. package/lib/tool-batch-edit.js +0 -190
  80. package/lib/truncate.js +0 -6
  81. package/lib/types/drift.d.ts +0 -5
  82. package/lib/types/dsh-context.d.ts +0 -5
  83. package/lib/types/edit-engine.d.ts +0 -7
  84. package/lib/types/edit-normalize.d.ts +0 -1
  85. package/lib/types/edit-pipeline.d.ts +0 -6
  86. package/lib/types/file-kind.d.ts +0 -6
  87. package/lib/types/file-reader.d.ts +0 -6
  88. package/lib/types/guidance/index.d.ts +0 -8
  89. package/lib/types/hashline/alphabet.d.ts +0 -1
  90. package/lib/types/hashline/apply.d.ts +0 -1
  91. package/lib/types/hashline/hasher.d.ts +0 -1
  92. package/lib/types/hashline/parse.d.ts +0 -1
  93. package/lib/types/hashline/pure.d.ts +0 -1
  94. package/lib/types/hashline/resolve.d.ts +0 -1
  95. package/lib/types/hashline/served.d.ts +0 -1
  96. package/lib/types/preview-controller.d.ts +0 -33
  97. package/lib/types/read-render.d.ts +0 -6
  98. package/lib/types/schema.d.ts +0 -25
  99. package/lib/types/served-store.d.ts +0 -5
  100. package/lib/types/tool-batch-edit.d.ts +0 -25
  101. package/lib/types/truncate.d.ts +0 -6
  102. package/lib/types/validation.d.ts +0 -6
  103. package/lib/types/workspace.d.ts +0 -5
  104. package/lib/validation.js +0 -6
  105. package/lib/workspace.js +0 -5
@@ -14,40 +14,79 @@
14
14
  *
15
15
  * @module dsh-better-edit/file-encoding-state
16
16
  */
17
- import { detectBom, isValidUtf8, decodeBytes, normalizeEncoding, top3Candidates, chardetTop3Candidates, } from "./encoding.js";
17
+ import { detectBom, isValidUtf8, decodeBytes, encodeText, normalizeEncoding, top3Candidates, chardetTop3Candidates, } from "./encoding.js";
18
18
  import { detectEnding, restoreEndings, toLF } from "./edit-diff.js";
19
19
  import { DomainError, formatError } from "./domain-errors.js";
20
+ /**
21
+ * The decode hint a mutating re-read must pass to the byte seam: the encoding
22
+ * recorded by the preceding `read({ encoding })` — but only while the memo still
23
+ * matches the on-disk version, and only for encodings the plain read path cannot
24
+ * reproduce.
25
+ *
26
+ * `utf8` / `utf8bom` need no hint: BOM sniff + strict UTF-8 (and the bridge's
27
+ * stripped-BOM restore) already decode them to the text the anchors were served
28
+ * for, so asking for a byte reread would only cost an RPC. Everything else
29
+ * (utf16le, windows-1251, GBK, …) is invisible to the plain path — without the
30
+ * hint the mutation re-read decodes lossily or fails, which is the stale-anchor /
31
+ * unsupported-file symptom this hint removes (issue #112).
32
+ *
33
+ * A drifted memo is dropped first, so a changed file is re-detected instead of
34
+ * having the old encoding laundered onto its new bytes.
35
+ */
36
+ export function encodingHintAtVersion(filePath, currentVersion) {
37
+ invalidateIfStale(filePath, currentVersion);
38
+ const encoding = getEncodingState(filePath)?.encoding;
39
+ if (encoding === undefined || encoding === "utf8" || encoding === "utf8bom")
40
+ return undefined;
41
+ return encoding;
42
+ }
20
43
  const encodingMemo = new Map();
21
44
  const autoGuessFooterMemo = new Map();
22
- export function getEncodingState(targetKey) {
23
- return encodingMemo.get(targetKey);
45
+ /**
46
+ * The memo identity of a file: its absolute path, slash-normalized (ADR-0038).
47
+ *
48
+ * This module is the only key construction site. A caller passes whatever path it
49
+ * holds — `FileIO.resolve` already returned `fs.processPath(target)` — and gets
50
+ * the same identity back, so no reader has to probe a second spelling: a memo
51
+ * keyed two ways makes every lookup a ladder and every write a dual write, and
52
+ * the two spellings then have to be kept in sync by hand. Backend canonicaliza-
53
+ * tion (symlink/case, the backend's opaque `targetKey`) is the backend's view of
54
+ * the target, not the memo's identity; it does not belong in this key — which is
55
+ * why every public function here takes `filePath`, never a backend key.
56
+ */
57
+ function keyOf(path) {
58
+ return String(path).replace(/\\/g, "/");
59
+ }
60
+ export function getEncodingState(filePath) {
61
+ return encodingMemo.get(keyOf(filePath));
24
62
  }
25
- export function setEncodingState(targetKey, state) {
26
- encodingMemo.set(targetKey, state);
63
+ export function setEncodingState(filePath, state) {
64
+ encodingMemo.set(keyOf(filePath), state);
27
65
  }
28
- export function clearEncodingState(targetKey) {
29
- if (targetKey)
30
- encodingMemo.delete(targetKey);
66
+ export function clearEncodingState(filePath) {
67
+ if (filePath)
68
+ encodingMemo.delete(keyOf(filePath));
31
69
  else
32
70
  encodingMemo.clear();
33
71
  }
34
- export function getAutoGuessFooter(targetKey) {
35
- return autoGuessFooterMemo.get(targetKey);
72
+ export function getAutoGuessFooter(filePath) {
73
+ return autoGuessFooterMemo.get(keyOf(filePath));
36
74
  }
37
- export function setAutoGuessFooter(targetKey, footer) {
38
- autoGuessFooterMemo.set(targetKey, footer);
75
+ export function setAutoGuessFooter(filePath, footer) {
76
+ autoGuessFooterMemo.set(keyOf(filePath), footer);
39
77
  }
40
- export function clearAutoGuessFooter(targetKey) {
41
- if (targetKey)
42
- autoGuessFooterMemo.delete(targetKey);
78
+ export function clearAutoGuessFooter(filePath) {
79
+ if (filePath)
80
+ autoGuessFooterMemo.delete(keyOf(filePath));
43
81
  else
44
82
  autoGuessFooterMemo.clear();
45
83
  }
46
84
  /** Invalidate memo when FsVersion drifted (ADR-0012). */
47
- export function invalidateIfStale(targetKey, currentVersion) {
48
- const memo = encodingMemo.get(targetKey);
85
+ export function invalidateIfStale(filePath, currentVersion) {
86
+ const key = keyOf(filePath);
87
+ const memo = encodingMemo.get(key);
49
88
  if (memo && memo.version !== currentVersion)
50
- encodingMemo.delete(targetKey);
89
+ encodingMemo.delete(key);
51
90
  }
52
91
  // ---------------------------------------------------------------------------
53
92
  // Pure helpers — no IO
@@ -260,63 +299,118 @@ export async function decodeForOpen(bytes, config, opts = {}) {
260
299
  });
261
300
  }
262
301
  // ---------------------------------------------------------------------------
263
- // Recording helpers — caller supplies targetKey + version after decode
302
+ // Recording helpers — caller supplies the file path + version after decode
303
+ // (identity is `keyOf`'d inside the seam, so one path is one memo entry)
264
304
  // ---------------------------------------------------------------------------
265
- export function recordOpenState(targetKey, text, encoding, hasBOM, version) {
305
+ export function recordOpenState(filePath, text, encoding, hasBOM, version) {
266
306
  const state = {
267
307
  encoding,
268
308
  hasBOM,
269
309
  lineEnding: detectEnding(text),
270
310
  version,
271
311
  };
272
- setEncodingState(targetKey, state);
312
+ setEncodingState(filePath, state);
273
313
  return state;
274
314
  }
275
- export function recordFooter(targetKey, footer) {
315
+ export function recordFooter(filePath, footer) {
276
316
  if (footer)
277
- setAutoGuessFooter(targetKey, footer);
317
+ setAutoGuessFooter(filePath, footer);
278
318
  }
279
319
  /** Shared UTF-8 BOM marker — single source for the BOM round-trip seam.
280
320
  * Prefer `prepareForSave` / `stripBOM` over re-implementing this check. */
281
321
  export const UTF8_BOM = "\uFEFF";
282
322
  /**
283
- * Decide what bytes (as text, since provider expects string) to write and
284
- * what new state to record. BOM and lineEnding are restored here when a
285
- * previous state exists; otherwise defaults are UTF-8 without BOM and LF.
286
- * For legacy encodings with normalizeToUtf8:false, we preserve the memo
287
- * (provider will write UTF-8 string, next read re-detects via version bump).
323
+ * True when the text's UTF-8 byte image is byte-identical to its byte image
324
+ * under `encoding` — an ASCII-only file in a single-byte charset, where the
325
+ * text-only write seam reproduces the original bytes exactly. Checking bytes
326
+ * (not the encoding name) is what keeps that file editable.
327
+ *
328
+ * This is a property of the TEXT only. A recorded `hasBOM` is a property of the
329
+ * FILE and is checked separately at the call site: the legacy BOM bytes cannot be
330
+ * reproduced by a UTF-8 string write (a UTF-8 BOM is a different byte image).
331
+ */
332
+ export function isByteFaithfulAsUtf8(text, encoding) {
333
+ if (encoding === "utf8" || encoding === "utf8bom")
334
+ return true;
335
+ const encoded = encodeText(text, encoding);
336
+ if (encoded === undefined)
337
+ return false;
338
+ const utf8 = new TextEncoder().encode(text);
339
+ if (encoded.length !== utf8.length)
340
+ return false;
341
+ for (let i = 0; i < utf8.length; i += 1)
342
+ if (encoded[i] !== utf8[i])
343
+ return false;
344
+ return true;
345
+ }
346
+ /**
347
+ * Decide what bytes (as text, since the write seam takes a string) to write and
348
+ * what new state to record. BOM and lineEnding are restored here when a state
349
+ * exists; otherwise defaults are UTF-8 without BOM and LF.
350
+ *
351
+ * ROUND-TRIP VERDICT: the bridge's only write is `writeText(target, content:
352
+ * string, …)`, which every backend encodes as UTF-8. So the save side can
353
+ * restore BOM + line ending for the UTF-8 family, and can write a legacy file
354
+ * only when its UTF-8 byte image is identical (ASCII-only). Anything else
355
+ * throws `E_ENCODING_UNWRITABLE` BEFORE the write, because writing UTF-8 would
356
+ * silently transcode the file and leave the anchors describing other bytes.
357
+ * `normalizeToUtf8: true` is the explicit migration: write UTF-8 and record
358
+ * `utf8` so the next read agrees with the bytes.
288
359
  */
289
360
  export function prepareForSave(content, existingState, opts = {}) {
361
+ const displayPath = opts.displayPath ?? "(unknown path)";
362
+ const normalize = opts.normalizeToUtf8 === true;
290
363
  if (opts.encodingHint) {
291
364
  const norm = normalizeEncoding(opts.encodingHint);
292
365
  if (!norm)
293
366
  throw new DomainError("E_BAD_PAYLOAD", { message: `Unknown encoding: ${opts.encodingHint}` });
367
+ // A non-UTF-8 hint names an encoding the UTF-8 text write cannot reproduce
368
+ // except byte-faithfully; a recorded BOM adds bytes it cannot reproduce at all.
369
+ const hintFaithful = (norm === "utf8" || norm === "utf8bom" || isByteFaithfulAsUtf8(content, norm)) &&
370
+ !(existingState?.hasBOM === true && norm !== "utf8bom");
371
+ if (!hintFaithful)
372
+ throw new DomainError("E_ENCODING_UNWRITABLE", { path: displayPath, encoding: norm });
294
373
  const hasBOM = norm === "utf8bom";
295
374
  const lineEnding = existingState?.lineEnding ?? detectEnding(content);
296
- // Caller will write `content` as UTF-8 string; record new state for next read.
375
+ // Caller writes `content` as a UTF-8 string; record what the next read detects.
297
376
  return {
298
377
  textToWrite: content,
299
378
  newState: { encoding: norm, hasBOM, lineEnding, version: undefined },
300
379
  };
301
380
  }
302
- if (existingState &&
303
- !opts.normalizeToUtf8 &&
304
- existingState.encoding !== "utf8" &&
305
- existingState.encoding !== "utf8bom") {
306
- // Legacy file, normalize false — preserve memo on wire (no transcode),
307
- // provider writes UTF-8 string, version bump will invalidate on next read.
381
+ if (!existingState) {
382
+ // New file, no memo: UTF-8, caller's own line endings.
308
383
  return { textToWrite: content };
309
384
  }
310
- // Default: restore recorded BOM + lineEnding via the shared seam so
311
- // governed writers (e.g. the str_replace_editor shadow) don't re-implement
312
- // the round-trip locally and diverge on future utf16le/lineEnding evolution.
313
- // Only add, never strip: a missing memo means UTF-8 without BOM + LF.
314
- let textToWrite = content;
315
- if (existingState?.lineEnding) {
316
- textToWrite = restoreEndings(toLF(textToWrite), existingState.lineEnding);
385
+ const recorded = existingState.encoding;
386
+ const lineEnding = existingState.lineEnding ?? detectEnding(content);
387
+ if (recorded !== "utf8" && recorded !== "utf8bom") {
388
+ const body = restoreEndings(toLF(content), lineEnding);
389
+ // A recorded BOM on a non-UTF-8 encoding means bytes the text write cannot
390
+ // reproduce (e.g. read({ encoding: "windows-1251" }) on a UTF-8-BOM file, or
391
+ // utf16le's FF FE), so even an ASCII body is not byte-faithful there.
392
+ const faithful = !existingState.hasBOM && isByteFaithfulAsUtf8(body, recorded);
393
+ if (!normalize && !faithful) {
394
+ throw new DomainError("E_ENCODING_UNWRITABLE", { path: displayPath, encoding: recorded });
395
+ }
396
+ // Migration (normalizeToUtf8) or a byte-faithful legacy image: both land UTF-8
397
+ // bytes, so the memo must describe UTF-8 — never a stale utf16le/legacy name.
398
+ return {
399
+ textToWrite: body,
400
+ newState: { encoding: "utf8", hasBOM: false, lineEnding, version: undefined },
401
+ };
317
402
  }
318
- if (existingState?.hasBOM && !textToWrite.startsWith(UTF8_BOM)) {
403
+ // UTF-8 family: restore the recorded BOM + lineEnding via the shared seam so
404
+ // governed writers (e.g. the str_replace_editor shadow) don't re-implement the
405
+ // round-trip locally and diverge on future lineEnding evolution.
406
+ // Only add, never strip: a missing BOM means UTF-8 without BOM.
407
+ let textToWrite = restoreEndings(toLF(content), lineEnding);
408
+ if (existingState.hasBOM && !textToWrite.startsWith(UTF8_BOM)) {
319
409
  textToWrite = `${UTF8_BOM}${textToWrite}`;
320
410
  }
321
- return { textToWrite };
411
+ const hasBOM = textToWrite.startsWith(UTF8_BOM);
412
+ return {
413
+ textToWrite,
414
+ newState: { encoding: hasBOM ? "utf8bom" : "utf8", hasBOM, lineEnding, version: undefined },
415
+ };
322
416
  }
package/lib/file-view.js CHANGED
@@ -2,32 +2,27 @@
2
2
  * FileView — deep module owning "what the model sees".
3
3
  *
4
4
  * Single seam for normalize → hash → render → truncate → served-row
5
- * selection. Previously split across file-reader, read-render, truncate,
6
- * file-kind, validation — each shallow (interface≈implementation). Now one
7
- * file owns the invariant; deleting it would scatter complexity (deep).
5
+ * selection. Previously split across five shallow modules
6
+ * (interface≈implementation). Now one file owns the invariant; deleting it
7
+ * would scatter complexity (deep).
8
8
  *
9
- * Private helpers inlined from file-reader (normFromText/fileSnap),
10
- * read-render (fmtReadPreview), truncate (truncateHead), file-kind
11
- * (loadFileKindAndText), validation (valKind/valAccess).
12
- * Old files are shims re-exporting from this seam for compat.
9
+ * Private helpers inlined from the retired reader, renderer and truncate
10
+ * modules: normFromText/fileSnap, fmtReadPreview, truncateHead.
13
11
  *
14
12
  * Two surfaces:
15
- * - `preview` (pure, no IO) — tested without filesystem
13
+ * - `fmtReadPreview` (pure, no IO) — tested without filesystem
16
14
  * - `readView` (IO) — read + normalize + render + truncate + hashes
17
15
  *
18
16
  * @module dsh-better-edit/file-view
19
17
  */
20
- import { constants } from "node:fs";
21
- import { open as fsOpen, stat as fsStat } from "fs/promises";
22
- import { access as fsAccess } from "fs/promises";
23
- import { fileTypeFromBuffer } from "file-type";
24
- import { SNIFF_BYTES, MAX_BYTES, MAX_READ_LINE_BYTES, eLargeFileMsg } from "./constants.js";
18
+ import { stat as fsStat } from "fs/promises";
19
+ import { MAX_READ_LINE_BYTES, eLargeFileMsg } from "./constants.js";
25
20
  import { lineHashes, fmtRegion, HASH_SEP } from "./hashline/index.js";
26
21
  import { HASH_SPACE } from "./hashline/hash-assign.js";
27
- import { visLines, abortIf, errCode } from "./utils.js";
22
+ import { visLines, abortIf } from "./utils.js";
28
23
  import { DomainError } from "./domain-errors.js";
29
24
  import { detectEnding, toLF, stripBOM } from "./edit-diff.js";
30
- import { resolveTarget, toCwd } from "./paths.js";
25
+ import { resolveTarget } from "./paths.js";
31
26
  export const MAX_HASH_LINES = HASH_SPACE;
32
27
  export const DEFAULT_MAX_LINES = 2000;
33
28
  export const DEFAULT_MAX_BYTES = 50 * 1024;
@@ -119,158 +114,6 @@ export function truncateHead(content, options = {}) {
119
114
  maxBytes,
120
115
  };
121
116
  }
122
- // --- File kind (from file-kind.ts, private) ---
123
- const IMG_TYPES = new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]);
124
- const TEXT_TYPES = new Set([
125
- "application/rtf",
126
- "application/xml",
127
- "application/x-ms-regedit",
128
- ]);
129
- function detectTextBom(sample) {
130
- if (sample.length >= 4 &&
131
- sample[0] === 0xff &&
132
- sample[1] === 0xfe &&
133
- sample[2] === 0x00 &&
134
- sample[3] === 0x00)
135
- return "UTF-32LE";
136
- if (sample.length >= 4 &&
137
- sample[0] === 0x00 &&
138
- sample[1] === 0x00 &&
139
- sample[2] === 0xfe &&
140
- sample[3] === 0xff)
141
- return "UTF-32BE";
142
- if (sample.length >= 2 && sample[0] === 0xff && sample[1] === 0xfe)
143
- return "UTF-16LE";
144
- if (sample.length >= 2 && sample[0] === 0xfe && sample[1] === 0xff)
145
- return "UTF-16BE";
146
- return undefined;
147
- }
148
- function isTextType(mimeType) {
149
- return mimeType.startsWith("text/") || TEXT_TYPES.has(mimeType);
150
- }
151
- export async function loadFileKindAndText(filePath, options) {
152
- const pathStat = await fsStat(filePath);
153
- if (pathStat.isDirectory()) {
154
- return { kind: "directory" };
155
- }
156
- if (!pathStat.isFile()) {
157
- return {
158
- kind: "binary",
159
- description: "unsupported file type",
160
- };
161
- }
162
- if (pathStat.size > MAX_BYTES) {
163
- return {
164
- kind: "binary",
165
- description: `file exceeds ${MAX_BYTES} byte limit`,
166
- };
167
- }
168
- const fileHandle = await fsOpen(filePath, "r");
169
- try {
170
- const buffer = Buffer.alloc(SNIFF_BYTES);
171
- const { bytesRead } = await fileHandle.read(buffer, 0, SNIFF_BYTES, 0);
172
- if (bytesRead === 0) {
173
- return { kind: "text", text: "", stats: pathStat };
174
- }
175
- const sample = buffer.subarray(0, bytesRead);
176
- const textBom = detectTextBom(sample);
177
- if (textBom) {
178
- return {
179
- kind: "binary",
180
- description: `${textBom} encoded text`,
181
- };
182
- }
183
- const detectedMimeType = (await fileTypeFromBuffer(sample))?.mime;
184
- if (detectedMimeType !== undefined && !isTextType(detectedMimeType)) {
185
- if (IMG_TYPES.has(detectedMimeType)) {
186
- return { kind: "image", mimeType: detectedMimeType };
187
- }
188
- return {
189
- kind: "binary",
190
- description: detectedMimeType,
191
- };
192
- }
193
- const decoder = new TextDecoder("utf-8", { fatal: false, ignoreBOM: true });
194
- let hadUtf8DecodeErrors = false;
195
- let newlineCount = 0;
196
- const parts = [];
197
- function decodeChunk(chunk, stream) {
198
- const decoded = decoder.decode(chunk, { stream });
199
- if (!hadUtf8DecodeErrors && decoded.includes("\uFFFD")) {
200
- hadUtf8DecodeErrors = true;
201
- }
202
- if (options?.maxLines !== undefined) {
203
- for (let i = 0; i < decoded.length; i++) {
204
- if (decoded.charCodeAt(i) === 10)
205
- newlineCount++;
206
- }
207
- if (newlineCount > options.maxLines) {
208
- throw new Error(eLargeFileMsg(options.displayPath ?? filePath, newlineCount, options.maxLines));
209
- }
210
- }
211
- return decoded;
212
- }
213
- parts.push(decodeChunk(sample, true));
214
- let position = bytesRead;
215
- while (true) {
216
- const { bytesRead: chunkBytesRead } = await fileHandle.read(buffer, 0, SNIFF_BYTES, position);
217
- if (chunkBytesRead === 0) {
218
- break;
219
- }
220
- const chunk = buffer.subarray(0, chunkBytesRead);
221
- parts.push(decodeChunk(chunk, true));
222
- position += chunkBytesRead;
223
- }
224
- parts.push(decodeChunk(new Uint8Array(0), false));
225
- return {
226
- kind: "text",
227
- text: parts.join(""),
228
- stats: pathStat,
229
- ...(hadUtf8DecodeErrors ? { hadUtf8DecodeErrors: true } : {}),
230
- };
231
- }
232
- finally {
233
- await fileHandle.close();
234
- }
235
- }
236
- // --- Validation (from validation.ts, private) ---
237
- export async function valAccess(absolutePath, path, accessMode = constants.R_OK) {
238
- try {
239
- await fsAccess(absolutePath, accessMode);
240
- }
241
- catch (error) {
242
- const code = errCode(error);
243
- if (code === "ENOENT") {
244
- throw new DomainError("E_NOT_FOUND", { path });
245
- }
246
- if (code === "EACCES" || code === "EPERM") {
247
- throw new DomainError("E_ACCESS", {
248
- path,
249
- kind: "denied",
250
- access: accessMode & constants.W_OK ? "write" : "read",
251
- });
252
- }
253
- if (code === "ELOOP") {
254
- throw new DomainError("E_ACCESS", { path, kind: "symlink-loop" });
255
- }
256
- throw new DomainError("E_ACCESS", { path, kind: "unreachable" });
257
- }
258
- }
259
- export function valKind(file, path) {
260
- if (file.kind === "directory") {
261
- throw new DomainError("E_UNSUPPORTED_FILE", { path, kind: "directory" });
262
- }
263
- if (file.kind === "binary") {
264
- throw new DomainError("E_UNSUPPORTED_FILE", {
265
- path,
266
- kind: "binary",
267
- description: file.description,
268
- });
269
- }
270
- if (file.kind === "image") {
271
- throw new DomainError("E_UNSUPPORTED_FILE", { path, kind: "image" });
272
- }
273
- }
274
117
  function fmtSnapId(canonicalPath, info) {
275
118
  return `v2|${canonicalPath}|${info.ino}|${info.mtimeMs}|${info.ctimeMs}|${info.size}`;
276
119
  }
@@ -313,35 +156,7 @@ export async function normFromText(input) {
313
156
  hadUtf8DecodeErrors: input.hadUtf8DecodeErrors === true,
314
157
  };
315
158
  }
316
- export async function readNormFile(path, cwd, options) {
317
- const absolutePath = toCwd(path, cwd);
318
- const resolvedPath = await resolveTarget(absolutePath);
319
- const signal = options?.signal;
320
- const accessMode = options?.accessMode ?? constants.R_OK;
321
- abortIf(signal);
322
- await valAccess(resolvedPath, path, accessMode);
323
- abortIf(signal);
324
- const file = options?.preloadedFile ??
325
- (await loadFileKindAndText(resolvedPath, {
326
- maxLines: options?.maxLines,
327
- displayPath: path,
328
- }));
329
- valKind(file, path);
330
- return normFromText({
331
- absolutePath: resolvedPath,
332
- rawText: file.text,
333
- displayPath: path,
334
- signal,
335
- maxLines: options?.maxLines,
336
- store: options?.store,
337
- noPersist: options?.noPersist,
338
- reservedHashes: options?.reservedHashes,
339
- retiredHashes: options?.retiredHashes,
340
- hadUtf8DecodeErrors: file.hadUtf8DecodeErrors,
341
- previous: options?.previous,
342
- });
343
- }
344
- // --- Read render (from read-render.ts, private) ---
159
+ // --- Read render (private to this seam) ---
345
160
  function normPosInt(value, name) {
346
161
  if (value === undefined)
347
162
  return undefined;
@@ -569,12 +384,16 @@ function buildWindowSection(params) {
569
384
  * runs first appear in the request — that order is part of the request, so it is never sorted by
570
385
  * position — while every section draws on ONE shared byte/line budget so N windows cannot multiply
571
386
  * the auto-read budget by N. Rows are served only for the lines actually shown; because each
572
- * position belongs to exactly one run, the position record is injective by construction.
387
+ * position belongs to exactly one run, the union's position record is injective by construction.
388
+ * The record is SORTED by position but never de-duplicated: the sort is load-bearing (runs render
389
+ * in request order, so run order is not position order), yet a collector that dropped duplicates
390
+ * would mask a `mergeWindowRuns` regression — overlapping runs would collapse into one served row
391
+ * instead of surfacing as two for the same position.
573
392
  */
574
393
  function buildWindowedPreview(params) {
575
394
  const { windows, allLines, allHashes, totalLines, maxBytes, maxTruncLines } = params;
576
395
  const sections = [];
577
- const hashByPosition = new Map();
396
+ const servedRows = [];
578
397
  let truncation;
579
398
  let remainingBytes = maxBytes;
580
399
  let remainingLines = maxTruncLines;
@@ -614,7 +433,7 @@ function buildWindowedPreview(params) {
614
433
  });
615
434
  sections.push(`${header}\n${built.text}`);
616
435
  for (const row of built.served)
617
- hashByPosition.set(row.position, row.hash);
436
+ servedRows.push(row);
618
437
  remainingLines -= built.text === "" ? 0 : built.text.split("\n").length;
619
438
  remainingBytes -= Buffer.byteLength(`${built.text}${header}`, "utf-8");
620
439
  if (truncation === undefined && built.truncation)
@@ -626,9 +445,7 @@ function buildWindowedPreview(params) {
626
445
  // WHY: a multi-window request is N discrete slices, not one stream, so the result carries no root
627
446
  // WHY: `nextOffset`: a scalar would invite `offset = nextOffset` and silently re-read a window the
628
447
  // WHY: caller never asked to continue. A truncated window says so in its own section text.
629
- served: [...hashByPosition.entries()]
630
- .sort((left, right) => left[0] - right[0])
631
- .map(([position, hash]) => ({ position, hash })),
448
+ served: [...servedRows].sort((left, right) => left.position - right.position),
632
449
  };
633
450
  }
634
451
  export async function fmtReadPreview(text, options, precomputedHashes, path, maxLineBytes = MAX_READ_LINE_BYTES, maxTruncLines = DEFAULT_MAX_LINES) {
@@ -709,9 +526,6 @@ export async function fmtReadPreview(text, options, precomputedHashes, path, max
709
526
  served: normal.served,
710
527
  };
711
528
  }
712
- export async function preview(content, hashes, opts = {}, absolutePath) {
713
- return fmtReadPreview(content, opts, hashes, absolutePath);
714
- }
715
529
  export async function readView(io, path, cwd, opts = {}) {
716
530
  const { signal } = opts;
717
531
  const absolutePath = await io.resolve(path, cwd, signal);
@@ -727,6 +541,12 @@ export async function readView(io, path, cwd, opts = {}) {
727
541
  previous: opts.previous,
728
542
  });
729
543
  const r = await fmtReadPreview(normalized, { offset: opts.offset, limit: opts.limit, windows: opts.windows }, fileHashes, absolutePath);
544
+ // The ONE computation of the full-read verdict (ADR-0035): the whole file, no page request, and
545
+ // nothing truncated away. Consumers read `view.fullRead`; none of them re-derives it.
546
+ const fullRead = opts.offset === undefined &&
547
+ opts.limit === undefined &&
548
+ !hasRequestedWindows(opts.windows) &&
549
+ !r.truncation?.truncated;
730
550
  return {
731
551
  text: r.text,
732
552
  hashes: fileHashes,
@@ -734,6 +554,7 @@ export async function readView(io, path, cwd, opts = {}) {
734
554
  absolutePath,
735
555
  truncation: r.truncation,
736
556
  nextOffset: r.nextOffset,
557
+ fullRead,
737
558
  hadUtf8DecodeErrors,
738
559
  bom,
739
560
  originalEnding,