dsh-better-edit 1.2.3 → 1.2.5

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 (105) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +39 -20
  3. package/README.zh.md +39 -31
  4. package/lib/contract.js +53 -22
  5. package/lib/domain-errors.js +18 -10
  6. package/lib/edit-mode.js +11 -0
  7. package/lib/encoding.js +2 -0
  8. package/lib/file-encoding-state.js +138 -44
  9. package/lib/file-view.js +26 -205
  10. package/lib/fs-bridge.js +53 -71
  11. package/lib/hashline/anchor-pipeline.js +8 -499
  12. package/lib/hashline/hash-assign.js +55 -4
  13. package/lib/hashline/index.js +5 -2
  14. package/lib/hashline/served-evidence.js +531 -0
  15. package/lib/index.js +177 -33
  16. package/lib/mutation/engine.js +19 -61
  17. package/lib/mutation.js +63 -105
  18. package/lib/noop-guard.js +24 -38
  19. package/lib/paths.js +9 -5
  20. package/lib/preset-toolset.js +144 -0
  21. package/lib/prompts.js +3 -3
  22. package/lib/read-and-serve.js +51 -53
  23. package/lib/reclaim.js +65 -0
  24. package/lib/self-heal.js +14 -13
  25. package/lib/session-view.js +79 -49
  26. package/lib/store/index.js +14 -14
  27. package/lib/store-config.js +4 -5
  28. package/lib/store-lifecycle.js +1 -1
  29. package/lib/tool-edit.js +14 -56
  30. package/lib/tool-read.js +2 -8
  31. package/lib/tool-str-replace-editor.js +34 -18
  32. package/lib/tool-undo.js +42 -24
  33. package/lib/types/contract.d.ts +11 -20
  34. package/lib/types/domain-errors.d.ts +14 -10
  35. package/lib/types/edit-mode.d.ts +11 -0
  36. package/lib/types/encoding.d.ts +1 -0
  37. package/lib/types/file-encoding-state.d.ts +51 -14
  38. package/lib/types/file-view.d.ts +18 -56
  39. package/lib/types/fs-bridge.d.ts +0 -1
  40. package/lib/types/hashline/anchor-pipeline.d.ts +6 -128
  41. package/lib/types/hashline/hash-assign.d.ts +40 -0
  42. package/lib/types/hashline/index.d.ts +6 -4
  43. package/lib/types/hashline/served-evidence.d.ts +152 -0
  44. package/lib/types/mutation/engine.d.ts +4 -12
  45. package/lib/types/mutation.d.ts +10 -58
  46. package/lib/types/noop-guard.d.ts +2 -33
  47. package/lib/types/paths.d.ts +0 -1
  48. package/lib/types/preset-toolset.d.ts +61 -0
  49. package/lib/types/reclaim.d.ts +36 -0
  50. package/lib/types/self-heal.d.ts +9 -3
  51. package/lib/types/session-view.d.ts +38 -8
  52. package/lib/types/store/index.d.ts +12 -11
  53. package/lib/types/store-config.d.ts +1 -1
  54. package/lib/types/store-lifecycle.d.ts +12 -2
  55. package/lib/types/tool-edit.d.ts +2 -4
  56. package/lib/types/tool-read.d.ts +0 -5
  57. package/lib/types/tool-str-replace-editor.d.ts +0 -6
  58. package/lib/types/tool-undo.d.ts +0 -5
  59. package/package.json +3 -2
  60. package/lib/drift.js +0 -5
  61. package/lib/dsh-context.js +0 -5
  62. package/lib/edit-engine.js +0 -7
  63. package/lib/edit-normalize.js +0 -9
  64. package/lib/edit-pipeline.js +0 -6
  65. package/lib/file-kind.js +0 -6
  66. package/lib/file-reader.js +0 -6
  67. package/lib/guidance/index.js +0 -8
  68. package/lib/hashline/alphabet.js +0 -2
  69. package/lib/hashline/apply.js +0 -2
  70. package/lib/hashline/hasher.js +0 -2
  71. package/lib/hashline/parse.js +0 -2
  72. package/lib/hashline/pure.js +0 -2
  73. package/lib/hashline/resolve.js +0 -3
  74. package/lib/hashline/served.js +0 -2
  75. package/lib/preview-controller.js +0 -65
  76. package/lib/read-render.js +0 -6
  77. package/lib/schema.js +0 -24
  78. package/lib/served-store.js +0 -5
  79. package/lib/tool-batch-edit.js +0 -190
  80. package/lib/truncate.js +0 -6
  81. package/lib/types/drift.d.ts +0 -5
  82. package/lib/types/dsh-context.d.ts +0 -5
  83. package/lib/types/edit-engine.d.ts +0 -7
  84. package/lib/types/edit-normalize.d.ts +0 -1
  85. package/lib/types/edit-pipeline.d.ts +0 -6
  86. package/lib/types/file-kind.d.ts +0 -6
  87. package/lib/types/file-reader.d.ts +0 -6
  88. package/lib/types/guidance/index.d.ts +0 -8
  89. package/lib/types/hashline/alphabet.d.ts +0 -1
  90. package/lib/types/hashline/apply.d.ts +0 -1
  91. package/lib/types/hashline/hasher.d.ts +0 -1
  92. package/lib/types/hashline/parse.d.ts +0 -1
  93. package/lib/types/hashline/pure.d.ts +0 -1
  94. package/lib/types/hashline/resolve.d.ts +0 -1
  95. package/lib/types/hashline/served.d.ts +0 -1
  96. package/lib/types/preview-controller.d.ts +0 -33
  97. package/lib/types/read-render.d.ts +0 -6
  98. package/lib/types/schema.d.ts +0 -25
  99. package/lib/types/served-store.d.ts +0 -5
  100. package/lib/types/tool-batch-edit.d.ts +0 -25
  101. package/lib/types/truncate.d.ts +0 -6
  102. package/lib/types/validation.d.ts +0 -6
  103. package/lib/types/workspace.d.ts +0 -5
  104. package/lib/validation.js +0 -6
  105. package/lib/workspace.js +0 -5
package/lib/noop-guard.js CHANGED
@@ -1,46 +1,32 @@
1
- import { formatError, formatWarning } from "./domain-errors.js";
2
- import { NOOP_LOOP_THRESHOLD } from "./constants.js";
1
+ /**
2
+ * The noop-loop counters, keyed by `(session, file)` identity (ADR-0039).
3
+ *
4
+ * WHY the session in the key: a counter keyed by the file alone is shared state
5
+ * across sessions, so one session's repeats advance another session's count —
6
+ * and at `NOOP_LOOP_THRESHOLD` the second session's FIRST submission of an
7
+ * unchanged edit was refused for a loop it never ran (measured pre-fix:
8
+ * session-A=1, session-A=2, session-B=3). The loop is a property of what a
9
+ * session keeps resubmitting, not of the file.
10
+ *
11
+ * The key is an IDENTITY, not a second copy of the payload: the payload
12
+ * (`noopPayloadKey`) already carries the absolute path as its first element, so
13
+ * the entry's `payload` equality check is scoped by the same file the key names.
14
+ */
3
15
  const noopLoopTracker = new Map();
16
+ /** Tracker identity: one counter per `(session, file)` pair. */
17
+ function trackerKey(sessionKey, absolutePath) {
18
+ return JSON.stringify([sessionKey, absolutePath]);
19
+ }
4
20
  export function noopPayloadKey(absolutePath, anchorFrom, anchorTo, replaceWith) {
5
21
  return JSON.stringify([absolutePath, anchorFrom, anchorTo, replaceWith]);
6
22
  }
7
- export function trackNoopPayload(absolutePath, payload) {
8
- const existing = noopLoopTracker.get(absolutePath);
23
+ export function trackNoopPayload(sessionKey, absolutePath, payload) {
24
+ const key = trackerKey(sessionKey, absolutePath);
25
+ const existing = noopLoopTracker.get(key);
9
26
  const count = existing && existing.payload === payload ? existing.count + 1 : 1;
10
- noopLoopTracker.set(absolutePath, { payload, count });
27
+ noopLoopTracker.set(key, { payload, count });
11
28
  return count;
12
29
  }
13
- export function clearNoopLoop(absolutePath) {
14
- noopLoopTracker.delete(absolutePath);
15
- }
16
- export { NOOP_LOOP_THRESHOLD };
17
- export function runNoopPolicySync(input, count) {
18
- if (count >= NOOP_LOOP_THRESHOLD) {
19
- const message = formatError("E_NOOP_LOOP", {
20
- ref: input.ref,
21
- anchorFrom: input.anchorFrom,
22
- anchorTo: input.anchorTo,
23
- count,
24
- batch: input.batch,
25
- servedBlock: "",
26
- });
27
- return { action: "reject", count, message };
28
- }
29
- if (count === 2) {
30
- // Channel rule: applied-tier notices are human-observable → USER audience via the registry.
31
- const notice = formatWarning("W_NOOP", {
32
- ref: input.ref,
33
- anchorFrom: input.anchorFrom,
34
- anchorTo: input.anchorTo,
35
- batch: input.batch,
36
- count,
37
- });
38
- return { action: "warn", count, notice };
39
- }
40
- return { action: "proceed", count };
41
- }
42
- export async function runNoopPolicy(input) {
43
- const payload = noopPayloadKey(input.absolutePath, input.anchorFrom, input.anchorTo, input.replaceWith);
44
- const count = trackNoopPayload(input.absolutePath, payload);
45
- return runNoopPolicySync(input, count);
30
+ export function clearNoopLoop(sessionKey, absolutePath) {
31
+ noopLoopTracker.delete(trackerKey(sessionKey, absolutePath));
46
32
  }
package/lib/paths.js CHANGED
@@ -1,15 +1,19 @@
1
1
  /**
2
2
  * Paths — thin adapter over StoreTenancy + CanonicalPath.
3
- * Public API preserved for compat: configDir, hashStorePath, hashStoreDir,
4
- * legacyHashStorePath, resolveTarget, toCwd.
5
- * Deep tenancy lives in StoreTenancy (config via StoreConfig); canonical
6
- * resolution in CanonicalPath.
3
+ * Carries only what its consumers name: `resolveTarget`/`canonicalSync`
4
+ * (canonical resolution, owned by CanonicalPath) and `toCwd` (workspace joins
5
+ * over `expand`).
6
+ *
7
+ * Store facts (`configDir`, `hashStorePath`, `hashStoreDir`,
8
+ * `legacyHashStorePath`, lifecycle hooks) are deliberately NOT re-exported
9
+ * here: they live in `store-tenancy`/`store-lifecycle`, and re-exporting the
10
+ * store barrel from this file closed the cycle
11
+ * `paths → store/index → store-lifecycle → paths`. Name the owning leaf.
7
12
  * @module dsh-better-edit/paths
8
13
  */
9
14
  import { isAbsolute } from "node:path";
10
15
  import { resolve as resolvePath } from "node:path";
11
16
  import { expand } from "./store-tenancy.js";
12
- export * from "./store/index.js"; // Store seam — single answer for "which store, where" (tenancy+lifecycle+path)
13
17
  export { canonicalAsync as resolveTarget } from "./canonical-path.js";
14
18
  export { canonicalSync } from "./canonical-path.js";
15
19
  export function toCwd(filePath, cwd) {
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Preset tool-policy gate: which hashline-owned tools one agent install may
3
+ * register. The registry cannot enforce a preset's policy for this plugin —
4
+ * scope restrictions filter only *inherited* tools, never a scope's own
5
+ * registrations (Rianico/dsh-better-edit#110) — so the install consults the
6
+ * composed preset's own layer instead.
7
+ *
8
+ * `read` is unconditional: it is the plugin's core capability and the source of
9
+ * every anchor. Every mutating tool is installed only when the preset's layer
10
+ * resolves the matching tool, which keeps `edit` paired with `read` and never
11
+ * shadows a tool the preset did not compose.
12
+ *
13
+ * The probe is an optional-service seam: no `agentPresets` service, no composed
14
+ * preset (preset-free composition), or no scope-read API (`acquireScope` on
15
+ * 0.2.x, `standingKeyFor` on older registries) keeps today's unconditional
16
+ * install, so a host that predates 0.2.1 keeps its pre-gate behavior.
17
+ * @module dsh-better-edit/preset-toolset
18
+ */
19
+ /** Today's install — the fallback for every composition the gate cannot read. */
20
+ export const UNCONDITIONAL_TOOLSET = {
21
+ edit: true,
22
+ strReplaceEditor: true,
23
+ undo: true,
24
+ writeHook: true,
25
+ };
26
+ const EDIT_SECTION = "tool:edit";
27
+ const UNDO_SECTION = "tool:undo_last_edit";
28
+ /**
29
+ * Derive the toolset from one predicate over preset tool names. `undo` follows
30
+ * `edit` because `undo_last_edit` reverts only hashline edits: installing it
31
+ * beside no `edit` would advertise a history that can never exist.
32
+ */
33
+ export function toolsetFor(resolves) {
34
+ const edit = resolves("edit");
35
+ return {
36
+ edit,
37
+ strReplaceEditor: resolves("str_replace_editor"),
38
+ undo: edit,
39
+ writeHook: resolves("write"),
40
+ };
41
+ }
42
+ /**
43
+ * Keep only the guidance sections whose tool was installed. `tool:read` always
44
+ * stays; the edit and undo sections follow their tools so the prompt never
45
+ * advertises a catalog entry the agent does not have.
46
+ */
47
+ export function sectionsForToolset(sections, toolset) {
48
+ return sections.filter((section) => {
49
+ if (section.name === EDIT_SECTION)
50
+ return toolset.edit;
51
+ if (section.name === UNDO_SECTION)
52
+ return toolset.undo;
53
+ return true;
54
+ });
55
+ }
56
+ const ASYNC_DISPOSE = Symbol.asyncDispose;
57
+ function warn(host, message) {
58
+ try {
59
+ host.logger?.warn(message);
60
+ }
61
+ catch {
62
+ // Diagnostics must never fail an install.
63
+ }
64
+ }
65
+ /**
66
+ * Resolve the toolset for one agent from its composed preset. Every failure —
67
+ * a missing service, an unreadable preset, a rejected scope read, or a throwing
68
+ * registry — falls back to {@link UNCONDITIONAL_TOOLSET} (and warns), never to a
69
+ * smaller set: the gate may only ever remove a tool it has positively seen the
70
+ * preset decline.
71
+ */
72
+ export async function resolveToolset(host, agentCtx) {
73
+ try {
74
+ return (await probePreset(host, agentCtx)) ?? UNCONDITIONAL_TOOLSET;
75
+ }
76
+ catch (error) {
77
+ warn(host, `dsh-better-edit: preset tool policy probe failed, installing the full tool set: ${error instanceof Error ? error.message : String(error)}`);
78
+ return UNCONDITIONAL_TOOLSET;
79
+ }
80
+ }
81
+ /** `undefined` means "no usable preset policy" — the caller installs today's set. */
82
+ async function probePreset(host, agentCtx) {
83
+ const presets = host.get("agentPresets");
84
+ if (!presets || typeof presets.composedPreset !== "function")
85
+ return undefined;
86
+ const presetId = presets.composedPreset(agentCtx);
87
+ // Preset-free composition: nothing composed the agent plane, so there is no
88
+ // preset policy to honour.
89
+ if (typeof presetId !== "string" || presetId.length === 0)
90
+ return undefined;
91
+ const tools = host.get("tools");
92
+ if (!tools || typeof tools.get !== "function")
93
+ return undefined;
94
+ const scope = await readPresetScope(presets, presetId, host);
95
+ if (scope === undefined)
96
+ return undefined;
97
+ try {
98
+ return toolsetFor((name) => tools.get(name, scope.key) !== undefined);
99
+ }
100
+ finally {
101
+ // Exactly one release, and only for a lease whose key was usable.
102
+ await scope.release();
103
+ }
104
+ }
105
+ /**
106
+ * Feature-detect the scope read: `acquireScope` (0.2.x, leased) first, then
107
+ * `standingKeyFor` (older, unleased). Neither means a pre-gate host. Both are
108
+ * awaited — on every supported host they resolve a promise, and reading `.key`
109
+ * off an unresolved promise would silently degrade the gate to the full set.
110
+ */
111
+ async function readPresetScope(presets, presetId, host) {
112
+ if (typeof presets.acquireScope === "function") {
113
+ const lease = await presets.acquireScope(presetId);
114
+ // A lease without a key is unusable: fall through (and release nothing,
115
+ // since no probe ever ran under it).
116
+ if (lease !== undefined && lease.key !== undefined) {
117
+ const key = lease.key;
118
+ return { key, release: () => disposeLease(lease, host) };
119
+ }
120
+ }
121
+ if (typeof presets.standingKeyFor === "function") {
122
+ const key = await presets.standingKeyFor(presetId);
123
+ if (key !== undefined)
124
+ return { key, release: async () => { } };
125
+ }
126
+ return undefined;
127
+ }
128
+ /**
129
+ * Release an `acquireScope` lease. Best effort by design: the probe answer
130
+ * already stands, so a failed release must not change which tools install.
131
+ */
132
+ async function disposeLease(lease, host) {
133
+ if (ASYNC_DISPOSE === undefined)
134
+ return;
135
+ const dispose = lease[ASYNC_DISPOSE];
136
+ if (typeof dispose !== "function")
137
+ return;
138
+ try {
139
+ await dispose.call(lease);
140
+ }
141
+ catch (error) {
142
+ warn(host, `dsh-better-edit: releasing the preset scope lease failed: ${error instanceof Error ? error.message : String(error)}`);
143
+ }
144
+ }
package/lib/prompts.js CHANGED
@@ -10,7 +10,7 @@ export const EDIT_DESCRIPTION = 'Edit a range of lines in a text file with `{ "f
10
10
  '`file` is the text file (a file, never a directory). `read` shows `HASH\u2502content` (e.g. `wUp\u2502 "site": {`) \u2014 use bare 3-char HASH anchors for ' +
11
11
  '`anchor_from`/`anchor_to` (e.g. "wUp"), never `HASH\u2502content`. `replace_with` is bare content, \\n joins lines, "" deletes. ' +
12
12
  'Example: `{"file":"a.py","edits":[{"anchor_from":"wUp","anchor_to":"AU6","replace_with":"new"}]}` (legacy tuples still fold). Reuse `HASH\u2502content` from the diff after success unless the result says NOT recorded as served, then re-read. ' +
13
- "On failure follow the error hint: `[TO MODEL]` errors need a retry with fresh anchors, `[USER]` is human-only.";
13
+ "`[TO MODEL]` errors need a retry with fresh anchors; `[MODEL]` warnings need action; `[USER]` is human-only.";
14
14
  export const EDIT_GUIDANCE = {
15
15
  intro: "Edit a range of lines via a bare 3-char HASH anchor \u2014 payload is { file, edits: [{anchor_from, anchor_to, replace_with}] } (single-file atomic; legacy tuples still fold pre-validation).",
16
16
  lines: [
@@ -21,7 +21,7 @@ export const EDIT_GUIDANCE = {
21
21
  "`edit`: `edits` entries are objects `{anchor_from, anchor_to, replace_with}` \u2014 legacy tuples still fold pre-validation; unknown fields are rejected.",
22
22
  "`edit`: after an edit whose serve landed, the returned diff shows fresh anchors (`HASH\u2502content`) \u2014 copy new `HASH` values from there for the next edit; if the result says the rows were NOT recorded as served, re-read instead.",
23
23
  "`edit`: `anchor_from`/`anchor_to` are inclusive; batch multiple edits to the same file only when independent \u2014 they apply atomically (fail \u2192 nothing written).",
24
- "`edit`: `[TO MODEL]` errors (e.g. `E_STALE_*`, `E_UNSERVED_*`, `E_BAD_PAYLOAD`, `E_SUSPICIOUS_TEXT`) need a retry \u2014 `[USER]` warnings/`drift:` notices are human-only.",
24
+ "`edit`: `[TO MODEL]` errors (e.g. `E_STALE_*`, `E_UNSERVED_*`, `E_BAD_PAYLOAD`, `E_SUSPICIOUS_TEXT`) need a retry; a `[MODEL]`-routed warning carries an action you must take (e.g. resending a no-op rejects) \u2014 `[USER]` warnings/`drift:` notices are human-only.",
25
25
  "`edit`: on `E_STALE_ANCHOR` re-read for fresh anchors; on `E_STALE_RANGE`/`E_UNSERVED_RANGE` the echoed rows are the file's current anchors, NOT serves — re-read before retrying.",
26
26
  ],
27
27
  };
@@ -44,7 +44,7 @@ export const UNDO_GUIDANCE = {
44
44
  intro: "Revert the last edit on a file.",
45
45
  lines: [
46
46
  "`undo_last_edit`: reverts only the most recent edit — any write clears history, so call it immediately after a bad edit.",
47
- "`undo_last_edit`: the restored diff\u2019s `+HASH│` and ` HASH│` rows are fresh anchors for follow-up edits \u2014 unless the result says the rows were NOT recorded as served, then re-read.",
47
+ "`undo_last_edit`: the restored diff\u2019s `+HASH│` and ` HASH│` rows carry the file\u2019s original pre-edit anchors for follow-up edits \u2014 unless the result says the rows were NOT recorded as served, then re-read.",
48
48
  ],
49
49
  };
50
50
  /**
@@ -8,11 +8,11 @@
8
8
  * @module dsh-better-edit/read-and-serve
9
9
  */
10
10
  import { abortIf } from "./utils.js";
11
- import { hasRequestedWindows, readView } from "./file-view.js";
11
+ import { readView } from "./file-view.js";
12
12
  import { canon } from "./hashline/hash-assign.js";
13
13
  import { splitLines } from "./utils.js";
14
14
  import { getAutoGuessFooter } from "./fs-bridge.js";
15
- import { AnchorSpaceExhaustedError, HASH_SPACE } from "./hashline/hash-assign.js";
15
+ import { HASH_SPACE, isPromotableAnchorSpaceExhaustion } from "./hashline/hash-assign.js";
16
16
  import { recordServed, clearDriftReported, loadRetiredAnchors, loadServed, loadServedCanons, } from "./session-view.js";
17
17
  import { loadServedStore } from "./hash-store.js";
18
18
  /** Appended when the file had non-UTF-8 bytes; editing rewrites it as UTF-8. */
@@ -44,7 +44,8 @@ export async function readAndServe(io, rawPath, cwd, options) {
44
44
  // Build previous for stable reuse (S): served filtered + canons reconstruction.
45
45
  // #62 alignment gate: the reconstructed arrays carry the SERVED index as the line
46
46
  // position, which equals the real line number only when the mirror is dense — the
47
- // `row.position === index` half of the `isFullRead` predicate (session-view.ts).
47
+ // `row.position === index` density half of the serve verdict, which session-view keeps as an
48
+ // ASSERTION about FileView rather than a decision (ADR-0035).
48
49
  // With holes (a partial mirror), `mapStableHashes` would match compressed indices
49
50
  // against whole-file positions and reshuffle anchors of an UNCHANGED file; pass
50
51
  // `previous = undefined` instead and take the content-addressed snapshot path
@@ -90,53 +91,53 @@ export async function readAndServe(io, rawPath, cwd, options) {
90
91
  });
91
92
  }
92
93
  catch (e) {
93
- if (e instanceof AnchorSpaceExhaustedError ||
94
- (e instanceof Error && e.message.includes("probing failed over"))) {
95
- const retiredCount = retiredHashes.size;
96
- const servedCount = servedForNorm.filter((h) => h !== null).length;
97
- const reservedCount = retiredCount + servedCount;
98
- // Major GC promotion: clear retired for this (session,path), keep served/canons
94
+ // INVARIANT (promotion is a retired-anchor GC, not a line-count escape hatch): a read that
95
+ // cannot be hashed at all must leave hazard state untouched — so the uncurable refusals
96
+ // (the line cap, and any other non-promotable error) rethrow HERE, before the store is
97
+ // reached. Clearing this (session,path)'s retired anchors for a failure the retry cannot
98
+ // cure would degrade stale-anchor checks while the same error still reaches the model.
99
+ if (!isPromotableAnchorSpaceExhaustion(e))
100
+ throw e;
101
+ const retiredCount = retiredHashes.size;
102
+ const servedCount = servedForNorm.filter((h) => h !== null).length;
103
+ const reservedCount = retiredCount + servedCount;
104
+ // Major GC promotion: clear retired for this (session,path), keep served/canons
105
+ try {
106
+ const store = await loadServedStore();
107
+ store.clearRetiredAnchors(sessionKey, absolutePath);
99
108
  try {
100
- const store = await loadServedStore();
101
- store.clearRetiredAnchors(sessionKey, absolutePath);
102
- try {
103
- store.clearCards(sessionKey, absolutePath);
104
- }
105
- catch {
106
- // Best-effort: card state is a cache; the promotion retry below proceeds without it.
107
- }
109
+ store.clearCards(sessionKey, absolutePath);
108
110
  }
109
111
  catch {
110
- // Best-effort: a store fault here must not fail the read — the retry proceeds on the
111
- // in-memory reservation state (ADR-0020 R2, promotion/wipe arm).
112
+ // Best-effort: card state is a cache; the promotion retry below proceeds without it.
112
113
  }
113
- // Soft promotion notice: plain non-header text (no [E_] code, no audience).
114
- promotionWarning = `Anchor space exhausted (retired ${retiredCount} + served ${servedCount} = ${reservedCount} of ${HASH_SPACE}); promotion cleared retired — re-read recommended, stale-anchor checks degraded until next full read.`;
115
- // Retry ignoring retired (served only) — also drop removedHashes from previous
116
- retiredHashes = new Set();
117
- reservedHashes = new Set([...servedForNorm.filter((h) => h !== null)]);
118
- reservations = { reservedHashes, retiredHashes };
119
- if (previous)
120
- previous = { content: previous.content, hashes: previous.hashes };
121
- view = await readView(io, rawPath, cwd, {
122
- encoding: options.encoding,
123
- offset: options.offset,
124
- limit: options.limit,
125
- windows: options.windows,
126
- signal,
127
- reservedHashes: reservations.reservedHashes,
128
- retiredHashes: reservations.retiredHashes,
129
- previous,
130
- });
131
114
  }
132
- else {
133
- throw e;
115
+ catch {
116
+ // Best-effort: a store fault here must not fail the read — the retry proceeds on the
117
+ // in-memory reservation state (ADR-0020 R2, promotion/wipe arm).
134
118
  }
119
+ // Soft promotion notice: plain non-header text (no [E_] code, no audience).
120
+ promotionWarning = `Anchor space exhausted (retired ${retiredCount} + served ${servedCount} = ${reservedCount} of ${HASH_SPACE}); promotion cleared retired — re-read recommended, stale-anchor checks degraded until next full read.`;
121
+ // Retry ignoring retired (served only) — also drop removedHashes from previous
122
+ retiredHashes = new Set();
123
+ reservedHashes = new Set([...servedForNorm.filter((h) => h !== null)]);
124
+ reservations = { reservedHashes, retiredHashes };
125
+ if (previous)
126
+ previous = { content: previous.content, hashes: previous.hashes };
127
+ view = await readView(io, rawPath, cwd, {
128
+ encoding: options.encoding,
129
+ offset: options.offset,
130
+ limit: options.limit,
131
+ windows: options.windows,
132
+ signal,
133
+ reservedHashes: reservations.reservedHashes,
134
+ retiredHashes: reservations.retiredHashes,
135
+ previous,
136
+ });
135
137
  }
136
138
  let servedLanded = true;
137
139
  if (view.served.length > 0) {
138
140
  const canons = splitLines(view.normalized).map((l) => canon(l));
139
- const canonServed = canons.map((canonText) => canonText);
140
141
  // Pad or trim canons to served length? For now use canons for full file
141
142
  const fullCanons = [];
142
143
  for (let i = 0; i < view.hashes.length; i++) {
@@ -146,22 +147,19 @@ export async function readAndServe(io, rawPath, cwd, options) {
146
147
  hashes: view.hashes,
147
148
  canons: fullCanons,
148
149
  content: view.normalized,
150
+ // The verdict travels with the serve: FileView computed it from the request shape, this
151
+ // seam only carries it (ADR-0035).
152
+ fullRead: view.fullRead,
149
153
  });
150
154
  }
151
- // #69: epoch lifecycle belongs to full reads — a partial (paged or
152
- // truncated) read merges window rows only and must not clear the
153
- // drift-reported marks; only a full read resets them. The `undefined`/`[]` →
154
- // no-windows rule is owned by file-view's `hasRequestedWindows`.
155
- const isFullRead = options.offset === undefined &&
156
- options.limit === undefined &&
157
- !hasRequestedWindows(options.windows) &&
158
- !view.truncation?.truncated;
159
- if (isFullRead)
155
+ // #69: epoch lifecycle belongs to full reads — a partial (paged or truncated) read merges window
156
+ // rows only and must not clear the drift-reported marks; only a full read resets them. The
157
+ // verdict is `view.fullRead` (ADR-0035): FileView owns the request-shape rule — including
158
+ // `undefined`/`[]` → no windows via `hasRequestedWindows` — so no second predicate exists here
159
+ // to disagree with it.
160
+ if (view.fullRead)
160
161
  await clearDriftReported(sessionKey, view.absolutePath);
161
- const autoFooter = getAutoGuessFooter(view.absolutePath) ??
162
- getAutoGuessFooter(rawPath) ??
163
- getAutoGuessFooter(view.absolutePath.replace(/\\/g, "/")) ??
164
- "";
162
+ const autoFooter = getAutoGuessFooter(view.absolutePath) ?? "";
165
163
  const autoWarning = autoFooter || undefined;
166
164
  const warning = promotionWarning
167
165
  ? autoWarning
package/lib/reclaim.js ADDED
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Shared tool reclamation utility for DSH scoped layers.
3
+ * Used by installAgentTools and createSelfHealWatcher.
4
+ * @module dsh-better-edit/reclaim
5
+ */
6
+ /**
7
+ * Resolve the agent's scoped tool layer from the DSH tools service.
8
+ */
9
+ export function getAgentScopedToolLayer(toolsSvc, agent) {
10
+ // SAFETY: toolsSvc is the DSH tools service — shape is `layers.scoped: Map<agent, {tools}>` per Cordis internals; narrow at boundary
11
+ return toolsSvc?.layers?.scoped?.get?.(agent)?.tools;
12
+ }
13
+ /**
14
+ * Reclaim an entry by deleting it from the scoped layer's data map.
15
+ */
16
+ export function reclaimToolEntry(layer, name) {
17
+ if (!layer?.data)
18
+ return false;
19
+ try {
20
+ const deleted = layer.data.delete(name);
21
+ return Boolean(deleted && layer.get?.(name) === undefined);
22
+ }
23
+ catch {
24
+ return false;
25
+ }
26
+ }
27
+ /**
28
+ * Register a tool with collision detection, guarded reclaim, and single retry.
29
+ */
30
+ export function registerWithReclaim(options) {
31
+ const { toolsSvc, agent, agentCtx, name, def, logger } = options;
32
+ const layer = getAgentScopedToolLayer(toolsSvc, agent);
33
+ const current = layer?.get?.(name) ?? layer?.data?.get?.(name);
34
+ if (current === def)
35
+ return () => { }; // Already registered with same ref; return no-op disposer
36
+ try {
37
+ return agentCtx.tools.register(def);
38
+ }
39
+ catch (initialError) {
40
+ const errorStr = String(initialError);
41
+ const isCollision = errorStr.includes("already registered") || current != null;
42
+ if (!isCollision) {
43
+ logger?.warn(`dsh-better-edit: tool "${name}" registration failed with non-collision error: ${errorStr} (#123)`);
44
+ return undefined;
45
+ }
46
+ if (!layer) {
47
+ logger?.warn(`dsh-better-edit: cannot reclaim tool "${name}" because scoped layer is unresolvable (#123)`);
48
+ return undefined;
49
+ }
50
+ const reclaimed = reclaimToolEntry(layer, name);
51
+ if (!reclaimed) {
52
+ logger?.warn(`dsh-better-edit: cannot reclaim contested tool "${name}" from scoped layer (#123)`);
53
+ return undefined;
54
+ }
55
+ try {
56
+ const dispose = agentCtx.tools.register(def);
57
+ logger?.warn(`dsh-better-edit: reclaimed contested tool "${name}" from peer registration (#123)`);
58
+ return dispose;
59
+ }
60
+ catch (retryError) {
61
+ logger?.warn(`dsh-better-edit: failed to register tool "${name}" after reclaim: ${String(retryError)} (#123)`);
62
+ return undefined;
63
+ }
64
+ }
65
+ }
package/lib/self-heal.js CHANGED
@@ -1,12 +1,16 @@
1
1
  /**
2
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).
3
+ * Restores the hashline tools the install actually registered when an external
4
+ * preset deletes them (e.g. router-standard stage advance). The heal set is the
5
+ * installed set: a tool the preset gate declined has no definition to restore,
6
+ * so a `tools/change` can never resurrect it (Rianico/dsh-better-edit#110).
5
7
  * See Rianico/dsh-better-edit#43.
6
8
  * @module dsh-better-edit/self-heal
7
9
  */
10
+ import { getAgentScopedToolLayer, reclaimToolEntry } from "./reclaim.js";
8
11
  export function createSelfHealWatcher(options) {
9
12
  const { agentId, rootCtx, agent, agentCtx, toolsSvc, hashReadDef, hashEditDef, hashStrReplaceDef, healMinIntervalMs = 1000, } = options;
13
+ const watchEdit = hashEditDef !== undefined;
10
14
  const watchStrReplace = hashStrReplaceDef !== undefined;
11
15
  let lastHealAt = 0;
12
16
  let healCount = 0;
@@ -17,14 +21,15 @@ export function createSelfHealWatcher(options) {
17
21
  try {
18
22
  if (selfHealDisabled)
19
23
  return;
20
- // SAFETY: toolsSvc is the DSH tools service — shape is `layers.scoped: Map<agent, {tools}>` per cordis internals; narrow at boundary
21
- const layer = toolsSvc?.layers?.scoped?.get?.(agent)?.tools;
24
+ const layer = getAgentScopedToolLayer(toolsSvc, agent);
22
25
  if (!layer)
23
26
  return;
24
27
  const currentRead = layer?.get?.("read") ?? layer?.data?.get?.("read");
25
28
  const currentEdit = layer?.get?.("edit") ?? layer?.data?.get?.("edit");
26
29
  const readOk = currentRead === hashReadDef;
27
- const editOk = currentEdit === hashEditDef;
30
+ // A declined edit has no definition to restore: a layer that happens to
31
+ // hold a built-in `edit` is the preset's own tool, not a takeover.
32
+ const editOk = !watchEdit || currentEdit === hashEditDef;
28
33
  const currentStrReplace = watchStrReplace
29
34
  ? (layer?.get?.("str_replace_editor") ?? layer?.data?.get?.("str_replace_editor"))
30
35
  : hashStrReplaceDef;
@@ -52,17 +57,13 @@ export function createSelfHealWatcher(options) {
52
57
  const restoreCount = healCount;
53
58
  queueMicrotask(() => {
54
59
  try {
55
- // SAFETY: re-read layer inside microtask — same shape as above
56
- const currentLayer = toolsSvc?.layers?.scoped?.get?.(agent)?.tools;
60
+ const currentLayer = getAgentScopedToolLayer(toolsSvc, agent);
57
61
  if (!currentLayer)
58
62
  return;
59
63
  const restoreTool = (name, def, toolLabel) => {
60
- try {
61
- currentLayer?.data?.delete?.(name);
62
- }
63
- catch {
64
- // ignore — best-effort delete of intruding entry
65
- }
64
+ // Best-effort delete of an intruding entry; a failed delete
65
+ // surfaces through the register throw below.
66
+ reclaimToolEntry(currentLayer, name);
66
67
  try {
67
68
  agentCtx.tools.register(def);
68
69
  }