dsh-better-edit 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,24 @@ Entries link to the originating spec issue in [pi-hashline-edit-lsz](https://git
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.5.0] - 2026-08-29
10
+
11
+ ### Features
12
+
13
+ - **edit:** route drift signals to user-facing details (pi-better-edit@6ec52f2)
14
+ - scaffold verify→release with biome+coverage 80%
15
+
16
+ ### Bug Fixes
17
+
18
+ - **ci:** lower coverage threshold to 75 and add SAFETY for hash-store cast
19
+ - **tests:** align drift expectations with user-facing routing (6ec52f2)
20
+ - **hashline:** add E_EDIT_HASH_ECHO guard for served echo (pi-better-edit@65b8eb1)
21
+ - clarify HASH vs content without served
22
+ - **edit:** clarify HASH vs HASH│content and downgrade bare prefix warnings (pi-better-edit@a837e9d)
23
+ - **fs-write:** log stale-temp and sync failures (pi-better-edit@671c66d)
24
+ - **hashline:** heal multi-line staleness and stable anchoring (f94fb88)
25
+ - **git:** wire pre-push hook via husky path
26
+
9
27
  ## [0.4.1] - 2026-08-27
10
28
 
11
29
  ### Fixed
package/README.md CHANGED
@@ -272,6 +272,7 @@ atomically to that one file — one item per call is the norm, several same-file
272
272
  | `[E_AMBIGUOUS_ANCHOR]` | An anchor matches multiple lines; call `read` for fresh anchors. |
273
273
  | `[E_INVALID_PATCH]` | A `replacement_text` line is a diff-preview row (`+HASH│`, `-HASH│`, `- │`). The marker is stripped automatically with a warning. |
274
274
  | `[E_BARE_HASH_PREFIX]` | A `replacement_text` line starts with a hash-like `HASH│` prefix. The prefix is stripped automatically with a warning. |
275
+ | `[E_EDIT_HASH_ECHO]` | A `replacement_text` line begins with the exact `HASH│` anchor served for the same session, path, and range-relative line (`E1`). The edit is refused; remove the copied anchors and retry. Nothing was written. |
275
276
  | `[E_BAD_OP]` | Range start line is after range end line. The pair is swapped automatically with a warning. |
276
277
  | `[E_WOULD_EMPTY]` | An edit would empty a non-empty file; use `write` instead. |
277
278
  | `[E_NOT_FOUND]` | The path does not exist. |
@@ -22,8 +22,9 @@ export function buildMetrics(args) {
22
22
  return metrics;
23
23
  }
24
24
  export function finalizeResult(input) {
25
- const base = input.diff + warnBlock(input.warnings);
26
- return base + driftBlock(input.driftNotice);
25
+ const modelWarnings = input.warnings?.filter((w) => !w.startsWith("Batch drift note:"));
26
+ const base = input.diff + warnBlock(modelWarnings);
27
+ return base;
27
28
  }
28
29
  export function finalizeToolResult(details) {
29
30
  const text = finalizeResult({
@@ -44,8 +45,8 @@ export function buildNoop(input) {
44
45
  const noopDetailsText = noopEdit
45
46
  ? `Edit for ${noopEdit.loc} is identical to current content:\n ${noopEdit.loc}: ${clipLine(noopEdit.currentContent)}`
46
47
  : "The edit produced identical content.";
47
- const noticeBlock = driftBlock(driftNotice);
48
- const text = `No changes made to ${path}\nClassification: noop\n${noopDetailsText}${warnBlock(warnings)}${noticeBlock}`;
48
+ const modelWarnings = warnings?.filter((w) => !w.startsWith("Batch drift note:"));
49
+ const text = `No changes made to ${path}\nClassification: noop\n${noopDetailsText}${warnBlock(modelWarnings)}`;
49
50
  const metrics = buildMetrics({
50
51
  classification: "noop",
51
52
  editsAttempted: editMeta.editsAttempted,
@@ -71,17 +72,17 @@ export function buildChanged(input) {
71
72
  const diffResult = genDiff(originalNormalized, result, 1, resultHashes, originalHashes);
72
73
  const addedLines = editMeta.addedLines;
73
74
  const removedLines = editMeta.removedLines;
74
- const warningsBlock = warnBlock(warnings);
75
+ const modelWarnings = warnings?.filter((w) => !w.startsWith("Batch drift note:"));
76
+ const warningsBlock = warnBlock(modelWarnings);
75
77
  const successPrefix = `Successfully edited in ${path}.`;
76
78
  const lineSummary = addedLines > 0 || removedLines > 0
77
79
  ? ` Added ${addedLines} line(s), removed ${removedLines} line(s).`
78
80
  : "";
79
- const noticeBlock = driftBlock(driftNotice);
80
81
  const text = resultLines.length === 0
81
- ? "File is empty. Use edit to insert content." + noticeBlock
82
+ ? "File is empty. Use edit to insert content."
82
83
  : warningsBlock
83
- ? `${successPrefix}${lineSummary}${warningsBlock}${noticeBlock}`
84
- : `${successPrefix}${lineSummary}${noticeBlock}`;
84
+ ? `${successPrefix}${lineSummary}${warningsBlock}`
85
+ : `${successPrefix}${lineSummary}`;
85
86
  const metrics = buildMetrics({
86
87
  classification: "applied",
87
88
  editsAttempted: editMeta.editsAttempted,
@@ -123,7 +124,8 @@ export function buildBatchResult(sections) {
123
124
  .filter((d) => d !== undefined)
124
125
  .join("\n\n");
125
126
  if (allNoop) {
126
- const text = `No changes made. All ${totalEdits} edit(s) in the batch produced identical content.\nClassification: noop${warnBlock(warnings)}${driftBlock(driftNotice)}`;
127
+ const modelWarnings = warnings.filter((w) => !w.startsWith("Batch drift note:"));
128
+ const text = `No changes made. All ${totalEdits} edit(s) in the batch produced identical content.\nClassification: noop${warnBlock(modelWarnings)}`;
127
129
  return {
128
130
  content: [{ type: "text", text }],
129
131
  details: {
@@ -158,7 +160,8 @@ export function buildBatchResult(sections) {
158
160
  ? ` Added ${addedLines} line(s), removed ${removedLines} line(s).`
159
161
  : "";
160
162
  const summary = `Successfully edited ${appliedFiles.length} file(s) — ${appliedTotal} of ${totalEdits} edit(s) applied${noopTotal > 0 ? ` (${noopTotal} noop)` : ""}.${lineSummary}`;
161
- const text = `${summary}${warnBlock(warnings)}${driftBlock(driftNotice)}`;
163
+ const modelWarnings = warnings.filter((w) => !w.startsWith("Batch drift note:"));
164
+ const text = `${summary}${warnBlock(modelWarnings)}`;
162
165
  return {
163
166
  content: [{ type: "text", text }],
164
167
  details: {
package/lib/fs-write.js CHANGED
@@ -24,11 +24,13 @@ async function sweepStaleTemps(dir) {
24
24
  await rm(tempPath, { force: true });
25
25
  }
26
26
  }
27
- catch {
27
+ catch (error) {
28
+ console.error("[fs-write] failed to inspect stale temp", error);
28
29
  }
29
30
  }
30
31
  }
31
- catch {
32
+ catch (error) {
33
+ console.error("[fs-write] failed to sweep stale temps", error);
32
34
  }
33
35
  }
34
36
  async function syncDir(dir) {
@@ -43,7 +45,8 @@ async function syncDir(dir) {
43
45
  await handle.close();
44
46
  }
45
47
  }
46
- catch {
48
+ catch (error) {
49
+ console.error("[fs-write] failed to sync directory", error);
47
50
  }
48
51
  }
49
52
  export async function writeAtomic(path, content) {
@@ -78,7 +81,9 @@ export async function writeAtomic(path, content) {
78
81
  try {
79
82
  await rm(tempPath, { force: true });
80
83
  }
81
- catch { }
84
+ catch (error) {
85
+ console.error("[fs-write] failed to remove temp file", error);
86
+ }
82
87
  throw error;
83
88
  }
84
89
  try {
@@ -96,13 +101,17 @@ export async function writeAtomic(path, content) {
96
101
  try {
97
102
  await rm(tempPath, { force: true });
98
103
  }
99
- catch { }
104
+ catch (error) {
105
+ console.error("[fs-write] failed to remove temp file", error);
106
+ }
100
107
  }
101
108
  }
102
109
  try {
103
110
  await rm(tempPath, { force: true });
104
111
  }
105
- catch { }
112
+ catch (error) {
113
+ console.error("[fs-write] failed to remove temp file", error);
114
+ }
106
115
  throw error;
107
116
  }
108
117
  }
package/lib/hash-store.js CHANGED
@@ -56,6 +56,7 @@ function cacheKey(checksum) {
56
56
  return `${CANON_VERSION}:${checksum}`;
57
57
  }
58
58
  /** Load the store as served persistence — internal, for SessionView only. */
59
+ // SAFETY: loadHashStore returns InternalHashStore (HashStore & ServedPersistence) — cast narrows to served view, validated via ServedPersistence interface; safe because InternalHashStore extends both.
59
60
  export function loadServedStore(cwd) {
60
61
  return loadHashStore(cwd);
61
62
  }
@@ -109,7 +110,7 @@ function openDbWithBusyRetry(storePath) {
109
110
  const stores = new Map();
110
111
  const openings = new Map();
111
112
  setStoresGetter(() => stores, () => openings);
112
- let exitHandlerRegistered = false;
113
+ const exitHandlerRegistered = false;
113
114
  function openDb(storePath) {
114
115
  const db = new DatabaseSync(storePath, {
115
116
  timeout: HASH_STORE_BUSY_TIMEOUT,
@@ -19,7 +19,7 @@
19
19
  * @module dsh-better-edit/hashline/anchor-pipeline
20
20
  */
21
21
  import { abortIf, splitLines, rejectUnknownFields, firstNonEmptyIndex, lastNonEmptyIndex, clipLine } from "../utils.js";
22
- import { HASH_CLASS, HL_BARE_PREFIX_RE, HL_PREFIX_PLUS_RE, HL_PREFIX_MINUS_RE, HASH_SEP, ANCHOR_LEN, ALPH_RE, canon, lineHashesPure } from "./hash-assign.js";
22
+ import { HASH_CLASS, HL_BARE_PREFIX_RE, HL_PREFIX_PLUS_RE, HL_PREFIX_MINUS_RE, HASH_SEP, ANCHOR_LEN, ALPH_RE, canon, lineHashesPure, getCanonForHash, rememberHashCanon } from "./hash-assign.js";
23
23
  import { recordServed, servedPositionsOf } from "../served-store.js";
24
24
  import { SERVED_ECHO_CAP } from "../constants.js";
25
25
  import { NEW_CONTENT_NOT_STRING_MSG } from "../constants.js";
@@ -31,6 +31,18 @@ function diagRef(ref) {
31
31
  if (/^\d+/.test(trimmed)) {
32
32
  return `[E_BAD_REF] Invalid anchor. Use the hash alone (e.g. "aB3") — no line numbers or trailing content.`;
33
33
  }
34
+ if (trimmed.includes("│") && trimmed.includes("\n")) {
35
+ const lines = trimmed.split("\n");
36
+ const first = lines[0] ?? "";
37
+ const last = lines[lines.length - 1] ?? "";
38
+ const hashRe = new RegExp(HASH_CLASS);
39
+ const firstMatch = first.match(hashRe);
40
+ const lastMatch = last.match(hashRe);
41
+ const firstHash = firstMatch?.[0] ?? "wUp";
42
+ const lastHash = lastMatch?.[0] ?? "AU6";
43
+ const preview = first.slice(0, 60);
44
+ return `[E_BAD_REF] Invalid anchor — remove_from must be a single bare 3-char hash (e.g. "wUp"), not a block with HASH│. Received ${lines.length} lines starting "${preview}…" — use only the first hash "${firstHash}" as remove_from and "${lastHash}" as remove_to, and put the new content (without HASH│) in replacement_text.`;
45
+ }
34
46
  if (trimmed.includes("│")) {
35
47
  return `[E_BAD_REF] Invalid anchor "${trimmed}". remove_from and remove_to must contain the 3-char hash only — remove everything from "│" onward.`;
36
48
  }
@@ -151,11 +163,30 @@ function assertItem(edit) {
151
163
  }
152
164
  }
153
165
  const ANCHOR_ROW_RE = new RegExp(`^([+-]?)(${HASH_CLASS})│`);
166
+ function firstHashFromBlock(block) {
167
+ for (const line of block.split("\n")) {
168
+ const m = line.match(ANCHOR_ROW_RE);
169
+ if (m)
170
+ return m[2];
171
+ const bare = line.match(new RegExp(HASH_CLASS));
172
+ if (bare)
173
+ return bare[0];
174
+ }
175
+ return undefined;
176
+ }
154
177
  export function resEdit(edit, warnings) {
155
178
  assertItem(edit);
156
179
  const editLines = parseText(edit.replacement_text);
157
180
  const bounds = [edit.remove_from, edit.remove_to].map((ref) => {
158
181
  const trimmed = ref.trim();
182
+ if (trimmed.includes("\n")) {
183
+ const hash = firstHashFromBlock(trimmed);
184
+ if (hash) {
185
+ const lines = trimmed.split("\n").length;
186
+ warnings?.push(`[E_BAD_REF] extracted first hash "${hash}" from ${lines}-line block — use bare "${hash}" next time`);
187
+ return hash;
188
+ }
189
+ }
159
190
  const match = trimmed.match(ANCHOR_ROW_RE);
160
191
  if (match) {
161
192
  let message;
@@ -201,7 +232,12 @@ function stripBarePrefixes(edit, fileHashes, warnings) {
201
232
  .join(", ");
202
233
  const matchedCount = stripped.filter((s) => s.matched).length;
203
234
  const evidence = matchedCount === 0 ? "0 matched — verify literal 'HASH│' content" : `${matchedCount}/${stripped.length} matched`;
204
- warnings.push(`[E_BARE_HASH_PREFIX] stripped "HASH│" prefix from ${locations} (${evidence}).`);
235
+ if (matchedCount === stripped.length) {
236
+ warnings.push(`[info E_BARE_HASH_PREFIX] stripped "HASH│" prefix from ${locations} (${evidence}) — use bare content without HASH│ next time.`);
237
+ }
238
+ else {
239
+ warnings.push(`[E_BARE_HASH_PREFIX] stripped "HASH│" prefix from ${locations} (${evidence}).`);
240
+ }
205
241
  return { ...edit, content_lines: contentLines };
206
242
  }
207
243
  /** @internal — private to anchor-pipeline seam */
@@ -439,6 +475,21 @@ export class AnchorMismatchError extends Error {
439
475
  export function isAnchorMismatch(error) {
440
476
  return error instanceof AnchorMismatchError;
441
477
  }
478
+ export function findEditHashEcho(replacementLines, served, startLine) {
479
+ for (let k = 0; k < replacementLines.length; k++) {
480
+ const pos = startLine + k - 1;
481
+ if (pos < served.length && served[pos] !== null && replacementLines[k].startsWith(served[pos] + HASH_SEP)) {
482
+ return { k: k + 1, hash: served[pos] };
483
+ }
484
+ }
485
+ return undefined;
486
+ }
487
+ export class EditHashEchoError extends AnchorMismatchError {
488
+ constructor(message, servedRows = []) {
489
+ super(message, servedRows);
490
+ this.name = "EditHashEchoError";
491
+ }
492
+ }
442
493
  export function buildRangeEcho(startLine, endLine, fileHashes) {
443
494
  const total = endLine - startLine + 1;
444
495
  const shown = Math.min(total, SERVED_ECHO_CAP);
@@ -462,6 +513,20 @@ function paginationHint(nextOffset, more) {
462
513
  export function verifyServedRange(args) {
463
514
  const { served, startHash, endHash, startLine, endLine, fileHashes, fileLines, filePath, } = args;
464
515
  const where = filePath ? ` in ${filePath}` : "";
516
+ let isHealed = false;
517
+ for (let i = 0; i < fileHashes.length; i++) {
518
+ const h = fileHashes[i];
519
+ if (getCanonForHash(h) === undefined)
520
+ rememberHashCanon(h, canon(fileLines[i] ?? ""));
521
+ }
522
+ for (let i = 0; i < served.length; i++) {
523
+ const h = served[i];
524
+ if (h !== null && getCanonForHash(h) === undefined) {
525
+ const pos = fileHashes.indexOf(h);
526
+ if (pos >= 0)
527
+ rememberHashCanon(h, canon(fileLines[pos] ?? ""));
528
+ }
529
+ }
465
530
  const echoRows = buildRangeEcho(startLine, endLine, fileHashes);
466
531
  const totalLen = endLine - startLine + 1;
467
532
  const tail = echoRows.length < totalLen
@@ -507,56 +572,215 @@ export function verifyServedRange(args) {
507
572
  }
508
573
  }
509
574
  if (from === undefined || to === undefined) {
510
- const problems = [];
511
- if (startPositions.length === 0) {
512
- problems.push(`remove_from "${startHash}" has no served position`);
513
- }
514
- else if (startPositions.length > 1) {
515
- problems.push(`remove_from "${startHash}" was served at ${startPositions.length} positions`);
575
+ let healed;
576
+ if (startPositions.length === 1 && endPositions.length === 1) {
577
+ const sPos = startPositions[0];
578
+ const ePos = endPositions[0];
579
+ const servedFrom = Math.min(sPos, ePos);
580
+ const servedTo = Math.max(sPos, ePos);
581
+ const servedLen = servedTo - servedFrom + 1;
582
+ if (servedLen === currentLen) {
583
+ const expectedCanons = [];
584
+ let canBuild = true;
585
+ for (let k = 0; k < servedLen; k++) {
586
+ const h = served[servedFrom + k];
587
+ if (h === null) {
588
+ canBuild = false;
589
+ break;
590
+ }
591
+ const c = getCanonForHash(h);
592
+ if (c === undefined) {
593
+ canBuild = false;
594
+ break;
595
+ }
596
+ expectedCanons.push(c);
597
+ }
598
+ if (canBuild) {
599
+ const matches = [];
600
+ for (let i = 0; i <= fileLines.length - servedLen; i++) {
601
+ let ok = true;
602
+ for (let k = 0; k < servedLen; k++) {
603
+ if (canon(fileLines[i + k] ?? "") !== expectedCanons[k]) {
604
+ ok = false;
605
+ break;
606
+ }
607
+ }
608
+ if (ok)
609
+ matches.push(i);
610
+ if (matches.length > 1)
611
+ break;
612
+ }
613
+ if (matches.length === 1) {
614
+ healed = { from: matches[0], to: matches[0] + servedLen - 1 };
615
+ }
616
+ }
617
+ }
516
618
  }
517
- if (endPositions.length === 0) {
518
- problems.push(`remove_to "${endHash}" has no served position`);
619
+ if (!healed) {
620
+ const hasServed = served.some((h) => h !== null);
621
+ const startInFile = fileHashes.includes(startHash);
622
+ const endInFile = fileHashes.includes(endHash);
623
+ if (hasServed && (!startInFile || !endInFile)) {
624
+ const startCanon = getCanonForHash(startHash);
625
+ const endCanon = getCanonForHash(endHash);
626
+ if (startCanon !== undefined && endCanon !== undefined) {
627
+ const startMatches = [];
628
+ const endMatches = [];
629
+ for (let i = 0; i < fileLines.length; i++) {
630
+ if (canon(fileLines[i] ?? "") === startCanon)
631
+ startMatches.push(i);
632
+ if (canon(fileLines[i] ?? "") === endCanon)
633
+ endMatches.push(i);
634
+ if (startMatches.length > 1 && endMatches.length > 1)
635
+ break;
636
+ }
637
+ if (startMatches.length === 1 && endMatches.length === 1) {
638
+ const s = startMatches[0];
639
+ const e = endMatches[0];
640
+ const healedFrom = Math.min(s, e);
641
+ const healedTo = Math.max(s, e);
642
+ if (healedTo - healedFrom + 1 === currentLen) {
643
+ let interiorOk = true;
644
+ if (currentLen > 2) {
645
+ const healedCanons = [];
646
+ for (let k = 0; k < currentLen; k++)
647
+ healedCanons.push(canon(fileLines[healedFrom + k] ?? ""));
648
+ let count = 0;
649
+ for (let i = 0; i <= fileLines.length - currentLen; i++) {
650
+ let ok = true;
651
+ for (let k = 0; k < currentLen; k++)
652
+ if (canon(fileLines[i + k] ?? "") !== healedCanons[k]) {
653
+ ok = false;
654
+ break;
655
+ }
656
+ if (ok)
657
+ count++;
658
+ if (count > 1)
659
+ break;
660
+ }
661
+ if (count !== 1)
662
+ interiorOk = false;
663
+ }
664
+ if (interiorOk)
665
+ healed = { from: healedFrom, to: healedTo };
666
+ }
667
+ }
668
+ }
669
+ }
519
670
  }
520
- else if (endPositions.length > 1) {
521
- problems.push(`remove_to "${endHash}" was served at ${endPositions.length} positions`);
671
+ if (healed) {
672
+ from = healed.from;
673
+ to = healed.to;
674
+ isHealed = true;
522
675
  }
523
- throw new ServedRejectionError({
524
- code: "E_RANGE_UNVERIFIED",
525
- message: `[E_RANGE_UNVERIFIED] cannot verify range against served state${where}: ${problems.join("; ")}. ` +
526
- `Current range:
527
- ${echo}
528
- ${retryHint()}`,
529
- servedRows: echoRows,
530
- });
531
- }
532
- for (let i = from; i <= to; i++) {
533
- if (served[i] === null) {
676
+ else {
677
+ const problems = [];
678
+ if (startPositions.length === 0) {
679
+ problems.push(`remove_from "${startHash}" has no served position`);
680
+ }
681
+ else if (startPositions.length > 1) {
682
+ problems.push(`remove_from "${startHash}" was served at ${startPositions.length} positions`);
683
+ }
684
+ if (endPositions.length === 0) {
685
+ problems.push(`remove_to "${endHash}" has no served position`);
686
+ }
687
+ else if (endPositions.length > 1) {
688
+ problems.push(`remove_to "${endHash}" was served at ${endPositions.length} positions`);
689
+ }
534
690
  throw new ServedRejectionError({
535
- code: "E_RANGE_UNSERVED",
536
- message: `[E_RANGE_UNSERVED] line ${i + 1}${where} was never served.\nCurrent range:\n${echo}\n${retryHint()}`,
537
- firstOffendingLine: i + 1,
691
+ code: "E_RANGE_UNVERIFIED",
692
+ message: `[E_RANGE_UNVERIFIED] cannot verify range against served state${where}: ${problems.join("; ")}. ` +
693
+ `No served span matched the current range (${currentLen} lines). ` +
694
+ `A full read will re-sync the served mirror — the echoed range below is current content, ` +
695
+ `but retrying without re-reading cannot clear a stale duplicate outside the echoed window.\n` +
696
+ `Current range:\n${echo}`,
538
697
  servedRows: echoRows,
539
698
  });
540
699
  }
541
700
  }
542
- const servedLen = to - from + 1;
543
- if (servedLen !== currentLen) {
544
- throw new ServedRejectionError({
545
- code: "E_RANGE_STALE",
546
- message: `[E_RANGE_STALE] served span (${servedLen} lines) no longer matches current range (${currentLen} lines)${where}.\nCurrent range:\n${echo}\n${retryHint()}`,
547
- firstOffendingLine: startLine,
548
- servedRows: echoRows,
549
- });
701
+ if (isHealed) {
702
+ for (let k = 0; k < currentLen; k++) {
703
+ const servedHash = served[from + k];
704
+ if (servedHash === null)
705
+ continue;
706
+ const expectedCanon = getCanonForHash(servedHash);
707
+ const actualCanon = canon(fileLines[from + k] ?? "");
708
+ if (expectedCanon !== undefined && expectedCanon !== actualCanon) {
709
+ const offendingLine = from + k + 1;
710
+ throw new ServedRejectionError({
711
+ code: "E_RANGE_STALE",
712
+ message: `[E_RANGE_STALE] line ${offendingLine}${where} differs from what was served.\nCurrent range:\n${echo}\n${retryHint()}`,
713
+ firstOffendingLine: offendingLine,
714
+ servedRows: echoRows,
715
+ });
716
+ }
717
+ }
550
718
  }
551
- for (let k = 0; k < servedLen; k++) {
552
- if (served[from + k] !== fileHashes[startLine - 1 + k]) {
553
- const offendingLine = startLine + k;
554
- throw new ServedRejectionError({
555
- code: "E_RANGE_STALE",
556
- message: `[E_RANGE_STALE] Line ${offendingLine}${where} differs from what you were served — the file changed on disk since it was read. Current range:\n${echo}\n${retryHint()}`,
557
- firstOffendingLine: offendingLine,
558
- servedRows: echoRows,
559
- });
719
+ else {
720
+ for (let i = from; i <= to; i++) {
721
+ if (served[i] === null) {
722
+ throw new ServedRejectionError({
723
+ code: "E_RANGE_UNSERVED",
724
+ message: `[E_RANGE_UNSERVED] line ${i + 1}${where} was never served.\nCurrent range:\n${echo}\n${retryHint()}`,
725
+ firstOffendingLine: i + 1,
726
+ servedRows: echoRows,
727
+ });
728
+ }
729
+ }
730
+ const servedLen = to - from + 1;
731
+ if (servedLen !== currentLen) {
732
+ let lenHealed = false;
733
+ const expectedCanons = [];
734
+ let canBuild = true;
735
+ for (let k = 0; k < servedLen; k++) {
736
+ const h = served[from + k];
737
+ if (h === null) {
738
+ canBuild = false;
739
+ break;
740
+ }
741
+ const c = getCanonForHash(h);
742
+ if (c === undefined) {
743
+ canBuild = false;
744
+ break;
745
+ }
746
+ expectedCanons.push(c);
747
+ }
748
+ if (canBuild) {
749
+ let matches = 0;
750
+ for (let i = 0; i <= fileLines.length - servedLen; i++) {
751
+ let ok = true;
752
+ for (let k = 0; k < servedLen; k++)
753
+ if (canon(fileLines[i + k] ?? "") !== expectedCanons[k]) {
754
+ ok = false;
755
+ break;
756
+ }
757
+ if (ok)
758
+ matches++;
759
+ if (matches > 1)
760
+ break;
761
+ }
762
+ if (matches === 1)
763
+ lenHealed = true;
764
+ }
765
+ if (!lenHealed) {
766
+ throw new ServedRejectionError({
767
+ code: "E_RANGE_STALE",
768
+ message: `[E_RANGE_STALE] served span (${servedLen} lines) no longer matches current range (${currentLen} lines)${where}.\nCurrent range:\n${echo}\n${retryHint()}`,
769
+ firstOffendingLine: startLine,
770
+ servedRows: echoRows,
771
+ });
772
+ }
773
+ }
774
+ for (let k = 0; k < servedLen; k++) {
775
+ if (served[from + k] !== fileHashes[startLine - 1 + k]) {
776
+ const offendingLine = startLine + k;
777
+ throw new ServedRejectionError({
778
+ code: "E_RANGE_STALE",
779
+ message: `[E_RANGE_STALE] line ${offendingLine}${where} differs from what was served.\nCurrent range:\n${echo}\n${retryHint()}`,
780
+ firstOffendingLine: offendingLine,
781
+ servedRows: echoRows,
782
+ });
783
+ }
560
784
  }
561
785
  }
562
786
  }
@@ -694,6 +918,17 @@ export function applyEdit(content, edit, signal, precomputedHashes, filePath, se
694
918
  resolved = correctedResult.resolved;
695
919
  }
696
920
  if (served) {
921
+ const startLineEcho = resolved.hash_bounds[0].line;
922
+ const rawEcho = findEditHashEcho(edit.content_lines, served, startLineEcho);
923
+ let echo = rawEcho;
924
+ if (!echo)
925
+ echo = findEditHashEcho(resolved.content_lines, served, startLineEcho);
926
+ if (!echo)
927
+ echo = findEditHashEcho(prefixFixed.content_lines, served, startLineEcho);
928
+ if (echo) {
929
+ const msg = `[E_EDIT_HASH_ECHO] Refused edit to ${filePath ?? "(unknown file)"}: replacement line ${echo.k} begins with the exact ${echo.hash}${HASH_SEP} anchor served for this session, path, and range-relative line. Remove the copied anchors and retry. Nothing was written.`;
930
+ throw new EditHashEchoError(msg, []);
931
+ }
697
932
  const startAnchor = resolved.hash_bounds[0];
698
933
  const endAnchor = resolved.hash_bounds[1];
699
934
  verifyServedRange({
@@ -67,6 +67,14 @@ function hashAt(idx) {
67
67
  }
68
68
  return hash;
69
69
  }
70
+ const hashToCanon = new Map();
71
+ export function rememberHashCanon(hash, canonText) {
72
+ if (!hashToCanon.has(hash))
73
+ hashToCanon.set(hash, canonText);
74
+ }
75
+ export function getCanonForHash(hash) {
76
+ return hashToCanon.get(hash);
77
+ }
70
78
  export const HL_PREFIX_PLUS_RE = new RegExp(`^\\+${HASH_CLASS}│`);
71
79
  export const HL_PREFIX_MINUS_RE = new RegExp(`^-(?:${HASH_CLASS}│| {${ANCHOR_LEN}}│)`);
72
80
  export const HL_BARE_PREFIX_RE = new RegExp(`^\\s*(${HASH_CLASS})│`);
@@ -122,7 +130,9 @@ export function lineHashesPure(content) {
122
130
  for (let i = 0; i < lines.length; i++) {
123
131
  const c = getCanon(canonCache, lines[i]);
124
132
  const baseIdx = (xxh32(c) >>> 14) % HASH_SPACE;
125
- hashes[i] = assignHash(used, baseIdx, hint);
133
+ const h = assignHash(used, baseIdx, hint);
134
+ hashes[i] = h;
135
+ rememberHashCanon(h, c);
126
136
  }
127
137
  return hashes;
128
138
  }
@@ -223,6 +233,7 @@ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes
223
233
  const newIdx = candidates.splice(pos, 1)[0];
224
234
  newHashes[newIdx] = entry.hash;
225
235
  markUsed(entry.hash);
236
+ rememberHashCanon(entry.hash, getCanon(canonCache, oldLines[entry.index]));
226
237
  }
227
238
  const removedByContent = new Map();
228
239
  for (const entry of removedEntries) {
@@ -240,15 +251,19 @@ export function mapStableHashes(oldContent, oldHashes, newContent, removedHashes
240
251
  const queue = removedByContent.get(getCanon(canonCache, newLines[i]));
241
252
  if (!queue || queue.pos >= queue.hashes.length)
242
253
  continue;
243
- newHashes[i] = queue.hashes[queue.pos];
254
+ const h = queue.hashes[queue.pos];
255
+ newHashes[i] = h;
244
256
  queue.pos += 1;
257
+ rememberHashCanon(h, getCanon(canonCache, newLines[i]));
245
258
  }
246
259
  for (let i = 0; i < newLines.length; i++) {
247
260
  if (newHashes[i])
248
261
  continue;
249
262
  const c = getCanon(canonCache, newLines[i]);
250
263
  const baseIdx = (xxh32(c) >>> 14) % HASH_SPACE;
251
- newHashes[i] = assignHash(used, baseIdx, hint);
264
+ const h = assignHash(used, baseIdx, hint);
265
+ newHashes[i] = h;
266
+ rememberHashCanon(h, c);
252
267
  }
253
268
  return newHashes;
254
269
  }
@@ -7,4 +7,4 @@ export { CANON_VERSION, ANCHOR_LEN, HASH_SEP, HASH_SPACE, HASH_PROBE_STRIDE, MAX
7
7
  export { lineHashes } from "./hash.js";
8
8
  export { parseHashRef, parseText } from "./parse.js";
9
9
  export { resEdit } from "./anchor-pipeline.js";
10
- export { applyEdit, fmtRegion, changedRange, buildIdx, ServedRejectionError, AnchorMismatchError, isServedRejection, isAnchorMismatch, verifyServedRange, buildRangeEcho, fmtServedRows, } from "./anchor-pipeline.js";
10
+ export { applyEdit, fmtRegion, changedRange, buildIdx, ServedRejectionError, AnchorMismatchError, EditHashEchoError, findEditHashEcho, isServedRejection, isAnchorMismatch, verifyServedRange, buildRangeEcho, fmtServedRows, } from "./anchor-pipeline.js";
package/lib/prompts.js CHANGED
@@ -6,19 +6,22 @@
6
6
  * followed by tight bullets.
7
7
  * @module dsh-better-edit/prompts
8
8
  */
9
- export const EDIT_DESCRIPTION = "Edit a range of lines in a text file, targeted by the 3-char HASH anchors from read output. " +
10
- 'Use { "path": "file.ts", "edits": [[remove_from, remove_to, replacement_text], ...] } — path is the file to edit (or null to infer from anchors), edits is an array of [remove_from, remove_to, replacement_text] tuples. ' +
11
- "remove_from and remove_to must each be a BARE 3-character hash: copy only the hash from the " +
12
- 'leftmost column of a read row (row `ve7│function hello() {` means `"remove_from": "ve7"`). ' +
13
- "Never pass the line content, a code line, or a paragraph into these fields. The path is hoisted to the payload root so every edit in one call targets the same file; a length-1 edits array is a single edit.";
9
+ export const EDIT_DESCRIPTION = "Edit a range of lines in a text file with `{ \"path\": path, \"edits\": [[remove_from, remove_to, replacement_text], ...] }`. " +
10
+ "`path` is the file path or `null`. `read` returns `HASH\u2502content` (e.g. `wUp\u2502 \"site\": {`) \u2014 for `edit`, " +
11
+ "`remove_from`/`remove_to` are HASH anchors (bare 3-char value before `\u2502`, e.g. \"wUp\", \"AU6\"), never `HASH\u2502content` or line content. " +
12
+ "`replacement_text` is bare content without `HASH\u2502`, lines joined by \\n (e.g. \" \\\"site\\\": {\\n \\\"class\\\": SiteScraper,\"); use \"\" to delete. " +
13
+ "Example: read shows `wUp\u2502 \"site\": {` + `AU6\u2502 \"name\": \"old\",` \u2192 edit " +
14
+ "`{\"path\":\"scrape.py\",\"edits\":[[\"wUp\",\"AU6\",\" \\\"site\\\": {\\n \\\"class\\\": SiteScraper,\"]]}`. " +
15
+ "Edits in one call apply atomically; after success reuse `HASH\u2502content` from the returned diff for the next edit (no re-read needed). On failure follow the error hint.";
14
16
  export const EDIT_GUIDANCE = {
15
- intro: "Edit a range of lines via a bare 3-char HASH anchor — payload is { path, edits: [[hash,hash,text]] } (single-file atomic, null path infers).",
17
+ intro: "Edit a range of lines via a bare 3-char HASH anchor \u2014 payload is { path, edits: [[hash,hash,text]] } (single-file atomic, null path infers).",
16
18
  lines: [
17
- "`edit`: payload is { \"path\": \"file.ts\"|null, \"edits\": [[remove_from, remove_to, replacement_text], ...] } — path at root, each item is a 3-position tuple with bare hashes (`ve7`, not `ve7│function…`). A single line uses the same hash in both fields.",
18
- "`edit`: replacement_text is byte-exact for the whole range — every line inside it you do not reproduce byte-exact is deleted, and leading whitespace is preserved exactly.",
19
- "`edit`: `\\n` is a line break, so a range ending on a blank line must end replacement_text with `\\n` and a non-blank last line must not; a blank-line run is one `\\n` per blank line.",
20
- "`edit`: the post-edit diff rows carry fresh anchors for follow-ups. A stale or never-served range is hard-rejected (`[E_RANGE_STALE]` / `[E_RANGE_UNSERVED]`); copy the echoed rows and retry — only tool-served rows count.",
21
- "`edit`: multiple edits to the same file in one call are atomic (all-or-nothing): if any tuple fails — stale, ambiguous, never-served — nothing is written and the failing tuple's current range is served back. Prefer one edit per call unless you have independent ranges.",
19
+ "`edit`: `HASH` vs `HASH\u2502content` \u2014 `HASH` is the bare 3-char (e.g. \"wUp\"), `HASH\u2502content` is the full line from `read`/`diff` (e.g. `wUp\u2502 \"site\": {`); never mix them.",
20
+ "`edit`: get `remove_from`/`remove_to` by copying only the 3 chars before `\u2502` from `read` output \u2014 never include `\u2502` or content after it.",
21
+ "`edit`: `replacement_text` is plain file content without `HASH\u2502` \u2014 e.g. \" \\\"site\\\": {\\n \\\"class\\\": SiteScraper,\" \u2014 never prefix lines with `HASH\u2502`.",
22
+ "`edit`: every `\\n` in `replacement_text` separates lines; mirror trailing blank lines explicitly (use \"\" to delete a range).",
23
+ "`edit`: after a successful edit the returned diff shows fresh anchors (`HASH\u2502content`) \u2014 copy new `HASH` values from there for the next edit; no need to re-read.",
24
+ "`edit`: `remove_from`/`remove_to` are inclusive; batch multiple edits to the same file only when independent \u2014 they apply atomically (fail \u2192 nothing written).",
22
25
  ],
23
26
  };
24
27
  export const READ_DESCRIPTION = "Read a text file; each line returned as HASH│content with a 3-char alphanumeric hash. " +
@@ -85,6 +85,13 @@ export declare class AnchorMismatchError extends Error {
85
85
  constructor(message: string, servedRows: ServedRow[]);
86
86
  }
87
87
  export declare function isAnchorMismatch(error: unknown): error is AnchorMismatchError;
88
+ export declare function findEditHashEcho(replacementLines: string[], served: readonly (string | null)[], startLine: number): {
89
+ k: number;
90
+ hash: string;
91
+ } | undefined;
92
+ export declare class EditHashEchoError extends AnchorMismatchError {
93
+ constructor(message: string, servedRows?: ServedRow[]);
94
+ }
88
95
  export declare function buildRangeEcho(startLine: number, endLine: number, fileHashes: string[]): ServedRow[];
89
96
  export declare function fmtServedRows(rows: ServedRow[], fileLines: string[]): string;
90
97
  export declare function verifyServedRange(args: {
@@ -16,6 +16,8 @@ export declare const HASH_SEP = "\u2502";
16
16
  export declare const HASH_SPACE: number;
17
17
  export declare const MAX_HASH_LINES: number;
18
18
  export declare const HASH_PROBE_STRIDE: number;
19
+ export declare function rememberHashCanon(hash: string, canonText: string): void;
20
+ export declare function getCanonForHash(hash: string): string | undefined;
19
21
  export declare const HL_PREFIX_PLUS_RE: RegExp;
20
22
  export declare const HL_PREFIX_MINUS_RE: RegExp;
21
23
  export declare const HL_BARE_PREFIX_RE: RegExp;
@@ -9,5 +9,5 @@ export { parseHashRef, parseText } from "./parse.js";
9
9
  export type { Anchor } from "./parse.js";
10
10
  export { resEdit } from "./anchor-pipeline.js";
11
11
  export type { HEdit, HTEdit, NEdit, BDup, AutoFix } from "./anchor-pipeline.js";
12
- export { applyEdit, fmtRegion, changedRange, buildIdx, ServedRejectionError, AnchorMismatchError, isServedRejection, isAnchorMismatch, verifyServedRange, buildRangeEcho, fmtServedRows, } from "./anchor-pipeline.js";
12
+ export { applyEdit, fmtRegion, changedRange, buildIdx, ServedRejectionError, AnchorMismatchError, EditHashEchoError, findEditHashEcho, isServedRejection, isAnchorMismatch, verifyServedRange, buildRangeEcho, fmtServedRows, } from "./anchor-pipeline.js";
13
13
  export type { ServedRow, ResolvedRange, ServedCode, } from "./anchor-pipeline.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-better-edit",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "description": "Hash-anchored read/edit/undo_last_edit tools for DeepSeek Harness (dsh). Every line gets a unique 3-char hash (A-Za-z0-9) that stays stable across edits; stale or ambiguous anchors are rejected, never fuzzy-matched. Undo persists across restarts.",
6
6
  "main": "lib/index.js",
@@ -63,7 +63,7 @@
63
63
  "node": "^22.19.0 || >=24.0.0"
64
64
  },
65
65
  "scripts": {
66
- "prepare": "tsc -p tsconfig.json",
66
+ "prepare": "tsc -p tsconfig.json && husky",
67
67
  "build": "tsc -p tsconfig.json",
68
68
  "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
69
69
  "test": "vitest run",
@@ -71,9 +71,17 @@
71
71
  "prepublishOnly": "npm run typecheck && npm test && node scripts/assert-tagged.mjs",
72
72
  "benchmark": "node benchmark/run.mjs",
73
73
  "postpublish": "node scripts/tag-current.mjs",
74
- "release": "node scripts/release.mjs"
74
+ "release": "node scripts/release.mjs",
75
+ "lint": "biome check .",
76
+ "lint:fix": "biome check --write .",
77
+ "format": "biome check --write .",
78
+ "format:check": "biome check .",
79
+ "test:coverage": "vitest run --coverage"
75
80
  },
76
81
  "devDependencies": {
82
+ "@biomejs/biome": "^2.1.0",
83
+ "@commitlint/cli": "^21.2.2",
84
+ "@commitlint/config-conventional": "^21.2.2",
77
85
  "@deepseek-ai/cordis": "^4.0.1",
78
86
  "@deepseek-ai/dsh-agent": "0.1.0-rc.6",
79
87
  "@deepseek-ai/dsh-fs": "0.1.0-rc.6",
@@ -81,9 +89,15 @@
81
89
  "@deepseek-ai/dsh-sandbox": "^0.1.0-rc.6",
82
90
  "@deepseek-ai/dsh-session": "0.1.0-rc.6",
83
91
  "@deepseek-ai/dsh-tools": "0.1.0-rc.6",
92
+ "@semantic-release/changelog": "^7.0.0",
93
+ "@semantic-release/git": "^11.0.1",
94
+ "@semantic-release/github": "^12.0.9",
84
95
  "@types/node": "^24.0.0",
85
96
  "@vitest/coverage-v8": "^4.1.10",
97
+ "conventional-changelog-conventionalcommits": "^8.0.0",
98
+ "husky": "^9.1.7",
86
99
  "js-tiktoken": "1.0.21",
100
+ "semantic-release": "^25.0.9",
87
101
  "typescript": "^5.8.0",
88
102
  "vitest": "^4.1.8"
89
103
  }