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
package/lib/tool-undo.js CHANGED
@@ -11,36 +11,36 @@ import { DomainError, formatError } from "./domain-errors.js";
11
11
  import { assertUndoRequest } from "./contract.js";
12
12
  import { normalizeRequest as normReq } from "./contract.js";
13
13
  import { loadHashStore, withStore } from "./hash-store.js";
14
- import { AnchorSpaceExhaustedError, HASH_SPACE, canon, contentChecksum, } from "./hashline/hash-assign.js";
14
+ import { HASH_SPACE, canon, contentChecksum, isPromotableAnchorSpaceExhaustion, } from "./hashline/hash-assign.js";
15
15
  import { lineHashes } from "./hashline/hash.js";
16
16
  import { changedRange } from "./hashline/anchor-pipeline.js";
17
17
  import { getUndo, clearUndo } from "./undo-edit.js";
18
- import { loadAnchorReservations, loadServedStore, recordServedTruncated, retireAnchorsInStore, } from "./session-view.js";
18
+ import { loadAnchorReservations, loadServedStore, recordServedTruncated, retireAnchorsInStore, unretireAnchorsInStore, } from "./session-view.js";
19
19
  import { UNDO_DESCRIPTION } from "./prompts.js";
20
20
  import { execCwd, execSessionKey } from "./workspace-context.js";
21
21
  import { withWorkspace } from "./workspace-context.js";
22
- function isAnchorSpaceExhausted(e) {
23
- return (e instanceof AnchorSpaceExhaustedError ||
24
- (e instanceof Error && e.message.includes("probing failed over")));
25
- }
22
+ import { encodingHintAtVersion, getEncodingState, prepareForSave } from "./file-encoding-state.js";
23
+ import { loadConfig } from "./store-config.js";
26
24
  /**
27
25
  * Anchor-space exhaustion guard mirrored from the edit path (`retryLineHashesWithPromotion` in
28
26
  * src/mutation/engine.ts): clear this (session, path)'s retired anchors once to promote hash space
29
27
  * and retry; a retry that still exhausts is a typed hard capacity refusal, never a raw probe error.
28
+ * The exhaustion test itself is shared (`isPromotableAnchorSpaceExhaustion`) — see its docblock
29
+ * for why promotion's question is narrower than "is this exhaustion".
30
30
  */
31
31
  async function hashWithAnchorSpacePromotion(fn, onPromote) {
32
32
  try {
33
33
  return await fn();
34
34
  }
35
35
  catch (error) {
36
- if (!isAnchorSpaceExhausted(error))
36
+ if (!isPromotableAnchorSpaceExhaustion(error))
37
37
  throw error;
38
38
  await onPromote();
39
39
  try {
40
40
  return await fn();
41
41
  }
42
42
  catch (retryError) {
43
- if (isAnchorSpaceExhausted(retryError))
43
+ if (isPromotableAnchorSpaceExhaustion(retryError))
44
44
  throw new DomainError("E_LARGE_FILE", { limitKind: "hash-space", limit: HASH_SPACE });
45
45
  throw retryError;
46
46
  }
@@ -86,7 +86,12 @@ export function buildUndoTool(io, sandbox) {
86
86
  }
87
87
  let currentRaw;
88
88
  try {
89
- currentRaw = await io.readText(absolutePath, signal);
89
+ // Issue #112: the staleness read consumes the encoding recorded by the preceding
90
+ // read, so a file admitted by read({ encoding }) compares as decoded text instead
91
+ // of mojibake (which would misreport a false E_UNDO_STALE "modified").
92
+ const currentVersion = await io.statVersion(absolutePath, signal);
93
+ const encodingHint = encodingHintAtVersion(absolutePath, currentVersion);
94
+ currentRaw = await io.readText(absolutePath, signal, encodingHint);
90
95
  }
91
96
  catch (error) {
92
97
  if (codeOf(error) === "E_NOT_FOUND") {
@@ -129,12 +134,13 @@ export function buildUndoTool(io, sandbox) {
129
134
  reservedHashes = served;
130
135
  };
131
136
  const currentHashes = await hashWithAnchorSpacePromotion(() => lineHashes(currentNormalized, absolutePath, undefined, undefined, false, reservedHashes, retiredHashes), promoteRetiredForAnchorSpace);
132
- const retiredOriginalHashes = new Set(undo.hashes.filter((hash) => retiredHashes.has(hash)));
133
- const restoredHashes = await hashWithAnchorSpacePromotion(() => lineHashes(undo.content, absolutePath, {
134
- content: undo.content,
135
- hashes: undo.hashes,
136
- removedHashes: retiredOriginalHashes,
137
- }, undefined, false, new Set([...reservedHashes, ...currentHashes]), retiredHashes), promoteRetiredForAnchorSpace);
137
+ // Restore the pre-edit assignment verbatim (ADR-0017 reversal): `undo.hashes` are
138
+ // the anchors the restored content carried before the edit, and `undo.content` is
139
+ // byte-identical to the content they were assigned to. The edit retired them; that
140
+ // retirement is reversed with the restore below, so the pass no longer lists them
141
+ // as removed. What still blocks reuse is the superseded post-edit assignment
142
+ // (`currentHashes`, live on the file right now) plus this session's reserved set.
143
+ const restoredHashes = await hashWithAnchorSpacePromotion(() => lineHashes(undo.content, absolutePath, { content: undo.content, hashes: undo.hashes }, undefined, false, new Set([...reservedHashes, ...currentHashes]), retiredHashes), promoteRetiredForAnchorSpace);
138
144
  // WHY: #96 (pi-better-edit@665a05d, upstream #173) — the summary counts come from the
139
145
  // WHY: source line multisets, never from the rendered projection: a deleted run past
140
146
  // WHY: DIFF_REMOVED_CAP collapses behind a marker row at context 0, so counting `-` rows
@@ -164,12 +170,29 @@ export function buildUndoTool(io, sandbox) {
164
170
  }
165
171
  const restoredRange = changedRange(currentNormalized, undo.content);
166
172
  const restoredSet = new Set(restoredHashes);
173
+ // Retirement moves with the restore: the anchors the edit retired for lines that come
174
+ // back byte-identically are revived in the same unit that retires the superseded
175
+ // post-edit assignment. An anchor whose line does not come back stays retired, and no
176
+ // anchor is rebound to different content — the restore is byte-identical or refused.
177
+ const revivedByUndo = [...restoredSet].filter((hash) => retiredHashes.has(hash));
167
178
  // WHY (#98, port of upstream CAND-3): retirement waits for the write. Committing it
168
179
  // before `writeText` let a failed revert leave anchors retired for a file that still
169
180
  // holds them — a torn store state with no later read likely to notice.
170
181
  const retiredByUndo = currentHashes.filter((hash) => !restoredSet.has(hash));
182
+ // The revert goes through the same save seam as every other write, so an
183
+ // encoding that cannot round-trip refuses BEFORE any write (#112).
184
+ const recorded = getEncodingState(absolutePath) ?? {
185
+ encoding: undo.bom ? "utf8bom" : "utf8",
186
+ hasBOM: undo.bom !== "",
187
+ lineEnding: undo.originalEnding,
188
+ version: undefined,
189
+ };
190
+ const prepared = prepareForSave(undo.content, recorded, {
191
+ normalizeToUtf8: loadConfig().normalizeToUtf8,
192
+ displayPath: path,
193
+ });
171
194
  try {
172
- await io.writeText(absolutePath, undo.bom + restoreEndings(undo.content, undo.originalEnding), signal, exec, sandboxPolicy);
195
+ await io.writeText(absolutePath, prepared.textToWrite, signal, exec, sandboxPolicy);
173
196
  }
174
197
  catch (error) {
175
198
  throw sandbox.mapError(error, sandboxPolicy);
@@ -189,6 +212,7 @@ export function buildUndoTool(io, sandbox) {
189
212
  withStore(() => {
190
213
  store.upsertSnapshot(absolutePath, contentChecksum(undo.content), splitLines(undo.content).length, restoredHashes, undo.content);
191
214
  retireAnchorsInStore(store, sessionKey, absolutePath, retiredByUndo);
215
+ unretireAnchorsInStore(store, sessionKey, absolutePath, revivedByUndo);
192
216
  store.deleteUndoPair(absolutePath);
193
217
  });
194
218
  }
@@ -209,16 +233,10 @@ export function buildUndoTool(io, sandbox) {
209
233
  serveLanded = await recordServedTruncated(sessionKey, absolutePath, undoDenseRows, splitLines(undo.content).length, restoredRange?.firstChangedLine ?? undoDiffResult.firstChangedLine ?? 0, splitLines(undo.content).map((l) => canon(l)), { content: undo.content, hashes: restoredHashes });
210
234
  }
211
235
  parts.push(serveLanded
212
- ? "File reverted to previous state. The post-edit diff rows carry the restored file\u2019s fresh anchors for follow-up edits."
213
- : "File reverted to previous state. WARNING: the restored file\u2019s fresh anchors were NOT recorded as served — the diff rows below are NOT usable anchors and no edit can be based on them. Re-read the file before editing it.");
236
+ ? "File reverted to previous state. The post-edit diff rows carry the restored file\u2019s original anchors for follow-up edits."
237
+ : "File reverted to previous state. WARNING: the restored file\u2019s original anchors were NOT recorded as served — the diff rows below are NOT usable anchors and no edit can be based on them. Re-read the file before editing it.");
214
238
  return [parts.join("\n"), "", "Diff of the revert:", "", undoDiff].join("\n");
215
239
  });
216
240
  },
217
241
  });
218
242
  }
219
- /**
220
- * Register the hashline tool on the calling agent’s scope (own layer).
221
- */
222
- export function registerUndoTool(_rootCtx, agentCtx, io, sandbox) {
223
- return agentCtx.tools.register(buildUndoTool(io, sandbox));
224
- }
@@ -4,19 +4,20 @@
4
4
  * declared once here; every tool validates through these asserts, and the
5
5
  * E_BAD_PAYLOAD vocabulary is shared instead of re-implemented per tool.
6
6
  *
7
- * Contract mirrors upstream ADR-0015: {file: string|null, edits: [{anchor_from, anchor_to, replace_with},...]} named-object payload
7
+ * Contract mirrors upstream ADR-0015: {file: string, edits: [{anchor_from, anchor_to, replace_with},...]} named-object payload
8
8
  * (plus legacy tuple items and legacy key spellings folded pre-validation), single-file, atomic. batch_edit is removed.
9
9
  * @module dsh-better-edit/contract
10
10
  */
11
11
  import type { ReadWindow } from "./file-view.js";
12
- export type EditMode = "general" | "literal";
12
+ import type { EditMode } from "./edit-mode.js";
13
+ export type { EditMode };
13
14
  export type EditItem = {
14
15
  anchor_from: string;
15
16
  anchor_to: string;
16
17
  replace_with: string;
17
18
  };
18
19
  export type EditRequest = {
19
- file: string | null;
20
+ file: string;
20
21
  edits: EditItem[];
21
22
  /**
22
23
  * "general" (default) refuses bytes reproducing served rows;
@@ -89,17 +90,12 @@ export declare const anchorToSchema: {
89
90
  };
90
91
  export declare const pathSchema: {
91
92
  readonly type: "string";
92
- readonly description: "File path; null infers it from anchors";
93
+ readonly description: "File path";
93
94
  };
94
95
  export declare const editPathSchema: {
95
- readonly anyOf: readonly [{
96
- readonly type: "string";
97
- readonly minLength: 1;
98
- readonly description: "File path; null infers it from anchors";
99
- }, {
100
- readonly type: "null";
101
- readonly description: "null infers path from anchors";
102
- }];
96
+ readonly type: "string";
97
+ readonly minLength: 1;
98
+ readonly description: "Text file to edit (a file, never a directory)";
103
99
  };
104
100
  export declare const editTupleSchema: {
105
101
  readonly type: "array";
@@ -181,14 +177,9 @@ export declare const editToolSchema: {
181
177
  readonly required: readonly ["file", "edits"];
182
178
  readonly properties: {
183
179
  readonly file: {
184
- readonly anyOf: readonly [{
185
- readonly type: "string";
186
- readonly minLength: 1;
187
- readonly description: "File path; null infers it from anchors";
188
- }, {
189
- readonly type: "null";
190
- readonly description: "null infers path from anchors";
191
- }];
180
+ readonly type: "string";
181
+ readonly minLength: 1;
182
+ readonly description: "Text file to edit (a file, never a directory)";
192
183
  };
193
184
  readonly edits: {
194
185
  readonly type: "array";
@@ -66,7 +66,7 @@ export interface ServedRow {
66
66
  }
67
67
  /** WHY: user-facing diagnosis carried as `details.cause` on range-family rejections. */
68
68
  export type RangeCause = "retirement" | "never-served" | "served-range staleness" | "anchor staleness" | "served span";
69
- export type DomainErrorCode = "E_BAD_PAYLOAD" | "E_EMPTY_RANGE" | "E_STALE_ANCHOR" | "E_UNKNOWN_ANCHOR" | "E_FOREIGN_ANCHOR" | "E_STALE_RANGE" | "E_TARGET_LOST" | "E_UNVERIFIED_RANGE" | "E_MALFORMED_ANCHOR" | "E_SUSPICIOUS_TEXT" | "E_BATCH_ABORT" | "E_NOOP_LOOP" | "E_UNSUPPORTED_FILE" | "E_ACCESS" | "E_NOT_FOUND" | "E_UNDO_STALE" | "E_UNDO_UNAVAILABLE" | "E_UNDO_NOT_RECORDED" | "E_UNKNOWN" | "E_LARGE_FILE" | "E_UNSERVED_RANGE" | "E_BLIND_REPLACE" | "E_UNSUPPORTED" | "E_BAD_COMMAND" | "E_FILE_EXISTS" | "E_NO_MATCH" | "E_AMBIGUOUS_MATCH" | "E_STORE_NEWER_VERSION";
69
+ export type DomainErrorCode = "E_BAD_PAYLOAD" | "E_EMPTY_RANGE" | "E_STALE_ANCHOR" | "E_UNKNOWN_ANCHOR" | "E_FOREIGN_ANCHOR" | "E_STALE_RANGE" | "E_TARGET_LOST" | "E_UNVERIFIED_RANGE" | "E_MALFORMED_ANCHOR" | "E_SUSPICIOUS_TEXT" | "E_BATCH_ABORT" | "E_NOOP_LOOP" | "E_UNSUPPORTED_FILE" | "E_ENCODING_UNWRITABLE" | "E_ACCESS" | "E_NOT_FOUND" | "E_UNDO_STALE" | "E_UNDO_UNAVAILABLE" | "E_UNDO_NOT_RECORDED" | "E_UNKNOWN" | "E_LARGE_FILE" | "E_UNSERVED_RANGE" | "E_BLIND_REPLACE" | "E_UNSUPPORTED" | "E_BAD_COMMAND" | "E_FILE_EXISTS" | "E_NO_MATCH" | "E_AMBIGUOUS_MATCH" | "E_STORE_NEWER_VERSION";
70
70
  /**
71
71
  * Applied-tier warning codes. A `[W_*]` line reports an applied mutation;
72
72
  * `[E_*]` reports a rejection. `formatWarning` is the sole producer of
@@ -166,17 +166,17 @@ export interface ErrorPayloadMap {
166
166
  count: number;
167
167
  batch: boolean;
168
168
  servedBlock: string;
169
- /**
170
- * Present on engine single rejects: the display path ("in <path>" flavor).
171
- * The batch ref already names the item, so no index is needed.
172
- */
173
- path?: string;
174
169
  };
175
170
  E_UNSUPPORTED_FILE: {
176
171
  path: string;
177
172
  kind: "directory" | "binary" | "image";
178
173
  description?: string;
179
174
  };
175
+ E_ENCODING_UNWRITABLE: {
176
+ path: string;
177
+ /** The encoding recorded when the file was read. */
178
+ encoding: string;
179
+ };
180
180
  E_ACCESS: {
181
181
  path: string;
182
182
  kind: "denied" | "symlink-loop" | "unreachable";
@@ -377,10 +377,14 @@ export declare const DECLARATION_ONLY_FIELDS: Readonly<Record<string, AllowlistE
377
377
  *
378
378
  * | ported upstream diagnostic | upstream producer (pi-better-edit@b92e0ec) | local producer |
379
379
  * |---|---|---|
380
- * | `E_FOREIGN_ANCHOR` | `lease-resolve.ts:116` | `anchor-pipeline.ts` (`throwUnknownOrForeign`, boundary placement) |
381
- * | `E_UNKNOWN_ANCHOR` | `lease-resolve.ts:118`, `served-verification.ts:745` | `anchor-pipeline.ts` (boundary placement, pre-gate) |
382
- * | `E_UNVERIFIED_RANGE` | `lease-resolve.ts:186`, `served-verification.ts:187` | `anchor-pipeline.ts` (pre-gate stale-boundary arm) |
383
- * | `E_TARGET_LOST` | `served-verification.ts:170`, `lease-resolve.ts:196` | `anchor-pipeline.ts` (pre-gate stale-boundary arm) |
380
+ * | `E_FOREIGN_ANCHOR` | `lease-resolve.ts:116` | `served-evidence.ts` (`throwUnknownOrForeign`, boundary placement) |
381
+ * | `E_UNKNOWN_ANCHOR` | `lease-resolve.ts:118`, `served-verification.ts:745` | `served-evidence.ts` (boundary placement, pre-gate) |
382
+ * | `E_UNVERIFIED_RANGE` | `lease-resolve.ts:186`, `served-verification.ts:187` | `served-evidence.ts` (pre-gate stale-boundary arm) |
383
+ * | `E_TARGET_LOST` | `served-verification.ts:170`, `lease-resolve.ts:196` | `served-evidence.ts` (pre-gate stale-boundary arm) |
384
+ *
385
+ * The upstream column is scoped to the upstream tree (`pi-better-edit@b92e0ec`): its
386
+ * `served-verification.ts` never existed downstream, so those cites never named a local
387
+ * file. The local column did move — the four arms live in `served-evidence.ts` (ADR-0037).
384
388
  *
385
389
  * Their owner is `"upstream absorb"` and their trigger is the absorb that
386
390
  * ports the corresponding producer. When that happens, reintroduce the code
@@ -0,0 +1,11 @@
1
+ /**
2
+ * EditMode — the one member of the request contract the write pipeline names.
3
+ *
4
+ * WHY a module of its own (ADR-0037): `EditMode` is the only edge from
5
+ * anchor-pipeline back into contract.ts, and contract.ts reaches the read side
6
+ * through `ReadWindow`. Left there, the type re-closed the import ring; as a leaf
7
+ * it closes nothing — both ends import this file and never each other.
8
+ *
9
+ * @module dsh-better-edit/edit-mode
10
+ */
11
+ export type EditMode = "general" | "literal";
@@ -5,6 +5,7 @@
5
5
  */
6
6
  export declare const SUPPORTED_ENCODINGS: readonly ["gbk", "big5", "shift_jis", "euc-kr", "windows-1251", "iso-8859-1"];
7
7
  export type SupportedEncoding = (typeof SUPPORTED_ENCODINGS)[number];
8
+ export declare const SUPPORTED_ENCODINGS_LABEL: string;
8
9
  /** Canonicalize case-insensitive encoding param, strip -_ . */
9
10
  export declare function normalizeEncoding(input: string): string | undefined;
10
11
  export declare function isSupportedEncoding(enc: string): boolean;
@@ -16,20 +16,37 @@
16
16
  */
17
17
  import type { CandidatePreview } from "./encoding.js";
18
18
  import { type LineEnding } from "./edit-diff.js";
19
+ /**
20
+ * The decode hint a mutating re-read must pass to the byte seam: the encoding
21
+ * recorded by the preceding `read({ encoding })` — but only while the memo still
22
+ * matches the on-disk version, and only for encodings the plain read path cannot
23
+ * reproduce.
24
+ *
25
+ * `utf8` / `utf8bom` need no hint: BOM sniff + strict UTF-8 (and the bridge's
26
+ * stripped-BOM restore) already decode them to the text the anchors were served
27
+ * for, so asking for a byte reread would only cost an RPC. Everything else
28
+ * (utf16le, windows-1251, GBK, …) is invisible to the plain path — without the
29
+ * hint the mutation re-read decodes lossily or fails, which is the stale-anchor /
30
+ * unsupported-file symptom this hint removes (issue #112).
31
+ *
32
+ * A drifted memo is dropped first, so a changed file is re-detected instead of
33
+ * having the old encoding laundered onto its new bytes.
34
+ */
35
+ export declare function encodingHintAtVersion(filePath: string, currentVersion: string | undefined): string | undefined;
19
36
  export interface FileEncodingState {
20
37
  encoding: string;
21
38
  hasBOM: boolean;
22
39
  lineEnding?: LineEnding;
23
40
  version: string | undefined;
24
41
  }
25
- export declare function getEncodingState(targetKey: string): FileEncodingState | undefined;
26
- export declare function setEncodingState(targetKey: string, state: FileEncodingState): void;
27
- export declare function clearEncodingState(targetKey?: string): void;
28
- export declare function getAutoGuessFooter(targetKey: string): string | undefined;
29
- export declare function setAutoGuessFooter(targetKey: string, footer: string): void;
30
- export declare function clearAutoGuessFooter(targetKey?: string): void;
42
+ export declare function getEncodingState(filePath: string): FileEncodingState | undefined;
43
+ export declare function setEncodingState(filePath: string, state: FileEncodingState): void;
44
+ export declare function clearEncodingState(filePath?: string): void;
45
+ export declare function getAutoGuessFooter(filePath: string): string | undefined;
46
+ export declare function setAutoGuessFooter(filePath: string, footer: string): void;
47
+ export declare function clearAutoGuessFooter(filePath?: string): void;
31
48
  /** Invalidate memo when FsVersion drifted (ADR-0012). */
32
- export declare function invalidateIfStale(targetKey: string, currentVersion: string | undefined): void;
49
+ export declare function invalidateIfStale(filePath: string, currentVersion: string | undefined): void;
33
50
  export declare function buildTop3Description(candidates: CandidatePreview[]): string;
34
51
  export declare function buildTop3ErrorMessage(displayPath: string, candidates: CandidatePreview[]): string;
35
52
  export interface DecodeAdmissionConfig {
@@ -58,22 +75,42 @@ export interface DecodeForOpenOptions {
58
75
  * `autoGuessEncoding`, but Top-3 is always computed for the error/ footer.
59
76
  */
60
77
  export declare function decodeForOpen(bytes: Uint8Array, config: DecodeAdmissionConfig, opts?: DecodeForOpenOptions): Promise<DecodeForOpenResult>;
61
- export declare function recordOpenState(targetKey: string, text: string, encoding: string, hasBOM: boolean, version: string | undefined): FileEncodingState;
62
- export declare function recordFooter(targetKey: string, footer: string | undefined): void;
78
+ export declare function recordOpenState(filePath: string, text: string, encoding: string, hasBOM: boolean, version: string | undefined): FileEncodingState;
79
+ export declare function recordFooter(filePath: string, footer: string | undefined): void;
63
80
  export interface EncodeForSaveOptions {
64
81
  encodingHint?: string;
65
82
  normalizeToUtf8?: boolean;
66
83
  currentVersion?: string | undefined;
84
+ /** Model-facing path for the round-trip refusal. */
85
+ displayPath?: string;
67
86
  }
68
87
  /** Shared UTF-8 BOM marker — single source for the BOM round-trip seam.
69
88
  * Prefer `prepareForSave` / `stripBOM` over re-implementing this check. */
70
89
  export declare const UTF8_BOM = "\uFEFF";
71
90
  /**
72
- * Decide what bytes (as text, since provider expects string) to write and
73
- * what new state to record. BOM and lineEnding are restored here when a
74
- * previous state exists; otherwise defaults are UTF-8 without BOM and LF.
75
- * For legacy encodings with normalizeToUtf8:false, we preserve the memo
76
- * (provider will write UTF-8 string, next read re-detects via version bump).
91
+ * True when the text's UTF-8 byte image is byte-identical to its byte image
92
+ * under `encoding` — an ASCII-only file in a single-byte charset, where the
93
+ * text-only write seam reproduces the original bytes exactly. Checking bytes
94
+ * (not the encoding name) is what keeps that file editable.
95
+ *
96
+ * This is a property of the TEXT only. A recorded `hasBOM` is a property of the
97
+ * FILE and is checked separately at the call site: the legacy BOM bytes cannot be
98
+ * reproduced by a UTF-8 string write (a UTF-8 BOM is a different byte image).
99
+ */
100
+ export declare function isByteFaithfulAsUtf8(text: string, encoding: string): boolean;
101
+ /**
102
+ * Decide what bytes (as text, since the write seam takes a string) to write and
103
+ * what new state to record. BOM and lineEnding are restored here when a state
104
+ * exists; otherwise defaults are UTF-8 without BOM and LF.
105
+ *
106
+ * ROUND-TRIP VERDICT: the bridge's only write is `writeText(target, content:
107
+ * string, …)`, which every backend encodes as UTF-8. So the save side can
108
+ * restore BOM + line ending for the UTF-8 family, and can write a legacy file
109
+ * only when its UTF-8 byte image is identical (ASCII-only). Anything else
110
+ * throws `E_ENCODING_UNWRITABLE` BEFORE the write, because writing UTF-8 would
111
+ * silently transcode the file and leave the anchors describing other bytes.
112
+ * `normalizeToUtf8: true` is the explicit migration: write UTF-8 and record
113
+ * `utf8` so the next read agrees with the bytes.
77
114
  */
78
115
  export declare function prepareForSave(content: string, existingState: FileEncodingState | undefined, opts?: EncodeForSaveOptions): {
79
116
  textToWrite: string;
@@ -2,17 +2,15 @@
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
@@ -50,32 +48,6 @@ export interface FileStats {
50
48
  mtimeMs: number;
51
49
  ctimeMs: number;
52
50
  }
53
- export interface LFileText {
54
- kind: "text";
55
- text: string;
56
- stats?: FileStats;
57
- hadUtf8DecodeErrors?: true;
58
- }
59
- export type LFile = {
60
- kind: "directory";
61
- } | {
62
- kind: "image";
63
- mimeType: string;
64
- } | LFileText | {
65
- kind: "binary";
66
- description: string;
67
- };
68
- export interface LoadFileOptions {
69
- maxLines?: number;
70
- displayPath?: string;
71
- }
72
- export declare function loadFileKindAndText(filePath: string, options?: LoadFileOptions): Promise<LFile>;
73
- export declare function valAccess(absolutePath: string, path: string, accessMode?: number): Promise<void>;
74
- export declare function valKind(file: LFile, path: string): asserts file is {
75
- kind: "text";
76
- text: string;
77
- hadUtf8DecodeErrors?: true;
78
- };
79
51
  export interface NormFile {
80
52
  absolutePath: string;
81
53
  normalized: string;
@@ -92,21 +64,6 @@ export type SnapInfo = {
92
64
  size: number;
93
65
  };
94
66
  export declare function fileSnap(absolutePath: string, preloadedStats?: FileStats): Promise<SnapInfo>;
95
- export interface ReadNormOptions {
96
- signal?: AbortSignal;
97
- accessMode?: number;
98
- preloadedFile?: LFile;
99
- maxLines?: number;
100
- store?: HashStore;
101
- noPersist?: boolean;
102
- reservedHashes?: ReadonlySet<string>;
103
- retiredHashes?: ReadonlySet<string>;
104
- previous?: {
105
- content: string;
106
- hashes: string[];
107
- removedHashes?: Set<string>;
108
- };
109
- }
110
67
  export declare function normFromText(input: {
111
68
  absolutePath: string;
112
69
  rawText: string;
@@ -124,7 +81,6 @@ export declare function normFromText(input: {
124
81
  removedHashes?: Set<string>;
125
82
  };
126
83
  }): Promise<NormFile>;
127
- export declare function readNormFile(path: string, cwd: string, options?: ReadNormOptions): Promise<NormFile>;
128
84
  /** One requested line range of a multi-window read (FU-6, port of pi-better-edit@2334352). */
129
85
  export interface ReadWindow {
130
86
  offset: number;
@@ -159,6 +115,18 @@ export interface FileView {
159
115
  absolutePath: string;
160
116
  truncation?: TruncationResult;
161
117
  nextOffset?: number;
118
+ /**
119
+ * The full-read verdict — computed HERE and nowhere else (ADR-0035).
120
+ *
121
+ * True only for an untruncated whole-file read: no `offset`, no `limit` and no requested windows
122
+ * (`undefined`/`[]` both mean none, per `hasRequestedWindows`), and nothing cut by the render.
123
+ * A page that happens to cover every line is still a page.
124
+ *
125
+ * WHY here: the request shape lives in this seam — the consumers of the verdict (session-view's
126
+ * `recordServed`, read-and-serve's drift clear) see only rows, and any verdict re-derived from
127
+ * rows says "full" for a page whose rows turn out dense.
128
+ */
129
+ fullRead: boolean;
162
130
  hadUtf8DecodeErrors: boolean;
163
131
  bom: string;
164
132
  originalEnding: LineEnding;
@@ -181,10 +149,4 @@ export interface ReadViewOpts extends PreviewOpts {
181
149
  removedHashes?: Set<string>;
182
150
  };
183
151
  }
184
- export declare function preview(content: string, hashes: string[], opts?: PreviewOpts, absolutePath?: string): Promise<{
185
- text: string;
186
- served: ServedRow[];
187
- truncation?: TruncationResult;
188
- nextOffset?: number;
189
- }>;
190
152
  export declare function readView(io: FileIO, path: string, cwd: string, opts?: ReadViewOpts): Promise<FileView>;
@@ -57,7 +57,6 @@ export interface FileIO {
57
57
  * @returns the mapped error, rethrown.
58
58
  */
59
59
  export declare function mapFsError(error: unknown, displayPath: string): never;
60
- /** FileIO over the deployment's `ctx.fs` service. */
61
60
  export declare function ctxFsIO(fs: FileSystem, ctx: Context): FileIO;
62
61
  /** FileIO over the host filesystem directly (tests, previews, fallback). */
63
62
  export declare function localIO(): FileIO;