dsh-better-edit 0.2.2 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/README.md +317 -240
- package/README.zh.md +19 -11
- package/lib/constants.js +3 -1
- package/lib/contract.js +159 -63
- package/lib/drift.js +5 -98
- package/lib/dsh-context.js +2 -24
- package/lib/edit-engine.js +9 -8
- package/lib/edit-pipeline.js +3 -121
- package/lib/edit-response.js +16 -8
- package/lib/file-kind.js +6 -121
- package/lib/file-reader.js +4 -77
- package/lib/file-view.js +486 -0
- package/lib/guidance/index.js +8 -0
- package/lib/guidance/materialize.js +212 -0
- package/lib/guidance/parse.js +80 -0
- package/lib/guidance/resolve.js +116 -0
- package/lib/guidance.js +6 -388
- package/lib/hash-store.js +6 -4
- package/lib/hashline/alphabet.js +2 -6
- package/lib/hashline/anchor-pipeline.js +786 -0
- package/lib/hashline/apply.js +2 -223
- package/lib/hashline/hash-assign.js +255 -0
- package/lib/hashline/hash.js +67 -29
- package/lib/hashline/hasher.js +2 -23
- package/lib/hashline/index.js +9 -4
- package/lib/hashline/parse.js +2 -35
- package/lib/hashline/pure.js +2 -213
- package/lib/hashline/resolve.js +3 -361
- package/lib/hashline/served.js +2 -120
- package/lib/index.js +1 -3
- package/lib/mutation.js +266 -0
- package/lib/noop-guard.js +20 -0
- package/lib/preview-controller.js +65 -0
- package/lib/prompts.js +14 -20
- package/lib/read-and-serve.js +23 -23
- package/lib/read-render.js +3 -139
- package/lib/served-store.js +2 -216
- package/lib/session-view.js +332 -0
- package/lib/tool-batch-edit.js +9 -10
- package/lib/tool-edit.js +73 -129
- package/lib/tool-read.js +3 -5
- package/lib/tool-undo.js +16 -10
- package/lib/truncate.js +3 -95
- package/lib/types/constants.d.ts +2 -0
- package/lib/types/contract.d.ts +120 -15
- package/lib/types/drift.d.ts +5 -29
- package/lib/types/dsh-context.d.ts +2 -20
- package/lib/types/edit-engine.d.ts +2 -2
- package/lib/types/edit-pipeline.d.ts +3 -44
- package/lib/types/file-kind.d.ts +6 -18
- package/lib/types/file-reader.d.ts +4 -45
- package/lib/types/file-view.d.ts +139 -0
- package/lib/types/guidance/index.d.ts +8 -0
- package/lib/types/guidance/materialize.d.ts +23 -0
- package/lib/types/guidance/parse.d.ts +36 -0
- package/lib/types/guidance/resolve.d.ts +55 -0
- package/lib/types/guidance.d.ts +6 -127
- package/lib/types/hashline/alphabet.d.ts +1 -5
- package/lib/types/hashline/anchor-pipeline.d.ts +127 -0
- package/lib/types/hashline/apply.d.ts +1 -22
- package/lib/types/hashline/hash-assign.d.ts +25 -0
- package/lib/types/hashline/hash.d.ts +8 -9
- package/lib/types/hashline/hasher.d.ts +1 -8
- package/lib/types/hashline/index.d.ts +12 -4
- package/lib/types/hashline/parse.d.ts +1 -7
- package/lib/types/hashline/pure.d.ts +1 -26
- package/lib/types/hashline/resolve.d.ts +1 -58
- package/lib/types/hashline/served.d.ts +1 -43
- package/lib/types/mutation.d.ts +131 -0
- package/lib/types/noop-guard.d.ts +29 -0
- package/lib/types/preview-controller.d.ts +33 -0
- package/lib/types/prompts.d.ts +9 -9
- package/lib/types/read-and-serve.d.ts +6 -5
- package/lib/types/read-render.d.ts +3 -18
- package/lib/types/served-store.d.ts +2 -81
- package/lib/types/session-view.d.ts +92 -0
- package/lib/types/tool-edit.d.ts +3 -14
- package/lib/types/truncate.d.ts +3 -29
- package/lib/types/validation.d.ts +6 -7
- package/lib/types/workspace.d.ts +2 -21
- package/lib/validation.js +6 -33
- package/lib/workspace.js +2 -27
- package/lib/write-hook.js +2 -2
- package/package.json +2 -2
package/lib/hashline/served.js
CHANGED
|
@@ -1,120 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
import { SERVED_ECHO_CAP } from "../constants.js";
|
|
4
|
-
export class ServedRejectionError extends Error {
|
|
5
|
-
code;
|
|
6
|
-
firstOffendingLine;
|
|
7
|
-
servedRows;
|
|
8
|
-
constructor(opts) {
|
|
9
|
-
super(opts.message);
|
|
10
|
-
this.name = "ServedRejectionError";
|
|
11
|
-
this.code = opts.code;
|
|
12
|
-
this.firstOffendingLine = opts.firstOffendingLine;
|
|
13
|
-
this.servedRows = opts.servedRows;
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
export function isServedRejection(error) {
|
|
17
|
-
return error instanceof ServedRejectionError;
|
|
18
|
-
}
|
|
19
|
-
export class AnchorMismatchError extends Error {
|
|
20
|
-
servedRows;
|
|
21
|
-
constructor(message, servedRows) {
|
|
22
|
-
super(message);
|
|
23
|
-
this.name = "AnchorMismatchError";
|
|
24
|
-
this.servedRows = servedRows;
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
export function isAnchorMismatch(error) {
|
|
28
|
-
return error instanceof AnchorMismatchError;
|
|
29
|
-
}
|
|
30
|
-
export function buildRangeEcho(startLine, endLine, fileHashes) {
|
|
31
|
-
const total = endLine - startLine + 1;
|
|
32
|
-
const shown = Math.min(total, SERVED_ECHO_CAP);
|
|
33
|
-
const rows = [];
|
|
34
|
-
for (let ln = startLine; ln < startLine + shown; ln++) {
|
|
35
|
-
rows.push({ position: ln - 1, hash: fileHashes[ln - 1] });
|
|
36
|
-
}
|
|
37
|
-
return rows;
|
|
38
|
-
}
|
|
39
|
-
export function fmtServedRows(rows, fileLines) {
|
|
40
|
-
return rows
|
|
41
|
-
.map((row) => `${row.hash}${HASH_SEP}${fileLines[row.position] ?? ""}`)
|
|
42
|
-
.join("\n");
|
|
43
|
-
}
|
|
44
|
-
function retryHint() {
|
|
45
|
-
return "Retry the edit with remove_from/remove_to copied from these fresh rows (no read needed).";
|
|
46
|
-
}
|
|
47
|
-
function paginationHint(nextOffset, more) {
|
|
48
|
-
return `[... ${more} more lines — use read with offset=${nextOffset} to see the rest]`;
|
|
49
|
-
}
|
|
50
|
-
export function verifyServedRange(args) {
|
|
51
|
-
const { served, startHash, endHash, startLine, endLine, fileHashes, fileLines, filePath, } = args;
|
|
52
|
-
const where = filePath ? ` in ${filePath}` : "";
|
|
53
|
-
const echoRows = buildRangeEcho(startLine, endLine, fileHashes);
|
|
54
|
-
const totalLen = endLine - startLine + 1;
|
|
55
|
-
const tail = echoRows.length < totalLen
|
|
56
|
-
? `\n${paginationHint(startLine + echoRows.length, totalLen - echoRows.length)}`
|
|
57
|
-
: "";
|
|
58
|
-
const echo = fmtServedRows(echoRows, fileLines) + tail;
|
|
59
|
-
const startPositions = servedPositionsOf(served, startHash);
|
|
60
|
-
const endPositions = servedPositionsOf(served, endHash);
|
|
61
|
-
if (startPositions.length !== 1 || endPositions.length !== 1) {
|
|
62
|
-
const problems = [];
|
|
63
|
-
if (startPositions.length === 0) {
|
|
64
|
-
problems.push(`remove_from "${startHash}" has no served position`);
|
|
65
|
-
}
|
|
66
|
-
else if (startPositions.length > 1) {
|
|
67
|
-
problems.push(`remove_from "${startHash}" was served at ${startPositions.length} positions`);
|
|
68
|
-
}
|
|
69
|
-
if (endPositions.length === 0) {
|
|
70
|
-
problems.push(`remove_to "${endHash}" has no served position`);
|
|
71
|
-
}
|
|
72
|
-
else if (endPositions.length > 1) {
|
|
73
|
-
problems.push(`remove_to "${endHash}" was served at ${endPositions.length} positions`);
|
|
74
|
-
}
|
|
75
|
-
throw new ServedRejectionError({
|
|
76
|
-
code: "E_RANGE_UNVERIFIED",
|
|
77
|
-
message: `[E_RANGE_UNVERIFIED] Cannot verify the range against served state${where}: ${problems.join("; ")}. ` +
|
|
78
|
-
`The tool only verifies what it delivered to the model's context; a boundary anchor that cannot be verified is never guessed at. Current range:\n${echo}\n${retryHint()}`,
|
|
79
|
-
servedRows: echoRows,
|
|
80
|
-
});
|
|
81
|
-
}
|
|
82
|
-
const from = Math.min(startPositions[0], endPositions[0]);
|
|
83
|
-
const to = Math.max(startPositions[0], endPositions[0]);
|
|
84
|
-
for (let i = from; i <= to; i++) {
|
|
85
|
-
if (served[i] === null) {
|
|
86
|
-
throw new ServedRejectionError({
|
|
87
|
-
code: "E_RANGE_UNSERVED",
|
|
88
|
-
message: `[E_RANGE_UNSERVED] Line ${i + 1}${where} was never served to the model — the range includes lines the model has not seen. Current range:\n${echo}\n${retryHint()}`,
|
|
89
|
-
firstOffendingLine: i + 1,
|
|
90
|
-
servedRows: echoRows,
|
|
91
|
-
});
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
const servedLen = to - from + 1;
|
|
95
|
-
const currentLen = endLine - startLine + 1;
|
|
96
|
-
if (servedLen !== currentLen) {
|
|
97
|
-
throw new ServedRejectionError({
|
|
98
|
-
code: "E_RANGE_STALE",
|
|
99
|
-
message: `[E_RANGE_STALE] The served span (${servedLen} lines) no longer matches the current range (${currentLen} lines)${where}. Current range:\n${echo}\n${retryHint()}`,
|
|
100
|
-
firstOffendingLine: startLine,
|
|
101
|
-
servedRows: echoRows,
|
|
102
|
-
});
|
|
103
|
-
}
|
|
104
|
-
for (let k = 0; k < servedLen; k++) {
|
|
105
|
-
if (served[from + k] !== fileHashes[startLine - 1 + k]) {
|
|
106
|
-
const offendingLine = startLine + k;
|
|
107
|
-
throw new ServedRejectionError({
|
|
108
|
-
code: "E_RANGE_STALE",
|
|
109
|
-
message: `[E_RANGE_STALE] Line ${offendingLine}${where} differs from what you were served — the file changed on disk since it was read. Current range:\n${echo}\n${retryHint()}`,
|
|
110
|
-
firstOffendingLine: offendingLine,
|
|
111
|
-
servedRows: echoRows,
|
|
112
|
-
});
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
export async function recordEchoServes(sessionKey, path, rows, policy, lineCount) {
|
|
117
|
-
if (policy !== "live")
|
|
118
|
-
return;
|
|
119
|
-
await recordServed(sessionKey, path, rows, lineCount);
|
|
120
|
-
}
|
|
1
|
+
// @deprecated — private to AnchorPipeline seam. Use `from "./anchor-pipeline.js"` instead.
|
|
2
|
+
export * from "./anchor-pipeline.js";
|
package/lib/index.js
CHANGED
|
@@ -19,10 +19,9 @@ import { ctxFsIO } from "./fs-bridge.js";
|
|
|
19
19
|
import { FsSandboxController } from "./sandbox.js";
|
|
20
20
|
import { registerReadTool } from "./tool-read.js";
|
|
21
21
|
import { registerEditTool } from "./tool-edit.js";
|
|
22
|
-
import { registerBatchEditTool } from "./tool-batch-edit.js";
|
|
23
22
|
import { registerUndoTool } from "./tool-undo.js";
|
|
24
23
|
import { registerWriteHook } from "./write-hook.js";
|
|
25
|
-
import { initHasher } from "./hashline/
|
|
24
|
+
import { initHasher } from "./hashline/hash-assign.js";
|
|
26
25
|
import { composeSections, ensurePresetGuidance, GUIDANCE_SECTIONS, } from "./guidance.js";
|
|
27
26
|
import { configDir } from "./paths.js";
|
|
28
27
|
/** Cordis plugin name used by loader diagnostics. */
|
|
@@ -82,7 +81,6 @@ function installAgentTools(rootCtx, agent) {
|
|
|
82
81
|
disposers.push(registerReadTool(rootCtx, agent.ctx, io));
|
|
83
82
|
const sandbox = new FsSandboxController(rootCtx);
|
|
84
83
|
disposers.push(registerEditTool(rootCtx, agent.ctx, io, sandbox));
|
|
85
|
-
disposers.push(registerBatchEditTool(rootCtx, agent.ctx, io, sandbox));
|
|
86
84
|
disposers.push(registerUndoTool(rootCtx, agent.ctx, io, sandbox));
|
|
87
85
|
disposers.push(registerWriteHook(rootCtx, agent.ctx, io));
|
|
88
86
|
// Shadow the preset's built-in tool guidance with the hashline
|
package/lib/mutation.js
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mutation — deep module owning the full file mutation lifecycle.
|
|
3
|
+
*
|
|
4
|
+
* Previously fragmented: tool-edit → edit-pipeline → edit-engine.applyOne →
|
|
5
|
+
* edit-response/diff/drift, and tool-batch-edit → edit-engine.runFileEdits
|
|
6
|
+
* (loop + unionRange + counters) → persistUndoAndWrite with a boolean flag.
|
|
7
|
+
* Warnings, hadUtf8DecodeErrors, firstChangedLine, driftNotice were threaded
|
|
8
|
+
* by mutation across 5 hops; bugs hid in wiring, not pure helpers.
|
|
9
|
+
*
|
|
10
|
+
* This seam owns: read → normalize → loadServed → applyOne* → stableRehash →
|
|
11
|
+
* drift → persist → render. Tools become thin adapters: validate → delegate → return.
|
|
12
|
+
* edit-diff, drift, noop-guard are private helpers of this seam.
|
|
13
|
+
*
|
|
14
|
+
* Public surface:
|
|
15
|
+
* execute(io, items, {sessionKey, exec, sandbox, signal}) → string — deep seam: ONE interface
|
|
16
|
+
* applySingle(io, params, cwd, opts) → PipelineResult — single-edit helper
|
|
17
|
+
* applySequence(io, items, ctx) → FileEditResult — per-file sequencer
|
|
18
|
+
* commit(io, files, {exec, sandboxPolicy, signal}) → void — transaction
|
|
19
|
+
*
|
|
20
|
+
* Depth: small interface (execute) with large implementation — locality and leverage.
|
|
21
|
+
*
|
|
22
|
+
* Internals (private): verifyServedRange, resToSpan, assemble, scanDrift,
|
|
23
|
+
* boundaryDups, noopGuard. Tested via PipelineResult/FileEditResult, not via split e2e.
|
|
24
|
+
*
|
|
25
|
+
* @module dsh-better-edit/mutation
|
|
26
|
+
*/
|
|
27
|
+
import { normFromText, fileSnap } from "./file-reader.js";
|
|
28
|
+
import { toCwd } from "./paths.js";
|
|
29
|
+
import { resEdit } from "./hashline/anchor-pipeline.js";
|
|
30
|
+
import { MAX_HASH_LINES } from "./hashline/hash-assign.js";
|
|
31
|
+
import { AnchorMismatchError, ServedRejectionError, recordEchoServes, } from "./hashline/anchor-pipeline.js";
|
|
32
|
+
import { loadServed, sessionKeyFor, scanDrift, recordServedTruncated } from "./session-view.js";
|
|
33
|
+
import { abortIf, splitLines } from "./utils.js";
|
|
34
|
+
import { applyOne } from "./edit-engine.js";
|
|
35
|
+
import { runFileEdits, resolveMissingPath, persistUndoAndWrite, enforceNoopLoop, collectRemovedHashes, countLineChanges, } from "./edit-engine.js";
|
|
36
|
+
import { buildMetrics, buildNoop, buildChanged, buildBatchResult } from "./edit-response.js";
|
|
37
|
+
import { genDiff, restoreEndings, toLF, stripBOM } from "./edit-diff.js";
|
|
38
|
+
import { computeDrift } from "./drift.js";
|
|
39
|
+
import { trackNoopPayload, clearNoopLoop, noopPayloadKey } from "./noop-guard.js";
|
|
40
|
+
export async function execPipeline(io, params, cwd, options) {
|
|
41
|
+
const path = params.path;
|
|
42
|
+
const editWarnings = [];
|
|
43
|
+
// Resolve the edit up front (before IO) so malformed anchors fail before
|
|
44
|
+
// any filesystem work, exactly as the tool always did.
|
|
45
|
+
const edit = resEdit({
|
|
46
|
+
remove_from: params.remove_from,
|
|
47
|
+
remove_to: params.remove_to,
|
|
48
|
+
replacement_text: params.replacement_text,
|
|
49
|
+
}, editWarnings);
|
|
50
|
+
const hashStore = options?.store;
|
|
51
|
+
const signal = options?.signal;
|
|
52
|
+
abortIf(signal);
|
|
53
|
+
const absolutePath = await io.resolve(path, cwd, signal);
|
|
54
|
+
const rawText = await io.readText(absolutePath, signal);
|
|
55
|
+
const { normalized: originalNormalized, bom, originalEnding, fileHashes: originalHashes, hadUtf8DecodeErrors, } = await normFromText({
|
|
56
|
+
absolutePath,
|
|
57
|
+
rawText,
|
|
58
|
+
displayPath: path,
|
|
59
|
+
signal,
|
|
60
|
+
maxLines: MAX_HASH_LINES,
|
|
61
|
+
store: hashStore,
|
|
62
|
+
noPersist: options?.noPersist,
|
|
63
|
+
});
|
|
64
|
+
const sessionKey = options?.sessionKey ?? sessionKeyFor(undefined);
|
|
65
|
+
const served = await loadServed(sessionKey, absolutePath);
|
|
66
|
+
const policy = options?.noPersist === true ? 'preview' : 'live';
|
|
67
|
+
const applied = await applyOne({
|
|
68
|
+
content: originalNormalized,
|
|
69
|
+
hashes: originalHashes,
|
|
70
|
+
served,
|
|
71
|
+
removeFrom: params.remove_from,
|
|
72
|
+
removeTo: params.remove_to,
|
|
73
|
+
replacementText: params.replacement_text,
|
|
74
|
+
absolutePath,
|
|
75
|
+
displayPath: path,
|
|
76
|
+
signal,
|
|
77
|
+
warnings: editWarnings,
|
|
78
|
+
store: hashStore,
|
|
79
|
+
persist: options?.noPersist !== true,
|
|
80
|
+
edit,
|
|
81
|
+
}, async (error) => {
|
|
82
|
+
if (error instanceof AnchorMismatchError ||
|
|
83
|
+
error instanceof ServedRejectionError) {
|
|
84
|
+
await recordEchoServes(sessionKey, absolutePath, error.servedRows, policy, originalHashes.length);
|
|
85
|
+
}
|
|
86
|
+
throw error;
|
|
87
|
+
});
|
|
88
|
+
const result = applied.result;
|
|
89
|
+
const isNoop = applied.noop;
|
|
90
|
+
const warnings = [...editWarnings, ...(applied.anchorWarnings ?? [])];
|
|
91
|
+
let driftNotice;
|
|
92
|
+
if (options?.noPersist !== true) {
|
|
93
|
+
try {
|
|
94
|
+
driftNotice = await scanDrift({
|
|
95
|
+
sessionKey,
|
|
96
|
+
served,
|
|
97
|
+
resultHashes: applied.hashes,
|
|
98
|
+
resultLines: splitLines(result),
|
|
99
|
+
range: applied.range,
|
|
100
|
+
path: absolutePath,
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
console.error('Failed to compute drift notice:', error);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return {
|
|
108
|
+
path,
|
|
109
|
+
absolutePath,
|
|
110
|
+
originalNormalized,
|
|
111
|
+
result,
|
|
112
|
+
bom,
|
|
113
|
+
originalEnding,
|
|
114
|
+
hadUtf8DecodeErrors,
|
|
115
|
+
warnings,
|
|
116
|
+
noopEdit: applied.noopEdit,
|
|
117
|
+
firstChangedLine: applied.firstChangedLine,
|
|
118
|
+
lastChangedLine: applied.lastChangedLine,
|
|
119
|
+
originalHashes,
|
|
120
|
+
resultHashes: applied.hashes,
|
|
121
|
+
totalAddedLines: applied.totalAddedLines,
|
|
122
|
+
totalRemovedLines: applied.totalRemovedLines,
|
|
123
|
+
driftNotice,
|
|
124
|
+
range: applied.range,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
/** Resolve the display path a caller names against the session cwd. */
|
|
128
|
+
export function resolveDisplayPath(path, cwd) {
|
|
129
|
+
return toCwd(path, cwd);
|
|
130
|
+
}
|
|
131
|
+
/** Snapshot bookkeeping for noop/success results (best-effort). */
|
|
132
|
+
export async function snapshotIdFor(io, absolutePath, signal) {
|
|
133
|
+
try {
|
|
134
|
+
return await io.statVersion(absolutePath, signal);
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
try {
|
|
138
|
+
return (await fileSnap(absolutePath)).snapshotId;
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
return undefined;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
export { runFileEdits, resolveMissingPath, persistUndoAndWrite, enforceNoopLoop, collectRemovedHashes, countLineChanges, };
|
|
146
|
+
export { buildMetrics, buildNoop, buildChanged, buildBatchResult };
|
|
147
|
+
export { genDiff, restoreEndings, toLF, stripBOM };
|
|
148
|
+
export { computeDrift, scanDrift };
|
|
149
|
+
export { trackNoopPayload, clearNoopLoop, noopPayloadKey };
|
|
150
|
+
// --- Deep seam: unified mutation API (one interface, thin adapters) ---
|
|
151
|
+
/**
|
|
152
|
+
* Deep seam: execute the full mutation lifecycle.
|
|
153
|
+
*
|
|
154
|
+
* Owns: applySequence → branch (single/multi × noop/applied) → commit →
|
|
155
|
+
* buildBatchResult → recordServedTruncated → return text.
|
|
156
|
+
*
|
|
157
|
+
* The tool layer (adapter) only validates and resolves the nullable path; all
|
|
158
|
+
* lifecycle branching concentrates here (locality). One interface serves N
|
|
159
|
+
* call sites (leverage). Deleting this module would scatter the lifecycle
|
|
160
|
+
* across every tool — it concentrates (deep).
|
|
161
|
+
*/
|
|
162
|
+
export async function execute(opts) {
|
|
163
|
+
const { io, items, sessionKey, signal, exec, sandbox, sandboxPolicy } = opts;
|
|
164
|
+
const fileResult = await applySequence(io, items, { signal, sessionKey });
|
|
165
|
+
const toSection = () => ({
|
|
166
|
+
path: fileResult.displayPath,
|
|
167
|
+
originalNormalized: fileResult.originalNormalized,
|
|
168
|
+
result: fileResult.result,
|
|
169
|
+
originalHashes: fileResult.originalHashes,
|
|
170
|
+
resultHashes: fileResult.resultHashes,
|
|
171
|
+
warnings: fileResult.warnings,
|
|
172
|
+
driftNotice: fileResult.driftNotice,
|
|
173
|
+
appliedCount: fileResult.appliedCount,
|
|
174
|
+
noopCount: fileResult.noopCount,
|
|
175
|
+
totalAddedLines: fileResult.totalAddedLines,
|
|
176
|
+
totalRemovedLines: fileResult.totalRemovedLines,
|
|
177
|
+
});
|
|
178
|
+
const recordIfNeeded = async (built) => {
|
|
179
|
+
if (built.details.servedRows && built.details.servedRows.length > 0) {
|
|
180
|
+
const entry = built.details.servedByPath?.[0];
|
|
181
|
+
if (entry) {
|
|
182
|
+
await recordServedTruncated(sessionKey, fileResult.absolutePath, entry.servedRows, splitLines(fileResult.result).length, fileResult.range.startLine - 1);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
const isSingleCall = items.length === 1 && fileResult.appliedCount + fileResult.noopCount === 1;
|
|
187
|
+
if (isSingleCall) {
|
|
188
|
+
if (fileResult.appliedCount === 0) {
|
|
189
|
+
const built = buildBatchResult([toSection()]);
|
|
190
|
+
await recordIfNeeded(built);
|
|
191
|
+
return built.content[0].text;
|
|
192
|
+
}
|
|
193
|
+
await commit({
|
|
194
|
+
io,
|
|
195
|
+
files: [
|
|
196
|
+
{
|
|
197
|
+
absolutePath: fileResult.absolutePath,
|
|
198
|
+
displayPath: fileResult.displayPath,
|
|
199
|
+
originalNormalized: fileResult.originalNormalized,
|
|
200
|
+
bom: fileResult.bom,
|
|
201
|
+
originalEnding: fileResult.originalEnding,
|
|
202
|
+
originalHashes: fileResult.originalHashes,
|
|
203
|
+
result: fileResult.result,
|
|
204
|
+
},
|
|
205
|
+
],
|
|
206
|
+
exec,
|
|
207
|
+
sandbox,
|
|
208
|
+
sandboxPolicy,
|
|
209
|
+
signal,
|
|
210
|
+
undoUnavailableMessage: (displayPath) => `[E_UNDO_UNAVAILABLE] Cannot persist undo history to the hash store; the edit was NOT applied and ${displayPath} is unchanged. Retry the edit, or use write if the store cannot be recovered.`,
|
|
211
|
+
restoreUnwrittenUndos: true,
|
|
212
|
+
});
|
|
213
|
+
const built = buildBatchResult([toSection()]);
|
|
214
|
+
await recordIfNeeded(built);
|
|
215
|
+
return built.content[0].text;
|
|
216
|
+
}
|
|
217
|
+
if (fileResult.appliedCount === 0 && fileResult.noopCount > 0) {
|
|
218
|
+
// all noops — no commit
|
|
219
|
+
}
|
|
220
|
+
else if (fileResult.appliedCount > 0) {
|
|
221
|
+
await commit({
|
|
222
|
+
io,
|
|
223
|
+
files: [
|
|
224
|
+
{
|
|
225
|
+
absolutePath: fileResult.absolutePath,
|
|
226
|
+
displayPath: fileResult.displayPath,
|
|
227
|
+
originalNormalized: fileResult.originalNormalized,
|
|
228
|
+
bom: fileResult.bom,
|
|
229
|
+
originalEnding: fileResult.originalEnding,
|
|
230
|
+
originalHashes: fileResult.originalHashes,
|
|
231
|
+
result: fileResult.result,
|
|
232
|
+
},
|
|
233
|
+
],
|
|
234
|
+
exec,
|
|
235
|
+
sandbox,
|
|
236
|
+
sandboxPolicy,
|
|
237
|
+
signal,
|
|
238
|
+
undoUnavailableMessage: () => "[E_UNDO_UNAVAILABLE] Cannot persist undo history to the hash store; the batch was NOT applied and no file was written. Retry the batch, or use write if the store cannot be recovered.",
|
|
239
|
+
restoreUnwrittenUndos: false,
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
const built = buildBatchResult([toSection()]);
|
|
243
|
+
await recordIfNeeded(built);
|
|
244
|
+
return built.content[0].text;
|
|
245
|
+
}
|
|
246
|
+
/** Apply a single edit — owns read→normalize→loadServed→applyOne→stableRehash→drift. */
|
|
247
|
+
export async function applySingle(io, params, cwd, opts) {
|
|
248
|
+
return execPipeline(io, params, cwd, opts);
|
|
249
|
+
}
|
|
250
|
+
/** Apply a per-file sequence (batch's group) — owns the loop + unionRange + counters. */
|
|
251
|
+
export async function applySequence(io, items, ctx) {
|
|
252
|
+
return runFileEdits(io, items, ctx);
|
|
253
|
+
}
|
|
254
|
+
/** Commit the transaction — owns persist-undo → write → restore. */
|
|
255
|
+
export async function commit(opts) {
|
|
256
|
+
return persistUndoAndWrite({
|
|
257
|
+
io: opts.io,
|
|
258
|
+
files: opts.files,
|
|
259
|
+
exec: opts.exec,
|
|
260
|
+
sandbox: opts.sandbox,
|
|
261
|
+
sandboxPolicy: opts.sandboxPolicy,
|
|
262
|
+
signal: opts.signal,
|
|
263
|
+
undoUnavailableMessage: opts.undoUnavailableMessage,
|
|
264
|
+
restoreUnwrittenUndos: opts.restoreUnwrittenUndos,
|
|
265
|
+
});
|
|
266
|
+
}
|
package/lib/noop-guard.js
CHANGED
|
@@ -13,3 +13,23 @@ export function clearNoopLoop(absolutePath) {
|
|
|
13
13
|
noopLoopTracker.delete(absolutePath);
|
|
14
14
|
}
|
|
15
15
|
export { NOOP_LOOP_THRESHOLD };
|
|
16
|
+
export function runNoopPolicySync(input, count) {
|
|
17
|
+
if (count >= NOOP_LOOP_THRESHOLD) {
|
|
18
|
+
const message = input.batch
|
|
19
|
+
? `[E_NOOP_LOOP] ${input.ref}: identical edit (${input.removeFrom} → ${input.removeTo}) submitted ${count}×, no changes each time. Range already contains this text; resend will reject the batch.`
|
|
20
|
+
: `[E_NOOP_LOOP] identical edit (${input.removeFrom} → ${input.removeTo} ${input.ref}) submitted ${count}×, no changes each time. Range already contains this text; resend will reject.`;
|
|
21
|
+
return { action: "reject", count, message };
|
|
22
|
+
}
|
|
23
|
+
if (count === 2) {
|
|
24
|
+
const notice = input.batch
|
|
25
|
+
? `[E_NOOP_LOOP] Notice: ${input.ref} — identical edit no-op'd twice; range already has this text. Resend will reject the batch.`
|
|
26
|
+
: `[E_NOOP_LOOP] Notice: identical edit (${input.removeFrom} → ${input.removeTo} ${input.ref}) no-op'd twice; range already has this text. Resend will reject.`;
|
|
27
|
+
return { action: "warn", count, notice };
|
|
28
|
+
}
|
|
29
|
+
return { action: "proceed", count };
|
|
30
|
+
}
|
|
31
|
+
export async function runNoopPolicy(input) {
|
|
32
|
+
const payload = noopPayloadKey(input.absolutePath, input.removeFrom, input.removeTo, input.replacementText);
|
|
33
|
+
const count = trackNoopPayload(input.absolutePath, payload);
|
|
34
|
+
return runNoopPolicySync(input, count);
|
|
35
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Debounced preview controller — extracted from buildToolDef so hashline seams
|
|
3
|
+
* stay pure and the debounce invariant is testable.
|
|
4
|
+
* @module dsh-better-edit/preview-controller
|
|
5
|
+
*/
|
|
6
|
+
export const PREVIEW_DEBOUNCE_MS = 150;
|
|
7
|
+
export function getPreviewInput(_args) {
|
|
8
|
+
return null;
|
|
9
|
+
}
|
|
10
|
+
export class DebouncedPreview {
|
|
11
|
+
compute;
|
|
12
|
+
debounceMs;
|
|
13
|
+
constructor(compute, debounceMs = PREVIEW_DEBOUNCE_MS) {
|
|
14
|
+
this.compute = compute;
|
|
15
|
+
this.debounceMs = debounceMs;
|
|
16
|
+
}
|
|
17
|
+
renderCall(host, args) {
|
|
18
|
+
const { state } = host;
|
|
19
|
+
const previewInput = getPreviewInput(args);
|
|
20
|
+
if (host.executionStarted || !host.argsComplete || !previewInput) {
|
|
21
|
+
this.cancel(state);
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
const argsKey = JSON.stringify(previewInput);
|
|
25
|
+
if (state.argsKey === argsKey)
|
|
26
|
+
return;
|
|
27
|
+
this.cancel(state);
|
|
28
|
+
state.argsKey = argsKey;
|
|
29
|
+
const previewGeneration = (state.previewGeneration ?? 0) + 1;
|
|
30
|
+
state.previewGeneration = previewGeneration;
|
|
31
|
+
state.previewTimer = setTimeout(() => {
|
|
32
|
+
state.previewTimer = undefined;
|
|
33
|
+
this.compute(args, host.cwd)
|
|
34
|
+
.then((preview) => {
|
|
35
|
+
if (state.argsKey === argsKey && state.previewGeneration === previewGeneration) {
|
|
36
|
+
state.preview = preview;
|
|
37
|
+
host.invalidate();
|
|
38
|
+
}
|
|
39
|
+
})
|
|
40
|
+
.catch((err) => {
|
|
41
|
+
if (state.argsKey === argsKey && state.previewGeneration === previewGeneration) {
|
|
42
|
+
state.preview = { error: err instanceof Error ? err.message : String(err) };
|
|
43
|
+
host.invalidate();
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
}, this.debounceMs);
|
|
47
|
+
}
|
|
48
|
+
cancel(state) {
|
|
49
|
+
if (state.previewTimer) {
|
|
50
|
+
clearTimeout(state.previewTimer);
|
|
51
|
+
state.previewTimer = undefined;
|
|
52
|
+
}
|
|
53
|
+
state.argsKey = undefined;
|
|
54
|
+
state.preview = undefined;
|
|
55
|
+
state.previewGeneration = (state.previewGeneration ?? 0) + 1;
|
|
56
|
+
}
|
|
57
|
+
clearResult(state) {
|
|
58
|
+
if (state.previewTimer) {
|
|
59
|
+
clearTimeout(state.previewTimer);
|
|
60
|
+
state.previewTimer = undefined;
|
|
61
|
+
}
|
|
62
|
+
state.preview = undefined;
|
|
63
|
+
state.previewGeneration = (state.previewGeneration ?? 0) + 1;
|
|
64
|
+
}
|
|
65
|
+
}
|
package/lib/prompts.js
CHANGED
|
@@ -7,17 +7,18 @@
|
|
|
7
7
|
* @module dsh-better-edit/prompts
|
|
8
8
|
*/
|
|
9
9
|
export const EDIT_DESCRIPTION = "Edit a range of lines in a text file, targeted by the 3-char HASH anchors from read output. " +
|
|
10
|
+
'Use { "path": "file.ts", "edits": [[remove_from, remove_to, replacement_text], ...] } — path is the file to edit (or null to infer from anchors), edits is an array of [remove_from, remove_to, replacement_text] tuples. ' +
|
|
10
11
|
"remove_from and remove_to must each be a BARE 3-character hash: copy only the hash from the " +
|
|
11
12
|
'leftmost column of a read row (row `ve7│function hello() {` means `"remove_from": "ve7"`). ' +
|
|
12
|
-
"Never pass the line content, a code line, or a paragraph into these fields.";
|
|
13
|
+
"Never pass the line content, a code line, or a paragraph into these fields. The path is hoisted to the payload root so every edit in one call targets the same file; a length-1 edits array is a single edit.";
|
|
13
14
|
export const EDIT_GUIDANCE = {
|
|
14
|
-
intro: "Edit a range of lines via a bare 3-char HASH anchor
|
|
15
|
+
intro: "Edit a range of lines via a bare 3-char HASH anchor — payload is { path, edits: [[hash,hash,text]] } (single-file atomic, null path infers).",
|
|
15
16
|
lines: [
|
|
16
|
-
"`edit`:
|
|
17
|
+
"`edit`: payload is { \"path\": \"file.ts\"|null, \"edits\": [[remove_from, remove_to, replacement_text], ...] } — path at root, each item is a 3-position tuple with bare hashes (`ve7`, not `ve7│function…`). A single line uses the same hash in both fields.",
|
|
17
18
|
"`edit`: replacement_text is byte-exact for the whole range — every line inside it you do not reproduce byte-exact is deleted, and leading whitespace is preserved exactly.",
|
|
18
19
|
"`edit`: `\\n` is a line break, so a range ending on a blank line must end replacement_text with `\\n` and a non-blank last line must not; a blank-line run is one `\\n` per blank line.",
|
|
19
20
|
"`edit`: the post-edit diff rows carry fresh anchors for follow-ups. A stale or never-served range is hard-rejected (`[E_RANGE_STALE]` / `[E_RANGE_UNSERVED]`); copy the echoed rows and retry — only tool-served rows count.",
|
|
20
|
-
"`edit`:
|
|
21
|
+
"`edit`: multiple edits to the same file in one call are atomic (all-or-nothing): if any tuple fails — stale, ambiguous, never-served — nothing is written and the failing tuple's current range is served back. Prefer one edit per call unless you have independent ranges.",
|
|
21
22
|
],
|
|
22
23
|
};
|
|
23
24
|
export const READ_DESCRIPTION = "Read a text file; each line returned as HASH│content with a 3-char alphanumeric hash. " +
|
|
@@ -31,22 +32,6 @@ export const READ_GUIDANCE = {
|
|
|
31
32
|
"`read`: binary/directory rejects; page large files with offset/limit.",
|
|
32
33
|
],
|
|
33
34
|
};
|
|
34
|
-
export const BATCH_EDIT_DESCRIPTION = "Apply several edits in one atomic call. Each item is exactly like the edit tool: " +
|
|
35
|
-
"{ path?, remove_from, remove_to, replacement_text }, where remove_from and remove_to are " +
|
|
36
|
-
"bare 3-char hashes from read or diff output. Items targeting the same file are applied in order. " +
|
|
37
|
-
"Every item is verified against what the tool served you before ANYTHING is written: if any item " +
|
|
38
|
-
"fails — stale or ambiguous anchor, changed range interior, never-served line — the whole batch " +
|
|
39
|
-
"is rejected and no file changes. The failing item\u2019s current range is served back as fresh " +
|
|
40
|
-
"HASH│content rows so you can retry without a read. Use batch_edit whenever you have multiple " +
|
|
41
|
-
"edits; do not issue several edit calls in one message.";
|
|
42
|
-
export const BATCH_EDIT_GUIDANCE = {
|
|
43
|
-
intro: "Apply several edits in one atomic call.",
|
|
44
|
-
lines: [
|
|
45
|
-
"`batch_edit`: each item is edit\u2019s shape — { path?, remove_from, remove_to, replacement_text } — with bare hash anchors; items apply in order, and same-file ranges must not overlap.",
|
|
46
|
-
"`batch_edit`: all-or-nothing — any failing item writes nothing anywhere and echoes its current range as fresh rows that count as serves.",
|
|
47
|
-
"`batch_edit`: a no-op item is reported without failing; the result is one combined diff per file with fresh anchors.",
|
|
48
|
-
],
|
|
49
|
-
};
|
|
50
35
|
export const UNDO_DESCRIPTION = "Undo the last edit on a file, reverting it to its previous state. Use when an edit produced " +
|
|
51
36
|
"incorrect results (e.g., wrong content, duplicated lines, broken syntax).";
|
|
52
37
|
export const UNDO_GUIDANCE = {
|
|
@@ -56,3 +41,12 @@ export const UNDO_GUIDANCE = {
|
|
|
56
41
|
"`undo_last_edit`: the restored diff\u2019s `+HASH│` and ` HASH│` rows are fresh anchors for follow-up edits.",
|
|
57
42
|
],
|
|
58
43
|
};
|
|
44
|
+
/**
|
|
45
|
+
* @deprecated batch_edit guidance seam was removed with ADR-0003 (payload contract
|
|
46
|
+
* merged batch_edit into edit's {path, edits:[[hash,hash,text]]} arity). This alias
|
|
47
|
+
* is kept for backwards compat — use EDIT_DESCRIPTION. The guidance system no
|
|
48
|
+
* longer includes tool:batch_edit.
|
|
49
|
+
*/
|
|
50
|
+
export const BATCH_EDIT_DESCRIPTION = EDIT_DESCRIPTION;
|
|
51
|
+
/** @deprecated see BATCH_EDIT_DESCRIPTION — use EDIT_GUIDANCE */
|
|
52
|
+
export const BATCH_EDIT_GUIDANCE = EDIT_GUIDANCE;
|
package/lib/read-and-serve.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The shared read-and-serve operation
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
2
|
+
* The shared read-and-serve operation — now a thin wrapper over FileView.
|
|
3
|
+
*
|
|
4
|
+
* FileView owns normalize → hash → render → truncate → served selection.
|
|
5
|
+
* This module only adds the persistence seam: recordServed + clearDriftReported
|
|
6
|
+
* + UTF-8 rewrite note. Used by the `read` tool and by the write auto-read
|
|
7
|
+
* hook, so the model is always shown fresh anchors the same way.
|
|
7
8
|
* @module dsh-better-edit/read-and-serve
|
|
8
9
|
*/
|
|
9
10
|
import { abortIf } from "./utils.js";
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import { recordServed, clearDriftReported } from "./served-store.js";
|
|
11
|
+
import { readView } from "./file-view.js";
|
|
12
|
+
import { recordServed, clearDriftReported } from "./session-view.js";
|
|
13
13
|
/** Appended when the file had non-UTF-8 bytes; editing rewrites it as UTF-8. */
|
|
14
14
|
export const UTF8_REWRITE_NOTE = "[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]";
|
|
15
15
|
/**
|
|
@@ -25,22 +25,22 @@ export const UTF8_REWRITE_NOTE = "[Non-UTF-8 bytes shown as U+FFFD; editing rewr
|
|
|
25
25
|
export async function readAndServe(io, rawPath, cwd, options) {
|
|
26
26
|
const { sessionKey, signal } = options;
|
|
27
27
|
abortIf(signal);
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
absolutePath,
|
|
32
|
-
rawText,
|
|
33
|
-
displayPath: rawPath,
|
|
28
|
+
const view = await readView(io, rawPath, cwd, {
|
|
29
|
+
offset: options.offset,
|
|
30
|
+
limit: options.limit,
|
|
34
31
|
signal,
|
|
35
|
-
maxLines: MAX_HASH_LINES,
|
|
36
32
|
});
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
await recordServed(sessionKey, absolutePath, preview.served, fileHashes.length);
|
|
33
|
+
if (view.served.length > 0) {
|
|
34
|
+
await recordServed(sessionKey, view.absolutePath, view.served, view.hashes.length);
|
|
40
35
|
}
|
|
41
|
-
await clearDriftReported(sessionKey, absolutePath);
|
|
42
|
-
const text = hadUtf8DecodeErrors
|
|
43
|
-
? `${
|
|
44
|
-
:
|
|
45
|
-
return {
|
|
36
|
+
await clearDriftReported(sessionKey, view.absolutePath);
|
|
37
|
+
const text = view.hadUtf8DecodeErrors
|
|
38
|
+
? `${view.text}\n\n${UTF8_REWRITE_NOTE}`
|
|
39
|
+
: view.text;
|
|
40
|
+
return {
|
|
41
|
+
text,
|
|
42
|
+
served: view.served,
|
|
43
|
+
hadUtf8DecodeErrors: view.hadUtf8DecodeErrors,
|
|
44
|
+
absolutePath: view.absolutePath,
|
|
45
|
+
};
|
|
46
46
|
}
|