dsh-better-edit 0.7.1 → 0.8.0
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 +40 -25
- package/README.md +72 -66
- package/README.zh.md +83 -83
- package/lib/canonical-path.js +4 -1
- package/lib/contract.js +67 -22
- package/lib/edit-diff.js +1 -5
- package/lib/encoding.js +22 -5
- package/lib/file-encoding-state.js +50 -11
- package/lib/file-view.js +28 -41
- package/lib/fs-bridge.js +19 -9
- package/lib/fs-write.js +1 -1
- package/lib/guidance/materialize.js +1 -6
- package/lib/guidance/resolve.js +1 -1
- package/lib/hash-store.js +12 -20
- package/lib/hashline/anchor-pipeline.js +29 -29
- package/lib/hashline/hash-assign.js +7 -4
- package/lib/hashline/hash.js +3 -3
- package/lib/index.js +6 -0
- package/lib/mutation/engine.js +11 -14
- package/lib/mutation.js +7 -6
- package/lib/prompts.js +9 -8
- package/lib/read-and-serve.js +22 -11
- package/lib/render-text-warning.js +21 -0
- package/lib/sandbox.js +2 -5
- package/lib/self-heal.js +30 -27
- package/lib/session-view.js +5 -1
- package/lib/store-config.js +7 -2
- package/lib/store-lifecycle.js +7 -2
- package/lib/tool-edit.js +5 -2
- package/lib/tool-read.js +6 -9
- package/lib/tool-str-replace-editor.js +274 -0
- package/lib/tool-undo.js +2 -3
- package/lib/types/contract.d.ts +104 -17
- package/lib/types/file-encoding-state.d.ts +3 -0
- package/lib/types/file-view.d.ts +1 -1
- package/lib/types/hashline/index.d.ts +1 -1
- package/lib/types/render-text-warning.d.ts +22 -0
- package/lib/types/self-heal.d.ts +2 -0
- package/lib/types/tool-str-replace-editor.d.ts +27 -0
- package/lib/types/undo-edit.d.ts +1 -1
- package/lib/types/write-hook.d.ts +2 -2
- package/lib/undo-edit.js +6 -8
- package/lib/utils.js +1 -2
- package/lib/workspace-context.js +1 -1
- package/lib/write-hook.js +19 -22
- package/package.json +63 -57
|
@@ -21,10 +21,12 @@ export function getH() {
|
|
|
21
21
|
return hasher;
|
|
22
22
|
throw new Error("xxhash-wasm hasher not initialized; await initHasher() before calling hashline APIs.");
|
|
23
23
|
}
|
|
24
|
-
const hasherP = xxhash()
|
|
24
|
+
const hasherP = xxhash()
|
|
25
|
+
.then((h) => {
|
|
25
26
|
hasher = h;
|
|
26
27
|
return hasher;
|
|
27
|
-
})
|
|
28
|
+
})
|
|
29
|
+
.catch((err) => {
|
|
28
30
|
console.error("xxhash-wasm initialization failed:", err);
|
|
29
31
|
throw err;
|
|
30
32
|
});
|
|
@@ -107,7 +109,7 @@ function getCanon(cache, line) {
|
|
|
107
109
|
}
|
|
108
110
|
const BITSET_WORDS = Math.ceil(HASH_SPACE / 32);
|
|
109
111
|
function getBit(bits, idx) {
|
|
110
|
-
return (bits[idx >>> 5] >>> (idx & 31) & 1) !== 0;
|
|
112
|
+
return ((bits[idx >>> 5] >>> (idx & 31)) & 1) !== 0;
|
|
111
113
|
}
|
|
112
114
|
function setBit(bits, idx) {
|
|
113
115
|
bits[idx >>> 5] |= 1 << (idx & 31);
|
|
@@ -188,7 +190,8 @@ function nearestNew(candidates, target) {
|
|
|
188
190
|
}
|
|
189
191
|
const left = lo - 1;
|
|
190
192
|
const right = lo;
|
|
191
|
-
if (left >= 0 &&
|
|
193
|
+
if (left >= 0 &&
|
|
194
|
+
(right >= candidates.length || target - candidates[left] <= candidates[right] - target)) {
|
|
192
195
|
return left;
|
|
193
196
|
}
|
|
194
197
|
return right < candidates.length ? right : -1;
|
package/lib/hashline/hash.js
CHANGED
|
@@ -25,7 +25,7 @@ export function snapshotIOFor(store) {
|
|
|
25
25
|
},
|
|
26
26
|
};
|
|
27
27
|
}
|
|
28
|
-
return defaultHashSnapshotIO ?? {
|
|
28
|
+
return (defaultHashSnapshotIO ?? {
|
|
29
29
|
get: async (path, content, deleteCorrupt) => {
|
|
30
30
|
const s = await loadHashStore();
|
|
31
31
|
return s.getSnapshot(path, content, deleteCorrupt);
|
|
@@ -34,7 +34,7 @@ export function snapshotIOFor(store) {
|
|
|
34
34
|
const s = await loadHashStore();
|
|
35
35
|
s.upsertSnapshot(path, checksum, lineCount, hashes);
|
|
36
36
|
},
|
|
37
|
-
};
|
|
37
|
+
});
|
|
38
38
|
}
|
|
39
39
|
export function isValidHashList(value) {
|
|
40
40
|
if (!Array.isArray(value))
|
|
@@ -52,7 +52,7 @@ export async function lineHashes(content, path, previous, ioOrStore, persist, re
|
|
|
52
52
|
// Back-compat: caller may pass HashStore as 4th arg; adapt to IO.
|
|
53
53
|
const io = ioOrStore && "getSnapshot" in ioOrStore
|
|
54
54
|
? snapshotIOFor(ioOrStore)
|
|
55
|
-
: ioOrStore ?? snapshotIOFor(undefined);
|
|
55
|
+
: (ioOrStore ?? snapshotIOFor(undefined));
|
|
56
56
|
if (previous) {
|
|
57
57
|
const newHashes = mapStableHashes(previous.content, previous.hashes, content, previous.removedHashes, reservedHashes, retiredHashes.size, previous.hashes.length);
|
|
58
58
|
if (persist !== false && io) {
|
package/lib/index.js
CHANGED
|
@@ -2,6 +2,7 @@ import { ctxFsIO } from "./fs-bridge.js";
|
|
|
2
2
|
import { FsSandboxController } from "./sandbox.js";
|
|
3
3
|
import { buildReadTool } from "./tool-read.js";
|
|
4
4
|
import { buildEditTool } from "./tool-edit.js";
|
|
5
|
+
import { buildStrReplaceEditorTool } from "./tool-str-replace-editor.js";
|
|
5
6
|
import { registerUndoTool } from "./tool-undo.js";
|
|
6
7
|
import { registerWriteHook } from "./write-hook.js";
|
|
7
8
|
import { createSelfHealWatcher } from "./self-heal.js";
|
|
@@ -70,6 +71,10 @@ function installAgentTools(rootCtx, agent) {
|
|
|
70
71
|
disposers.push(agent.ctx.tools.register(hashReadDef));
|
|
71
72
|
const hashEditDef = buildEditTool(io, sandbox);
|
|
72
73
|
disposers.push(agent.ctx.tools.register(hashEditDef));
|
|
74
|
+
// Governed shadow of the preset's built-in str_replace_editor
|
|
75
|
+
// (ADR-0015): identical contract, encoding-governed mutations.
|
|
76
|
+
const hashStrReplaceDef = buildStrReplaceEditorTool(io);
|
|
77
|
+
disposers.push(agent.ctx.tools.register(hashStrReplaceDef));
|
|
73
78
|
disposers.push(registerUndoTool(rootCtx, agent.ctx, io, sandbox));
|
|
74
79
|
disposers.push(registerWriteHook(rootCtx, agent.ctx, io));
|
|
75
80
|
const toolsSvc = rootCtx.get("tools");
|
|
@@ -81,6 +86,7 @@ function installAgentTools(rootCtx, agent) {
|
|
|
81
86
|
toolsSvc,
|
|
82
87
|
hashReadDef,
|
|
83
88
|
hashEditDef,
|
|
89
|
+
hashStrReplaceDef,
|
|
84
90
|
}));
|
|
85
91
|
// Shadow the preset's built-in tool guidance with the hashline
|
|
86
92
|
// contract. Same section names on the agent's own layer win over the
|
package/lib/mutation/engine.js
CHANGED
|
@@ -20,7 +20,8 @@ import { applyEdit, resEdit, parseHashRef, } from "../hashline/anchor-pipeline.j
|
|
|
20
20
|
import { lineHashes } from "../hashline/hash.js";
|
|
21
21
|
import { AnchorSpaceExhaustedError, HASH_SPACE } from "../hashline/hash-assign.js";
|
|
22
22
|
function isAnchorSpaceExhausted(e) {
|
|
23
|
-
return e instanceof AnchorSpaceExhaustedError ||
|
|
23
|
+
return (e instanceof AnchorSpaceExhaustedError ||
|
|
24
|
+
(e instanceof Error && e.message.includes("E_ANCHOR_SPACE_EXHAUSTED")));
|
|
24
25
|
}
|
|
25
26
|
function promotionWarning(retiredSize, servedLen) {
|
|
26
27
|
return `[E_ANCHOR_SPACE_EXHAUSTED] Anchor space exhausted (retired ${retiredSize} + served ${servedLen} of ${HASH_SPACE}); promotion cleared retired — re-read recommended, stale-anchor checks degraded until next full read.`;
|
|
@@ -54,7 +55,7 @@ async function retryLineHashesWithPromotion(sessionKey, absolutePath, retired, s
|
|
|
54
55
|
import { MAX_HASH_LINES } from "../hashline/hash-assign.js";
|
|
55
56
|
import { AnchorMismatchError, ServedRejectionError, buildRangeEcho, fmtServedRows, recordEchoServes, } from "../hashline/anchor-pipeline.js";
|
|
56
57
|
import { findSnapshotPathsByHashes } from "../hash-store.js";
|
|
57
|
-
import { clearNoopLoop, noopPayloadKey, trackNoopPayload
|
|
58
|
+
import { clearNoopLoop, noopPayloadKey, trackNoopPayload } from "../noop-guard.js";
|
|
58
59
|
import { NOOP_LOOP_THRESHOLD } from "../constants.js";
|
|
59
60
|
import { abortIf, splitLines } from "../utils.js";
|
|
60
61
|
// ---------------------------------------------------------------------------
|
|
@@ -94,7 +95,7 @@ export async function resolveMissingPath(request) {
|
|
|
94
95
|
};
|
|
95
96
|
}
|
|
96
97
|
if (matches.length > 1) {
|
|
97
|
-
throw new Error(`[MODEL] [E_BAD_PAYLOAD] Edit request requires a non-empty "path" string; the anchors match multiple known files: ${matches.join(
|
|
98
|
+
throw new Error(`[MODEL] [E_BAD_PAYLOAD] Edit request requires a non-empty "path" string; the anchors match multiple known files: ${matches.join(", ")}. Include the intended path.`);
|
|
98
99
|
}
|
|
99
100
|
return undefined;
|
|
100
101
|
}
|
|
@@ -161,17 +162,14 @@ export async function applyOne(input, onReject) {
|
|
|
161
162
|
anchorResult = applyEdit(input.content, edit, input.signal, input.hashes, input.displayPath, input.served, input.servedCanons, retiredForApply, input.epochSnapshotId, input.curSnapshotId, input.strictPos);
|
|
162
163
|
}
|
|
163
164
|
catch (error) {
|
|
164
|
-
if (error instanceof AnchorMismatchError ||
|
|
165
|
-
error instanceof ServedRejectionError) {
|
|
165
|
+
if (error instanceof AnchorMismatchError || error instanceof ServedRejectionError) {
|
|
166
166
|
return onReject(error, edit);
|
|
167
167
|
}
|
|
168
168
|
throw error;
|
|
169
169
|
}
|
|
170
170
|
const result = anchorResult.content;
|
|
171
171
|
const noop = result === input.content;
|
|
172
|
-
const removedHashes = noop
|
|
173
|
-
? undefined
|
|
174
|
-
: collectRemovedHashes(edit, input.hashes);
|
|
172
|
+
const removedHashes = noop ? undefined : collectRemovedHashes(edit, input.hashes);
|
|
175
173
|
const retiredForHash = input.retired;
|
|
176
174
|
let resultHashes;
|
|
177
175
|
if (noop) {
|
|
@@ -238,9 +236,7 @@ export async function enforceNoopLoop(opts) {
|
|
|
238
236
|
await recordEchoServes(sessionKey, absolutePath, echoRows, "live", originalHashes.length);
|
|
239
237
|
}
|
|
240
238
|
throw new Error(`[E_NOOP_LOOP] edits[${index}] (${displayPath}): identical edit (${removeFrom} → ${removeTo}) submitted ${count}×, no changes each time. Range already has this text; resend will reject the batch.` +
|
|
241
|
-
(echoRows
|
|
242
|
-
? ` Current on-disk range:\n${fmtServedRows(echoRows, originalLines)}`
|
|
243
|
-
: ""));
|
|
239
|
+
(echoRows ? ` Current on-disk range:\n${fmtServedRows(echoRows, originalLines)}` : ""));
|
|
244
240
|
}
|
|
245
241
|
if (count === 2) {
|
|
246
242
|
return `[E_NOOP_LOOP] Notice: edits[${index}] (${displayPath}) — identical edit no-op'd twice; range already has this text. Resend will reject the batch.`;
|
|
@@ -288,7 +284,9 @@ export async function runFileEdits(io, items, opts) {
|
|
|
288
284
|
curSnapshotId = (await fileSnap(absolutePath)).snapshotId;
|
|
289
285
|
}
|
|
290
286
|
catch { }
|
|
291
|
-
const strictPos = epochSnapshotId !== undefined &&
|
|
287
|
+
const strictPos = epochSnapshotId !== undefined &&
|
|
288
|
+
curSnapshotId !== undefined &&
|
|
289
|
+
epochSnapshotId !== curSnapshotId; // automatic: strict when epoch mismatch (conservative, future: changed∩[L,R] refined)
|
|
292
290
|
const warnings = [];
|
|
293
291
|
let currentContent = originalNormalized;
|
|
294
292
|
let currentHashes = originalHashes;
|
|
@@ -324,8 +322,7 @@ export async function runFileEdits(io, items, opts) {
|
|
|
324
322
|
curSnapshotId,
|
|
325
323
|
strictPos,
|
|
326
324
|
}, async (error, edit) => {
|
|
327
|
-
if (error instanceof AnchorMismatchError ||
|
|
328
|
-
error instanceof ServedRejectionError) {
|
|
325
|
+
if (error instanceof AnchorMismatchError || error instanceof ServedRejectionError) {
|
|
329
326
|
const originalLines = splitLines(originalNormalized);
|
|
330
327
|
const echoRows = error.servedRows.length > 0
|
|
331
328
|
? error.servedRows
|
package/lib/mutation.js
CHANGED
|
@@ -35,7 +35,7 @@ import { sessionKeyFor } from "./workspace-context.js";
|
|
|
35
35
|
import { loadServed, loadServedCanons, loadEpochSnapshotId, loadRetiredAnchors, scanDrift, recordServedTruncated, } from "./session-view.js";
|
|
36
36
|
import { abortIf, splitLines } from "./utils.js";
|
|
37
37
|
import { applyOne } from "./mutation/engine.js";
|
|
38
|
-
import { runFileEdits, resolveMissingPath
|
|
38
|
+
import { runFileEdits, resolveMissingPath } from "./mutation/engine.js";
|
|
39
39
|
import { saveUndo } from "./undo-edit.js";
|
|
40
40
|
import { restoreEndings } from "./edit-diff.js";
|
|
41
41
|
import { buildMetrics, buildNoop, buildChanged, buildBatchResult } from "./edit-response.js";
|
|
@@ -79,9 +79,11 @@ export async function execPipeline(io, params, cwd, options) {
|
|
|
79
79
|
curSnapshotId = (await fileSnap(absolutePath)).snapshotId;
|
|
80
80
|
}
|
|
81
81
|
catch { }
|
|
82
|
-
const strictPos = epochSnapshotId !== undefined &&
|
|
82
|
+
const strictPos = epochSnapshotId !== undefined &&
|
|
83
|
+
curSnapshotId !== undefined &&
|
|
84
|
+
epochSnapshotId !== curSnapshotId; // automatic: strict when epoch mismatch (conservative, future: changed∩[L,R] refined)
|
|
83
85
|
const retiredPerSession = await loadRetiredAnchors(sessionKey, absolutePath);
|
|
84
|
-
const policy = options?.noPersist === true ?
|
|
86
|
+
const policy = options?.noPersist === true ? "preview" : "live";
|
|
85
87
|
const applied = await applyOne({
|
|
86
88
|
content: originalNormalized,
|
|
87
89
|
hashes: originalHashes,
|
|
@@ -103,8 +105,7 @@ export async function execPipeline(io, params, cwd, options) {
|
|
|
103
105
|
strictPos,
|
|
104
106
|
edit,
|
|
105
107
|
}, async (error) => {
|
|
106
|
-
if (error instanceof AnchorMismatchError ||
|
|
107
|
-
error instanceof ServedRejectionError) {
|
|
108
|
+
if (error instanceof AnchorMismatchError || error instanceof ServedRejectionError) {
|
|
108
109
|
await recordEchoServes(sessionKey, absolutePath, error.servedRows, policy, originalHashes.length);
|
|
109
110
|
}
|
|
110
111
|
throw error;
|
|
@@ -125,7 +126,7 @@ export async function execPipeline(io, params, cwd, options) {
|
|
|
125
126
|
});
|
|
126
127
|
}
|
|
127
128
|
catch (error) {
|
|
128
|
-
console.error(
|
|
129
|
+
console.error("Failed to compute drift notice:", error);
|
|
129
130
|
}
|
|
130
131
|
}
|
|
131
132
|
return {
|
package/lib/prompts.js
CHANGED
|
@@ -6,18 +6,19 @@
|
|
|
6
6
|
* followed by tight bullets.
|
|
7
7
|
* @module dsh-better-edit/prompts
|
|
8
8
|
*/
|
|
9
|
-
export const EDIT_DESCRIPTION =
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
9
|
+
export const EDIT_DESCRIPTION = 'Edit a range of lines in a text file with `{ "path": path, "edits": [[remove_from, remove_to, replacement_text], ...] }` (tuple) or object `{remove_from, remove_to, replacement_text}` entries \u2014 mixed batches allowed. ' +
|
|
10
|
+
'`path` is file path or null. `read` shows `HASH\u2502content` (e.g. `wUp\u2502 "site": {`) \u2014 use bare 3-char HASH anchors for ' +
|
|
11
|
+
'`remove_from`/`remove_to` (e.g. "wUp"), never `HASH\u2502content`. `replacement_text` is bare content, \\n joins lines, "" deletes. ' +
|
|
12
|
+
'Example: `{"path":"a.py","edits":[["wUp","AU6","new"]]}` (object form `{remove_from:"wUp",remove_to:"AU6",replacement_text:"new"}` equivalent). Edits are atomic; reuse `HASH\u2502content` from the diff after success. ' +
|
|
13
13
|
"On failure follow the error hint: `[MODEL]` errors need a retry with fresh anchors, `[USER]` notices are human-only.";
|
|
14
14
|
export const EDIT_GUIDANCE = {
|
|
15
|
-
intro: "Edit a range of lines via a bare 3-char HASH anchor \u2014 payload is { path, edits: [[hash,hash,text]] } (single-file atomic, null path infers).",
|
|
15
|
+
intro: "Edit a range of lines via a bare 3-char HASH anchor \u2014 payload is { path, edits: [[hash,hash,text]] } or { path, edits: [{remove_from, remove_to, replacement_text}] } (single-file atomic, null path infers; tuple and object forms are equivalent, mixed batches allowed).",
|
|
16
16
|
lines: [
|
|
17
|
-
|
|
17
|
+
'`edit`: `HASH` vs `HASH\u2502content` \u2014 `HASH` is the bare 3-char (e.g. "wUp"), `HASH\u2502content` is the full line from `read`/`diff` (e.g. `wUp\u2502 "site": {`); never mix them.',
|
|
18
18
|
"`edit`: get `remove_from`/`remove_to` by copying only the 3 chars before `\u2502` from `read` output \u2014 never include `\u2502` or content after it.",
|
|
19
|
-
|
|
20
|
-
|
|
19
|
+
'`edit`: `replacement_text` is plain file content without `HASH\u2502` \u2014 e.g. " \\"site\\": {\\n \\"class\\": SiteScraper," \u2014 never prefix lines with `HASH\u2502`.',
|
|
20
|
+
'`edit`: every `\\n` in `replacement_text` separates lines; mirror trailing blank lines explicitly (use "" to delete a range).',
|
|
21
|
+
"`edit`: `edits` entries accept either tuple `[remove_from, remove_to, replacement_text]` or object `{remove_from, remove_to, replacement_text}` \u2014 mixed batches allowed, each entry normalizes independently; unknown fields (e.g. stray `path`) are rejected.",
|
|
21
22
|
"`edit`: after a successful edit the returned diff shows fresh anchors (`HASH\u2502content`) \u2014 copy new `HASH` values from there for the next edit; no need to re-read.",
|
|
22
23
|
"`edit`: `remove_from`/`remove_to` are inclusive; batch multiple edits to the same file only when independent \u2014 they apply atomically (fail \u2192 nothing written).",
|
|
23
24
|
"`edit`: `[MODEL]` errors (e.g. `E_STALE_*`, `E_UNSERVED_*`, `E_BAD_PAYLOAD`, `E_SERVED_ECHO`) need a retry \u2014 `[USER]` warnings/`drift:` notices are human-only.",
|
package/lib/read-and-serve.js
CHANGED
|
@@ -50,10 +50,17 @@ export async function readAndServe(io, rawPath, cwd, options) {
|
|
|
50
50
|
if (filteredHashes.length > 0) {
|
|
51
51
|
// Reconstruct previous content from canons — canon is idempotent and whitespace-insensitive (ADR-0002: canon strips ASCII whitespace, so "a b" and "a b" share canon and hash). Joining filteredCanons preserves reuse correctness for mapStableHashes nearest-canon matching; byte-fidelity of whitespace is not required for anchor stability, only canon equality.
|
|
52
52
|
const prevContent = filteredCanons.join("\n");
|
|
53
|
-
previous = {
|
|
53
|
+
previous = {
|
|
54
|
+
content: prevContent,
|
|
55
|
+
hashes: filteredHashes,
|
|
56
|
+
removedHashes: new Set(retiredHashes),
|
|
57
|
+
};
|
|
54
58
|
}
|
|
55
59
|
}
|
|
56
|
-
let reservedHashes = new Set([
|
|
60
|
+
let reservedHashes = new Set([
|
|
61
|
+
...retiredHashes,
|
|
62
|
+
...servedForNorm.filter((h) => h !== null),
|
|
63
|
+
]);
|
|
57
64
|
let reservations = { reservedHashes, retiredHashes };
|
|
58
65
|
let promotionWarning;
|
|
59
66
|
let view;
|
|
@@ -69,7 +76,8 @@ export async function readAndServe(io, rawPath, cwd, options) {
|
|
|
69
76
|
});
|
|
70
77
|
}
|
|
71
78
|
catch (e) {
|
|
72
|
-
if (e instanceof AnchorSpaceExhaustedError ||
|
|
79
|
+
if (e instanceof AnchorSpaceExhaustedError ||
|
|
80
|
+
(e instanceof Error && e.message.includes("E_ANCHOR_SPACE_EXHAUSTED"))) {
|
|
73
81
|
const retiredCount = retiredHashes.size;
|
|
74
82
|
const servedCount = servedForNorm.filter((h) => h !== null).length;
|
|
75
83
|
const reservedCount = retiredCount + servedCount;
|
|
@@ -127,17 +135,20 @@ export async function readAndServe(io, rawPath, cwd, options) {
|
|
|
127
135
|
// #69: epoch lifecycle belongs to full reads — a partial (paged or
|
|
128
136
|
// truncated) read merges window rows only and must not clear the
|
|
129
137
|
// drift-reported marks; only a full read resets them.
|
|
130
|
-
const isFullRead = options.offset === undefined &&
|
|
131
|
-
options.limit === undefined &&
|
|
132
|
-
!view.truncation?.truncated;
|
|
138
|
+
const isFullRead = options.offset === undefined && options.limit === undefined && !view.truncation?.truncated;
|
|
133
139
|
if (isFullRead)
|
|
134
140
|
await clearDriftReported(sessionKey, view.absolutePath);
|
|
135
|
-
const autoFooter = getAutoGuessFooter(view.absolutePath) ??
|
|
141
|
+
const autoFooter = getAutoGuessFooter(view.absolutePath) ??
|
|
142
|
+
getAutoGuessFooter(rawPath) ??
|
|
143
|
+
getAutoGuessFooter(view.absolutePath.replace(/\\/g, "/")) ??
|
|
144
|
+
"";
|
|
136
145
|
const autoWarning = autoFooter || undefined;
|
|
137
|
-
const warning = promotionWarning
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
146
|
+
const warning = promotionWarning
|
|
147
|
+
? autoWarning
|
|
148
|
+
? `${promotionWarning}\n${autoWarning}`
|
|
149
|
+
: promotionWarning
|
|
150
|
+
: autoWarning;
|
|
151
|
+
const text = view.hadUtf8DecodeErrors ? `${view.text}\n\n${UTF8_REWRITE_NOTE}` : view.text;
|
|
141
152
|
return {
|
|
142
153
|
text,
|
|
143
154
|
served: view.served,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared output-render seam for the `{ text, warning? }` tool payload.
|
|
3
|
+
*
|
|
4
|
+
* `read` (tool-read.ts) and `str_replace_editor` view (tool-str-replace-editor.ts)
|
|
5
|
+
* previously carried verbatim copies of this render closure, so a warning-format
|
|
6
|
+
* change had to be made in two places (report #7). Both now delegate here.
|
|
7
|
+
* @module dsh-better-edit/render-text-warning
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* Render a `{ text, warning? }` payload (or bare string) as content blocks:
|
|
11
|
+
* string input yields a single text block, object input yields the text block
|
|
12
|
+
* plus a second block when `warning` is present.
|
|
13
|
+
*/
|
|
14
|
+
export function renderTextWarning(value) {
|
|
15
|
+
if (typeof value === "string")
|
|
16
|
+
return [{ type: "text", text: value }];
|
|
17
|
+
const blocks = [{ type: "text", text: value.text }];
|
|
18
|
+
if (value.warning)
|
|
19
|
+
blocks.push({ type: "text", text: value.warning });
|
|
20
|
+
return blocks;
|
|
21
|
+
}
|
package/lib/sandbox.js
CHANGED
|
@@ -27,9 +27,7 @@ export class FsSandboxController {
|
|
|
27
27
|
const defaultMode = ctx.fs.sandboxMode;
|
|
28
28
|
this.escalationModes = defaultMode === undefined ? [] : ESCALATION_TARGETS;
|
|
29
29
|
this.policy =
|
|
30
|
-
defaultMode === undefined
|
|
31
|
-
? undefined
|
|
32
|
-
: ctx.get("sandboxPolicy");
|
|
30
|
+
defaultMode === undefined ? undefined : ctx.get("sandboxPolicy");
|
|
33
31
|
if (defaultMode !== undefined && this.policy === undefined) {
|
|
34
32
|
throw new Error("dsh-better-edit: the mounted filesystem confines but ctx.sandboxPolicy is missing");
|
|
35
33
|
}
|
|
@@ -72,8 +70,7 @@ export class FsSandboxController {
|
|
|
72
70
|
const standingPolicy = this.policy?.resolve({
|
|
73
71
|
...(exec.agent ? { session: exec.agent.session } : {}),
|
|
74
72
|
});
|
|
75
|
-
if (args.sandbox_permissions === undefined ||
|
|
76
|
-
args.justification === undefined) {
|
|
73
|
+
if (args.sandbox_permissions === undefined || args.justification === undefined) {
|
|
77
74
|
return standingPolicy;
|
|
78
75
|
}
|
|
79
76
|
if (this.escalationModes.length === 0) {
|
package/lib/self-heal.js
CHANGED
|
@@ -6,24 +6,30 @@
|
|
|
6
6
|
* @module dsh-better-edit/self-heal
|
|
7
7
|
*/
|
|
8
8
|
export function createSelfHealWatcher(options) {
|
|
9
|
-
const { agentId, rootCtx, agent, agentCtx, toolsSvc, hashReadDef, hashEditDef, healMinIntervalMs = 1000, } = options;
|
|
9
|
+
const { agentId, rootCtx, agent, agentCtx, toolsSvc, hashReadDef, hashEditDef, hashStrReplaceDef, healMinIntervalMs = 1000, } = options;
|
|
10
|
+
const watchStrReplace = hashStrReplaceDef !== undefined;
|
|
10
11
|
let lastHealAt = 0;
|
|
11
12
|
let healCount = 0;
|
|
12
13
|
let selfHealDisabled = false;
|
|
14
|
+
const formatFailMsg = (error) => `dsh-better-edit: self-heal failed for agent ${agentId}: ${error instanceof Error ? error.message : String(error)} \u2014 see Rianico/dsh-better-edit#43`;
|
|
15
|
+
const formatRestoredMsg = (toolLabel, attempt) => `dsh-better-edit: restored ${toolLabel} after external takeover \u2014 agent ${agentId} (${attempt}/2) \u2014 see Rianico/dsh-better-edit#43`;
|
|
13
16
|
const stop = agentCtx.on("tools/change", () => {
|
|
14
17
|
try {
|
|
15
18
|
if (selfHealDisabled)
|
|
16
19
|
return;
|
|
17
20
|
// SAFETY: toolsSvc is the DSH tools service — shape is `layers.scoped: Map<agent, {tools}>` per cordis internals; narrow at boundary
|
|
18
|
-
const layer = toolsSvc
|
|
19
|
-
?.layers?.scoped?.get?.(agent)?.tools;
|
|
21
|
+
const layer = toolsSvc?.layers?.scoped?.get?.(agent)?.tools;
|
|
20
22
|
if (!layer)
|
|
21
23
|
return;
|
|
22
24
|
const currentRead = layer?.get?.("read") ?? layer?.data?.get?.("read");
|
|
23
25
|
const currentEdit = layer?.get?.("edit") ?? layer?.data?.get?.("edit");
|
|
24
26
|
const readOk = currentRead === hashReadDef;
|
|
25
27
|
const editOk = currentEdit === hashEditDef;
|
|
26
|
-
|
|
28
|
+
const currentStrReplace = watchStrReplace
|
|
29
|
+
? (layer?.get?.("str_replace_editor") ?? layer?.data?.get?.("str_replace_editor"))
|
|
30
|
+
: hashStrReplaceDef;
|
|
31
|
+
const strReplaceOk = !watchStrReplace || currentStrReplace === hashStrReplaceDef;
|
|
32
|
+
if (readOk && editOk && strReplaceOk)
|
|
27
33
|
return;
|
|
28
34
|
const now = Date.now();
|
|
29
35
|
if (now - lastHealAt < healMinIntervalMs)
|
|
@@ -42,55 +48,52 @@ export function createSelfHealWatcher(options) {
|
|
|
42
48
|
lastHealAt = now;
|
|
43
49
|
const restoreRead = !readOk;
|
|
44
50
|
const restoreEdit = !editOk;
|
|
51
|
+
const restoreStrReplace = watchStrReplace && !strReplaceOk;
|
|
45
52
|
const restoreCount = healCount;
|
|
46
53
|
queueMicrotask(() => {
|
|
47
54
|
try {
|
|
48
55
|
// SAFETY: re-read layer inside microtask — same shape as above
|
|
49
|
-
const currentLayer = toolsSvc
|
|
50
|
-
?.layers?.scoped?.get?.(agent)?.tools;
|
|
56
|
+
const currentLayer = toolsSvc?.layers?.scoped?.get?.(agent)?.tools;
|
|
51
57
|
if (!currentLayer)
|
|
52
58
|
return;
|
|
53
|
-
|
|
59
|
+
const restoreTool = (name, def, toolLabel) => {
|
|
54
60
|
try {
|
|
55
|
-
currentLayer?.data?.delete?.(
|
|
61
|
+
currentLayer?.data?.delete?.(name);
|
|
56
62
|
}
|
|
57
63
|
catch {
|
|
58
64
|
// ignore — best-effort delete of intruding entry
|
|
59
65
|
}
|
|
60
66
|
try {
|
|
61
|
-
agentCtx.tools.register(
|
|
67
|
+
agentCtx.tools.register(def);
|
|
62
68
|
}
|
|
63
69
|
catch (e) {
|
|
64
|
-
rootCtx.logger.warn(
|
|
65
|
-
return;
|
|
70
|
+
rootCtx.logger.warn(formatFailMsg(e));
|
|
71
|
+
return false;
|
|
66
72
|
}
|
|
67
|
-
rootCtx.logger.warn(
|
|
73
|
+
rootCtx.logger.warn(formatRestoredMsg(toolLabel, restoreCount));
|
|
74
|
+
return true;
|
|
75
|
+
};
|
|
76
|
+
if (restoreEdit) {
|
|
77
|
+
if (!restoreTool("edit", hashEditDef, "hash-anchored edit"))
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (restoreStrReplace) {
|
|
81
|
+
if (!restoreTool("str_replace_editor", hashStrReplaceDef, "governed str_replace_editor"))
|
|
82
|
+
return;
|
|
68
83
|
}
|
|
69
84
|
if (restoreRead) {
|
|
70
|
-
|
|
71
|
-
currentLayer?.data?.delete?.("read");
|
|
72
|
-
}
|
|
73
|
-
catch {
|
|
74
|
-
// ignore — best-effort delete of intruding entry
|
|
75
|
-
}
|
|
76
|
-
try {
|
|
77
|
-
agentCtx.tools.register(hashReadDef);
|
|
78
|
-
}
|
|
79
|
-
catch (e) {
|
|
80
|
-
rootCtx.logger.warn(`dsh-better-edit: self-heal failed for agent ${agentId}: ${e instanceof Error ? e.message : String(e)} \u2014 see Rianico/dsh-better-edit#43`);
|
|
85
|
+
if (!restoreTool("read", hashReadDef, "hash-anchored read"))
|
|
81
86
|
return;
|
|
82
|
-
}
|
|
83
|
-
rootCtx.logger.warn(`dsh-better-edit: restored hash-anchored read after external takeover \u2014 agent ${agentId} (${restoreCount}/2) \u2014 see Rianico/dsh-better-edit#43`);
|
|
84
87
|
}
|
|
85
88
|
}
|
|
86
89
|
catch (error) {
|
|
87
|
-
rootCtx.logger.warn(
|
|
90
|
+
rootCtx.logger.warn(formatFailMsg(error));
|
|
88
91
|
}
|
|
89
92
|
});
|
|
90
93
|
}
|
|
91
94
|
catch (error) {
|
|
92
95
|
try {
|
|
93
|
-
rootCtx.logger.warn(
|
|
96
|
+
rootCtx.logger.warn(formatFailMsg(error));
|
|
94
97
|
}
|
|
95
98
|
catch {
|
|
96
99
|
// ignore — logger may throw in mock
|
package/lib/session-view.js
CHANGED
|
@@ -273,7 +273,11 @@ export async function recordServedTruncated(sessionKey, path, rows, lineCount, c
|
|
|
273
273
|
rowCanon.set(row.position, fullCanons[row.position] ?? null);
|
|
274
274
|
const updatedCanons = [];
|
|
275
275
|
for (let i = 0; i < updated.length; i++) {
|
|
276
|
-
updatedCanons.push(updated[i] === null
|
|
276
|
+
updatedCanons.push(updated[i] === null
|
|
277
|
+
? null
|
|
278
|
+
: rowCanon.has(i)
|
|
279
|
+
? rowCanon.get(i)
|
|
280
|
+
: (currentCanons[i] ?? null));
|
|
277
281
|
}
|
|
278
282
|
store.upsertServedCanons(sessionKey, path, JSON.stringify(updatedCanons));
|
|
279
283
|
}
|
package/lib/store-config.js
CHANGED
|
@@ -76,7 +76,10 @@ function parseAutoGitIgnoreRaw(v) {
|
|
|
76
76
|
}
|
|
77
77
|
function parseSupportedEncodingsRaw(v) {
|
|
78
78
|
const inner = v.trim().replace(/^\[/, "").replace(/\]$/, "");
|
|
79
|
-
const items = inner
|
|
79
|
+
const items = inner
|
|
80
|
+
.split(/[ ,;]+/)
|
|
81
|
+
.map((s) => s.trim().toLowerCase())
|
|
82
|
+
.filter((s) => s.length > 0);
|
|
80
83
|
if (items.length === 0)
|
|
81
84
|
return undefined;
|
|
82
85
|
return items;
|
|
@@ -90,7 +93,9 @@ const StoreConfigSchema = z.object({
|
|
|
90
93
|
autoGitignore: z.boolean().default(false), // workspace only: auto-append ".dsh_better_edit/" to .gitignore when .git exists but entry missing (false = warn once)
|
|
91
94
|
autoGuessEncoding: z.boolean().default(false), // VS Code files.autoGuessEncoding — deterministic BOM→UTF-8 first, model-assisted top-3 only when true
|
|
92
95
|
normalizeToUtf8: z.boolean().default(false), // when true, legacy files (GBK etc.) migrate to UTF-8 on first edit/write
|
|
93
|
-
supportedEncodings: z
|
|
96
|
+
supportedEncodings: z
|
|
97
|
+
.array(z.string())
|
|
98
|
+
.default(["gbk", "big5", "shift_jis", "euc-kr", "windows-1251", "iso-8859-1"]),
|
|
94
99
|
undo_ttl_s: z.number().int().min(-1).default(604800), // undo history TTL in seconds; -1 = keep forever (default 604800 = 7 days)
|
|
95
100
|
storeMaxAgeS: z.number().int().min(1).default(2592000), // central janitor: max idle age in seconds before evicting runtime/<name>-<hash8>/ (default 2592000 = 30 days)
|
|
96
101
|
storeMaxTotalBytes: z.number().int().min(0).default(524288000), // central janitor: max total bytes under runtime/ before LRU eviction (default 524288000 = 500 MB)
|
package/lib/store-lifecycle.js
CHANGED
|
@@ -37,7 +37,7 @@ function gitignoreHasEntry(ws) {
|
|
|
37
37
|
const content = readFileSync(join(ws, ".gitignore"), "utf-8");
|
|
38
38
|
return content.split("\n").some((l) => {
|
|
39
39
|
const t = l.trim();
|
|
40
|
-
return t === ".dsh_better_edit" || t === ".dsh_better_edit/" || t.startsWith(".dsh_better_edit/");
|
|
40
|
+
return (t === ".dsh_better_edit" || t === ".dsh_better_edit/" || t.startsWith(".dsh_better_edit/"));
|
|
41
41
|
});
|
|
42
42
|
}
|
|
43
43
|
catch {
|
|
@@ -134,7 +134,12 @@ export async function runCentralJanitorIfDue() {
|
|
|
134
134
|
if (!st.isDirectory())
|
|
135
135
|
continue;
|
|
136
136
|
let totalBytes = 0;
|
|
137
|
-
for (const file of [
|
|
137
|
+
for (const file of [
|
|
138
|
+
"hash-store.sqlite",
|
|
139
|
+
"hash-store.sqlite-wal",
|
|
140
|
+
"hash-store.sqlite-shm",
|
|
141
|
+
".wsPath",
|
|
142
|
+
]) {
|
|
138
143
|
try {
|
|
139
144
|
totalBytes += (await stat(join(dir, file))).size;
|
|
140
145
|
}
|
package/lib/tool-edit.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* @module dsh-better-edit/tool-edit
|
|
7
7
|
*/
|
|
8
8
|
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
9
|
-
import { normalizeRequest as normReq, assertEditRequest
|
|
9
|
+
import { normalizeRequest as normReq, assertEditRequest } from "./contract.js";
|
|
10
10
|
import { abortIf } from "./utils.js";
|
|
11
11
|
import { execute } from "./mutation.js";
|
|
12
12
|
import { EDIT_DESCRIPTION } from "./prompts.js";
|
|
@@ -54,7 +54,10 @@ export function buildEditTool(io, sandbox) {
|
|
|
54
54
|
edits: {
|
|
55
55
|
type: "array",
|
|
56
56
|
description: "Ordered list of edit tuples [remove_from, remove_to, replacement_text] — one edit per tuple, single-file atomic",
|
|
57
|
-
items: {
|
|
57
|
+
items: {
|
|
58
|
+
type: "json",
|
|
59
|
+
description: "[remove_from, remove_to, replacement_text]",
|
|
60
|
+
},
|
|
58
61
|
},
|
|
59
62
|
...(sandbox.escalationModes.length > 0 ? sandbox.schemaFields() : {}),
|
|
60
63
|
},
|
package/lib/tool-read.js
CHANGED
|
@@ -10,6 +10,7 @@ import { normalizeRequest as normReq, assertReadRequest, pathSchema } from "./co
|
|
|
10
10
|
import { readAndServe } from "./read-and-serve.js";
|
|
11
11
|
import { READ_DESCRIPTION } from "./prompts.js";
|
|
12
12
|
import { normalizeEncoding } from "./encoding.js";
|
|
13
|
+
import { renderTextWarning } from "./render-text-warning.js";
|
|
13
14
|
import { execCwd, execSessionKey } from "./workspace-context.js";
|
|
14
15
|
import { withWorkspace } from "./workspace-context.js";
|
|
15
16
|
/**
|
|
@@ -39,16 +40,12 @@ export function buildReadTool(io) {
|
|
|
39
40
|
},
|
|
40
41
|
},
|
|
41
42
|
output: {
|
|
42
|
-
schema: {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
return [{ type: "text", text: v }];
|
|
47
|
-
const blocks = [{ type: "text", text: v.text }];
|
|
48
|
-
if (v.warning)
|
|
49
|
-
blocks.push({ type: "text", text: v.warning });
|
|
50
|
-
return blocks;
|
|
43
|
+
schema: {
|
|
44
|
+
type: "object",
|
|
45
|
+
properties: { text: { type: "string", required: true }, warning: { type: "string" } },
|
|
46
|
+
additionalProperties: false,
|
|
51
47
|
},
|
|
48
|
+
render: (_args, value) => renderTextWarning(value),
|
|
52
49
|
},
|
|
53
50
|
async execute(args, exec) {
|
|
54
51
|
return withWorkspace(execCwd(exec), async () => {
|