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
@@ -9,8 +9,8 @@
9
9
  *
10
10
  * Public surface: _mergeServedRows, loadServed, recordServed,
11
11
  * recordServedTruncated, driftReported, markDriftReported,
12
- * clearDriftReported, wipeServedState, servedPositionsOf,
13
- * currentPositionOfDrifted, computeDrift, scanDrift, and
12
+ * clearDriftReported, wipeServedState, servedPositionsOf (re-exported from
13
+ * hashline/served-evidence), currentPositionOfDrifted, computeDrift, scanDrift, and
14
14
  * hash-store persistence delegation (ServedPersistence).
15
15
  *
16
16
  * Ownership: This file OWNS the served-merge invariant
@@ -23,10 +23,13 @@
23
23
  * @module dsh-better-edit/session-view
24
24
  */
25
25
  import { ALPH, HASH_LEN, HASH_SPACE, HASH_RE, canon } from "./hashline/hash-assign.js";
26
- import { loadHashStore, loadServedStore, withStore, DRIFT_EPISODE_PREFIX, DRIFT_EPISODE_RE, } from "./hash-store.js";
26
+ import { loadServedStore, withStore, DRIFT_EPISODE_PREFIX, DRIFT_EPISODE_RE, } from "./hash-store.js";
27
27
  import { SERVED_ECHO_CAP } from "./constants.js";
28
- import { fmtServedRows } from "./hashline/anchor-pipeline.js";
28
+ import { fmtServedRows, moreRowsHint, servedPositionsOf } from "./hashline/served-evidence.js";
29
29
  import { splitLines } from "./utils.js";
30
+ // Re-exported from the served-evidence leaf (ADR-0037): the scan is pure and the
31
+ // verifier needs it, so the seam that owns it is the evidence module.
32
+ export { servedPositionsOf };
30
33
  // --- hash-store re-export (persistence note) ---
31
34
  export { loadHashStore, loadServedStore, shutdownHashStore, withStore } from "./hash-store.js";
32
35
  /**
@@ -83,34 +86,32 @@ function addRetiredAnchors(store, sessionKey, path, hashes) {
83
86
  const additions = [...hashes];
84
87
  if (additions.length === 0)
85
88
  return;
86
- const retired = store.getRetiredAnchors(sessionKey, path);
89
+ // Contract first, dedupe second: an invalid hash is rejected whether or not it is new.
87
90
  for (const hash of additions) {
88
91
  if (!HASH_RE.test(hash)) {
89
92
  throw new TypeError(`Invalid retired hash: ${hash}`);
90
93
  }
91
- retired.add(hash);
92
94
  }
93
- // Persist as legacy string array for backward compat; new entries with deathPos use object form via addRetiredEntries
94
- store.upsertRetiredAnchors(sessionKey, path, JSON.stringify([...retired]));
95
- }
96
- function addRetiredEntries(store, sessionKey, path, entries) {
97
- if (entries.length === 0)
98
- return;
95
+ // WHY (ADR-0036): ONE writer, ONE serialization. `sweepAndRetire` and
96
+ // `unretireAnchorsInStore` read and write `RetiredEntry[]`; this appender is the third
97
+ // writer of the same column, so it must too — an appended entry carries `deathPos: null`
98
+ // (unknown position) while every existing entry keeps its own death position. Writing
99
+ // bare strings here rewrote the whole column into the shape `parseRetiredJson` coerces to
100
+ // `deathPos: null`, which no incremental sweep can free (accumulation until a full read).
101
+ // `store.getRetiredAnchors` stays the READ-side projection and is not used for writing.
99
102
  const existing = store.getRetiredEntries(sessionKey, path);
100
- const seen = new Set(existing.map((e) => e.hash));
101
- for (const e of entries) {
102
- if (!HASH_RE.test(e.hash))
103
- throw new TypeError(`Invalid retired hash: ${e.hash}`);
104
- if (!seen.has(e.hash)) {
105
- existing.push(e);
106
- seen.add(e.hash);
107
- }
103
+ const known = new Set(existing.map((entry) => entry.hash));
104
+ const appended = [];
105
+ for (const hash of additions) {
106
+ if (known.has(hash))
107
+ continue;
108
+ known.add(hash);
109
+ appended.push({ hash, deathPos: null });
108
110
  }
109
- store.upsertRetiredAnchors(sessionKey, path, JSON.stringify(existing));
110
- }
111
- function displacedHashes(current, updated) {
112
- const remaining = new Set(updated.filter((hash) => hash !== null));
113
- return new Set(current.filter((hash) => hash !== null && !remaining.has(hash)));
111
+ // Idempotent retirement must not bump the row.
112
+ if (appended.length === 0)
113
+ return;
114
+ store.upsertRetiredAnchors(sessionKey, path, JSON.stringify([...existing, ...appended]));
114
115
  }
115
116
  function displacedEntries(current, updated) {
116
117
  const remaining = new Set(updated.filter((hash) => hash !== null));
@@ -124,19 +125,9 @@ function displacedEntries(current, updated) {
124
125
  return entries;
125
126
  }
126
127
  // deathPos=null = legacy/unknown position (pre-GC String[] format or migration).
127
- // These entries are NOT swept incrementally — retained until full-recordServed (isFullRead) or major-GC promotion clears retired.
128
+ // These entries are NOT swept incrementally — retained until a full-read serve (the `fullRead`
129
+ // verdict) or major-GC promotion clears retired.
128
130
  // Incremental hazard sweep only frees deathPos (number) whose card was re-observed; null survives partial sweeps by design (minor leak documented here) and is drained only on epoch promotion/full read.
129
- function sweepRetiredByPositions(store, sessionKey, path, servedPositions) {
130
- if (servedPositions.size === 0)
131
- return;
132
- const entries = store.getRetiredEntries(sessionKey, path);
133
- if (entries.length === 0)
134
- return;
135
- const filtered = entries.filter((e) => e.deathPos === null || !servedPositions.has(e.deathPos));
136
- if (filtered.length !== entries.length) {
137
- store.upsertRetiredAnchors(sessionKey, path, JSON.stringify(filtered));
138
- }
139
- }
140
131
  function sweepAndRetire(store, sessionKey, path, current, updated, rows) {
141
132
  const servedPositions = new Set(rows.map((r) => r.position));
142
133
  const existingCards = store.getCards(sessionKey, path);
@@ -180,6 +171,41 @@ export async function retireAnchors(sessionKey, path, hashes) {
180
171
  retireAnchorsInStore(store, sessionKey, path, additions);
181
172
  });
182
173
  }
174
+ /**
175
+ * Caller-owned transaction: revive retired anchors inside the caller's unit.
176
+ *
177
+ * The undo restore is the one path that brings a retired assignment back: when the
178
+ * pre-edit line returns byte-identically, its pre-edit anchor is live again, so the
179
+ * retirement that the edit recorded must move with the restore (ADR-0017 reversal).
180
+ * Anchors not in the store's retired set are left untouched; the entry's `deathPos`
181
+ * does not matter — the anchor's line is back, so the whole entry goes.
182
+ */
183
+ export function unretireAnchorsInStore(store, sessionKey, path, hashes) {
184
+ const revivals = new Set(hashes);
185
+ if (revivals.size === 0)
186
+ return;
187
+ const entries = store.getRetiredEntries(sessionKey, path);
188
+ const kept = entries.filter((entry) => !revivals.has(entry.hash));
189
+ if (kept.length !== entries.length) {
190
+ store.upsertRetiredAnchors(sessionKey, path, JSON.stringify(kept));
191
+ }
192
+ }
193
+ /**
194
+ * Assertion about FileView, never a decision (ADR-0035): a full-read verdict must arrive with a
195
+ * dense mirror — `rows` covering every hash of the file, in order, hash for hash. Rows that fall
196
+ * short of that were served by a read that also claims to have shown the whole file; the two
197
+ * cannot both be right, so the disagreement is reported with the path and the counts, and the
198
+ * verdict still decides (a warning must not silently become a second authority).
199
+ */
200
+ function warnOnNonDenseFullReadMirror(path, rows, full) {
201
+ const dense = rows.length === full.hashes.length &&
202
+ rows.every((row, index) => row.position === index && row.hash === full.hashes[index]);
203
+ if (dense)
204
+ return;
205
+ console.warn(`dsh-better-edit: full read of ${path} served a non-dense mirror (${rows.length} row(s) for ` +
206
+ `${full.hashes.length} hash(es)) — proceeding on the full-read verdict; FileView.served ` +
207
+ `disagrees with FileView.hashes.`);
208
+ }
183
209
  /**
184
210
  * Funnel for lease granting: materialize-or-adopt the serve snapshot and grant
185
211
  * leases for the served rows as-is. Caller-owned transaction: this must run
@@ -205,6 +231,10 @@ function grantServeLeases(store, sessionKey, path, rows, hashes, content) {
205
231
  * `false` means the write rolled back and no lease was granted, so the caller must not advertise
206
232
  * the rows' anchors as usable: that is a partial failure of the caller's operation, not a failed
207
233
  * operation. The best-effort contract is unchanged — this never throws.
234
+ *
235
+ * The context's `fullRead` verdict — not the shape of `rows` — decides whether this serve also
236
+ * performs the full-read effects (clearing retired anchors and hazard cards, overwriting the whole
237
+ * canon array); everything else here belongs to every serve alike (ADR-0035).
208
238
  */
209
239
  export async function recordServed(sessionKey, path, rows, lineCount, full) {
210
240
  // Nothing to record, so nothing can fail: vacuously landed.
@@ -212,9 +242,12 @@ export async function recordServed(sessionKey, path, rows, lineCount, full) {
212
242
  return true;
213
243
  try {
214
244
  const store = await loadServedStore();
215
- const isFullRead = full !== undefined &&
216
- rows.length === full.hashes.length &&
217
- rows.every((row, index) => row.position === index && row.hash === full.hashes[index]);
245
+ // The verdict is the caller's, not ours (ADR-0035): FileView knows the request shape, this
246
+ // seam only sees rows. The density check that used to decide here is the assertion below —
247
+ // it reports a FileView/rows disagreement and then gets out of the verdict's way.
248
+ const isFullRead = full?.fullRead === true;
249
+ if (isFullRead && full !== undefined)
250
+ warnOnNonDenseFullReadMirror(path, rows, full);
218
251
  withStore(() => {
219
252
  const current = store.getServed(sessionKey, path);
220
253
  const updated = _mergeServedRows(current, rows, lineCount === undefined ? undefined : { truncateTo: lineCount });
@@ -254,6 +287,11 @@ export async function recordServed(sessionKey, path, rows, lineCount, full) {
254
287
  sweepAndRetire(store, sessionKey, path, current, updated, rows);
255
288
  }
256
289
  // Pair #6: the lease grant and the `served` row it derives from are ONE unit.
290
+ //
291
+ // WHY the grant is NOT gated on the full-read verdict (ADR-0035): a served anchor is
292
+ // editable only through its lease, and a lease is stamped with the snapshot it belongs to,
293
+ // so a page still commits the content it showed. Gate this and a displayed anchor becomes
294
+ // uneditable (`E_UNKNOWN_ANCHOR` on page-then-edit, 12 cells across 7 files).
257
295
  grantServeLeases(store, sessionKey, path, rows, full?.hashes, full?.content);
258
296
  });
259
297
  return true;
@@ -361,14 +399,6 @@ export async function wipeServedState(sessionKey) {
361
399
  console.error("Failed to wipe served state:", error);
362
400
  }
363
401
  }
364
- export function servedPositionsOf(served, hash) {
365
- const out = [];
366
- for (let i = 0; i < served.length; i++) {
367
- if (served[i] === hash)
368
- out.push(i);
369
- }
370
- return out;
371
- }
372
402
  function nearestSurvivingPosition(served, surviving, from, direction) {
373
403
  if (direction === "below") {
374
404
  for (let q = from - 1; q >= 0; q--) {
@@ -555,7 +585,7 @@ export function computeDrift(input) {
555
585
  drifted: driftedSet.has(position),
556
586
  }));
557
587
  const rowsText = fmtServedRows(rows, resultLines);
558
- const moreText = unshown > 0 ? `\n[... ${unshown} more — re-read to see]` : "";
588
+ const moreText = unshown > 0 ? `\n${moreRowsHint(unshown, "re-read to see")}` : "";
559
589
  return {
560
590
  text: `${DRIFT_NOTICE_HEADING} ${countLabel} changed outside the range:\n${rowsText}${moreText}`,
561
591
  rows,
@@ -1,28 +1,28 @@
1
1
  /**
2
- * Store — deep module owning tenancy + lifecycle + path resolution.
2
+ * Store — seam VIEW over tenancy + lifecycle + path resolution.
3
3
  *
4
- * Single seam that answers "which store, where, and is it open?"
5
- * Tenancy (where DB lives) and lifecycle (central GC + row TTL + WAL)
6
- * are private details of this seam; hash-store keeps only schema +
7
- * row-family domain logic and imports path resolution from here.
8
- * StoreConfig remains the config complement seam but its path is
9
- * resolved via this Store seam.
4
+ * Single seam that answers "which store, where, and is it open?" for its
5
+ * consumers. This file owns no behaviour: every export below is a re-export
6
+ * of code owned by a leaf module.
7
+ *
8
+ * Ownership direction, stated once and not to be inverted:
9
+ * `store-config` → `store-tenancy` → this barrel, and `hash-store` → this
10
+ * barrel. The leaves hold the code — `store-tenancy` resolves where the DB
11
+ * lives and imports `loadConfig` FROM `store-config`, which resolves its own
12
+ * path through `resolveDshHome` — while this file is the view they surface
13
+ * through.
10
14
  *
11
15
  * YAGNI-gated: DB plumbing (openDb/buildStore/quarantine/busy-retry/
12
16
  * WAL/legacy JSON migration) stays in hash-store for now and is
13
17
  * re-exported here for testability without importing domain helpers
14
- * — full plumbing move is deferred to avoid contract risk. Old
15
- * store-tenancy/store-lifecycle files are kept as compat shims
16
- * re-exporting from this seam (reversible).
18
+ * — full plumbing move is deferred to avoid contract risk.
17
19
  *
18
20
  * @module dsh-better-edit/store
19
21
  */
20
- // Tenancy — re-export as seam ownership (private details, public via Store)
22
+ // Tenancy — re-exported from its owner (`store-tenancy`), surfaced here
21
23
  export { tenancyFor, configDir, hashStorePath, hashStoreDir, legacyHashStorePath, loadConfig, _resetConfigCache, expand, } from "../store-tenancy.js";
22
- // Lifecycle — re-export as seam ownership
24
+ // Lifecycle — re-exported from its owner (`store-lifecycle`)
23
25
  export { onStoreOpen, onAppStart, onSessionStart, setStoresGetter, runCentralJanitorIfDue, _resetLifecycleForTests, } from "../store-lifecycle.js";
24
- // StoreConfig path helper — canonical Store seam entry for config consumers
25
- export { loadConfig as loadStoreConfig } from "../store-config.js";
26
26
  // Hash-store plumbing re-exported for testability without domain coupling
27
27
  // (future: move openDb/buildStore/quarantine/busy-retry here)
28
28
  export { isCorruptionError, loadHashStore, shutdownHashStore, withStore, findSnapshotPathsByHashes, upsertSnapshotFor, } from "../hash-store.js";
@@ -11,6 +11,7 @@ import { mkdir, writeFile } from "node:fs/promises";
11
11
  import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
12
12
  import { z } from "zod";
13
13
  import { errCode } from "./utils.js";
14
+ import { SUPPORTED_ENCODINGS } from "./encoding.js";
14
15
  // ---- helpers (pure, no IO) ----
15
16
  function homeBase() {
16
17
  const envHome = process.env.HOME;
@@ -93,9 +94,7 @@ const StoreConfigSchema = z.object({
93
94
  autoGitignore: z.boolean().default(false), // workspace only: auto-append ".dsh_better_edit/" to .gitignore when .git exists but entry missing (false = warn once)
94
95
  autoGuessEncoding: z.boolean().default(false), // VS Code files.autoGuessEncoding — deterministic BOM→UTF-8 first, model-assisted top-3 only when true
95
96
  normalizeToUtf8: z.boolean().default(false), // when true, legacy files (GBK etc.) migrate to UTF-8 on first edit/write
96
- supportedEncodings: z
97
- .array(z.string())
98
- .default(["gbk", "big5", "shift_jis", "euc-kr", "windows-1251", "iso-8859-1"]),
97
+ supportedEncodings: z.array(z.string()).default([...SUPPORTED_ENCODINGS]),
99
98
  undo_ttl_s: z.number().int().min(-1).default(604800), // undo history TTL in seconds; -1 = keep forever (default 604800 = 7 days)
100
99
  storeMaxAgeS: z.number().int().min(1).default(2592000), // central janitor: max idle age in seconds before evicting runtime/<name>-<hash8>/ (default 2592000 = 30 days)
101
100
  storeMaxTotalBytes: z.number().int().min(0).default(524288000), // central janitor: max total bytes under runtime/ before LRU eviction (default 524288000 = 500 MB)
@@ -131,7 +130,7 @@ autoGuessEncoding: false
131
130
  # when true, legacy files (GBK etc.) migrate to UTF-8 on first write
132
131
  normalizeToUtf8: false
133
132
  # allowlist scored for top-3 previews when autoGuessEncoding:true
134
- supportedEncodings: [gbk, big5, shift_jis, euc-kr, windows-1251, iso-8859-1]
133
+ supportedEncodings: [${SUPPORTED_ENCODINGS.join(", ")}]
135
134
 
136
135
  # undo history TTL in seconds; -1 = keep forever (default 604800 = 7 days)
137
136
  undo_ttl_s: 604800
@@ -355,7 +354,7 @@ function complementMissingFieldsSync(yamlPath, yamlPartial) {
355
354
  if (yamlPartial.normalizeToUtf8 === undefined)
356
355
  missingLines.push("normalizeToUtf8: false");
357
356
  if (yamlPartial.supportedEncodings === undefined)
358
- missingLines.push("supportedEncodings: [gbk, big5, shift_jis, euc-kr, windows-1251, iso-8859-1]");
357
+ missingLines.push(`supportedEncodings: [${SUPPORTED_ENCODINGS.join(", ")}]`);
359
358
  if (yamlPartial.undo_ttl_s === undefined)
360
359
  missingLines.push("undo_ttl_s: 604800");
361
360
  if (yamlPartial.storeMaxAgeS === undefined)
@@ -15,7 +15,7 @@ import { readdir, rm, stat } from "node:fs/promises";
15
15
  import { dirname, join } from "node:path";
16
16
  import { DatabaseSync } from "node:sqlite";
17
17
  import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
18
- import { hashStorePath, loadConfig } from "./paths.js";
18
+ import { loadConfig } from "./store-config.js";
19
19
  import { workspaceCwd } from "./workspace-context.js";
20
20
  import { errCode, splitLines } from "./utils.js";
21
21
  import { HASH_STORE_BUSY_TIMEOUT, SERVED_TTL_MS } from "./constants.js";
package/lib/tool-edit.js CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * The dsh `edit` tool: hash-anchored literal range edits that shadow the
3
3
  * built-in `edit` on the agent's own scope layer. Now the sole mutation tool
4
- * (batch_edit removed, ADR-0007): payload is { file: string|null, edits: [{anchor_from,anchor_to,replace_with},...] }
5
- * single-file atomic batch, legacy null file inference via anchors.
4
+ * (batch_edit removed, ADR-0007): payload is { file: string, edits: [{anchor_from,anchor_to,replace_with},...] }
5
+ * single-file atomic batch; the file is named explicitly, never inferred (#117).
6
6
  * @module dsh-better-edit/tool-edit
7
7
  */
8
8
  import { defineTool } from "@deepseek-ai/dsh-tools";
@@ -10,41 +10,9 @@ import { normalizeRequest as normReq, assertEditRequest } from "./contract.js";
10
10
  import { abortIf } from "./utils.js";
11
11
  import { execute } from "./mutation.js";
12
12
  import { EDIT_DESCRIPTION } from "./prompts.js";
13
- import { codeOf } from "./utils.js";
14
- import { DomainError, formatError } from "./domain-errors.js";
13
+ import { DomainError } from "./domain-errors.js";
15
14
  import { execCwd, execSessionKey } from "./workspace-context.js";
16
15
  import { withWorkspace } from "./workspace-context.js";
17
- import { findSnapshotPathsByHashes } from "./hash-store.js";
18
- import { parseHashRef } from "./hashline/anchor-pipeline.js";
19
- async function resolveNullPath(edits) {
20
- if (edits.length === 0)
21
- return undefined;
22
- const first = edits[0];
23
- try {
24
- const h1 = parseHashRef(first.anchor_from).hash;
25
- const h2 = parseHashRef(first.anchor_to).hash;
26
- const matches = await findSnapshotPathsByHashes([h1, h2]);
27
- if (matches.length === 1) {
28
- return {
29
- file: matches[0],
30
- warning: formatError("E_BAD_PAYLOAD", {
31
- message: `Autocorrected: missing "file" resolved to ${matches[0]} — the only file whose stored hashes contain both anchors.`,
32
- }),
33
- };
34
- }
35
- if (matches.length > 1) {
36
- throw new DomainError("E_BAD_PAYLOAD", {
37
- message: `Edit request requires a non-empty "file" string; the anchors match multiple known files: ${matches.join(", ")}. Include the intended file.`,
38
- });
39
- }
40
- }
41
- catch (e) {
42
- if (codeOf(e) === "E_BAD_PAYLOAD")
43
- throw e;
44
- return undefined;
45
- }
46
- return undefined;
47
- }
48
16
  /**
49
17
  * E_UNKNOWN producer: the edit tool boundary is where raw unexpected errors
50
18
  * surface. DomainError members and aborts pass through untouched; anything else
@@ -69,8 +37,9 @@ export function buildEditTool(io, sandbox) {
69
37
  file: {
70
38
  oneOf: [
71
39
  { type: "string", description: "Text file to edit (a file, never a directory)" },
72
- // N1: no description — ADR-0015 keeps the legacy null path admissible
73
- // but undocumented, so the schema admits without teaching.
40
+ // #117: null stays wire-admissible so the domain rejects it with
41
+ // E_BAD_PAYLOAD; dsh would otherwise answer INVALID_ARGS before the
42
+ // contract runs. Undocumented and never inferable.
74
43
  { type: "null" },
75
44
  ],
76
45
  },
@@ -111,22 +80,15 @@ export function buildEditTool(io, sandbox) {
111
80
  const signal = exec.signal;
112
81
  const canonical = normReq(args);
113
82
  assertEditRequest(canonical);
83
+ // `assertEditRequest` narrows the raw args to the normalized contract.
114
84
  const req = canonical;
115
- let resolvedFile = req.file;
116
- let fileWarning;
117
- if (resolvedFile === null) {
118
- const resolved = await resolveNullPath(req.edits);
119
- if (resolved) {
120
- resolvedFile = resolved.file;
121
- fileWarning = resolved.warning;
122
- }
123
- else {
124
- throw new DomainError("E_BAD_PAYLOAD", {
125
- message: "Edit request file is null and could not be inferred from anchors — anchors match no known file. Include the intended file.",
126
- });
127
- }
128
- }
129
- const sandboxPolicy = await sandbox.resolvePolicy("edit", { file: resolvedFile, edits: req.edits }, exec);
85
+ // #117: a null/absent file is rejected at admission (assertEditRequest);
86
+ // the retired anchor-inference arm never resolves one here.
87
+ const resolvedFile = req.file;
88
+ const sandboxPolicy = await sandbox.resolvePolicy("edit",
89
+ // SAFETY: `resolvePolicy` reads only sandbox_permissions/justification;
90
+ // the file/edits fields are legacy context it ignores.
91
+ { file: resolvedFile, edits: req.edits }, exec);
130
92
  abortIf(signal);
131
93
  const items = [];
132
94
  for (let index = 0; index < req.edits.length; index++) {
@@ -138,7 +100,6 @@ export function buildEditTool(io, sandbox) {
138
100
  anchor_from: e.anchor_from,
139
101
  anchor_to: e.anchor_to,
140
102
  replace_with: e.replace_with,
141
- fileWarning: index === 0 ? fileWarning : undefined,
142
103
  ...(req.mode !== undefined ? { mode: req.mode } : {}),
143
104
  });
144
105
  }
@@ -152,6 +113,3 @@ export function buildEditTool(io, sandbox) {
152
113
  },
153
114
  });
154
115
  }
155
- export function registerEditTool(_rootCtx, agentCtx, io, sandbox) {
156
- return agentCtx.tools.register(buildEditTool(io, sandbox));
157
- }
package/lib/tool-read.js CHANGED
@@ -9,7 +9,7 @@ import { defineTool } from "@deepseek-ai/dsh-tools";
9
9
  import { normalizeRequest as normReq, assertReadRequest, pathSchema } from "./contract.js";
10
10
  import { readAndServe } from "./read-and-serve.js";
11
11
  import { READ_DESCRIPTION } from "./prompts.js";
12
- import { normalizeEncoding } from "./encoding.js";
12
+ import { normalizeEncoding, SUPPORTED_ENCODINGS_LABEL } from "./encoding.js";
13
13
  import { DomainError } from "./domain-errors.js";
14
14
  import { MAX_READ_WINDOWS } from "./file-view.js";
15
15
  import { renderTextWarning } from "./render-text-warning.js";
@@ -82,7 +82,7 @@ export function buildReadTool(io) {
82
82
  const norm = normalizeEncoding(String(encoding));
83
83
  if (!norm)
84
84
  throw new DomainError("E_BAD_PAYLOAD", {
85
- message: `Unknown encoding: ${String(encoding)}. Supported: utf8, gbk, big5, shift_jis, euc-kr, windows-1251, iso-8859-1`,
85
+ message: `Unknown encoding: ${String(encoding)}. Supported: ${SUPPORTED_ENCODINGS_LABEL}`,
86
86
  });
87
87
  }
88
88
  const canonical = normReq(args);
@@ -105,9 +105,3 @@ export function buildReadTool(io) {
105
105
  },
106
106
  });
107
107
  }
108
- /**
109
- * Register the hashline tool on the calling agent’s scope (own layer).
110
- */
111
- export function registerReadTool(_rootCtx, agentCtx, io) {
112
- return agentCtx.tools.register(buildReadTool(io));
113
- }
@@ -23,7 +23,8 @@
23
23
  */
24
24
  import { defineTool } from "@deepseek-ai/dsh-tools";
25
25
  import { getAutoGuessFooter } from "./fs-bridge.js";
26
- import { getEncodingState, invalidateIfStale, prepareForSave, recordOpenState, } from "./file-encoding-state.js";
26
+ import { encodingHintAtVersion, getEncodingState, invalidateIfStale, prepareForSave, recordOpenState, } from "./file-encoding-state.js";
27
+ import { loadConfig } from "./store-config.js";
27
28
  import { stripBOM } from "./edit-diff.js";
28
29
  import { renderTextWarning } from "./render-text-warning.js";
29
30
  import { execCwd, withWorkspace } from "./workspace-context.js";
@@ -76,9 +77,17 @@ function requireViewRange(args) {
76
77
  return [value[0], value[1]];
77
78
  }
78
79
  /**
79
- * Strict read-first gate: the file must carry file encoding state recorded by
80
- * a prior `view`/`read` at the current version. Stale memos are invalidated
81
- * first, so drifted files fail loud instead of editing blind. Never writes.
80
+ * Strict read-first gate: the file must carry file encoding state recorded by a
81
+ * prior `view`/`read` at the current version. Stale memos are invalidated first,
82
+ * so drifted files fail loud instead of editing blind.
83
+ *
84
+ * A successful write also refreshes the memo at the post-write version (the memo
85
+ * must describe the bytes actually written, #112), so the model's own write
86
+ * authorizes a follow-up non-anchored edit without a re-`view`. An EXTERNAL change
87
+ * still drifts the version and fails with E_BLIND_REPLACE.
88
+ *
89
+ * Never writes; returns the version it validated so the caller can reuse it as the
90
+ * decode-hint guard instead of stat'ing twice.
82
91
  */
83
92
  async function requireObserved(io, absolutePath, displayPath, signal) {
84
93
  const version = await io.statVersion(absolutePath, signal);
@@ -86,6 +95,7 @@ async function requireObserved(io, absolutePath, displayPath, signal) {
86
95
  if (!getEncodingState(absolutePath)) {
87
96
  throw new DomainError("E_BLIND_REPLACE", { path: displayPath, command: "str_replace_editor" });
88
97
  }
98
+ return version;
89
99
  }
90
100
  /**
91
101
  * Governed save: resolve the per-call sandbox policy — the session's standing
@@ -125,13 +135,15 @@ function countOccurrences(haystack, needle) {
125
135
  * Replaces the former local `restoreBom` so the shadow can't diverge from
126
136
  * the file-encoding-state round-trip (report #2). */
127
137
  function restoreForSave(content, absolutePath) {
128
- return prepareForSave(content, getEncodingState(absolutePath)).textToWrite;
138
+ // Throws E_ENCODING_UNWRITABLE before the write when the recorded encoding
139
+ // cannot round-trip through the text-only seam (issue #112).
140
+ return prepareForSave(content, getEncodingState(absolutePath), {
141
+ normalizeToUtf8: loadConfig().normalizeToUtf8,
142
+ displayPath: absolutePath,
143
+ }).textToWrite;
129
144
  }
130
- function autoGuessWarning(absolutePath, rawPath) {
131
- return (getAutoGuessFooter(absolutePath) ??
132
- getAutoGuessFooter(rawPath) ??
133
- getAutoGuessFooter(absolutePath.replace(/\\/g, "/")) ??
134
- undefined);
145
+ function autoGuessWarning(absolutePath) {
146
+ return getAutoGuessFooter(absolutePath);
135
147
  }
136
148
  export function buildStrReplaceEditorTool(io, sandbox) {
137
149
  return defineTool({
@@ -148,6 +160,7 @@ export function buildStrReplaceEditorTool(io, sandbox) {
148
160
  required: true,
149
161
  description: "File path",
150
162
  },
163
+ // SAFETY: the value-schema DSL types `json` loosely; the tool validates the shape at admission.
151
164
  view_range: {
152
165
  type: "json",
153
166
  description: "[start, end] 1-indexed inclusive line range for view",
@@ -195,7 +208,11 @@ export function buildStrReplaceEditorTool(io, sandbox) {
195
208
  abortIf(signal);
196
209
  const absolutePath = await io.resolve(rawPath, cwd, signal);
197
210
  if (cmd === "view") {
198
- const text = await io.readText(absolutePath, signal);
211
+ // Issue #112: consume the encoding recorded by read({ encoding }) so a
212
+ // re-view decodes the same text instead of re-detecting (or failing).
213
+ const viewVersion = await io.statVersion(absolutePath, signal);
214
+ const viewHint = encodingHintAtVersion(absolutePath, viewVersion);
215
+ const text = await io.readText(absolutePath, signal, viewHint);
199
216
  // Observation only: encoding state is recorded by readText;
200
217
  // served state is never touched here.
201
218
  // NOTE (report #10): the readText + emitObserved pair costs two
@@ -225,7 +242,7 @@ export function buildStrReplaceEditorTool(io, sandbox) {
225
242
  }
226
243
  }
227
244
  }
228
- const warning = autoGuessWarning(absolutePath, rawPath);
245
+ const warning = autoGuessWarning(absolutePath);
229
246
  return warning ? { text: out, warning } : { text: out };
230
247
  }
231
248
  if (cmd === "create") {
@@ -255,8 +272,11 @@ export function buildStrReplaceEditorTool(io, sandbox) {
255
272
  // an edit on drifted bytes. Returning the version from readText would
256
273
  // need a FileIO contract break for an unmeasured hot-path nit; same
257
274
  // pattern as the view double-RPC above, so documented, not collapsed.
258
- await requireObserved(io, absolutePath, rawPath, signal);
259
- const current = await io.readText(absolutePath, signal);
275
+ const guardedVersion = await requireObserved(io, absolutePath, rawPath, signal);
276
+ // Issue #112: the mutating read consumes the encoding recorded by
277
+ // read({ encoding }), version-guarded by requireObserved just above.
278
+ const encodingHint = encodingHintAtVersion(absolutePath, guardedVersion);
279
+ const current = await io.readText(absolutePath, signal, encodingHint);
260
280
  if (cmd === "str_replace") {
261
281
  const oldStr = requireString(rec, "old_str");
262
282
  if (!("new_str" in rec) || typeof rec["new_str"] !== "string") {
@@ -303,7 +323,3 @@ export function buildStrReplaceEditorTool(io, sandbox) {
303
323
  },
304
324
  });
305
325
  }
306
- /** Register the shadow `str_replace_editor` on the calling agent's scope (own layer). */
307
- export function registerStrReplaceEditorTool(agentCtx, io, sandbox) {
308
- return agentCtx.tools.register(buildStrReplaceEditorTool(io, sandbox));
309
- }