dsh-better-edit 0.5.1 → 0.6.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.
Files changed (42) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/lib/edit-engine.js +4 -454
  3. package/lib/edit-response.js +24 -2
  4. package/lib/file-encoding-state.js +263 -0
  5. package/lib/file-view.js +5 -1
  6. package/lib/fs-bridge.js +94 -251
  7. package/lib/hash-store.js +180 -2
  8. package/lib/hashline/anchor-pipeline.js +94 -166
  9. package/lib/hashline/hash-assign.js +15 -27
  10. package/lib/hashline/hash.js +5 -5
  11. package/lib/index.js +2 -2
  12. package/lib/mutation/engine.js +415 -0
  13. package/lib/mutation.js +105 -11
  14. package/lib/paths.js +1 -1
  15. package/lib/read-and-serve.js +25 -3
  16. package/lib/session-view.js +107 -58
  17. package/lib/store/index.js +28 -0
  18. package/lib/store-lifecycle.js +1 -1
  19. package/lib/tool-edit.js +2 -2
  20. package/lib/tool-read.js +2 -2
  21. package/lib/tool-undo.js +21 -8
  22. package/lib/types/edit-diff.d.ts +1 -1
  23. package/lib/types/edit-engine.d.ts +4 -176
  24. package/lib/types/edit-response.d.ts +1 -1
  25. package/lib/types/file-encoding-state.d.ts +77 -0
  26. package/lib/types/file-view.d.ts +7 -1
  27. package/lib/types/fs-bridge.d.ts +4 -11
  28. package/lib/types/hash-store.d.ts +15 -0
  29. package/lib/types/hashline/anchor-pipeline.d.ts +12 -21
  30. package/lib/types/hashline/hash-assign.d.ts +2 -2
  31. package/lib/types/hashline/hash.d.ts +1 -1
  32. package/lib/types/hashline/index.d.ts +1 -1
  33. package/lib/types/mutation/engine.d.ts +149 -0
  34. package/lib/types/mutation.d.ts +30 -5
  35. package/lib/types/paths.d.ts +1 -1
  36. package/lib/types/read-and-serve.d.ts +1 -1
  37. package/lib/types/session-view.d.ts +25 -31
  38. package/lib/types/store/index.d.ts +25 -0
  39. package/lib/types/workspace-context.d.ts +23 -0
  40. package/lib/workspace-context.js +44 -0
  41. package/lib/write-hook.js +2 -1
  42. package/package.json +1 -1
package/lib/mutation.js CHANGED
@@ -24,18 +24,23 @@
24
24
  *
25
25
  * @module dsh-better-edit/mutation
26
26
  */
27
+ import { loadConfig } from "./store-config.js";
28
+ import { canon } from "./hashline/hash-assign.js";
27
29
  import { normFromText, fileSnap } from "./file-reader.js";
28
30
  import { toCwd } from "./paths.js";
29
31
  import { resEdit } from "./hashline/anchor-pipeline.js";
30
32
  import { MAX_HASH_LINES } from "./hashline/hash-assign.js";
31
33
  import { AnchorMismatchError, ServedRejectionError, recordEchoServes, } from "./hashline/anchor-pipeline.js";
32
- import { loadServed, sessionKeyFor, scanDrift, recordServedTruncated } from "./session-view.js";
34
+ import { sessionKeyFor } from "./workspace-context.js";
35
+ import { loadServed, loadServedCanons, loadEpochSnapshotId, loadRetiredAnchors, scanDrift, recordServedTruncated, } from "./session-view.js";
33
36
  import { abortIf, splitLines } from "./utils.js";
34
- import { applyOne } from "./edit-engine.js";
35
- import { runFileEdits, resolveMissingPath, persistUndoAndWrite, enforceNoopLoop, collectRemovedHashes, countLineChanges, } from "./edit-engine.js";
37
+ import { applyOne } from "./mutation/engine.js";
38
+ import { runFileEdits, resolveMissingPath, } from "./mutation/engine.js";
39
+ import { saveUndo } from "./undo-edit.js";
40
+ import { restoreEndings } from "./edit-diff.js";
36
41
  import { buildMetrics, buildNoop, buildChanged, buildBatchResult } from "./edit-response.js";
37
- import { genDiff, restoreEndings, toLF, stripBOM } from "./edit-diff.js";
38
- import { computeDrift } from "./drift.js";
42
+ import { genDiff, toLF, stripBOM } from "./edit-diff.js";
43
+ import { computeDrift } from "./session-view.js";
39
44
  import { trackNoopPayload, clearNoopLoop, noopPayloadKey } from "./noop-guard.js";
40
45
  export async function execPipeline(io, params, cwd, options) {
41
46
  const path = params.path;
@@ -51,6 +56,8 @@ export async function execPipeline(io, params, cwd, options) {
51
56
  const signal = options?.signal;
52
57
  abortIf(signal);
53
58
  const absolutePath = await io.resolve(path, cwd, signal);
59
+ const sessionKeyEarly = options?.sessionKey ?? sessionKeyFor(undefined);
60
+ const perSessionTombstoneForNorm = await loadRetiredAnchors(sessionKeyEarly, absolutePath);
54
61
  const rawText = await io.readText(absolutePath, signal);
55
62
  const { normalized: originalNormalized, bom, originalEnding, fileHashes: originalHashes, hadUtf8DecodeErrors, } = await normFromText({
56
63
  absolutePath,
@@ -60,9 +67,20 @@ export async function execPipeline(io, params, cwd, options) {
60
67
  maxLines: MAX_HASH_LINES,
61
68
  store: hashStore,
62
69
  noPersist: options?.noPersist,
70
+ reservedHashes: perSessionTombstoneForNorm,
71
+ retiredHashes: perSessionTombstoneForNorm,
63
72
  });
64
73
  const sessionKey = options?.sessionKey ?? sessionKeyFor(undefined);
65
74
  const served = await loadServed(sessionKey, absolutePath);
75
+ const servedCanons = await loadServedCanons(sessionKey, absolutePath);
76
+ const epochSnapshotId = await loadEpochSnapshotId(sessionKey, absolutePath);
77
+ let curSnapshotId;
78
+ try {
79
+ curSnapshotId = (await fileSnap(absolutePath)).snapshotId;
80
+ }
81
+ catch { }
82
+ const strictPos = false; // automatic resist: pos-free for exterior shift, strict via tombstone+canon (changed ∩ [L,R] handled by tombstone interior gated on canon)
83
+ const tombstonePerSession = await loadRetiredAnchors(sessionKey, absolutePath);
66
84
  const policy = options?.noPersist === true ? 'preview' : 'live';
67
85
  const applied = await applyOne({
68
86
  content: originalNormalized,
@@ -77,6 +95,12 @@ export async function execPipeline(io, params, cwd, options) {
77
95
  warnings: editWarnings,
78
96
  store: hashStore,
79
97
  persist: options?.noPersist !== true,
98
+ reservedHashes: perSessionTombstoneForNorm,
99
+ servedCanons,
100
+ tombstone: tombstonePerSession,
101
+ epochSnapshotId,
102
+ curSnapshotId,
103
+ strictPos,
80
104
  edit,
81
105
  }, async (error) => {
82
106
  if (error instanceof AnchorMismatchError ||
@@ -142,11 +166,82 @@ export async function snapshotIdFor(io, absolutePath, signal) {
142
166
  }
143
167
  }
144
168
  }
145
- export { runFileEdits, resolveMissingPath, persistUndoAndWrite, enforceNoopLoop, collectRemovedHashes, countLineChanges, };
169
+ // Engine helpers are private to Mutation — not re-exported for new code.
170
+ // Deprecated re-exports kept for existing tests (commitlint: ignore):
171
+ export { runFileEdits, resolveMissingPath };
172
+ export { persistUndoAndWrite };
146
173
  export { buildMetrics, buildNoop, buildChanged, buildBatchResult };
147
174
  export { genDiff, restoreEndings, toLF, stripBOM };
148
175
  export { computeDrift, scanDrift };
149
176
  export { trackNoopPayload, clearNoopLoop, noopPayloadKey };
177
+ async function persistUndoAndWrite(opts) {
178
+ const { io, files } = opts;
179
+ const undos = [];
180
+ for (const file of files) {
181
+ const undo = await saveUndo(file.absolutePath, {
182
+ content: file.originalNormalized,
183
+ bom: file.bom,
184
+ originalEnding: file.originalEnding,
185
+ hashes: file.originalHashes,
186
+ resultContent: file.result,
187
+ });
188
+ if (!undo.persisted) {
189
+ for (const u of undos) {
190
+ try {
191
+ await u.restore();
192
+ }
193
+ catch (e) {
194
+ console.error("Failed to restore undo entry after abort:", e);
195
+ }
196
+ }
197
+ throw new Error(opts.undoUnavailableMessage(file.displayPath));
198
+ }
199
+ undos.push({ file, restore: undo.restore });
200
+ }
201
+ const written = [];
202
+ try {
203
+ for (const u of undos) {
204
+ abortIf(opts.signal);
205
+ await io.writeText(u.file.absolutePath, u.file.bom + restoreEndings(u.file.result, u.file.originalEnding), opts.signal, opts.exec, opts.sandboxPolicy);
206
+ written.push(u);
207
+ }
208
+ }
209
+ catch (error) {
210
+ for (const w of written) {
211
+ try {
212
+ await io.writeText(w.file.absolutePath, w.file.bom + restoreEndings(w.file.originalNormalized, w.file.originalEnding), undefined, opts.exec, opts.sandboxPolicy);
213
+ }
214
+ catch (e) {
215
+ console.error("Failed to restore file after write failure:", e);
216
+ }
217
+ try {
218
+ await w.restore();
219
+ }
220
+ catch (e) {
221
+ console.error("Failed to restore undo entry after write failure:", e);
222
+ }
223
+ }
224
+ if (opts.restoreUnwrittenUndos) {
225
+ for (const u of undos) {
226
+ if (written.includes(u))
227
+ continue;
228
+ try {
229
+ await u.restore();
230
+ }
231
+ catch (e) {
232
+ console.error("Failed to restore undo entry after write failure:", e);
233
+ }
234
+ }
235
+ }
236
+ throw opts.sandbox.mapError(error, opts.sandboxPolicy);
237
+ }
238
+ }
239
+ async function commitSingle(opts) {
240
+ return persistUndoAndWrite({ ...opts, restoreUnwrittenUndos: true });
241
+ }
242
+ async function commitBatch(opts) {
243
+ return persistUndoAndWrite({ ...opts, restoreUnwrittenUndos: false });
244
+ }
150
245
  // --- Deep seam: unified mutation API (one interface, thin adapters) ---
151
246
  /**
152
247
  * Deep seam: execute the full mutation lifecycle.
@@ -190,7 +285,7 @@ export async function execute(opts) {
190
285
  await recordIfNeeded(built);
191
286
  return built.content[0].text;
192
287
  }
193
- await commit({
288
+ await commitSingle({
194
289
  io,
195
290
  files: [
196
291
  {
@@ -208,7 +303,6 @@ export async function execute(opts) {
208
303
  sandboxPolicy,
209
304
  signal,
210
305
  undoUnavailableMessage: (displayPath) => `[E_UNDO_UNAVAILABLE] Cannot persist undo history to the hash store; the edit was NOT applied and ${displayPath} is unchanged. Retry the edit, or use write if the store cannot be recovered.`,
211
- restoreUnwrittenUndos: true,
212
306
  });
213
307
  const built = buildBatchResult([toSection()]);
214
308
  await recordIfNeeded(built);
@@ -218,7 +312,7 @@ export async function execute(opts) {
218
312
  // all noops — no commit
219
313
  }
220
314
  else if (fileResult.appliedCount > 0) {
221
- await commit({
315
+ await commitBatch({
222
316
  io,
223
317
  files: [
224
318
  {
@@ -236,7 +330,6 @@ export async function execute(opts) {
236
330
  sandboxPolicy,
237
331
  signal,
238
332
  undoUnavailableMessage: () => "[E_UNDO_UNAVAILABLE] Cannot persist undo history to the hash store; the batch was NOT applied and no file was written. Retry the batch, or use write if the store cannot be recovered.",
239
- restoreUnwrittenUndos: false,
240
333
  });
241
334
  }
242
335
  const built = buildBatchResult([toSection()]);
@@ -261,6 +354,7 @@ export async function commit(opts) {
261
354
  sandboxPolicy: opts.sandboxPolicy,
262
355
  signal: opts.signal,
263
356
  undoUnavailableMessage: opts.undoUnavailableMessage,
264
- restoreUnwrittenUndos: opts.restoreUnwrittenUndos,
357
+ restoreUnwrittenUndos: opts.restoreUnwrittenUndos ?? false,
265
358
  });
266
359
  }
360
+ export { commitSingle, commitBatch };
package/lib/paths.js CHANGED
@@ -9,7 +9,7 @@
9
9
  import { isAbsolute } from "node:path";
10
10
  import { resolve as resolvePath } from "node:path";
11
11
  import { expand } from "./store-tenancy.js";
12
- export * from "./store-tenancy.js";
12
+ export * from "./store/index.js"; // Store seam — single answer for "which store, where" (tenancy+lifecycle+path)
13
13
  export { canonicalAsync as resolveTarget } from "./canonical-path.js";
14
14
  export { canonicalSync } from "./canonical-path.js";
15
15
  export function toCwd(filePath, cwd) {
@@ -8,9 +8,11 @@
8
8
  * @module dsh-better-edit/read-and-serve
9
9
  */
10
10
  import { abortIf } from "./utils.js";
11
- import { readView } from "./file-view.js";
11
+ import { readView, fileSnap } from "./file-view.js";
12
+ import { canon } from "./hashline/hash-assign.js";
13
+ import { splitLines } from "./utils.js";
12
14
  import { getAutoGuessFooter } from "./fs-bridge.js";
13
- import { recordServed, clearDriftReported } from "./session-view.js";
15
+ import { recordServed, clearDriftReported, loadRetiredAnchors, loadServed, } from "./session-view.js";
14
16
  /** Appended when the file had non-UTF-8 bytes; editing rewrites it as UTF-8. */
15
17
  export const UTF8_REWRITE_NOTE = "[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]";
16
18
  /**
@@ -26,14 +28,34 @@ export const UTF8_REWRITE_NOTE = "[Non-UTF-8 bytes shown as U+FFFD; editing rewr
26
28
  export async function readAndServe(io, rawPath, cwd, options) {
27
29
  const { sessionKey, signal } = options;
28
30
  abortIf(signal);
31
+ const absolutePath = await io.resolve(rawPath, cwd, signal);
32
+ const retiredHashes = await loadRetiredAnchors(sessionKey, absolutePath);
33
+ const servedForNorm = await loadServed(sessionKey, absolutePath);
34
+ const reservedHashes = new Set([...retiredHashes, ...servedForNorm.filter((h) => h !== null)]);
35
+ const reservations = { reservedHashes, retiredHashes };
29
36
  const view = await readView(io, rawPath, cwd, {
30
37
  encoding: options.encoding,
31
38
  offset: options.offset,
32
39
  limit: options.limit,
33
40
  signal,
41
+ reservedHashes: reservations.reservedHashes,
42
+ retiredHashes: reservations.retiredHashes,
34
43
  });
35
44
  if (view.served.length > 0) {
36
- await recordServed(sessionKey, view.absolutePath, view.served, view.hashes.length);
45
+ const canons = splitLines(view.normalized).map((l) => canon(l));
46
+ const canonServed = canons.map((canonText) => canonText);
47
+ // For full read, compute snapshotId
48
+ let snapshotId;
49
+ try {
50
+ snapshotId = (await fileSnap(view.absolutePath)).snapshotId;
51
+ }
52
+ catch { }
53
+ // Pad or trim canons to served length? For now use canons for full file
54
+ const fullCanons = [];
55
+ for (let i = 0; i < view.hashes.length; i++) {
56
+ fullCanons.push(canons[i] ?? null);
57
+ }
58
+ await recordServed(sessionKey, view.absolutePath, view.served, view.hashes.length, view.hashes, fullCanons, snapshotId);
37
59
  }
38
60
  await clearDriftReported(sessionKey, view.absolutePath);
39
61
  const autoFooter = getAutoGuessFooter(view.absolutePath) ?? getAutoGuessFooter(rawPath) ?? getAutoGuessFooter(view.absolutePath.replace(/\\/g, "/")) ?? "";
@@ -1,63 +1,30 @@
1
1
  /**
2
2
  * SessionView — deep module owning served rows + drift + position reconstruction.
3
3
  *
4
- * Previously split: served-store (merge invariant, persistence via hash-store)
5
- * and drift (pure computeDrift + IO scanDrift that reads+writes served state).
6
- * The drift notice both *reads* served state and *writes* it (marking reported
7
- * + recording drift rows) — a side effect hidden inside a "notice" module.
4
+ * Previously also owned workspace/session context (AsyncLocalStorage +
5
+ * execCwd/execSessionKey/sessionKeyFor + path re-exports) as
6
+ * "private to this seam, @internal". That mixed two invariants:
7
+ * served-merge+drift vs context propagation. Now this seam owns ONLY
8
+ * served state and drift; WorkspaceContext owns execution context.
8
9
  *
9
- * This seam co-locates that invariant. Public surface:
10
- * view(sessionKey, path) -> {served, reported}
11
- * recordRead(sessionKey, path, rows, lineCount)
12
- * recordEdit(sessionKey, path, rows, lineCount, clearFrom)
13
- * scanDrift(sessionKey, path, resultHashes, resultLines, range) -> notice?
14
- * servedPositionsOf, currentPositionOfDrifted, _mergeServedRows (via served-store)
10
+ * Public surface: _mergeServedRows, loadServed, recordServed,
11
+ * recordServedTruncated, driftReported, markDriftReported,
12
+ * clearDriftReported, wipeServedState, servedPositionsOf,
13
+ * currentPositionOfDrifted, computeDrift, scanDrift, and
14
+ * hash-store persistence delegation (ServedPersistence).
15
15
  *
16
- * Explicit Workspace note: loadHashStore(cwd) now requires cwd. The
17
- * AsyncLocalStorage magic in workspace.ts is @internal — new code should pass
18
- * cwd explicitly through read-and-serve / edit-pipeline / drift. Forgetting
19
- * cwd is now a compile error where callers use this seam; legacy callers
20
- * via served-store still fall back to workspaceCwd() for backwards compat
21
- * but are marked deprecated.
22
- *
23
- * Ownership: This file now OWNS the served-merge invariant
24
- * (_mergeServedRows), the position-reconstruction math, and the drift
25
- * computation. Deleting it would scatter the served+drift invariant
26
- * across 4 files — it concentrates (deep).
16
+ * Ownership: This file OWNS the served-merge invariant
17
+ * (_mergeServedRows with orphan healing per ADR-0008), the
18
+ * position-reconstruction math, and the drift computation. Deleting
19
+ * it would scatter the served+drift invariant across 4 files — it
20
+ * concentrates (deep).
27
21
  *
28
22
  * @module dsh-better-edit/session-view
29
23
  */
30
- import { randomUUID } from "node:crypto";
31
- import { AsyncLocalStorage } from "node:async_hooks";
32
24
  import { HASH_RE } from "./hashline/hash-assign.js";
33
- import { loadHashStore, loadServedStore, withStore } from "./hash-store.js";
25
+ import { loadHashStore, loadServedStore, withStore, } from "./hash-store.js";
34
26
  import { SERVED_ECHO_CAP } from "./constants.js";
35
- import { fmtServedRows } from "./hashline/served.js";
36
- import { configDir, hashStorePath, resolveTarget } from "./paths.js";
37
- // --- workspace (private to this seam, @internal) ---
38
- const current = new AsyncLocalStorage();
39
- export function withWorkspace(cwd, fn) {
40
- return current.run(cwd, fn);
41
- }
42
- export function workspaceCwd() {
43
- return current.getStore();
44
- }
45
- // --- dsh-context (private to this seam) ---
46
- let fallbackSessionKey;
47
- export function sessionKeyFor(sessionId) {
48
- if (sessionId && sessionId.length > 0)
49
- return sessionId;
50
- // fallback for previews/tests
51
- return fallbackSessionKey ??= randomUUID();
52
- }
53
- export function execCwd(exec) {
54
- return exec.agent?.session.header.cwd ?? process.cwd();
55
- }
56
- export function execSessionKey(exec) {
57
- return sessionKeyFor(exec.agent?.session.id);
58
- }
59
- // --- paths re-export (seam visibility) ---
60
- export { configDir, hashStorePath, resolveTarget };
27
+ import { fmtServedRows } from "./hashline/anchor-pipeline.js";
61
28
  // --- hash-store re-export (persistence note) ---
62
29
  export { loadHashStore, loadServedStore, shutdownHashStore, withStore } from "./hash-store.js";
63
30
  /**
@@ -124,17 +91,99 @@ export async function loadServed(sessionKey, path) {
124
91
  const store = await loadServedStore();
125
92
  return store.getServed(sessionKey, path);
126
93
  }
127
- export async function recordServed(sessionKey, path, rows, lineCount) {
94
+ /** Anchors that must not be allocated while any session can still remember them. */
95
+ export async function loadAnchorReservations(path) {
96
+ const store = await loadServedStore();
97
+ return store.getAnchorReservations(path);
98
+ }
99
+ export async function loadServedCanons(sessionKey, path) {
100
+ const store = await loadServedStore();
101
+ return store.getServedCanons(sessionKey, path);
102
+ }
103
+ export async function loadEpochSnapshotId(sessionKey, path) {
104
+ const store = await loadServedStore();
105
+ return store.getEpochSnapshotId(sessionKey, path);
106
+ }
107
+ export async function loadRetiredAnchors(sessionKey, path) {
108
+ const store = await loadServedStore();
109
+ return store.getRetiredAnchors(sessionKey, path);
110
+ }
111
+ function addRetiredAnchors(store, sessionKey, path, hashes) {
112
+ const additions = [...hashes];
113
+ if (additions.length === 0)
114
+ return;
115
+ const retired = store.getRetiredAnchors(sessionKey, path);
116
+ for (const hash of additions) {
117
+ if (!HASH_RE.test(hash)) {
118
+ throw new TypeError(`Invalid retired hash: ${hash}`);
119
+ }
120
+ retired.add(hash);
121
+ }
122
+ store.upsertRetiredAnchors(sessionKey, path, JSON.stringify([...retired]));
123
+ }
124
+ function displacedHashes(current, updated) {
125
+ const remaining = new Set(updated.filter((hash) => hash !== null));
126
+ return new Set(current.filter((hash) => hash !== null && !remaining.has(hash)));
127
+ }
128
+ /** Keep freed anchors dead for this session until it has seen the whole file again. */
129
+ export async function retireAnchors(sessionKey, path, hashes) {
130
+ const additions = [...hashes];
131
+ if (additions.length === 0)
132
+ return;
133
+ const store = await loadServedStore();
134
+ withStore(() => {
135
+ addRetiredAnchors(store, sessionKey, path, additions);
136
+ });
137
+ }
138
+ export async function recordServed(sessionKey, path, rows, lineCount, fullReadHashes, fullReadCanons, fullReadSnapshotId) {
128
139
  if (rows.length === 0)
129
140
  return;
130
141
  try {
131
142
  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]);
132
146
  withStore(() => {
133
147
  const current = store.getServed(sessionKey, path);
134
148
  const updated = _mergeServedRows(current, rows, lineCount === undefined ? undefined : { truncateTo: lineCount });
135
- if (current.length === updated.length && current.every((v, i) => v === updated[i]))
136
- return;
137
- store.upsertServed(sessionKey, path, JSON.stringify(updated));
149
+ if (current.length !== updated.length || current.some((v, i) => v !== updated[i])) {
150
+ store.upsertServed(sessionKey, path, JSON.stringify(updated));
151
+ }
152
+ if (isFullRead) {
153
+ store.clearRetiredAnchors(sessionKey, path);
154
+ if (fullReadCanons)
155
+ store.upsertServedCanons(sessionKey, path, JSON.stringify(fullReadCanons));
156
+ if (fullReadSnapshotId)
157
+ store.upsertEpochSnapshotId(sessionKey, path, fullReadSnapshotId);
158
+ }
159
+ else {
160
+ // For partial reads, update canons for the served rows via hash-to-canon map (robust for partial views)
161
+ if (fullReadCanons && fullReadHashes) {
162
+ 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);
168
+ }
169
+ const currentCanons = store.getServedCanons(sessionKey, path);
170
+ const updatedCanons = currentCanons.slice();
171
+ while (updatedCanons.length < (lineCount ?? 0))
172
+ updatedCanons.push(null);
173
+ for (const row of rows) {
174
+ while (updatedCanons.length <= row.position)
175
+ updatedCanons.push(null);
176
+ const canonVal = row.hash ? (canonByHash.get(row.hash) ?? null) : null;
177
+ updatedCanons[row.position] = canonVal;
178
+ }
179
+ while (updatedCanons.length > 0 && updatedCanons[updatedCanons.length - 1] === null)
180
+ updatedCanons.pop();
181
+ store.upsertServedCanons(sessionKey, path, JSON.stringify(updatedCanons));
182
+ }
183
+ if (fullReadSnapshotId)
184
+ store.upsertEpochSnapshotId(sessionKey, path, fullReadSnapshotId);
185
+ addRetiredAnchors(store, sessionKey, path, displacedHashes(current, updated));
186
+ }
138
187
  });
139
188
  }
140
189
  catch (error) {
@@ -149,10 +198,10 @@ export async function recordServedTruncated(sessionKey, path, rows, lineCount, c
149
198
  withStore(() => {
150
199
  const current = store.getServed(sessionKey, path);
151
200
  const updated = _mergeServedRows(current, rows, { truncateTo: lineCount, clearFrom });
152
- // Avoid no-op writes (perf: O(1) check, no extra I/O beyond current read)
153
- if (current.length === updated.length && current.every((v, i) => v === updated[i]))
154
- return;
155
- store.upsertServed(sessionKey, path, JSON.stringify(updated));
201
+ if (current.length !== updated.length || current.some((v, i) => v !== updated[i])) {
202
+ store.upsertServed(sessionKey, path, JSON.stringify(updated));
203
+ }
204
+ addRetiredAnchors(store, sessionKey, path, displacedHashes(current, updated));
156
205
  });
157
206
  }
158
207
  catch (error) {
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Store — deep module owning tenancy + lifecycle + path resolution.
3
+ *
4
+ * Single seam that answers "which store, where, and is it open?"
5
+ * Tenancy (where DB lives) and lifecycle (central GC + row TTL + WAL)
6
+ * are private details of this seam; hash-store keeps only schema +
7
+ * row-family domain logic and imports path resolution from here.
8
+ * StoreConfig remains the config complement seam but its path is
9
+ * resolved via this Store seam.
10
+ *
11
+ * YAGNI-gated: DB plumbing (openDb/buildStore/quarantine/busy-retry/
12
+ * WAL/legacy JSON migration) stays in hash-store for now and is
13
+ * re-exported here for testability without importing domain helpers
14
+ * — full plumbing move is deferred to avoid contract risk. Old
15
+ * store-tenancy/store-lifecycle files are kept as compat shims
16
+ * re-exporting from this seam (reversible).
17
+ *
18
+ * @module dsh-better-edit/store
19
+ */
20
+ // Tenancy — re-export as seam ownership (private details, public via Store)
21
+ export { tenancyFor, configDir, hashStorePath, hashStoreDir, legacyHashStorePath, loadConfig, _resetConfigCache, expand, } from "../store-tenancy.js";
22
+ // Lifecycle — re-export as seam ownership
23
+ export { onStoreOpen, onAppStart, onSessionStart, setStoresGetter, runCentralJanitorIfDue, _resetLifecycleForTests, } from "../store-lifecycle.js";
24
+ // StoreConfig path helper — canonical Store seam entry for config consumers
25
+ export { loadConfig as loadStoreConfig } from "../store-config.js";
26
+ // Hash-store plumbing re-exported for testability without domain coupling
27
+ // (future: move openDb/buildStore/quarantine/busy-retry here)
28
+ export { isCorruptionError, loadHashStore, shutdownHashStore, withStore, findSnapshotPathsByHashes, upsertSnapshotFor, } from "../hash-store.js";
@@ -16,7 +16,7 @@ import { dirname, join } from "node:path";
16
16
  import { DatabaseSync } from "node:sqlite";
17
17
  import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
18
18
  import { hashStorePath, loadConfig } from "./paths.js";
19
- import { workspaceCwd } from "./workspace.js";
19
+ import { workspaceCwd } from "./workspace-context.js";
20
20
  import { errCode, splitLines } from "./utils.js";
21
21
  import { HASH_STORE_BUSY_TIMEOUT, SERVED_TTL_MS } from "./constants.js";
22
22
  // ---- throttling state (owned here) ----
package/lib/tool-edit.js CHANGED
@@ -10,8 +10,8 @@ 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 { execCwd, execSessionKey } from "./session-view.js";
14
- import { withWorkspace } from "./session-view.js";
13
+ import { execCwd, execSessionKey } from "./workspace-context.js";
14
+ import { withWorkspace } from "./workspace-context.js";
15
15
  import { findSnapshotPathsByHashes } from "./hash-store.js";
16
16
  import { parseHashRef } from "./hashline/anchor-pipeline.js";
17
17
  async function resolveNullPath(edits) {
package/lib/tool-read.js CHANGED
@@ -10,8 +10,8 @@ import { normalizeRequest as normReq, assertReadRequest, pathSchema } from "./co
10
10
  import { readAndServe } from "./read-and-serve.js";
11
11
  import { READ_DESCRIPTION } from "./prompts.js";
12
12
  import { normalizeEncoding } from "./encoding.js";
13
- import { execCwd, execSessionKey } from "./session-view.js";
14
- import { withWorkspace } from "./session-view.js";
13
+ import { execCwd, execSessionKey } from "./workspace-context.js";
14
+ import { withWorkspace } from "./workspace-context.js";
15
15
  /**
16
16
  * Register the hash-anchored `read` tool on the calling agent's scope.
17
17
  * @param _rootCtx - host context.
package/lib/tool-undo.js CHANGED
@@ -14,10 +14,10 @@ import { 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";
17
- import { recordServedTruncated } from "./session-view.js";
17
+ import { loadAnchorReservations, recordServedTruncated, retireAnchors, } from "./session-view.js";
18
18
  import { UNDO_DESCRIPTION } from "./prompts.js";
19
- import { execCwd, execSessionKey } from "./session-view.js";
20
- import { withWorkspace } from "./session-view.js";
19
+ import { execCwd, execSessionKey } from "./workspace-context.js";
20
+ import { withWorkspace } from "./workspace-context.js";
21
21
  /**
22
22
  * Register the `undo_last_edit` tool on the calling agent's scope.
23
23
  * @param _rootCtx - host context.
@@ -75,17 +75,30 @@ export function buildUndoTool(io, sandbox) {
75
75
  }
76
76
  const { text: currentStripped } = stripBOM(currentRaw);
77
77
  const currentNormalized = toLF(currentStripped);
78
- const currentHashes = await lineHashes(currentNormalized, absolutePath);
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);
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, {
86
+ content: undo.content,
87
+ hashes: undo.hashes,
88
+ removedHashes: retiredOriginalHashes,
89
+ }, undefined, false, blockedRestoreHashes, reservations.retiredHashes);
79
90
  const diffResult = genDiff(undo.content, currentNormalized, 0, undefined, undo.hashes);
80
91
  const linesAddedByEdit = cntDiff(diffResult.diff, "+");
81
92
  const linesRemovedByEdit = cntDiff(diffResult.diff, "-");
82
- const undoDiffResult = genDiff(currentNormalized, undo.content, 1, undo.hashes, currentHashes);
93
+ const undoDiffResult = genDiff(currentNormalized, undo.content, 1, restoredHashes, currentHashes);
83
94
  const undoDiff = undoDiffResult.diff;
84
95
  const undoDenseRows = [];
85
- for (let i = 0; i < undo.hashes.length; i++) {
86
- undoDenseRows.push({ position: i, hash: undo.hashes[i] });
96
+ for (let i = 0; i < restoredHashes.length; i++) {
97
+ undoDenseRows.push({ position: i, hash: restoredHashes[i] });
87
98
  }
88
99
  const restoredRange = changedRange(currentNormalized, undo.content);
100
+ const restoredSet = new Set(restoredHashes);
101
+ await retireAnchors(sessionKey, absolutePath, currentHashes.filter((hash) => !restoredSet.has(hash)));
89
102
  try {
90
103
  await io.writeText(absolutePath, undo.bom + restoreEndings(undo.content, undo.originalEnding), signal, exec, sandboxPolicy);
91
104
  }
@@ -93,7 +106,7 @@ export function buildUndoTool(io, sandbox) {
93
106
  throw sandbox.mapError(error, sandboxPolicy);
94
107
  }
95
108
  try {
96
- await upsertSnapshotFor(absolutePath, contentChecksum(undo.content), splitLines(undo.content).length, undo.hashes);
109
+ await upsertSnapshotFor(absolutePath, contentChecksum(undo.content), splitLines(undo.content).length, restoredHashes);
97
110
  }
98
111
  catch (error) {
99
112
  console.error("Failed to restore hash store snapshot after undo:", error);
@@ -1,4 +1,4 @@
1
- import type { ServedRow } from "./hashline/served.js";
1
+ import type { ServedRow } from "./hashline/anchor-pipeline.js";
2
2
  export type LineEnding = "\r\n" | "\n" | "\r";
3
3
  export declare function detectEnding(content: string): LineEnding;
4
4
  export declare function toLF(text: string): string;