dsh-better-edit 1.2.4 → 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 +19 -0
- package/lib/domain-errors.js +11 -9
- package/lib/edit-mode.js +11 -0
- package/lib/encoding.js +2 -0
- package/lib/file-encoding-state.js +42 -25
- package/lib/file-view.js +26 -205
- package/lib/fs-bridge.js +14 -49
- 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 +176 -47
- package/lib/mutation/engine.js +10 -13
- package/lib/mutation.js +36 -100
- package/lib/noop-guard.js +24 -39
- package/lib/paths.js +9 -5
- package/lib/read-and-serve.js +51 -53
- package/lib/reclaim.js +65 -0
- package/lib/self-heal.js +6 -10
- package/lib/session-view.js +61 -21
- 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 +0 -3
- package/lib/tool-read.js +2 -8
- package/lib/tool-str-replace-editor.js +3 -10
- package/lib/tool-undo.js +5 -13
- package/lib/types/contract.d.ts +2 -1
- package/lib/types/domain-errors.d.ts +8 -9
- 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 +10 -10
- package/lib/types/file-view.d.ts +18 -56
- 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 -2
- package/lib/types/mutation.d.ts +9 -57
- package/lib/types/noop-guard.d.ts +2 -33
- package/lib/types/paths.d.ts +0 -1
- package/lib/types/reclaim.d.ts +36 -0
- package/lib/types/session-view.d.ts +28 -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 +0 -2
- 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,10 +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 } from "./preset-toolset.js";
|
|
9
|
+
import { resolveToolset, sectionsForToolset, UNCONDITIONAL_TOOLSET, } from "./preset-toolset.js";
|
|
10
|
+
import { registerWithReclaim } from "./reclaim.js";
|
|
10
11
|
import { initHasher } from "./hashline/hash-assign.js";
|
|
11
12
|
import { composeSections, ensurePresetGuidance, GUIDANCE_SECTIONS, } from "./guidance.js";
|
|
12
13
|
import { configDir } from "./store/index.js";
|
|
@@ -83,62 +84,190 @@ async function resolveAgentSections(rootCtx, agent) {
|
|
|
83
84
|
}
|
|
84
85
|
}
|
|
85
86
|
function installAgentTools(rootCtx, agent) {
|
|
86
|
-
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
|
+
};
|
|
87
104
|
// `fs` is host-plane: use the plugin's own context (covered by
|
|
88
105
|
// inject) rather than the agent's scoped one, whose fiber chain does
|
|
89
106
|
// not declare it. The session's live directory still reaches the bridge
|
|
90
107
|
// per call via `execCwd` (the `workingDirectory` service, falling back to
|
|
91
108
|
// `exec.agent.session.header.cwd`).
|
|
92
|
-
|
|
93
|
-
// this agent gets; `read` is unconditional (Rianico/dsh-better-edit#110).
|
|
94
|
-
const toolset = await resolveToolset(rootCtx, agent.ctx);
|
|
109
|
+
const toolsSvc = rootCtx.get("tools");
|
|
95
110
|
const io = ctxFsIO(rootCtx.fs, rootCtx);
|
|
96
|
-
const disposers = [];
|
|
97
111
|
const sandbox = new FsSandboxController(rootCtx);
|
|
98
|
-
//
|
|
99
|
-
//
|
|
100
|
-
//
|
|
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.
|
|
101
117
|
const hashReadDef = buildReadTool(io);
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
: undefined;
|
|
112
|
-
if (hashStrReplaceDef !== undefined) {
|
|
113
|
-
disposers.push(agent.ctx.tools.register(hashStrReplaceDef));
|
|
118
|
+
try {
|
|
119
|
+
registerDisposer(registerWithReclaim({
|
|
120
|
+
toolsSvc,
|
|
121
|
+
agent,
|
|
122
|
+
agentCtx: agent.ctx,
|
|
123
|
+
name: "read",
|
|
124
|
+
def: hashReadDef,
|
|
125
|
+
logger: rootCtx.logger,
|
|
126
|
+
}));
|
|
114
127
|
}
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
// The hook guards the preset's own built-in `write` and auto-reads after it.
|
|
118
|
-
if (toolset.writeHook)
|
|
119
|
-
disposers.push(registerWriteHook(rootCtx, agent.ctx, io));
|
|
120
|
-
const toolsSvc = rootCtx.get("tools");
|
|
121
|
-
disposers.push(createSelfHealWatcher({
|
|
122
|
-
agentId: agent.id,
|
|
123
|
-
rootCtx,
|
|
124
|
-
agent,
|
|
125
|
-
agentCtx: agent.ctx,
|
|
126
|
-
toolsSvc,
|
|
127
|
-
hashReadDef,
|
|
128
|
-
hashEditDef,
|
|
129
|
-
hashStrReplaceDef,
|
|
130
|
-
}));
|
|
131
|
-
// Shadow the preset's built-in tool guidance with the hashline
|
|
132
|
-
// contract. Same section names on the agent's own layer win over the
|
|
133
|
-
// preset's; text and order come from the per-preset resolution, with the
|
|
134
|
-
// harness's canonical tool slot as the default order.
|
|
135
|
-
const sections = sectionsForToolset(await resolveAgentSections(rootCtx, agent), toolset);
|
|
136
|
-
for (const section of sections) {
|
|
137
|
-
disposers.push(agent.ctx.systemPrompt.section(section));
|
|
128
|
+
catch (error) {
|
|
129
|
+
rootCtx.logger.warn(`dsh-better-edit: failed to install synchronous read tool: ${error instanceof Error ? error.message : String(error)} (#123)`);
|
|
138
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
|
+
});
|
|
139
260
|
return () => {
|
|
140
|
-
|
|
141
|
-
|
|
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;
|
|
142
271
|
};
|
|
143
272
|
});
|
|
144
273
|
}
|
package/lib/mutation/engine.js
CHANGED
|
@@ -14,17 +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
23
|
import { encodingHintAtVersion } from "../file-encoding-state.js";
|
|
24
|
-
function isAnchorSpaceExhausted(e) {
|
|
25
|
-
return (e instanceof AnchorSpaceExhaustedError ||
|
|
26
|
-
(e instanceof Error && e.message.includes("probing failed over")));
|
|
27
|
-
}
|
|
28
24
|
function promotionWarning(retiredSize, servedLen) {
|
|
29
25
|
// Soft promotion notice: plain non-header text (no [E_] code, no audience).
|
|
30
26
|
// The hard capacity refusal routes through E_LARGE_FILE (hash-space).
|
|
@@ -63,13 +59,14 @@ async function retryLineHashesWithPromotion(sessionKey, absolutePath, retired, s
|
|
|
63
59
|
return await fn(recomputed, new Set());
|
|
64
60
|
}
|
|
65
61
|
catch (e2) {
|
|
66
|
-
if (
|
|
62
|
+
if (isPromotableAnchorSpaceExhaustion(e2))
|
|
67
63
|
throw new DomainError("E_LARGE_FILE", { limitKind: "hash-space", limit: HASH_SPACE });
|
|
68
64
|
throw e2;
|
|
69
65
|
}
|
|
70
66
|
}
|
|
71
67
|
import { MAX_HASH_LINES } from "../hashline/hash-assign.js";
|
|
72
|
-
import { AnchorMismatchError
|
|
68
|
+
import { AnchorMismatchError } from "../hashline/anchor-pipeline.js";
|
|
69
|
+
import { ServedRejectionError, buildRangeEcho, fmtServedRows, } from "../hashline/served-evidence.js";
|
|
73
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";
|
|
@@ -162,7 +159,7 @@ export async function applyOne(input, onReject) {
|
|
|
162
159
|
}, input.store, input.persist, input.reservedHashes, retiredForHash);
|
|
163
160
|
}
|
|
164
161
|
catch (e) {
|
|
165
|
-
if (!
|
|
162
|
+
if (!isPromotableAnchorSpaceExhaustion(e))
|
|
166
163
|
throw e;
|
|
167
164
|
resultHashes = await retryLineHashesWithPromotion(input.sessionKey, input.absolutePath, retiredForHash, input.served, input.warnings ?? [], (recomputed, emptyRetired) => lineHashes(result, input.absolutePath, {
|
|
168
165
|
content: input.content,
|
|
@@ -613,7 +610,7 @@ export async function runFileEdits(io, items, opts) {
|
|
|
613
610
|
if (applied.noop) {
|
|
614
611
|
noopCount += 1;
|
|
615
612
|
const payload = noopPayloadKey(absolutePath, item.anchor_from, item.anchor_to, item.replace_with);
|
|
616
|
-
const count = trackNoopPayload(absolutePath, payload);
|
|
613
|
+
const count = trackNoopPayload(opts.sessionKey, absolutePath, payload);
|
|
617
614
|
const notice = await enforceNoopLoop({
|
|
618
615
|
anchorFrom: item.anchor_from,
|
|
619
616
|
anchorTo: item.anchor_to,
|
|
@@ -647,7 +644,7 @@ export async function runFileEdits(io, items, opts) {
|
|
|
647
644
|
currentIds = spliceWorkingBufferIds(currentIds, range.startLine, range.endLine, splitLines(applied.result).length);
|
|
648
645
|
}
|
|
649
646
|
currentHashes = applied.hashes;
|
|
650
|
-
clearNoopLoop(absolutePath);
|
|
647
|
+
clearNoopLoop(opts.sessionKey, absolutePath);
|
|
651
648
|
pushAppliedWarnings(applied.anchorWarnings, applied.neverServedCount);
|
|
652
649
|
}
|
|
653
650
|
if (neverServedTotal > 0) {
|
|
@@ -664,7 +661,7 @@ export async function runFileEdits(io, items, opts) {
|
|
|
664
661
|
}, undefined, true, reservedHashes, perSessionRetired);
|
|
665
662
|
}
|
|
666
663
|
catch (e) {
|
|
667
|
-
if (!
|
|
664
|
+
if (!isPromotableAnchorSpaceExhaustion(e))
|
|
668
665
|
throw e;
|
|
669
666
|
resultHashes = await retryLineHashesWithPromotion(opts.sessionKey, absolutePath, perSessionRetired, served, warnings, (recomputed, emptyRetired) => lineHashes(result, absolutePath, {
|
|
670
667
|
content: lastApplied.content,
|
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,58 +13,26 @@
|
|
|
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
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 { genDiff, toLF, stripBOM } from "./edit-diff.js";
|
|
37
|
-
import { computeDrift } from "./session-view.js";
|
|
38
|
-
import { trackNoopPayload, clearNoopLoop, noopPayloadKey } from "./noop-guard.js";
|
|
32
|
+
import { buildBatchResult } from "./edit-response.js";
|
|
39
33
|
import { getEncodingState, prepareForSave } from "./file-encoding-state.js";
|
|
40
34
|
import { loadConfig } from "./store-config.js";
|
|
41
|
-
|
|
42
|
-
export function resolveDisplayPath(path, cwd) {
|
|
43
|
-
return toCwd(path, cwd);
|
|
44
|
-
}
|
|
45
|
-
/** Snapshot bookkeeping for noop/success results (best-effort). */
|
|
46
|
-
export async function snapshotIdFor(io, absolutePath, signal) {
|
|
47
|
-
try {
|
|
48
|
-
return await io.statVersion(absolutePath, signal);
|
|
49
|
-
}
|
|
50
|
-
catch {
|
|
51
|
-
try {
|
|
52
|
-
return (await fileSnap(absolutePath)).snapshotId;
|
|
53
|
-
}
|
|
54
|
-
catch {
|
|
55
|
-
return undefined;
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
// Engine helpers are private to Mutation — not re-exported for new code.
|
|
60
|
-
// Deprecated re-exports kept for existing tests (commitlint: ignore):
|
|
61
|
-
export { runFileEdits };
|
|
62
|
-
export { persistUndoAndWrite };
|
|
63
|
-
export { buildMetrics, buildNoop, buildChanged, buildBatchResult };
|
|
64
|
-
export { genDiff, restoreEndings, toLF, stripBOM };
|
|
65
|
-
export { computeDrift, scanDrift };
|
|
66
|
-
export { trackNoopPayload, clearNoopLoop, noopPayloadKey };
|
|
67
|
-
async function persistUndoAndWrite(opts) {
|
|
35
|
+
export async function persistUndoAndWrite(opts) {
|
|
68
36
|
const { io, files } = opts;
|
|
69
37
|
// Issue #112: decide the save text for EVERY file BEFORE any write. The seam throws
|
|
70
38
|
// E_ENCODING_UNWRITABLE when the recorded encoding cannot be reproduced through the
|
|
@@ -131,32 +99,28 @@ async function persistUndoAndWrite(opts) {
|
|
|
131
99
|
console.error("Failed to restore undo entry after write failure:", e);
|
|
132
100
|
}
|
|
133
101
|
}
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
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);
|
|
144
114
|
}
|
|
145
115
|
}
|
|
146
116
|
throw opts.sandbox.mapError(error, opts.sandboxPolicy);
|
|
147
117
|
}
|
|
148
118
|
}
|
|
149
|
-
async function commitSingle(opts) {
|
|
150
|
-
return persistUndoAndWrite({ ...opts, restoreUnwrittenUndos: true });
|
|
151
|
-
}
|
|
152
|
-
async function commitBatch(opts) {
|
|
153
|
-
return persistUndoAndWrite({ ...opts, restoreUnwrittenUndos: false });
|
|
154
|
-
}
|
|
155
119
|
// --- Deep seam: unified mutation API (one interface, thin adapters) ---
|
|
156
120
|
/**
|
|
157
121
|
* Deep seam: execute the full mutation lifecycle.
|
|
158
122
|
*
|
|
159
|
-
* Owns:
|
|
123
|
+
* Owns: runFileEdits → branch (single/multi × noop/applied) → commit →
|
|
160
124
|
* buildBatchResult → recordServedTruncated → return text.
|
|
161
125
|
*
|
|
162
126
|
* The tool layer (adapter) only validates and delegates; all
|
|
@@ -166,7 +130,7 @@ async function commitBatch(opts) {
|
|
|
166
130
|
*/
|
|
167
131
|
export async function execute(opts) {
|
|
168
132
|
const { io, items, sessionKey, signal, exec, sandbox, sandboxPolicy } = opts;
|
|
169
|
-
const fileResult = await
|
|
133
|
+
const fileResult = await runFileEdits(io, items, { signal, sessionKey });
|
|
170
134
|
const toSection = () => ({
|
|
171
135
|
path: fileResult.displayPath,
|
|
172
136
|
originalNormalized: fileResult.originalNormalized,
|
|
@@ -224,25 +188,25 @@ export async function execute(opts) {
|
|
|
224
188
|
}
|
|
225
189
|
};
|
|
226
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
|
+
};
|
|
227
201
|
if (isSingleCall) {
|
|
228
202
|
if (fileResult.appliedCount === 0) {
|
|
229
203
|
const built = buildBatchResult([toSection()]);
|
|
230
204
|
const serveLanded = await recordIfNeeded(built);
|
|
231
205
|
return withServeNotice(built.content[0].text, serveLanded);
|
|
232
206
|
}
|
|
233
|
-
await
|
|
207
|
+
await persistUndoAndWrite({
|
|
234
208
|
io,
|
|
235
|
-
files: [
|
|
236
|
-
{
|
|
237
|
-
absolutePath: fileResult.absolutePath,
|
|
238
|
-
displayPath: fileResult.displayPath,
|
|
239
|
-
originalNormalized: fileResult.originalNormalized,
|
|
240
|
-
bom: fileResult.bom,
|
|
241
|
-
originalEnding: fileResult.originalEnding,
|
|
242
|
-
originalHashes: fileResult.originalHashes,
|
|
243
|
-
result: fileResult.result,
|
|
244
|
-
},
|
|
245
|
-
],
|
|
209
|
+
files: [commitFile],
|
|
246
210
|
exec,
|
|
247
211
|
sandbox,
|
|
248
212
|
sandboxPolicy,
|
|
@@ -258,19 +222,9 @@ export async function execute(opts) {
|
|
|
258
222
|
// all noops — no commit
|
|
259
223
|
}
|
|
260
224
|
else if (fileResult.appliedCount > 0) {
|
|
261
|
-
await
|
|
225
|
+
await persistUndoAndWrite({
|
|
262
226
|
io,
|
|
263
|
-
files: [
|
|
264
|
-
{
|
|
265
|
-
absolutePath: fileResult.absolutePath,
|
|
266
|
-
displayPath: fileResult.displayPath,
|
|
267
|
-
originalNormalized: fileResult.originalNormalized,
|
|
268
|
-
bom: fileResult.bom,
|
|
269
|
-
originalEnding: fileResult.originalEnding,
|
|
270
|
-
originalHashes: fileResult.originalHashes,
|
|
271
|
-
result: fileResult.result,
|
|
272
|
-
},
|
|
273
|
-
],
|
|
227
|
+
files: [commitFile],
|
|
274
228
|
exec,
|
|
275
229
|
sandbox,
|
|
276
230
|
sandboxPolicy,
|
|
@@ -283,21 +237,3 @@ export async function execute(opts) {
|
|
|
283
237
|
const serveLanded = await recordIfNeeded(built);
|
|
284
238
|
return withServeNotice(built.content[0].text, serveLanded);
|
|
285
239
|
}
|
|
286
|
-
/** Apply a per-file sequence (batch's group) — owns the loop + unionRange + counters. */
|
|
287
|
-
export async function applySequence(io, items, ctx) {
|
|
288
|
-
return runFileEdits(io, items, ctx);
|
|
289
|
-
}
|
|
290
|
-
/** Commit the transaction — owns persist-undo → write → restore. */
|
|
291
|
-
export async function commit(opts) {
|
|
292
|
-
return persistUndoAndWrite({
|
|
293
|
-
io: opts.io,
|
|
294
|
-
files: opts.files,
|
|
295
|
-
exec: opts.exec,
|
|
296
|
-
sandbox: opts.sandbox,
|
|
297
|
-
sandboxPolicy: opts.sandboxPolicy,
|
|
298
|
-
signal: opts.signal,
|
|
299
|
-
undoUnavailableMessage: opts.undoUnavailableMessage,
|
|
300
|
-
restoreUnwrittenUndos: opts.restoreUnwrittenUndos ?? false,
|
|
301
|
-
});
|
|
302
|
-
}
|
|
303
|
-
export { commitSingle, commitBatch };
|
package/lib/noop-guard.js
CHANGED
|
@@ -1,47 +1,32 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
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
|
|
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(
|
|
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
|
-
// Audience rule: the notice predicts the next resend rejects, so the model must
|
|
31
|
-
// act on it — MODEL (#116, ADR-0014 amendment).
|
|
32
|
-
const notice = formatWarning("W_NOOP", {
|
|
33
|
-
ref: input.ref,
|
|
34
|
-
anchorFrom: input.anchorFrom,
|
|
35
|
-
anchorTo: input.anchorTo,
|
|
36
|
-
batch: input.batch,
|
|
37
|
-
count,
|
|
38
|
-
});
|
|
39
|
-
return { action: "warn", count, notice };
|
|
40
|
-
}
|
|
41
|
-
return { action: "proceed", count };
|
|
42
|
-
}
|
|
43
|
-
export async function runNoopPolicy(input) {
|
|
44
|
-
const payload = noopPayloadKey(input.absolutePath, input.anchorFrom, input.anchorTo, input.replaceWith);
|
|
45
|
-
const count = trackNoopPayload(input.absolutePath, payload);
|
|
46
|
-
return runNoopPolicySync(input, count);
|
|
30
|
+
export function clearNoopLoop(sessionKey, absolutePath) {
|
|
31
|
+
noopLoopTracker.delete(trackerKey(sessionKey, absolutePath));
|
|
47
32
|
}
|
package/lib/paths.js
CHANGED
|
@@ -1,15 +1,19 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Paths — thin adapter over StoreTenancy + CanonicalPath.
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
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) {
|