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.
- package/CHANGELOG.md +33 -0
- package/README.md +39 -20
- package/README.zh.md +39 -31
- package/lib/contract.js +53 -22
- package/lib/domain-errors.js +18 -10
- package/lib/edit-mode.js +11 -0
- package/lib/encoding.js +2 -0
- package/lib/file-encoding-state.js +138 -44
- package/lib/file-view.js +26 -205
- package/lib/fs-bridge.js +53 -71
- package/lib/hashline/anchor-pipeline.js +8 -499
- package/lib/hashline/hash-assign.js +55 -4
- package/lib/hashline/index.js +5 -2
- package/lib/hashline/served-evidence.js +531 -0
- package/lib/index.js +177 -33
- package/lib/mutation/engine.js +19 -61
- package/lib/mutation.js +63 -105
- package/lib/noop-guard.js +24 -38
- package/lib/paths.js +9 -5
- package/lib/preset-toolset.js +144 -0
- package/lib/prompts.js +3 -3
- package/lib/read-and-serve.js +51 -53
- package/lib/reclaim.js +65 -0
- package/lib/self-heal.js +14 -13
- package/lib/session-view.js +79 -49
- package/lib/store/index.js +14 -14
- package/lib/store-config.js +4 -5
- package/lib/store-lifecycle.js +1 -1
- package/lib/tool-edit.js +14 -56
- package/lib/tool-read.js +2 -8
- package/lib/tool-str-replace-editor.js +34 -18
- package/lib/tool-undo.js +42 -24
- package/lib/types/contract.d.ts +11 -20
- package/lib/types/domain-errors.d.ts +14 -10
- package/lib/types/edit-mode.d.ts +11 -0
- package/lib/types/encoding.d.ts +1 -0
- package/lib/types/file-encoding-state.d.ts +51 -14
- package/lib/types/file-view.d.ts +18 -56
- package/lib/types/fs-bridge.d.ts +0 -1
- package/lib/types/hashline/anchor-pipeline.d.ts +6 -128
- package/lib/types/hashline/hash-assign.d.ts +40 -0
- package/lib/types/hashline/index.d.ts +6 -4
- package/lib/types/hashline/served-evidence.d.ts +152 -0
- package/lib/types/mutation/engine.d.ts +4 -12
- package/lib/types/mutation.d.ts +10 -58
- package/lib/types/noop-guard.d.ts +2 -33
- package/lib/types/paths.d.ts +0 -1
- package/lib/types/preset-toolset.d.ts +61 -0
- package/lib/types/reclaim.d.ts +36 -0
- package/lib/types/self-heal.d.ts +9 -3
- package/lib/types/session-view.d.ts +38 -8
- package/lib/types/store/index.d.ts +12 -11
- package/lib/types/store-config.d.ts +1 -1
- package/lib/types/store-lifecycle.d.ts +12 -2
- package/lib/types/tool-edit.d.ts +2 -4
- package/lib/types/tool-read.d.ts +0 -5
- package/lib/types/tool-str-replace-editor.d.ts +0 -6
- package/lib/types/tool-undo.d.ts +0 -5
- package/package.json +3 -2
- package/lib/drift.js +0 -5
- package/lib/dsh-context.js +0 -5
- package/lib/edit-engine.js +0 -7
- package/lib/edit-normalize.js +0 -9
- package/lib/edit-pipeline.js +0 -6
- package/lib/file-kind.js +0 -6
- package/lib/file-reader.js +0 -6
- package/lib/guidance/index.js +0 -8
- package/lib/hashline/alphabet.js +0 -2
- package/lib/hashline/apply.js +0 -2
- package/lib/hashline/hasher.js +0 -2
- package/lib/hashline/parse.js +0 -2
- package/lib/hashline/pure.js +0 -2
- package/lib/hashline/resolve.js +0 -3
- package/lib/hashline/served.js +0 -2
- package/lib/preview-controller.js +0 -65
- package/lib/read-render.js +0 -6
- package/lib/schema.js +0 -24
- package/lib/served-store.js +0 -5
- package/lib/tool-batch-edit.js +0 -190
- package/lib/truncate.js +0 -6
- package/lib/types/drift.d.ts +0 -5
- package/lib/types/dsh-context.d.ts +0 -5
- package/lib/types/edit-engine.d.ts +0 -7
- package/lib/types/edit-normalize.d.ts +0 -1
- package/lib/types/edit-pipeline.d.ts +0 -6
- package/lib/types/file-kind.d.ts +0 -6
- package/lib/types/file-reader.d.ts +0 -6
- package/lib/types/guidance/index.d.ts +0 -8
- package/lib/types/hashline/alphabet.d.ts +0 -1
- package/lib/types/hashline/apply.d.ts +0 -1
- package/lib/types/hashline/hasher.d.ts +0 -1
- package/lib/types/hashline/parse.d.ts +0 -1
- package/lib/types/hashline/pure.d.ts +0 -1
- package/lib/types/hashline/resolve.d.ts +0 -1
- package/lib/types/hashline/served.d.ts +0 -1
- package/lib/types/preview-controller.d.ts +0 -33
- package/lib/types/read-render.d.ts +0 -6
- package/lib/types/schema.d.ts +0 -25
- package/lib/types/served-store.d.ts +0 -5
- package/lib/types/tool-batch-edit.d.ts +0 -25
- package/lib/types/truncate.d.ts +0 -6
- package/lib/types/validation.d.ts +0 -6
- package/lib/types/workspace.d.ts +0 -5
- package/lib/validation.js +0 -6
- package/lib/workspace.js +0 -5
package/lib/index.js
CHANGED
|
@@ -3,9 +3,11 @@ import { FsSandboxController } from "./sandbox.js";
|
|
|
3
3
|
import { buildReadTool } from "./tool-read.js";
|
|
4
4
|
import { buildEditTool } from "./tool-edit.js";
|
|
5
5
|
import { buildStrReplaceEditorTool } from "./tool-str-replace-editor.js";
|
|
6
|
-
import {
|
|
6
|
+
import { buildUndoTool } from "./tool-undo.js";
|
|
7
7
|
import { registerWriteHook } from "./write-hook.js";
|
|
8
8
|
import { createSelfHealWatcher } from "./self-heal.js";
|
|
9
|
+
import { resolveToolset, sectionsForToolset, UNCONDITIONAL_TOOLSET, } from "./preset-toolset.js";
|
|
10
|
+
import { registerWithReclaim } from "./reclaim.js";
|
|
9
11
|
import { initHasher } from "./hashline/hash-assign.js";
|
|
10
12
|
import { composeSections, ensurePresetGuidance, GUIDANCE_SECTIONS, } from "./guidance.js";
|
|
11
13
|
import { configDir } from "./store/index.js";
|
|
@@ -82,48 +84,190 @@ async function resolveAgentSections(rootCtx, agent) {
|
|
|
82
84
|
}
|
|
83
85
|
}
|
|
84
86
|
function installAgentTools(rootCtx, agent) {
|
|
85
|
-
agent.ctx.effect(
|
|
87
|
+
agent.ctx.effect(() => {
|
|
88
|
+
let disposed = false;
|
|
89
|
+
const disposers = [];
|
|
90
|
+
const registerDisposer = (dispose) => {
|
|
91
|
+
if (!dispose)
|
|
92
|
+
return;
|
|
93
|
+
if (disposed) {
|
|
94
|
+
try {
|
|
95
|
+
dispose();
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
// A registration that lost the teardown race is still released.
|
|
99
|
+
}
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
disposers.push(dispose);
|
|
103
|
+
};
|
|
86
104
|
// `fs` is host-plane: use the plugin's own context (covered by
|
|
87
105
|
// inject) rather than the agent's scoped one, whose fiber chain does
|
|
88
106
|
// not declare it. The session's live directory still reaches the bridge
|
|
89
107
|
// per call via `execCwd` (the `workingDirectory` service, falling back to
|
|
90
108
|
// `exec.agent.session.header.cwd`).
|
|
109
|
+
const toolsSvc = rootCtx.get("tools");
|
|
91
110
|
const io = ctxFsIO(rootCtx.fs, rootCtx);
|
|
92
|
-
const disposers = [];
|
|
93
111
|
const sandbox = new FsSandboxController(rootCtx);
|
|
94
|
-
//
|
|
112
|
+
// Step 1: `read` is unconditional (Rianico/dsh-better-edit#110) and is
|
|
113
|
+
// claimed synchronously inside `agent/created`, before any eager peer can
|
|
114
|
+
// take the name. The owned definition stays in this closure: self-heal
|
|
115
|
+
// verifies identity against it and must never read `layer.get("read")`,
|
|
116
|
+
// which would ratify an intruder.
|
|
95
117
|
const hashReadDef = buildReadTool(io);
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
const toolsSvc = rootCtx.get("tools");
|
|
106
|
-
disposers.push(createSelfHealWatcher({
|
|
107
|
-
agentId: agent.id,
|
|
108
|
-
rootCtx,
|
|
109
|
-
agent,
|
|
110
|
-
agentCtx: agent.ctx,
|
|
111
|
-
toolsSvc,
|
|
112
|
-
hashReadDef,
|
|
113
|
-
hashEditDef,
|
|
114
|
-
hashStrReplaceDef,
|
|
115
|
-
}));
|
|
116
|
-
// Shadow the preset's built-in tool guidance with the hashline
|
|
117
|
-
// contract. Same section names on the agent's own layer win over the
|
|
118
|
-
// preset's; text and order come from the per-preset resolution, with the
|
|
119
|
-
// harness's canonical tool slot as the default order.
|
|
120
|
-
const sections = await resolveAgentSections(rootCtx, agent);
|
|
121
|
-
for (const section of sections) {
|
|
122
|
-
disposers.push(agent.ctx.systemPrompt.section(section));
|
|
118
|
+
try {
|
|
119
|
+
registerDisposer(registerWithReclaim({
|
|
120
|
+
toolsSvc,
|
|
121
|
+
agent,
|
|
122
|
+
agentCtx: agent.ctx,
|
|
123
|
+
name: "read",
|
|
124
|
+
def: hashReadDef,
|
|
125
|
+
logger: rootCtx.logger,
|
|
126
|
+
}));
|
|
123
127
|
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
rootCtx.logger.warn(`dsh-better-edit: failed to install synchronous read tool: ${error instanceof Error ? error.message : String(error)} (#123)`);
|
|
130
|
+
}
|
|
131
|
+
// The composed preset's own tool policy decides which mutating tools this
|
|
132
|
+
// agent gets. `agentPresets.acquireScope` is async in dsh 0.2.x, so these
|
|
133
|
+
// registrations land after the first microtask; the guarded reclaim in
|
|
134
|
+
// `registerWithReclaim` wins ownership back from peers that claimed a name
|
|
135
|
+
// first.
|
|
136
|
+
(async () => {
|
|
137
|
+
let toolset;
|
|
138
|
+
try {
|
|
139
|
+
toolset = await resolveToolset(rootCtx, agent.ctx);
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
rootCtx.logger.warn(`dsh-better-edit: resolveToolset failed, using default: ${error instanceof Error ? error.message : String(error)} (#123)`);
|
|
143
|
+
toolset = UNCONDITIONAL_TOOLSET;
|
|
144
|
+
}
|
|
145
|
+
if (disposed)
|
|
146
|
+
return;
|
|
147
|
+
// Step 2: `edit`. Build and register are isolated: a factory fault must
|
|
148
|
+
// not cost the later tools or the guidance sections.
|
|
149
|
+
let hashEditDef;
|
|
150
|
+
if (toolset.edit) {
|
|
151
|
+
try {
|
|
152
|
+
hashEditDef = buildEditTool(io, sandbox);
|
|
153
|
+
registerDisposer(registerWithReclaim({
|
|
154
|
+
toolsSvc,
|
|
155
|
+
agent,
|
|
156
|
+
agentCtx: agent.ctx,
|
|
157
|
+
name: "edit",
|
|
158
|
+
def: hashEditDef,
|
|
159
|
+
logger: rootCtx.logger,
|
|
160
|
+
}));
|
|
161
|
+
}
|
|
162
|
+
catch (error) {
|
|
163
|
+
rootCtx.logger.warn(`dsh-better-edit: failed to build/register edit: ${error instanceof Error ? error.message : String(error)} (#123)`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
if (disposed)
|
|
167
|
+
return;
|
|
168
|
+
// Step 3: governed shadow of the preset's built-in str_replace_editor
|
|
169
|
+
// (ADR-0015): identical contract, encoding-governed mutations. Only a
|
|
170
|
+
// preset that composed the built-in earns the shadow.
|
|
171
|
+
let hashStrReplaceDef;
|
|
172
|
+
if (toolset.strReplaceEditor) {
|
|
173
|
+
try {
|
|
174
|
+
hashStrReplaceDef = buildStrReplaceEditorTool(io, sandbox);
|
|
175
|
+
registerDisposer(registerWithReclaim({
|
|
176
|
+
toolsSvc,
|
|
177
|
+
agent,
|
|
178
|
+
agentCtx: agent.ctx,
|
|
179
|
+
name: "str_replace_editor",
|
|
180
|
+
def: hashStrReplaceDef,
|
|
181
|
+
logger: rootCtx.logger,
|
|
182
|
+
}));
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
rootCtx.logger.warn(`dsh-better-edit: failed to build/register str_replace_editor: ${error instanceof Error ? error.message : String(error)} (#123)`);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
if (disposed)
|
|
189
|
+
return;
|
|
190
|
+
// Step 4: `undo_last_edit`, built by the arity-pinned factory and routed
|
|
191
|
+
// through the same guarded reclaim (issue #123).
|
|
192
|
+
if (toolset.undo) {
|
|
193
|
+
try {
|
|
194
|
+
const hashUndoDef = buildUndoTool(io, sandbox);
|
|
195
|
+
registerDisposer(registerWithReclaim({
|
|
196
|
+
toolsSvc,
|
|
197
|
+
agent,
|
|
198
|
+
agentCtx: agent.ctx,
|
|
199
|
+
name: "undo_last_edit",
|
|
200
|
+
def: hashUndoDef,
|
|
201
|
+
logger: rootCtx.logger,
|
|
202
|
+
}));
|
|
203
|
+
}
|
|
204
|
+
catch (error) {
|
|
205
|
+
rootCtx.logger.warn(`dsh-better-edit: failed to register undo tool: ${error instanceof Error ? error.message : String(error)} (#123)`);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
if (disposed)
|
|
209
|
+
return;
|
|
210
|
+
// Step 5: the write hook guards the preset's own built-in `write` and
|
|
211
|
+
// auto-reads after it. It attaches event listeners rather than naming a
|
|
212
|
+
// tool, so it carries no collision surface and needs no reclaim.
|
|
213
|
+
if (toolset.writeHook) {
|
|
214
|
+
try {
|
|
215
|
+
registerDisposer(registerWriteHook(rootCtx, agent.ctx, io));
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
rootCtx.logger.warn(`dsh-better-edit: failed to register write hook: ${error instanceof Error ? error.message : String(error)} (#123)`);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
if (disposed)
|
|
222
|
+
return;
|
|
223
|
+
// Step 6: self-heal receives the exact definitions installed above, so
|
|
224
|
+
// the heal set can never drift from the installed set.
|
|
225
|
+
try {
|
|
226
|
+
registerDisposer(createSelfHealWatcher({
|
|
227
|
+
agentId: agent.id,
|
|
228
|
+
rootCtx,
|
|
229
|
+
agent,
|
|
230
|
+
agentCtx: agent.ctx,
|
|
231
|
+
toolsSvc,
|
|
232
|
+
hashReadDef,
|
|
233
|
+
hashEditDef,
|
|
234
|
+
hashStrReplaceDef,
|
|
235
|
+
}));
|
|
236
|
+
}
|
|
237
|
+
catch (error) {
|
|
238
|
+
rootCtx.logger.warn(`dsh-better-edit: failed to initialize self-heal watcher: ${error instanceof Error ? error.message : String(error)} (#123)`);
|
|
239
|
+
}
|
|
240
|
+
if (disposed)
|
|
241
|
+
return;
|
|
242
|
+
// Step 7: shadow the preset's built-in tool guidance with the hashline
|
|
243
|
+
// contract. Same section names on the agent's own layer win over the
|
|
244
|
+
// preset's; text and order come from the per-preset resolution, with the
|
|
245
|
+
// harness's canonical tool slot as the default order.
|
|
246
|
+
try {
|
|
247
|
+
const sections = sectionsForToolset(await resolveAgentSections(rootCtx, agent), toolset);
|
|
248
|
+
if (disposed)
|
|
249
|
+
return;
|
|
250
|
+
for (const section of sections) {
|
|
251
|
+
registerDisposer(agent.ctx.systemPrompt.section(section));
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
catch (error) {
|
|
255
|
+
rootCtx.logger.warn(`dsh-better-edit: failed to register system prompt guidance: ${error instanceof Error ? error.message : String(error)} (#123)`);
|
|
256
|
+
}
|
|
257
|
+
})().catch((error) => {
|
|
258
|
+
rootCtx.logger.warn(`dsh-better-edit: unhandled async install failure: ${error instanceof Error ? error.message : String(error)} (#123)`);
|
|
259
|
+
});
|
|
124
260
|
return () => {
|
|
125
|
-
|
|
126
|
-
|
|
261
|
+
disposed = true;
|
|
262
|
+
for (const dispose of disposers) {
|
|
263
|
+
try {
|
|
264
|
+
dispose();
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
// Best-effort teardown: one failing disposer must not strand the rest.
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
disposers.length = 0;
|
|
127
271
|
};
|
|
128
272
|
});
|
|
129
273
|
}
|
package/lib/mutation/engine.js
CHANGED
|
@@ -14,16 +14,13 @@
|
|
|
14
14
|
import { loadHashStore } from "../hash-store.js";
|
|
15
15
|
import { loadConfig } from "../store-config.js";
|
|
16
16
|
import { canon } from "../hashline/hash-assign.js";
|
|
17
|
-
import { normFromText } from "../file-
|
|
17
|
+
import { normFromText } from "../file-view.js";
|
|
18
18
|
import { scanDrift, loadServed, loadServedCanons, loadRetiredAnchors } from "../session-view.js";
|
|
19
|
-
import { applyEdit, resEdit
|
|
19
|
+
import { applyEdit, resEdit } from "../hashline/anchor-pipeline.js";
|
|
20
20
|
import { lineHashes } from "../hashline/hash.js";
|
|
21
|
-
import {
|
|
21
|
+
import { HASH_SPACE, isPromotableAnchorSpaceExhaustion } from "../hashline/hash-assign.js";
|
|
22
22
|
import { buildNeverServedEditHint } from "../hashline/served-guard.js";
|
|
23
|
-
|
|
24
|
-
return (e instanceof AnchorSpaceExhaustedError ||
|
|
25
|
-
(e instanceof Error && e.message.includes("probing failed over")));
|
|
26
|
-
}
|
|
23
|
+
import { encodingHintAtVersion } from "../file-encoding-state.js";
|
|
27
24
|
function promotionWarning(retiredSize, servedLen) {
|
|
28
25
|
// Soft promotion notice: plain non-header text (no [E_] code, no audience).
|
|
29
26
|
// The hard capacity refusal routes through E_LARGE_FILE (hash-space).
|
|
@@ -62,63 +59,20 @@ async function retryLineHashesWithPromotion(sessionKey, absolutePath, retired, s
|
|
|
62
59
|
return await fn(recomputed, new Set());
|
|
63
60
|
}
|
|
64
61
|
catch (e2) {
|
|
65
|
-
if (
|
|
62
|
+
if (isPromotableAnchorSpaceExhaustion(e2))
|
|
66
63
|
throw new DomainError("E_LARGE_FILE", { limitKind: "hash-space", limit: HASH_SPACE });
|
|
67
64
|
throw e2;
|
|
68
65
|
}
|
|
69
66
|
}
|
|
70
67
|
import { MAX_HASH_LINES } from "../hashline/hash-assign.js";
|
|
71
|
-
import { AnchorMismatchError
|
|
72
|
-
import {
|
|
73
|
-
import {
|
|
68
|
+
import { AnchorMismatchError } from "../hashline/anchor-pipeline.js";
|
|
69
|
+
import { ServedRejectionError, buildRangeEcho, fmtServedRows, } from "../hashline/served-evidence.js";
|
|
70
|
+
import { DomainError, formatWarning } from "../domain-errors.js";
|
|
74
71
|
import { clearNoopLoop, noopPayloadKey, trackNoopPayload } from "../noop-guard.js";
|
|
75
72
|
import { NOOP_LOOP_THRESHOLD } from "../constants.js";
|
|
76
73
|
import { abortIf, splitLines } from "../utils.js";
|
|
77
74
|
// ---------------------------------------------------------------------------
|
|
78
75
|
// request / counting helpers shared by both tool paths
|
|
79
|
-
/**
|
|
80
|
-
* Resolve a request's missing `path` from its anchors: the only file whose
|
|
81
|
-
* stored hashes contain both anchors. Returns the path plus an autocorrect
|
|
82
|
-
* warning, or undefined when no resolution is possible.
|
|
83
|
-
*/
|
|
84
|
-
export async function resolveMissingPath(request) {
|
|
85
|
-
if (typeof request.path === "string")
|
|
86
|
-
return undefined;
|
|
87
|
-
const from = request.anchor_from;
|
|
88
|
-
const to = request.anchor_to;
|
|
89
|
-
if (typeof from !== "string" || typeof to !== "string")
|
|
90
|
-
return undefined;
|
|
91
|
-
const hashes = [];
|
|
92
|
-
for (const ref of [from, to]) {
|
|
93
|
-
try {
|
|
94
|
-
hashes.push(parseHashRef(ref).hash);
|
|
95
|
-
}
|
|
96
|
-
catch {
|
|
97
|
-
return undefined;
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
let matches;
|
|
101
|
-
try {
|
|
102
|
-
matches = await findSnapshotPathsByHashes(hashes);
|
|
103
|
-
}
|
|
104
|
-
catch {
|
|
105
|
-
return undefined;
|
|
106
|
-
}
|
|
107
|
-
if (matches.length === 1) {
|
|
108
|
-
return {
|
|
109
|
-
path: matches[0],
|
|
110
|
-
warning: formatError("E_BAD_PAYLOAD", {
|
|
111
|
-
message: `Autocorrected: missing "path" resolved to ${matches[0]} — the only file whose stored hashes contain both anchors.`,
|
|
112
|
-
}),
|
|
113
|
-
};
|
|
114
|
-
}
|
|
115
|
-
if (matches.length > 1) {
|
|
116
|
-
throw new DomainError("E_BAD_PAYLOAD", {
|
|
117
|
-
message: `Edit request requires a non-empty "path" string; the anchors match multiple known files: ${matches.join(", ")}. Include the intended path.`,
|
|
118
|
-
});
|
|
119
|
-
}
|
|
120
|
-
return undefined;
|
|
121
|
-
}
|
|
122
76
|
/** The hashes a range edit removes, for stable re-hash bookkeeping. */
|
|
123
77
|
export function collectRemovedHashes(edit, originalHashes) {
|
|
124
78
|
const removedHashes = new Set();
|
|
@@ -205,7 +159,7 @@ export async function applyOne(input, onReject) {
|
|
|
205
159
|
}, input.store, input.persist, input.reservedHashes, retiredForHash);
|
|
206
160
|
}
|
|
207
161
|
catch (e) {
|
|
208
|
-
if (!
|
|
162
|
+
if (!isPromotableAnchorSpaceExhaustion(e))
|
|
209
163
|
throw e;
|
|
210
164
|
resultHashes = await retryLineHashesWithPromotion(input.sessionKey, input.absolutePath, retiredForHash, input.served, input.warnings ?? [], (recomputed, emptyRetired) => lineHashes(result, input.absolutePath, {
|
|
211
165
|
content: input.content,
|
|
@@ -497,7 +451,13 @@ export async function runFileEdits(io, items, opts) {
|
|
|
497
451
|
const absolutePath = first.absolutePath;
|
|
498
452
|
const perSessionRetired = await loadRetiredAnchors(opts.sessionKey, absolutePath);
|
|
499
453
|
const reservedHashes = new Set(perSessionRetired);
|
|
500
|
-
|
|
454
|
+
// Issue #112: the mutating re-read consumes the encoding recorded by `read`,
|
|
455
|
+
// so a file admitted by `read({ encoding })` decodes to the same text (and the
|
|
456
|
+
// same anchors). The version guard drops a drifted memo first — re-detect, never
|
|
457
|
+
// launder the old encoding onto changed bytes.
|
|
458
|
+
const currentVersion = await io.statVersion(absolutePath, opts.signal);
|
|
459
|
+
const encodingHint = encodingHintAtVersion(absolutePath, currentVersion);
|
|
460
|
+
const rawText = await io.readText(absolutePath, opts.signal, encodingHint);
|
|
501
461
|
const { normalized: originalNormalized, bom, originalEnding, fileHashes: originalHashes, hadUtf8DecodeErrors, } = await normFromText({
|
|
502
462
|
absolutePath,
|
|
503
463
|
rawText,
|
|
@@ -650,7 +610,7 @@ export async function runFileEdits(io, items, opts) {
|
|
|
650
610
|
if (applied.noop) {
|
|
651
611
|
noopCount += 1;
|
|
652
612
|
const payload = noopPayloadKey(absolutePath, item.anchor_from, item.anchor_to, item.replace_with);
|
|
653
|
-
const count = trackNoopPayload(absolutePath, payload);
|
|
613
|
+
const count = trackNoopPayload(opts.sessionKey, absolutePath, payload);
|
|
654
614
|
const notice = await enforceNoopLoop({
|
|
655
615
|
anchorFrom: item.anchor_from,
|
|
656
616
|
anchorTo: item.anchor_to,
|
|
@@ -684,7 +644,7 @@ export async function runFileEdits(io, items, opts) {
|
|
|
684
644
|
currentIds = spliceWorkingBufferIds(currentIds, range.startLine, range.endLine, splitLines(applied.result).length);
|
|
685
645
|
}
|
|
686
646
|
currentHashes = applied.hashes;
|
|
687
|
-
clearNoopLoop(absolutePath);
|
|
647
|
+
clearNoopLoop(opts.sessionKey, absolutePath);
|
|
688
648
|
pushAppliedWarnings(applied.anchorWarnings, applied.neverServedCount);
|
|
689
649
|
}
|
|
690
650
|
if (neverServedTotal > 0) {
|
|
@@ -701,7 +661,7 @@ export async function runFileEdits(io, items, opts) {
|
|
|
701
661
|
}, undefined, true, reservedHashes, perSessionRetired);
|
|
702
662
|
}
|
|
703
663
|
catch (e) {
|
|
704
|
-
if (!
|
|
664
|
+
if (!isPromotableAnchorSpaceExhaustion(e))
|
|
705
665
|
throw e;
|
|
706
666
|
resultHashes = await retryLineHashesWithPromotion(opts.sessionKey, absolutePath, perSessionRetired, served, warnings, (recomputed, emptyRetired) => lineHashes(result, absolutePath, {
|
|
707
667
|
content: lastApplied.content,
|
|
@@ -716,8 +676,6 @@ export async function runFileEdits(io, items, opts) {
|
|
|
716
676
|
if (hadUtf8DecodeErrors) {
|
|
717
677
|
warnings.push("Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.");
|
|
718
678
|
}
|
|
719
|
-
if (first.fileWarning)
|
|
720
|
-
warnings.unshift(first.fileWarning);
|
|
721
679
|
let driftNotice;
|
|
722
680
|
if (appliedCount > 0 && unionStartLine !== Infinity) {
|
|
723
681
|
const resultLines = splitLines(result);
|
package/lib/mutation.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Mutation — deep module owning the full file mutation lifecycle.
|
|
3
3
|
*
|
|
4
|
-
* Previously fragmented: tool-edit → edit-pipeline →
|
|
5
|
-
* edit-response/diff/drift, and tool-batch-edit →
|
|
4
|
+
* Previously fragmented: tool-edit → edit-pipeline → engine.applyOne →
|
|
5
|
+
* edit-response/diff/drift, and tool-batch-edit → engine.runFileEdits
|
|
6
6
|
* (loop + unionRange + counters) → persistUndoAndWrite with a boolean flag.
|
|
7
7
|
* Warnings, hadUtf8DecodeErrors, firstChangedLine, driftNotice were threaded
|
|
8
8
|
* by mutation across 5 hops; bugs hid in wiring, not pure helpers.
|
|
@@ -13,59 +13,49 @@
|
|
|
13
13
|
*
|
|
14
14
|
* Public surface:
|
|
15
15
|
* execute(io, items, {sessionKey, exec, sandbox, signal}) → string — deep seam: ONE interface
|
|
16
|
-
*
|
|
17
|
-
* commit(io, files, {exec, sandboxPolicy, signal}) → void — transaction
|
|
16
|
+
* persistUndoAndWrite(opts) → void — transaction (exported for tests)
|
|
18
17
|
*
|
|
19
18
|
* Depth: small interface (execute) with large implementation — locality and leverage.
|
|
20
19
|
*
|
|
21
|
-
* Internals (private): verifyServedRange, resToSpan, assemble,
|
|
22
|
-
*
|
|
20
|
+
* Internals (private): verifyServedRange, resToSpan, assemble, boundaryDups,
|
|
21
|
+
* noopGuard. Tested via FileEditResult, not via split e2e.
|
|
23
22
|
*
|
|
24
23
|
* @module dsh-better-edit/mutation
|
|
25
24
|
*/
|
|
26
25
|
import { formatError } from "./domain-errors.js";
|
|
27
26
|
import { canon } from "./hashline/hash-assign.js";
|
|
28
|
-
import {
|
|
29
|
-
import { toCwd } from "./paths.js";
|
|
30
|
-
import { recordServedTruncated, retireAnchors, scanDrift } from "./session-view.js";
|
|
27
|
+
import { recordServedTruncated, retireAnchors } from "./session-view.js";
|
|
31
28
|
import { abortIf, splitLines } from "./utils.js";
|
|
32
|
-
import { runFileEdits
|
|
29
|
+
import { runFileEdits } from "./mutation/engine.js";
|
|
33
30
|
import { saveUndo } from "./undo-edit.js";
|
|
34
31
|
import { restoreEndings } from "./edit-diff.js";
|
|
35
|
-
import {
|
|
36
|
-
import {
|
|
37
|
-
import {
|
|
38
|
-
|
|
39
|
-
/** Resolve the display path a caller names against the session cwd. */
|
|
40
|
-
export function resolveDisplayPath(path, cwd) {
|
|
41
|
-
return toCwd(path, cwd);
|
|
42
|
-
}
|
|
43
|
-
/** Snapshot bookkeeping for noop/success results (best-effort). */
|
|
44
|
-
export async function snapshotIdFor(io, absolutePath, signal) {
|
|
45
|
-
try {
|
|
46
|
-
return await io.statVersion(absolutePath, signal);
|
|
47
|
-
}
|
|
48
|
-
catch {
|
|
49
|
-
try {
|
|
50
|
-
return (await fileSnap(absolutePath)).snapshotId;
|
|
51
|
-
}
|
|
52
|
-
catch {
|
|
53
|
-
return undefined;
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
// Engine helpers are private to Mutation — not re-exported for new code.
|
|
58
|
-
// Deprecated re-exports kept for existing tests (commitlint: ignore):
|
|
59
|
-
export { runFileEdits, resolveMissingPath };
|
|
60
|
-
export { persistUndoAndWrite };
|
|
61
|
-
export { buildMetrics, buildNoop, buildChanged, buildBatchResult };
|
|
62
|
-
export { genDiff, restoreEndings, toLF, stripBOM };
|
|
63
|
-
export { computeDrift, scanDrift };
|
|
64
|
-
export { trackNoopPayload, clearNoopLoop, noopPayloadKey };
|
|
65
|
-
async function persistUndoAndWrite(opts) {
|
|
32
|
+
import { buildBatchResult } from "./edit-response.js";
|
|
33
|
+
import { getEncodingState, prepareForSave } from "./file-encoding-state.js";
|
|
34
|
+
import { loadConfig } from "./store-config.js";
|
|
35
|
+
export async function persistUndoAndWrite(opts) {
|
|
66
36
|
const { io, files } = opts;
|
|
37
|
+
// Issue #112: decide the save text for EVERY file BEFORE any write. The seam throws
|
|
38
|
+
// E_ENCODING_UNWRITABLE when the recorded encoding cannot be reproduced through the
|
|
39
|
+
// text-only write, so a batch never leaves file 1 transcoded and file 2 refused —
|
|
40
|
+
// nothing (not even the undo rows) is written when the round-trip is impossible.
|
|
41
|
+
const normalizeToUtf8 = loadConfig().normalizeToUtf8;
|
|
42
|
+
const prepared = files.map((file) => {
|
|
43
|
+
const recorded = getEncodingState(file.absolutePath);
|
|
44
|
+
// No memo (e.g. a first write): reconstruct the utf8/utf8bom state the edit read.
|
|
45
|
+
const state = recorded ?? {
|
|
46
|
+
encoding: file.bom ? "utf8bom" : "utf8",
|
|
47
|
+
hasBOM: file.bom !== "",
|
|
48
|
+
lineEnding: file.originalEnding,
|
|
49
|
+
version: undefined,
|
|
50
|
+
};
|
|
51
|
+
const prep = prepareForSave(file.result, state, {
|
|
52
|
+
normalizeToUtf8,
|
|
53
|
+
displayPath: file.displayPath,
|
|
54
|
+
});
|
|
55
|
+
return { file, textToWrite: prep.textToWrite };
|
|
56
|
+
});
|
|
67
57
|
const undos = [];
|
|
68
|
-
for (const file of
|
|
58
|
+
for (const { file, textToWrite } of prepared) {
|
|
69
59
|
const undo = await saveUndo(file.absolutePath, {
|
|
70
60
|
content: file.originalNormalized,
|
|
71
61
|
bom: file.bom,
|
|
@@ -84,13 +74,13 @@ async function persistUndoAndWrite(opts) {
|
|
|
84
74
|
}
|
|
85
75
|
throw new Error(opts.undoUnavailableMessage(file.displayPath));
|
|
86
76
|
}
|
|
87
|
-
undos.push({ file, restore: undo.restore });
|
|
77
|
+
undos.push({ file, textToWrite, restore: undo.restore });
|
|
88
78
|
}
|
|
89
79
|
const written = [];
|
|
90
80
|
try {
|
|
91
81
|
for (const u of undos) {
|
|
92
82
|
abortIf(opts.signal);
|
|
93
|
-
await io.writeText(u.file.absolutePath, u.
|
|
83
|
+
await io.writeText(u.file.absolutePath, u.textToWrite, opts.signal, opts.exec, opts.sandboxPolicy);
|
|
94
84
|
written.push(u);
|
|
95
85
|
}
|
|
96
86
|
}
|
|
@@ -109,42 +99,38 @@ async function persistUndoAndWrite(opts) {
|
|
|
109
99
|
console.error("Failed to restore undo entry after write failure:", e);
|
|
110
100
|
}
|
|
111
101
|
}
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
102
|
+
// ADR-0034: the transaction is the one authority for these rows. A row `saveUndo` persisted for
|
|
103
|
+
// a file this write never reached describes content that is not on disk; leaving it there makes
|
|
104
|
+
// the next `undo_last_edit` compare the real file against a phantom and report `E_UNDO_STALE
|
|
105
|
+
// "modified"` — blaming an external write for the tool's own failed write.
|
|
106
|
+
for (const u of undos) {
|
|
107
|
+
if (written.includes(u))
|
|
108
|
+
continue;
|
|
109
|
+
try {
|
|
110
|
+
await u.restore();
|
|
111
|
+
}
|
|
112
|
+
catch (e) {
|
|
113
|
+
console.error("Failed to restore undo entry after write failure:", e);
|
|
122
114
|
}
|
|
123
115
|
}
|
|
124
116
|
throw opts.sandbox.mapError(error, opts.sandboxPolicy);
|
|
125
117
|
}
|
|
126
118
|
}
|
|
127
|
-
async function commitSingle(opts) {
|
|
128
|
-
return persistUndoAndWrite({ ...opts, restoreUnwrittenUndos: true });
|
|
129
|
-
}
|
|
130
|
-
async function commitBatch(opts) {
|
|
131
|
-
return persistUndoAndWrite({ ...opts, restoreUnwrittenUndos: false });
|
|
132
|
-
}
|
|
133
119
|
// --- Deep seam: unified mutation API (one interface, thin adapters) ---
|
|
134
120
|
/**
|
|
135
121
|
* Deep seam: execute the full mutation lifecycle.
|
|
136
122
|
*
|
|
137
|
-
* Owns:
|
|
123
|
+
* Owns: runFileEdits → branch (single/multi × noop/applied) → commit →
|
|
138
124
|
* buildBatchResult → recordServedTruncated → return text.
|
|
139
125
|
*
|
|
140
|
-
* The tool layer (adapter) only validates and
|
|
126
|
+
* The tool layer (adapter) only validates and delegates; all
|
|
141
127
|
* lifecycle branching concentrates here (locality). One interface serves N
|
|
142
128
|
* call sites (leverage). Deleting this module would scatter the lifecycle
|
|
143
129
|
* across every tool — it concentrates (deep).
|
|
144
130
|
*/
|
|
145
131
|
export async function execute(opts) {
|
|
146
132
|
const { io, items, sessionKey, signal, exec, sandbox, sandboxPolicy } = opts;
|
|
147
|
-
const fileResult = await
|
|
133
|
+
const fileResult = await runFileEdits(io, items, { signal, sessionKey });
|
|
148
134
|
const toSection = () => ({
|
|
149
135
|
path: fileResult.displayPath,
|
|
150
136
|
originalNormalized: fileResult.originalNormalized,
|
|
@@ -202,25 +188,25 @@ export async function execute(opts) {
|
|
|
202
188
|
}
|
|
203
189
|
};
|
|
204
190
|
const isSingleCall = items.length === 1 && fileResult.appliedCount + fileResult.noopCount === 1;
|
|
191
|
+
// Both branches commit exactly this one file, so both name it the same way.
|
|
192
|
+
const commitFile = {
|
|
193
|
+
absolutePath: fileResult.absolutePath,
|
|
194
|
+
displayPath: fileResult.displayPath,
|
|
195
|
+
originalNormalized: fileResult.originalNormalized,
|
|
196
|
+
bom: fileResult.bom,
|
|
197
|
+
originalEnding: fileResult.originalEnding,
|
|
198
|
+
originalHashes: fileResult.originalHashes,
|
|
199
|
+
result: fileResult.result,
|
|
200
|
+
};
|
|
205
201
|
if (isSingleCall) {
|
|
206
202
|
if (fileResult.appliedCount === 0) {
|
|
207
203
|
const built = buildBatchResult([toSection()]);
|
|
208
204
|
const serveLanded = await recordIfNeeded(built);
|
|
209
205
|
return withServeNotice(built.content[0].text, serveLanded);
|
|
210
206
|
}
|
|
211
|
-
await
|
|
207
|
+
await persistUndoAndWrite({
|
|
212
208
|
io,
|
|
213
|
-
files: [
|
|
214
|
-
{
|
|
215
|
-
absolutePath: fileResult.absolutePath,
|
|
216
|
-
displayPath: fileResult.displayPath,
|
|
217
|
-
originalNormalized: fileResult.originalNormalized,
|
|
218
|
-
bom: fileResult.bom,
|
|
219
|
-
originalEnding: fileResult.originalEnding,
|
|
220
|
-
originalHashes: fileResult.originalHashes,
|
|
221
|
-
result: fileResult.result,
|
|
222
|
-
},
|
|
223
|
-
],
|
|
209
|
+
files: [commitFile],
|
|
224
210
|
exec,
|
|
225
211
|
sandbox,
|
|
226
212
|
sandboxPolicy,
|
|
@@ -236,19 +222,9 @@ export async function execute(opts) {
|
|
|
236
222
|
// all noops — no commit
|
|
237
223
|
}
|
|
238
224
|
else if (fileResult.appliedCount > 0) {
|
|
239
|
-
await
|
|
225
|
+
await persistUndoAndWrite({
|
|
240
226
|
io,
|
|
241
|
-
files: [
|
|
242
|
-
{
|
|
243
|
-
absolutePath: fileResult.absolutePath,
|
|
244
|
-
displayPath: fileResult.displayPath,
|
|
245
|
-
originalNormalized: fileResult.originalNormalized,
|
|
246
|
-
bom: fileResult.bom,
|
|
247
|
-
originalEnding: fileResult.originalEnding,
|
|
248
|
-
originalHashes: fileResult.originalHashes,
|
|
249
|
-
result: fileResult.result,
|
|
250
|
-
},
|
|
251
|
-
],
|
|
227
|
+
files: [commitFile],
|
|
252
228
|
exec,
|
|
253
229
|
sandbox,
|
|
254
230
|
sandboxPolicy,
|
|
@@ -261,21 +237,3 @@ export async function execute(opts) {
|
|
|
261
237
|
const serveLanded = await recordIfNeeded(built);
|
|
262
238
|
return withServeNotice(built.content[0].text, serveLanded);
|
|
263
239
|
}
|
|
264
|
-
/** Apply a per-file sequence (batch's group) — owns the loop + unionRange + counters. */
|
|
265
|
-
export async function applySequence(io, items, ctx) {
|
|
266
|
-
return runFileEdits(io, items, ctx);
|
|
267
|
-
}
|
|
268
|
-
/** Commit the transaction — owns persist-undo → write → restore. */
|
|
269
|
-
export async function commit(opts) {
|
|
270
|
-
return persistUndoAndWrite({
|
|
271
|
-
io: opts.io,
|
|
272
|
-
files: opts.files,
|
|
273
|
-
exec: opts.exec,
|
|
274
|
-
sandbox: opts.sandbox,
|
|
275
|
-
sandboxPolicy: opts.sandboxPolicy,
|
|
276
|
-
signal: opts.signal,
|
|
277
|
-
undoUnavailableMessage: opts.undoUnavailableMessage,
|
|
278
|
-
restoreUnwrittenUndos: opts.restoreUnwrittenUndos ?? false,
|
|
279
|
-
});
|
|
280
|
-
}
|
|
281
|
-
export { commitSingle, commitBatch };
|