dsh-better-edit 1.2.2 → 1.2.4
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 +21 -0
- package/README.md +39 -20
- package/README.zh.md +39 -31
- package/lib/contract.js +53 -22
- package/lib/domain-errors.js +7 -1
- package/lib/file-encoding-state.js +99 -22
- package/lib/fs-bridge.js +58 -41
- package/lib/hashline/anchor-pipeline.js +10 -35
- package/lib/index.js +24 -9
- package/lib/mutation/engine.js +10 -49
- package/lib/mutation.js +28 -6
- package/lib/noop-guard.js +2 -1
- package/lib/preset-toolset.js +144 -0
- package/lib/prompts.js +3 -3
- package/lib/read-and-serve.js +2 -2
- package/lib/self-heal.js +8 -3
- package/lib/session-view.js +22 -32
- package/lib/tool-edit.js +14 -53
- package/lib/tool-str-replace-editor.js +31 -8
- package/lib/tool-undo.js +37 -11
- package/lib/types/contract.d.ts +9 -19
- package/lib/types/domain-errors.d.ts +6 -1
- package/lib/types/file-encoding-state.d.ts +42 -5
- package/lib/types/fs-bridge.d.ts +0 -1
- package/lib/types/mutation/engine.d.ts +0 -10
- package/lib/types/mutation.d.ts +3 -3
- package/lib/types/preset-toolset.d.ts +61 -0
- package/lib/types/read-and-serve.d.ts +2 -2
- package/lib/types/self-heal.d.ts +9 -3
- package/lib/types/session-view.d.ts +10 -0
- package/lib/types/tool-edit.d.ts +2 -2
- package/lib/write-hook.js +10 -1
- package/package.json +1 -1
package/lib/fs-bridge.js
CHANGED
|
@@ -20,7 +20,7 @@ import { loadConfig } from "./store-config.js";
|
|
|
20
20
|
import { fileSnap } from "./file-reader.js";
|
|
21
21
|
import { resolveTarget, toCwd } from "./paths.js";
|
|
22
22
|
import { decodeForOpen, recordOpenState, recordFooter, getEncodingState as _getEncodingState, setEncodingState as _setEncodingState, clearEncodingState as _clearEncodingState, getAutoGuessFooter as _getAutoGuessFooter, setAutoGuessFooter as _setAutoGuessFooter, clearAutoGuessFooter as _clearAutoGuessFooter, invalidateIfStale, prepareForSave, } from "./file-encoding-state.js";
|
|
23
|
-
import { codeOf } from "./utils.js";
|
|
23
|
+
import { codeOf, errCode } from "./utils.js";
|
|
24
24
|
import { DomainError } from "./domain-errors.js";
|
|
25
25
|
export { _getEncodingState as getEncodingState, _setEncodingState as setEncodingState, _clearEncodingState as clearEncodingState, _getAutoGuessFooter as getAutoGuessFooter, _setAutoGuessFooter as setAutoGuessFooter, _clearAutoGuessFooter as clearAutoGuessFooter, };
|
|
26
26
|
// Keep alias for tests that import getAutoGuessFooter via fs-bridge
|
|
@@ -36,6 +36,8 @@ export function getAutoGuessFooterCompat(k) {
|
|
|
36
36
|
*/
|
|
37
37
|
export function mapFsError(error, displayPath) {
|
|
38
38
|
if (error instanceof Error && typeof error.code === "string") {
|
|
39
|
+
// SAFETY: provider failures (FsError or the local backend's plain Error) carry a
|
|
40
|
+
// string `code` field that the published error type does not declare.
|
|
39
41
|
const code = error.code;
|
|
40
42
|
if (code === "FS_NOT_FOUND") {
|
|
41
43
|
throw new DomainError("E_NOT_FOUND", { path: displayPath });
|
|
@@ -120,7 +122,15 @@ async function restoreStrippedUtf8Bom(fs, target, text, signal) {
|
|
|
120
122
|
}
|
|
121
123
|
return { text: `${UTF8_BOM}${text}`, version };
|
|
122
124
|
}
|
|
123
|
-
/**
|
|
125
|
+
/**
|
|
126
|
+
* The memo/policy key for a resolved target: the backend's optional `targetKey`
|
|
127
|
+
* when it carries one (symlink/case canonicalisation), else the absolute path.
|
|
128
|
+
* One seam for the five read/write sites so the memo cannot be keyed two ways.
|
|
129
|
+
*/
|
|
130
|
+
function targetKeyOf(target, absolutePath) {
|
|
131
|
+
// SAFETY: FsTarget is opaque; `targetKey` is an optional string field on the local backend.
|
|
132
|
+
return String(target.targetKey ?? absolutePath);
|
|
133
|
+
}
|
|
124
134
|
export function ctxFsIO(fs, ctx) {
|
|
125
135
|
return {
|
|
126
136
|
async resolve(path, cwd, signal) {
|
|
@@ -144,7 +154,7 @@ export function ctxFsIO(fs, ctx) {
|
|
|
144
154
|
encodingHint,
|
|
145
155
|
displayPath: absolutePath,
|
|
146
156
|
});
|
|
147
|
-
const targetKey =
|
|
157
|
+
const targetKey = targetKeyOf(target, absolutePath);
|
|
148
158
|
recordOpenState(targetKey, decoded.text, decoded.encoding, decoded.hasBOM, info?.version);
|
|
149
159
|
// Gate looks up by resolved absolutePath; targetKey may differ
|
|
150
160
|
// (symlink/case) — mirror under both keys (issue #69 note).
|
|
@@ -169,7 +179,7 @@ export function ctxFsIO(fs, ctx) {
|
|
|
169
179
|
const { text: restored, version } = await restoreStrippedUtf8Bom(fs, target, text, signal);
|
|
170
180
|
// record file encoding state for round-trip (BOM + lineEnding)
|
|
171
181
|
try {
|
|
172
|
-
const targetKey =
|
|
182
|
+
const targetKey = targetKeyOf(target, absolutePath);
|
|
173
183
|
const hasBOM = restored.startsWith(UTF8_BOM);
|
|
174
184
|
const clean = hasBOM ? restored.slice(1) : restored;
|
|
175
185
|
// use seam to record with correct lineEnding detection
|
|
@@ -188,7 +198,7 @@ export function ctxFsIO(fs, ctx) {
|
|
|
188
198
|
return restored;
|
|
189
199
|
}
|
|
190
200
|
catch (error) {
|
|
191
|
-
const isNotText = error
|
|
201
|
+
const isNotText = errCode(error) === "FS_NOT_TEXT";
|
|
192
202
|
if (isNotText) {
|
|
193
203
|
const cfg = loadConfig();
|
|
194
204
|
const target = await fs.resolve(absolutePath, {
|
|
@@ -199,7 +209,7 @@ export function ctxFsIO(fs, ctx) {
|
|
|
199
209
|
if (info && info.size !== undefined && info.size > maxBytes)
|
|
200
210
|
throw error;
|
|
201
211
|
const bytes = await fs.readBytes(target, signal, maxBytes);
|
|
202
|
-
const targetKey =
|
|
212
|
+
const targetKey = targetKeyOf(target, absolutePath);
|
|
203
213
|
// Delegate deterministic admission to the deep seam
|
|
204
214
|
const decoded = await decodeForOpen(bytes, cfg, { displayPath: absolutePath });
|
|
205
215
|
recordOpenState(targetKey, decoded.text, decoded.encoding, decoded.hasBOM, info?.version);
|
|
@@ -217,42 +227,42 @@ export function ctxFsIO(fs, ctx) {
|
|
|
217
227
|
}
|
|
218
228
|
},
|
|
219
229
|
async writeText(absolutePath, content, signal, exec, sandboxPolicy) {
|
|
220
|
-
// handle drift invalidation before encode — seam owns version check
|
|
221
230
|
try {
|
|
222
|
-
const
|
|
231
|
+
const target = await fs.resolve(absolutePath, {
|
|
223
232
|
...(signal === undefined ? {} : { signal }),
|
|
224
233
|
});
|
|
225
|
-
const key =
|
|
226
|
-
|
|
227
|
-
|
|
234
|
+
const key = targetKeyOf(target, absolutePath);
|
|
235
|
+
// Drop a memo that no longer matches the on-disk version before deciding:
|
|
236
|
+
// the save verdict must describe the bytes actually being replaced.
|
|
237
|
+
const info = await fs.stat(target, signal).catch(() => undefined);
|
|
238
|
+
const version = info?.version;
|
|
239
|
+
invalidateIfStale(key, version);
|
|
228
240
|
if (key !== absolutePath)
|
|
229
|
-
invalidateIfStale(absolutePath,
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
const
|
|
234
|
-
|
|
241
|
+
invalidateIfStale(absolutePath, version);
|
|
242
|
+
// The seam owns the round-trip verdict. It throws E_ENCODING_UNWRITABLE
|
|
243
|
+
// BEFORE the provider sees a write when the recorded encoding cannot be
|
|
244
|
+
// reproduced through the text-only write (issue #112).
|
|
245
|
+
const cfgW = loadConfig();
|
|
246
|
+
const existing = _getEncodingState(key) ?? _getEncodingState(absolutePath);
|
|
247
|
+
const prep = prepareForSave(content, existing, {
|
|
248
|
+
normalizeToUtf8: cfgW.normalizeToUtf8,
|
|
249
|
+
displayPath: absolutePath,
|
|
235
250
|
});
|
|
236
251
|
const intent = await ctx.waterfall("fs/write-intent", target, exec, () => undefined);
|
|
237
|
-
//
|
|
238
|
-
//
|
|
239
|
-
|
|
240
|
-
try {
|
|
241
|
-
const cfgW = loadConfig();
|
|
242
|
-
const key = String(target.targetKey ?? absolutePath);
|
|
243
|
-
// Honor manual override if content was produced via write({encoding}) — not wired here,
|
|
244
|
-
// encodingHint is not part of writeText signature for ctxFsIO in current call sites.
|
|
245
|
-
// Check existing memo for legacy preservation.
|
|
246
|
-
const existing = _getEncodingState(key);
|
|
247
|
-
const prep = prepareForSave(content, existing, { normalizeToUtf8: cfgW.normalizeToUtf8 });
|
|
248
|
-
// For Save with Encoding hint, prepareForSave would create newState — not used in this path (tool-undo/write-hook carry hint separately)
|
|
249
|
-
if (prep.newState)
|
|
250
|
-
_setEncodingState(key, prep.newState);
|
|
251
|
-
// content stays as UTF-8 string for provider; prep.textToWrite is same as content
|
|
252
|
-
}
|
|
253
|
-
catch { } // biome-ignore: best-effort
|
|
254
|
-
const outcome = await fs.writeText(target, content, intent, signal, sandboxPolicy);
|
|
252
|
+
// The provider encodes the string as UTF-8; prep.textToWrite already carries
|
|
253
|
+
// the restored BOM + line endings (or the explicit normalizeToUtf8 migration).
|
|
254
|
+
const outcome = await fs.writeText(target, prep.textToWrite, intent, signal, sandboxPolicy);
|
|
255
255
|
ctx.emit("fs/observed", target, { kind: "present", version: outcome.version }, exec);
|
|
256
|
+
// Memo/bytes agreement: every write records the state of the bytes just written.
|
|
257
|
+
if (prep.newState) {
|
|
258
|
+
const written = {
|
|
259
|
+
...prep.newState,
|
|
260
|
+
version: outcome.version,
|
|
261
|
+
};
|
|
262
|
+
_setEncodingState(key, written);
|
|
263
|
+
if (key !== absolutePath)
|
|
264
|
+
_setEncodingState(absolutePath, written);
|
|
265
|
+
}
|
|
256
266
|
}
|
|
257
267
|
catch (error) {
|
|
258
268
|
return mapFsError(error, absolutePath);
|
|
@@ -328,13 +338,20 @@ export function localIO() {
|
|
|
328
338
|
},
|
|
329
339
|
async writeText(absolutePath, content, signal, _exec, _sandboxPolicy) {
|
|
330
340
|
signal?.throwIfAborted();
|
|
331
|
-
//
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
341
|
+
// Drop a stale memo, then let the seam decide: it throws E_ENCODING_UNWRITABLE
|
|
342
|
+
// before writeAtomic when the recorded encoding cannot round-trip (#112).
|
|
343
|
+
const info = await fileSnap(absolutePath).catch(() => undefined);
|
|
344
|
+
invalidateIfStale(absolutePath, info?.snapshotId);
|
|
345
|
+
const cfgL = loadConfig();
|
|
346
|
+
const prep = prepareForSave(content, _getEncodingState(absolutePath), {
|
|
347
|
+
normalizeToUtf8: cfgL.normalizeToUtf8,
|
|
348
|
+
displayPath: absolutePath,
|
|
349
|
+
});
|
|
350
|
+
await writeAtomic(absolutePath, prep.textToWrite);
|
|
351
|
+
if (prep.newState) {
|
|
352
|
+
const after = await fileSnap(absolutePath).catch(() => undefined);
|
|
353
|
+
_setEncodingState(absolutePath, { ...prep.newState, version: after?.snapshotId });
|
|
335
354
|
}
|
|
336
|
-
catch { }
|
|
337
|
-
await writeAtomic(absolutePath, content);
|
|
338
355
|
},
|
|
339
356
|
async emitObserved() {
|
|
340
357
|
// No policy event gate on the host filesystem; nothing to record.
|
|
@@ -34,21 +34,6 @@ function diagRef(ref) {
|
|
|
34
34
|
reason: 'Use the hash alone (e.g. "aB3") — no line numbers or trailing content.',
|
|
35
35
|
};
|
|
36
36
|
}
|
|
37
|
-
if (trimmed.includes("│") && trimmed.includes("\n")) {
|
|
38
|
-
const lines = trimmed.split("\n");
|
|
39
|
-
const first = lines[0] ?? "";
|
|
40
|
-
const last = lines[lines.length - 1] ?? "";
|
|
41
|
-
const hashRe = new RegExp(HASH_CLASS);
|
|
42
|
-
const firstMatch = first.match(hashRe);
|
|
43
|
-
const lastMatch = last.match(hashRe);
|
|
44
|
-
const firstHash = firstMatch?.[0] ?? "wUp";
|
|
45
|
-
const lastHash = lastMatch?.[0] ?? "AU6";
|
|
46
|
-
const preview = first.slice(0, 60);
|
|
47
|
-
return {
|
|
48
|
-
rawAnchor: trimmed,
|
|
49
|
-
reason: `anchor_from must be a single bare 3-char hash (e.g. "wUp"), not a block with HASH│. Received ${lines.length} lines starting "${preview}…" — use only the first hash "${firstHash}" as anchor_from and "${lastHash}" as anchor_to, and put the new content (without HASH│) in replace_with.`,
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
37
|
if (trimmed.includes("│")) {
|
|
53
38
|
return {
|
|
54
39
|
rawAnchor: trimmed,
|
|
@@ -187,31 +172,21 @@ function assertItem(edit) {
|
|
|
187
172
|
}
|
|
188
173
|
}
|
|
189
174
|
const ANCHOR_ROW_RE = new RegExp(`^([+-]?)(${HASH_CLASS})│`);
|
|
190
|
-
function firstHashFromBlock(block) {
|
|
191
|
-
for (const line of block.split("\n")) {
|
|
192
|
-
const m = line.match(ANCHOR_ROW_RE);
|
|
193
|
-
if (m)
|
|
194
|
-
return m[2];
|
|
195
|
-
const bare = line.match(new RegExp(HASH_CLASS));
|
|
196
|
-
if (bare)
|
|
197
|
-
return bare[0];
|
|
198
|
-
}
|
|
199
|
-
return undefined;
|
|
200
|
-
}
|
|
201
175
|
export function resEdit(edit, _warnings) {
|
|
202
176
|
assertItem(edit);
|
|
203
177
|
const editLines = parseText(edit.replace_with);
|
|
204
178
|
const bounds = [edit.anchor_from, edit.anchor_to].map((ref) => {
|
|
205
179
|
const trimmed = ref.trim();
|
|
180
|
+
// #108: a pasted block carries no verified coordinate — refuse by SHAPE, naming no
|
|
181
|
+
// extracted hash. The old first-3-char-alnum-run guess minted a pseudo-anchor whose
|
|
182
|
+
// "use bare <hash> next time" hint steered the model into an unrelated line.
|
|
206
183
|
if (trimmed.includes("\n")) {
|
|
207
|
-
const
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
});
|
|
214
|
-
}
|
|
184
|
+
const lines = trimmed.split("\n").length;
|
|
185
|
+
throw new DomainError("E_MALFORMED_ANCHOR", {
|
|
186
|
+
// Redacted, upstream shape: never echo the pasted block back into the transcript.
|
|
187
|
+
rawAnchor: `${lines}-line block`,
|
|
188
|
+
reason: `anchor_from/anchor_to must be a single bare 3-char hash — the anchor read() served beside the one line you mean. You passed a ${lines}-line block; pass that bare hash, or re-read the file.`,
|
|
189
|
+
});
|
|
215
190
|
}
|
|
216
191
|
const match = trimmed.match(ANCHOR_ROW_RE);
|
|
217
192
|
if (match) {
|
|
@@ -311,7 +286,7 @@ function swapReversedRanges(edit, fileHashes, warnings) {
|
|
|
311
286
|
return { ...edit, hash_bounds: [endRef, startRef] };
|
|
312
287
|
}
|
|
313
288
|
/** @internal — private to anchor-pipeline seam */
|
|
314
|
-
function valEdit(edit, fileLines, fileHashes,
|
|
289
|
+
function valEdit(edit, fileLines, fileHashes, _warnings, signal) {
|
|
315
290
|
assertAligned(fileLines, fileHashes, "valEdit");
|
|
316
291
|
const mismatches = [];
|
|
317
292
|
const hashIndex = new Map();
|
package/lib/index.js
CHANGED
|
@@ -6,6 +6,7 @@ import { buildStrReplaceEditorTool } from "./tool-str-replace-editor.js";
|
|
|
6
6
|
import { registerUndoTool } 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
10
|
import { initHasher } from "./hashline/hash-assign.js";
|
|
10
11
|
import { composeSections, ensurePresetGuidance, GUIDANCE_SECTIONS, } from "./guidance.js";
|
|
11
12
|
import { configDir } from "./store/index.js";
|
|
@@ -88,20 +89,34 @@ function installAgentTools(rootCtx, agent) {
|
|
|
88
89
|
// not declare it. The session's live directory still reaches the bridge
|
|
89
90
|
// per call via `execCwd` (the `workingDirectory` service, falling back to
|
|
90
91
|
// `exec.agent.session.header.cwd`).
|
|
92
|
+
// The composed preset's own tool policy decides which mutating tools
|
|
93
|
+
// this agent gets; `read` is unconditional (Rianico/dsh-better-edit#110).
|
|
94
|
+
const toolset = await resolveToolset(rootCtx, agent.ctx);
|
|
91
95
|
const io = ctxFsIO(rootCtx.fs, rootCtx);
|
|
92
96
|
const disposers = [];
|
|
93
97
|
const sandbox = new FsSandboxController(rootCtx);
|
|
94
|
-
// Keep owned definitions by reference for self-heal identity check
|
|
98
|
+
// Keep owned definitions by reference for self-heal identity check. An
|
|
99
|
+
// absent definition is also the watcher's "never heal this" signal, so the
|
|
100
|
+
// heal set and the installed set cannot drift apart.
|
|
95
101
|
const hashReadDef = buildReadTool(io);
|
|
96
102
|
disposers.push(agent.ctx.tools.register(hashReadDef));
|
|
97
|
-
const hashEditDef = buildEditTool(io, sandbox);
|
|
98
|
-
|
|
103
|
+
const hashEditDef = toolset.edit ? buildEditTool(io, sandbox) : undefined;
|
|
104
|
+
if (hashEditDef !== undefined)
|
|
105
|
+
disposers.push(agent.ctx.tools.register(hashEditDef));
|
|
99
106
|
// Governed shadow of the preset's built-in str_replace_editor
|
|
100
|
-
// (ADR-0015): identical contract, encoding-governed mutations.
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
107
|
+
// (ADR-0015): identical contract, encoding-governed mutations. Only a
|
|
108
|
+
// preset that composed the built-in earns the shadow.
|
|
109
|
+
const hashStrReplaceDef = toolset.strReplaceEditor
|
|
110
|
+
? buildStrReplaceEditorTool(io, sandbox)
|
|
111
|
+
: undefined;
|
|
112
|
+
if (hashStrReplaceDef !== undefined) {
|
|
113
|
+
disposers.push(agent.ctx.tools.register(hashStrReplaceDef));
|
|
114
|
+
}
|
|
115
|
+
if (toolset.undo)
|
|
116
|
+
disposers.push(registerUndoTool(rootCtx, agent.ctx, io, sandbox));
|
|
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));
|
|
105
120
|
const toolsSvc = rootCtx.get("tools");
|
|
106
121
|
disposers.push(createSelfHealWatcher({
|
|
107
122
|
agentId: agent.id,
|
|
@@ -117,7 +132,7 @@ function installAgentTools(rootCtx, agent) {
|
|
|
117
132
|
// contract. Same section names on the agent's own layer win over the
|
|
118
133
|
// preset's; text and order come from the per-preset resolution, with the
|
|
119
134
|
// harness's canonical tool slot as the default order.
|
|
120
|
-
const sections = await resolveAgentSections(rootCtx, agent);
|
|
135
|
+
const sections = sectionsForToolset(await resolveAgentSections(rootCtx, agent), toolset);
|
|
121
136
|
for (const section of sections) {
|
|
122
137
|
disposers.push(agent.ctx.systemPrompt.section(section));
|
|
123
138
|
}
|
package/lib/mutation/engine.js
CHANGED
|
@@ -16,10 +16,11 @@ import { loadConfig } from "../store-config.js";
|
|
|
16
16
|
import { canon } from "../hashline/hash-assign.js";
|
|
17
17
|
import { normFromText } from "../file-reader.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
21
|
import { AnchorSpaceExhaustedError, HASH_SPACE } from "../hashline/hash-assign.js";
|
|
22
22
|
import { buildNeverServedEditHint } from "../hashline/served-guard.js";
|
|
23
|
+
import { encodingHintAtVersion } from "../file-encoding-state.js";
|
|
23
24
|
function isAnchorSpaceExhausted(e) {
|
|
24
25
|
return (e instanceof AnchorSpaceExhaustedError ||
|
|
25
26
|
(e instanceof Error && e.message.includes("probing failed over")));
|
|
@@ -69,56 +70,12 @@ async function retryLineHashesWithPromotion(sessionKey, absolutePath, retired, s
|
|
|
69
70
|
}
|
|
70
71
|
import { MAX_HASH_LINES } from "../hashline/hash-assign.js";
|
|
71
72
|
import { AnchorMismatchError, ServedRejectionError, buildRangeEcho, fmtServedRows, } from "../hashline/anchor-pipeline.js";
|
|
72
|
-
import { DomainError,
|
|
73
|
-
import { findSnapshotPathsByHashes } from "../hash-store.js";
|
|
73
|
+
import { DomainError, formatWarning } from "../domain-errors.js";
|
|
74
74
|
import { clearNoopLoop, noopPayloadKey, trackNoopPayload } from "../noop-guard.js";
|
|
75
75
|
import { NOOP_LOOP_THRESHOLD } from "../constants.js";
|
|
76
76
|
import { abortIf, splitLines } from "../utils.js";
|
|
77
77
|
// ---------------------------------------------------------------------------
|
|
78
78
|
// 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
79
|
/** The hashes a range edit removes, for stable re-hash bookkeeping. */
|
|
123
80
|
export function collectRemovedHashes(edit, originalHashes) {
|
|
124
81
|
const removedHashes = new Set();
|
|
@@ -497,7 +454,13 @@ export async function runFileEdits(io, items, opts) {
|
|
|
497
454
|
const absolutePath = first.absolutePath;
|
|
498
455
|
const perSessionRetired = await loadRetiredAnchors(opts.sessionKey, absolutePath);
|
|
499
456
|
const reservedHashes = new Set(perSessionRetired);
|
|
500
|
-
|
|
457
|
+
// Issue #112: the mutating re-read consumes the encoding recorded by `read`,
|
|
458
|
+
// so a file admitted by `read({ encoding })` decodes to the same text (and the
|
|
459
|
+
// same anchors). The version guard drops a drifted memo first — re-detect, never
|
|
460
|
+
// launder the old encoding onto changed bytes.
|
|
461
|
+
const currentVersion = await io.statVersion(absolutePath, opts.signal);
|
|
462
|
+
const encodingHint = encodingHintAtVersion(absolutePath, currentVersion);
|
|
463
|
+
const rawText = await io.readText(absolutePath, opts.signal, encodingHint);
|
|
501
464
|
const { normalized: originalNormalized, bom, originalEnding, fileHashes: originalHashes, hadUtf8DecodeErrors, } = await normFromText({
|
|
502
465
|
absolutePath,
|
|
503
466
|
rawText,
|
|
@@ -716,8 +679,6 @@ export async function runFileEdits(io, items, opts) {
|
|
|
716
679
|
if (hadUtf8DecodeErrors) {
|
|
717
680
|
warnings.push("Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.");
|
|
718
681
|
}
|
|
719
|
-
if (first.fileWarning)
|
|
720
|
-
warnings.unshift(first.fileWarning);
|
|
721
682
|
let driftNotice;
|
|
722
683
|
if (appliedCount > 0 && unionStartLine !== Infinity) {
|
|
723
684
|
const resultLines = splitLines(result);
|
package/lib/mutation.js
CHANGED
|
@@ -29,13 +29,15 @@ import { fileSnap } from "./file-reader.js";
|
|
|
29
29
|
import { toCwd } from "./paths.js";
|
|
30
30
|
import { recordServedTruncated, retireAnchors, scanDrift } from "./session-view.js";
|
|
31
31
|
import { abortIf, splitLines } from "./utils.js";
|
|
32
|
-
import { runFileEdits
|
|
32
|
+
import { runFileEdits } from "./mutation/engine.js";
|
|
33
33
|
import { saveUndo } from "./undo-edit.js";
|
|
34
34
|
import { restoreEndings } from "./edit-diff.js";
|
|
35
35
|
import { buildMetrics, buildNoop, buildChanged, buildBatchResult } from "./edit-response.js";
|
|
36
36
|
import { genDiff, toLF, stripBOM } from "./edit-diff.js";
|
|
37
37
|
import { computeDrift } from "./session-view.js";
|
|
38
38
|
import { trackNoopPayload, clearNoopLoop, noopPayloadKey } from "./noop-guard.js";
|
|
39
|
+
import { getEncodingState, prepareForSave } from "./file-encoding-state.js";
|
|
40
|
+
import { loadConfig } from "./store-config.js";
|
|
39
41
|
/** Resolve the display path a caller names against the session cwd. */
|
|
40
42
|
export function resolveDisplayPath(path, cwd) {
|
|
41
43
|
return toCwd(path, cwd);
|
|
@@ -56,7 +58,7 @@ export async function snapshotIdFor(io, absolutePath, signal) {
|
|
|
56
58
|
}
|
|
57
59
|
// Engine helpers are private to Mutation — not re-exported for new code.
|
|
58
60
|
// Deprecated re-exports kept for existing tests (commitlint: ignore):
|
|
59
|
-
export { runFileEdits
|
|
61
|
+
export { runFileEdits };
|
|
60
62
|
export { persistUndoAndWrite };
|
|
61
63
|
export { buildMetrics, buildNoop, buildChanged, buildBatchResult };
|
|
62
64
|
export { genDiff, restoreEndings, toLF, stripBOM };
|
|
@@ -64,8 +66,28 @@ export { computeDrift, scanDrift };
|
|
|
64
66
|
export { trackNoopPayload, clearNoopLoop, noopPayloadKey };
|
|
65
67
|
async function persistUndoAndWrite(opts) {
|
|
66
68
|
const { io, files } = opts;
|
|
69
|
+
// Issue #112: decide the save text for EVERY file BEFORE any write. The seam throws
|
|
70
|
+
// E_ENCODING_UNWRITABLE when the recorded encoding cannot be reproduced through the
|
|
71
|
+
// text-only write, so a batch never leaves file 1 transcoded and file 2 refused —
|
|
72
|
+
// nothing (not even the undo rows) is written when the round-trip is impossible.
|
|
73
|
+
const normalizeToUtf8 = loadConfig().normalizeToUtf8;
|
|
74
|
+
const prepared = files.map((file) => {
|
|
75
|
+
const recorded = getEncodingState(file.absolutePath);
|
|
76
|
+
// No memo (e.g. a first write): reconstruct the utf8/utf8bom state the edit read.
|
|
77
|
+
const state = recorded ?? {
|
|
78
|
+
encoding: file.bom ? "utf8bom" : "utf8",
|
|
79
|
+
hasBOM: file.bom !== "",
|
|
80
|
+
lineEnding: file.originalEnding,
|
|
81
|
+
version: undefined,
|
|
82
|
+
};
|
|
83
|
+
const prep = prepareForSave(file.result, state, {
|
|
84
|
+
normalizeToUtf8,
|
|
85
|
+
displayPath: file.displayPath,
|
|
86
|
+
});
|
|
87
|
+
return { file, textToWrite: prep.textToWrite };
|
|
88
|
+
});
|
|
67
89
|
const undos = [];
|
|
68
|
-
for (const file of
|
|
90
|
+
for (const { file, textToWrite } of prepared) {
|
|
69
91
|
const undo = await saveUndo(file.absolutePath, {
|
|
70
92
|
content: file.originalNormalized,
|
|
71
93
|
bom: file.bom,
|
|
@@ -84,13 +106,13 @@ async function persistUndoAndWrite(opts) {
|
|
|
84
106
|
}
|
|
85
107
|
throw new Error(opts.undoUnavailableMessage(file.displayPath));
|
|
86
108
|
}
|
|
87
|
-
undos.push({ file, restore: undo.restore });
|
|
109
|
+
undos.push({ file, textToWrite, restore: undo.restore });
|
|
88
110
|
}
|
|
89
111
|
const written = [];
|
|
90
112
|
try {
|
|
91
113
|
for (const u of undos) {
|
|
92
114
|
abortIf(opts.signal);
|
|
93
|
-
await io.writeText(u.file.absolutePath, u.
|
|
115
|
+
await io.writeText(u.file.absolutePath, u.textToWrite, opts.signal, opts.exec, opts.sandboxPolicy);
|
|
94
116
|
written.push(u);
|
|
95
117
|
}
|
|
96
118
|
}
|
|
@@ -137,7 +159,7 @@ async function commitBatch(opts) {
|
|
|
137
159
|
* Owns: applySequence → branch (single/multi × noop/applied) → commit →
|
|
138
160
|
* buildBatchResult → recordServedTruncated → return text.
|
|
139
161
|
*
|
|
140
|
-
* The tool layer (adapter) only validates and
|
|
162
|
+
* The tool layer (adapter) only validates and delegates; all
|
|
141
163
|
* lifecycle branching concentrates here (locality). One interface serves N
|
|
142
164
|
* call sites (leverage). Deleting this module would scatter the lifecycle
|
|
143
165
|
* across every tool — it concentrates (deep).
|
package/lib/noop-guard.js
CHANGED
|
@@ -27,7 +27,8 @@ export function runNoopPolicySync(input, count) {
|
|
|
27
27
|
return { action: "reject", count, message };
|
|
28
28
|
}
|
|
29
29
|
if (count === 2) {
|
|
30
|
-
//
|
|
30
|
+
// Audience rule: the notice predicts the next resend rejects, so the model must
|
|
31
|
+
// act on it — MODEL (#116, ADR-0014 amendment).
|
|
31
32
|
const notice = formatWarning("W_NOOP", {
|
|
32
33
|
ref: input.ref,
|
|
33
34
|
anchorFrom: input.anchorFrom,
|
|
@@ -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
|
+
}
|