dsh-hashline-edit 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Post-edit syntax health: parse the committed text and report only NEWLY introduced errors.
3
+ *
4
+ * WHY this exists: a hash-anchored range edit can match both anchors, commit, and still swallow
5
+ * or leave one extra brace — an off-by-one at a boundary. Nothing in the anchor machinery can see
6
+ * that, and waiting for a compiler wastes a whole tool round. A tree parse is 1-3 ms and turns that
7
+ * silently-wrong case into a same-call warning the model can self-heal from.
8
+ *
9
+ * The signal is deliberately narrow. It compares the error-node count of the file BEFORE the edit
10
+ * with the count AFTER it and speaks only when the edit ADDED errors to a previously clean file.
11
+ * A file that arrives broken stays silent (no baseline to attribute a new error to) and a clean
12
+ * file stays clean. No grammar, no wasm host, or an abort all mean say nothing — this seam never
13
+ * blocks, never fails a call, and never invents a diagnosis.
14
+ *
15
+ * @module dsh-hashline-edit/syntax-health
16
+ */
17
+ import type { FileIO } from "./contracts.js";
18
+ import type { GrammarHandle } from "../src/read-expansion/ast-span.js";
19
+ /** The grammar key for one path, or undefined when no grammar covers its extension. */
20
+ export declare function grammarForPath(path: string): string | undefined;
21
+ export interface SyntaxHealthOptions {
22
+ /** Override the grammar lookup (tests). */
23
+ readonly grammarFor?: (path: string) => Promise<GrammarHandle | undefined>;
24
+ /** Abort signal from the hosting tool call. */
25
+ readonly signal?: AbortSignal | undefined;
26
+ }
27
+ /**
28
+ * Diagnose one committed edit.
29
+ *
30
+ * @returns a one-line model-facing warning when this edit INTRODUCED parse errors, else undefined.
31
+ * Never throws: every internal failure is no signal.
32
+ */
33
+ export declare function syntaxWarningForEdit(path: string, before: string, after: string, options?: SyntaxHealthOptions): Promise<string | undefined>;
34
+ /** A pre-edit snapshot: the absolute path and the text the file held before the write. */
35
+ export interface SyntaxBaseline {
36
+ readonly path: string;
37
+ readonly text: string;
38
+ }
39
+ /**
40
+ * Snapshot one file's text BEFORE its edit commits, when a grammar covers its extension.
41
+ *
42
+ * WHY the extension gate comes first: a path no grammar parses never needs a read, so an edit to a
43
+ * lockfile or a config pays nothing for this seam.
44
+ * @param io - the call's filesystem seam.
45
+ * @param path - the absolute path the edit will write.
46
+ * @param signal - caller cancellation.
47
+ * @returns the baseline, or undefined when the path is unsupported, unreadable or already aborted.
48
+ */
49
+ export declare function readSyntaxBaseline(io: Pick<FileIO, "read">, path: string, signal?: AbortSignal): Promise<SyntaxBaseline | undefined>;
50
+ /**
51
+ * Re-read the committed file and diagnose the edit against its baseline.
52
+ *
53
+ * Split from {@link syntaxWarningForEdit} so the pre-edit read happens before the write and the
54
+ * post-edit read happens after it: one function cannot straddle the mutation it measures.
55
+ * @param io - the call's filesystem seam.
56
+ * @param baseline - the snapshot {@link readSyntaxBaseline} took before the write.
57
+ * @param options - grammar override (tests) and caller cancellation.
58
+ * @returns the model-facing warning, or undefined when the edit introduced no parse error.
59
+ */
60
+ export declare function syntaxWarningAfterEdit(io: Pick<FileIO, "read">, baseline: SyntaxBaseline, options?: SyntaxHealthOptions): Promise<string | undefined>;
@@ -106,4 +106,14 @@ export declare function diffResultView(title: string, result: {
106
106
  * @returns the same object, typed as the declared output.
107
107
  */
108
108
  export declare function toCanonicalValue(result: ToolResultValue): ToolResultOutput;
109
+ /**
110
+ * Append one model-facing warning to a settled result.
111
+ *
112
+ * The warning reaches both channels the envelope already exposes: the text the model reads and the
113
+ * `warnings` array a presenter and the metrics recorder inspect. Every other byte is preserved.
114
+ * @param result - the canonical value a tool is about to return.
115
+ * @param warning - the line to append, or undefined to return the result untouched.
116
+ * @returns the same result when no warning applies; a copy carrying the warning otherwise.
117
+ */
118
+ export declare function withWarning(result: ToolResultOutput, warning: string | undefined): ToolResultOutput;
109
119
  export {};
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Read an asset that ships inside this package.
3
+ *
4
+ * WHY this module sits one level below the package root: `new URL("../x", import.meta.url)` is
5
+ * resolved from THIS file, so the root is one level up both in the source tree (`src/`) and in the
6
+ * published bundle (`lib/index.js`), where every `src/` module is inlined and `import.meta.url` is
7
+ * the bundle's own URL. A helper at any other depth would resolve correctly in one of the two and
8
+ * silently miss in the other.
9
+ *
10
+ * @param relativePath - path from the package root, e.g. `grammars/typescript-...wasm`.
11
+ * @returns the file's bytes, or undefined when it is absent (a partial install, a stripped build).
12
+ */
13
+ export declare function readBundledAsset(relativePath: string): Uint8Array | undefined;
@@ -120,7 +120,8 @@ export interface NEdit {
120
120
  export type HTEdit = {
121
121
  text: string;
122
122
  anchor_from: string;
123
- anchor_to: string;
123
+ /** Last line of the target range; omitted means a single-line target — the line `anchor_from` names. */
124
+ anchor_to?: string;
124
125
  placement?: EditPlacement;
125
126
  source?: {
126
127
  anchor_from: string;
@@ -16,6 +16,10 @@ export type DesiredContent = {
16
16
  mode: "copy" | "cut";
17
17
  } | {
18
18
  kind: "empty";
19
+ } | {
20
+ kind: "insert";
21
+ side: "before" | "after";
22
+ text: string;
19
23
  };
20
24
  export type NormalizedEditItem = {
21
25
  target: {
@@ -28,7 +28,11 @@ export declare const _placementVocabularyAgreement: [
28
28
  Placement extends EditPlacement ? true : never,
29
29
  EditPlacement extends Placement ? true : never
30
30
  ];
31
- /** The anchor pair an item targets — placement and payload are relative to its resolved span. */
31
+ /**
32
+ * The anchor pair an item targets — placement and payload are relative to its resolved span. A
33
+ * single-line target names its one line in both bounds (`anchor_from === anchor_to`): the engine
34
+ * keeps the closed pair so nothing downstream has to branch on an absent bound.
35
+ */
32
36
  type AnchorSpan = {
33
37
  anchor_from: string;
34
38
  anchor_to: string;
@@ -42,6 +46,10 @@ type DesiredContent = {
42
46
  mode: "copy" | "cut";
43
47
  } | {
44
48
  kind: "empty";
49
+ } | {
50
+ kind: "insert";
51
+ side: "before" | "after";
52
+ text: string;
45
53
  };
46
54
  type NormalizedEditItem = {
47
55
  target: AnchorSpan;
@@ -6,7 +6,9 @@
6
6
  * cache file, so a manifest bump cannot keep serving the previous grammar.
7
7
  *
8
8
  * WHY nothing here is imported as a module: the runtime (`web-tree-sitter`) is the only dependency;
9
- * grammar `.wasm` files are fetched on first use and are never part of the published package.
9
+ * WHY nothing here is imported as a module: the runtime (`web-tree-sitter`) is the only dependency;
10
+ * the pinned `.wasm` files ship inside this package under `grammars/` (ADR-0026) and are fetched only
11
+ * when that copy is missing, so a first read parses offline and never waits on the network.
10
12
  */
11
13
  export interface GrammarManifestEntry {
12
14
  readonly language: string;
@@ -6,7 +6,7 @@
6
6
  * the wasm host. `hasWebTreeSitterRuntime` is the cheap preflight; grammar bytes are only fetched
7
7
  * after it answered yes, and a resolution failure is the same answer as an offline grammar.
8
8
  *
9
- * WHY the runtime is the only dependency: grammars are fetched bytes, so the package grows only by
9
+ * WHY the runtime is the only DEPENDENCY: grammar bytes ship in this package (`grammars/`, ADR-0026)
10
10
  * the wasm host, never by a grammar set. `Language.load` accepts the verified bytes directly, so no
11
11
  * second disk read is needed after the cache check.
12
12
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-hashline-edit",
3
- "version": "0.4.2",
3
+ "version": "0.5.0",
4
4
  "description": "Hash-anchored read/apply_patch/edit tools for DeepSeek Harness (dsh). Every line gets a unique 3- or 4-char hash (A-Za-z0-9, configurable) that stays stable across edits; apply_patch and the anchored range edit tool are the file-mutation entry points, each committing its whole batch as one transaction.",
5
5
  "keywords": [
6
6
  "anchors",
@@ -33,7 +33,8 @@
33
33
  "prompts",
34
34
  "src",
35
35
  "README.md",
36
- "LICENSE"
36
+ "LICENSE",
37
+ "grammars"
37
38
  ],
38
39
  "type": "module",
39
40
  "main": "./lib/index.js",
@@ -1,8 +1,10 @@
1
1
  - edit: one call targets one `file` in one transaction — batch all N changes to that file as N items in the same call, and use parallel `edit` calls for different target files.
2
- - edit: every item carries exactly one payload — `text` (literal content; `""` deletes the range when `at` is `"in-place"`, and is a no-op for `"before"`/`"after"`) or `text_ref` (with required non-null `mode`: `"copy"` re-inserts the served span's bytes, `"cut"` also deletes the source lines); never both, never neither.
2
+ - edit: every item carries exactly one payload — `text` (literal content; `""` deletes the range when `at` is `"in-place"`, and is a no-op for `"before"`/`"after"`), `text_ref` (with required non-null `mode`: `"copy"` re-inserts the served span's bytes, `"cut"` also deletes the source lines), or one of the insertion slots `after`/`before` (the lines to place immediately below/above `anchor_from`); never two, never none.
3
3
  - edit: when `text_ref` uses `mode: "cut"` (same file or another served file via `text_ref.file`), the source lines are deleted automatically in the same correlated transaction — never send a second `edit` to delete the source span.
4
- - edit: anchors are strictly the bare `{{HASH_LEN}}` characters before `│` in served `HASH│content` rows — never a line number, full row, or null. Both `anchor_from` and `anchor_to` are required and inclusive; for a single-line target (mandatory when `at` is `"before"` or `"after"`), pass the identical hash for both (`anchor_from === anchor_to`).
4
+ - edit: anchors are strictly the bare `{{HASH_LEN}}` characters before `│` in served `HASH│content` rows — never a line number, full row, or null. `anchor_from` is always required and names the first line of the range; `anchor_to` is optional and names the last line — omit it to edit the single line `anchor_from` names (the range is single-line without it, which is mandatory when `at` is `"before"` or `"after"`), and a `text_ref` span always names both bounds.
5
5
  - edit: change only what the task changes — one item per intended range, keeping unchanged boundary rows and `HASH│` prefixes out of `text`.
6
6
  - edit: a stale or unknown anchor, or an overlapping range, rejects the whole call and writes nothing. A `text` payload echoing served rows in default top-level `mode: "general"` is refused (`E_SUSPICIOUS_TEXT`); prefer `text_ref` to duplicate or move served spans, or set top-level `mode: "literal"` when `text` must intentionally reproduce served lines.
7
7
  - edit: anchors already in context (from `read`, an auto-read, or an intercepted shell view that output `HASH│content` rows) need no re-read; an anchor rejection serves the current `HASH│content` rows back, so repair directly from those rows instead of re-reading or guessing.
8
+ - edit: to insert without touching the anchor line, use `after` or `before` — `{ "anchor_from": "aB3", "after": " x: 1," }` adds one line below; the payload is bare file content and never restates the anchor line (`at` + `text` is the older spelling of the same insertion and still accepted).
9
+ - edit: a successful call that turns a clean file into one with parse errors appends a `[W_SYNTAX]` warning naming the damaged line; the write already landed, so re-read around that line and correct the range instead of repeating the call.
8
10
  - edit: `write` is the whole-file path — use `write` to create a new file or replace every line, never `edit`.
package/prompts/edit.md CHANGED
@@ -1 +1 @@
1
- Change one or more line ranges in one target text file with hash anchors: pass `file`, `edits` (one item per change), and optional top-level `mode` (`"general"` by default, or `"literal"`). Each item requires two inclusive bare `{{HASH_LEN}}`-character anchors from before `│` in served rows (`anchor_from`, `anchor_to`; pass `anchor_from === anchor_to` for a single line), optional `at` (`"in-place"` by default; `"before"` or `"after"` inserts at a single-line target), and exactly one payload — `text` for replacement content (`""` deletes the span when `at` is `"in-place"`, and is a no-op with `"before"`/`"after"`) or `text_ref` (`{ anchor_from, anchor_to, file?, mode: "copy" | "cut" }`, where required `mode` `"copy"` re-inserts the served span's bytes and `"cut"` also deletes the source lines). One call targets one `file`; only `text_ref.file` may reference another served file as the copy/cut source (with `"cut"` deleting those source lines in the same correlated transaction). A rejected call writes nothing.
1
+ Change one or more line ranges in one target text file with hash anchors: pass `file`, `edits` (one item per change), and optional top-level `mode` (`"general"` by default, or `"literal"`). Each item names one inclusive bare `{{HASH_LEN}}`-character anchor from before `│` in served rows (`anchor_from`), an optional second one closing a multi-line range (`anchor_to` — omit it to edit the single line `anchor_from` names; pass the identical hash to spell a single line explicitly), optional `at` (`"in-place"` by default; `"before"` or `"after"` inserts at a single-line target), and exactly one payload — `text` for replacement content (`""` deletes the span when `at` is `"in-place"`, and is a no-op with `"before"`/`"after"`) or `text_ref` (`{ anchor_from, anchor_to, file?, mode: "copy" | "cut" }`, whose two bounds are always required, where required `mode` `"copy"` re-inserts the served span's bytes and `"cut"` also deletes the source lines). One call targets one `file`; only `text_ref.file` may reference another served file as the copy/cut source (with `"cut"` deleting those source lines in the same correlated transaction). A rejected call writes nothing. Two shortcuts cover the common pure insertions: `after` and `before` each carry the exact lines to place immediately below or above the single line `anchor_from` names, instead of spelling `at` plus `text`. An item still carries exactly one payload — `text`, `text_ref`, `after`, or `before`.
@@ -0,0 +1,23 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ /**
4
+ * Read an asset that ships inside this package.
5
+ *
6
+ * WHY this module sits one level below the package root: `new URL("../x", import.meta.url)` is
7
+ * resolved from THIS file, so the root is one level up both in the source tree (`src/`) and in the
8
+ * published bundle (`lib/index.js`), where every `src/` module is inlined and `import.meta.url` is
9
+ * the bundle's own URL. A helper at any other depth would resolve correctly in one of the two and
10
+ * silently miss in the other.
11
+ *
12
+ * @param relativePath - path from the package root, e.g. `grammars/typescript-...wasm`.
13
+ * @returns the file's bytes, or undefined when it is absent (a partial install, a stripped build).
14
+ */
15
+ export function readBundledAsset(relativePath: string): Uint8Array | undefined {
16
+ try {
17
+ return readFileSync(new URL(`../${relativePath}`, import.meta.url));
18
+ } catch {
19
+ // SAFETY: a missing or unreadable asset is "not bundled", never a failure: every caller has a
20
+ // SAFETY: fallback (a cached copy, a fetch, or simply no parse) and must stay silent.
21
+ return undefined;
22
+ }
23
+ }
@@ -207,7 +207,8 @@ export interface NEdit {
207
207
  export type HTEdit = {
208
208
  text: string;
209
209
  anchor_from: string;
210
- anchor_to: string;
210
+ /** Last line of the target range; omitted means a single-line target — the line `anchor_from` names. */
211
+ anchor_to?: string;
211
212
  placement?: EditPlacement;
212
213
  source?: { anchor_from: string; anchor_to: string; retire: boolean };
213
214
  };
@@ -371,9 +372,9 @@ function assertItem(edit: Record<string, unknown>): void {
371
372
  '"text" must be a string with \\n line separators, not an array. Multiple lines belong in one string, such as "line1\\nline2". An empty string deletes a range. Nothing was written.',
372
373
  });
373
374
  }
374
- if (typeof edit.anchor_from !== "string" || typeof edit.anchor_to !== "string") {
375
+ if (typeof edit.anchor_from !== "string") {
375
376
  throw new DomainError("E_BAD_PAYLOAD", {
376
- message: `The edit requires "anchor_from" and "anchor_to" anchor strings (bare ${HASH_LEN}-char hashes from served output). Nothing was written.`,
377
+ message: `The edit requires an "anchor_from" anchor string (a bare ${HASH_LEN}-char hash from served output). Nothing was written.`,
377
378
  });
378
379
  }
379
380
  // SAFETY: (ticket-04 item (iii)) this is the ONLY fail-closed check on the internal placement
@@ -425,7 +426,10 @@ export function resEdit(edit: HTEdit): HEdit {
425
426
  assertItem(edit as Record<string, unknown>);
426
427
 
427
428
  const editLines = parseText(edit.text);
428
- const bounds = [edit.anchor_from, edit.anchor_to].map((ref) => {
429
+ // WHY: `anchor_to` is optional: an absent bound makes the target the single line `anchor_from`
430
+ // WHY: names, which is what a single-line edit always meant — the closed pair is built here so
431
+ // WHY: `hash_bounds` stays a total two-element tuple for every consumer.
432
+ const bounds = [edit.anchor_from, edit.anchor_to ?? edit.anchor_from].map((ref) => {
429
433
  const trimmed = ref.trim();
430
434
  if (trimmed.includes("\n")) {
431
435
  const hash = firstHashFromBlock(trimmed);
@@ -15,7 +15,10 @@ type Placement = "in-place" | "before" | "after";
15
15
  export type DesiredContent =
16
16
  | { kind: "literal"; text: string }
17
17
  | { kind: "reference"; span: SpanRef; mode: "copy" | "cut" }
18
- | { kind: "empty" };
18
+ | { kind: "empty" }
19
+ // WHY: (ADR-0025) a pure insertion carries its own side; it is never folded into `literal` +
20
+ // WHY: `at`, so nothing downstream can turn an insert into a rewrite of the anchor line.
21
+ | { kind: "insert"; side: "before" | "after"; text: string };
19
22
 
20
23
  export type NormalizedEditItem = {
21
24
  target: { anchor_from: string; anchor_to: string };
@@ -68,7 +68,7 @@ import { loadHashStore } from "../hash-store.js";
68
68
  import { snapshotIOFor, upsertSnapshotFor, snapshotHashFor } from "../snapshot-store";
69
69
  import { applyEdit } from "../hashline/apply.js";
70
70
  import { buildNeverServedEditHint } from "../served-session/serve-render.js";
71
- import { resEdit, type HEdit, type NEdit } from "../hashline/resolve.js";
71
+ import { resEdit, type EditPlacement, type HEdit, type NEdit } from "../hashline/resolve.js";
72
72
  import { defaultHashIdentity, lineHashes } from "../hashline/hash-identity.js";
73
73
  import { HASH_LEN } from "../hashline/alphabet.js";
74
74
  import { denseServeRows, type ResolvedRange } from "../served-session/serve-render.js";
@@ -362,6 +362,10 @@ function replacementTextForPayload(payload: DesiredContent): string {
362
362
  return `span:${payload.span.anchor_from}..${payload.span.anchor_to}:${payload.mode === "cut" ? "move" : "copy"}`;
363
363
  case "empty":
364
364
  return "";
365
+ // WHY: (ADR-0025) an insertion is identified by its side and its own lines, never by the anchor
366
+ // WHY: line it sits next to — that line is not part of this item's content.
367
+ case "insert":
368
+ return `${payload.side}:${payload.text}`;
365
369
  default:
366
370
  return assertNever(payload);
367
371
  }
@@ -394,6 +398,9 @@ function parseEdits(
394
398
  const payload = item.payload;
395
399
  let text: string;
396
400
  let source: { anchor_from: string; anchor_to: string; retire: boolean } | undefined;
401
+ // WHY: (ADR-0025) an insertion sets this instead of `item.at`; both feed the same
402
+ // WHY: zero-width splice, and `item.at` stays the placement of a resolved RANGE.
403
+ let placement: EditPlacement | undefined;
397
404
  switch (payload.kind) {
398
405
  case "literal":
399
406
  // WHY: (remediation-2 B4) the min-line guard must sit where the destructive behaviour is
@@ -441,6 +448,14 @@ function parseEdits(
441
448
  }
442
449
  text = "";
443
450
  break;
451
+ // WHY: (ADR-0025) a pure insertion reuses the engine's zero-width placement splice: the
452
+ // WHY: payload lines ARE the content and the anchor line is only the zero-width boundary.
453
+ // WHY: Because `content_lines` never contains the anchor line, no splice path can rewrite
454
+ // WHY: it — the "insert turned into a re-typed boundary row" failure is not representable.
455
+ case "insert":
456
+ text = payload.text;
457
+ placement = payload.side;
458
+ break;
444
459
  default:
445
460
  assertNever(payload);
446
461
  }
@@ -450,6 +465,7 @@ function parseEdits(
450
465
  anchor_to: item.target.anchor_to,
451
466
  text,
452
467
  ...(item.at !== "in-place" ? { placement: item.at } : {}),
468
+ ...(placement !== undefined ? { placement } : {}),
453
469
  ...(source ? { source } : {}),
454
470
  }),
455
471
  });
@@ -19,17 +19,22 @@ type SpanRef = {
19
19
  };
20
20
 
21
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`).
22
+ * Wire item (ticket-04): exactly one payload per item — `text`, `text_ref`, or one insertion slot
23
+ * (`after` / `before`, ADR-0025) — over the inclusive anchor pair, with optional `at` placement.
24
+ * There is no `op` field and no verbs: the key set IS the vocabulary (ADR-0007 line 26; content
25
+ * comes from the copy of another served file, which the wire expresses as `text_ref.file`).
26
26
  */
27
27
  type EditItem = {
28
28
  anchor_from: string;
29
- anchor_to: string;
29
+ /** Last line of the target range. Omitted (or null) means a single-line target: the range is "anchor_from" alone. */
30
+ anchor_to?: string;
30
31
  at?: "in-place" | "before" | "after";
31
32
  text?: string;
32
33
  text_ref?: SpanRef;
34
+ /** Insertion content placed immediately AFTER the target line; the line itself is never rewritten. */
35
+ after?: string;
36
+ /** Insertion content placed immediately BEFORE the target line; the line itself is never rewritten. */
37
+ before?: string;
33
38
  };
34
39
 
35
40
  type EditMode = "general" | "literal";
@@ -54,14 +59,21 @@ export const _placementVocabularyAgreement: [
54
59
  EditPlacement extends Placement ? true : never,
55
60
  ] = [true, true];
56
61
 
57
- /** The anchor pair an item targets — placement and payload are relative to its resolved span. */
62
+ /**
63
+ * The anchor pair an item targets — placement and payload are relative to its resolved span. A
64
+ * single-line target names its one line in both bounds (`anchor_from === anchor_to`): the engine
65
+ * keeps the closed pair so nothing downstream has to branch on an absent bound.
66
+ */
58
67
  type AnchorSpan = { anchor_from: string; anchor_to: string };
59
68
 
60
69
  type DesiredContent =
61
70
  | { kind: "literal"; text: string }
62
71
  | { kind: "reference"; span: SpanRef; mode: "copy" | "cut" }
63
- | { kind: "empty" };
64
-
72
+ | { kind: "empty" }
73
+ // WHY: (ADR-0025) an insertion is its own payload kind, not a `text` plus a placement: the
74
+ // WHY: model names only where the new lines go and never restates the anchor line, so this
75
+ // WHY: kind is structurally incapable of rewriting the line it is anchored to.
76
+ | { kind: "insert"; side: "before" | "after"; text: string };
65
77
  type NormalizedEditItem = {
66
78
  target: AnchorSpan;
67
79
  at: Placement;
@@ -97,17 +109,20 @@ function isNormalizedEdit(input: unknown): input is Record<string, unknown> {
97
109
  }
98
110
 
99
111
  const ITEM_SHAPE =
100
- "an item is exactly { anchor_from, anchor_to, text[, at] } or { anchor_from, anchor_to, text_ref[, at] }";
112
+ "an item is exactly { anchor_from, anchor_to?, text[, at] }, { anchor_from, anchor_to?, text_ref[, at] }, or { anchor_from, anchor_to?, after | before }";
101
113
 
102
114
  const EDIT_PAYLOAD_HINT =
103
115
  "Edit must be called with exactly one payload per item, and each call edits ONE file. Use the canonical payload " +
104
116
  '{"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).';
117
+ '"file" is the text file to edit (a non-empty string, never a directory); each item names the bare-' +
118
+ `${HASH_LEN}-char anchor "anchor_from" (the first line of the range, and the whole range of a single-line edit), an optional ` +
119
+ 'second bare anchor "anchor_to" (the last line of a multi-line range; omit it to edit "anchor_from" alone) and exactly one ' +
120
+ 'payload — "text" (bare replacement content; an empty string deletes the range), "text_ref" ' +
121
+ '({ anchor_from, anchor_to, file?, mode (required): "copy" | "cut" } — the served span\'s bytes, whose two bounds are ' +
122
+ 'always required, and whose "file" may name another served file as the copy/cut source), or an insertion slot ' +
123
+ '"after"/"before" (the exact lines to insert below/above the single anchor line, which is never restated); optional ' +
124
+ '"at" is "in-place" (default), "before" or "after" (single-line resolved target only); optional "mode" is ' +
125
+ '"general" (default, reproduced served rows are refused) or "literal" (declared literal content).';
111
126
  function describeReceived(input: unknown): string {
112
127
  if (input === undefined) return "Received no arguments.";
113
128
  if (input === null) return "Received null.";
@@ -165,15 +180,25 @@ function sanitizePath(value: unknown): string | null {
165
180
  }
166
181
 
167
182
  // 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.
183
+ // WHY: one of the eight shapes — { anchor_from, anchor_to?, text } and { anchor_from, anchor_to?,
184
+ // WHY: text_ref }, each optionally plus `at` — set EQUALITY, never superset, so a legacy key, an
185
+ // WHY: `op` field, both payloads or neither payload all refuse with the offending keys named.
186
+ // WHY: (ADR-0024) `anchor_to` is optional in every shape: one anchor means a single-line target.
187
+ // WHY: The vocabulary stays "anchor_from plus an optional closing anchor_to, one payload, optional
188
+ // WHY: placement" and one call edits one file.
172
189
  const ITEM_KEY_SETS: readonly (readonly string[])[] = [
173
190
  ["anchor_from", "anchor_to", "text"],
191
+ ["anchor_from", "text"],
174
192
  ["anchor_from", "anchor_to", "at", "text"],
193
+ ["anchor_from", "at", "text"],
175
194
  ["anchor_from", "anchor_to", "text_ref"],
195
+ ["anchor_from", "text_ref"],
176
196
  ["anchor_from", "anchor_to", "at", "text_ref"],
197
+ ["anchor_from", "at", "text_ref"],
198
+ ["anchor_from", "after"],
199
+ ["anchor_from", "after", "anchor_to"],
200
+ ["anchor_from", "before"],
201
+ ["anchor_from", "before", "anchor_to"],
177
202
  ];
178
203
 
179
204
  function keySetEquals(keys: Set<string>, shape: readonly string[]): boolean {
@@ -190,9 +215,9 @@ const AT_SPELLINGS = ["in-place", "before", "after"] as const satisfies readonly
190
215
 
191
216
  // WHY: (ticket-67) strict structured-output harnesses spell "absent" as an explicit `null`
192
217
  // 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.
218
+ // WHY: was refused as carrying both. `null`/`undefined` in the optional slots (`text`,
219
+ // WHY: `text_ref`, `at`, `anchor_to`, root `mode`) reads as ABSENT wherever presence is decided —
220
+ // WHY: one predicate, so the gate, the validators and the normalizers cannot disagree.
196
221
  // WHY: (ticket-75) the nested reference's optional `file` is the same slot one level down: a
197
222
  // WHY: harness that must spell an omitted optional property emits `"file": null`, and reading it
198
223
  // WHY: as present refused a call no retry could satisfy — the #67 class, one object deeper.
@@ -205,7 +230,7 @@ function isAbsentValue(value: unknown): value is null | undefined {
205
230
  // WHY: shape `analyzeRequest` stores and nothing downstream can see an absent value as present.
206
231
  function foldAbsentSlots(item: Record<string, unknown>): Record<string, unknown> {
207
232
  const folded: Record<string, unknown> = { ...item };
208
- for (const key of ["text", "text_ref", "at"] as const) {
233
+ for (const key of ["text", "text_ref", "at", "anchor_to", "after", "before"] as const) {
209
234
  if (isAbsentValue(folded[key])) delete folded[key];
210
235
  }
211
236
  if (isRec(folded.text_ref)) {
@@ -225,7 +250,20 @@ function analyzeItem(value: unknown, index: number): string | undefined {
225
250
  const keys = new Set(Object.keys(value));
226
251
  const hasText = keys.has("text");
227
252
  const hasRef = keys.has("text_ref");
253
+ const hasAfter = keys.has("after");
254
+ const hasBefore = keys.has("before");
255
+ const hasInsert = hasAfter || hasBefore;
256
+ // WHY: (ADR-0025) `after` and `before` are two placements of ONE payload, so carrying both is
257
+ // WHY: as illegal as carrying two payloads; the refusal names every payload key it found.
258
+ const carried = [
259
+ hasText ? "text" : undefined,
260
+ hasRef ? "text_ref" : undefined,
261
+ hasAfter ? "after" : undefined,
262
+ hasBefore ? "before" : undefined,
263
+ ].filter((key) => key !== undefined);
228
264
  if (!isLegalItemKeySet(keys)) {
265
+ // WHY: (ADR-0024/0025) `text` and `text_ref` is the classic pair and keeps its two-choice
266
+ // WHY: phrasing; any other collision gets the full menu so every payload key is named once.
229
267
  if (hasText && hasRef) {
230
268
  return (
231
269
  `edit[${index}] carries both "text" and "text_ref" fields: choose exactly one payload field per item (${ITEM_SHAPE}). ` +
@@ -233,15 +271,34 @@ function analyzeItem(value: unknown, index: number): string | undefined {
233
271
  `Choice B (copy/cut served span): keep "text_ref" and delete "text" from the JSON object.`
234
272
  );
235
273
  }
274
+ if (carried.length > 1) {
275
+ const names = carried.map((key) => `"${key}"`).join(" and ");
276
+ return (
277
+ `edit[${index}] carries ${carried.length} payload fields (${names}): choose exactly one payload field per item (${ITEM_SHAPE}). ` +
278
+ `Keep one of "text" (literal content), "text_ref" (copy/cut a served span), "after" or "before" (insert next to the anchor line) and delete the rest.`
279
+ );
280
+ }
236
281
  // WHY: (§9.3) an illegal key set is often also MISSING a required key; the unsupported-field
237
282
  // 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"]);
283
+ const payloadKeys = new Set([
284
+ "anchor_from",
285
+ "anchor_to",
286
+ "at",
287
+ "text",
288
+ "text_ref",
289
+ "after",
290
+ "before",
291
+ ]);
239
292
  const offending = [...keys].filter((key) => !payloadKeys.has(key));
240
- const missing = ["anchor_from", "anchor_to"].filter((key) => !keys.has(key));
293
+ // WHY: `anchor_to` is optional at the wire — a single-line target needs no second bound — so a
294
+ // WHY: missing `anchor_to` is not a refusal; the normalizer folds it onto `anchor_from`.
295
+ const missing = ["anchor_from"].filter((key) => !keys.has(key));
241
296
  const clauses: string[] = [];
242
297
  if (offending.length > 0) clauses.push(`unsupported field(s) ${quoted(offending)}`);
243
298
  if (missing.length > 0) clauses.push(`missing required field(s) ${quoted(missing)}`);
244
- if (!hasText && !hasRef) {
299
+ // WHY: (ADR-0025) the insertion slots are payloads too, so "no payload" must count them —
300
+ // WHY: an item carrying only `after` is a pure insert, not an empty item.
301
+ if (!hasText && !hasRef && !hasInsert) {
245
302
  const named = clauses.length > 0 ? `${clauses.join(";")} — ` : "";
246
303
  return (
247
304
  `edit[${index}] carries no payload (neither "text" nor "text_ref" fields): ${named}choose exactly one payload field per item (${ITEM_SHAPE}) — ` +
@@ -251,8 +308,11 @@ function analyzeItem(value: unknown, index: number): string | undefined {
251
308
  return `edit[${index}] has ${clauses.join(";")} (${ITEM_SHAPE}).`;
252
309
  }
253
310
  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.`;
311
+ if (typeof anchor_from !== "string") {
312
+ return `edit[${index}] "anchor_from" must be a bare ${HASH_LEN}-char hash anchor copied from served output (before │): it is the one anchor every item needs — an omitted "anchor_to" makes it the whole single-line target.`;
313
+ }
314
+ if (anchor_to !== undefined && typeof anchor_to !== "string") {
315
+ return `edit[${index}] "anchor_to" must be a bare ${HASH_LEN}-char hash anchor copied from served output (before │) or omitted to target the single line "anchor_from" names.`;
256
316
  }
257
317
  if (!isAbsentValue(at)) {
258
318
  if (at === "in_place") {
@@ -262,6 +322,31 @@ function analyzeItem(value: unknown, index: number): string | undefined {
262
322
  return `edit[${index}] "at" must be "in-place", "before" or "after" when present.`;
263
323
  }
264
324
  }
325
+ // WHY: (ADR-0025) an insertion is validated before `text` so the refusal can tell the model it
326
+ // WHY: sent the right shape with the wrong value, instead of reporting a missing payload.
327
+ if (hasInsert) {
328
+ if (hasAfter && hasBefore) {
329
+ return `edit[${index}] carries both "after" and "before": an insertion picks one side. Keep "after" to add lines below "anchor_from", or "before" to add them above, and delete the other.`;
330
+ }
331
+ const side = hasAfter ? "after" : "before";
332
+ const insertion = hasAfter
333
+ ? (value as Record<string, unknown>).after
334
+ : (value as Record<string, unknown>).before;
335
+ if (typeof insertion !== "string") {
336
+ return `edit[${index}] "${side}" must be a string with \\n line separators: the exact lines to insert next to the anchor line.`;
337
+ }
338
+ // WHY: an empty insertion would report success while changing nothing, which trains the model
339
+ // WHY: to trust a no-op; refuse it at admission instead of folding it into a silent noop item.
340
+ if (insertion === "") {
341
+ return `edit[${index}] "${side}" is empty: an insertion must carry at least one line. To delete a line use "text": "" with that line's anchor.`;
342
+ }
343
+ // WHY: a multi-line anchor range has no single side to insert against, so the target must be one
344
+ // WHY: line — the same constraint `at` carries on a resolved span.
345
+ if (anchor_to !== undefined && anchor_to !== anchor_from) {
346
+ return `edit[${index}] "${side}" inserts next to ONE line, but "anchor_from"/"anchor_to" name a range. Omit "anchor_to" (or make it equal "anchor_from") to insert next to a single line.`;
347
+ }
348
+ return undefined;
349
+ }
265
350
  if (hasText) {
266
351
  if (typeof text !== "string") {
267
352
  return `edit[${index}] "text" must be a string with \\n line separators, not an array. An empty string deletes the range.`;
@@ -325,7 +410,7 @@ function analyzeRequest(input: unknown): Admission {
325
410
  ok: false,
326
411
  message:
327
412
  `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" }. ` +
413
+ `{ file, edits: [{ anchor_from, anchor_to, text | text_ref | after | before[, at] }, ...], mode?: "general" | "literal" }. ` +
329
414
  describeReceived(input),
330
415
  };
331
416
  }
@@ -387,11 +472,22 @@ function normalizedItemFrom(item: EditItem): NormalizedEditItem {
387
472
  const payload: DesiredContent =
388
473
  item.text_ref !== undefined
389
474
  ? { kind: "reference", span: item.text_ref, mode: item.text_ref.mode }
390
- : item.text === ""
391
- ? { kind: "empty" }
392
- : { kind: "literal", text: item.text ?? "" };
475
+ : item.after !== undefined
476
+ ? { kind: "insert", side: "after", text: item.after }
477
+ : item.before !== undefined
478
+ ? { kind: "insert", side: "before", text: item.before }
479
+ : item.text === ""
480
+ ? { kind: "empty" }
481
+ : { kind: "literal", text: item.text ?? "" };
482
+ // WHY: the wire may omit `anchor_to`; the target is then the single line `anchor_from` names.
483
+ // WHY: The engine always receives a closed pair, so this one defaulting point keeps every
484
+ // WHY: downstream consumer shape-stable and nothing has to test for an absent bound.
485
+ const target: AnchorSpan = {
486
+ anchor_from: item.anchor_from,
487
+ anchor_to: item.anchor_to ?? item.anchor_from,
488
+ };
393
489
  return {
394
- target: { anchor_from: item.anchor_from, anchor_to: item.anchor_to },
490
+ target,
395
491
  at,
396
492
  payload,
397
493
  };
@@ -449,6 +545,11 @@ function isNormalizedEditItem(value: unknown): value is NormalizedEditItem {
449
545
  (payload.mode === "copy" || payload.mode === "cut")
450
546
  );
451
547
  }
548
+ if (payload.kind === "insert") {
549
+ return (
550
+ (payload.side === "before" || payload.side === "after") && typeof payload.text === "string"
551
+ );
552
+ }
452
553
  return false;
453
554
  }
454
555