dsh-better-edit 1.2.3 → 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 +14 -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/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/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/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/package.json +1 -1
package/lib/session-view.js
CHANGED
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
* @module dsh-better-edit/session-view
|
|
24
24
|
*/
|
|
25
25
|
import { ALPH, HASH_LEN, HASH_SPACE, HASH_RE, canon } from "./hashline/hash-assign.js";
|
|
26
|
-
import {
|
|
26
|
+
import { loadServedStore, withStore, DRIFT_EPISODE_PREFIX, DRIFT_EPISODE_RE, } from "./hash-store.js";
|
|
27
27
|
import { SERVED_ECHO_CAP } from "./constants.js";
|
|
28
28
|
import { fmtServedRows } from "./hashline/anchor-pipeline.js";
|
|
29
29
|
import { splitLines } from "./utils.js";
|
|
@@ -90,28 +90,10 @@ function addRetiredAnchors(store, sessionKey, path, hashes) {
|
|
|
90
90
|
}
|
|
91
91
|
retired.add(hash);
|
|
92
92
|
}
|
|
93
|
-
// Persist as legacy string array for backward compat;
|
|
93
|
+
// Persist as legacy string array for backward compat; `sweepAndRetire` writes object
|
|
94
|
+
// entries (hash + deathPos) for positions the served view displaced.
|
|
94
95
|
store.upsertRetiredAnchors(sessionKey, path, JSON.stringify([...retired]));
|
|
95
96
|
}
|
|
96
|
-
function addRetiredEntries(store, sessionKey, path, entries) {
|
|
97
|
-
if (entries.length === 0)
|
|
98
|
-
return;
|
|
99
|
-
const existing = store.getRetiredEntries(sessionKey, path);
|
|
100
|
-
const seen = new Set(existing.map((e) => e.hash));
|
|
101
|
-
for (const e of entries) {
|
|
102
|
-
if (!HASH_RE.test(e.hash))
|
|
103
|
-
throw new TypeError(`Invalid retired hash: ${e.hash}`);
|
|
104
|
-
if (!seen.has(e.hash)) {
|
|
105
|
-
existing.push(e);
|
|
106
|
-
seen.add(e.hash);
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
store.upsertRetiredAnchors(sessionKey, path, JSON.stringify(existing));
|
|
110
|
-
}
|
|
111
|
-
function displacedHashes(current, updated) {
|
|
112
|
-
const remaining = new Set(updated.filter((hash) => hash !== null));
|
|
113
|
-
return new Set(current.filter((hash) => hash !== null && !remaining.has(hash)));
|
|
114
|
-
}
|
|
115
97
|
function displacedEntries(current, updated) {
|
|
116
98
|
const remaining = new Set(updated.filter((hash) => hash !== null));
|
|
117
99
|
const entries = [];
|
|
@@ -126,17 +108,6 @@ function displacedEntries(current, updated) {
|
|
|
126
108
|
// deathPos=null = legacy/unknown position (pre-GC String[] format or migration).
|
|
127
109
|
// These entries are NOT swept incrementally — retained until full-recordServed (isFullRead) or major-GC promotion clears retired.
|
|
128
110
|
// Incremental hazard sweep only frees deathPos (number) whose card was re-observed; null survives partial sweeps by design (minor leak documented here) and is drained only on epoch promotion/full read.
|
|
129
|
-
function sweepRetiredByPositions(store, sessionKey, path, servedPositions) {
|
|
130
|
-
if (servedPositions.size === 0)
|
|
131
|
-
return;
|
|
132
|
-
const entries = store.getRetiredEntries(sessionKey, path);
|
|
133
|
-
if (entries.length === 0)
|
|
134
|
-
return;
|
|
135
|
-
const filtered = entries.filter((e) => e.deathPos === null || !servedPositions.has(e.deathPos));
|
|
136
|
-
if (filtered.length !== entries.length) {
|
|
137
|
-
store.upsertRetiredAnchors(sessionKey, path, JSON.stringify(filtered));
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
111
|
function sweepAndRetire(store, sessionKey, path, current, updated, rows) {
|
|
141
112
|
const servedPositions = new Set(rows.map((r) => r.position));
|
|
142
113
|
const existingCards = store.getCards(sessionKey, path);
|
|
@@ -180,6 +151,25 @@ export async function retireAnchors(sessionKey, path, hashes) {
|
|
|
180
151
|
retireAnchorsInStore(store, sessionKey, path, additions);
|
|
181
152
|
});
|
|
182
153
|
}
|
|
154
|
+
/**
|
|
155
|
+
* Caller-owned transaction: revive retired anchors inside the caller's unit.
|
|
156
|
+
*
|
|
157
|
+
* The undo restore is the one path that brings a retired assignment back: when the
|
|
158
|
+
* pre-edit line returns byte-identically, its pre-edit anchor is live again, so the
|
|
159
|
+
* retirement that the edit recorded must move with the restore (ADR-0017 reversal).
|
|
160
|
+
* Anchors not in the store's retired set are left untouched; the entry's `deathPos`
|
|
161
|
+
* does not matter — the anchor's line is back, so the whole entry goes.
|
|
162
|
+
*/
|
|
163
|
+
export function unretireAnchorsInStore(store, sessionKey, path, hashes) {
|
|
164
|
+
const revivals = new Set(hashes);
|
|
165
|
+
if (revivals.size === 0)
|
|
166
|
+
return;
|
|
167
|
+
const entries = store.getRetiredEntries(sessionKey, path);
|
|
168
|
+
const kept = entries.filter((entry) => !revivals.has(entry.hash));
|
|
169
|
+
if (kept.length !== entries.length) {
|
|
170
|
+
store.upsertRetiredAnchors(sessionKey, path, JSON.stringify(kept));
|
|
171
|
+
}
|
|
172
|
+
}
|
|
183
173
|
/**
|
|
184
174
|
* Funnel for lease granting: materialize-or-adopt the serve snapshot and grant
|
|
185
175
|
* leases for the served rows as-is. Caller-owned transaction: this must run
|
package/lib/tool-edit.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The dsh `edit` tool: hash-anchored literal range edits that shadow the
|
|
3
3
|
* built-in `edit` on the agent's own scope layer. Now the sole mutation tool
|
|
4
|
-
* (batch_edit removed, ADR-0007): payload is { file: string
|
|
5
|
-
* single-file atomic batch
|
|
4
|
+
* (batch_edit removed, ADR-0007): payload is { file: string, edits: [{anchor_from,anchor_to,replace_with},...] }
|
|
5
|
+
* single-file atomic batch; the file is named explicitly, never inferred (#117).
|
|
6
6
|
* @module dsh-better-edit/tool-edit
|
|
7
7
|
*/
|
|
8
8
|
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
@@ -10,41 +10,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";
|
|
13
|
-
import {
|
|
14
|
-
import { DomainError, formatError } from "./domain-errors.js";
|
|
13
|
+
import { DomainError } from "./domain-errors.js";
|
|
15
14
|
import { execCwd, execSessionKey } from "./workspace-context.js";
|
|
16
15
|
import { withWorkspace } from "./workspace-context.js";
|
|
17
|
-
import { findSnapshotPathsByHashes } from "./hash-store.js";
|
|
18
|
-
import { parseHashRef } from "./hashline/anchor-pipeline.js";
|
|
19
|
-
async function resolveNullPath(edits) {
|
|
20
|
-
if (edits.length === 0)
|
|
21
|
-
return undefined;
|
|
22
|
-
const first = edits[0];
|
|
23
|
-
try {
|
|
24
|
-
const h1 = parseHashRef(first.anchor_from).hash;
|
|
25
|
-
const h2 = parseHashRef(first.anchor_to).hash;
|
|
26
|
-
const matches = await findSnapshotPathsByHashes([h1, h2]);
|
|
27
|
-
if (matches.length === 1) {
|
|
28
|
-
return {
|
|
29
|
-
file: matches[0],
|
|
30
|
-
warning: formatError("E_BAD_PAYLOAD", {
|
|
31
|
-
message: `Autocorrected: missing "file" resolved to ${matches[0]} — the only file whose stored hashes contain both anchors.`,
|
|
32
|
-
}),
|
|
33
|
-
};
|
|
34
|
-
}
|
|
35
|
-
if (matches.length > 1) {
|
|
36
|
-
throw new DomainError("E_BAD_PAYLOAD", {
|
|
37
|
-
message: `Edit request requires a non-empty "file" string; the anchors match multiple known files: ${matches.join(", ")}. Include the intended file.`,
|
|
38
|
-
});
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
catch (e) {
|
|
42
|
-
if (codeOf(e) === "E_BAD_PAYLOAD")
|
|
43
|
-
throw e;
|
|
44
|
-
return undefined;
|
|
45
|
-
}
|
|
46
|
-
return undefined;
|
|
47
|
-
}
|
|
48
16
|
/**
|
|
49
17
|
* E_UNKNOWN producer: the edit tool boundary is where raw unexpected errors
|
|
50
18
|
* surface. DomainError members and aborts pass through untouched; anything else
|
|
@@ -69,8 +37,9 @@ export function buildEditTool(io, sandbox) {
|
|
|
69
37
|
file: {
|
|
70
38
|
oneOf: [
|
|
71
39
|
{ type: "string", description: "Text file to edit (a file, never a directory)" },
|
|
72
|
-
//
|
|
73
|
-
//
|
|
40
|
+
// #117: null stays wire-admissible so the domain rejects it with
|
|
41
|
+
// E_BAD_PAYLOAD; dsh would otherwise answer INVALID_ARGS before the
|
|
42
|
+
// contract runs. Undocumented and never inferable.
|
|
74
43
|
{ type: "null" },
|
|
75
44
|
],
|
|
76
45
|
},
|
|
@@ -111,22 +80,15 @@ export function buildEditTool(io, sandbox) {
|
|
|
111
80
|
const signal = exec.signal;
|
|
112
81
|
const canonical = normReq(args);
|
|
113
82
|
assertEditRequest(canonical);
|
|
83
|
+
// `assertEditRequest` narrows the raw args to the normalized contract.
|
|
114
84
|
const req = canonical;
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
}
|
|
123
|
-
else {
|
|
124
|
-
throw new DomainError("E_BAD_PAYLOAD", {
|
|
125
|
-
message: "Edit request file is null and could not be inferred from anchors — anchors match no known file. Include the intended file.",
|
|
126
|
-
});
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
const sandboxPolicy = await sandbox.resolvePolicy("edit", { file: resolvedFile, edits: req.edits }, exec);
|
|
85
|
+
// #117: a null/absent file is rejected at admission (assertEditRequest);
|
|
86
|
+
// the retired anchor-inference arm never resolves one here.
|
|
87
|
+
const resolvedFile = req.file;
|
|
88
|
+
const sandboxPolicy = await sandbox.resolvePolicy("edit",
|
|
89
|
+
// SAFETY: `resolvePolicy` reads only sandbox_permissions/justification;
|
|
90
|
+
// the file/edits fields are legacy context it ignores.
|
|
91
|
+
{ file: resolvedFile, edits: req.edits }, exec);
|
|
130
92
|
abortIf(signal);
|
|
131
93
|
const items = [];
|
|
132
94
|
for (let index = 0; index < req.edits.length; index++) {
|
|
@@ -138,7 +100,6 @@ export function buildEditTool(io, sandbox) {
|
|
|
138
100
|
anchor_from: e.anchor_from,
|
|
139
101
|
anchor_to: e.anchor_to,
|
|
140
102
|
replace_with: e.replace_with,
|
|
141
|
-
fileWarning: index === 0 ? fileWarning : undefined,
|
|
142
103
|
...(req.mode !== undefined ? { mode: req.mode } : {}),
|
|
143
104
|
});
|
|
144
105
|
}
|
|
@@ -23,7 +23,8 @@
|
|
|
23
23
|
*/
|
|
24
24
|
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
25
25
|
import { getAutoGuessFooter } from "./fs-bridge.js";
|
|
26
|
-
import { getEncodingState, invalidateIfStale, prepareForSave, recordOpenState, } from "./file-encoding-state.js";
|
|
26
|
+
import { encodingHintAtVersion, getEncodingState, invalidateIfStale, prepareForSave, recordOpenState, } from "./file-encoding-state.js";
|
|
27
|
+
import { loadConfig } from "./store-config.js";
|
|
27
28
|
import { stripBOM } from "./edit-diff.js";
|
|
28
29
|
import { renderTextWarning } from "./render-text-warning.js";
|
|
29
30
|
import { execCwd, withWorkspace } from "./workspace-context.js";
|
|
@@ -76,9 +77,17 @@ function requireViewRange(args) {
|
|
|
76
77
|
return [value[0], value[1]];
|
|
77
78
|
}
|
|
78
79
|
/**
|
|
79
|
-
* Strict read-first gate: the file must carry file encoding state recorded by
|
|
80
|
-
*
|
|
81
|
-
*
|
|
80
|
+
* Strict read-first gate: the file must carry file encoding state recorded by a
|
|
81
|
+
* prior `view`/`read` at the current version. Stale memos are invalidated first,
|
|
82
|
+
* so drifted files fail loud instead of editing blind.
|
|
83
|
+
*
|
|
84
|
+
* A successful write also refreshes the memo at the post-write version (the memo
|
|
85
|
+
* must describe the bytes actually written, #112), so the model's own write
|
|
86
|
+
* authorizes a follow-up non-anchored edit without a re-`view`. An EXTERNAL change
|
|
87
|
+
* still drifts the version and fails with E_BLIND_REPLACE.
|
|
88
|
+
*
|
|
89
|
+
* Never writes; returns the version it validated so the caller can reuse it as the
|
|
90
|
+
* decode-hint guard instead of stat'ing twice.
|
|
82
91
|
*/
|
|
83
92
|
async function requireObserved(io, absolutePath, displayPath, signal) {
|
|
84
93
|
const version = await io.statVersion(absolutePath, signal);
|
|
@@ -86,6 +95,7 @@ async function requireObserved(io, absolutePath, displayPath, signal) {
|
|
|
86
95
|
if (!getEncodingState(absolutePath)) {
|
|
87
96
|
throw new DomainError("E_BLIND_REPLACE", { path: displayPath, command: "str_replace_editor" });
|
|
88
97
|
}
|
|
98
|
+
return version;
|
|
89
99
|
}
|
|
90
100
|
/**
|
|
91
101
|
* Governed save: resolve the per-call sandbox policy — the session's standing
|
|
@@ -125,7 +135,12 @@ function countOccurrences(haystack, needle) {
|
|
|
125
135
|
* Replaces the former local `restoreBom` so the shadow can't diverge from
|
|
126
136
|
* the file-encoding-state round-trip (report #2). */
|
|
127
137
|
function restoreForSave(content, absolutePath) {
|
|
128
|
-
|
|
138
|
+
// Throws E_ENCODING_UNWRITABLE before the write when the recorded encoding
|
|
139
|
+
// cannot round-trip through the text-only seam (issue #112).
|
|
140
|
+
return prepareForSave(content, getEncodingState(absolutePath), {
|
|
141
|
+
normalizeToUtf8: loadConfig().normalizeToUtf8,
|
|
142
|
+
displayPath: absolutePath,
|
|
143
|
+
}).textToWrite;
|
|
129
144
|
}
|
|
130
145
|
function autoGuessWarning(absolutePath, rawPath) {
|
|
131
146
|
return (getAutoGuessFooter(absolutePath) ??
|
|
@@ -148,6 +163,7 @@ export function buildStrReplaceEditorTool(io, sandbox) {
|
|
|
148
163
|
required: true,
|
|
149
164
|
description: "File path",
|
|
150
165
|
},
|
|
166
|
+
// SAFETY: the value-schema DSL types `json` loosely; the tool validates the shape at admission.
|
|
151
167
|
view_range: {
|
|
152
168
|
type: "json",
|
|
153
169
|
description: "[start, end] 1-indexed inclusive line range for view",
|
|
@@ -195,7 +211,11 @@ export function buildStrReplaceEditorTool(io, sandbox) {
|
|
|
195
211
|
abortIf(signal);
|
|
196
212
|
const absolutePath = await io.resolve(rawPath, cwd, signal);
|
|
197
213
|
if (cmd === "view") {
|
|
198
|
-
|
|
214
|
+
// Issue #112: consume the encoding recorded by read({ encoding }) so a
|
|
215
|
+
// re-view decodes the same text instead of re-detecting (or failing).
|
|
216
|
+
const viewVersion = await io.statVersion(absolutePath, signal);
|
|
217
|
+
const viewHint = encodingHintAtVersion(absolutePath, viewVersion);
|
|
218
|
+
const text = await io.readText(absolutePath, signal, viewHint);
|
|
199
219
|
// Observation only: encoding state is recorded by readText;
|
|
200
220
|
// served state is never touched here.
|
|
201
221
|
// NOTE (report #10): the readText + emitObserved pair costs two
|
|
@@ -255,8 +275,11 @@ export function buildStrReplaceEditorTool(io, sandbox) {
|
|
|
255
275
|
// an edit on drifted bytes. Returning the version from readText would
|
|
256
276
|
// need a FileIO contract break for an unmeasured hot-path nit; same
|
|
257
277
|
// pattern as the view double-RPC above, so documented, not collapsed.
|
|
258
|
-
await requireObserved(io, absolutePath, rawPath, signal);
|
|
259
|
-
|
|
278
|
+
const guardedVersion = await requireObserved(io, absolutePath, rawPath, signal);
|
|
279
|
+
// Issue #112: the mutating read consumes the encoding recorded by
|
|
280
|
+
// read({ encoding }), version-guarded by requireObserved just above.
|
|
281
|
+
const encodingHint = encodingHintAtVersion(absolutePath, guardedVersion);
|
|
282
|
+
const current = await io.readText(absolutePath, signal, encodingHint);
|
|
260
283
|
if (cmd === "str_replace") {
|
|
261
284
|
const oldStr = requireString(rec, "old_str");
|
|
262
285
|
if (!("new_str" in rec) || typeof rec["new_str"] !== "string") {
|
package/lib/tool-undo.js
CHANGED
|
@@ -15,10 +15,12 @@ import { AnchorSpaceExhaustedError, HASH_SPACE, canon, contentChecksum, } from "
|
|
|
15
15
|
import { lineHashes } from "./hashline/hash.js";
|
|
16
16
|
import { changedRange } from "./hashline/anchor-pipeline.js";
|
|
17
17
|
import { getUndo, clearUndo } from "./undo-edit.js";
|
|
18
|
-
import { loadAnchorReservations, loadServedStore, recordServedTruncated, retireAnchorsInStore, } from "./session-view.js";
|
|
18
|
+
import { loadAnchorReservations, loadServedStore, recordServedTruncated, retireAnchorsInStore, unretireAnchorsInStore, } from "./session-view.js";
|
|
19
19
|
import { UNDO_DESCRIPTION } from "./prompts.js";
|
|
20
20
|
import { execCwd, execSessionKey } from "./workspace-context.js";
|
|
21
21
|
import { withWorkspace } from "./workspace-context.js";
|
|
22
|
+
import { encodingHintAtVersion, getEncodingState, prepareForSave } from "./file-encoding-state.js";
|
|
23
|
+
import { loadConfig } from "./store-config.js";
|
|
22
24
|
function isAnchorSpaceExhausted(e) {
|
|
23
25
|
return (e instanceof AnchorSpaceExhaustedError ||
|
|
24
26
|
(e instanceof Error && e.message.includes("probing failed over")));
|
|
@@ -86,7 +88,12 @@ export function buildUndoTool(io, sandbox) {
|
|
|
86
88
|
}
|
|
87
89
|
let currentRaw;
|
|
88
90
|
try {
|
|
89
|
-
|
|
91
|
+
// Issue #112: the staleness read consumes the encoding recorded by the preceding
|
|
92
|
+
// read, so a file admitted by read({ encoding }) compares as decoded text instead
|
|
93
|
+
// of mojibake (which would misreport a false E_UNDO_STALE "modified").
|
|
94
|
+
const currentVersion = await io.statVersion(absolutePath, signal);
|
|
95
|
+
const encodingHint = encodingHintAtVersion(absolutePath, currentVersion);
|
|
96
|
+
currentRaw = await io.readText(absolutePath, signal, encodingHint);
|
|
90
97
|
}
|
|
91
98
|
catch (error) {
|
|
92
99
|
if (codeOf(error) === "E_NOT_FOUND") {
|
|
@@ -129,12 +136,13 @@ export function buildUndoTool(io, sandbox) {
|
|
|
129
136
|
reservedHashes = served;
|
|
130
137
|
};
|
|
131
138
|
const currentHashes = await hashWithAnchorSpacePromotion(() => lineHashes(currentNormalized, absolutePath, undefined, undefined, false, reservedHashes, retiredHashes), promoteRetiredForAnchorSpace);
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
139
|
+
// Restore the pre-edit assignment verbatim (ADR-0017 reversal): `undo.hashes` are
|
|
140
|
+
// the anchors the restored content carried before the edit, and `undo.content` is
|
|
141
|
+
// byte-identical to the content they were assigned to. The edit retired them; that
|
|
142
|
+
// retirement is reversed with the restore below, so the pass no longer lists them
|
|
143
|
+
// as removed. What still blocks reuse is the superseded post-edit assignment
|
|
144
|
+
// (`currentHashes`, live on the file right now) plus this session's reserved set.
|
|
145
|
+
const restoredHashes = await hashWithAnchorSpacePromotion(() => lineHashes(undo.content, absolutePath, { content: undo.content, hashes: undo.hashes }, undefined, false, new Set([...reservedHashes, ...currentHashes]), retiredHashes), promoteRetiredForAnchorSpace);
|
|
138
146
|
// WHY: #96 (pi-better-edit@665a05d, upstream #173) — the summary counts come from the
|
|
139
147
|
// WHY: source line multisets, never from the rendered projection: a deleted run past
|
|
140
148
|
// WHY: DIFF_REMOVED_CAP collapses behind a marker row at context 0, so counting `-` rows
|
|
@@ -164,12 +172,29 @@ export function buildUndoTool(io, sandbox) {
|
|
|
164
172
|
}
|
|
165
173
|
const restoredRange = changedRange(currentNormalized, undo.content);
|
|
166
174
|
const restoredSet = new Set(restoredHashes);
|
|
175
|
+
// Retirement moves with the restore: the anchors the edit retired for lines that come
|
|
176
|
+
// back byte-identically are revived in the same unit that retires the superseded
|
|
177
|
+
// post-edit assignment. An anchor whose line does not come back stays retired, and no
|
|
178
|
+
// anchor is rebound to different content — the restore is byte-identical or refused.
|
|
179
|
+
const revivedByUndo = [...restoredSet].filter((hash) => retiredHashes.has(hash));
|
|
167
180
|
// WHY (#98, port of upstream CAND-3): retirement waits for the write. Committing it
|
|
168
181
|
// before `writeText` let a failed revert leave anchors retired for a file that still
|
|
169
182
|
// holds them — a torn store state with no later read likely to notice.
|
|
170
183
|
const retiredByUndo = currentHashes.filter((hash) => !restoredSet.has(hash));
|
|
184
|
+
// The revert goes through the same save seam as every other write, so an
|
|
185
|
+
// encoding that cannot round-trip refuses BEFORE any write (#112).
|
|
186
|
+
const recorded = getEncodingState(absolutePath) ?? {
|
|
187
|
+
encoding: undo.bom ? "utf8bom" : "utf8",
|
|
188
|
+
hasBOM: undo.bom !== "",
|
|
189
|
+
lineEnding: undo.originalEnding,
|
|
190
|
+
version: undefined,
|
|
191
|
+
};
|
|
192
|
+
const prepared = prepareForSave(undo.content, recorded, {
|
|
193
|
+
normalizeToUtf8: loadConfig().normalizeToUtf8,
|
|
194
|
+
displayPath: path,
|
|
195
|
+
});
|
|
171
196
|
try {
|
|
172
|
-
await io.writeText(absolutePath,
|
|
197
|
+
await io.writeText(absolutePath, prepared.textToWrite, signal, exec, sandboxPolicy);
|
|
173
198
|
}
|
|
174
199
|
catch (error) {
|
|
175
200
|
throw sandbox.mapError(error, sandboxPolicy);
|
|
@@ -189,6 +214,7 @@ export function buildUndoTool(io, sandbox) {
|
|
|
189
214
|
withStore(() => {
|
|
190
215
|
store.upsertSnapshot(absolutePath, contentChecksum(undo.content), splitLines(undo.content).length, restoredHashes, undo.content);
|
|
191
216
|
retireAnchorsInStore(store, sessionKey, absolutePath, retiredByUndo);
|
|
217
|
+
unretireAnchorsInStore(store, sessionKey, absolutePath, revivedByUndo);
|
|
192
218
|
store.deleteUndoPair(absolutePath);
|
|
193
219
|
});
|
|
194
220
|
}
|
|
@@ -209,8 +235,8 @@ export function buildUndoTool(io, sandbox) {
|
|
|
209
235
|
serveLanded = await recordServedTruncated(sessionKey, absolutePath, undoDenseRows, splitLines(undo.content).length, restoredRange?.firstChangedLine ?? undoDiffResult.firstChangedLine ?? 0, splitLines(undo.content).map((l) => canon(l)), { content: undo.content, hashes: restoredHashes });
|
|
210
236
|
}
|
|
211
237
|
parts.push(serveLanded
|
|
212
|
-
? "File reverted to previous state. The post-edit diff rows carry the restored file\u2019s
|
|
213
|
-
: "File reverted to previous state. WARNING: the restored file\u2019s
|
|
238
|
+
? "File reverted to previous state. The post-edit diff rows carry the restored file\u2019s original anchors for follow-up edits."
|
|
239
|
+
: "File reverted to previous state. WARNING: the restored file\u2019s original anchors were NOT recorded as served — the diff rows below are NOT usable anchors and no edit can be based on them. Re-read the file before editing it.");
|
|
214
240
|
return [parts.join("\n"), "", "Diff of the revert:", "", undoDiff].join("\n");
|
|
215
241
|
});
|
|
216
242
|
},
|
package/lib/types/contract.d.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* declared once here; every tool validates through these asserts, and the
|
|
5
5
|
* E_BAD_PAYLOAD vocabulary is shared instead of re-implemented per tool.
|
|
6
6
|
*
|
|
7
|
-
* Contract mirrors upstream ADR-0015: {file: string
|
|
7
|
+
* Contract mirrors upstream ADR-0015: {file: string, edits: [{anchor_from, anchor_to, replace_with},...]} named-object payload
|
|
8
8
|
* (plus legacy tuple items and legacy key spellings folded pre-validation), single-file, atomic. batch_edit is removed.
|
|
9
9
|
* @module dsh-better-edit/contract
|
|
10
10
|
*/
|
|
@@ -16,7 +16,7 @@ export type EditItem = {
|
|
|
16
16
|
replace_with: string;
|
|
17
17
|
};
|
|
18
18
|
export type EditRequest = {
|
|
19
|
-
file: string
|
|
19
|
+
file: string;
|
|
20
20
|
edits: EditItem[];
|
|
21
21
|
/**
|
|
22
22
|
* "general" (default) refuses bytes reproducing served rows;
|
|
@@ -89,17 +89,12 @@ export declare const anchorToSchema: {
|
|
|
89
89
|
};
|
|
90
90
|
export declare const pathSchema: {
|
|
91
91
|
readonly type: "string";
|
|
92
|
-
readonly description: "File path
|
|
92
|
+
readonly description: "File path";
|
|
93
93
|
};
|
|
94
94
|
export declare const editPathSchema: {
|
|
95
|
-
readonly
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
readonly description: "File path; null infers it from anchors";
|
|
99
|
-
}, {
|
|
100
|
-
readonly type: "null";
|
|
101
|
-
readonly description: "null infers path from anchors";
|
|
102
|
-
}];
|
|
95
|
+
readonly type: "string";
|
|
96
|
+
readonly minLength: 1;
|
|
97
|
+
readonly description: "Text file to edit (a file, never a directory)";
|
|
103
98
|
};
|
|
104
99
|
export declare const editTupleSchema: {
|
|
105
100
|
readonly type: "array";
|
|
@@ -181,14 +176,9 @@ export declare const editToolSchema: {
|
|
|
181
176
|
readonly required: readonly ["file", "edits"];
|
|
182
177
|
readonly properties: {
|
|
183
178
|
readonly file: {
|
|
184
|
-
readonly
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
readonly description: "File path; null infers it from anchors";
|
|
188
|
-
}, {
|
|
189
|
-
readonly type: "null";
|
|
190
|
-
readonly description: "null infers path from anchors";
|
|
191
|
-
}];
|
|
179
|
+
readonly type: "string";
|
|
180
|
+
readonly minLength: 1;
|
|
181
|
+
readonly description: "Text file to edit (a file, never a directory)";
|
|
192
182
|
};
|
|
193
183
|
readonly edits: {
|
|
194
184
|
readonly type: "array";
|
|
@@ -66,7 +66,7 @@ export interface ServedRow {
|
|
|
66
66
|
}
|
|
67
67
|
/** WHY: user-facing diagnosis carried as `details.cause` on range-family rejections. */
|
|
68
68
|
export type RangeCause = "retirement" | "never-served" | "served-range staleness" | "anchor staleness" | "served span";
|
|
69
|
-
export type DomainErrorCode = "E_BAD_PAYLOAD" | "E_EMPTY_RANGE" | "E_STALE_ANCHOR" | "E_UNKNOWN_ANCHOR" | "E_FOREIGN_ANCHOR" | "E_STALE_RANGE" | "E_TARGET_LOST" | "E_UNVERIFIED_RANGE" | "E_MALFORMED_ANCHOR" | "E_SUSPICIOUS_TEXT" | "E_BATCH_ABORT" | "E_NOOP_LOOP" | "E_UNSUPPORTED_FILE" | "E_ACCESS" | "E_NOT_FOUND" | "E_UNDO_STALE" | "E_UNDO_UNAVAILABLE" | "E_UNDO_NOT_RECORDED" | "E_UNKNOWN" | "E_LARGE_FILE" | "E_UNSERVED_RANGE" | "E_BLIND_REPLACE" | "E_UNSUPPORTED" | "E_BAD_COMMAND" | "E_FILE_EXISTS" | "E_NO_MATCH" | "E_AMBIGUOUS_MATCH" | "E_STORE_NEWER_VERSION";
|
|
69
|
+
export type DomainErrorCode = "E_BAD_PAYLOAD" | "E_EMPTY_RANGE" | "E_STALE_ANCHOR" | "E_UNKNOWN_ANCHOR" | "E_FOREIGN_ANCHOR" | "E_STALE_RANGE" | "E_TARGET_LOST" | "E_UNVERIFIED_RANGE" | "E_MALFORMED_ANCHOR" | "E_SUSPICIOUS_TEXT" | "E_BATCH_ABORT" | "E_NOOP_LOOP" | "E_UNSUPPORTED_FILE" | "E_ENCODING_UNWRITABLE" | "E_ACCESS" | "E_NOT_FOUND" | "E_UNDO_STALE" | "E_UNDO_UNAVAILABLE" | "E_UNDO_NOT_RECORDED" | "E_UNKNOWN" | "E_LARGE_FILE" | "E_UNSERVED_RANGE" | "E_BLIND_REPLACE" | "E_UNSUPPORTED" | "E_BAD_COMMAND" | "E_FILE_EXISTS" | "E_NO_MATCH" | "E_AMBIGUOUS_MATCH" | "E_STORE_NEWER_VERSION";
|
|
70
70
|
/**
|
|
71
71
|
* Applied-tier warning codes. A `[W_*]` line reports an applied mutation;
|
|
72
72
|
* `[E_*]` reports a rejection. `formatWarning` is the sole producer of
|
|
@@ -177,6 +177,11 @@ export interface ErrorPayloadMap {
|
|
|
177
177
|
kind: "directory" | "binary" | "image";
|
|
178
178
|
description?: string;
|
|
179
179
|
};
|
|
180
|
+
E_ENCODING_UNWRITABLE: {
|
|
181
|
+
path: string;
|
|
182
|
+
/** The encoding recorded when the file was read. */
|
|
183
|
+
encoding: string;
|
|
184
|
+
};
|
|
180
185
|
E_ACCESS: {
|
|
181
186
|
path: string;
|
|
182
187
|
kind: "denied" | "symlink-loop" | "unreachable";
|
|
@@ -16,6 +16,23 @@
|
|
|
16
16
|
*/
|
|
17
17
|
import type { CandidatePreview } from "./encoding.js";
|
|
18
18
|
import { type LineEnding } from "./edit-diff.js";
|
|
19
|
+
/**
|
|
20
|
+
* The decode hint a mutating re-read must pass to the byte seam: the encoding
|
|
21
|
+
* recorded by the preceding `read({ encoding })` — but only while the memo still
|
|
22
|
+
* matches the on-disk version, and only for encodings the plain read path cannot
|
|
23
|
+
* reproduce.
|
|
24
|
+
*
|
|
25
|
+
* `utf8` / `utf8bom` need no hint: BOM sniff + strict UTF-8 (and the bridge's
|
|
26
|
+
* stripped-BOM restore) already decode them to the text the anchors were served
|
|
27
|
+
* for, so asking for a byte reread would only cost an RPC. Everything else
|
|
28
|
+
* (utf16le, windows-1251, GBK, …) is invisible to the plain path — without the
|
|
29
|
+
* hint the mutation re-read decodes lossily or fails, which is the stale-anchor /
|
|
30
|
+
* unsupported-file symptom this hint removes (issue #112).
|
|
31
|
+
*
|
|
32
|
+
* A drifted memo is dropped first, so a changed file is re-detected instead of
|
|
33
|
+
* having the old encoding laundered onto its new bytes.
|
|
34
|
+
*/
|
|
35
|
+
export declare function encodingHintAtVersion(targetKey: string, currentVersion: string | undefined): string | undefined;
|
|
19
36
|
export interface FileEncodingState {
|
|
20
37
|
encoding: string;
|
|
21
38
|
hasBOM: boolean;
|
|
@@ -64,16 +81,36 @@ export interface EncodeForSaveOptions {
|
|
|
64
81
|
encodingHint?: string;
|
|
65
82
|
normalizeToUtf8?: boolean;
|
|
66
83
|
currentVersion?: string | undefined;
|
|
84
|
+
/** Model-facing path for the round-trip refusal. */
|
|
85
|
+
displayPath?: string;
|
|
67
86
|
}
|
|
68
87
|
/** Shared UTF-8 BOM marker — single source for the BOM round-trip seam.
|
|
69
88
|
* Prefer `prepareForSave` / `stripBOM` over re-implementing this check. */
|
|
70
89
|
export declare const UTF8_BOM = "\uFEFF";
|
|
71
90
|
/**
|
|
72
|
-
*
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
*
|
|
91
|
+
* True when the text's UTF-8 byte image is byte-identical to its byte image
|
|
92
|
+
* under `encoding` — an ASCII-only file in a single-byte charset, where the
|
|
93
|
+
* text-only write seam reproduces the original bytes exactly. Checking bytes
|
|
94
|
+
* (not the encoding name) is what keeps that file editable.
|
|
95
|
+
*
|
|
96
|
+
* This is a property of the TEXT only. A recorded `hasBOM` is a property of the
|
|
97
|
+
* FILE and is checked separately at the call site: the legacy BOM bytes cannot be
|
|
98
|
+
* reproduced by a UTF-8 string write (a UTF-8 BOM is a different byte image).
|
|
99
|
+
*/
|
|
100
|
+
export declare function isByteFaithfulAsUtf8(text: string, encoding: string): boolean;
|
|
101
|
+
/**
|
|
102
|
+
* Decide what bytes (as text, since the write seam takes a string) to write and
|
|
103
|
+
* what new state to record. BOM and lineEnding are restored here when a state
|
|
104
|
+
* exists; otherwise defaults are UTF-8 without BOM and LF.
|
|
105
|
+
*
|
|
106
|
+
* ROUND-TRIP VERDICT: the bridge's only write is `writeText(target, content:
|
|
107
|
+
* string, …)`, which every backend encodes as UTF-8. So the save side can
|
|
108
|
+
* restore BOM + line ending for the UTF-8 family, and can write a legacy file
|
|
109
|
+
* only when its UTF-8 byte image is identical (ASCII-only). Anything else
|
|
110
|
+
* throws `E_ENCODING_UNWRITABLE` BEFORE the write, because writing UTF-8 would
|
|
111
|
+
* silently transcode the file and leave the anchors describing other bytes.
|
|
112
|
+
* `normalizeToUtf8: true` is the explicit migration: write UTF-8 and record
|
|
113
|
+
* `utf8` so the next read agrees with the bytes.
|
|
77
114
|
*/
|
|
78
115
|
export declare function prepareForSave(content: string, existingState: FileEncodingState | undefined, opts?: EncodeForSaveOptions): {
|
|
79
116
|
textToWrite: string;
|
package/lib/types/fs-bridge.d.ts
CHANGED
|
@@ -57,7 +57,6 @@ export interface FileIO {
|
|
|
57
57
|
* @returns the mapped error, rethrown.
|
|
58
58
|
*/
|
|
59
59
|
export declare function mapFsError(error: unknown, displayPath: string): never;
|
|
60
|
-
/** FileIO over the deployment's `ctx.fs` service. */
|
|
61
60
|
export declare function ctxFsIO(fs: FileSystem, ctx: Context): FileIO;
|
|
62
61
|
/** FileIO over the host filesystem directly (tests, previews, fallback). */
|
|
63
62
|
export declare function localIO(): FileIO;
|
|
@@ -24,7 +24,6 @@ export interface PreparedItem {
|
|
|
24
24
|
anchor_from: string;
|
|
25
25
|
anchor_to: string;
|
|
26
26
|
replace_with: string;
|
|
27
|
-
fileWarning?: string;
|
|
28
27
|
/** Request-level edit mode ("general" default, "literal" bypasses served-echo). */
|
|
29
28
|
mode?: EditMode;
|
|
30
29
|
}
|
|
@@ -51,15 +50,6 @@ export interface FileEditResult {
|
|
|
51
50
|
newlyRetired: string[];
|
|
52
51
|
range: ResolvedRange;
|
|
53
52
|
}
|
|
54
|
-
/**
|
|
55
|
-
* Resolve a request's missing `path` from its anchors: the only file whose
|
|
56
|
-
* stored hashes contain both anchors. Returns the path plus an autocorrect
|
|
57
|
-
* warning, or undefined when no resolution is possible.
|
|
58
|
-
*/
|
|
59
|
-
export declare function resolveMissingPath(request: Record<string, unknown>): Promise<{
|
|
60
|
-
path: string;
|
|
61
|
-
warning: string;
|
|
62
|
-
} | undefined>;
|
|
63
53
|
/** The hashes a range edit removes, for stable re-hash bookkeeping. */
|
|
64
54
|
export declare function collectRemovedHashes(edit: HEdit, originalHashes: string[]): Set<string>;
|
|
65
55
|
/** Added/removed line counts for one resolved edit against a file's original hashes. */
|
package/lib/types/mutation.d.ts
CHANGED
|
@@ -29,7 +29,7 @@ import type { SandboxExecutionPolicy } from "@deepseek-ai/dsh-sandbox";
|
|
|
29
29
|
import type { FsSandboxController } from "./sandbox.js";
|
|
30
30
|
import type { LineEnding } from "./edit-diff.js";
|
|
31
31
|
import { scanDrift } from "./session-view.js";
|
|
32
|
-
import { runFileEdits
|
|
32
|
+
import { runFileEdits } from "./mutation/engine.js";
|
|
33
33
|
import type { FileEditResult, PreparedItem } from "./mutation/engine.js";
|
|
34
34
|
import { restoreEndings } from "./edit-diff.js";
|
|
35
35
|
import { buildMetrics, buildNoop, buildChanged, buildBatchResult } from "./edit-response.js";
|
|
@@ -41,7 +41,7 @@ import { trackNoopPayload, clearNoopLoop, noopPayloadKey } from "./noop-guard.js
|
|
|
41
41
|
export declare function resolveDisplayPath(path: string, cwd: string): string;
|
|
42
42
|
/** Snapshot bookkeeping for noop/success results (best-effort). */
|
|
43
43
|
export declare function snapshotIdFor(io: FileIO, absolutePath: string, signal?: AbortSignal): Promise<string | undefined>;
|
|
44
|
-
export { runFileEdits
|
|
44
|
+
export { runFileEdits };
|
|
45
45
|
export { persistUndoAndWrite };
|
|
46
46
|
export type { FileEditResult, PreparedItem };
|
|
47
47
|
export { buildMetrics, buildNoop, buildChanged, buildBatchResult };
|
|
@@ -77,7 +77,7 @@ declare function commitBatch(opts: Omit<PersistWriteOptions, "restoreUnwrittenUn
|
|
|
77
77
|
* Owns: applySequence → branch (single/multi × noop/applied) → commit →
|
|
78
78
|
* buildBatchResult → recordServedTruncated → return text.
|
|
79
79
|
*
|
|
80
|
-
* The tool layer (adapter) only validates and
|
|
80
|
+
* The tool layer (adapter) only validates and delegates; all
|
|
81
81
|
* lifecycle branching concentrates here (locality). One interface serves N
|
|
82
82
|
* call sites (leverage). Deleting this module would scatter the lifecycle
|
|
83
83
|
* across every tool — it concentrates (deep).
|