dsh-hashline-edit 0.3.12 → 0.4.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/README.md +68 -29
- package/cordis.patch.yml +7 -5
- package/lib/client.js +7 -7
- package/lib/index.js +3521 -1034
- package/lib/types/dsh/guidance.d.ts +4 -5
- package/lib/types/dsh/hide.d.ts +6 -39
- package/lib/types/dsh/index.d.ts +17 -15
- package/lib/types/dsh/tools/edit.d.ts +3 -0
- package/lib/types/src/edit-tool.d.ts +41 -0
- package/lib/types/src/mutation-engine/engine.d.ts +31 -0
- package/lib/types/src/mutation-result.d.ts +35 -0
- package/lib/types/src/payload-contract.d.ts +64 -0
- package/package.json +3 -2
- package/src/edit-tool.ts +118 -0
- package/src/mutation-engine/engine.ts +175 -0
- package/src/mutation-result.ts +37 -0
- package/src/payload-contract.ts +511 -0
- package/src/prompts-bundled.ts +10 -4
- package/lib/types/dsh/tools/undo.d.ts +0 -15
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { DomainErrorCode, RangeCause, ServedRow } from "./domain-errors.js";
|
|
2
|
+
import type { EditDetails, RMetrics } from "./edit-response.js";
|
|
3
|
+
import type { ProcessedEditFile } from "./mutation-engine/types.js";
|
|
4
|
+
|
|
5
|
+
export interface MutationSuccess {
|
|
6
|
+
ok: true;
|
|
7
|
+
result: string;
|
|
8
|
+
diff: string;
|
|
9
|
+
drift: string | undefined;
|
|
10
|
+
metrics: RMetrics;
|
|
11
|
+
raw: ProcessedEditFile;
|
|
12
|
+
toolResult: {
|
|
13
|
+
content: Array<{ type: "text"; text: string }>;
|
|
14
|
+
details: EditDetails;
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface MutationFailure {
|
|
19
|
+
ok: false;
|
|
20
|
+
code: DomainErrorCode;
|
|
21
|
+
message: string;
|
|
22
|
+
servedBlock?: string;
|
|
23
|
+
servedRows?: ServedRow[];
|
|
24
|
+
payloadMessage?: string;
|
|
25
|
+
cause?: RangeCause;
|
|
26
|
+
details?: { code: DomainErrorCode; cause: RangeCause };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export type MutationResult = MutationSuccess | MutationFailure;
|
|
30
|
+
|
|
31
|
+
export function isMutationSuccess(r: MutationResult): r is MutationSuccess {
|
|
32
|
+
return r.ok === true;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function isMutationFailure(r: MutationResult): r is MutationFailure {
|
|
36
|
+
return r.ok === false;
|
|
37
|
+
}
|
|
@@ -0,0 +1,511 @@
|
|
|
1
|
+
import { DomainError } from "./domain-errors.js";
|
|
2
|
+
import { HASH_LEN } from "./hashline/alphabet.js";
|
|
3
|
+
import type { EditPlacement } from "./hashline/resolve.js";
|
|
4
|
+
import { rejectUnknownFields } from "./utils.js";
|
|
5
|
+
|
|
6
|
+
const normalizedEdit = Symbol("normalizedEdit");
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The `text_ref` payload: two inclusive bare anchors bounding a served span, an optional serving
|
|
10
|
+
* `file`, and a REQUIRED `mode` — `"copy"` re-inserts the span bytes, `"cut"` additionally retires
|
|
11
|
+
* them. Both modes apply to this file AND to another served file (ticket-04b): a foreign-source
|
|
12
|
+
* `"cut"` commits the insert and the source retirement as one correlated transaction (ADR-0028).
|
|
13
|
+
*/
|
|
14
|
+
type SpanRef = {
|
|
15
|
+
anchor_from: string;
|
|
16
|
+
anchor_to: string;
|
|
17
|
+
file?: string;
|
|
18
|
+
mode: "copy" | "cut";
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Wire item (ticket-04): exactly one payload per item — `text` or `text_ref` — over the inclusive
|
|
23
|
+
* anchor pair, with optional `at` placement. There is no `op` field and no verbs: the key set IS
|
|
24
|
+
* the vocabulary (ADR-0007 line 26; content comes from the copy of another served file, which the
|
|
25
|
+
* wire expresses as `text_ref.file`).
|
|
26
|
+
*/
|
|
27
|
+
type EditItem = {
|
|
28
|
+
anchor_from: string;
|
|
29
|
+
anchor_to: string;
|
|
30
|
+
at?: "in-place" | "before" | "after";
|
|
31
|
+
text?: string;
|
|
32
|
+
text_ref?: SpanRef;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
type EditMode = "general" | "literal";
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Internal normalized vocabulary owned by the admission boundary (ticket-01, renamed ticket-04).
|
|
39
|
+
* The wire never names these shapes: `normReq` builds them once from the validated payload and
|
|
40
|
+
* everything downstream consumes the union — the engine switches on `payload.kind` exhaustively.
|
|
41
|
+
*/
|
|
42
|
+
export type Placement = "in-place" | "before" | "after";
|
|
43
|
+
|
|
44
|
+
// WHY: (§9.12) the wire `at` union and the engine seam's placement union are one vocabulary by
|
|
45
|
+
// WHY: contract, not by copy: this compile-time mutual-assignability assertion fails
|
|
46
|
+
// WHY: `pnpm run typecheck` the moment the two unions drift apart.
|
|
47
|
+
/**
|
|
48
|
+
* @public Intentional surface (knip): the tuple type is the wire/engine
|
|
49
|
+
* vocabulary check, so the binding is never imported — its reason to exist
|
|
50
|
+
* is the typecheck failure it produces when the unions drift.
|
|
51
|
+
*/
|
|
52
|
+
export const _placementVocabularyAgreement: [
|
|
53
|
+
Placement extends EditPlacement ? true : never,
|
|
54
|
+
EditPlacement extends Placement ? true : never,
|
|
55
|
+
] = [true, true];
|
|
56
|
+
|
|
57
|
+
/** The anchor pair an item targets — placement and payload are relative to its resolved span. */
|
|
58
|
+
type AnchorSpan = { anchor_from: string; anchor_to: string };
|
|
59
|
+
|
|
60
|
+
type DesiredContent =
|
|
61
|
+
| { kind: "literal"; text: string }
|
|
62
|
+
| { kind: "reference"; span: SpanRef; mode: "copy" | "cut" }
|
|
63
|
+
| { kind: "empty" };
|
|
64
|
+
|
|
65
|
+
type NormalizedEditItem = {
|
|
66
|
+
target: AnchorSpan;
|
|
67
|
+
at: Placement;
|
|
68
|
+
payload: DesiredContent;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
export type NormalizedEditRequest = {
|
|
72
|
+
file: string;
|
|
73
|
+
edits: NormalizedEditItem[];
|
|
74
|
+
mode?: EditMode;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
/** The wire-folded request (the admission analyzer's view): canonical keys, pre-union. */
|
|
78
|
+
type PreAdmissionRequest = {
|
|
79
|
+
file: string;
|
|
80
|
+
edits: EditItem[];
|
|
81
|
+
mode?: EditMode;
|
|
82
|
+
};
|
|
83
|
+
type NormalizedPayload = NormalizedEditRequest & {
|
|
84
|
+
readonly [normalizedEdit]: true;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
type RawPayload = string | number | boolean | null | undefined | Record<string, unknown>;
|
|
88
|
+
|
|
89
|
+
export type NormReqResult = NormalizedPayload | RawPayload;
|
|
90
|
+
|
|
91
|
+
function isRec(value: unknown): value is Record<string, unknown> {
|
|
92
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function isNormalizedEdit(input: unknown): input is Record<string, unknown> {
|
|
96
|
+
return isRec(input) && (input as Record<string | symbol, unknown>)[normalizedEdit] === true;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const ITEM_SHAPE =
|
|
100
|
+
"an item is exactly { anchor_from, anchor_to, text[, at] } or { anchor_from, anchor_to, text_ref[, at] }";
|
|
101
|
+
|
|
102
|
+
const EDIT_PAYLOAD_HINT =
|
|
103
|
+
"Edit must be called with exactly one payload per item, and each call edits ONE file. Use the canonical payload " +
|
|
104
|
+
'{"file": file, "edits": [{ "anchor_from": anchor_from, "anchor_to": anchor_to, "text": text }, ...], "mode"?: "general" | "literal"}: ' +
|
|
105
|
+
'"file" is the text file to edit (a non-empty string, never a directory); each item names two inclusive ' +
|
|
106
|
+
`bare-${HASH_LEN}-char anchors and exactly one payload — "text" (bare replacement content; an empty string deletes the ` +
|
|
107
|
+
'range) or "text_ref" ({ anchor_from, anchor_to, file?, mode (required): "copy" | "cut" } — the served span\'s bytes, ' +
|
|
108
|
+
'whose "file" may name another served file as the copy/cut source; optional "at" is "in-place" (default), ' +
|
|
109
|
+
'"before" or "after" (single-line resolved target only); optional "mode" is "general" (default, reproduced ' +
|
|
110
|
+
'served rows are refused) or "literal" (declared literal content).';
|
|
111
|
+
function describeReceived(input: unknown): string {
|
|
112
|
+
if (input === undefined) return "Received no arguments.";
|
|
113
|
+
if (input === null) return "Received null.";
|
|
114
|
+
if (typeof input === "string") return `Received a bare string (${JSON.stringify(input)}).`;
|
|
115
|
+
const json = JSON.stringify(input);
|
|
116
|
+
if (typeof json === "string" && json.length > 600) {
|
|
117
|
+
const truncated = json.slice(0, 600);
|
|
118
|
+
return `Received: ${truncated}… (+truncated, full file+edits in tool input)`;
|
|
119
|
+
}
|
|
120
|
+
return `Received: ${json}`;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function quoted(keys: string[]): string {
|
|
124
|
+
return keys.map((key) => `"${key}"`).join(", ");
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function sanitizePath(value: unknown): string | null {
|
|
128
|
+
if (typeof value !== "string") return null;
|
|
129
|
+
let s = value.trim();
|
|
130
|
+
// WHY: Gemma 4 bleed: model may wrap path in <|>, │, |, quotes, or backticks due to │ confusion — see via https://github.com/Rianico/pi-better-edit/issues/55
|
|
131
|
+
// WHY: Strip leading/trailing wrappers iteratively — model may re-wrap after slice, see sanitizePath
|
|
132
|
+
let changed = true;
|
|
133
|
+
while (changed) {
|
|
134
|
+
changed = false;
|
|
135
|
+
if (s.startsWith("<|>") && s.endsWith("<|>") && s.length > 6) {
|
|
136
|
+
s = s.slice(3, -3).trim();
|
|
137
|
+
changed = true;
|
|
138
|
+
}
|
|
139
|
+
if (s.startsWith("│") && s.endsWith("│") && s.length > 2) {
|
|
140
|
+
s = s.slice(1, -1).trim();
|
|
141
|
+
changed = true;
|
|
142
|
+
}
|
|
143
|
+
if (s.startsWith("|") && s.endsWith("|") && s.length > 2) {
|
|
144
|
+
s = s.slice(1, -1).trim();
|
|
145
|
+
changed = true;
|
|
146
|
+
}
|
|
147
|
+
if (
|
|
148
|
+
(s.startsWith('"') && s.endsWith('"')) ||
|
|
149
|
+
(s.startsWith("'") && s.endsWith("'")) ||
|
|
150
|
+
(s.startsWith("`") && s.endsWith("`"))
|
|
151
|
+
) {
|
|
152
|
+
s = s.slice(1, -1).trim();
|
|
153
|
+
changed = true;
|
|
154
|
+
}
|
|
155
|
+
if (s.startsWith("<|>")) {
|
|
156
|
+
s = s.slice(3).trim();
|
|
157
|
+
changed = true;
|
|
158
|
+
}
|
|
159
|
+
if (s.endsWith("<|>")) {
|
|
160
|
+
s = s.slice(0, -3).trim();
|
|
161
|
+
changed = true;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return s.length > 0 ? s : null;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// WHY: (ticket-04 §3) the finite key-set gate: an item is legal only when its key set is EXACTLY
|
|
168
|
+
// WHY: one of S1 {anchor_from, anchor_to, text}, S2 = S1 + at, S3 {anchor_from, anchor_to,
|
|
169
|
+
// WHY: text_ref}, S4 = S3 + at — set EQUALITY, never superset, so a legacy key, an `op` field,
|
|
170
|
+
// WHY: both payloads or neither payload all refuse with the offending keys named. The vocabulary
|
|
171
|
+
// WHY: stays "two anchors, one payload, optional placement" and one call edits one file.
|
|
172
|
+
const ITEM_KEY_SETS: readonly (readonly string[])[] = [
|
|
173
|
+
["anchor_from", "anchor_to", "text"],
|
|
174
|
+
["anchor_from", "anchor_to", "at", "text"],
|
|
175
|
+
["anchor_from", "anchor_to", "text_ref"],
|
|
176
|
+
["anchor_from", "anchor_to", "at", "text_ref"],
|
|
177
|
+
];
|
|
178
|
+
|
|
179
|
+
function keySetEquals(keys: Set<string>, shape: readonly string[]): boolean {
|
|
180
|
+
if (keys.size !== shape.length) return false;
|
|
181
|
+
return shape.every((key) => keys.has(key));
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function isLegalItemKeySet(keys: Set<string>): boolean {
|
|
185
|
+
return ITEM_KEY_SETS.some((shape) => keySetEquals(keys, shape));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// WHY: bound to the union (§9.12): a list element outside `Placement` fails `pnpm run typecheck`.
|
|
189
|
+
const AT_SPELLINGS = ["in-place", "before", "after"] as const satisfies readonly Placement[];
|
|
190
|
+
|
|
191
|
+
// WHY: (ticket-67) strict structured-output harnesses spell "absent" as an explicit `null`
|
|
192
|
+
// WHY: (every property required). Key existence alone then lies: `{ text: "…", text_ref: null }`
|
|
193
|
+
// WHY: was refused as carrying both. `null`/`undefined` in the four optional slots (`text`,
|
|
194
|
+
// WHY: `text_ref`, `at`, root `mode`) reads as ABSENT wherever presence is decided — one
|
|
195
|
+
// WHY: predicate, so the gate, the validators and the normalizers cannot disagree.
|
|
196
|
+
// WHY: (ticket-75) the nested reference's optional `file` is the same slot one level down: a
|
|
197
|
+
// WHY: harness that must spell an omitted optional property emits `"file": null`, and reading it
|
|
198
|
+
// WHY: as present refused a call no retry could satisfy — the #67 class, one object deeper.
|
|
199
|
+
function isAbsentValue(value: unknown): value is null | undefined {
|
|
200
|
+
return value === null || value === undefined;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// WHY: (ticket-75) ONE fold site for the declaration and for the stored item: the item's optional
|
|
204
|
+
// WHY: slots and the nested optional `file` fold together, so `analyzeItem` validates exactly the
|
|
205
|
+
// WHY: shape `analyzeRequest` stores and nothing downstream can see an absent value as present.
|
|
206
|
+
function foldAbsentSlots(item: Record<string, unknown>): Record<string, unknown> {
|
|
207
|
+
const folded: Record<string, unknown> = { ...item };
|
|
208
|
+
for (const key of ["text", "text_ref", "at"] as const) {
|
|
209
|
+
if (isAbsentValue(folded[key])) delete folded[key];
|
|
210
|
+
}
|
|
211
|
+
if (isRec(folded.text_ref)) {
|
|
212
|
+
const reference: Record<string, unknown> = { ...folded.text_ref };
|
|
213
|
+
if (isAbsentValue(reference.file)) delete reference.file;
|
|
214
|
+
folded.text_ref = reference;
|
|
215
|
+
}
|
|
216
|
+
return folded;
|
|
217
|
+
}
|
|
218
|
+
function analyzeItem(value: unknown, index: number): string | undefined {
|
|
219
|
+
if (!isRec(value)) {
|
|
220
|
+
return `edit[${index}] must be an object: ${ITEM_SHAPE}.`;
|
|
221
|
+
}
|
|
222
|
+
// WHY: (ticket-75) `value` arrives already folded by `foldAbsentSlots`: an absent optional slot
|
|
223
|
+
// WHY: is gone, nested `text_ref.file` included, so this key set IS the declaration the gate
|
|
224
|
+
// WHY: reads and no second fold site can disagree with the one that stored the item.
|
|
225
|
+
const keys = new Set(Object.keys(value));
|
|
226
|
+
const hasText = keys.has("text");
|
|
227
|
+
const hasRef = keys.has("text_ref");
|
|
228
|
+
if (!isLegalItemKeySet(keys)) {
|
|
229
|
+
if (hasText && hasRef) {
|
|
230
|
+
return (
|
|
231
|
+
`edit[${index}] carries both "text" and "text_ref" fields: choose exactly one payload field per item (${ITEM_SHAPE}). ` +
|
|
232
|
+
`Choice A (literal content): Keep "text" and delete "text_ref" from the JSON object. ` +
|
|
233
|
+
`Choice B (copy/cut served span): keep "text_ref" and delete "text" from the JSON object.`
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
// WHY: (§9.3) an illegal key set is often also MISSING a required key; the unsupported-field
|
|
237
|
+
// WHY: list alone renders blank there, so the refusal must name the missing keys too.
|
|
238
|
+
const payloadKeys = new Set(["anchor_from", "anchor_to", "at", "text", "text_ref"]);
|
|
239
|
+
const offending = [...keys].filter((key) => !payloadKeys.has(key));
|
|
240
|
+
const missing = ["anchor_from", "anchor_to"].filter((key) => !keys.has(key));
|
|
241
|
+
const clauses: string[] = [];
|
|
242
|
+
if (offending.length > 0) clauses.push(`unsupported field(s) ${quoted(offending)}`);
|
|
243
|
+
if (missing.length > 0) clauses.push(`missing required field(s) ${quoted(missing)}`);
|
|
244
|
+
if (!hasText && !hasRef) {
|
|
245
|
+
const named = clauses.length > 0 ? `${clauses.join(";")} — ` : "";
|
|
246
|
+
return (
|
|
247
|
+
`edit[${index}] carries no payload (neither "text" nor "text_ref" fields): ${named}choose exactly one payload field per item (${ITEM_SHAPE}) — ` +
|
|
248
|
+
`supply the "text" field (authored content) OR the "text_ref" field (served span).`
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
return `edit[${index}] has ${clauses.join(";")} (${ITEM_SHAPE}).`;
|
|
252
|
+
}
|
|
253
|
+
const { anchor_from, anchor_to, at, text, text_ref } = value;
|
|
254
|
+
if (typeof anchor_from !== "string" || typeof anchor_to !== "string") {
|
|
255
|
+
return `edit[${index}] "anchor_from"/"anchor_to" must be bare ${HASH_LEN}-char hash anchor strings copied from served output (before │): both anchors are required, so null is not a value here.`;
|
|
256
|
+
}
|
|
257
|
+
if (!isAbsentValue(at)) {
|
|
258
|
+
if (at === "in_place") {
|
|
259
|
+
return `edit[${index}] "at" was "in_place" — the canonical spelling is "in-place": "at" must be "in-place", "before" or "after".`;
|
|
260
|
+
}
|
|
261
|
+
if (typeof at !== "string" || !(AT_SPELLINGS as readonly string[]).includes(at)) {
|
|
262
|
+
return `edit[${index}] "at" must be "in-place", "before" or "after" when present.`;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
if (hasText) {
|
|
266
|
+
if (typeof text !== "string") {
|
|
267
|
+
return `edit[${index}] "text" must be a string with \\n line separators, not an array. An empty string deletes the range.`;
|
|
268
|
+
}
|
|
269
|
+
return undefined;
|
|
270
|
+
}
|
|
271
|
+
if (!isRec(text_ref)) {
|
|
272
|
+
return `edit[${index}] "text_ref" must be an object { anchor_from, anchor_to, file?, mode }.`;
|
|
273
|
+
}
|
|
274
|
+
const refKeys = new Set(Object.keys(text_ref));
|
|
275
|
+
if (!refKeys.has("mode")) {
|
|
276
|
+
return `edit[${index}] "text_ref" requires "mode": "copy" or "cut".`;
|
|
277
|
+
}
|
|
278
|
+
const refBase = new Set(["anchor_from", "anchor_to", "file", "mode"]);
|
|
279
|
+
const refOffending = [...refKeys].filter((key) => !refBase.has(key));
|
|
280
|
+
if (refOffending.length > 0) {
|
|
281
|
+
return `edit[${index}] "text_ref" has unsupported field(s) ${quoted(refOffending)}; it is { anchor_from, anchor_to, file?, mode }.`;
|
|
282
|
+
}
|
|
283
|
+
const { mode } = text_ref;
|
|
284
|
+
if (mode !== "copy" && mode !== "cut") {
|
|
285
|
+
return `edit[${index}] "text_ref" "mode" must be "copy" or "cut": "mode" is required, so null is not a value here.`;
|
|
286
|
+
}
|
|
287
|
+
const refFile = text_ref.file;
|
|
288
|
+
if ("file" in text_ref && typeof refFile !== "string") {
|
|
289
|
+
return `edit[${index}] "text_ref" "file" must be a string naming the served file to read from — omit "file" to reference this file.`;
|
|
290
|
+
}
|
|
291
|
+
// WHY: (§9.2) an empty "file" was admitted and only failed deep in the loader as
|
|
292
|
+
// WHY: `[E_UNSUPPORTED_FILE] Path is a directory: .` — the field-level refusal belongs here.
|
|
293
|
+
if (refFile === "") {
|
|
294
|
+
return `edit[${index}] "text_ref" "file" must name a served file to read from — an empty string is not a path (omit "file" to reference this file).`;
|
|
295
|
+
}
|
|
296
|
+
if (typeof text_ref.anchor_from !== "string" || typeof text_ref.anchor_to !== "string") {
|
|
297
|
+
return `edit[${index}] "text_ref" "anchor_from"/"anchor_to" must be bare ${HASH_LEN}-char hash anchor strings copied from the served output of the file they name: both anchors are required, so null is not a value here.`;
|
|
298
|
+
}
|
|
299
|
+
return undefined;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// WHY: (remediation-2 B3 → ticket-04b) there was previously a second, LEXICAL "same file" test
|
|
303
|
+
// WHY: here that refused foreign `mode: "cut"` at admission. One definition owns the question —
|
|
304
|
+
// WHY: the engine's realpath classification (`sameResolvedPath`, mutation-engine/pipeline.ts) —
|
|
305
|
+
// WHY: and admission stays a pure shape check: a foreign `cut` is ADMITTED and committed as one
|
|
306
|
+
// WHY: correlated transaction (`runCutTransaction`, ADR-0028), witnessed through the entry point
|
|
307
|
+
// WHY: by `edit.wire-contract.test.ts` and `edit.foreign-cut.test.ts`. Path identity on the real
|
|
308
|
+
// WHY: filesystem belongs to the engine seam.
|
|
309
|
+
/**
|
|
310
|
+
* The single admission analyzer shared by `normReq`, `prepareEditArguments` and
|
|
311
|
+
* `assertReq` (ticket-04): every entry point rejects the same inputs with the same message, so the
|
|
312
|
+
* tool seam and the engine seam cannot drift apart.
|
|
313
|
+
*/
|
|
314
|
+
type Admission = { ok: true; request: PreAdmissionRequest } | { ok: false; message: string };
|
|
315
|
+
|
|
316
|
+
function analyzeRequest(input: unknown): Admission {
|
|
317
|
+
if (!isRec(input)) {
|
|
318
|
+
return { ok: false, message: `${EDIT_PAYLOAD_HINT} ${describeReceived(input)}` };
|
|
319
|
+
}
|
|
320
|
+
const rec = input as Record<string, unknown>;
|
|
321
|
+
const rootBase = new Set(["file", "edits", "mode"]);
|
|
322
|
+
const rootOffending = Object.keys(rec).filter((key) => !rootBase.has(key));
|
|
323
|
+
if (rootOffending.length > 0) {
|
|
324
|
+
return {
|
|
325
|
+
ok: false,
|
|
326
|
+
message:
|
|
327
|
+
`Edit request has unsupported field(s) ${quoted(rootOffending)}; it is exactly ` +
|
|
328
|
+
`{ file, edits: [{ anchor_from, anchor_to, text | text_ref[, at] }, ...], mode?: "general" | "literal" }. ` +
|
|
329
|
+
describeReceived(input),
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
let mode: EditMode | undefined;
|
|
333
|
+
if ("mode" in rec && !isAbsentValue(rec.mode)) {
|
|
334
|
+
if (rec.mode !== "general" && rec.mode !== "literal") {
|
|
335
|
+
return {
|
|
336
|
+
ok: false,
|
|
337
|
+
message: `Edit request "mode" must be "general" or "literal" (absent means "general"). ${EDIT_PAYLOAD_HINT}`,
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
mode = rec.mode;
|
|
341
|
+
}
|
|
342
|
+
if (!("file" in rec)) {
|
|
343
|
+
return {
|
|
344
|
+
ok: false,
|
|
345
|
+
message: `Edit request requires "file" (the text file to edit). ${EDIT_PAYLOAD_HINT}`,
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
const sanitized = sanitizePath(rec.file);
|
|
349
|
+
if (sanitized === null) {
|
|
350
|
+
return {
|
|
351
|
+
ok: false,
|
|
352
|
+
message: `Edit request "file" must be a non-empty string path to a text file. ${EDIT_PAYLOAD_HINT}`,
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
if (!("edits" in rec) || !Array.isArray(rec.edits) || rec.edits.length === 0) {
|
|
356
|
+
return {
|
|
357
|
+
ok: false,
|
|
358
|
+
message: `Edit request requires a non-empty "edits" array. ${EDIT_PAYLOAD_HINT}`,
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
const file = sanitized;
|
|
362
|
+
const items = rec.edits as unknown[];
|
|
363
|
+
const failures: string[] = [];
|
|
364
|
+
const edited: EditItem[] = [];
|
|
365
|
+
for (let index = 0; index < items.length; index++) {
|
|
366
|
+
// WHY: (ticket-75) fold BEFORE validation, so the item the gate reads is the item stored.
|
|
367
|
+
const raw = items[index];
|
|
368
|
+
const item = isRec(raw) ? foldAbsentSlots(raw) : raw;
|
|
369
|
+
const refusal = analyzeItem(item, index);
|
|
370
|
+
if (refusal !== undefined) {
|
|
371
|
+
failures.push(refusal);
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
// SAFETY: `analyzeItem` just admitted this raw record — every field it reads validated, so the
|
|
375
|
+
// SAFETY: item has the `EditItem` shape; TypeScript cannot narrow a `Record<string, unknown>` member.
|
|
376
|
+
edited.push(item as unknown as EditItem);
|
|
377
|
+
}
|
|
378
|
+
if (failures.length > 0) {
|
|
379
|
+
return { ok: false, message: `${failures.join(" ")} ${describeReceived(input)}` };
|
|
380
|
+
}
|
|
381
|
+
if (mode !== undefined) return { ok: true, request: { file, edits: edited, mode } };
|
|
382
|
+
return { ok: true, request: { file, edits: edited } };
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function normalizedItemFrom(item: EditItem): NormalizedEditItem {
|
|
386
|
+
const at = item.at ?? "in-place";
|
|
387
|
+
const payload: DesiredContent =
|
|
388
|
+
item.text_ref !== undefined
|
|
389
|
+
? { kind: "reference", span: item.text_ref, mode: item.text_ref.mode }
|
|
390
|
+
: item.text === ""
|
|
391
|
+
? { kind: "empty" }
|
|
392
|
+
: { kind: "literal", text: item.text ?? "" };
|
|
393
|
+
return {
|
|
394
|
+
target: { anchor_from: item.anchor_from, anchor_to: item.anchor_to },
|
|
395
|
+
at,
|
|
396
|
+
payload,
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
export function normReq(input: unknown): NormReqResult {
|
|
401
|
+
const admitted = analyzeRequest(input);
|
|
402
|
+
// SAFETY: input is unvalidated at admission — cast to NormReqResult preserves runtime value for caller validation, narrowed by analyzeRequest refusing invalid shapes
|
|
403
|
+
if (!admitted.ok) return input as NormReqResult;
|
|
404
|
+
const items = admitted.request.edits.map(normalizedItemFrom);
|
|
405
|
+
const record: Record<string, unknown> & { file: string; edits: NormalizedEditItem[] } =
|
|
406
|
+
admitted.request.mode !== undefined
|
|
407
|
+
? { file: admitted.request.file, edits: items, mode: admitted.request.mode }
|
|
408
|
+
: { file: admitted.request.file, edits: items };
|
|
409
|
+
Object.defineProperty(record, normalizedEdit, {
|
|
410
|
+
value: true,
|
|
411
|
+
enumerable: false,
|
|
412
|
+
});
|
|
413
|
+
return record;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
export function prepareEditArguments(args: unknown): Record<string, unknown> {
|
|
417
|
+
const admitted = analyzeRequest(args);
|
|
418
|
+
if (admitted.ok) {
|
|
419
|
+
// SAFETY: `analyzeRequest` built this value from the validated record and admitted it, so the
|
|
420
|
+
// SAFETY: widening back to the record shape the schema accepts is sound; the caller consumes it as validated.
|
|
421
|
+
return admitted.request as unknown as Record<string, unknown>;
|
|
422
|
+
}
|
|
423
|
+
throw new DomainError("E_BAD_PAYLOAD", { message: admitted.message });
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
const ROOT_KS = new Set(["file", "edits", "mode"]);
|
|
427
|
+
|
|
428
|
+
// WHY: bound to the union (§9.12): a list element outside `Placement` fails `pnpm run typecheck`.
|
|
429
|
+
const PLACEMENTS = ["in-place", "before", "after"] as const satisfies readonly Placement[];
|
|
430
|
+
|
|
431
|
+
function isPlacementValue(value: string): value is Placement {
|
|
432
|
+
return (PLACEMENTS as readonly string[]).includes(value);
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
function isNormalizedEditItem(value: unknown): value is NormalizedEditItem {
|
|
436
|
+
if (!isRec(value)) return false;
|
|
437
|
+
const { target, at, payload } = value;
|
|
438
|
+
if (!isRec(target)) return false;
|
|
439
|
+
if (typeof target.anchor_from !== "string" || typeof target.anchor_to !== "string") return false;
|
|
440
|
+
if (typeof at !== "string" || !isPlacementValue(at)) return false;
|
|
441
|
+
if (!isRec(payload)) return false;
|
|
442
|
+
if (payload.kind === "empty") return true;
|
|
443
|
+
if (payload.kind === "literal") return typeof payload.text === "string";
|
|
444
|
+
if (payload.kind === "reference") {
|
|
445
|
+
return (
|
|
446
|
+
isRec(payload.span) &&
|
|
447
|
+
typeof payload.span.anchor_from === "string" &&
|
|
448
|
+
typeof payload.span.anchor_to === "string" &&
|
|
449
|
+
(payload.mode === "copy" || payload.mode === "cut")
|
|
450
|
+
);
|
|
451
|
+
}
|
|
452
|
+
return false;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
export function assertReq(request: unknown): asserts request is NormalizedEditRequest {
|
|
456
|
+
if (!isNormalizedEdit(request)) {
|
|
457
|
+
// WHY: a raw (un-normalized) request reaching assertReq must hit the SAME finite key-set gate
|
|
458
|
+
// WHY: as `prepareEditArguments` — one analyzer, one refusal message, both entry points.
|
|
459
|
+
const admitted = analyzeRequest(request);
|
|
460
|
+
if (!admitted.ok) {
|
|
461
|
+
throw new DomainError("E_BAD_PAYLOAD", { message: admitted.message });
|
|
462
|
+
}
|
|
463
|
+
throw new DomainError("E_BAD_PAYLOAD", {
|
|
464
|
+
message:
|
|
465
|
+
"Edit request reached assertReq without normReq: the engine consumes the normalized shape. " +
|
|
466
|
+
EDIT_PAYLOAD_HINT,
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
rejectUnknownFields(
|
|
471
|
+
request,
|
|
472
|
+
ROOT_KS,
|
|
473
|
+
"Edit request",
|
|
474
|
+
'Pass "file" (the text file to edit), "edits", and optional "mode" ("general" | "literal").',
|
|
475
|
+
);
|
|
476
|
+
|
|
477
|
+
const modeValue = (request as Record<string, unknown>).mode;
|
|
478
|
+
if (modeValue !== undefined && modeValue !== "general" && modeValue !== "literal") {
|
|
479
|
+
throw new DomainError("E_BAD_PAYLOAD", {
|
|
480
|
+
message:
|
|
481
|
+
'Edit request "mode" must be "general" or "literal" (absent means "general"). ' +
|
|
482
|
+
EDIT_PAYLOAD_HINT,
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
// WHY: the file was answered at admission (analyzeRequest); the narrowed type carries it here.
|
|
487
|
+
if (!Array.isArray(request.edits) || request.edits.length === 0) {
|
|
488
|
+
throw new DomainError("E_BAD_PAYLOAD", {
|
|
489
|
+
message: 'Edit request requires a non-empty "edits" array.',
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
for (let index = 0; index < request.edits.length; index++) {
|
|
494
|
+
const item = request.edits[index];
|
|
495
|
+
if (!isNormalizedEditItem(item)) {
|
|
496
|
+
throw new DomainError("E_BAD_PAYLOAD", {
|
|
497
|
+
message: `Edit request edits[${index}] must be { target, at, payload } with exactly one payload: text content, a served-span reference with mode "copy" or "cut", or a deletion (no content).`,
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
// WHY: (ticket-04 item (i), remediation-2 B4) the wire folds `"text": ""` into the deletion
|
|
501
|
+
// WHY: payload, so this guard is a defense for direct `assertReq` callers only; the
|
|
502
|
+
// WHY: enforcement point for the engine seam is the parse guard in
|
|
503
|
+
// WHY: `mutation-engine/pipeline.ts` (`parseEdits`, same message), which `execute()` cannot
|
|
504
|
+
// WHY: bypass. Naming the wire field `"text"` keeps the model-actionable wording.
|
|
505
|
+
if (item.payload.kind === "literal" && item.payload.text === "") {
|
|
506
|
+
throw new DomainError("E_BAD_PAYLOAD", {
|
|
507
|
+
message: `Edit request edits[${index}] "text" must carry at least one line; "text": "" is the deletion payload. Nothing was written.`,
|
|
508
|
+
});
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
}
|
package/src/prompts-bundled.ts
CHANGED
|
@@ -21,6 +21,16 @@ export const BUNDLED_PROMPTS: Readonly<Record<string, string>> = {
|
|
|
21
21
|
- apply_patch: a rejection writes nothing; retry from the served \`HASH│content\` rows without another \`read\`.
|
|
22
22
|
- apply_patch: success returns fresh anchors for the changed lines; a patch carries only the changed rows, so a new file or an every-line rewrite stays with \`write\`.`,
|
|
23
23
|
"apply-patch.md": `Change an existing file with \`apply_patch\`; it is the default for every change to an existing file, including a one-line change. \`write\` is only for a new file or for a rewrite where every line changes; a partial change is never a whole-file replacement. Pass the complete patch as \`input\`. When this session already served the file — through \`read\`, \`grep\`, a \`bash\` view, or a previous \`apply_patch\` result — every hunk MUST be an identity hunk on a served row: reuse the bare anchor before \`│\` (\`@@<anchor>\` to replace that row, \`@@<from>-<to>\` to replace a span whose anchors you hold), and add only the changed \`+\` lines rather than re-emitting rows you are not changing. Anchors already in hand need no re-read: patch them directly instead of calling \`read\` again. A fragment hunk (\`@@\` or \`@@ <context>\` matched by file text) is legal only for a file or region this session never served; if the file was served, a fragment hunk is the wrong tool even when the text matches, because it discards the anchor check that proves you edited the version you actually saw.`,
|
|
24
|
+
"edit-guidelines.md": `- edit: one call = one file and one transaction; N changes in that file are N items in the same call, and a different file is a different call.
|
|
25
|
+
- edit: every item carries exactly one payload — \`text\` (literal content; \`""\` deletes the range) or \`text_ref\` (\`mode: "copy"\` or \`"cut"\`); never both, never neither.
|
|
26
|
+
- edit: anchors are the bare \`{{HASH_LEN}}\` characters before \`│\` in served output — never the whole row, never a line number.
|
|
27
|
+
- edit: both anchors are inclusive; \`at\` is \`in-place\` by default, while \`before\`/\`after\` insert at the boundary and require a single-line resolved target.
|
|
28
|
+
- edit: \`text_ref\` copies a served span's bytes; \`"cut"\` also retires the source lines, and \`text_ref.file\` may name another served file as that source.
|
|
29
|
+
- edit: anchors already in hand need no re-read — a rejection serves the current rows back, so repair from the \`HASH│content\` rows instead of guessing.
|
|
30
|
+
- edit: change only what the task changes — one item per intended range, and unchanged rows stay out of the payload.
|
|
31
|
+
- edit: a stale or unknown anchor, an overlapping range, or a payload reproducing served rows in \`general\` mode rejects the whole call and writes nothing; \`mode: "literal"\` declares reproduced rows as intended content.
|
|
32
|
+
- edit: \`write\` is the whole-file path — a new file or an every-line rewrite stays with \`write\`, never an edit item.`,
|
|
33
|
+
"edit.md": `Change a range of lines in one text file with hash anchors: pass \`file\` plus \`edits\`, one item per change. Each item names two inclusive bare anchors from served rows (\`anchor_from\`, \`anchor_to\`), exactly one payload — \`text\` for the replacement content (\`""\` deletes the range) or \`text_ref\` for a served span (\`mode: "copy"\` re-inserts its bytes, \`"cut"\` also retires them) — and optional \`at\` (\`in-place\` by default, \`before\`/\`after\` for a single-line target). One call edits one file; \`text_ref.file\` may name another served file as the copy/cut source. Anchors are the bare \`{{HASH_LEN}}\` characters before \`│\` in served output. A rejected call writes nothing.`,
|
|
24
34
|
"read-guidelines.md": `- read: call it for content the tool has never served you; a bash view or an auto-read already served the file, so \`apply_patch\` can use those rows.
|
|
25
35
|
- read: batch several disjoint ranges in ONE call with \`windows\` — an offset/limit range, or \`around_anchor\` plus \`radius\` around a line this session served.
|
|
26
36
|
- read: pass \`mode: "verbatim"\` when you will not \`apply_patch\` the file (config, docs, a README, skill files); otherwise omit it so the rows carry anchors.
|
|
@@ -28,10 +38,6 @@ export const BUNDLED_PROMPTS: Readonly<Record<string, string>> = {
|
|
|
28
38
|
- read: read several files with parallel \`read\` calls, one file per call.
|
|
29
39
|
- read: PNG/JPG/GIF/WebP files return as an image attachment for multimodal models; binary files and directories are refused.`,
|
|
30
40
|
"read.md": `Reads a UTF-8 file as \`HASH│content\` rows in served mode; each row's anchor is the \`apply_patch\` identity anchor for that line, and only the \`{{HASH_LEN}}\` characters before \`│\` are the anchor. Pass \`mode: "verbatim"\` for plain text with no anchors when you will not apply_patch; verbatim is not capped by line budget. Batch disjoint ranges in one call with \`windows\` (offset/limit or \`around_anchor\`).`,
|
|
31
|
-
"undo-last-edit-guidelines.md": `- undo_last_edit: reverts the most recent \`apply_patch\` batch that touched the file at \`path\`, and every member of that batch: text hunks plus file lifecycle actions (add/delete/move). The exception is a foreign \`cut\`: undo then restores the source file too. The file must still hold the edited bytes. An out-of-band write makes the call fail with \`E_UNDO_STALE\`, and the file stays byte-identical. Call it as soon as a result is bad.
|
|
32
|
-
- undo_last_edit: a \`write\` to the file, or a later \`apply_patch\` batch, replaces the undo entry. A read, a bash view or an out-of-band write leaves the entry in place. An apply_patch result is bad when its diff shows \`-HASH│\` rows for lines you meant to keep. Examples are a closing brace, an import, or a declaration.`,
|
|
33
|
-
"undo-last-edit-snippet.md": `Undo the last \`apply_patch\` batch on the file at \`path\``,
|
|
34
|
-
"undo-last-edit.md": `Undo the last \`apply_patch\` batch that touched the file at \`path\`, reverting the whole batch — every text hunk plus file lifecycle actions (add/delete/move) — to its previous state. Use when an \`apply_patch\` produced incorrect results (e.g., wrong content, duplicated lines, broken syntax). The file must be unchanged since that batch.`,
|
|
35
41
|
"write-guidelines.md": `- write: the content is the complete file; a partial change stays an \`apply_patch\` identity hunk, even when the whole file is already in context.
|
|
36
42
|
- write: never paste served \`HASH│\` rows into the content; a line that reproduces a served row is refused as a served hash echo.`,
|
|
37
43
|
"write.md": `Read a file before overwriting it with \`write\`. \`write\` replaces the whole file: use it for a new file, or for a rewrite where every line changes. For a change to part of an existing file, use \`apply_patch\` identity hunks on the served rows instead.`,
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import type { ToolDefinition } from "@deepseek-ai/dsh-tools";
|
|
2
|
-
import type { ToolDependencies } from "../contracts.js";
|
|
3
|
-
/** dsh tool name; `undo_last_edit` is plugin-owned (no preset shadow). */
|
|
4
|
-
export declare const UNDO_TOOL_NAME = "undo_last_edit";
|
|
5
|
-
/**
|
|
6
|
-
* The core's prompt text, kept in sync with `prompts/undo-last-edit.md`. Exported only so the drift
|
|
7
|
-
* test can pin it to the file the guidance section loads; the tool itself uses the inlined copy.
|
|
8
|
-
*/
|
|
9
|
-
export declare const UNDO_DESCRIPTION: string;
|
|
10
|
-
/**
|
|
11
|
-
* Build the dsh `undo_last_edit` tool for one agent install.
|
|
12
|
-
* @param deps - the host seams this tool may touch; `sandbox` advertises and resolves escalation.
|
|
13
|
-
* @returns a registry-ready dsh tool definition named `undo_last_edit`.
|
|
14
|
-
*/
|
|
15
|
-
export declare function buildUndoTool(deps: ToolDependencies): ToolDefinition;
|