dsh-better-edit 0.6.3 → 0.7.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.
@@ -21,7 +21,7 @@
21
21
  *
22
22
  * @module dsh-better-edit/session-view
23
23
  */
24
- import { HASH_RE } from "./hashline/hash-assign.js";
24
+ import { HASH_RE, canon } from "./hashline/hash-assign.js";
25
25
  import { loadHashStore, loadServedStore, withStore, } from "./hash-store.js";
26
26
  import { SERVED_ECHO_CAP } from "./constants.js";
27
27
  import { fmtServedRows } from "./hashline/anchor-pipeline.js";
@@ -92,9 +92,9 @@ export async function loadServed(sessionKey, path) {
92
92
  return store.getServed(sessionKey, path);
93
93
  }
94
94
  /** Anchors that must not be allocated while any session can still remember them. */
95
- export async function loadAnchorReservations(path) {
95
+ export async function loadAnchorReservations(sessionKey, path) {
96
96
  const store = await loadServedStore();
97
- return store.getAnchorReservations(path);
97
+ return store.getAnchorReservations(sessionKey, path);
98
98
  }
99
99
  export async function loadServedCanons(sessionKey, path) {
100
100
  const store = await loadServedStore();
@@ -119,12 +119,74 @@ function addRetiredAnchors(store, sessionKey, path, hashes) {
119
119
  }
120
120
  retired.add(hash);
121
121
  }
122
+ // Persist as legacy string array for backward compat; new entries with deathPos use object form via addRetiredEntries
122
123
  store.upsertRetiredAnchors(sessionKey, path, JSON.stringify([...retired]));
123
124
  }
125
+ function addRetiredEntries(store, sessionKey, path, entries) {
126
+ if (entries.length === 0)
127
+ return;
128
+ const existing = store.getRetiredEntries(sessionKey, path);
129
+ const seen = new Set(existing.map((e) => e.hash));
130
+ for (const e of entries) {
131
+ if (!HASH_RE.test(e.hash))
132
+ throw new TypeError(`Invalid retired hash: ${e.hash}`);
133
+ if (!seen.has(e.hash)) {
134
+ existing.push(e);
135
+ seen.add(e.hash);
136
+ }
137
+ }
138
+ store.upsertRetiredAnchors(sessionKey, path, JSON.stringify(existing));
139
+ }
124
140
  function displacedHashes(current, updated) {
125
141
  const remaining = new Set(updated.filter((hash) => hash !== null));
126
142
  return new Set(current.filter((hash) => hash !== null && !remaining.has(hash)));
127
143
  }
144
+ function displacedEntries(current, updated) {
145
+ const remaining = new Set(updated.filter((hash) => hash !== null));
146
+ const entries = [];
147
+ for (let i = 0; i < current.length; i++) {
148
+ const h = current[i];
149
+ if (h !== null && !remaining.has(h)) {
150
+ entries.push({ hash: h, deathPos: i });
151
+ }
152
+ }
153
+ return entries;
154
+ }
155
+ // deathPos=null = legacy/unknown position (pre-GC String[] format or migration).
156
+ // These entries are NOT swept incrementally — retained until full-recordServed (isFullRead) or major-GC promotion clears retired.
157
+ // 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.
158
+ function sweepRetiredByPositions(store, sessionKey, path, servedPositions) {
159
+ if (servedPositions.size === 0)
160
+ return;
161
+ const entries = store.getRetiredEntries(sessionKey, path);
162
+ if (entries.length === 0)
163
+ return;
164
+ const filtered = entries.filter((e) => e.deathPos === null || !servedPositions.has(e.deathPos));
165
+ if (filtered.length !== entries.length) {
166
+ store.upsertRetiredAnchors(sessionKey, path, JSON.stringify(filtered));
167
+ }
168
+ }
169
+ function sweepAndRetire(store, sessionKey, path, current, updated, rows) {
170
+ const servedPositions = new Set(rows.map((r) => r.position));
171
+ const existingCards = store.getCards(sessionKey, path);
172
+ let cardsChanged = false;
173
+ for (const pos of servedPositions)
174
+ if (!existingCards.has(pos)) {
175
+ existingCards.add(pos);
176
+ cardsChanged = true;
177
+ }
178
+ if (cardsChanged)
179
+ store.upsertCards(sessionKey, path, JSON.stringify([...existingCards]));
180
+ const existingEntries = store.getRetiredEntries(sessionKey, path);
181
+ const displaced = displacedEntries(current, updated);
182
+ const existingHashes = new Set(existingEntries.map((e) => e.hash));
183
+ const filteredDisplaced = displaced.filter((e) => !existingHashes.has(e.hash));
184
+ const afterSweep = existingEntries.filter((e) => e.deathPos === null || !existingCards.has(e.deathPos));
185
+ const merged = [...afterSweep, ...filteredDisplaced];
186
+ if (merged.length !== existingEntries.length || filteredDisplaced.length > 0 || cardsChanged) {
187
+ store.upsertRetiredAnchors(sessionKey, path, JSON.stringify(merged));
188
+ }
189
+ }
128
190
  /** Keep freed anchors dead for this session until it has seen the whole file again. */
129
191
  export async function retireAnchors(sessionKey, path, hashes) {
130
192
  const additions = [...hashes];
@@ -135,14 +197,14 @@ export async function retireAnchors(sessionKey, path, hashes) {
135
197
  addRetiredAnchors(store, sessionKey, path, additions);
136
198
  });
137
199
  }
138
- export async function recordServed(sessionKey, path, rows, lineCount, fullReadHashes, fullReadCanons, fullReadSnapshotId) {
200
+ export async function recordServed(sessionKey, path, rows, lineCount, full) {
139
201
  if (rows.length === 0)
140
202
  return;
141
203
  try {
142
204
  const store = await loadServedStore();
143
- const isFullRead = fullReadHashes !== undefined &&
144
- rows.length === fullReadHashes.length &&
145
- rows.every((row, index) => row.position === index && row.hash === fullReadHashes[index]);
205
+ const isFullRead = full !== undefined &&
206
+ rows.length === full.hashes.length &&
207
+ rows.every((row, index) => row.position === index && row.hash === full.hashes[index]);
146
208
  withStore(() => {
147
209
  const current = store.getServed(sessionKey, path);
148
210
  const updated = _mergeServedRows(current, rows, lineCount === undefined ? undefined : { truncateTo: lineCount });
@@ -151,20 +213,21 @@ export async function recordServed(sessionKey, path, rows, lineCount, fullReadHa
151
213
  }
152
214
  if (isFullRead) {
153
215
  store.clearRetiredAnchors(sessionKey, path);
154
- if (fullReadCanons)
155
- store.upsertServedCanons(sessionKey, path, JSON.stringify(fullReadCanons));
156
- if (fullReadSnapshotId)
157
- store.upsertEpochSnapshotId(sessionKey, path, fullReadSnapshotId);
216
+ store.clearCards(sessionKey, path);
217
+ if (full?.canons)
218
+ store.upsertServedCanons(sessionKey, path, JSON.stringify(full.canons));
219
+ if (full?.snapshotId)
220
+ store.upsertEpochSnapshotId(sessionKey, path, full.snapshotId);
158
221
  }
159
222
  else {
160
223
  // For partial reads, update canons for the served rows via hash-to-canon map (robust for partial views)
161
- if (fullReadCanons && fullReadHashes) {
224
+ if (full?.canons && full.hashes) {
162
225
  const canonByHash = new Map();
163
- for (let i = 0; i < fullReadHashes.length; i++) {
164
- const h = fullReadHashes[i];
165
- const c = fullReadCanons[i] ?? null;
166
- if (h)
167
- canonByHash.set(h, c);
226
+ for (let i = 0; i < full.hashes.length; i++) {
227
+ const lineHash = full.hashes[i];
228
+ const lineCanon = full.canons[i] ?? null;
229
+ if (lineHash)
230
+ canonByHash.set(lineHash, lineCanon);
168
231
  }
169
232
  const currentCanons = store.getServedCanons(sessionKey, path);
170
233
  const updatedCanons = currentCanons.slice();
@@ -180,9 +243,7 @@ export async function recordServed(sessionKey, path, rows, lineCount, fullReadHa
180
243
  updatedCanons.pop();
181
244
  store.upsertServedCanons(sessionKey, path, JSON.stringify(updatedCanons));
182
245
  }
183
- if (fullReadSnapshotId)
184
- store.upsertEpochSnapshotId(sessionKey, path, fullReadSnapshotId);
185
- addRetiredAnchors(store, sessionKey, path, displacedHashes(current, updated));
246
+ sweepAndRetire(store, sessionKey, path, current, updated, rows);
186
247
  }
187
248
  });
188
249
  }
@@ -190,7 +251,7 @@ export async function recordServed(sessionKey, path, rows, lineCount, fullReadHa
190
251
  console.error("Failed to record served rows:", error);
191
252
  }
192
253
  }
193
- export async function recordServedTruncated(sessionKey, path, rows, lineCount, clearFrom = 0) {
254
+ export async function recordServedTruncated(sessionKey, path, rows, lineCount, clearFrom = 0, fullCanons) {
194
255
  if (rows.length === 0)
195
256
  return;
196
257
  try {
@@ -201,7 +262,22 @@ export async function recordServedTruncated(sessionKey, path, rows, lineCount, c
201
262
  if (current.length !== updated.length || current.some((v, i) => v !== updated[i])) {
202
263
  store.upsertServed(sessionKey, path, JSON.stringify(updated));
203
264
  }
204
- addRetiredAnchors(store, sessionKey, path, displacedHashes(current, updated));
265
+ if (fullCanons) {
266
+ // #53: hashes without fresh canons leave the verify collision-guard
267
+ // comparing live content against stale metadata (false E_STALE_RANGE).
268
+ // Refresh canons for recorded rows; null where served is null so the
269
+ // parallel arrays stay consistent (canon null <=> served null).
270
+ const currentCanons = store.getServedCanons(sessionKey, path);
271
+ const rowCanon = new Map();
272
+ for (const row of rows)
273
+ rowCanon.set(row.position, fullCanons[row.position] ?? null);
274
+ const updatedCanons = [];
275
+ for (let i = 0; i < updated.length; i++) {
276
+ updatedCanons.push(updated[i] === null ? null : rowCanon.has(i) ? rowCanon.get(i) : (currentCanons[i] ?? null));
277
+ }
278
+ store.upsertServedCanons(sessionKey, path, JSON.stringify(updatedCanons));
279
+ }
280
+ sweepAndRetire(store, sessionKey, path, current, updated, rows);
205
281
  });
206
282
  }
207
283
  catch (error) {
@@ -288,7 +364,60 @@ export function currentPositionOfDrifted(served, currentPositions, surviving, se
288
364
  return currentPositions.get(served[above]) - 1;
289
365
  return servedIndex + delta;
290
366
  }
291
- export const DRIFT_NOTICE_HEADING = "drift:";
367
+ export const DRIFT_NOTICE_HEADING = "[USER] drift:";
368
+ /**
369
+ * WHY (#68 hash-rotation vs content loss): probing + retired growth reassign
370
+ * distinct hashes to identical duplicate lines across sequential edits, so a
371
+ * served hash missing from the result set may still survive under a fresh hash.
372
+ * Suppress those by consuming one matching canon outside the edited span;
373
+ * report only true canon deficit. Whitespace-only reformats stay silent
374
+ * (canon strips ASCII whitespace, ADR-0002). Absent/empty servedCanons keeps
375
+ * legacy hash-equality.
376
+ */
377
+ function buildRotatedSurvivorCheck(input, rangeFrom, rangeTo, delta) {
378
+ const canons = input.servedCanons;
379
+ if (!canons || !canons.some((c) => c !== null))
380
+ return () => false;
381
+ // Edited served interval mapped to result coordinates (single range).
382
+ const spanFrom = Math.max(0, rangeFrom);
383
+ const spanTo = Math.max(spanFrom - 1, rangeTo + delta);
384
+ const remaining = new Map();
385
+ for (let i = 0; i < input.resultLines.length; i++) {
386
+ if (i >= spanFrom && i <= spanTo)
387
+ continue;
388
+ const c = canon(input.resultLines[i] ?? "");
389
+ remaining.set(c, (remaining.get(c) ?? 0) + 1);
390
+ }
391
+ const take = (c) => {
392
+ const left = remaining.get(c) ?? 0;
393
+ if (left <= 0)
394
+ return false;
395
+ remaining.set(c, left - 1);
396
+ return true;
397
+ };
398
+ // Pre-consume: served lines that survived under their own hash already
399
+ // account for their result content, so a deleted duplicate is not masked
400
+ // by a surviving twin (multiset difference, not per-hash presence).
401
+ const currentPosOfHash = new Map();
402
+ for (let i = 0; i < input.resultHashes.length; i++) {
403
+ currentPosOfHash.set(input.resultHashes[i], i);
404
+ }
405
+ for (let p = 0; p < input.served.length; p++) {
406
+ const h = input.served[p];
407
+ if (h === null || (p >= rangeFrom && p <= rangeTo))
408
+ continue;
409
+ const currentPos = currentPosOfHash.get(h);
410
+ if (currentPos === undefined)
411
+ continue;
412
+ take(canon(input.resultLines[currentPos] ?? ""));
413
+ }
414
+ return (servedPos) => {
415
+ const c = canons[servedPos] ?? null;
416
+ if (c === null)
417
+ return false;
418
+ return take(c);
419
+ };
420
+ }
292
421
  export function computeDrift(input) {
293
422
  const { served, resultHashes, resultLines, range, reported, cap = SERVED_ECHO_CAP } = input;
294
423
  const resultHashSet = new Set(resultHashes);
@@ -310,6 +439,7 @@ export function computeDrift(input) {
310
439
  }
311
440
  const rangeFrom = Math.min(servedStartIdx, servedEndIdx);
312
441
  const rangeTo = Math.max(servedStartIdx, servedEndIdx);
442
+ const isRotatedSurvivor = buildRotatedSurvivorCheck(input, rangeFrom, rangeTo, range.delta);
313
443
  let total = 0;
314
444
  let unshown = 0;
315
445
  let anyNotReported = false;
@@ -322,6 +452,8 @@ export function computeDrift(input) {
322
452
  continue;
323
453
  if (resultHashSet.has(servedHash))
324
454
  continue;
455
+ if (isRotatedSurvivor(p))
456
+ continue;
325
457
  total++;
326
458
  if (!reported.has(servedHash))
327
459
  anyNotReported = true;
@@ -372,7 +504,8 @@ export function computeDrift(input) {
372
504
  }
373
505
  export async function scanDrift(input) {
374
506
  const reported = await driftReported(input.sessionKey, input.path);
375
- const result = computeDrift({ ...input, reported });
507
+ const servedCanons = await loadServedCanons(input.sessionKey, input.path);
508
+ const result = computeDrift({ ...input, reported, servedCanons });
376
509
  if (!result || result.allAlreadyReported)
377
510
  return result?.text;
378
511
  await recordServed(input.sessionKey, input.path, result.rows.map((row) => ({ position: row.position, hash: row.hash })), input.resultLines.length);
package/lib/tool-edit.js CHANGED
@@ -10,6 +10,7 @@ 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";
13
14
  import { execCwd, execSessionKey } from "./workspace-context.js";
14
15
  import { withWorkspace } from "./workspace-context.js";
15
16
  import { findSnapshotPathsByHashes } from "./hash-store.js";
@@ -25,15 +26,15 @@ async function resolveNullPath(edits) {
25
26
  if (matches.length === 1) {
26
27
  return {
27
28
  path: matches[0],
28
- warning: `[E_BAD_SHAPE] Autocorrected: missing "path" resolved to ${matches[0]} — the only file whose stored hashes contain both anchors.`,
29
+ warning: `[MODEL] [E_BAD_PAYLOAD] Autocorrected: missing "path" resolved to ${matches[0]} — the only file whose stored hashes contain both anchors.`,
29
30
  };
30
31
  }
31
32
  if (matches.length > 1) {
32
- throw new Error(`[E_BAD_SHAPE] Edit request requires a non-empty "path" string; the anchors match multiple known files: ${matches.join(", ")}. Include the intended path.`);
33
+ throw new Error(`[MODEL] [E_BAD_PAYLOAD] Edit request requires a non-empty "path" string; the anchors match multiple known files: ${matches.join(", ")}. Include the intended path.`);
33
34
  }
34
35
  }
35
36
  catch (e) {
36
- if (e instanceof Error && e.message.startsWith("[E_BAD_SHAPE]"))
37
+ if (codeOf(e) === "E_BAD_PAYLOAD")
37
38
  throw e;
38
39
  return undefined;
39
40
  }
@@ -78,7 +79,7 @@ export function buildEditTool(io, sandbox) {
78
79
  pathWarning = resolved.warning;
79
80
  }
80
81
  else {
81
- throw new Error("[E_BAD_SHAPE] Edit request path is null and could not be inferred from anchors — anchors match no known file. Include the intended path.");
82
+ throw new Error("[MODEL] [E_BAD_PAYLOAD] Edit request path is null and could not be inferred from anchors — anchors match no known file. Include the intended path.");
82
83
  }
83
84
  }
84
85
  const sandboxPolicy = await sandbox.resolvePolicy("edit", { path: resolvedPath, edits: req.edits }, exec);
package/lib/tool-undo.js CHANGED
@@ -6,11 +6,11 @@
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 } from "./utils.js";
9
+ import { cntDiff, splitLines, codeOf } from "./utils.js";
10
10
  import { assertUndoRequest } from "./contract.js";
11
11
  import { normalizeRequest as normReq } from "./contract.js";
12
12
  import { upsertSnapshotFor } from "./hash-store.js";
13
- import { contentChecksum } from "./hashline/hash-assign.js";
13
+ import { canon, contentChecksum } from "./hashline/hash-assign.js";
14
14
  import { lineHashes } from "./hashline/hash.js";
15
15
  import { changedRange } from "./hashline/anchor-pipeline.js";
16
16
  import { getUndo, clearUndo } from "./undo-edit.js";
@@ -62,7 +62,7 @@ export function buildUndoTool(io, sandbox) {
62
62
  }
63
63
  catch (error) {
64
64
  const message = error instanceof Error ? error.message : String(error);
65
- if (message.includes("[E_NOT_FOUND]")) {
65
+ if (codeOf(error) === "E_NOT_FOUND") {
66
66
  await clearUndo(absolutePath);
67
67
  return `[E_UNDO_STALE] cannot undo on ${path}: file no longer exists.`;
68
68
  }
@@ -75,8 +75,8 @@ export function buildUndoTool(io, sandbox) {
75
75
  }
76
76
  const { text: currentStripped } = stripBOM(currentRaw);
77
77
  const currentNormalized = toLF(currentStripped);
78
- // undo is file-global: must block hashes retired by any session, not just current session, to prevent recycling current-file-only hash - test expects global
79
- const reservations = await loadAnchorReservations(absolutePath);
78
+ // Per-session reservations: retired/ served are per (session, path) per ADR-0013; file snapshots stay global last-writer-wins
79
+ const reservations = await loadAnchorReservations(sessionKey, absolutePath);
80
80
  const currentHashes = await lineHashes(currentNormalized, absolutePath, undefined, undefined, false, reservations.reservedHashes, reservations.retiredHashes);
81
81
  const retiredOriginalHashes = new Set(undo.hashes.filter((hash) => reservations.retiredHashes.has(hash)));
82
82
  const blockedRestoreHashes = new Set(reservations.reservedHashes);
@@ -118,7 +118,7 @@ export function buildUndoTool(io, sandbox) {
118
118
  }
119
119
  parts.push("File reverted to previous state. The post-edit diff rows carry the restored file\u2019s fresh anchors for follow-up edits.");
120
120
  if (undoDenseRows.length > 0) {
121
- await recordServedTruncated(sessionKey, absolutePath, undoDenseRows, splitLines(undo.content).length, restoredRange?.firstChangedLine ?? undoDiffResult.firstChangedLine ?? 0);
121
+ await recordServedTruncated(sessionKey, absolutePath, undoDenseRows, splitLines(undo.content).length, restoredRange?.firstChangedLine ?? undoDiffResult.firstChangedLine ?? 0, splitLines(undo.content).map((l) => canon(l)));
122
122
  }
123
123
  return [parts.join("\n"), "", "Diff of the revert:", "", undoDiff].join("\n");
124
124
  });
@@ -11,3 +11,5 @@ export declare const SERVED_TTL_MS: number;
11
11
  export declare const SERVED_ECHO_CAP = 150;
12
12
  export declare const NOOP_LOOP_THRESHOLD = 3;
13
13
  export declare const NEW_CONTENT_NOT_STRING_MSG: string;
14
+ export declare function eLargeFileMsg(displayPath: string, lineCount: number, maxLines: number): string;
15
+ export declare const E_ANCHOR_SPACE_EXHAUSTED_WARNING = "[E_ANCHOR_SPACE_EXHAUSTED] Anchor space exhausted";
@@ -2,7 +2,7 @@
2
2
  * One module owns the request shapes for the hashline tools — edit,
3
3
  * read, undo_last_edit — plus their validation. Field sets are
4
4
  * declared once here; every tool validates through these asserts, and the
5
- * [E_BAD_SHAPE] vocabulary is shared instead of re-implemented per tool.
5
+ * [E_BAD_PAYLOAD] vocabulary is shared instead of re-implemented per tool.
6
6
  *
7
7
  * Contract now mirrors upstream ADR-0007: {path: string|null, edits: [[remove_from,remove_to,replacement_text],...]} tuple payload,
8
8
  * single-file, atomic. batch_edit is removed.
@@ -48,6 +48,7 @@ export type NormalizedEditRequest = EditRequest & {
48
48
  export declare function isNormalizedEdit(input: unknown): input is NormalizedEditRequest;
49
49
  export declare function itemFromTuple(value: unknown): EditItem | undefined;
50
50
  export declare function editRequestFrom(input: unknown): NormalizedEditRequest | undefined;
51
+ export declare function sanitizePath(value: unknown): string | null;
51
52
  export declare const EDIT_TUPLE_HINT: string;
52
53
  /**
53
54
  * Normalize `file_path` → `path` alias on the request record and tuple edits → objects.
@@ -1,6 +1,10 @@
1
1
  import type { ServedRow } from "./hashline/anchor-pipeline.js";
2
2
  export type EditDetails = {
3
3
  diff: string;
4
+ /** Bare `E_*` code for the primary error signal, if any (no `[MODEL]` prefix). Structured counterpart to message-string codes. */
5
+ errCode?: string;
6
+ /** Disambiguator for `E_UNSERVED_RANGE`: boundary miss vs interior hole. */
7
+ unservedKind?: "boundary" | "interior";
4
8
  firstChangedLine?: number;
5
9
  snapshotId?: string;
6
10
  classification?: "noop";
@@ -35,7 +35,7 @@ export declare function hasReplacementChar(text: string): boolean;
35
35
  */
36
36
  export declare function detectWithChardet(bytes: Uint8Array, allowlist: string[]): Promise<string | undefined>;
37
37
  /**
38
- * Chardet-based Top-3 for E_NOT_TEXT (primary) and autoGuess.
38
+ * Chardet-based Top-3 for E_UNSUPPORTED_FILE (primary) and autoGuess.
39
39
  * Returns chardet candidates filtered by allowlist and decodable, else empty.
40
40
  */
41
41
  export declare function chardetTop3Candidates(bytes: Uint8Array, allowlist: string[]): Promise<Array<{
@@ -50,7 +50,7 @@ export interface DecodeForOpenOptions {
50
50
  /**
51
51
  * Deterministic admission for a raw byte buffer. No IO, no side effects
52
52
  * except Top-3 scoring. Caller owns recording the returned state via
53
- * `recordOpenState` and handling the footer vs E_NOT_TEXT split.
53
+ * `recordOpenState` and handling the footer vs E_UNSUPPORTED_FILE split.
54
54
  *
55
55
  * Order is fixed: BOM sniff always precedes strict UTF-8, which always
56
56
  * precedes guessing. Probabilistic encodings are last resort, gated by
@@ -91,6 +91,11 @@ export interface ReadNormOptions {
91
91
  noPersist?: boolean;
92
92
  reservedHashes?: ReadonlySet<string>;
93
93
  retiredHashes?: ReadonlySet<string>;
94
+ previous?: {
95
+ content: string;
96
+ hashes: string[];
97
+ removedHashes?: Set<string>;
98
+ };
94
99
  }
95
100
  export declare function normFromText(input: {
96
101
  absolutePath: string;
@@ -103,6 +108,11 @@ export declare function normFromText(input: {
103
108
  reservedHashes?: ReadonlySet<string>;
104
109
  retiredHashes?: ReadonlySet<string>;
105
110
  hadUtf8DecodeErrors?: boolean;
111
+ previous?: {
112
+ content: string;
113
+ hashes: string[];
114
+ removedHashes?: Set<string>;
115
+ };
106
116
  }): Promise<NormFile>;
107
117
  export declare function readNormFile(path: string, cwd: string, options?: ReadNormOptions): Promise<NormFile>;
108
118
  export declare function formatPaginationHint(startLine: number, endLine: number, totalLines: number, nextOffset: number, byteLimit?: number): string;
@@ -136,6 +146,11 @@ export interface ReadViewOpts extends PreviewOpts {
136
146
  signal?: AbortSignal;
137
147
  reservedHashes?: ReadonlySet<string>;
138
148
  retiredHashes?: ReadonlySet<string>;
149
+ previous?: {
150
+ content: string;
151
+ hashes: string[];
152
+ removedHashes?: Set<string>;
153
+ };
139
154
  }
140
155
  export declare function preview(content: string, hashes: string[], opts?: PreviewOpts, absolutePath?: string): Promise<{
141
156
  text: string;
@@ -67,10 +67,14 @@ export interface HashStore {
67
67
  export interface ServedPersistence {
68
68
  getServed(sessionKey: string, path: string): (string | null)[];
69
69
  getServedReported(sessionKey: string, path: string): Set<string>;
70
- getAnchorReservations(path: string): AnchorReservations;
70
+ getAnchorReservations(sessionKey: string, path: string): AnchorReservations;
71
71
  getRetiredAnchors(sessionKey: string, path: string): Set<string>;
72
+ getRetiredEntries(sessionKey: string, path: string): RetiredEntry[];
72
73
  getServedCanons(sessionKey: string, path: string): (string | null)[];
73
74
  getEpochSnapshotId(sessionKey: string, path: string): string | undefined;
75
+ getCards(sessionKey: string, path: string): Set<number>;
76
+ upsertCards(sessionKey: string, path: string, cardsJson: string): void;
77
+ clearCards(sessionKey: string, path: string): void;
74
78
  upsertServed(sessionKey: string, path: string, hashesJson: string): void;
75
79
  upsertServedReported(sessionKey: string, path: string, reportedJson: string): void;
76
80
  clearServedReported(sessionKey: string, path: string): void;
@@ -89,6 +93,13 @@ export interface AnchorReservations {
89
93
  reservedHashes: Set<string>;
90
94
  retiredHashes: Set<string>;
91
95
  }
96
+ export type DeathPos = number | null;
97
+ export interface RetiredEntry {
98
+ hash: string;
99
+ deathPos: DeathPos;
100
+ }
101
+ export declare function isValidRetiredEntry(value: unknown): value is RetiredEntry;
102
+ export declare function isValidRetiredEntries(value: unknown): value is RetiredEntry[];
92
103
  export type InternalHashStore = HashStore & ServedPersistence;
93
104
  /** Load the store as served persistence — internal, for SessionView only. */
94
105
  export declare function loadServedStore(cwd?: string): Promise<ServedPersistence>;
@@ -16,6 +16,7 @@
16
16
  *
17
17
  * @module dsh-better-edit/hashline/anchor-pipeline
18
18
  */
19
+ import { CodedError } from "../utils.js";
19
20
  export type Anchor = {
20
21
  hash: string;
21
22
  };
@@ -44,31 +45,40 @@ export type HTEdit = {
44
45
  remove_from: string;
45
46
  remove_to: string;
46
47
  };
47
- export declare function resEdit(edit: HTEdit, warnings?: string[]): HEdit;
48
+ export declare function resEdit(edit: HTEdit, _warnings?: string[]): HEdit;
48
49
  declare function warnUnicodeEsc(edit: HEdit, warnings: string[]): void;
49
50
  export declare function findNewEdge(): undefined;
50
51
  export { warnUnicodeEsc };
51
- export type ServedCode = "E_RANGE_STALE" | "E_RANGE_UNSERVED" | "E_RANGE_UNVERIFIED";
52
+ export type ServedCode = "E_STALE_RANGE" | "E_UNSERVED_RANGE";
52
53
  export interface ServedRow {
53
54
  position: number;
54
55
  hash: string;
55
56
  }
56
- export declare class ServedRejectionError extends Error {
57
+ export declare class ServedRejectionError extends CodedError {
57
58
  readonly code: ServedCode;
59
+ readonly unservedKind: "boundary" | "interior" | undefined;
58
60
  readonly firstOffendingLine: number | undefined;
59
61
  readonly servedRows: ServedRow[];
60
62
  constructor(opts: {
61
63
  code: ServedCode;
64
+ unservedKind?: "boundary" | "interior";
62
65
  message: string;
63
66
  firstOffendingLine?: number;
64
67
  servedRows: ServedRow[];
65
68
  });
66
69
  }
67
70
  export declare function isServedRejection(error: unknown): error is ServedRejectionError;
68
- export declare class AnchorMismatchError extends Error {
71
+ export declare class AnchorMismatchError extends CodedError {
69
72
  readonly servedRows: ServedRow[];
70
73
  constructor(message: string, servedRows: ServedRow[]);
71
74
  }
75
+ /** Thrown when replacement_text carries anchor-syntax garbage (HASH│/diff-preview prefixes).
76
+ * Carries the stripped edit so applyEdit can distinguish served-echo (→ E_SERVED_ECHO
77
+ * denial downstream) from garbage (→ E_BAD_ANCHOR stands). */
78
+ export declare class BadAnchorError extends CodedError {
79
+ readonly stripped: HEdit;
80
+ constructor(message: string, stripped: HEdit);
81
+ }
72
82
  export declare function isAnchorMismatch(error: unknown): error is AnchorMismatchError;
73
83
  export declare function findEditHashEcho(replacementLines: string[], served: readonly (string | null)[], startLine: number): {
74
84
  k: number;
@@ -89,7 +99,7 @@ export declare function verifyServedRange(args: {
89
99
  fileLines: string[];
90
100
  filePath?: string;
91
101
  servedCanons?: (string | null)[];
92
- tombstone?: ReadonlySet<string>;
102
+ retired?: ReadonlySet<string>;
93
103
  epochSnapshotId?: string;
94
104
  curSnapshotId?: string;
95
105
  strictPos?: boolean;
@@ -108,7 +118,7 @@ type LIdx = {
108
118
  lineStarts: number[];
109
119
  };
110
120
  export declare function buildIdx(content: string): LIdx;
111
- export declare function applyEdit(content: string, edit: HEdit, signal?: AbortSignal, precomputedHashes?: string[], filePath?: string, served?: (string | null)[], servedCanons?: (string | null)[], tombstone?: ReadonlySet<string>, epochSnapshotId?: string, curSnapshotId?: string, strictPos?: boolean): {
121
+ export declare function applyEdit(content: string, edit: HEdit, signal?: AbortSignal, precomputedHashes?: string[], filePath?: string, served?: (string | null)[], servedCanons?: (string | null)[], retired?: ReadonlySet<string>, epochSnapshotId?: string, curSnapshotId?: string, strictPos?: boolean): {
112
122
  content: string;
113
123
  firstChangedLine: number | undefined;
114
124
  lastChangedLine: number | undefined;
@@ -16,6 +16,14 @@ 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 class AnchorSpaceExhaustedError extends Error {
20
+ readonly code = "E_ANCHOR_SPACE_EXHAUSTED";
21
+ readonly retiredCount: number;
22
+ readonly servedCount: number;
23
+ constructor(retiredCount: number, servedCount: number, reservedCount: number);
24
+ }
25
+ export declare function idxToHash(idx: number): string;
26
+ export declare function hashAt(idx: number): string;
19
27
  export declare function rememberHashCanon(hash: string, canonText: string): void;
20
28
  export declare function getCanonForHash(hash: string): string | undefined;
21
29
  export declare const HL_PREFIX_PLUS_RE: RegExp;
@@ -23,5 +31,5 @@ export declare const HL_PREFIX_MINUS_RE: RegExp;
23
31
  export declare const HL_BARE_PREFIX_RE: RegExp;
24
32
  export declare const CANON_VERSION = 2;
25
33
  export declare function canon(line: string): string;
26
- export declare function lineHashesPure(content: string, reservedHashes?: ReadonlySet<string>): string[];
27
- export declare function mapStableHashes(oldContent: string, oldHashes: string[], newContent: string, removedHashes?: Set<string>, reservedHashes?: ReadonlySet<string>): string[];
34
+ export declare function lineHashesPure(content: string, reservedHashes?: ReadonlySet<string>, retiredCount?: number, servedCount?: number): string[];
35
+ export declare function mapStableHashes(oldContent: string, oldHashes: string[], newContent: string, removedHashes?: Set<string>, reservedHashes?: ReadonlySet<string>, retiredCount?: number, servedCount?: number): string[];
@@ -81,10 +81,11 @@ export interface ApplyOneInput {
81
81
  persist: boolean;
82
82
  reservedHashes?: ReadonlySet<string>;
83
83
  servedCanons?: (string | null)[];
84
- tombstone?: ReadonlySet<string>;
84
+ retired?: ReadonlySet<string>;
85
85
  epochSnapshotId?: string;
86
86
  curSnapshotId?: string;
87
87
  strictPos?: boolean;
88
+ sessionKey?: string;
88
89
  /** Pre-resolved edit (single path keeps resEdit before IO for error order). */
89
90
  edit?: HEdit;
90
91
  }
@@ -42,21 +42,27 @@ export declare function _mergeServedRows(current: (string | null)[], rows: Serve
42
42
  }): (string | null)[];
43
43
  export declare function loadServed(sessionKey: string, path: string): Promise<(string | null)[]>;
44
44
  /** Anchors that must not be allocated while any session can still remember them. */
45
- export declare function loadAnchorReservations(path: string): Promise<AnchorReservations>;
45
+ export declare function loadAnchorReservations(sessionKey: string, path: string): Promise<AnchorReservations>;
46
46
  export declare function loadServedCanons(sessionKey: string, path: string): Promise<(string | null)[]>;
47
47
  export declare function loadEpochSnapshotId(sessionKey: string, path: string): Promise<string | undefined>;
48
48
  export declare function loadRetiredAnchors(sessionKey: string, path: string): Promise<Set<string>>;
49
49
  /** Keep freed anchors dead for this session until it has seen the whole file again. */
50
50
  export declare function retireAnchors(sessionKey: string, path: string, hashes: Iterable<string>): Promise<void>;
51
- export declare function recordServed(sessionKey: string, path: string, rows: ServedEntry[], lineCount?: number, fullReadHashes?: readonly string[], fullReadCanons?: readonly (string | null)[], fullReadSnapshotId?: string): Promise<void>;
52
- export declare function recordServedTruncated(sessionKey: string, path: string, rows: ServedEntry[], lineCount: number, clearFrom?: number): Promise<void>;
51
+ /** Full-file context for a complete read — when present and matching `rows`, the call is a full read. */
52
+ export interface FullReadContext {
53
+ hashes: readonly string[];
54
+ canons?: readonly (string | null)[];
55
+ snapshotId?: string;
56
+ }
57
+ export declare function recordServed(sessionKey: string, path: string, rows: ServedEntry[], lineCount?: number, full?: FullReadContext): Promise<void>;
58
+ export declare function recordServedTruncated(sessionKey: string, path: string, rows: ServedEntry[], lineCount: number, clearFrom?: number, fullCanons?: readonly (string | null)[]): Promise<void>;
53
59
  export declare function driftReported(sessionKey: string, path: string): Promise<Set<string>>;
54
60
  export declare function markDriftReported(sessionKey: string, path: string, hashes: string[]): Promise<void>;
55
61
  export declare function clearDriftReported(sessionKey: string, path: string): Promise<void>;
56
62
  export declare function wipeServedState(sessionKey: string): Promise<void>;
57
63
  export declare function servedPositionsOf(served: (string | null)[], hash: string): number[];
58
64
  export declare function currentPositionOfDrifted(served: (string | null)[], currentPositions: Map<string, number>, surviving: Set<string>, servedIndex: number, delta: number): number;
59
- export declare const DRIFT_NOTICE_HEADING = "drift:";
65
+ export declare const DRIFT_NOTICE_HEADING = "[USER] drift:";
60
66
  export interface DriftRow extends ServedRow {
61
67
  content: string;
62
68
  drifted: boolean;
@@ -68,6 +74,9 @@ export interface ComputeDriftInput {
68
74
  range: ResolvedRange;
69
75
  reported: Set<string>;
70
76
  cap?: number;
77
+ /** WHY (#68): parallel to `served`, whitespace-stripped form at serve time.
78
+ * Absent/empty preserves legacy hash-equality (old DBs, unit callers). */
79
+ servedCanons?: (string | null)[];
71
80
  }
72
81
  export interface DriftNoticeResult {
73
82
  text: string;
@@ -11,3 +11,10 @@ export declare function firstNonEmptyIndex(lines: string[]): number;
11
11
  export declare function lastNonEmpty(lines: string[]): string | undefined;
12
12
  export declare function firstNonEmpty(lines: string[]): string | undefined;
13
13
  export declare function clipLine(line: string, maxLen?: number): string;
14
+ /** Machine-readable error-code carrier — bare `E_*` code alongside the human message. */
15
+ export declare class CodedError extends Error {
16
+ readonly code: string;
17
+ constructor(code: string, message: string);
18
+ }
19
+ /** Structured bare-code read for any tool error: carrier first, `[E_*]` message convention as fallback. */
20
+ export declare function codeOf(error: unknown): string | undefined;