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.
package/README.md CHANGED
@@ -73,7 +73,7 @@ p9r│ return total;
73
73
  a1b│}
74
74
  ```
75
75
 
76
- Copy only the build-width characters before `│` (3 by default; 4 in a 4-char build). `edit` passes them as `anchor_from` / `anchor_to`; `apply_patch` writes them as `@@<anchor>` for one row or `@@<from>-<to>` for a span. Both forms target an inclusive served range; a successful call returns a diff whose modified and context rows carry fresh anchors:
76
+ Copy only the build-width characters before `│` (3 by default; 4 in a 4-char build). `edit` passes them as `anchor_from`, plus `anchor_to` only when the range spans more than one line; `apply_patch` writes them as `@@<anchor>` for one row or `@@<from>-<to>` for a span. Both forms target an inclusive served range; a successful call returns a diff whose modified and context rows carry fresh anchors:
77
77
 
78
78
  ```text
79
79
  - szJ│ let total = 0;
@@ -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`
@@ -177,17 +177,16 @@ The anchored range writer. One call targets one file and carries one ordered `ed
177
177
  {
178
178
  "file": "src/config.ts",
179
179
  "edits": [
180
- { "anchor_from": "szJ", "anchor_to": "szJ", "text": " retries: 5," },
180
+ { "anchor_from": "szJ", "text": " retries: 5," },
181
181
  {
182
182
  "anchor_from": "d2x",
183
- "anchor_to": "d2x",
184
183
  "text_ref": { "anchor_from": "a1b", "anchor_to": "a1b", "file": "src/defaults.ts", "mode": "copy" }
185
184
  }
186
185
  ]
187
186
  }
188
187
  ```
189
188
 
190
- Each item names two inclusive bare anchors 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. 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).
191
190
 
192
191
  ## Shell view
193
192
 
@@ -278,7 +277,7 @@ Every refusal carries a bracketed code; `src/domain-errors.ts` is the source of
278
277
  | `[W_SERVED_PREFIX_MISMATCH]` | A served prefix does not match; fresh rows were served. |
279
278
  | `[W_UNICODE_LITERAL]` | A Unicode literal in the payload looks like a copied anchor. |
280
279
 
281
- Range-family rejections render their current-row evidence exactly once: the headline plus one `Current range (fresh read):` block. A single-line anchor pair (`anchor_from` equals `anchor_to`) is listed once, and the distinct-anchor lists de-duplicate. `[E_UNKNOWN_ANCHOR]` and `[E_FOREIGN_ANCHOR]` also name each distinct anchor once.
280
+ Range-family rejections render their current-row evidence exactly once: the headline plus one `Current range (fresh read):` block. A single-line target — whether written as one anchor or as a pair with `anchor_from` equal to `anchor_to` — is listed once, and the distinct-anchor lists de-duplicate. `[E_UNKNOWN_ANCHOR]` and `[E_FOREIGN_ANCHOR]` also name each distinct anchor once.
282
281
 
283
282
  ## Current limitations
284
283
 
package/lib/index.js CHANGED
@@ -6435,9 +6435,9 @@ function assertItem(edit) {
6435
6435
  message: '"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.'
6436
6436
  });
6437
6437
  }
6438
- if (typeof edit.anchor_from !== "string" || typeof edit.anchor_to !== "string") {
6438
+ if (typeof edit.anchor_from !== "string") {
6439
6439
  throw new DomainError("E_BAD_PAYLOAD", {
6440
- message: `The edit requires "anchor_from" and "anchor_to" anchor strings (bare ${HASH_LEN}-char hashes from served output). Nothing was written.`
6440
+ message: `The edit requires an "anchor_from" anchor string (a bare ${HASH_LEN}-char hash from served output). Nothing was written.`
6441
6441
  });
6442
6442
  }
6443
6443
  if ("placement" in edit && !isEditPlacement(edit.placement)) {
@@ -6467,7 +6467,7 @@ function firstHashFromBlock(block) {
6467
6467
  function resEdit(edit) {
6468
6468
  assertItem(edit);
6469
6469
  const editLines = parseText(edit.text);
6470
- const bounds = [edit.anchor_from, edit.anchor_to].map((ref) => {
6470
+ const bounds = [edit.anchor_from, edit.anchor_to ?? edit.anchor_from].map((ref) => {
6471
6471
  const trimmed = ref.trim();
6472
6472
  if (trimmed.includes("\n")) {
6473
6473
  const hash = firstHashFromBlock(trimmed);
@@ -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 two inclusive bare-${HASH_LEN}-char anchors 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 "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.";
@@ -15147,9 +15201,17 @@ function sanitizePath(value) {
15147
15201
  }
15148
15202
  var ITEM_KEY_SETS = [
15149
15203
  ["anchor_from", "anchor_to", "text"],
15204
+ ["anchor_from", "text"],
15150
15205
  ["anchor_from", "anchor_to", "at", "text"],
15206
+ ["anchor_from", "at", "text"],
15151
15207
  ["anchor_from", "anchor_to", "text_ref"],
15152
- ["anchor_from", "anchor_to", "at", "text_ref"]
15208
+ ["anchor_from", "text_ref"],
15209
+ ["anchor_from", "anchor_to", "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"]
15153
15215
  ];
15154
15216
  function keySetEquals(keys, shape) {
15155
15217
  if (keys.size !== shape.length) return false;
@@ -15164,7 +15226,7 @@ function isAbsentValue(value) {
15164
15226
  }
15165
15227
  function foldAbsentSlots(item) {
15166
15228
  const folded = { ...item };
15167
- for (const key of ["text", "text_ref", "at"]) {
15229
+ for (const key of ["text", "text_ref", "at", "anchor_to", "after", "before"]) {
15168
15230
  if (isAbsentValue(folded[key])) delete folded[key];
15169
15231
  }
15170
15232
  if (isRec(folded.text_ref)) {
@@ -15181,25 +15243,49 @@ function analyzeItem(value, index) {
15181
15243
  const keys = new Set(Object.keys(value));
15182
15244
  const hasText = keys.has("text");
15183
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);
15184
15255
  if (!isLegalItemKeySet(keys)) {
15185
15256
  if (hasText && hasRef) {
15186
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.`;
15187
15258
  }
15188
- 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
+ ]);
15189
15272
  const offending = [...keys].filter((key) => !payloadKeys.has(key));
15190
- const missing = ["anchor_from", "anchor_to"].filter((key) => !keys.has(key));
15273
+ const missing = ["anchor_from"].filter((key) => !keys.has(key));
15191
15274
  const clauses = [];
15192
15275
  if (offending.length > 0) clauses.push(`unsupported field(s) ${quoted(offending)}`);
15193
15276
  if (missing.length > 0) clauses.push(`missing required field(s) ${quoted(missing)}`);
15194
- if (!hasText && !hasRef) {
15277
+ if (!hasText && !hasRef && !hasInsert) {
15195
15278
  const named = clauses.length > 0 ? `${clauses.join(";")} \u2014 ` : "";
15196
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).`;
15197
15280
  }
15198
15281
  return `edit[${index}] has ${clauses.join(";")} (${ITEM_SHAPE}).`;
15199
15282
  }
15200
15283
  const { anchor_from, anchor_to, at, text, text_ref } = value;
15201
- if (typeof anchor_from !== "string" || typeof anchor_to !== "string") {
15202
- return `edit[${index}] "anchor_from"/"anchor_to" must be bare ${HASH_LEN}-char hash anchor strings copied from served output (before \u2502): both anchors are required, so null is not a value here.`;
15284
+ if (typeof anchor_from !== "string") {
15285
+ return `edit[${index}] "anchor_from" must be a bare ${HASH_LEN}-char hash anchor copied from served output (before \u2502): it is the one anchor every item needs \u2014 an omitted "anchor_to" makes it the whole single-line target.`;
15286
+ }
15287
+ if (anchor_to !== void 0 && typeof anchor_to !== "string") {
15288
+ return `edit[${index}] "anchor_to" must be a bare ${HASH_LEN}-char hash anchor copied from served output (before \u2502) or omitted to target the single line "anchor_from" names.`;
15203
15289
  }
15204
15290
  if (!isAbsentValue(at)) {
15205
15291
  if (at === "in_place") {
@@ -15209,6 +15295,23 @@ function analyzeItem(value, index) {
15209
15295
  return `edit[${index}] "at" must be "in-place", "before" or "after" when present.`;
15210
15296
  }
15211
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
+ }
15212
15315
  if (hasText) {
15213
15316
  if (typeof text !== "string") {
15214
15317
  return `edit[${index}] "text" must be a string with \\n line separators, not an array. An empty string deletes the range.`;
@@ -15253,7 +15356,7 @@ function analyzeRequest(input) {
15253
15356
  if (rootOffending.length > 0) {
15254
15357
  return {
15255
15358
  ok: false,
15256
- 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)
15257
15360
  };
15258
15361
  }
15259
15362
  let mode;
@@ -15307,9 +15410,13 @@ function analyzeRequest(input) {
15307
15410
  }
15308
15411
  function normalizedItemFrom(item) {
15309
15412
  const at = item.at ?? "in-place";
15310
- 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 ?? "" };
15414
+ const target = {
15415
+ anchor_from: item.anchor_from,
15416
+ anchor_to: item.anchor_to ?? item.anchor_from
15417
+ };
15311
15418
  return {
15312
- target: { anchor_from: item.anchor_from, anchor_to: item.anchor_to },
15419
+ target,
15313
15420
  at,
15314
15421
  payload
15315
15422
  };
@@ -15349,6 +15456,9 @@ function isNormalizedEditItem(value) {
15349
15456
  if (payload.kind === "reference") {
15350
15457
  return isRec(payload.span) && typeof payload.span.anchor_from === "string" && typeof payload.span.anchor_to === "string" && (payload.mode === "copy" || payload.mode === "cut");
15351
15458
  }
15459
+ if (payload.kind === "insert") {
15460
+ return (payload.side === "before" || payload.side === "after") && typeof payload.text === "string";
15461
+ }
15352
15462
  return false;
15353
15463
  }
15354
15464
  function assertReq(request) {
@@ -15557,6 +15667,107 @@ function createEditTool() {
15557
15667
  };
15558
15668
  }
15559
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
+
15560
15771
  // dsh/tools/edit.ts
15561
15772
  var EDIT_TOOL_NAME = "edit";
15562
15773
  var EDIT_PARAMETERS = {
@@ -15579,9 +15790,13 @@ var EDIT_PARAMETERS = {
15579
15790
  description: "Bare hash anchor of the first range line (inclusive)"
15580
15791
  },
15581
15792
  anchor_to: {
15582
- type: "string",
15583
- required: true,
15584
- description: "Bare hash anchor of the last range line (inclusive)"
15793
+ oneOf: [
15794
+ {
15795
+ type: "string",
15796
+ description: "Bare hash anchor of the last range line (inclusive); omit it to edit the single line anchor_from names"
15797
+ },
15798
+ { type: "null" }
15799
+ ]
15585
15800
  },
15586
15801
  at: {
15587
15802
  oneOf: [
@@ -15602,6 +15817,24 @@ var EDIT_PARAMETERS = {
15602
15817
  { type: "null" }
15603
15818
  ]
15604
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
+ },
15605
15838
  text_ref: {
15606
15839
  oneOf: [
15607
15840
  {
@@ -15720,10 +15953,13 @@ function buildEditTool(deps) {
15720
15953
  throw new DomainError("E_NOT_FOUND", { path: admitted.file });
15721
15954
  }
15722
15955
  }
15956
+ const syntaxBefore = await readSyntaxBaseline(deps.io, absolutePath, toolCtx.signal);
15723
15957
  const members = writtenMemberFiles(admitted);
15724
15958
  await announcePluginWrites(deps, members, toolCtx, exec);
15725
15959
  const result = await tool.execute(admitted, toolCtx.signal, upstreamContext(toolCtx));
15726
- 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);
15727
15963
  await publishPluginWrites(deps, members, toolCtx, exec);
15728
15964
  metrics?.record({
15729
15965
  tool: "edit",