dsh-better-edit 0.6.0 → 0.6.3

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/lib/mutation.js CHANGED
@@ -24,13 +24,15 @@
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
34
  import { sessionKeyFor } from "./workspace-context.js";
33
- import { loadServed, scanDrift, recordServedTruncated } from "./session-view.js";
35
+ import { loadServed, loadServedCanons, loadEpochSnapshotId, loadRetiredAnchors, scanDrift, recordServedTruncated, } from "./session-view.js";
34
36
  import { abortIf, splitLines } from "./utils.js";
35
37
  import { applyOne } from "./mutation/engine.js";
36
38
  import { runFileEdits, resolveMissingPath, } from "./mutation/engine.js";
@@ -54,6 +56,8 @@ export async function execPipeline(io, params, cwd, options) {
54
56
  const signal = options?.signal;
55
57
  abortIf(signal);
56
58
  const absolutePath = await io.resolve(path, cwd, signal);
59
+ const sessionKeyEarly = options?.sessionKey ?? sessionKeyFor(undefined);
60
+ const perSessionTombstoneForNorm = await loadRetiredAnchors(sessionKeyEarly, absolutePath);
57
61
  const rawText = await io.readText(absolutePath, signal);
58
62
  const { normalized: originalNormalized, bom, originalEnding, fileHashes: originalHashes, hadUtf8DecodeErrors, } = await normFromText({
59
63
  absolutePath,
@@ -63,9 +67,20 @@ export async function execPipeline(io, params, cwd, options) {
63
67
  maxLines: MAX_HASH_LINES,
64
68
  store: hashStore,
65
69
  noPersist: options?.noPersist,
70
+ reservedHashes: perSessionTombstoneForNorm,
71
+ retiredHashes: perSessionTombstoneForNorm,
66
72
  });
67
73
  const sessionKey = options?.sessionKey ?? sessionKeyFor(undefined);
68
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);
69
84
  const policy = options?.noPersist === true ? 'preview' : 'live';
70
85
  const applied = await applyOne({
71
86
  content: originalNormalized,
@@ -80,6 +95,12 @@ export async function execPipeline(io, params, cwd, options) {
80
95
  warnings: editWarnings,
81
96
  store: hashStore,
82
97
  persist: options?.noPersist !== true,
98
+ reservedHashes: perSessionTombstoneForNorm,
99
+ servedCanons,
100
+ tombstone: tombstonePerSession,
101
+ epochSnapshotId,
102
+ curSnapshotId,
103
+ strictPos,
83
104
  edit,
84
105
  }, async (error) => {
85
106
  if (error instanceof AnchorMismatchError ||
@@ -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, "/")) ?? "";
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Self-healing watcher for hash-anchored tools.
3
+ * Restores `read`/`edit` on the agent's own scope layer if an external
4
+ * preset deletes them (e.g. router-standard stage advance).
5
+ * See Rianico/dsh-better-edit#43.
6
+ * @module dsh-better-edit/self-heal
7
+ */
8
+ export function createSelfHealWatcher(options) {
9
+ const { agentId, rootCtx, agent, agentCtx, toolsSvc, hashReadDef, hashEditDef, healMinIntervalMs = 1000, } = options;
10
+ let lastHealAt = 0;
11
+ let healCount = 0;
12
+ let selfHealDisabled = false;
13
+ const stop = agentCtx.on("tools/change", () => {
14
+ try {
15
+ if (selfHealDisabled)
16
+ return;
17
+ // SAFETY: toolsSvc is the DSH tools service — shape is `layers.scoped: Map<agent, {tools}>` per cordis internals; narrow at boundary
18
+ const layer = toolsSvc
19
+ ?.layers?.scoped?.get?.(agent)?.tools;
20
+ if (!layer)
21
+ return;
22
+ const currentRead = layer?.get?.("read") ?? layer?.data?.get?.("read");
23
+ const currentEdit = layer?.get?.("edit") ?? layer?.data?.get?.("edit");
24
+ const readOk = currentRead === hashReadDef;
25
+ const editOk = currentEdit === hashEditDef;
26
+ if (readOk && editOk)
27
+ return;
28
+ const now = Date.now();
29
+ if (now - lastHealAt < healMinIntervalMs)
30
+ return;
31
+ if (healCount >= 2) {
32
+ selfHealDisabled = true;
33
+ try {
34
+ rootCtx.logger.error(`dsh-better-edit: repeated takeover of edit detected; self-heal disabled for agent ${agentId} \u2014 edit will remain built-in for this session \u2014 see Rianico/dsh-better-edit#43`);
35
+ }
36
+ catch {
37
+ // ignore — logger may throw in mock
38
+ }
39
+ return;
40
+ }
41
+ healCount++;
42
+ lastHealAt = now;
43
+ const restoreRead = !readOk;
44
+ const restoreEdit = !editOk;
45
+ const restoreCount = healCount;
46
+ queueMicrotask(() => {
47
+ try {
48
+ // SAFETY: re-read layer inside microtask — same shape as above
49
+ const currentLayer = toolsSvc
50
+ ?.layers?.scoped?.get?.(agent)?.tools;
51
+ if (!currentLayer)
52
+ return;
53
+ if (restoreEdit) {
54
+ try {
55
+ currentLayer?.data?.delete?.("edit");
56
+ }
57
+ catch {
58
+ // ignore — best-effort delete of intruding entry
59
+ }
60
+ try {
61
+ agentCtx.tools.register(hashEditDef);
62
+ }
63
+ catch (e) {
64
+ rootCtx.logger.warn(`dsh-better-edit: self-heal failed for agent ${agentId}: ${e instanceof Error ? e.message : String(e)} \u2014 see Rianico/dsh-better-edit#43`);
65
+ return;
66
+ }
67
+ rootCtx.logger.warn(`dsh-better-edit: restored hash-anchored edit after external takeover \u2014 agent ${agentId} (${restoreCount}/2) \u2014 see Rianico/dsh-better-edit#43`);
68
+ }
69
+ if (restoreRead) {
70
+ try {
71
+ currentLayer?.data?.delete?.("read");
72
+ }
73
+ catch {
74
+ // ignore — best-effort delete of intruding entry
75
+ }
76
+ try {
77
+ agentCtx.tools.register(hashReadDef);
78
+ }
79
+ catch (e) {
80
+ rootCtx.logger.warn(`dsh-better-edit: self-heal failed for agent ${agentId}: ${e instanceof Error ? e.message : String(e)} \u2014 see Rianico/dsh-better-edit#43`);
81
+ return;
82
+ }
83
+ rootCtx.logger.warn(`dsh-better-edit: restored hash-anchored read after external takeover \u2014 agent ${agentId} (${restoreCount}/2) \u2014 see Rianico/dsh-better-edit#43`);
84
+ }
85
+ }
86
+ catch (error) {
87
+ rootCtx.logger.warn(`dsh-better-edit: self-heal failed for agent ${agentId}: ${error instanceof Error ? error.message : String(error)} \u2014 see Rianico/dsh-better-edit#43`);
88
+ }
89
+ });
90
+ }
91
+ catch (error) {
92
+ try {
93
+ rootCtx.logger.warn(`dsh-better-edit: self-heal failed for agent ${agentId}: ${error instanceof Error ? error.message : String(error)} \u2014 see Rianico/dsh-better-edit#43`);
94
+ }
95
+ catch {
96
+ // ignore — logger may throw in mock
97
+ }
98
+ }
99
+ });
100
+ return stop;
101
+ }
@@ -22,7 +22,7 @@
22
22
  * @module dsh-better-edit/session-view
23
23
  */
24
24
  import { HASH_RE } from "./hashline/hash-assign.js";
25
- import { loadHashStore, loadServedStore, withStore } from "./hash-store.js";
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";
28
28
  // --- hash-store re-export (persistence note) ---
@@ -91,17 +91,99 @@ export async function loadServed(sessionKey, path) {
91
91
  const store = await loadServedStore();
92
92
  return store.getServed(sessionKey, path);
93
93
  }
94
- 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) {
95
139
  if (rows.length === 0)
96
140
  return;
97
141
  try {
98
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]);
99
146
  withStore(() => {
100
147
  const current = store.getServed(sessionKey, path);
101
148
  const updated = _mergeServedRows(current, rows, lineCount === undefined ? undefined : { truncateTo: lineCount });
102
- if (current.length === updated.length && current.every((v, i) => v === updated[i]))
103
- return;
104
- 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
+ }
105
187
  });
106
188
  }
107
189
  catch (error) {
@@ -116,10 +198,10 @@ export async function recordServedTruncated(sessionKey, path, rows, lineCount, c
116
198
  withStore(() => {
117
199
  const current = store.getServed(sessionKey, path);
118
200
  const updated = _mergeServedRows(current, rows, { truncateTo: lineCount, clearFrom });
119
- // Avoid no-op writes (perf: O(1) check, no extra I/O beyond current read)
120
- if (current.length === updated.length && current.every((v, i) => v === updated[i]))
121
- return;
122
- 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));
123
205
  });
124
206
  }
125
207
  catch (error) {
package/lib/tool-undo.js CHANGED
@@ -14,7 +14,7 @@ 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
19
  import { execCwd, execSessionKey } from "./workspace-context.js";
20
20
  import { withWorkspace } from "./workspace-context.js";
@@ -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);
@@ -89,6 +89,8 @@ export interface ReadNormOptions {
89
89
  maxLines?: number;
90
90
  store?: HashStore;
91
91
  noPersist?: boolean;
92
+ reservedHashes?: ReadonlySet<string>;
93
+ retiredHashes?: ReadonlySet<string>;
92
94
  }
93
95
  export declare function normFromText(input: {
94
96
  absolutePath: string;
@@ -98,6 +100,8 @@ export declare function normFromText(input: {
98
100
  maxLines?: number;
99
101
  store?: HashStore;
100
102
  noPersist?: boolean;
103
+ reservedHashes?: ReadonlySet<string>;
104
+ retiredHashes?: ReadonlySet<string>;
101
105
  hadUtf8DecodeErrors?: boolean;
102
106
  }): Promise<NormFile>;
103
107
  export declare function readNormFile(path: string, cwd: string, options?: ReadNormOptions): Promise<NormFile>;
@@ -130,6 +134,8 @@ export interface PreviewOpts {
130
134
  export interface ReadViewOpts extends PreviewOpts {
131
135
  encoding?: string;
132
136
  signal?: AbortSignal;
137
+ reservedHashes?: ReadonlySet<string>;
138
+ retiredHashes?: ReadonlySet<string>;
133
139
  }
134
140
  export declare function preview(content: string, hashes: string[], opts?: PreviewOpts, absolutePath?: string): Promise<{
135
141
  text: string;
@@ -21,6 +21,7 @@ export interface LegacySnapshot {
21
21
  export declare function isValidHashList(value: unknown): value is string[];
22
22
  export declare function isValidSnapshot(value: unknown): value is LegacySnapshot;
23
23
  /** A served-row array: per-position hash, or null for never-served slots. */
24
+ export declare function isValidCanonsList(value: unknown): value is (string | null)[];
24
25
  export declare function isValidServedList(value: unknown): value is (string | null)[];
25
26
  /** The undo row contract shared by undo-edit and the store. */
26
27
  export interface UndoRecord {
@@ -66,14 +67,28 @@ export interface HashStore {
66
67
  export interface ServedPersistence {
67
68
  getServed(sessionKey: string, path: string): (string | null)[];
68
69
  getServedReported(sessionKey: string, path: string): Set<string>;
70
+ getAnchorReservations(path: string): AnchorReservations;
71
+ getRetiredAnchors(sessionKey: string, path: string): Set<string>;
72
+ getServedCanons(sessionKey: string, path: string): (string | null)[];
73
+ getEpochSnapshotId(sessionKey: string, path: string): string | undefined;
69
74
  upsertServed(sessionKey: string, path: string, hashesJson: string): void;
70
75
  upsertServedReported(sessionKey: string, path: string, reportedJson: string): void;
71
76
  clearServedReported(sessionKey: string, path: string): void;
77
+ upsertRetiredAnchors(sessionKey: string, path: string, hashesJson: string): void;
78
+ clearRetiredAnchors(sessionKey: string, path: string): void;
79
+ upsertServedCanons(sessionKey: string, path: string, canonsJson: string): void;
80
+ clearServedCanons(sessionKey: string, path: string): void;
81
+ upsertEpochSnapshotId(sessionKey: string, path: string, snapshotId: string): void;
82
+ clearEpochSnapshotId(sessionKey: string, path: string): void;
72
83
  deleteServed(sessionKey: string, path: string): void;
73
84
  deleteServedByPath(path: string): void;
74
85
  wipeServed(sessionKey: string): void;
75
86
  pruneServedOlderThan(ts: number): void;
76
87
  }
88
+ export interface AnchorReservations {
89
+ reservedHashes: Set<string>;
90
+ retiredHashes: Set<string>;
91
+ }
77
92
  export type InternalHashStore = HashStore & ServedPersistence;
78
93
  /** Load the store as served persistence — internal, for SessionView only. */
79
94
  export declare function loadServedStore(cwd?: string): Promise<ServedPersistence>;
@@ -88,6 +88,11 @@ export declare function verifyServedRange(args: {
88
88
  fileHashes: string[];
89
89
  fileLines: string[];
90
90
  filePath?: string;
91
+ servedCanons?: (string | null)[];
92
+ tombstone?: ReadonlySet<string>;
93
+ epochSnapshotId?: string;
94
+ curSnapshotId?: string;
95
+ strictPos?: boolean;
91
96
  }): void;
92
97
  export interface ResolvedRange {
93
98
  startLine: number;
@@ -103,7 +108,7 @@ type LIdx = {
103
108
  lineStarts: number[];
104
109
  };
105
110
  export declare function buildIdx(content: string): LIdx;
106
- export declare function applyEdit(content: string, edit: HEdit, signal?: AbortSignal, precomputedHashes?: string[], filePath?: string, served?: (string | null)[]): {
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): {
107
112
  content: string;
108
113
  firstChangedLine: number | undefined;
109
114
  lastChangedLine: number | undefined;
@@ -23,5 +23,5 @@ export declare const HL_PREFIX_MINUS_RE: RegExp;
23
23
  export declare const HL_BARE_PREFIX_RE: RegExp;
24
24
  export declare const CANON_VERSION = 2;
25
25
  export declare function canon(line: string): string;
26
- export declare function lineHashesPure(content: string): string[];
27
- export declare function mapStableHashes(oldContent: string, oldHashes: string[], newContent: string, removedHashes?: Set<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[];
@@ -10,4 +10,4 @@ export declare function lineHashes(content: string, path?: string, previous?: {
10
10
  content: string;
11
11
  hashes: string[];
12
12
  removedHashes?: Set<string>;
13
- }, ioOrStore?: HashStore | HashSnapshotIO, persist?: boolean): Promise<string[]>;
13
+ }, ioOrStore?: HashStore | HashSnapshotIO, persist?: boolean, reservedHashes?: ReadonlySet<string>, retiredHashes?: ReadonlySet<string>): Promise<string[]>;
@@ -79,6 +79,12 @@ export interface ApplyOneInput {
79
79
  countHashes?: string[];
80
80
  store?: HashStore;
81
81
  persist: boolean;
82
+ reservedHashes?: ReadonlySet<string>;
83
+ servedCanons?: (string | null)[];
84
+ tombstone?: ReadonlySet<string>;
85
+ epochSnapshotId?: string;
86
+ curSnapshotId?: string;
87
+ strictPos?: boolean;
82
88
  /** Pre-resolved edit (single path keeps resEdit before IO for error order). */
83
89
  edit?: HEdit;
84
90
  }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Self-healing watcher for hash-anchored tools.
3
+ * Restores `read`/`edit` on the agent's own scope layer if an external
4
+ * preset deletes them (e.g. router-standard stage advance).
5
+ * See Rianico/dsh-better-edit#43.
6
+ * @module dsh-better-edit/self-heal
7
+ */
8
+ export interface SelfHealOptions {
9
+ agentId: string;
10
+ rootCtx: {
11
+ logger: {
12
+ warn(msg: string): void;
13
+ error(msg: string): void;
14
+ };
15
+ get(service: string): any;
16
+ };
17
+ agent: unknown;
18
+ agentCtx: {
19
+ tools: {
20
+ register(def: unknown): () => void;
21
+ };
22
+ on(event: string, handler: () => void): () => void;
23
+ };
24
+ toolsSvc: unknown;
25
+ hashReadDef: unknown;
26
+ hashEditDef: unknown;
27
+ healMinIntervalMs?: number;
28
+ }
29
+ export declare function createSelfHealWatcher(options: SelfHealOptions): () => void;
@@ -21,6 +21,7 @@
21
21
  *
22
22
  * @module dsh-better-edit/session-view
23
23
  */
24
+ import { type AnchorReservations } from "./hash-store.js";
24
25
  import type { ServedRow, ResolvedRange } from "./hashline/anchor-pipeline.js";
25
26
  export { loadHashStore, loadServedStore, shutdownHashStore, withStore } from "./hash-store.js";
26
27
  export type { HashStore } from "./hash-store.js";
@@ -40,7 +41,14 @@ export declare function _mergeServedRows(current: (string | null)[], rows: Serve
40
41
  clearFrom?: number;
41
42
  }): (string | null)[];
42
43
  export declare function loadServed(sessionKey: string, path: string): Promise<(string | null)[]>;
43
- export declare function recordServed(sessionKey: string, path: string, rows: ServedEntry[], lineCount?: number): Promise<void>;
44
+ /** Anchors that must not be allocated while any session can still remember them. */
45
+ export declare function loadAnchorReservations(path: string): Promise<AnchorReservations>;
46
+ export declare function loadServedCanons(sessionKey: string, path: string): Promise<(string | null)[]>;
47
+ export declare function loadEpochSnapshotId(sessionKey: string, path: string): Promise<string | undefined>;
48
+ export declare function loadRetiredAnchors(sessionKey: string, path: string): Promise<Set<string>>;
49
+ /** Keep freed anchors dead for this session until it has seen the whole file again. */
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>;
44
52
  export declare function recordServedTruncated(sessionKey: string, path: string, rows: ServedEntry[], lineCount: number, clearFrom?: number): Promise<void>;
45
53
  export declare function driftReported(sessionKey: string, path: string): Promise<Set<string>>;
46
54
  export declare function markDriftReported(sessionKey: string, path: string, hashes: string[]): Promise<void>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-better-edit",
3
- "version": "0.6.0",
3
+ "version": "0.6.3",
4
4
  "type": "module",
5
5
  "description": "Hash-anchored read/edit/undo_last_edit tools for DeepSeek Harness (dsh). Every line gets a unique 3-char hash (A-Za-z0-9) that stays stable across edits; stale or ambiguous anchors are rejected, never fuzzy-matched. Undo persists across restarts.",
6
6
  "main": "lib/index.js",
@@ -84,12 +84,12 @@
84
84
  "@commitlint/cli": "^21.2.2",
85
85
  "@commitlint/config-conventional": "^21.2.2",
86
86
  "@deepseek-ai/cordis": "^4.0.1",
87
- "@deepseek-ai/dsh-agent": "0.1.0-rc.6",
88
- "@deepseek-ai/dsh-fs": "0.1.0-rc.6",
89
- "@deepseek-ai/dsh-home-paths": "0.1.0-rc.6",
90
- "@deepseek-ai/dsh-sandbox": "^0.1.0-rc.6",
91
- "@deepseek-ai/dsh-session": "0.1.0-rc.6",
92
- "@deepseek-ai/dsh-tools": "0.1.0-rc.6",
87
+ "@deepseek-ai/dsh-agent": "0.1.1-rc.2",
88
+ "@deepseek-ai/dsh-fs": "0.1.1-rc.2",
89
+ "@deepseek-ai/dsh-home-paths": "0.1.1-rc.2",
90
+ "@deepseek-ai/dsh-sandbox": "0.1.1-rc.2",
91
+ "@deepseek-ai/dsh-session": "0.1.1-rc.2",
92
+ "@deepseek-ai/dsh-tools": "0.1.1-rc.2",
93
93
  "@semantic-release/changelog": "^7.0.0",
94
94
  "@semantic-release/git": "^11.0.1",
95
95
  "@semantic-release/github": "^12.0.9",