dsh-hashline-edit 0.4.3 → 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.
package/README.md CHANGED
@@ -127,7 +127,7 @@ read({
127
127
 
128
128
  - **Served mode** returns one `HASH│content` row per line and records every shown row as a lease for this session. A windowed read also includes a `[Lines A-B of N total]` page header. Every row shown is usable by one subsequent `apply_patch` or `edit`, even when the windows are far apart.
129
129
  - **Verbatim mode** returns the same page as plain text with no anchors and serves nothing; an `apply_patch` identity hunk or an `edit` item cannot target those lines.
130
- - A small requested window — up to 61 lines after folding — may widen to its enclosing function, method, class, section or paragraph; a `[widened …]` note names the block that was served. Expansion applies in both modes. Languages: TypeScript/TSX, Python, Go, Rust, Java and Vue through pinned tree-sitter wasm grammars (fetched lazily and verified against a committed SHA-256), plus Bash through the existing `unbash` parser (no wasm). Vue widens a top-level `template`/`script`/`style` block without parsing embedded JS/TS. SQL is not supported: real migrations largely fail to parse and `.tql` is a Java template, not SQL (see [`docs/spec/sql-vue-feasibility-gate.md`](docs/spec/sql-vue-feasibility-gate.md)).
130
+ - A small requested window — up to 61 lines after folding — may widen to its enclosing function, method, class, section or paragraph; a `[widened …]` note names the block that was served. Expansion applies in both modes. Languages: TypeScript/TSX, Python, Go, Rust, Java and Vue through pinned tree-sitter wasm grammars (all seven ship inside the package under `grammars/` and are verified against a committed SHA-256; the lazy download only covers a manifest entry with no shipped asset), plus Bash through the existing `unbash` parser (no wasm). Vue widens a top-level `template`/`script`/`style` block without parsing embedded JS/TS. SQL is not supported: real migrations largely fail to parse and `.tql` is a Java template, not SQL (see [`docs/spec/sql-vue-feasibility-gate.md`](docs/spec/sql-vue-feasibility-gate.md)).
131
131
  - `offset`/`limit` and `windows` are page requests, not anchors: only `served` output grants mutation leases.
132
132
 
133
133
  ### `apply_patch`
@@ -186,7 +186,7 @@ The anchored range writer. One call targets one file and carries one ordered `ed
186
186
  }
187
187
  ```
188
188
 
189
- Each item names one inclusive bare anchor, `anchor_from`, and exactly one payload: `text` is the replacement content (`""` deletes the range), or `text_ref` is a served span read in `copy` or `cut` mode. A multi-line range adds the optional second anchor `anchor_to` (the last line, inclusive), so a single-line edit omits it and the target is the one line `anchor_from` names — spelling `anchor_from === anchor_to` still validates. A `text_ref` span always names both bounds. Optional `at` is `in-place` by default; `before` / `after` insert at the boundary and require a single-line target. A `text_ref.file` may name another served file as the copy/cut source, and `cut` also retires those source lines; the call's own target remains one file. The retired item-level `file` field is not part of the payload — an old multi-file item shape is refused with `[E_BAD_PAYLOAD]`, and a different target file is a different call. The call commits as one transaction and writes one undo record for recovery; undo is not exposed as a model tool.
189
+ Each item names one inclusive bare anchor, `anchor_from`, and exactly one payload: `text` is the replacement content (`""` deletes the range), or `text_ref` is a served span read in `copy` or `cut` mode. A multi-line range adds the optional second anchor `anchor_to` (the last line, inclusive), so a single-line edit omits it and the target is the one line `anchor_from` names — spelling `anchor_from === anchor_to` still validates. A `text_ref` span always names both bounds. Optional `at` is `in-place` by default; `before` / `after` insert at the boundary and require a single-line target. A `text_ref.file` may name another served file as the copy/cut source, and `cut` also retires those source lines; the call's own target remains one file. The retired item-level `file` field is not part of the payload — an old multi-file item shape is refused with `[E_BAD_PAYLOAD]`, and a different target file is a different call. The call commits as one transaction and writes one undo record for recovery; undo is not exposed as a model tool. A pure insertion can instead carry its own payload slot: `after` places the given lines immediately below the single line `anchor_from` names and `before` places them above, without restating the anchor line (`at` + `text` is the older spelling of the same insertion).
190
190
 
191
191
  ## Shell view
192
192
 
package/lib/index.js CHANGED
@@ -8378,9 +8378,19 @@ function findEnclosingScope(root, requestedStart, requestedEnd, scopeKinds) {
8378
8378
 
8379
8379
  // src/read-expansion/grammar-cache.ts
8380
8380
  import { createHash } from "node:crypto";
8381
- import { existsSync as existsSync3, mkdirSync as mkdirSync5, readFileSync as readFileSync2, renameSync as renameSync4, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
8381
+ import { existsSync as existsSync3, mkdirSync as mkdirSync5, readFileSync as readFileSync3, renameSync as renameSync4, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
8382
8382
  import { dirname as dirname7, join as join8 } from "node:path";
8383
8383
 
8384
+ // src/bundled-assets.ts
8385
+ import { readFileSync as readFileSync2 } from "node:fs";
8386
+ function readBundledAsset(relativePath2) {
8387
+ try {
8388
+ return readFileSync2(new URL(`../${relativePath2}`, import.meta.url));
8389
+ } catch {
8390
+ return void 0;
8391
+ }
8392
+ }
8393
+
8384
8394
  // src/read-expansion/grammar-manifest.ts
8385
8395
  var GRAMMAR_MANIFEST = {
8386
8396
  typescript: {
@@ -8473,7 +8483,7 @@ function readVerifiedCache(path, expected) {
8473
8483
  if (!existsSync3(path)) return void 0;
8474
8484
  let bytes;
8475
8485
  try {
8476
- bytes = readFileSync2(path);
8486
+ bytes = readFileSync3(path);
8477
8487
  } catch {
8478
8488
  discardCachedGrammar(path);
8479
8489
  return void 0;
@@ -8536,6 +8546,11 @@ async function requestGrammar(language, options = {}) {
8536
8546
  const path = grammarCachePath(language, entry, options.cacheRoot);
8537
8547
  const cached = readVerifiedCache(path, entry.sha256);
8538
8548
  if (cached !== void 0) return { status: "ready", artifact: { language, path, bytes: cached } };
8549
+ const bundled = bundledGrammarBytes(language, entry);
8550
+ if (bundled !== void 0) {
8551
+ writeCache(path, bundled);
8552
+ return { status: "ready", artifact: { language, path, bytes: bundled } };
8553
+ }
8539
8554
  let pending = inFlight.get(path);
8540
8555
  if (pending === void 0) {
8541
8556
  pending = fetchAndCache(entry, path, options);
@@ -8550,6 +8565,16 @@ async function requestGrammar(language, options = {}) {
8550
8565
  if (fetched === void 0) return { status: "unavailable", language };
8551
8566
  return { status: "ready", artifact: { language, path, bytes: fetched } };
8552
8567
  }
8568
+ async function ensureGrammar(language, options = {}) {
8569
+ const result = await requestGrammar(language, options);
8570
+ return result.status === "ready" ? result.artifact : void 0;
8571
+ }
8572
+ function bundledGrammarBytes(language, entry) {
8573
+ const name2 = `${language}-${entry.version}-${entry.sha256.slice(0, 16)}.wasm`;
8574
+ const bytes = readBundledAsset(`grammars/${name2}`);
8575
+ if (bytes === void 0) return void 0;
8576
+ return sha256Hex(bytes) === entry.sha256 ? bytes : void 0;
8577
+ }
8553
8578
 
8554
8579
  // src/read-expansion/grammar-runtime.ts
8555
8580
  var runtime;
@@ -8889,7 +8914,7 @@ function decline(refusal, language) {
8889
8914
  function createAstSpanProvider(options = {}) {
8890
8915
  const handles = /* @__PURE__ */ new Map();
8891
8916
  const loadGrammar = options.loadGrammar ?? loadWebTreeSitterGrammar;
8892
- const readText = options.readTextFile ?? defaultReadText;
8917
+ const readText2 = options.readTextFile ?? defaultReadText;
8893
8918
  const runtimeAvailable = options.runtimeAvailable ?? hasWebTreeSitterRuntime;
8894
8919
  const usesDefaultRuntime = options.loadGrammar === void 0;
8895
8920
  let runtimeAbsent = false;
@@ -8972,7 +8997,7 @@ function createAstSpanProvider(options = {}) {
8972
8997
  if (!isOffsetWindow(window)) return decline("provider_declined");
8973
8998
  const language = grammarLanguageForFile(file);
8974
8999
  if (language === void 0) return decline("no_provider");
8975
- const source = await readText(file);
9000
+ const source = await readText2(file);
8976
9001
  if (source === void 0) return decline("provider_declined", language);
8977
9002
  const languageScope = LANGUAGES[language];
8978
9003
  if (languageScope === void 0) return decline("no_provider", language);
@@ -9119,12 +9144,12 @@ async function defaultReadText2(path) {
9119
9144
  }
9120
9145
  }
9121
9146
  function createMarkdownSpanProvider(options = {}) {
9122
- const readText = options.readTextFile ?? defaultReadText2;
9147
+ const readText2 = options.readTextFile ?? defaultReadText2;
9123
9148
  return {
9124
9149
  async enclosingSpan(file, window) {
9125
9150
  if (!("offset" in window) || !("limit" in window)) return { refusal: "provider_declined" };
9126
9151
  if (!isMarkdownPath(file)) return { refusal: "no_provider" };
9127
- const text = await readText(file);
9152
+ const text = await readText2(file);
9128
9153
  if (text === void 0) return { refusal: "provider_declined" };
9129
9154
  const section = findMarkdownSection(text, window.offset, window.offset + window.limit - 1);
9130
9155
  if (section === null) return { refusal: "boundary_crossing" };
@@ -9225,12 +9250,12 @@ function functionName(fn) {
9225
9250
  return value.trim() === "" ? "function" : value.trim();
9226
9251
  }
9227
9252
  function createBashSpanProvider(options = {}) {
9228
- const readText = options.readTextFile ?? defaultReadText3;
9253
+ const readText2 = options.readTextFile ?? defaultReadText3;
9229
9254
  return {
9230
9255
  async enclosingSpan(file, window) {
9231
9256
  if (!("offset" in window) || !("limit" in window)) return { refusal: "provider_declined" };
9232
9257
  if (!isShellPath(file)) return { refusal: "no_provider" };
9233
- const text = await readText(file);
9258
+ const text = await readText2(file);
9234
9259
  if (text === void 0) return { refusal: "provider_declined" };
9235
9260
  let script;
9236
9261
  try {
@@ -9314,12 +9339,12 @@ async function defaultReadText4(path) {
9314
9339
  }
9315
9340
  }
9316
9341
  function createParagraphSpanProvider(options = {}) {
9317
- const readText = options.readTextFile ?? defaultReadText4;
9342
+ const readText2 = options.readTextFile ?? defaultReadText4;
9318
9343
  return {
9319
9344
  async enclosingSpan(file, window) {
9320
9345
  if (!("offset" in window) || !("limit" in window)) return { refusal: "provider_declined" };
9321
9346
  if (!isPlainTextPath(file)) return { refusal: "no_provider" };
9322
- const text = await readText(file);
9347
+ const text = await readText2(file);
9323
9348
  if (text === void 0) return { refusal: "provider_declined" };
9324
9349
  const paragraph = findParagraph(text, window.offset, window.offset + window.limit - 1);
9325
9350
  if (paragraph === null) return { refusal: "boundary_crossing" };
@@ -9753,7 +9778,7 @@ import {
9753
9778
  constants as constants5,
9754
9779
  existsSync as existsSync4,
9755
9780
  mkdirSync as mkdirSync6,
9756
- readFileSync as readFileSync3,
9781
+ readFileSync as readFileSync4,
9757
9782
  renameSync as renameSync5,
9758
9783
  unlinkSync as unlinkSync2,
9759
9784
  writeFileSync as writeFileSync3
@@ -9825,7 +9850,7 @@ function reasonOf2(error) {
9825
9850
  function readConfigObject(path, onWarn) {
9826
9851
  let raw;
9827
9852
  try {
9828
- raw = readFileSync3(path, "utf-8");
9853
+ raw = readFileSync4(path, "utf-8");
9829
9854
  } catch (error) {
9830
9855
  if (!isMissingFile(error)) onWarn?.(`cannot read config ${path}: ${reasonOf2(error)}`);
9831
9856
  return void 0;
@@ -13307,6 +13332,10 @@ function replacementTextForPayload(payload) {
13307
13332
  return `span:${payload.span.anchor_from}..${payload.span.anchor_to}:${payload.mode === "cut" ? "move" : "copy"}`;
13308
13333
  case "empty":
13309
13334
  return "";
13335
+ // WHY: (ADR-0025) an insertion is identified by its side and its own lines, never by the anchor
13336
+ // WHY: line it sits next to — that line is not part of this item's content.
13337
+ case "insert":
13338
+ return `${payload.side}:${payload.text}`;
13310
13339
  default:
13311
13340
  return assertNever(payload);
13312
13341
  }
@@ -13321,6 +13350,7 @@ function parseEdits(items, path, itemNumbers) {
13321
13350
  const payload = item.payload;
13322
13351
  let text;
13323
13352
  let source;
13353
+ let placement;
13324
13354
  switch (payload.kind) {
13325
13355
  case "literal":
13326
13356
  if (payload.text === "") {
@@ -13350,6 +13380,14 @@ function parseEdits(items, path, itemNumbers) {
13350
13380
  }
13351
13381
  text = "";
13352
13382
  break;
13383
+ // WHY: (ADR-0025) a pure insertion reuses the engine's zero-width placement splice: the
13384
+ // WHY: payload lines ARE the content and the anchor line is only the zero-width boundary.
13385
+ // WHY: Because `content_lines` never contains the anchor line, no splice path can rewrite
13386
+ // WHY: it — the "insert turned into a re-typed boundary row" failure is not representable.
13387
+ case "insert":
13388
+ text = payload.text;
13389
+ placement = payload.side;
13390
+ break;
13353
13391
  default:
13354
13392
  assertNever(payload);
13355
13393
  }
@@ -13359,6 +13397,7 @@ function parseEdits(items, path, itemNumbers) {
13359
13397
  anchor_to: item.target.anchor_to,
13360
13398
  text,
13361
13399
  ...item.at !== "in-place" ? { placement: item.at } : {},
13400
+ ...placement !== void 0 ? { placement } : {},
13362
13401
  ...source ? { source } : {}
13363
13402
  })
13364
13403
  });
@@ -14843,6 +14882,21 @@ function diffResultView(title, result) {
14843
14882
  function toCanonicalValue(result) {
14844
14883
  return result;
14845
14884
  }
14885
+ function withWarning(result, warning) {
14886
+ if (warning === void 0) return result;
14887
+ const details = typeof result.details === "object" && result.details !== null ? result.details : {};
14888
+ const existing = Array.isArray(details.warnings) ? details.warnings.filter((entry) => typeof entry === "string") : [];
14889
+ return {
14890
+ ...result,
14891
+ content: result.content.map((block) => {
14892
+ const text = block;
14893
+ return text.type === "text" && typeof text.text === "string" ? { type: "text", text: `${text.text}
14894
+
14895
+ ${warning}` } : block;
14896
+ }),
14897
+ details: { ...details, warnings: [...existing, warning] }
14898
+ };
14899
+ }
14846
14900
 
14847
14901
  // dsh/tools/apply-patch.ts
14848
14902
  var APPLY_PATCH_DESCRIPTION = loadP("../prompts/apply-patch.md");
@@ -15096,8 +15150,8 @@ function isRec(value) {
15096
15150
  function isNormalizedEdit(input) {
15097
15151
  return isRec(input) && input[normalizedEdit] === true;
15098
15152
  }
15099
- var ITEM_SHAPE = "an item is exactly { anchor_from, anchor_to?, text[, at] } or { anchor_from, anchor_to?, text_ref[, at] }";
15100
- var EDIT_PAYLOAD_HINT = `Edit must be called with exactly one payload per item, and each call edits ONE file. Use the canonical payload {"file": file, "edits": [{ "anchor_from": anchor_from, "anchor_to": anchor_to, "text": text }, ...], "mode"?: "general" | "literal"}: "file" is the text file to edit (a non-empty string, never a directory); each item names the bare-${HASH_LEN}-char anchor "anchor_from" (the first line of the range, and the whole range of a single-line edit), an optional second bare anchor "anchor_to" (the last line of a multi-line range; omit it to edit "anchor_from" alone) and exactly one payload \u2014 "text" (bare replacement content; an empty string deletes the range) or "text_ref" ({ anchor_from, anchor_to, file?, mode (required): "copy" | "cut" } \u2014 the served span's bytes, whose two bounds are always required, and whose "file" may name another served file as the copy/cut source); optional "at" is "in-place" (default), "before" or "after" (single-line resolved target only); optional "mode" is "general" (default, reproduced served rows are refused) or "literal" (declared literal content).`;
15153
+ var ITEM_SHAPE = "an item is exactly { anchor_from, anchor_to?, text[, at] }, { anchor_from, anchor_to?, text_ref[, at] }, or { anchor_from, anchor_to?, after | before }";
15154
+ var EDIT_PAYLOAD_HINT = `Edit must be called with exactly one payload per item, and each call edits ONE file. Use the canonical payload {"file": file, "edits": [{ "anchor_from": anchor_from, "anchor_to": anchor_to, "text": text }, ...], "mode"?: "general" | "literal"}: "file" is the text file to edit (a non-empty string, never a directory); each item names the bare-${HASH_LEN}-char anchor "anchor_from" (the first line of the range, and the whole range of a single-line edit), an optional second bare anchor "anchor_to" (the last line of a multi-line range; omit it to edit "anchor_from" alone) and exactly one payload \u2014 "text" (bare replacement content; an empty string deletes the range), "text_ref" ({ anchor_from, anchor_to, file?, mode (required): "copy" | "cut" } \u2014 the served span's bytes, whose two bounds are always required, and whose "file" may name another served file as the copy/cut source), or an insertion slot "after"/"before" (the exact lines to insert below/above the single anchor line, which is never restated); optional "at" is "in-place" (default), "before" or "after" (single-line resolved target only); optional "mode" is "general" (default, reproduced served rows are refused) or "literal" (declared literal content).`;
15101
15155
  function describeReceived(input) {
15102
15156
  if (input === void 0) return "Received no arguments.";
15103
15157
  if (input === null) return "Received null.";
@@ -15153,7 +15207,11 @@ var ITEM_KEY_SETS = [
15153
15207
  ["anchor_from", "anchor_to", "text_ref"],
15154
15208
  ["anchor_from", "text_ref"],
15155
15209
  ["anchor_from", "anchor_to", "at", "text_ref"],
15156
- ["anchor_from", "at", "text_ref"]
15210
+ ["anchor_from", "at", "text_ref"],
15211
+ ["anchor_from", "after"],
15212
+ ["anchor_from", "after", "anchor_to"],
15213
+ ["anchor_from", "before"],
15214
+ ["anchor_from", "before", "anchor_to"]
15157
15215
  ];
15158
15216
  function keySetEquals(keys, shape) {
15159
15217
  if (keys.size !== shape.length) return false;
@@ -15168,7 +15226,7 @@ function isAbsentValue(value) {
15168
15226
  }
15169
15227
  function foldAbsentSlots(item) {
15170
15228
  const folded = { ...item };
15171
- for (const key of ["text", "text_ref", "at", "anchor_to"]) {
15229
+ for (const key of ["text", "text_ref", "at", "anchor_to", "after", "before"]) {
15172
15230
  if (isAbsentValue(folded[key])) delete folded[key];
15173
15231
  }
15174
15232
  if (isRec(folded.text_ref)) {
@@ -15185,17 +15243,38 @@ function analyzeItem(value, index) {
15185
15243
  const keys = new Set(Object.keys(value));
15186
15244
  const hasText = keys.has("text");
15187
15245
  const hasRef = keys.has("text_ref");
15246
+ const hasAfter = keys.has("after");
15247
+ const hasBefore = keys.has("before");
15248
+ const hasInsert = hasAfter || hasBefore;
15249
+ const carried = [
15250
+ hasText ? "text" : void 0,
15251
+ hasRef ? "text_ref" : void 0,
15252
+ hasAfter ? "after" : void 0,
15253
+ hasBefore ? "before" : void 0
15254
+ ].filter((key) => key !== void 0);
15188
15255
  if (!isLegalItemKeySet(keys)) {
15189
15256
  if (hasText && hasRef) {
15190
15257
  return `edit[${index}] carries both "text" and "text_ref" fields: choose exactly one payload field per item (${ITEM_SHAPE}). Choice A (literal content): Keep "text" and delete "text_ref" from the JSON object. Choice B (copy/cut served span): keep "text_ref" and delete "text" from the JSON object.`;
15191
15258
  }
15192
- const payloadKeys = /* @__PURE__ */ new Set(["anchor_from", "anchor_to", "at", "text", "text_ref"]);
15259
+ if (carried.length > 1) {
15260
+ const names = carried.map((key) => `"${key}"`).join(" and ");
15261
+ return `edit[${index}] carries ${carried.length} payload fields (${names}): choose exactly one payload field per item (${ITEM_SHAPE}). 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.`;
15262
+ }
15263
+ const payloadKeys = /* @__PURE__ */ new Set([
15264
+ "anchor_from",
15265
+ "anchor_to",
15266
+ "at",
15267
+ "text",
15268
+ "text_ref",
15269
+ "after",
15270
+ "before"
15271
+ ]);
15193
15272
  const offending = [...keys].filter((key) => !payloadKeys.has(key));
15194
15273
  const missing = ["anchor_from"].filter((key) => !keys.has(key));
15195
15274
  const clauses = [];
15196
15275
  if (offending.length > 0) clauses.push(`unsupported field(s) ${quoted(offending)}`);
15197
15276
  if (missing.length > 0) clauses.push(`missing required field(s) ${quoted(missing)}`);
15198
- if (!hasText && !hasRef) {
15277
+ if (!hasText && !hasRef && !hasInsert) {
15199
15278
  const named = clauses.length > 0 ? `${clauses.join(";")} \u2014 ` : "";
15200
15279
  return `edit[${index}] carries no payload (neither "text" nor "text_ref" fields): ${named}choose exactly one payload field per item (${ITEM_SHAPE}) \u2014 supply the "text" field (authored content) OR the "text_ref" field (served span).`;
15201
15280
  }
@@ -15216,6 +15295,23 @@ function analyzeItem(value, index) {
15216
15295
  return `edit[${index}] "at" must be "in-place", "before" or "after" when present.`;
15217
15296
  }
15218
15297
  }
15298
+ if (hasInsert) {
15299
+ if (hasAfter && hasBefore) {
15300
+ 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.`;
15301
+ }
15302
+ const side = hasAfter ? "after" : "before";
15303
+ const insertion = hasAfter ? value.after : value.before;
15304
+ if (typeof insertion !== "string") {
15305
+ return `edit[${index}] "${side}" must be a string with \\n line separators: the exact lines to insert next to the anchor line.`;
15306
+ }
15307
+ if (insertion === "") {
15308
+ 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.`;
15309
+ }
15310
+ if (anchor_to !== void 0 && anchor_to !== anchor_from) {
15311
+ 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.`;
15312
+ }
15313
+ return void 0;
15314
+ }
15219
15315
  if (hasText) {
15220
15316
  if (typeof text !== "string") {
15221
15317
  return `edit[${index}] "text" must be a string with \\n line separators, not an array. An empty string deletes the range.`;
@@ -15260,7 +15356,7 @@ function analyzeRequest(input) {
15260
15356
  if (rootOffending.length > 0) {
15261
15357
  return {
15262
15358
  ok: false,
15263
- message: `Edit request has unsupported field(s) ${quoted(rootOffending)}; it is exactly { file, edits: [{ anchor_from, anchor_to, text | text_ref[, at] }, ...], mode?: "general" | "literal" }. ` + describeReceived(input)
15359
+ message: `Edit request has unsupported field(s) ${quoted(rootOffending)}; it is exactly { file, edits: [{ anchor_from, anchor_to, text | text_ref | after | before[, at] }, ...], mode?: "general" | "literal" }. ` + describeReceived(input)
15264
15360
  };
15265
15361
  }
15266
15362
  let mode;
@@ -15314,7 +15410,7 @@ function analyzeRequest(input) {
15314
15410
  }
15315
15411
  function normalizedItemFrom(item) {
15316
15412
  const at = item.at ?? "in-place";
15317
- const payload = item.text_ref !== void 0 ? { kind: "reference", span: item.text_ref, mode: item.text_ref.mode } : item.text === "" ? { kind: "empty" } : { kind: "literal", text: item.text ?? "" };
15413
+ const payload = item.text_ref !== void 0 ? { kind: "reference", span: item.text_ref, mode: item.text_ref.mode } : item.after !== void 0 ? { kind: "insert", side: "after", text: item.after } : item.before !== void 0 ? { kind: "insert", side: "before", text: item.before } : item.text === "" ? { kind: "empty" } : { kind: "literal", text: item.text ?? "" };
15318
15414
  const target = {
15319
15415
  anchor_from: item.anchor_from,
15320
15416
  anchor_to: item.anchor_to ?? item.anchor_from
@@ -15360,6 +15456,9 @@ function isNormalizedEditItem(value) {
15360
15456
  if (payload.kind === "reference") {
15361
15457
  return isRec(payload.span) && typeof payload.span.anchor_from === "string" && typeof payload.span.anchor_to === "string" && (payload.mode === "copy" || payload.mode === "cut");
15362
15458
  }
15459
+ if (payload.kind === "insert") {
15460
+ return (payload.side === "before" || payload.side === "after") && typeof payload.text === "string";
15461
+ }
15363
15462
  return false;
15364
15463
  }
15365
15464
  function assertReq(request) {
@@ -15568,6 +15667,107 @@ function createEditTool() {
15568
15667
  };
15569
15668
  }
15570
15669
 
15670
+ // dsh/syntax-health.ts
15671
+ var GRAMMAR_BY_EXTENSION = {
15672
+ ".ts": "typescript",
15673
+ ".mts": "typescript",
15674
+ ".cts": "typescript",
15675
+ ".tsx": "tsx",
15676
+ ".js": "tsx",
15677
+ ".mjs": "tsx",
15678
+ ".cjs": "tsx",
15679
+ ".jsx": "tsx",
15680
+ ".py": "python",
15681
+ ".pyi": "python",
15682
+ ".go": "go",
15683
+ ".rs": "rust",
15684
+ ".java": "java",
15685
+ ".vue": "vue"
15686
+ };
15687
+ function grammarForPath(path) {
15688
+ const lower = path.toLowerCase();
15689
+ const dot = lower.lastIndexOf(".");
15690
+ if (dot === -1) return void 0;
15691
+ return GRAMMAR_BY_EXTENSION[lower.slice(dot)];
15692
+ }
15693
+ function errorLines(root, cap) {
15694
+ const found = [];
15695
+ let deepestDamaged;
15696
+ const visit = (node) => {
15697
+ if (!node.hasError) return;
15698
+ const line = node.startPosition.row + 1;
15699
+ if (node.type === "ERROR") {
15700
+ if (found.length < cap) found.push(line);
15701
+ return;
15702
+ }
15703
+ deepestDamaged = deepestDamaged === void 0 ? line : Math.max(deepestDamaged, line);
15704
+ for (const child of node.namedChildren) visit(child);
15705
+ };
15706
+ visit(root);
15707
+ if (found.length > 0) return [...new Set(found)].sort((a, b) => a - b);
15708
+ return deepestDamaged === void 0 ? [] : [deepestDamaged];
15709
+ }
15710
+ function aborted(signal) {
15711
+ return signal?.aborted === true;
15712
+ }
15713
+ async function defaultGrammarFor(path) {
15714
+ const language = grammarForPath(path);
15715
+ if (language === void 0) return void 0;
15716
+ const artifact = await ensureGrammar(language);
15717
+ if (artifact === void 0) return void 0;
15718
+ return loadWebTreeSitterGrammar(artifact.bytes);
15719
+ }
15720
+ async function syntaxWarningForEdit(path, before, after, options = {}) {
15721
+ if (before === after) return void 0;
15722
+ if (aborted(options.signal)) return void 0;
15723
+ try {
15724
+ const grammar = await (options.grammarFor ?? defaultGrammarFor)(path);
15725
+ if (grammar === void 0) return void 0;
15726
+ if (aborted(options.signal)) return void 0;
15727
+ const beforeTree = grammar.parse(before);
15728
+ const beforeClean = beforeTree !== null && beforeTree.rootNode.hasError === false;
15729
+ beforeTree?.delete?.();
15730
+ if (beforeClean === false) return void 0;
15731
+ const afterTree = grammar.parse(after);
15732
+ if (afterTree === null) return void 0;
15733
+ let lines;
15734
+ try {
15735
+ if (!afterTree.rootNode.hasError) return void 0;
15736
+ lines = errorLines(afterTree.rootNode, 5);
15737
+ } finally {
15738
+ afterTree.delete?.();
15739
+ }
15740
+ if (lines.length === 0) return void 0;
15741
+ const first = lines[0];
15742
+ const noun = lines.length === 1 ? "a syntax error" : "syntax errors";
15743
+ return [
15744
+ "[W_SYNTAX] This edit introduced " + noun + " near line " + lines.join(", ") + ".",
15745
+ "The file was committed as written. The usual cause is a replaced range that swallowed or left",
15746
+ "one extra closing brace or bracket \u2014 re-read around line " + first + " and correct the range."
15747
+ ].join(" ");
15748
+ } catch {
15749
+ return void 0;
15750
+ }
15751
+ }
15752
+ async function readText(io, path, signal) {
15753
+ try {
15754
+ return decodeUtf8Strict(await io.read(path, signal), path);
15755
+ } catch {
15756
+ return void 0;
15757
+ }
15758
+ }
15759
+ async function readSyntaxBaseline(io, path, signal) {
15760
+ if (signal?.aborted === true) return void 0;
15761
+ if (grammarForPath(path) === void 0) return void 0;
15762
+ const text = await readText(io, path, signal);
15763
+ return text === void 0 ? void 0 : { path, text };
15764
+ }
15765
+ async function syntaxWarningAfterEdit(io, baseline, options = {}) {
15766
+ const after = await readText(io, baseline.path, options.signal);
15767
+ if (after === void 0) return void 0;
15768
+ return syntaxWarningForEdit(baseline.path, baseline.text, after, options);
15769
+ }
15770
+
15571
15771
  // dsh/tools/edit.ts
15572
15772
  var EDIT_TOOL_NAME = "edit";
15573
15773
  var EDIT_PARAMETERS = {
@@ -15617,6 +15817,24 @@ var EDIT_PARAMETERS = {
15617
15817
  { type: "null" }
15618
15818
  ]
15619
15819
  },
15820
+ after: {
15821
+ oneOf: [
15822
+ {
15823
+ type: "string",
15824
+ description: "Exact lines to insert immediately BELOW anchor_from; the anchor line itself is never rewritten, so it is never restated"
15825
+ },
15826
+ { type: "null" }
15827
+ ]
15828
+ },
15829
+ before: {
15830
+ oneOf: [
15831
+ {
15832
+ type: "string",
15833
+ description: "Exact lines to insert immediately ABOVE anchor_from; the anchor line itself is never rewritten, so it is never restated"
15834
+ },
15835
+ { type: "null" }
15836
+ ]
15837
+ },
15620
15838
  text_ref: {
15621
15839
  oneOf: [
15622
15840
  {
@@ -15735,10 +15953,13 @@ function buildEditTool(deps) {
15735
15953
  throw new DomainError("E_NOT_FOUND", { path: admitted.file });
15736
15954
  }
15737
15955
  }
15956
+ const syntaxBefore = await readSyntaxBaseline(deps.io, absolutePath, toolCtx.signal);
15738
15957
  const members = writtenMemberFiles(admitted);
15739
15958
  await announcePluginWrites(deps, members, toolCtx, exec);
15740
15959
  const result = await tool.execute(admitted, toolCtx.signal, upstreamContext(toolCtx));
15741
- const canonical = toCanonicalValue(result);
15960
+ const raw = toCanonicalValue(result);
15961
+ const introduced = syntaxBefore === void 0 ? void 0 : await syntaxWarningAfterEdit(deps.io, syntaxBefore, { signal: toolCtx.signal });
15962
+ const canonical = withWarning(raw, introduced);
15742
15963
  await publishPluginWrites(deps, members, toolCtx, exec);
15743
15964
  metrics?.record({
15744
15965
  tool: "edit",
@@ -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;
@@ -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: {
@@ -46,6 +46,10 @@ type DesiredContent = {
46
46
  mode: "copy" | "cut";
47
47
  } | {
48
48
  kind: "empty";
49
+ } | {
50
+ kind: "insert";
51
+ side: "before" | "after";
52
+ text: string;
49
53
  };
50
54
  type NormalizedEditItem = {
51
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.3",
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
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 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.
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
+ }
@@ -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,10 +19,10 @@ 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;
@@ -31,6 +31,10 @@ type EditItem = {
31
31
  at?: "in-place" | "before" | "after";
32
32
  text?: string;
33
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;
34
38
  };
35
39
 
36
40
  type EditMode = "general" | "literal";
@@ -65,8 +69,11 @@ type AnchorSpan = { anchor_from: string; anchor_to: string };
65
69
  type DesiredContent =
66
70
  | { kind: "literal"; text: string }
67
71
  | { kind: "reference"; span: SpanRef; mode: "copy" | "cut" }
68
- | { kind: "empty" };
69
-
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 };
70
77
  type NormalizedEditItem = {
71
78
  target: AnchorSpan;
72
79
  at: Placement;
@@ -102,7 +109,7 @@ function isNormalizedEdit(input: unknown): input is Record<string, unknown> {
102
109
  }
103
110
 
104
111
  const ITEM_SHAPE =
105
- "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 }";
106
113
 
107
114
  const EDIT_PAYLOAD_HINT =
108
115
  "Edit must be called with exactly one payload per item, and each call edits ONE file. Use the canonical payload " +
@@ -110,11 +117,12 @@ const EDIT_PAYLOAD_HINT =
110
117
  '"file" is the text file to edit (a non-empty string, never a directory); each item names the bare-' +
111
118
  `${HASH_LEN}-char anchor "anchor_from" (the first line of the range, and the whole range of a single-line edit), an optional ` +
112
119
  'second bare anchor "anchor_to" (the last line of a multi-line range; omit it to edit "anchor_from" alone) and exactly one ' +
113
- 'payload — "text" (bare replacement content; an empty string deletes the range) or "text_ref" ' +
120
+ 'payload — "text" (bare replacement content; an empty string deletes the range), "text_ref" ' +
114
121
  '({ anchor_from, anchor_to, file?, mode (required): "copy" | "cut" } — the served span\'s bytes, whose two bounds are ' +
115
- 'always required, and whose "file" may name another served file as the copy/cut source); optional "at" is "in-place" ' +
116
- '(default), "before" or "after" (single-line resolved target only); optional "mode" is "general" (default, reproduced ' +
117
- 'served rows are refused) or "literal" (declared literal content).';
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).';
118
126
  function describeReceived(input: unknown): string {
119
127
  if (input === undefined) return "Received no arguments.";
120
128
  if (input === null) return "Received null.";
@@ -187,6 +195,10 @@ const ITEM_KEY_SETS: readonly (readonly string[])[] = [
187
195
  ["anchor_from", "text_ref"],
188
196
  ["anchor_from", "anchor_to", "at", "text_ref"],
189
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"],
190
202
  ];
191
203
 
192
204
  function keySetEquals(keys: Set<string>, shape: readonly string[]): boolean {
@@ -218,7 +230,7 @@ function isAbsentValue(value: unknown): value is null | undefined {
218
230
  // WHY: shape `analyzeRequest` stores and nothing downstream can see an absent value as present.
219
231
  function foldAbsentSlots(item: Record<string, unknown>): Record<string, unknown> {
220
232
  const folded: Record<string, unknown> = { ...item };
221
- for (const key of ["text", "text_ref", "at", "anchor_to"] as const) {
233
+ for (const key of ["text", "text_ref", "at", "anchor_to", "after", "before"] as const) {
222
234
  if (isAbsentValue(folded[key])) delete folded[key];
223
235
  }
224
236
  if (isRec(folded.text_ref)) {
@@ -238,7 +250,20 @@ function analyzeItem(value: unknown, index: number): string | undefined {
238
250
  const keys = new Set(Object.keys(value));
239
251
  const hasText = keys.has("text");
240
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);
241
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.
242
267
  if (hasText && hasRef) {
243
268
  return (
244
269
  `edit[${index}] carries both "text" and "text_ref" fields: choose exactly one payload field per item (${ITEM_SHAPE}). ` +
@@ -246,9 +271,24 @@ function analyzeItem(value: unknown, index: number): string | undefined {
246
271
  `Choice B (copy/cut served span): keep "text_ref" and delete "text" from the JSON object.`
247
272
  );
248
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
+ }
249
281
  // WHY: (§9.3) an illegal key set is often also MISSING a required key; the unsupported-field
250
282
  // WHY: list alone renders blank there, so the refusal must name the missing keys too.
251
- 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
+ ]);
252
292
  const offending = [...keys].filter((key) => !payloadKeys.has(key));
253
293
  // WHY: `anchor_to` is optional at the wire — a single-line target needs no second bound — so a
254
294
  // WHY: missing `anchor_to` is not a refusal; the normalizer folds it onto `anchor_from`.
@@ -256,7 +296,9 @@ function analyzeItem(value: unknown, index: number): string | undefined {
256
296
  const clauses: string[] = [];
257
297
  if (offending.length > 0) clauses.push(`unsupported field(s) ${quoted(offending)}`);
258
298
  if (missing.length > 0) clauses.push(`missing required field(s) ${quoted(missing)}`);
259
- 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) {
260
302
  const named = clauses.length > 0 ? `${clauses.join(";")} — ` : "";
261
303
  return (
262
304
  `edit[${index}] carries no payload (neither "text" nor "text_ref" fields): ${named}choose exactly one payload field per item (${ITEM_SHAPE}) — ` +
@@ -280,6 +322,31 @@ function analyzeItem(value: unknown, index: number): string | undefined {
280
322
  return `edit[${index}] "at" must be "in-place", "before" or "after" when present.`;
281
323
  }
282
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
+ }
283
350
  if (hasText) {
284
351
  if (typeof text !== "string") {
285
352
  return `edit[${index}] "text" must be a string with \\n line separators, not an array. An empty string deletes the range.`;
@@ -343,7 +410,7 @@ function analyzeRequest(input: unknown): Admission {
343
410
  ok: false,
344
411
  message:
345
412
  `Edit request has unsupported field(s) ${quoted(rootOffending)}; it is exactly ` +
346
- `{ 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" }. ` +
347
414
  describeReceived(input),
348
415
  };
349
416
  }
@@ -405,9 +472,13 @@ function normalizedItemFrom(item: EditItem): NormalizedEditItem {
405
472
  const payload: DesiredContent =
406
473
  item.text_ref !== undefined
407
474
  ? { kind: "reference", span: item.text_ref, mode: item.text_ref.mode }
408
- : item.text === ""
409
- ? { kind: "empty" }
410
- : { 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 ?? "" };
411
482
  // WHY: the wire may omit `anchor_to`; the target is then the single line `anchor_from` names.
412
483
  // WHY: The engine always receives a closed pair, so this one defaulting point keeps every
413
484
  // WHY: downstream consumer shape-stable and nothing has to test for an absent bound.
@@ -474,6 +545,11 @@ function isNormalizedEditItem(value: unknown): value is NormalizedEditItem {
474
545
  (payload.mode === "copy" || payload.mode === "cut")
475
546
  );
476
547
  }
548
+ if (payload.kind === "insert") {
549
+ return (
550
+ (payload.side === "before" || payload.side === "after") && typeof payload.text === "string"
551
+ );
552
+ }
477
553
  return false;
478
554
  }
479
555
 
@@ -1,7 +1,9 @@
1
1
  /**
2
2
  * Lazy, hash-pinned grammar cache.
3
3
  *
4
- * WHY fetch on first use instead of bundling: the full grammar set measured megabytes against a
4
+ * WHY bundled first and fetched only as a fallback: ADR-0026 ships all seven grammars inside the
5
+ * package (`grammars/`), so a first read never waits on — and never needs — the network. Bytes are
6
+ * digest-verified whichever source they come from; the committed manifest stays the trust anchor.
5
7
  * small extension bundle, and most sessions never touch most languages. The committed manifest is
6
8
  * the trust anchor: bytes are cached only after their SHA-256 matches, and a cache entry whose
7
9
  * digest no longer matches is deleted rather than parsed.
@@ -14,6 +16,7 @@ import { createHash } from "node:crypto";
14
16
  import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
15
17
  import { dirname, join } from "node:path";
16
18
  import { stateRoot } from "../config-dir.js";
19
+ import { readBundledAsset } from "../bundled-assets.js";
17
20
  import {
18
21
  GRAMMAR_MANIFEST,
19
22
  type GrammarManifest,
@@ -179,6 +182,13 @@ export async function requestGrammar(
179
182
  const path = grammarCachePath(language, entry, options.cacheRoot);
180
183
  const cached = readVerifiedCache(path, entry.sha256);
181
184
  if (cached !== undefined) return { status: "ready", artifact: { language, path, bytes: cached } };
185
+ // WHY: bundled before the network — the shipped grammars are the common path now, so a first
186
+ // WHY: read never waits on a fetch. A miss falls through to the lazy download below.
187
+ const bundled = bundledGrammarBytes(language, entry);
188
+ if (bundled !== undefined) {
189
+ writeCache(path, bundled);
190
+ return { status: "ready", artifact: { language, path, bytes: bundled } };
191
+ }
182
192
 
183
193
  let pending = inFlight.get(path);
184
194
  if (pending === undefined) {
@@ -207,3 +217,25 @@ export async function ensureGrammar(
207
217
  const result = await requestGrammar(language, options);
208
218
  return result.status === "ready" ? result.artifact : undefined;
209
219
  }
220
+
221
+ /**
222
+ * Verified bytes taken from this package's own `grammars/` directory, or undefined.
223
+ *
224
+ * WHY bundle AND keep the fetch: the shipped artifact must work offline and instantly, but a
225
+ * language can enter the manifest before it enters the tarball, so the download stays as the
226
+ * fallback for that window.
227
+ * @param language - manifest key.
228
+ * @param entry - the pinned version and digest for that key.
229
+ * @returns the verified bytes, or undefined when the asset is absent or no longer matches the pin.
230
+ */
231
+ function bundledGrammarBytes(
232
+ language: string,
233
+ entry: GrammarManifestEntry,
234
+ ): Uint8Array | undefined {
235
+ const name = `${language}-${entry.version}-${entry.sha256.slice(0, 16)}.wasm`;
236
+ const bytes = readBundledAsset(`grammars/${name}`);
237
+ if (bytes === undefined) return undefined;
238
+ // WHY: bundled bytes are verified too — a truncated download, a bad publish or a hand-edited
239
+ // WHY: file in the tarball must never reach the parser, exactly as for a fetched grammar.
240
+ return sha256Hex(bytes) === entry.sha256 ? bytes : undefined;
241
+ }
@@ -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
  */