dsh-better-edit 1.2.0 → 1.2.1

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
@@ -11,6 +11,31 @@ All notable changes to this project will be documented in this file.
11
11
 
12
12
  ## [Unreleased]
13
13
 
14
+ ## [1.2.1] - 2026-11-04
15
+
16
+ ### Bug Fixes
17
+
18
+ * **edit-undo:** derive undo-summary counts from the source line multisets, not the rendered rows, so a collapsed deletion reports the same restored-line count as an expanded one — port of `pi-better-edit@665a05d` (#96) (#103)
19
+ * **drift:** key drift-notice episodes on the drifted line's rebased position, so a duplicated anchor no longer silences a distinct line and a lease rotation no longer re-notices one (#98) (#103)
20
+ * **mutation:** retire an edit's and an undo's freed anchors after the write, and commit the undo's retirement with its restore transaction — a failed write no longer leaves live anchors marked dead (#98) (#103)
21
+ * **drift:** namespace drift-episode keys outside the anchor alphabet, so a stale pre-upgrade hash can never suppress a fresh drift notice; the store reader accepts both grammars (#105)
22
+ * **mutation:** keep a landed edit landed when post-write retirement faults — warn and continue instead of throwing for bytes already on disk (#105)
23
+ * **edit-undo:** map anchor-space exhaustion on the undo rehash to the typed `E_LARGE_FILE` refusal with promotion retry, mirroring the edit path (#105)
24
+
25
+ ### Code Refactoring
26
+
27
+ * **errors:** retire the dead `tombstone` range cause and speak one vocabulary for the freed-hash concept — the rename to upstream's name is declined in ADR-0028 (#97) (#103)
28
+
29
+ ### Tests
30
+
31
+ * **edit:** pin the `{file, edits}` wire shape against third-party shape adapters, and pin duplicate-line occurrence counting in the undo summary (#100) (#103)
32
+ * **arch:** pin the install surface (one built entry through `main`/`exports`, the tarball shipping the declared bundle patch, fail-loud `prepare`/`prepublishOnly`) and fault-inject the undo restore transaction so its all-or-nothing claim rests on a test (#101) (#103)
33
+
34
+ ### Documentation
35
+
36
+ * **absorb:** close the `0925f1a`..`0b1934c` range — all 19 upstream commits carry a disposition (five tickets ported or adapted: #96, #97, #98, #100, #101; three declined: #97's rename half, #100's typebox peer, #101's bundle; #102 confirms the release-ledger defect is absent), and eleven docs/deps/pi-lens/release/merge commits are deliberately not absorbed. No downstream version bump rides the absorb; the cursor moves to `0b1934c` (#102) (#103)
37
+ * **release:** confirm upstream's ledger-clearing defect cannot occur here — the gate has no `clear` subcommand and the promotion plugin empties `[Unreleased]` after promoting it (#102) (#103)
38
+
14
39
  ## [1.2.0] - 2026-10-29
15
40
 
16
41
  ### Features
package/lib/hash-store.js CHANGED
@@ -22,7 +22,7 @@ import { hashStorePath } from "./store-tenancy.js";
22
22
  import { onStoreOpen, setStoresGetter } from "./store-lifecycle.js";
23
23
  import { workspaceCwd } from "./workspace-context.js";
24
24
  import { errCode, splitLines } from "./utils.js";
25
- import { initHasher, HASH_RE } from "./hashline/hash-assign.js";
25
+ import { initHasher, HASH_CLASS, HASH_RE } from "./hashline/hash-assign.js";
26
26
  import { HASH_STORE_VERSION, HASH_STORE_BUSY_TIMEOUT, SERVED_TTL_MS } from "./constants.js";
27
27
  import { DomainError } from "./domain-errors.js";
28
28
  import { createSnapshotStore, isValidHashList, reportVacuum, vacuumSnapshots as runVacuumSnapshots, } from "./snapshot-store/index.js";
@@ -505,6 +505,15 @@ function buildStore(db, storePath) {
505
505
  };
506
506
  return { db, stmts };
507
507
  }
508
+ /**
509
+ * Namespace for drift-episode keys in a served-reported set. The set historically stored bare
510
+ * anchor hashes (`HASH_RE`); a position-encoded episode key shares the hash alphabet, so it
511
+ * carries a prefix outside ALPH to keep the two domains disjoint. `driftEpisodeKey`
512
+ * (session-view) is the sole encoder; the reader below accepts both grammars so a namespaced
513
+ * mark survives the store round-trip instead of being dropped on load.
514
+ */
515
+ export const DRIFT_EPISODE_PREFIX = "#";
516
+ export const DRIFT_EPISODE_RE = new RegExp(`^${DRIFT_EPISODE_PREFIX}${HASH_CLASS}$`);
508
517
  /** Wire the domain methods over the prepared statements. */
509
518
  function makeDomainStore(stmts, snapshotStore, lineageStore, db) {
510
519
  /**
@@ -728,7 +737,7 @@ function makeDomainStore(stmts, snapshotStore, lineageStore, db) {
728
737
  const parsed = JSON.parse(raw);
729
738
  if (!Array.isArray(parsed))
730
739
  return new Set();
731
- return new Set(parsed.filter((h) => typeof h === "string" && HASH_RE.test(h)));
740
+ return new Set(parsed.filter((h) => typeof h === "string" && (HASH_RE.test(h) || DRIFT_EPISODE_RE.test(h))));
732
741
  }
733
742
  catch (error) {
734
743
  return new Set();
@@ -698,7 +698,8 @@ export function verifyServedRange(args) {
698
698
  ? `\n${paginationHint(startLine + echoRows.length, totalLen - echoRows.length)}`
699
699
  : "";
700
700
  const echo = fmtServedRows(echoRows, fileLines) + tail;
701
- // Tombstone check for boundaries (whole-span S@3==S@3)
701
+ // Retired-anchor check for boundaries (whole-span S@3==S@3) — the freed-hash concept, named
702
+ // `retired` here since ADR-0013 (ADR-0028 records the vocabulary ruling).
702
703
  // If hash was freed in this epoch, any reuse is stale even at same pos+same canon.
703
704
  // Early reject checks canon change to avoid false positive on same line re-read.
704
705
  if (retiredSet.has(startHash) || retiredSet.has(endHash)) {
@@ -861,7 +862,7 @@ export function verifyServedRange(args) {
861
862
  }
862
863
  }
863
864
  }
864
- // Tombstone interior check (whole-span) — gated on canon inequality (fail-closed only for different canon)
865
+ // Retired-anchor interior check (whole-span) — gated on canon inequality (fail-closed only for different canon)
865
866
  for (let k = 0; k < servedLen; k++) {
866
867
  const h = fileHashes[startLine - 1 + k];
867
868
  if (h && retiredSet.has(h)) {
@@ -15,7 +15,7 @@ import { loadHashStore } from "../hash-store.js";
15
15
  import { loadConfig } from "../store-config.js";
16
16
  import { canon } from "../hashline/hash-assign.js";
17
17
  import { normFromText } from "../file-reader.js";
18
- import { scanDrift, loadServed, loadServedCanons, loadRetiredAnchors, retireAnchors, } from "../session-view.js";
18
+ import { scanDrift, loadServed, loadServedCanons, loadRetiredAnchors } from "../session-view.js";
19
19
  import { applyEdit, resEdit, parseHashRef, } from "../hashline/anchor-pipeline.js";
20
20
  import { lineHashes } from "../hashline/hash.js";
21
21
  import { AnchorSpaceExhaustedError, HASH_SPACE } from "../hashline/hash-assign.js";
@@ -709,7 +709,9 @@ export async function runFileEdits(io, items, opts) {
709
709
  removedHashes: lastApplied.removedHashes,
710
710
  }, undefined, true, recomputed, emptyRetired));
711
711
  }
712
- await retireAnchors(opts.sessionKey, absolutePath, newlyRetired);
712
+ // WHY (#98, port of upstream CAND-3): retirement is returned to the caller and committed
713
+ // AFTER the write. Doing it here — inside the read-only apply phase — let a failed write
714
+ // leave anchors retired for a file that still holds them.
713
715
  }
714
716
  if (hadUtf8DecodeErrors) {
715
717
  warnings.push("Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.");
@@ -756,6 +758,7 @@ export async function runFileEdits(io, items, opts) {
756
758
  totalAddedLines,
757
759
  totalRemovedLines,
758
760
  driftNotice,
761
+ newlyRetired: [...newlyRetired],
759
762
  range: {
760
763
  startLine: unionStartLine,
761
764
  endLine: unionEndLine,
package/lib/mutation.js CHANGED
@@ -27,7 +27,7 @@ import { formatError } from "./domain-errors.js";
27
27
  import { canon } from "./hashline/hash-assign.js";
28
28
  import { fileSnap } from "./file-reader.js";
29
29
  import { toCwd } from "./paths.js";
30
- import { recordServedTruncated, scanDrift } from "./session-view.js";
30
+ import { recordServedTruncated, retireAnchors, scanDrift } from "./session-view.js";
31
31
  import { abortIf, splitLines } from "./utils.js";
32
32
  import { runFileEdits, resolveMissingPath } from "./mutation/engine.js";
33
33
  import { saveUndo } from "./undo-edit.js";
@@ -175,6 +175,32 @@ export async function execute(opts) {
175
175
  // Nothing to record, so nothing can fail: vacuously landed.
176
176
  return true;
177
177
  };
178
+ // WHY (#98, port of upstream CAND-3): the apply phase reports the anchors its edits freed, and
179
+ // this is where they are retired — after the write transaction landed. Retiring them inside the
180
+ // apply phase let a failed write leave a file's live anchors marked dead.
181
+ //
182
+ // Residual window (deliberately kept: fail-safe, do NOT "fix" by re-merging phases): if this
183
+ // retire call throws after the write landed, the freed anchors stay live for one session — the
184
+ // next use of one rejects loud (stale/probed hash) and the user re-reads. That is strictly safer
185
+ // than a retire that commits for a write which never happened; re-merging the phases reintroduces
186
+ // the torn state this ticket removed.
187
+ const retireFreedAnchors = async () => {
188
+ if (fileResult.newlyRetired.length === 0)
189
+ return;
190
+ try {
191
+ await retireAnchors(sessionKey, fileResult.absolutePath, fileResult.newlyRetired);
192
+ }
193
+ catch (error) {
194
+ // WHY (R1 review, #98): retirement is best-effort AFTER the landed write — a store fault here
195
+ // must never turn an applied edit into a thrown error. The freed anchors stay live for this
196
+ // session; the next use of one rejects loud (stale/probed hash) and the user re-reads.
197
+ const detail = error instanceof Error ? error.message : String(error);
198
+ console.warn("Failed to retire freed anchors after the edit landed:", error);
199
+ fileResult.warnings.push("WARNING: the edit applied and stands \u2014 nothing was rolled back \u2014 but the anchors it " +
200
+ `freed could not be retired for this session (${detail}). The next use of a freed anchor ` +
201
+ "will reject as stale; re-read the file to refresh.");
202
+ }
203
+ };
178
204
  const isSingleCall = items.length === 1 && fileResult.appliedCount + fileResult.noopCount === 1;
179
205
  if (isSingleCall) {
180
206
  if (fileResult.appliedCount === 0) {
@@ -201,6 +227,7 @@ export async function execute(opts) {
201
227
  signal,
202
228
  undoUnavailableMessage: (displayPath) => formatError("E_UNDO_UNAVAILABLE", { path: displayPath }),
203
229
  });
230
+ await retireFreedAnchors();
204
231
  const built = buildBatchResult([toSection()]);
205
232
  const serveLanded = await recordIfNeeded(built);
206
233
  return withServeNotice(built.content[0].text, serveLanded);
@@ -228,6 +255,7 @@ export async function execute(opts) {
228
255
  signal,
229
256
  undoUnavailableMessage: (displayPath) => formatError("E_UNDO_UNAVAILABLE", { path: displayPath, batch: true }),
230
257
  });
258
+ await retireFreedAnchors();
231
259
  }
232
260
  const built = buildBatchResult([toSection()]);
233
261
  const serveLanded = await recordIfNeeded(built);
@@ -22,8 +22,8 @@
22
22
  *
23
23
  * @module dsh-better-edit/session-view
24
24
  */
25
- import { HASH_RE, canon } from "./hashline/hash-assign.js";
26
- import { loadHashStore, loadServedStore, withStore, } from "./hash-store.js";
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";
27
27
  import { SERVED_ECHO_CAP } from "./constants.js";
28
28
  import { fmtServedRows } from "./hashline/anchor-pipeline.js";
29
29
  import { splitLines } from "./utils.js";
@@ -158,6 +158,18 @@ function sweepAndRetire(store, sessionKey, path, current, updated, rows) {
158
158
  store.upsertRetiredAnchors(sessionKey, path, JSON.stringify(merged));
159
159
  }
160
160
  }
161
+ /**
162
+ * Caller-owned transaction: append retired anchors for the session inside the caller's unit.
163
+ *
164
+ * WHY (#98, port of upstream CAND-3): the edit path and the undo path must commit their
165
+ * retirement together with the rest of the post-write store state, so a torn state (retired
166
+ * anchors without the revert, or a revert without its retirement) is unreachable. Callers pass
167
+ * the store they already hold inside `withStore`; `retireAnchors` below is the self-committing
168
+ * wrapper for callers with no surrounding unit.
169
+ */
170
+ export function retireAnchorsInStore(store, sessionKey, path, hashes) {
171
+ addRetiredAnchors(store, sessionKey, path, hashes);
172
+ }
161
173
  /** Keep freed anchors dead for this session until it has seen the whole file again. */
162
174
  export async function retireAnchors(sessionKey, path, hashes) {
163
175
  const additions = [...hashes];
@@ -165,7 +177,7 @@ export async function retireAnchors(sessionKey, path, hashes) {
165
177
  return;
166
178
  const store = await loadServedStore();
167
179
  withStore(() => {
168
- addRetiredAnchors(store, sessionKey, path, additions);
180
+ retireAnchorsInStore(store, sessionKey, path, additions);
169
181
  });
170
182
  }
171
183
  /**
@@ -314,7 +326,7 @@ export async function driftReported(sessionKey, path) {
314
326
  }
315
327
  export async function markDriftReported(sessionKey, path, hashes) {
316
328
  try {
317
- const valid = hashes.filter((hash) => HASH_RE.test(hash));
329
+ const valid = hashes.filter((hash) => HASH_RE.test(hash) || DRIFT_EPISODE_RE.test(hash));
318
330
  if (valid.length === 0)
319
331
  return;
320
332
  const store = await loadServedStore();
@@ -383,6 +395,34 @@ export function currentPositionOfDrifted(served, currentPositions, surviving, se
383
395
  return servedIndex + delta;
384
396
  }
385
397
  export const DRIFT_NOTICE_HEADING = "[USER] drift:";
398
+ /**
399
+ * WHY (#98, upstream CAND-9): the drift-notice episode identity is the drifted line's rebased
400
+ * position in the CURRENT file — not its anchor string. An anchor is a spelling, not an
401
+ * identity: one reported entry for a hash shared by two distinct lines silenced both
402
+ * (duplicate-hash collapse), and a lease rotation renamed the mirror anchor of an
403
+ * already-reported line, spuriously re-noticing it. The session's reported-set keeps storing
404
+ * strings (schema unchanged); this base-62 encoding of the position, carrying the
405
+ * `DRIFT_EPISODE_PREFIX` namespace so it can never equal a legacy bare-hash entry, is the KEY
406
+ * VALUE.
407
+ * Positions are bounded by `HASH_SPACE` (= |ALPH|^HASH_LEN, files larger cannot be hashed), so
408
+ * the encoding is injective over every reachable position. Injection is over POSITIONS, not over
409
+ * lines: two ambiguous duplicate-hash lines can rebase onto one position and therefore share one
410
+ * episode key, so one marker reports both (fail-open: content is still served, and it is strictly
411
+ * better than the old hash-only key, which silenced every line sharing the anchor). An out-of-file position (never
412
+ * shown, never marked) keys on "" — not a valid stored entry, always "not yet reported",
413
+ * matching the legacy behavior for unshown drift.
414
+ */
415
+ export function driftEpisodeKey(position) {
416
+ if (!Number.isInteger(position) || position < 0 || position >= HASH_SPACE)
417
+ return "";
418
+ let idx = position;
419
+ let out = "";
420
+ for (let j = 0; j < HASH_LEN; j++) {
421
+ out = ALPH[idx % ALPH.length] + out;
422
+ idx = Math.floor(idx / ALPH.length);
423
+ }
424
+ return DRIFT_EPISODE_PREFIX + out;
425
+ }
386
426
  /**
387
427
  * WHY (#68 hash-rotation vs content loss): probing + retired growth reassign
388
428
  * distinct hashes to identical duplicate lines across sequential edits, so a
@@ -473,9 +513,12 @@ export function computeDrift(input) {
473
513
  if (isRotatedSurvivor(p))
474
514
  continue;
475
515
  total++;
476
- if (!reported.has(servedHash))
477
- anyNotReported = true;
478
516
  const currentPos = currentPositionOfDrifted(served, currentPosOfHash, resultHashSet, p, range.delta);
517
+ // WHY (#98, upstream CAND-9): key the episode on the rebased position, never the anchor
518
+ // spelling — a shared anchor must not silence a distinct line, and a rotation must not
519
+ // re-notice one.
520
+ if (!reported.has(driftEpisodeKey(currentPos)))
521
+ anyNotReported = true;
479
522
  if (currentPos >= 0 && currentPos < resultHashes.length && currentPos < resultLines.length) {
480
523
  driftedPositions.push(currentPos);
481
524
  }
@@ -527,6 +570,8 @@ export async function scanDrift(input) {
527
570
  if (!result || result.allAlreadyReported)
528
571
  return result?.text;
529
572
  await recordServed(input.sessionKey, input.path, result.rows.map((row) => ({ position: row.position, hash: row.hash })), input.resultLines.length);
530
- await markDriftReported(input.sessionKey, input.path, result.rows.filter((row) => row.drifted).map((row) => row.hash));
573
+ // WHY (#98, upstream CAND-9): the episode key is the drifted row's rebased position, not its
574
+ // anchor hash (see `driftEpisodeKey`). The handle keeps its string[] storage contract.
575
+ await markDriftReported(input.sessionKey, input.path, result.rows.filter((row) => row.drifted).map((row) => driftEpisodeKey(row.position)));
531
576
  return result.text;
532
577
  }
package/lib/tool-undo.js CHANGED
@@ -6,19 +6,46 @@
6
6
  */
7
7
  import { defineTool } from "@deepseek-ai/dsh-tools";
8
8
  import { toLF, stripBOM, genDiff, restoreEndings } from "./edit-diff.js";
9
- import { cntDiff, splitLines, codeOf } from "./utils.js";
9
+ import { visLines, splitLines, codeOf } from "./utils.js";
10
10
  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 { canon, contentChecksum } from "./hashline/hash-assign.js";
14
+ import { AnchorSpaceExhaustedError, HASH_SPACE, canon, contentChecksum, } 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, recordServedTruncated, retireAnchors } from "./session-view.js";
18
+ import { loadAnchorReservations, loadServedStore, recordServedTruncated, retireAnchorsInStore, } 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
+ }
26
+ /**
27
+ * Anchor-space exhaustion guard mirrored from the edit path (`retryLineHashesWithPromotion` in
28
+ * src/mutation/engine.ts): clear this (session, path)'s retired anchors once to promote hash space
29
+ * and retry; a retry that still exhausts is a typed hard capacity refusal, never a raw probe error.
30
+ */
31
+ async function hashWithAnchorSpacePromotion(fn, onPromote) {
32
+ try {
33
+ return await fn();
34
+ }
35
+ catch (error) {
36
+ if (!isAnchorSpaceExhausted(error))
37
+ throw error;
38
+ await onPromote();
39
+ try {
40
+ return await fn();
41
+ }
42
+ catch (retryError) {
43
+ if (isAnchorSpaceExhausted(retryError))
44
+ throw new DomainError("E_LARGE_FILE", { limitKind: "hash-space", limit: HASH_SPACE });
45
+ throw retryError;
46
+ }
47
+ }
48
+ }
22
49
  /**
23
50
  * Register the `undo_last_edit` tool on the calling agent's scope.
24
51
  * @param _rootCtx - host context.
@@ -62,7 +89,6 @@ export function buildUndoTool(io, sandbox) {
62
89
  currentRaw = await io.readText(absolutePath, signal);
63
90
  }
64
91
  catch (error) {
65
- const message = error instanceof Error ? error.message : String(error);
66
92
  if (codeOf(error) === "E_NOT_FOUND") {
67
93
  await clearUndo(absolutePath);
68
94
  return formatError("E_UNDO_STALE", { path, reason: "deleted" });
@@ -77,19 +103,59 @@ export function buildUndoTool(io, sandbox) {
77
103
  const currentNormalized = toLF(currentStripped);
78
104
  // Per-session reservations: retired/ served are per (session, path) per ADR-0013; file snapshots stay global last-writer-wins
79
105
  const reservations = await loadAnchorReservations(sessionKey, absolutePath);
80
- const currentHashes = await lineHashes(currentNormalized, absolutePath, undefined, undefined, false, reservations.reservedHashes, reservations.retiredHashes);
81
- const retiredOriginalHashes = new Set(undo.hashes.filter((hash) => reservations.retiredHashes.has(hash)));
82
- const blockedRestoreHashes = new Set(reservations.reservedHashes);
83
- for (const hash of currentHashes)
84
- blockedRestoreHashes.add(hash);
85
- const restoredHashes = await lineHashes(undo.content, absolutePath, {
106
+ // Anchor-space promotion mirrors the edit path (src/mutation/engine.ts): on exhaustion,
107
+ // clear this (session, path)'s retired anchors to free hash space and retry once; a retry
108
+ // that still exhausts is a hard capacity refusal (E_LARGE_FILE hash-space). The in-memory
109
+ // reservation sets track the cleared store so the restore rehash below sees them too.
110
+ let reservedHashes = new Set(reservations.reservedHashes);
111
+ let retiredHashes = new Set(reservations.retiredHashes);
112
+ const promoteRetiredForAnchorSpace = async () => {
113
+ try {
114
+ const store = await loadServedStore();
115
+ store.clearRetiredAnchors(sessionKey, absolutePath);
116
+ try {
117
+ store.clearCards(sessionKey, absolutePath);
118
+ }
119
+ catch {
120
+ // Best-effort: card state is a cache; the retry proceeds without it.
121
+ }
122
+ }
123
+ catch {
124
+ // Best-effort: a store fault here must not fail the undo — the retry proceeds on the
125
+ // in-memory reservation state (ADR-0020 R2, promotion/wipe arm).
126
+ }
127
+ const served = new Set([...reservedHashes].filter((h) => !retiredHashes.has(h)));
128
+ retiredHashes = new Set();
129
+ reservedHashes = served;
130
+ };
131
+ 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, {
86
134
  content: undo.content,
87
135
  hashes: undo.hashes,
88
136
  removedHashes: retiredOriginalHashes,
89
- }, undefined, false, blockedRestoreHashes, reservations.retiredHashes);
90
- const diffResult = genDiff(undo.content, currentNormalized, 0, undefined, undo.hashes);
91
- const linesAddedByEdit = cntDiff(diffResult.diff, "+");
92
- const linesRemovedByEdit = cntDiff(diffResult.diff, "-");
137
+ }, undefined, false, new Set([...reservedHashes, ...currentHashes]), retiredHashes), promoteRetiredForAnchorSpace);
138
+ // WHY: #96 (pi-better-edit@665a05d, upstream #173) — the summary counts come from the
139
+ // WHY: source line multisets, never from the rendered projection: a deleted run past
140
+ // WHY: DIFF_REMOVED_CAP collapses behind a marker row at context 0, so counting `-` rows
141
+ // WHY: underreported the restored lines. A line the edit added is one present in the
142
+ // WHY: current file beyond its occurrence count in `undo.content`; a removed line is the
143
+ // WHY: converse. Collapsed and expanded projections therefore report identical counts.
144
+ const remainingUndoCounts = new Map();
145
+ for (const line of visLines(undo.content)) {
146
+ remainingUndoCounts.set(line, (remainingUndoCounts.get(line) ?? 0) + 1);
147
+ }
148
+ let linesAddedByEdit = 0;
149
+ for (const line of visLines(currentNormalized)) {
150
+ const remaining = remainingUndoCounts.get(line) ?? 0;
151
+ if (remaining > 0)
152
+ remainingUndoCounts.set(line, remaining - 1);
153
+ else
154
+ linesAddedByEdit++;
155
+ }
156
+ let linesRemovedByEdit = 0;
157
+ for (const remaining of remainingUndoCounts.values())
158
+ linesRemovedByEdit += remaining;
93
159
  const undoDiffResult = genDiff(currentNormalized, undo.content, 1, restoredHashes, currentHashes);
94
160
  const undoDiff = undoDiffResult.diff;
95
161
  const undoDenseRows = [];
@@ -98,22 +164,31 @@ export function buildUndoTool(io, sandbox) {
98
164
  }
99
165
  const restoredRange = changedRange(currentNormalized, undo.content);
100
166
  const restoredSet = new Set(restoredHashes);
101
- await retireAnchors(sessionKey, absolutePath, currentHashes.filter((hash) => !restoredSet.has(hash)));
167
+ // WHY (#98, port of upstream CAND-3): retirement waits for the write. Committing it
168
+ // before `writeText` let a failed revert leave anchors retired for a file that still
169
+ // holds them — a torn store state with no later read likely to notice.
170
+ const retiredByUndo = currentHashes.filter((hash) => !restoredSet.has(hash));
102
171
  try {
103
172
  await io.writeText(absolutePath, undo.bom + restoreEndings(undo.content, undo.originalEnding), signal, exec, sandboxPolicy);
104
173
  }
105
174
  catch (error) {
106
175
  throw sandbox.mapError(error, sandboxPolicy);
107
176
  }
108
- // The file is reverted; the store pair must move as ONE unit: the snapshot/lineage
109
- // adopt (`upsertSnapshot`) and the undo-pair clear (`deleteUndoPair`) are both-or-neither.
110
- // `withStore` routes both calls through the store's single re-entrant transaction owner
111
- // (the store was just loaded for this workspace, so `currentStore()` is that same handle).
112
- // Fail loud: a cleared pair over an un-adopted snapshot is a desync no later read/edit can see.
113
- const store = await loadHashStore();
177
+ // The file is reverted; the store state must move as ONE unit: the snapshot/lineage adopt
178
+ // (`upsertSnapshot`), the retirement of the anchors the revert freed, and the undo-pair
179
+ // clear (`deleteUndoPair`) are all-or-nothing. `withStore` routes every call through the
180
+ // store's single re-entrant transaction owner (the store was just loaded for this
181
+ // workspace, so `currentStore()` is that same handle). Fail loud: a cleared pair over an
182
+ // un-adopted snapshot, or a revert without its retirement, is a desync no later read or
183
+ // edit can see.
184
+ // SAFETY: loadHashStore returns the InternalHashStore
185
+ // (HashStore & ServedPersistence & LineageStore); its public return type is narrowed, and
186
+ // this unit needs the served face for the retirement that commits with the adopt.
187
+ const store = (await loadHashStore());
114
188
  try {
115
189
  withStore(() => {
116
190
  store.upsertSnapshot(absolutePath, contentChecksum(undo.content), splitLines(undo.content).length, restoredHashes, undo.content);
191
+ retireAnchorsInStore(store, sessionKey, absolutePath, retiredByUndo);
117
192
  store.deleteUndoPair(absolutePath);
118
193
  });
119
194
  }
@@ -65,7 +65,7 @@ export interface ServedRow {
65
65
  hash: string;
66
66
  }
67
67
  /** WHY: user-facing diagnosis carried as `details.cause` on range-family rejections. */
68
- export type RangeCause = "retirement" | "tombstone" | "never-served" | "served-range staleness" | "anchor staleness" | "served span";
68
+ export type RangeCause = "retirement" | "never-served" | "served-range staleness" | "anchor staleness" | "served span";
69
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";
70
70
  /**
71
71
  * Applied-tier warning codes. A `[W_*]` line reports an applied mutation;
@@ -122,6 +122,15 @@ export type InternalHashStore = HashStore & ServedPersistence & LineageStore;
122
122
  /** Load the store as served persistence — internal, for SessionView only. */
123
123
  export declare function loadServedStore(cwd?: string): Promise<ServedPersistence>;
124
124
  export declare function isCorruptionError(error: unknown): boolean;
125
+ /**
126
+ * Namespace for drift-episode keys in a served-reported set. The set historically stored bare
127
+ * anchor hashes (`HASH_RE`); a position-encoded episode key shares the hash alphabet, so it
128
+ * carries a prefix outside ALPH to keep the two domains disjoint. `driftEpisodeKey`
129
+ * (session-view) is the sole encoder; the reader below accepts both grammars so a namespaced
130
+ * mark survives the store round-trip instead of being dropped on load.
131
+ */
132
+ export declare const DRIFT_EPISODE_PREFIX = "#";
133
+ export declare const DRIFT_EPISODE_RE: RegExp;
125
134
  /**
126
135
  * Load (and cache) the hash store for the given cwd — or, when omitted, the
127
136
  * workspace active for this async execution (`withWorkspace`), falling back to
@@ -44,6 +44,11 @@ export interface FileEditResult {
44
44
  totalAddedLines: number;
45
45
  totalRemovedLines: number;
46
46
  driftNotice: string | undefined;
47
+ /**
48
+ * Anchors this edit freed, to be retired by the caller AFTER the write lands (upstream
49
+ * CAND-3, #98). This phase only reports them; it must never commit them.
50
+ */
51
+ newlyRetired: string[];
47
52
  range: ResolvedRange;
48
53
  }
49
54
  /**
@@ -22,7 +22,7 @@
22
22
  *
23
23
  * @module dsh-better-edit/session-view
24
24
  */
25
- import { type AnchorReservations } from "./hash-store.js";
25
+ import { type AnchorReservations, type ServedPersistence } from "./hash-store.js";
26
26
  import type { ServedRow, ResolvedRange } from "./hashline/anchor-pipeline.js";
27
27
  export { loadHashStore, loadServedStore, shutdownHashStore, withStore } from "./hash-store.js";
28
28
  export type { HashStore } from "./hash-store.js";
@@ -48,6 +48,16 @@ export declare function loadServed(sessionKey: string, path: string): Promise<(s
48
48
  export declare function loadAnchorReservations(sessionKey: string, path: string): Promise<AnchorReservations>;
49
49
  export declare function loadServedCanons(sessionKey: string, path: string): Promise<(string | null)[]>;
50
50
  export declare function loadRetiredAnchors(sessionKey: string, path: string): Promise<Set<string>>;
51
+ /**
52
+ * Caller-owned transaction: append retired anchors for the session inside the caller's unit.
53
+ *
54
+ * WHY (#98, port of upstream CAND-3): the edit path and the undo path must commit their
55
+ * retirement together with the rest of the post-write store state, so a torn state (retired
56
+ * anchors without the revert, or a revert without its retirement) is unreachable. Callers pass
57
+ * the store they already hold inside `withStore`; `retireAnchors` below is the self-committing
58
+ * wrapper for callers with no surrounding unit.
59
+ */
60
+ export declare function retireAnchorsInStore(store: ServedPersistence, sessionKey: string, path: string, hashes: Iterable<string>): void;
51
61
  /** Keep freed anchors dead for this session until it has seen the whole file again. */
52
62
  export declare function retireAnchors(sessionKey: string, path: string, hashes: Iterable<string>): Promise<void>;
53
63
  /** Full-file context for a complete read — when present and matching `rows`, the call is a full read. */
@@ -92,6 +102,24 @@ export declare function wipeServedState(sessionKey: string): Promise<void>;
92
102
  export declare function servedPositionsOf(served: (string | null)[], hash: string): number[];
93
103
  export declare function currentPositionOfDrifted(served: (string | null)[], currentPositions: Map<string, number>, surviving: Set<string>, servedIndex: number, delta: number): number;
94
104
  export declare const DRIFT_NOTICE_HEADING = "[USER] drift:";
105
+ /**
106
+ * WHY (#98, upstream CAND-9): the drift-notice episode identity is the drifted line's rebased
107
+ * position in the CURRENT file — not its anchor string. An anchor is a spelling, not an
108
+ * identity: one reported entry for a hash shared by two distinct lines silenced both
109
+ * (duplicate-hash collapse), and a lease rotation renamed the mirror anchor of an
110
+ * already-reported line, spuriously re-noticing it. The session's reported-set keeps storing
111
+ * strings (schema unchanged); this base-62 encoding of the position, carrying the
112
+ * `DRIFT_EPISODE_PREFIX` namespace so it can never equal a legacy bare-hash entry, is the KEY
113
+ * VALUE.
114
+ * Positions are bounded by `HASH_SPACE` (= |ALPH|^HASH_LEN, files larger cannot be hashed), so
115
+ * the encoding is injective over every reachable position. Injection is over POSITIONS, not over
116
+ * lines: two ambiguous duplicate-hash lines can rebase onto one position and therefore share one
117
+ * episode key, so one marker reports both (fail-open: content is still served, and it is strictly
118
+ * better than the old hash-only key, which silenced every line sharing the anchor). An out-of-file position (never
119
+ * shown, never marked) keys on "" — not a valid stored entry, always "not yet reported",
120
+ * matching the legacy behavior for unshown drift.
121
+ */
122
+ export declare function driftEpisodeKey(position: number): string;
95
123
  export interface DriftRow extends ServedRow {
96
124
  content: string;
97
125
  drifted: boolean;
@@ -3,7 +3,6 @@ export declare function normalizeFilePath(record: Record<string, unknown>): void
3
3
  export declare function splitLines(text: string): string[];
4
4
  export declare function visLines(text: string): string[];
5
5
  export declare function rejectUnknownFields(obj: Record<string, unknown>, allowed: Set<string>, label: string, hint?: string): void;
6
- export declare function cntDiff(diff: string, marker: "+" | "-"): number;
7
6
  export declare function abortIf(signal?: AbortSignal): void;
8
7
  export declare function errCode(error: unknown): string | undefined;
9
8
  export declare function lastNonEmptyIndex(lines: string[]): number;
package/lib/utils.js CHANGED
@@ -29,17 +29,6 @@ export function rejectUnknownFields(obj, allowed, label, hint) {
29
29
  });
30
30
  }
31
31
  }
32
- export function cntDiff(diff, marker) {
33
- if (!diff)
34
- return 0;
35
- let count = 0;
36
- for (const line of diff.split("\n")) {
37
- if (line.startsWith(marker) && !line.startsWith(`${marker}${marker}${marker}`)) {
38
- count += 1;
39
- }
40
- }
41
- return count;
42
- }
43
32
  export function abortIf(signal) {
44
33
  if (signal?.aborted)
45
34
  throw new Error("Operation aborted");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-better-edit",
3
- "version": "1.2.0",
3
+ "version": "1.2.1",
4
4
  "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.",
5
5
  "keywords": [
6
6
  "anchors",