dsh-hashline-edit 0.4.3 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/CHANGELOG.md +345 -0
  2. package/README.md +58 -5
  3. package/cordis.patch.yml +11 -1
  4. package/grammars/go-0.25.0-9504573f352b20be.wasm +0 -0
  5. package/grammars/java-0.23.5-4fdeac4ca6ca089f.wasm +0 -0
  6. package/grammars/python-0.25.0-16108b50df4ee9a3.wasm +0 -0
  7. package/grammars/rust-0.24.2-24c89bd9252255e4.wasm +0 -0
  8. package/grammars/tsx-0.23.2-79e5da75ea62855a.wasm +0 -0
  9. package/grammars/typescript-0.23.2-778025db5a8be0e7.wasm +0 -0
  10. package/grammars/vue-0.1.0-193c01119229352f.wasm +0 -0
  11. package/lib/client.js +13 -3
  12. package/lib/index.js +2345 -75
  13. package/lib/types/dsh/codegraph/cli.d.ts +61 -0
  14. package/lib/types/dsh/codegraph/project.d.ts +27 -0
  15. package/lib/types/dsh/codegraph/tools.d.ts +36 -0
  16. package/lib/types/dsh/codegraph/view.d.ts +25 -0
  17. package/lib/types/dsh/diagnostics/cli.d.ts +76 -0
  18. package/lib/types/dsh/diagnostics/messages.d.ts +37 -0
  19. package/lib/types/dsh/diagnostics/parse.d.ts +39 -0
  20. package/lib/types/dsh/diagnostics/tools.d.ts +20 -0
  21. package/lib/types/dsh/diagnostics/view.d.ts +31 -0
  22. package/lib/types/dsh/guidance.d.ts +7 -3
  23. package/lib/types/dsh/index.d.ts +32 -3
  24. package/lib/types/dsh/syntax-health.d.ts +60 -0
  25. package/lib/types/dsh/tools/edit.d.ts +15 -1
  26. package/lib/types/dsh/tools/output.d.ts +10 -0
  27. package/lib/types/dsh/tools/read-folded.d.ts +85 -0
  28. package/lib/types/src/bundled-assets.d.ts +13 -0
  29. package/lib/types/src/domain-errors.d.ts +12 -1
  30. package/lib/types/src/edit-tool.d.ts +9 -1
  31. package/lib/types/src/mutation-engine/edit-expand.d.ts +36 -0
  32. package/lib/types/src/mutation-engine/edit-indent.d.ts +49 -0
  33. package/lib/types/src/mutation-engine/edit-request.d.ts +8 -0
  34. package/lib/types/src/mutation-engine/types.d.ts +57 -0
  35. package/lib/types/src/payload-contract.d.ts +8 -0
  36. package/lib/types/src/read-expansion/fold-skeleton.d.ts +32 -0
  37. package/lib/types/src/read-expansion/grammar-manifest.d.ts +3 -1
  38. package/lib/types/src/read-expansion/grammar-runtime.d.ts +1 -1
  39. package/lib/types/src/read-expansion/span-expansion.d.ts +26 -0
  40. package/package.json +21 -23
  41. package/prompts/codegraph-guidelines.md +8 -0
  42. package/prompts/diagnostics-guidelines.md +8 -0
  43. package/prompts/edit-guidelines.md +6 -2
  44. package/prompts/edit.md +3 -1
  45. package/prompts/read-description.md +1 -1
  46. package/prompts/read-guidelines.md +3 -1
  47. package/src/bundled-assets.ts +23 -0
  48. package/src/domain-errors.ts +52 -1
  49. package/src/edit-tool.ts +12 -1
  50. package/src/mutation-engine/edit-expand.ts +328 -0
  51. package/src/mutation-engine/edit-indent.ts +121 -0
  52. package/src/mutation-engine/edit-request.ts +8 -1
  53. package/src/mutation-engine/pipeline.ts +150 -48
  54. package/src/mutation-engine/types.ts +54 -0
  55. package/src/payload-contract.ts +165 -19
  56. package/src/read-expansion/ast-provider.ts +32 -0
  57. package/src/read-expansion/fold-skeleton.ts +56 -0
  58. package/src/read-expansion/grammar-cache.ts +33 -1
  59. package/src/read-expansion/grammar-manifest.ts +3 -1
  60. package/src/read-expansion/grammar-runtime.ts +1 -1
  61. package/src/read-expansion/qualified-names.ts +7 -0
  62. package/src/read-expansion/read-provider.ts +9 -0
  63. package/src/read-expansion/span-expansion.ts +26 -0
package/lib/index.js CHANGED
@@ -112,6 +112,19 @@ function unsupportedFormat(payload) {
112
112
  }
113
113
  return `Path is a binary file: ${payload.path} (${payload.description ?? "binary"}).`;
114
114
  }
115
+ function expandUnavailableFormat(payload) {
116
+ const where = `line ${payload.line} of ${payload.path}`;
117
+ if (payload.reason === "non-code") {
118
+ return `"expand": "item" is unavailable at ${where}: the shipped syntax grammars serve rust, typescript, tsx, vue, python, go and java files only. Nothing was written.`;
119
+ }
120
+ if (payload.reason === "grammar-unavailable") {
121
+ return `"expand": "item" is unavailable at ${where}: this host has no syntax grammar for the file. Nothing was written.`;
122
+ }
123
+ if (payload.reason === "stale-content") {
124
+ return `"expand": "item" is unavailable at ${where}: the resolved syntax item no longer contains the anchor line. Nothing was written.`;
125
+ }
126
+ return `"expand": "item" is unavailable at ${where}: no single syntax item contains that line \u2014 it sits outside every item (imports, file header) or the syntax tree could not resolve one. Nothing was written.`;
127
+ }
115
128
  function accessFormat(payload) {
116
129
  if (payload.kind === "symlink-loop") {
117
130
  return `Too many symbolic links while resolving: ${payload.path}.`;
@@ -345,6 +358,10 @@ ${servedBlock}`
345
358
  E_UNIQUE_MATCH: {
346
359
  audience: "MODEL",
347
360
  format: ({ message }) => message
361
+ },
362
+ E_EXPAND_UNAVAILABLE: {
363
+ audience: "MODEL",
364
+ format: expandUnavailableFormat
348
365
  }
349
366
  };
350
367
  function neverServedShapeFormat(payload) {
@@ -1948,6 +1965,16 @@ var GUIDANCE_SECTIONS = [
1948
1965
  orderName: "TOOL_READ",
1949
1966
  renderDefault: () => guidanceText("", loadGuide("../prompts/read-guidelines.md"))
1950
1967
  },
1968
+ {
1969
+ name: "tool:codegraph",
1970
+ defaultOrder: 1200,
1971
+ renderDefault: () => guidanceText("", loadGuide("../prompts/codegraph-guidelines.md"))
1972
+ },
1973
+ {
1974
+ name: "tool:diagnostics",
1975
+ defaultOrder: 1250,
1976
+ renderDefault: () => guidanceText("", loadGuide("../prompts/diagnostics-guidelines.md"))
1977
+ },
1951
1978
  {
1952
1979
  name: "tool:write",
1953
1980
  defaultOrder: 1300,
@@ -1996,6 +2023,8 @@ function sectionEnabled(name2, toggles) {
1996
2023
  if (name2 === "tool:write") return toggles.applyPatch || toggles.edit;
1997
2024
  if (name2 === "tool:apply_patch") return toggles.applyPatch;
1998
2025
  if (name2 === "tool:edit") return toggles.edit;
2026
+ if (name2 === "tool:codegraph") return toggles.codegraph === true;
2027
+ if (name2 === "tool:diagnostics") return toggles.diagnostics === true;
1999
2028
  return true;
2000
2029
  }
2001
2030
  function toolVisible(agentCtx, name2) {
@@ -8376,11 +8405,39 @@ function findEnclosingScope(root, requestedStart, requestedEnd, scopeKinds) {
8376
8405
  return best ?? null;
8377
8406
  }
8378
8407
 
8408
+ // src/read-expansion/fold-skeleton.ts
8409
+ function collectSkeletonItems(root, kinds, decorate) {
8410
+ const items = [];
8411
+ const visit = (node, depth) => {
8412
+ for (const child of node.namedChildren) {
8413
+ if (!Object.hasOwn(kinds, child.type)) {
8414
+ visit(child, depth);
8415
+ continue;
8416
+ }
8417
+ const decorated = decorate(child);
8418
+ items.push({ startLine: decorated.startLine, endLine: decorated.endLine, depth });
8419
+ visit(child, depth + 1);
8420
+ }
8421
+ };
8422
+ visit(root, 1);
8423
+ return items;
8424
+ }
8425
+
8379
8426
  // src/read-expansion/grammar-cache.ts
8380
8427
  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";
8428
+ import { existsSync as existsSync3, mkdirSync as mkdirSync5, readFileSync as readFileSync3, renameSync as renameSync4, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
8382
8429
  import { dirname as dirname7, join as join8 } from "node:path";
8383
8430
 
8431
+ // src/bundled-assets.ts
8432
+ import { readFileSync as readFileSync2 } from "node:fs";
8433
+ function readBundledAsset(relativePath2) {
8434
+ try {
8435
+ return readFileSync2(new URL(`../${relativePath2}`, import.meta.url));
8436
+ } catch {
8437
+ return void 0;
8438
+ }
8439
+ }
8440
+
8384
8441
  // src/read-expansion/grammar-manifest.ts
8385
8442
  var GRAMMAR_MANIFEST = {
8386
8443
  typescript: {
@@ -8473,7 +8530,7 @@ function readVerifiedCache(path, expected) {
8473
8530
  if (!existsSync3(path)) return void 0;
8474
8531
  let bytes;
8475
8532
  try {
8476
- bytes = readFileSync2(path);
8533
+ bytes = readFileSync3(path);
8477
8534
  } catch {
8478
8535
  discardCachedGrammar(path);
8479
8536
  return void 0;
@@ -8536,6 +8593,11 @@ async function requestGrammar(language, options = {}) {
8536
8593
  const path = grammarCachePath(language, entry, options.cacheRoot);
8537
8594
  const cached = readVerifiedCache(path, entry.sha256);
8538
8595
  if (cached !== void 0) return { status: "ready", artifact: { language, path, bytes: cached } };
8596
+ const bundled = bundledGrammarBytes(language, entry);
8597
+ if (bundled !== void 0) {
8598
+ writeCache(path, bundled);
8599
+ return { status: "ready", artifact: { language, path, bytes: bundled } };
8600
+ }
8539
8601
  let pending = inFlight.get(path);
8540
8602
  if (pending === void 0) {
8541
8603
  pending = fetchAndCache(entry, path, options);
@@ -8550,6 +8612,16 @@ async function requestGrammar(language, options = {}) {
8550
8612
  if (fetched === void 0) return { status: "unavailable", language };
8551
8613
  return { status: "ready", artifact: { language, path, bytes: fetched } };
8552
8614
  }
8615
+ async function ensureGrammar(language, options = {}) {
8616
+ const result = await requestGrammar(language, options);
8617
+ return result.status === "ready" ? result.artifact : void 0;
8618
+ }
8619
+ function bundledGrammarBytes(language, entry) {
8620
+ const name2 = `${language}-${entry.version}-${entry.sha256.slice(0, 16)}.wasm`;
8621
+ const bytes = readBundledAsset(`grammars/${name2}`);
8622
+ if (bytes === void 0) return void 0;
8623
+ return sha256Hex(bytes) === entry.sha256 ? bytes : void 0;
8624
+ }
8553
8625
 
8554
8626
  // src/read-expansion/grammar-runtime.ts
8555
8627
  var runtime;
@@ -8889,7 +8961,7 @@ function decline(refusal, language) {
8889
8961
  function createAstSpanProvider(options = {}) {
8890
8962
  const handles = /* @__PURE__ */ new Map();
8891
8963
  const loadGrammar = options.loadGrammar ?? loadWebTreeSitterGrammar;
8892
- const readText = options.readTextFile ?? defaultReadText;
8964
+ const readText2 = options.readTextFile ?? defaultReadText;
8893
8965
  const runtimeAvailable = options.runtimeAvailable ?? hasWebTreeSitterRuntime;
8894
8966
  const usesDefaultRuntime = options.loadGrammar === void 0;
8895
8967
  let runtimeAbsent = false;
@@ -8968,11 +9040,40 @@ function createAstSpanProvider(options = {}) {
8968
9040
  return runtimeAbsent;
8969
9041
  },
8970
9042
  prefetch,
9043
+ /**
9044
+ * The whole file's structural skeleton: every item the language's kind table owns, at its
9045
+ * nesting depth. WHY it reuses the boundary policy: the same handle cache, the same decline
9046
+ * vocabulary and the same decoration tables mean a folded read and a widened read can never
9047
+ * disagree about what an item is.
9048
+ */
9049
+ async skeleton(file) {
9050
+ const language = grammarLanguageForFile(file);
9051
+ if (language === void 0) return decline("no_provider");
9052
+ const languageScope = LANGUAGES[language];
9053
+ if (languageScope === void 0) return decline("no_provider", language);
9054
+ const source = await readText2(file);
9055
+ if (source === void 0) return decline("provider_declined", language);
9056
+ const outcome = await handleFor(language);
9057
+ if (outcome.kind === "decline") return outcome.decline;
9058
+ const tree = outcome.handle.parse(source);
9059
+ if (tree === null) return decline("grammar_unavailable", language);
9060
+ try {
9061
+ if (tree.rootNode.hasError) return decline("provider_declined", language);
9062
+ return {
9063
+ items: collectSkeletonItems(tree.rootNode, languageScope.kinds, languageScope.decorate)
9064
+ };
9065
+ } catch {
9066
+ outcome.handle.onFailure?.();
9067
+ return decline("provider_declined", language);
9068
+ } finally {
9069
+ tree.delete?.();
9070
+ }
9071
+ },
8971
9072
  async enclosingSpan(file, window) {
8972
9073
  if (!isOffsetWindow(window)) return decline("provider_declined");
8973
9074
  const language = grammarLanguageForFile(file);
8974
9075
  if (language === void 0) return decline("no_provider");
8975
- const source = await readText(file);
9076
+ const source = await readText2(file);
8976
9077
  if (source === void 0) return decline("provider_declined", language);
8977
9078
  const languageScope = LANGUAGES[language];
8978
9079
  if (languageScope === void 0) return decline("no_provider", language);
@@ -9119,12 +9220,12 @@ async function defaultReadText2(path) {
9119
9220
  }
9120
9221
  }
9121
9222
  function createMarkdownSpanProvider(options = {}) {
9122
- const readText = options.readTextFile ?? defaultReadText2;
9223
+ const readText2 = options.readTextFile ?? defaultReadText2;
9123
9224
  return {
9124
9225
  async enclosingSpan(file, window) {
9125
9226
  if (!("offset" in window) || !("limit" in window)) return { refusal: "provider_declined" };
9126
9227
  if (!isMarkdownPath(file)) return { refusal: "no_provider" };
9127
- const text = await readText(file);
9228
+ const text = await readText2(file);
9128
9229
  if (text === void 0) return { refusal: "provider_declined" };
9129
9230
  const section = findMarkdownSection(text, window.offset, window.offset + window.limit - 1);
9130
9231
  if (section === null) return { refusal: "boundary_crossing" };
@@ -9225,12 +9326,12 @@ function functionName(fn) {
9225
9326
  return value.trim() === "" ? "function" : value.trim();
9226
9327
  }
9227
9328
  function createBashSpanProvider(options = {}) {
9228
- const readText = options.readTextFile ?? defaultReadText3;
9329
+ const readText2 = options.readTextFile ?? defaultReadText3;
9229
9330
  return {
9230
9331
  async enclosingSpan(file, window) {
9231
9332
  if (!("offset" in window) || !("limit" in window)) return { refusal: "provider_declined" };
9232
9333
  if (!isShellPath(file)) return { refusal: "no_provider" };
9233
- const text = await readText(file);
9334
+ const text = await readText2(file);
9234
9335
  if (text === void 0) return { refusal: "provider_declined" };
9235
9336
  let script;
9236
9337
  try {
@@ -9314,12 +9415,12 @@ async function defaultReadText4(path) {
9314
9415
  }
9315
9416
  }
9316
9417
  function createParagraphSpanProvider(options = {}) {
9317
- const readText = options.readTextFile ?? defaultReadText4;
9418
+ const readText2 = options.readTextFile ?? defaultReadText4;
9318
9419
  return {
9319
9420
  async enclosingSpan(file, window) {
9320
9421
  if (!("offset" in window) || !("limit" in window)) return { refusal: "provider_declined" };
9321
9422
  if (!isPlainTextPath(file)) return { refusal: "no_provider" };
9322
- const text = await readText(file);
9423
+ const text = await readText2(file);
9323
9424
  if (text === void 0) return { refusal: "provider_declined" };
9324
9425
  const paragraph = findParagraph(text, window.offset, window.offset + window.limit - 1);
9325
9426
  if (paragraph === null) return { refusal: "boundary_crossing" };
@@ -9379,6 +9480,12 @@ function withQualifiedNames(provider, resolver, timeoutMs = DEFAULT_QUALIFIED_NA
9379
9480
  } catch {
9380
9481
  }
9381
9482
  return span;
9483
+ },
9484
+ // WHY: a name resolver has nothing to say about an item list, so the skeleton is forwarded
9485
+ // WHY: untouched instead of being dropped with the other members.
9486
+ skeleton(file) {
9487
+ const derive = provider.skeleton;
9488
+ return derive === void 0 ? { refusal: "no_provider" } : derive(file);
9382
9489
  }
9383
9490
  };
9384
9491
  }
@@ -9408,6 +9515,13 @@ function createReadSpanProvider(options = {}) {
9408
9515
  if (isPlainTextPath(file)) return paragraph.enclosingSpan(file, window);
9409
9516
  if (isShellPath(file)) return bash.enclosingSpan(file, window);
9410
9517
  return ast.enclosingSpan(file, window);
9518
+ },
9519
+ skeleton(file) {
9520
+ if (isMarkdownPath(file) || isDataPath(file) || isPlainTextPath(file) || isShellPath(file)) {
9521
+ return { refusal: "no_provider" };
9522
+ }
9523
+ const derive = ast.skeleton;
9524
+ return derive === void 0 ? { refusal: "no_provider" } : derive(file);
9411
9525
  }
9412
9526
  };
9413
9527
  return withQualifiedNames(
@@ -9753,7 +9867,7 @@ import {
9753
9867
  constants as constants5,
9754
9868
  existsSync as existsSync4,
9755
9869
  mkdirSync as mkdirSync6,
9756
- readFileSync as readFileSync3,
9870
+ readFileSync as readFileSync4,
9757
9871
  renameSync as renameSync5,
9758
9872
  unlinkSync as unlinkSync2,
9759
9873
  writeFileSync as writeFileSync3
@@ -9825,7 +9939,7 @@ function reasonOf2(error) {
9825
9939
  function readConfigObject(path, onWarn) {
9826
9940
  let raw;
9827
9941
  try {
9828
- raw = readFileSync3(path, "utf-8");
9942
+ raw = readFileSync4(path, "utf-8");
9829
9943
  } catch (error) {
9830
9944
  if (!isMissingFile(error)) onWarn?.(`cannot read config ${path}: ${reasonOf2(error)}`);
9831
9945
  return void 0;
@@ -9974,10 +10088,127 @@ async function publishPluginWrites(deps, requestPaths, ctx, exec) {
9974
10088
  }
9975
10089
  }
9976
10090
 
10091
+ // dsh/tools/read-folded.ts
10092
+ var DEFAULT_FOLD_DEPTH = 1;
10093
+ var MAX_FOLD_DEPTH = 3;
10094
+ var FOLDED_VIEW_LABEL = "Folded view";
10095
+ function badPayload2(message) {
10096
+ return new DomainError("E_BAD_PAYLOAD", { message });
10097
+ }
10098
+ function admitFoldedRequest(params) {
10099
+ if (params.mode !== "folded") {
10100
+ if (params.foldDepth === void 0) return void 0;
10101
+ throw badPayload2(
10102
+ 'Read request field "foldDepth" is only valid together with "mode": "folded".'
10103
+ );
10104
+ }
10105
+ const foldDepth = admitFoldDepth(params.foldDepth);
10106
+ const rest = {};
10107
+ for (const [key, value] of Object.entries(params)) {
10108
+ if (key === "mode" || key === "foldDepth") continue;
10109
+ rest[key] = value;
10110
+ }
10111
+ const request = admitReadRequest(rest);
10112
+ if (request.windows !== void 0) {
10113
+ throw badPayload2(
10114
+ 'A "mode": "folded" read always covers the whole file; drop "offset", "limit" and "windows".'
10115
+ );
10116
+ }
10117
+ return { request, foldDepth };
10118
+ }
10119
+ function admitFoldDepth(value) {
10120
+ if (value === void 0) return DEFAULT_FOLD_DEPTH;
10121
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > MAX_FOLD_DEPTH) {
10122
+ throw badPayload2(
10123
+ `Read request field "foldDepth" must be an integer from 1 to ${MAX_FOLD_DEPTH}; it sets how deeply a folded read reveals nested items.`
10124
+ );
10125
+ }
10126
+ return value;
10127
+ }
10128
+ function foldSegments(items, totalLines, foldDepth) {
10129
+ const kept = items.filter(
10130
+ (item) => item.depth <= foldDepth && item.startLine >= 1 && item.endLine <= totalLines && item.startLine <= item.endLine
10131
+ ).sort((left, right) => left.startLine - right.startLine || right.endLine - left.endLine);
10132
+ const segments = [];
10133
+ let next = 1;
10134
+ for (const item of kept) {
10135
+ if (item.startLine > next) {
10136
+ segments.push({ kind: "gap", startLine: next, endLine: item.startLine - 1 });
10137
+ }
10138
+ segments.push({ kind: "item", startLine: item.startLine, endLine: item.endLine });
10139
+ next = Math.max(next, item.endLine + 1);
10140
+ }
10141
+ if (next <= totalLines) segments.push({ kind: "gap", startLine: next, endLine: totalLines });
10142
+ return segments;
10143
+ }
10144
+ function foldedLineNumbers(segments) {
10145
+ const lines = [];
10146
+ for (const segment of segments) {
10147
+ lines.push(segment.startLine);
10148
+ if (segment.endLine !== segment.startLine) lines.push(segment.endLine);
10149
+ }
10150
+ return lines;
10151
+ }
10152
+ function gapContent(count) {
10153
+ return `\u2026 (${count} ${count === 1 ? "line" : "lines"}) \u2026`;
10154
+ }
10155
+ function foldedLabel(itemCount, elided) {
10156
+ const items = `${itemCount} ${itemCount === 1 ? "item" : "items"}`;
10157
+ const lines = `${elided} ${elided === 1 ? "line" : "lines"} elided`;
10158
+ return `${FOLDED_VIEW_LABEL}, ${items}, ${lines}`;
10159
+ }
10160
+ async function renderFoldedPage(input) {
10161
+ const segments = foldSegments(input.items, input.totalLines, input.foldDepth);
10162
+ const served = await input.serve(foldedLineNumbers(segments));
10163
+ const byLine = /* @__PURE__ */ new Map();
10164
+ for (const row of served) byLine.set(row.line, row);
10165
+ const rows = [];
10166
+ let itemCount = 0;
10167
+ for (const segment of segments) {
10168
+ const first = byLine.get(segment.startLine);
10169
+ const last = segment.endLine === segment.startLine ? first : byLine.get(segment.endLine);
10170
+ if (first === void 0 || last === void 0) return void 0;
10171
+ if (segment.kind === "item") {
10172
+ itemCount += 1;
10173
+ rows.push(
10174
+ segment.endLine === segment.startLine ? `${first.hash}${HASH_SEP}${first.text}` : `${first.hash}..${last.hash}${HASH_SEP}${first.text}`
10175
+ );
10176
+ continue;
10177
+ }
10178
+ const count = segment.endLine - segment.startLine + 1;
10179
+ rows.push(
10180
+ segment.endLine === segment.startLine ? `${first.hash}${HASH_SEP}${gapContent(count)}` : `${first.hash}..${last.hash}${HASH_SEP}${gapContent(count)}`
10181
+ );
10182
+ }
10183
+ const header = formatPageHeader({
10184
+ label: foldedLabel(itemCount, input.totalLines - itemCount),
10185
+ file: input.file,
10186
+ totalLines: input.totalLines
10187
+ });
10188
+ return { text: [header, ...rows].join("\n") };
10189
+ }
10190
+ var UNAVAILABLE_REASONS = {
10191
+ no_provider: "this file has no supported grammar",
10192
+ grammar_unavailable: "its grammar is unavailable",
10193
+ cold_grammar: "its grammar is still loading",
10194
+ runtime_absent: "the grammar runtime is unavailable",
10195
+ provider_declined: "the parser declined this file",
10196
+ provider_error: "the parser failed on it",
10197
+ boundary_crossing: "no item encloses this file",
10198
+ invalid_answer: "the parser gave no usable item",
10199
+ not_superset: "the parser gave no usable item",
10200
+ unanchored: "its items could not be anchored",
10201
+ empty_file: "the file has no lines"
10202
+ };
10203
+ function foldedUnavailableNote(reason) {
10204
+ const detail = UNAVAILABLE_REASONS[reason] ?? "its structure could not be derived";
10205
+ return `[Folded view unavailable: ${detail}. Showing the served page instead.]`;
10206
+ }
10207
+
9977
10208
  // dsh/tools/read.ts
9978
10209
  var READ_TOOL_NAME = "read";
9979
10210
  var READ_DESCRIPTION = loadP("../prompts/read-description.md");
9980
- var RENDER_MODES = ["served", "verbatim"];
10211
+ var READ_MODES = ["served", "verbatim", "folded"];
9981
10212
  function createDefaultReadSpanProvider(io) {
9982
10213
  const readTextFile = io === void 0 ? void 0 : async (path) => {
9983
10214
  try {
@@ -10279,7 +10510,8 @@ async function serveFileLines(deps, request) {
10279
10510
  async function readAndServe(deps, rawArgs, exec, spanProvider) {
10280
10511
  const ctx = resolveToolContext(exec);
10281
10512
  const raw = rawArgs;
10282
- const request = admitReadRequest(raw);
10513
+ const folded = admitFoldedRequest(raw);
10514
+ const request = folded === void 0 ? admitReadRequest(raw) : folded.request;
10283
10515
  const mode = request.mode;
10284
10516
  const absolutePath = toCwd(request.file, ctx.cwd);
10285
10517
  ctx.signal?.throwIfAborted();
@@ -10305,6 +10537,18 @@ async function readAndServe(deps, rawArgs, exec, spanProvider) {
10305
10537
  })();
10306
10538
  return resolvedText;
10307
10539
  };
10540
+ if (folded !== void 0) {
10541
+ return foldedReadPage({
10542
+ deps,
10543
+ exec,
10544
+ ctx,
10545
+ request,
10546
+ absolutePath,
10547
+ normalized,
10548
+ spanProvider,
10549
+ foldDepth: folded.foldDepth
10550
+ });
10551
+ }
10308
10552
  const wantsAnchor = request.windows?.some((window) => window.kind === "anchor") === true;
10309
10553
  const store = mode === "served" || wantsAnchor ? await loadHashStore() : void 0;
10310
10554
  const anchorText = wantsAnchor ? await normalized() : void 0;
@@ -10363,6 +10607,49 @@ async function readAndServe(deps, rawArgs, exec, spanProvider) {
10363
10607
  ...presentation === void 0 ? {} : { presentation }
10364
10608
  };
10365
10609
  }
10610
+ async function foldedReadPage(input) {
10611
+ const { deps, exec, ctx, request, absolutePath, spanProvider } = input;
10612
+ const fallback = async (reason) => {
10613
+ const served = await readAndServe(
10614
+ deps,
10615
+ { path: request.file, mode: "served" },
10616
+ exec,
10617
+ spanProvider
10618
+ );
10619
+ return { ...served, text: `${foldedUnavailableNote(reason)}
10620
+
10621
+ ${served.text}` };
10622
+ };
10623
+ const provider = spanProvider;
10624
+ if (provider === void 0 || provider.skeleton === void 0) return fallback("no_provider");
10625
+ let answer;
10626
+ try {
10627
+ answer = await provider.skeleton(absolutePath);
10628
+ } catch {
10629
+ answer = { refusal: "provider_error" };
10630
+ }
10631
+ if ("refusal" in answer) return fallback(answer.refusal);
10632
+ const text = await input.normalized();
10633
+ if (text === void 0) return fallback("not_text");
10634
+ const totalLines = visibleLineTotal(text.normalized, walkLines(text.normalized).total);
10635
+ if (totalLines === 0) return fallback("empty_file");
10636
+ const page = await renderFoldedPage({
10637
+ file: request.file,
10638
+ totalLines,
10639
+ foldDepth: input.foldDepth,
10640
+ items: answer.items,
10641
+ serve: (lineNumbers) => serveFileLines(deps, {
10642
+ path: request.file,
10643
+ cwd: ctx.cwd,
10644
+ sessionKey: ctx.sessionKey,
10645
+ signal: ctx.signal,
10646
+ lineNumbers
10647
+ })
10648
+ });
10649
+ if (page === void 0) return fallback("unanchored");
10650
+ await deps.observations?.publish(absolutePath, exec, { signal: ctx.signal });
10651
+ return { text: page.text };
10652
+ }
10366
10653
  var MAX_PRESENTATION_LINES = 400;
10367
10654
  var MAX_PRESENTATION_LINE_CHARS = 2048;
10368
10655
  function capPresentationLine(text) {
@@ -10473,8 +10760,12 @@ function buildReadTool(deps, options = {}) {
10473
10760
  },
10474
10761
  mode: {
10475
10762
  type: "string",
10476
- enum: RENDER_MODES,
10477
- description: "`served` (default) returns `HASH\u2502content` rows and records them as served; `verbatim` returns plain text with no anchors."
10763
+ enum: READ_MODES,
10764
+ description: "`served` (default) returns `HASH\u2502content` rows and records them as served; `verbatim` returns plain text with no anchors; `folded` returns the file's structural skeleton \u2014 one anchored row per syntax item \u2014 and always covers the whole file."
10765
+ },
10766
+ foldDepth: {
10767
+ type: "number",
10768
+ description: "Folded mode only: how deeply the skeleton nests, 1-3 (default 1). 1 keeps top-level items and each value reaches one level deeper. Refused unless `mode` is `folded`."
10478
10769
  }
10479
10770
  },
10480
10771
  output: {
@@ -13162,6 +13453,251 @@ async function repairCutIntents(store) {
13162
13453
  }
13163
13454
  }
13164
13455
 
13456
+ // src/mutation-engine/edit-indent.ts
13457
+ function leadingWhitespaceOf(line) {
13458
+ let end = 0;
13459
+ while (end < line.length && (line[end] === " " || line[end] === " ")) end += 1;
13460
+ return line.slice(0, end);
13461
+ }
13462
+ function isBlankLine(line) {
13463
+ return line.trim() === "";
13464
+ }
13465
+ function commonIndentPrefix(lines) {
13466
+ let prefix;
13467
+ for (const line of lines) {
13468
+ if (isBlankLine(line)) continue;
13469
+ const indent = leadingWhitespaceOf(line);
13470
+ if (prefix === void 0) {
13471
+ prefix = indent;
13472
+ if (prefix === "") return "";
13473
+ continue;
13474
+ }
13475
+ let shared = 0;
13476
+ while (shared < prefix.length && shared < indent.length && prefix[shared] === indent[shared]) {
13477
+ shared += 1;
13478
+ }
13479
+ prefix = prefix.slice(0, shared);
13480
+ if (prefix === "") return "";
13481
+ }
13482
+ return prefix ?? "";
13483
+ }
13484
+ function applyAutoIndent(text, baseIndent) {
13485
+ const lines = text.split("\n");
13486
+ const strippedPrefix = commonIndentPrefix(lines);
13487
+ let changedLines = 0;
13488
+ const rebased = lines.map((line) => {
13489
+ if (isBlankLine(line)) return line;
13490
+ const next = `${baseIndent}${line.slice(strippedPrefix.length)}`;
13491
+ if (next !== line) changedLines += 1;
13492
+ return next;
13493
+ });
13494
+ const nextText = rebased.join("\n");
13495
+ return {
13496
+ text: nextText,
13497
+ changed: nextText !== text,
13498
+ changedLines,
13499
+ strippedPrefix
13500
+ };
13501
+ }
13502
+ function describeIndent(indent) {
13503
+ if (indent === "") return "no indentation";
13504
+ if (/^ +$/.test(indent)) {
13505
+ return indent.length === 1 ? "1 space" : `${indent.length} spaces`;
13506
+ }
13507
+ if (/^\t+$/.test(indent)) {
13508
+ return indent.length === 1 ? "1 tab" : `${indent.length} tabs`;
13509
+ }
13510
+ return `the exact prefix ${JSON.stringify(indent)}`;
13511
+ }
13512
+ function buildIndentNote(args) {
13513
+ const { ref, summary } = args;
13514
+ const stripped = summary.strippedPrefix === "" ? "" : `; a shared ${describeIndent(summary.strippedPrefix)} prefix was dropped from the payload`;
13515
+ return `${ref}: "indent": "auto" re-indented ${summary.changedLines} line(s) to the anchor line's ${describeIndent(summary.baseIndent)}${stripped}.`;
13516
+ }
13517
+
13518
+ // src/mutation-engine/edit-expand.ts
13519
+ var sharedProvider;
13520
+ function defaultExpandProvider() {
13521
+ if (sharedProvider === void 0) sharedProvider = createAstSpanProvider();
13522
+ return sharedProvider;
13523
+ }
13524
+ function refusalReasonOf(answer) {
13525
+ if (answer === null) return "no-enclosing-item";
13526
+ if (!("refusal" in answer)) return "no-enclosing-item";
13527
+ switch (answer.refusal) {
13528
+ case "no_provider":
13529
+ case "not_text":
13530
+ case "toggle_off":
13531
+ return "non-code";
13532
+ case "grammar_unavailable":
13533
+ case "cold_grammar":
13534
+ case "runtime_absent":
13535
+ return "grammar-unavailable";
13536
+ default:
13537
+ return "no-enclosing-item";
13538
+ }
13539
+ }
13540
+ function expandUnavailable(args) {
13541
+ return new DomainError("E_EXPAND_UNAVAILABLE", {
13542
+ path: args.path,
13543
+ line: args.line,
13544
+ reason: args.reason
13545
+ });
13546
+ }
13547
+ async function resolveEnclosingItem(args) {
13548
+ const answer = await args.provider.enclosingSpan(args.absolutePath, {
13549
+ offset: args.anchorLine,
13550
+ limit: 1
13551
+ });
13552
+ if (answer === null || "refusal" in answer) {
13553
+ throw expandUnavailable({
13554
+ path: args.filePath,
13555
+ line: args.anchorLine,
13556
+ reason: refusalReasonOf(answer)
13557
+ });
13558
+ }
13559
+ const startLine = answer.start;
13560
+ const endLine = answer.end;
13561
+ if (!Number.isInteger(startLine) || !Number.isInteger(endLine) || startLine < 1 || endLine < startLine || startLine > args.anchorLine || endLine < args.anchorLine || endLine > args.totalLines) {
13562
+ throw expandUnavailable({
13563
+ path: args.filePath,
13564
+ line: args.anchorLine,
13565
+ reason: "stale-content"
13566
+ });
13567
+ }
13568
+ return { startLine, endLine };
13569
+ }
13570
+ function replaceItemSpan(content, startLine, endLine, lines) {
13571
+ const fileLines = splitLines(content);
13572
+ const out = [...fileLines.slice(0, startLine - 1), ...lines, ...fileLines.slice(endLine)];
13573
+ return serializeLineList(content, fileLines, void 0, out);
13574
+ }
13575
+ async function applyExpandedItem(input) {
13576
+ abortIf(input.signal);
13577
+ const lines = splitLines(input.content);
13578
+ const leased = resolveLeasedEdit({
13579
+ edit: {
13580
+ content_lines: [],
13581
+ hash_bounds: [input.edit.hash_bounds[0], input.edit.hash_bounds[0]]
13582
+ },
13583
+ snapshot: {
13584
+ fileHashes: input.hashes,
13585
+ fileLines: lines,
13586
+ filePath: input.absolutePath
13587
+ },
13588
+ served: input.served,
13589
+ source: input.identity
13590
+ });
13591
+ const anchorLine = leased.resolved.hash_bounds[0].line;
13592
+ const provider = input.provider ?? defaultExpandProvider();
13593
+ const item = await resolveEnclosingItem({
13594
+ provider,
13595
+ absolutePath: input.absolutePath,
13596
+ filePath: input.filePath,
13597
+ anchorLine,
13598
+ totalLines: input.hashes.length
13599
+ });
13600
+ let replacement = input.edit.content_lines;
13601
+ let indent;
13602
+ if (input.indent === "auto" && replacement.length > 0) {
13603
+ const anchorText = lines[anchorLine - 1] ?? "";
13604
+ const rebased = applyAutoIndent(replacement.join("\n"), leadingWhitespaceOf(anchorText));
13605
+ if (rebased.changed) {
13606
+ replacement = rebased.text.split("\n");
13607
+ indent = {
13608
+ baseIndent: leadingWhitespaceOf(anchorText),
13609
+ strippedPrefix: rebased.strippedPrefix,
13610
+ changedLines: rebased.changedLines
13611
+ };
13612
+ }
13613
+ }
13614
+ const nextContent = replaceItemSpan(input.content, item.startLine, item.endLine, replacement);
13615
+ const range = {
13616
+ startLine: item.startLine,
13617
+ endLine: item.endLine,
13618
+ startHash: input.hashes[item.startLine - 1],
13619
+ endHash: input.hashes[item.endLine - 1],
13620
+ delta: replacement.length - (item.endLine - item.startLine + 1)
13621
+ };
13622
+ const warnings = [];
13623
+ const echo = findServedHashEcho(replacement, input.served, input.canonDigests, 1);
13624
+ let literalBypass = false;
13625
+ if (echo !== void 0) {
13626
+ if (input.mode === "literal") {
13627
+ literalBypass = true;
13628
+ warnings.push(LITERAL_BYPASS_NOTICE);
13629
+ } else {
13630
+ const count = trackServedEditRefusal(
13631
+ input.sessionKey,
13632
+ input.absolutePath,
13633
+ input.edit.hash_bounds[0].hash,
13634
+ input.edit.hash_bounds[1].hash,
13635
+ replacement[echo.k - 1] ?? ""
13636
+ );
13637
+ throw new DomainError("E_SUSPICIOUS_TEXT", {
13638
+ target: "edit",
13639
+ path: input.filePath,
13640
+ line: echo.k,
13641
+ hash: echo.hash,
13642
+ servedLine: echo.servedLine,
13643
+ count
13644
+ });
13645
+ }
13646
+ }
13647
+ const payloadEdit = { ...input.edit, content_lines: replacement };
13648
+ warnUnicodeEsc(payloadEdit, warnings);
13649
+ const neverServedCount = findNeverServedAnchorShapes(replacement, input.served, 1).length;
13650
+ if (nextContent === input.content) {
13651
+ return {
13652
+ kind: "noop",
13653
+ range,
13654
+ noopEdit: {
13655
+ loc: input.edit.hash_bounds[0].hash,
13656
+ currentContent: lines.slice(item.startLine - 1, item.endLine).join("\n")
13657
+ },
13658
+ anchorWarnings: warnings.length > 0 ? warnings : void 0,
13659
+ literalBypass,
13660
+ neverServedCount,
13661
+ ...indent !== void 0 ? { indent } : {}
13662
+ };
13663
+ }
13664
+ if (input.content !== "" && nextContent === "") {
13665
+ throw new DomainError("E_EMPTY_RANGE", {});
13666
+ }
13667
+ const removedHashes = new Set(input.hashes.slice(item.startLine - 1, item.endLine));
13668
+ const nextHashes = await defaultHashIdentity.hashesFor(nextContent, {
13669
+ path: input.absolutePath,
13670
+ prior: { content: input.content, hashes: input.hashes, removedHashes },
13671
+ persist: false,
13672
+ snapshotIO: snapshotIOFor(input.store),
13673
+ // SAFETY: the options object is typed by HashIdentity's internal parameter shape, which the caller
13674
+ // SAFETY: never sees; every field above is already typed, so the cast widens nothing.
13675
+ blockedHashes: input.blockedHashes
13676
+ });
13677
+ const changed = changedRange(input.content, nextContent);
13678
+ return {
13679
+ kind: "applied",
13680
+ content: nextContent,
13681
+ hashes: nextHashes,
13682
+ removedHashes,
13683
+ range,
13684
+ firstChangedLine: changed?.firstChangedLine,
13685
+ lastChangedLine: changed?.lastChangedLine,
13686
+ anchorWarnings: warnings.length > 0 ? warnings : void 0,
13687
+ literalBypass,
13688
+ neverServedCount,
13689
+ sourceRange: void 0,
13690
+ mutationSpans: void 0,
13691
+ // WHY: the loop's fallback counts the item's own target span, which for an expansion is the one
13692
+ // WHY: anchor line rather than the whole item; the expansion reports its honest counts instead.
13693
+ mutationStats: {
13694
+ addedLines: replacement.length,
13695
+ removedLines: item.endLine - item.startLine + 1
13696
+ },
13697
+ ...indent !== void 0 ? { indent } : {}
13698
+ };
13699
+ }
13700
+
13165
13701
  // src/mutation-engine/pipeline.ts
13166
13702
  function collectRemovedHashes(edit, originalHashes) {
13167
13703
  const removedHashes = /* @__PURE__ */ new Set();
@@ -13198,6 +13734,31 @@ function countLineChanges(edit, originalHashes, isNoop) {
13198
13734
  totalRemovedLines
13199
13735
  };
13200
13736
  }
13737
+ function autoIndentedEdit(input, identity) {
13738
+ if (input.edit.content_lines.length === 0) return { edit: input.edit };
13739
+ const fileLines = splitLines(input.content);
13740
+ const leased = resolveLeasedEdit({
13741
+ edit: {
13742
+ content_lines: [],
13743
+ hash_bounds: [input.edit.hash_bounds[0], input.edit.hash_bounds[0]]
13744
+ },
13745
+ snapshot: { fileHashes: input.hashes, fileLines, filePath: input.absolutePath },
13746
+ served: input.served,
13747
+ source: identity
13748
+ });
13749
+ const anchorLine = leased.resolved.hash_bounds[0].line;
13750
+ const baseIndent = leadingWhitespaceOf(fileLines[anchorLine - 1] ?? "");
13751
+ const rebased = applyAutoIndent(input.edit.content_lines.join("\n"), baseIndent);
13752
+ if (!rebased.changed) return { edit: input.edit };
13753
+ return {
13754
+ edit: { ...input.edit, content_lines: rebased.text.split("\n") },
13755
+ indent: {
13756
+ baseIndent,
13757
+ strippedPrefix: rebased.strippedPrefix,
13758
+ changedLines: rebased.changedLines
13759
+ }
13760
+ };
13761
+ }
13201
13762
  async function applyOneEdit(input) {
13202
13763
  abortIf(input.signal);
13203
13764
  const identity = leaseSpanSource({
@@ -13207,9 +13768,12 @@ async function applyOneEdit(input) {
13207
13768
  content: input.content,
13208
13769
  ...input.currentIds !== void 0 ? { currentIds: input.currentIds } : {}
13209
13770
  });
13771
+ let indent;
13210
13772
  let anchorResult;
13211
13773
  try {
13212
- anchorResult = applyEdit(input.content, input.edit, input.signal, input.hashes, {
13774
+ const prepared = input.indent === "auto" ? autoIndentedEdit(input, identity) : { edit: input.edit };
13775
+ indent = prepared.indent;
13776
+ anchorResult = applyEdit(input.content, prepared.edit, input.signal, input.hashes, {
13213
13777
  // WHY: read/write agreement — the verify path is literally the same
13214
13778
  // WHY: canonical absolute path the `hashesFor` call below uses (one field).
13215
13779
  filePath: input.absolutePath,
@@ -13245,7 +13809,8 @@ async function applyOneEdit(input) {
13245
13809
  noopEdit: anchorResult.noopEdit,
13246
13810
  anchorWarnings,
13247
13811
  literalBypass,
13248
- neverServedCount
13812
+ neverServedCount,
13813
+ ...indent !== void 0 ? { indent } : {}
13249
13814
  };
13250
13815
  }
13251
13816
  if (!input.hashes || input.hashes.length === 0)
@@ -13280,7 +13845,8 @@ async function applyOneEdit(input) {
13280
13845
  neverServedCount,
13281
13846
  sourceRange: anchorResult.sourceRange,
13282
13847
  mutationSpans: anchorResult.mutationSpans,
13283
- mutationStats: anchorResult.mutationStats
13848
+ mutationStats: anchorResult.mutationStats,
13849
+ ...indent !== void 0 ? { indent } : {}
13284
13850
  };
13285
13851
  }
13286
13852
  async function recordRejectionServe(args) {
@@ -13307,6 +13873,10 @@ function replacementTextForPayload(payload) {
13307
13873
  return `span:${payload.span.anchor_from}..${payload.span.anchor_to}:${payload.mode === "cut" ? "move" : "copy"}`;
13308
13874
  case "empty":
13309
13875
  return "";
13876
+ // WHY: (ADR-0025) an insertion is identified by its side and its own lines, never by the anchor
13877
+ // WHY: line it sits next to — that line is not part of this item's content.
13878
+ case "insert":
13879
+ return `${payload.side}:${payload.text}`;
13310
13880
  default:
13311
13881
  return assertNever(payload);
13312
13882
  }
@@ -13321,6 +13891,7 @@ function parseEdits(items, path, itemNumbers) {
13321
13891
  const payload = item.payload;
13322
13892
  let text;
13323
13893
  let source;
13894
+ let placement;
13324
13895
  switch (payload.kind) {
13325
13896
  case "literal":
13326
13897
  if (payload.text === "") {
@@ -13350,6 +13921,14 @@ function parseEdits(items, path, itemNumbers) {
13350
13921
  }
13351
13922
  text = "";
13352
13923
  break;
13924
+ // WHY: (ADR-0025) a pure insertion reuses the engine's zero-width placement splice: the
13925
+ // WHY: payload lines ARE the content and the anchor line is only the zero-width boundary.
13926
+ // WHY: Because `content_lines` never contains the anchor line, no splice path can rewrite
13927
+ // WHY: it — the "insert turned into a re-typed boundary row" failure is not representable.
13928
+ case "insert":
13929
+ text = payload.text;
13930
+ placement = payload.side;
13931
+ break;
13353
13932
  default:
13354
13933
  assertNever(payload);
13355
13934
  }
@@ -13359,6 +13938,7 @@ function parseEdits(items, path, itemNumbers) {
13359
13938
  anchor_to: item.target.anchor_to,
13360
13939
  text,
13361
13940
  ...item.at !== "in-place" ? { placement: item.at } : {},
13941
+ ...placement !== void 0 ? { placement } : {},
13362
13942
  ...source ? { source } : {}
13363
13943
  })
13364
13944
  });
@@ -13563,7 +14143,8 @@ async function runMutations(request, cwd, options, itemNumbers) {
13563
14143
  fileHashes: originalHashes,
13564
14144
  hadUtf8DecodeErrors,
13565
14145
  absolutePath,
13566
- served
14146
+ served,
14147
+ canonDigests
13567
14148
  } = await loadEditFile({
13568
14149
  path,
13569
14150
  cwd,
@@ -13652,28 +14233,73 @@ async function runMutations(request, cwd, options, itemNumbers) {
13652
14233
  continue;
13653
14234
  }
13654
14235
  const edit = parsedItem.edit;
13655
- const outcome = await applyOneEdit({
13656
- content: currentContent,
13657
- hashes: currentHashes,
13658
- edit,
13659
- ...options?.signal !== void 0 ? { signal: options.signal } : {},
13660
- served,
13661
- blockedHashes: batchBlockedHashes,
13662
- canonDigests: baseCanonDigests,
13663
- sessionKey,
13664
- absolutePath,
13665
- store: hashStore,
13666
- isPreview,
13667
- mode,
13668
- // WHY: the intermediate buffer is in-memory only, so its identities come from the buffer map
13669
- // WHY: (`null` lines are the batch's own creations) — a re-diff of it against S_latest cannot
13670
- // WHY: tell which of two byte-identical lines carries a leased line_id.
13671
- ...isPreview ? {} : { currentIds },
13672
- onRejected: async (error) => {
14236
+ let outcome;
14237
+ if (item.expand === "item") {
14238
+ try {
14239
+ outcome = await applyExpandedItem({
14240
+ edit,
14241
+ ...item.indent !== void 0 ? { indent: item.indent } : {},
14242
+ content: currentContent,
14243
+ hashes: currentHashes,
14244
+ served,
14245
+ canonDigests,
14246
+ identity: leaseSpanSource({
14247
+ store: hashStore,
14248
+ sessionKey,
14249
+ absolutePath,
14250
+ content: currentContent,
14251
+ ...isPreview ? {} : { currentIds }
14252
+ }),
14253
+ absolutePath,
14254
+ filePath: path,
14255
+ mode,
14256
+ sessionKey,
14257
+ store: hashStore,
14258
+ blockedHashes: batchBlockedHashes,
14259
+ provider: options?.spanProvider,
14260
+ ...options?.signal !== void 0 ? { signal: options.signal } : {}
14261
+ });
14262
+ } catch (error) {
14263
+ if (!(error instanceof DomainError)) throw error;
14264
+ await recordRejectionServe({
14265
+ error,
14266
+ sessionKey,
14267
+ absolutePath,
14268
+ isPreview,
14269
+ lineCount: currentHashes.length,
14270
+ contentHash: isPreview ? void 0 : snapshotHashFor(currentContent)
14271
+ });
13673
14272
  if (items.length === 1) throw error;
13674
14273
  throw batchAbortFor({ error, index: number, path });
13675
14274
  }
13676
- });
14275
+ } else {
14276
+ outcome = await applyOneEdit({
14277
+ content: currentContent,
14278
+ hashes: currentHashes,
14279
+ edit,
14280
+ ...options?.signal !== void 0 ? { signal: options.signal } : {},
14281
+ served,
14282
+ blockedHashes: batchBlockedHashes,
14283
+ canonDigests: baseCanonDigests,
14284
+ sessionKey,
14285
+ absolutePath,
14286
+ store: hashStore,
14287
+ isPreview,
14288
+ mode,
14289
+ ...item.indent !== void 0 ? { indent: item.indent } : {},
14290
+ // WHY: the intermediate buffer is in-memory only, so its identities come from the buffer map
14291
+ // WHY: (`null` lines are the batch's own creations) — a re-diff of it against S_latest cannot
14292
+ // WHY: tell which of two byte-identical lines carries a leased line_id.
14293
+ ...isPreview ? {} : { currentIds },
14294
+ onRejected: async (error) => {
14295
+ if (items.length === 1) throw error;
14296
+ throw batchAbortFor({ error, index: number, path });
14297
+ }
14298
+ });
14299
+ }
14300
+ if (outcome.kind === "applied" && outcome.indent !== void 0) {
14301
+ warnings.push(buildIndentNote({ ref: `edit[${number}] (${path})`, summary: outcome.indent }));
14302
+ }
13677
14303
  const range = outcome.range;
13678
14304
  const coveredRanges = outcome.kind === "applied" && outcome.sourceRange ? [range, outcome.sourceRange] : [range];
13679
14305
  editedIntervals.push(...coveredRanges);
@@ -14843,6 +15469,21 @@ function diffResultView(title, result) {
14843
15469
  function toCanonicalValue(result) {
14844
15470
  return result;
14845
15471
  }
15472
+ function withWarning(result, warning) {
15473
+ if (warning === void 0) return result;
15474
+ const details = typeof result.details === "object" && result.details !== null ? result.details : {};
15475
+ const existing = Array.isArray(details.warnings) ? details.warnings.filter((entry) => typeof entry === "string") : [];
15476
+ return {
15477
+ ...result,
15478
+ content: result.content.map((block) => {
15479
+ const text = block;
15480
+ return text.type === "text" && typeof text.text === "string" ? { type: "text", text: `${text.text}
15481
+
15482
+ ${warning}` } : block;
15483
+ }),
15484
+ details: { ...details, warnings: [...existing, warning] }
15485
+ };
15486
+ }
14846
15487
 
14847
15488
  // dsh/tools/apply-patch.ts
14848
15489
  var APPLY_PATCH_DESCRIPTION = loadP("../prompts/apply-patch.md");
@@ -15096,8 +15737,8 @@ function isRec(value) {
15096
15737
  function isNormalizedEdit(input) {
15097
15738
  return isRec(input) && input[normalizedEdit] === true;
15098
15739
  }
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).`;
15740
+ var ITEM_SHAPE = 'an item is one payload over its anchor pair \u2014 `text` (optionally with `indent: "auto"` and, alone, `expand: "item"`), `text_ref`, or one insertion slot `after`/`before` (optionally with `indent: "auto"`) \u2014 plus optional `at`';
15741
+ 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); optional "indent": "auto" re-bases a "text"/"after"/"before" payload on the leading whitespace of the line "anchor_from" names, and optional "expand": "item" replaces the whole syntax item around "anchor_from" (in-place "text" only: "anchor_to" is refused because the AST decides the end).`;
15101
15742
  function describeReceived(input) {
15102
15743
  if (input === void 0) return "Received no arguments.";
15103
15744
  if (input === null) return "Received null.";
@@ -15153,7 +15794,11 @@ var ITEM_KEY_SETS = [
15153
15794
  ["anchor_from", "anchor_to", "text_ref"],
15154
15795
  ["anchor_from", "text_ref"],
15155
15796
  ["anchor_from", "anchor_to", "at", "text_ref"],
15156
- ["anchor_from", "at", "text_ref"]
15797
+ ["anchor_from", "at", "text_ref"],
15798
+ ["anchor_from", "after"],
15799
+ ["anchor_from", "after", "anchor_to"],
15800
+ ["anchor_from", "before"],
15801
+ ["anchor_from", "before", "anchor_to"]
15157
15802
  ];
15158
15803
  function keySetEquals(keys, shape) {
15159
15804
  if (keys.size !== shape.length) return false;
@@ -15168,7 +15813,16 @@ function isAbsentValue(value) {
15168
15813
  }
15169
15814
  function foldAbsentSlots(item) {
15170
15815
  const folded = { ...item };
15171
- for (const key of ["text", "text_ref", "at", "anchor_to"]) {
15816
+ for (const key of [
15817
+ "text",
15818
+ "text_ref",
15819
+ "at",
15820
+ "anchor_to",
15821
+ "after",
15822
+ "before",
15823
+ "indent",
15824
+ "expand"
15825
+ ]) {
15172
15826
  if (isAbsentValue(folded[key])) delete folded[key];
15173
15827
  }
15174
15828
  if (isRec(folded.text_ref)) {
@@ -15182,20 +15836,42 @@ function analyzeItem(value, index) {
15182
15836
  if (!isRec(value)) {
15183
15837
  return `edit[${index}] must be an object: ${ITEM_SHAPE}.`;
15184
15838
  }
15185
- const keys = new Set(Object.keys(value));
15839
+ const modifierKeys = /* @__PURE__ */ new Set(["indent", "expand"]);
15840
+ const keys = new Set(Object.keys(value).filter((key) => !modifierKeys.has(key)));
15186
15841
  const hasText = keys.has("text");
15187
15842
  const hasRef = keys.has("text_ref");
15843
+ const hasAfter = keys.has("after");
15844
+ const hasBefore = keys.has("before");
15845
+ const hasInsert = hasAfter || hasBefore;
15846
+ const carried = [
15847
+ hasText ? "text" : void 0,
15848
+ hasRef ? "text_ref" : void 0,
15849
+ hasAfter ? "after" : void 0,
15850
+ hasBefore ? "before" : void 0
15851
+ ].filter((key) => key !== void 0);
15188
15852
  if (!isLegalItemKeySet(keys)) {
15189
15853
  if (hasText && hasRef) {
15190
15854
  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
15855
  }
15192
- const payloadKeys = /* @__PURE__ */ new Set(["anchor_from", "anchor_to", "at", "text", "text_ref"]);
15856
+ if (carried.length > 1) {
15857
+ const names = carried.map((key) => `"${key}"`).join(" and ");
15858
+ 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.`;
15859
+ }
15860
+ const payloadKeys = /* @__PURE__ */ new Set([
15861
+ "anchor_from",
15862
+ "anchor_to",
15863
+ "at",
15864
+ "text",
15865
+ "text_ref",
15866
+ "after",
15867
+ "before"
15868
+ ]);
15193
15869
  const offending = [...keys].filter((key) => !payloadKeys.has(key));
15194
15870
  const missing = ["anchor_from"].filter((key) => !keys.has(key));
15195
15871
  const clauses = [];
15196
15872
  if (offending.length > 0) clauses.push(`unsupported field(s) ${quoted(offending)}`);
15197
15873
  if (missing.length > 0) clauses.push(`missing required field(s) ${quoted(missing)}`);
15198
- if (!hasText && !hasRef) {
15874
+ if (!hasText && !hasRef && !hasInsert) {
15199
15875
  const named = clauses.length > 0 ? `${clauses.join(";")} \u2014 ` : "";
15200
15876
  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
15877
  }
@@ -15216,6 +15892,45 @@ function analyzeItem(value, index) {
15216
15892
  return `edit[${index}] "at" must be "in-place", "before" or "after" when present.`;
15217
15893
  }
15218
15894
  }
15895
+ const indentValue = value.indent;
15896
+ if (indentValue !== void 0 && indentValue !== "auto") {
15897
+ return `edit[${index}] "indent" must be "auto" when present ("as-is" is the default and may be omitted).`;
15898
+ }
15899
+ const expandValue = value.expand;
15900
+ if (expandValue !== void 0 && expandValue !== "item") {
15901
+ return `edit[${index}] "expand" must be "item" when present: it replaces the whole syntax item that contains "anchor_from".`;
15902
+ }
15903
+ const wantsAutoIndent = indentValue === "auto";
15904
+ const wantsExpand = expandValue === "item";
15905
+ if (wantsExpand && anchor_to !== void 0) {
15906
+ return `edit[${index}] "expand": "item" takes only "anchor_from": the syntax item's own span decides the end, so delete "anchor_to" from the item.`;
15907
+ }
15908
+ if (wantsExpand && (hasRef || hasInsert || at !== void 0 && at !== "in-place")) {
15909
+ return `edit[${index}] "expand": "item" replaces the whole syntax item with "text", so it takes no "text_ref", "after", "before" or "at": keep "text" and delete the other payload and placement fields.`;
15910
+ }
15911
+ if (wantsAutoIndent && hasRef) {
15912
+ return `edit[${index}] "indent" does not apply to "text_ref": the referenced served bytes are copied verbatim. Delete "indent" from the item, or send the lines as "text" to have them re-indented.`;
15913
+ }
15914
+ if (wantsAutoIndent && hasText && text === "") {
15915
+ return `edit[${index}] "indent" has no lines to indent: "text": "" is the deletion payload. Delete "indent" from the item.`;
15916
+ }
15917
+ if (hasInsert) {
15918
+ if (hasAfter && hasBefore) {
15919
+ 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.`;
15920
+ }
15921
+ const side = hasAfter ? "after" : "before";
15922
+ const insertion = hasAfter ? value.after : value.before;
15923
+ if (typeof insertion !== "string") {
15924
+ return `edit[${index}] "${side}" must be a string with \\n line separators: the exact lines to insert next to the anchor line.`;
15925
+ }
15926
+ if (insertion === "") {
15927
+ 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.`;
15928
+ }
15929
+ if (anchor_to !== void 0 && anchor_to !== anchor_from) {
15930
+ 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.`;
15931
+ }
15932
+ return void 0;
15933
+ }
15219
15934
  if (hasText) {
15220
15935
  if (typeof text !== "string") {
15221
15936
  return `edit[${index}] "text" must be a string with \\n line separators, not an array. An empty string deletes the range.`;
@@ -15260,7 +15975,7 @@ function analyzeRequest(input) {
15260
15975
  if (rootOffending.length > 0) {
15261
15976
  return {
15262
15977
  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)
15978
+ 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
15979
  };
15265
15980
  }
15266
15981
  let mode;
@@ -15306,6 +16021,11 @@ function analyzeRequest(input) {
15306
16021
  }
15307
16022
  edited.push(item);
15308
16023
  }
16024
+ if (items.length > 1 && edited.some((item) => item.expand === "item")) {
16025
+ failures.push(
16026
+ `Edit request carries "expand": "item" in a call with ${items.length} items: an expanded item must be the only item in the call \u2014 send one expand edit per call.`
16027
+ );
16028
+ }
15309
16029
  if (failures.length > 0) {
15310
16030
  return { ok: false, message: `${failures.join(" ")} ${describeReceived(input)}` };
15311
16031
  }
@@ -15314,7 +16034,7 @@ function analyzeRequest(input) {
15314
16034
  }
15315
16035
  function normalizedItemFrom(item) {
15316
16036
  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 ?? "" };
16037
+ 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
16038
  const target = {
15319
16039
  anchor_from: item.anchor_from,
15320
16040
  anchor_to: item.anchor_to ?? item.anchor_from
@@ -15322,7 +16042,9 @@ function normalizedItemFrom(item) {
15322
16042
  return {
15323
16043
  target,
15324
16044
  at,
15325
- payload
16045
+ payload,
16046
+ ...item.indent === "auto" ? { indent: item.indent } : {},
16047
+ ...item.expand === "item" ? { expand: item.expand } : {}
15326
16048
  };
15327
16049
  }
15328
16050
  function normReq(input) {
@@ -15350,6 +16072,8 @@ function isPlacementValue(value) {
15350
16072
  }
15351
16073
  function isNormalizedEditItem(value) {
15352
16074
  if (!isRec(value)) return false;
16075
+ if (value.indent !== void 0 && value.indent !== "auto") return false;
16076
+ if (value.expand !== void 0 && value.expand !== "item") return false;
15353
16077
  const { target, at, payload } = value;
15354
16078
  if (!isRec(target)) return false;
15355
16079
  if (typeof target.anchor_from !== "string" || typeof target.anchor_to !== "string") return false;
@@ -15360,6 +16084,9 @@ function isNormalizedEditItem(value) {
15360
16084
  if (payload.kind === "reference") {
15361
16085
  return isRec(payload.span) && typeof payload.span.anchor_from === "string" && typeof payload.span.anchor_to === "string" && (payload.mode === "copy" || payload.mode === "cut");
15362
16086
  }
16087
+ if (payload.kind === "insert") {
16088
+ return (payload.side === "before" || payload.side === "after") && typeof payload.text === "string";
16089
+ }
15363
16090
  return false;
15364
16091
  }
15365
16092
  function assertReq(request) {
@@ -15509,7 +16236,7 @@ function isMutationSuccess(r) {
15509
16236
  }
15510
16237
 
15511
16238
  // src/edit-tool.ts
15512
- function createEditTool() {
16239
+ function createEditTool(options = {}) {
15513
16240
  return {
15514
16241
  async execute(params, signal, ctx) {
15515
16242
  const canonical = normReq(params);
@@ -15521,7 +16248,8 @@ function createEditTool() {
15521
16248
  accessMode: constants7.R_OK | constants7.W_OK,
15522
16249
  // SAFETY: signal is AbortSignal | undefined at pi boundary — runtime check via engine's abortIf
15523
16250
  ...signal !== void 0 ? { signal } : {},
15524
- sessionKey
16251
+ sessionKey,
16252
+ ...options.spanProvider !== void 0 ? { spanProvider: options.spanProvider } : {}
15525
16253
  });
15526
16254
  if (isMutationSuccess(result)) {
15527
16255
  return result.toolResult;
@@ -15544,7 +16272,8 @@ function createEditTool() {
15544
16272
  assertReq(normalized);
15545
16273
  const result = await preview(normalized, cwd, {
15546
16274
  accessMode: constants7.R_OK,
15547
- sessionKey: sessionKeyFor(ctx)
16275
+ sessionKey: sessionKeyFor(ctx),
16276
+ ...options.spanProvider !== void 0 ? { spanProvider: options.spanProvider } : {}
15548
16277
  });
15549
16278
  if (!isMutationSuccess(result)) {
15550
16279
  return { error: result.message };
@@ -15568,24 +16297,125 @@ function createEditTool() {
15568
16297
  };
15569
16298
  }
15570
16299
 
15571
- // dsh/tools/edit.ts
15572
- var EDIT_TOOL_NAME = "edit";
15573
- var EDIT_PARAMETERS = {
15574
- file: {
15575
- type: "string",
15576
- required: true,
15577
- description: "Path to the text file to edit (a file, never a directory)"
15578
- },
15579
- edits: {
15580
- type: "array",
15581
- required: true,
15582
- description: "Ordered list of edit items",
15583
- items: {
15584
- type: "object",
15585
- additionalProperties: true,
15586
- properties: {
15587
- anchor_from: {
15588
- type: "string",
16300
+ // dsh/syntax-health.ts
16301
+ var GRAMMAR_BY_EXTENSION = {
16302
+ ".ts": "typescript",
16303
+ ".mts": "typescript",
16304
+ ".cts": "typescript",
16305
+ ".tsx": "tsx",
16306
+ ".js": "tsx",
16307
+ ".mjs": "tsx",
16308
+ ".cjs": "tsx",
16309
+ ".jsx": "tsx",
16310
+ ".py": "python",
16311
+ ".pyi": "python",
16312
+ ".go": "go",
16313
+ ".rs": "rust",
16314
+ ".java": "java",
16315
+ ".vue": "vue"
16316
+ };
16317
+ function grammarForPath(path) {
16318
+ const lower = path.toLowerCase();
16319
+ const dot = lower.lastIndexOf(".");
16320
+ if (dot === -1) return void 0;
16321
+ return GRAMMAR_BY_EXTENSION[lower.slice(dot)];
16322
+ }
16323
+ function errorLines(root, cap) {
16324
+ const found = [];
16325
+ let deepestDamaged;
16326
+ const visit = (node) => {
16327
+ if (!node.hasError) return;
16328
+ const line = node.startPosition.row + 1;
16329
+ if (node.type === "ERROR") {
16330
+ if (found.length < cap) found.push(line);
16331
+ return;
16332
+ }
16333
+ deepestDamaged = deepestDamaged === void 0 ? line : Math.max(deepestDamaged, line);
16334
+ for (const child of node.namedChildren) visit(child);
16335
+ };
16336
+ visit(root);
16337
+ if (found.length > 0) return [...new Set(found)].sort((a, b) => a - b);
16338
+ return deepestDamaged === void 0 ? [] : [deepestDamaged];
16339
+ }
16340
+ function aborted(signal) {
16341
+ return signal?.aborted === true;
16342
+ }
16343
+ async function defaultGrammarFor(path) {
16344
+ const language = grammarForPath(path);
16345
+ if (language === void 0) return void 0;
16346
+ const artifact = await ensureGrammar(language);
16347
+ if (artifact === void 0) return void 0;
16348
+ return loadWebTreeSitterGrammar(artifact.bytes);
16349
+ }
16350
+ async function syntaxWarningForEdit(path, before, after, options = {}) {
16351
+ if (before === after) return void 0;
16352
+ if (aborted(options.signal)) return void 0;
16353
+ try {
16354
+ const grammar = await (options.grammarFor ?? defaultGrammarFor)(path);
16355
+ if (grammar === void 0) return void 0;
16356
+ if (aborted(options.signal)) return void 0;
16357
+ const beforeTree = grammar.parse(before);
16358
+ const beforeClean = beforeTree !== null && beforeTree.rootNode.hasError === false;
16359
+ beforeTree?.delete?.();
16360
+ if (beforeClean === false) return void 0;
16361
+ const afterTree = grammar.parse(after);
16362
+ if (afterTree === null) return void 0;
16363
+ let lines;
16364
+ try {
16365
+ if (!afterTree.rootNode.hasError) return void 0;
16366
+ lines = errorLines(afterTree.rootNode, 5);
16367
+ } finally {
16368
+ afterTree.delete?.();
16369
+ }
16370
+ if (lines.length === 0) return void 0;
16371
+ const first = lines[0];
16372
+ const noun = lines.length === 1 ? "a syntax error" : "syntax errors";
16373
+ return [
16374
+ "[W_SYNTAX] This edit introduced " + noun + " near line " + lines.join(", ") + ".",
16375
+ "The file was committed as written. The usual cause is a replaced range that swallowed or left",
16376
+ "one extra closing brace or bracket \u2014 re-read around line " + first + " and correct the range."
16377
+ ].join(" ");
16378
+ } catch {
16379
+ return void 0;
16380
+ }
16381
+ }
16382
+ async function readText(io, path, signal) {
16383
+ try {
16384
+ return decodeUtf8Strict(await io.read(path, signal), path);
16385
+ } catch {
16386
+ return void 0;
16387
+ }
16388
+ }
16389
+ async function readSyntaxBaseline(io, path, signal) {
16390
+ if (signal?.aborted === true) return void 0;
16391
+ if (grammarForPath(path) === void 0) return void 0;
16392
+ const text = await readText(io, path, signal);
16393
+ return text === void 0 ? void 0 : { path, text };
16394
+ }
16395
+ async function syntaxWarningAfterEdit(io, baseline, options = {}) {
16396
+ const after = await readText(io, baseline.path, options.signal);
16397
+ if (after === void 0) return void 0;
16398
+ return syntaxWarningForEdit(baseline.path, baseline.text, after, options);
16399
+ }
16400
+
16401
+ // dsh/tools/edit.ts
16402
+ var EDIT_TOOL_NAME = "edit";
16403
+ var EDIT_PARAMETERS = {
16404
+ file: {
16405
+ type: "string",
16406
+ required: true,
16407
+ description: "Path to the text file to edit (a file, never a directory)"
16408
+ },
16409
+ edits: {
16410
+ type: "array",
16411
+ required: true,
16412
+ description: "Ordered list of edit items",
16413
+ items: {
16414
+ type: "object",
16415
+ additionalProperties: true,
16416
+ properties: {
16417
+ anchor_from: {
16418
+ type: "string",
15589
16419
  required: true,
15590
16420
  description: "Bare hash anchor of the first range line (inclusive)"
15591
16421
  },
@@ -15617,6 +16447,24 @@ var EDIT_PARAMETERS = {
15617
16447
  { type: "null" }
15618
16448
  ]
15619
16449
  },
16450
+ after: {
16451
+ oneOf: [
16452
+ {
16453
+ type: "string",
16454
+ description: "Exact lines to insert immediately BELOW anchor_from; the anchor line itself is never rewritten, so it is never restated"
16455
+ },
16456
+ { type: "null" }
16457
+ ]
16458
+ },
16459
+ before: {
16460
+ oneOf: [
16461
+ {
16462
+ type: "string",
16463
+ description: "Exact lines to insert immediately ABOVE anchor_from; the anchor line itself is never rewritten, so it is never restated"
16464
+ },
16465
+ { type: "null" }
16466
+ ]
16467
+ },
15620
16468
  text_ref: {
15621
16469
  oneOf: [
15622
16470
  {
@@ -15652,6 +16500,26 @@ var EDIT_PARAMETERS = {
15652
16500
  },
15653
16501
  { type: "null" }
15654
16502
  ]
16503
+ },
16504
+ indent: {
16505
+ oneOf: [
16506
+ {
16507
+ type: "string",
16508
+ enum: ["as-is", "auto"],
16509
+ description: '"auto" re-bases the payload on the leading whitespace of the anchor_from line; "as-is" (the default) writes it verbatim'
16510
+ },
16511
+ { type: "null" }
16512
+ ]
16513
+ },
16514
+ expand: {
16515
+ oneOf: [
16516
+ {
16517
+ type: "string",
16518
+ enum: ["item"],
16519
+ description: '"item" replaces the whole syntax item that contains anchor_from (leading doc comment through closing brace); takes only anchor_from and text'
16520
+ },
16521
+ { type: "null" }
16522
+ ]
15655
16523
  }
15656
16524
  }
15657
16525
  }
@@ -15685,8 +16553,10 @@ function writtenMemberFiles(admitted) {
15685
16553
  return files;
15686
16554
  }
15687
16555
  var EDIT_TOOL_DESCRIPTION = loadP("../prompts/edit.md");
15688
- function buildEditTool(deps) {
15689
- const tool = createEditTool();
16556
+ function buildEditTool(deps, options = {}) {
16557
+ const tool = createEditTool(
16558
+ options.spanProvider === void 0 ? {} : { spanProvider: options.spanProvider }
16559
+ );
15690
16560
  const sandboxFields = deps.sandbox.escalationModes.length > 0 ? deps.sandbox.schemaFields() : {};
15691
16561
  return defineTool3({
15692
16562
  name: EDIT_TOOL_NAME,
@@ -15735,10 +16605,13 @@ function buildEditTool(deps) {
15735
16605
  throw new DomainError("E_NOT_FOUND", { path: admitted.file });
15736
16606
  }
15737
16607
  }
16608
+ const syntaxBefore = await readSyntaxBaseline(deps.io, absolutePath, toolCtx.signal);
15738
16609
  const members = writtenMemberFiles(admitted);
15739
16610
  await announcePluginWrites(deps, members, toolCtx, exec);
15740
16611
  const result = await tool.execute(admitted, toolCtx.signal, upstreamContext(toolCtx));
15741
- const canonical = toCanonicalValue(result);
16612
+ const raw = toCanonicalValue(result);
16613
+ const introduced = syntaxBefore === void 0 ? void 0 : await syntaxWarningAfterEdit(deps.io, syntaxBefore, { signal: toolCtx.signal });
16614
+ const canonical = withWarning(raw, introduced);
15742
16615
  await publishPluginWrites(deps, members, toolCtx, exec);
15743
16616
  metrics?.record({
15744
16617
  tool: "edit",
@@ -15805,6 +16678,1332 @@ function admit2(args) {
15805
16678
  }
15806
16679
  }
15807
16680
 
16681
+ // dsh/codegraph/cli.ts
16682
+ import { spawn } from "node:child_process";
16683
+ import { existsSync as existsSync5 } from "node:fs";
16684
+ import { dirname as dirname10, extname, join as join10 } from "node:path";
16685
+ var PACKAGE_SCRIPT = join10(
16686
+ "node_modules",
16687
+ "@colbymchenry",
16688
+ "codegraph",
16689
+ "dist",
16690
+ "bin",
16691
+ "codegraph.js"
16692
+ );
16693
+ var BUNDLED_SCRIPT = join10("lib", "dist", "bin", "codegraph.js");
16694
+ var WINDOWS_SHIM_NAMES = [
16695
+ "codegraph.cmd",
16696
+ "codegraph.exe",
16697
+ "codegraph.bat",
16698
+ "codegraph"
16699
+ ];
16700
+ var POSIX_SHIM_NAMES = ["codegraph"];
16701
+ function isScript(entry) {
16702
+ const ext = extname(entry).toLowerCase();
16703
+ return ext === ".js" || ext === ".mjs" || ext === ".cjs";
16704
+ }
16705
+ function isCommandShim(entry) {
16706
+ const lower = entry.toLowerCase();
16707
+ return lower.endsWith(".cmd") || lower.endsWith(".bat");
16708
+ }
16709
+ function invocationOf(entry, platform, exists) {
16710
+ if (isScript(entry)) return { command: process.execPath, prefixArgs: [entry], source: entry };
16711
+ if (!isCommandShim(entry)) {
16712
+ if (platform === "win32" && !entry.toLowerCase().endsWith(".exe")) return void 0;
16713
+ return { command: entry, prefixArgs: [], source: entry };
16714
+ }
16715
+ const binDir = dirname10(entry);
16716
+ const installRoot = dirname10(binDir);
16717
+ const candidates = [
16718
+ { command: join10(installRoot, "node.exe"), script: join10(installRoot, BUNDLED_SCRIPT) },
16719
+ { command: process.execPath, script: join10(binDir, PACKAGE_SCRIPT) },
16720
+ { command: process.execPath, script: join10(installRoot, PACKAGE_SCRIPT) }
16721
+ ];
16722
+ for (const candidate of candidates) {
16723
+ if (!exists(candidate.script)) continue;
16724
+ if (candidate.command !== process.execPath && !exists(candidate.command)) continue;
16725
+ return { command: candidate.command, prefixArgs: [candidate.script], source: entry };
16726
+ }
16727
+ return void 0;
16728
+ }
16729
+ function resolveCodegraphInvocation(options = {}) {
16730
+ const platform = options.platform ?? process.platform;
16731
+ const exists = options.exists ?? existsSync5;
16732
+ const explicit = options.explicitPath?.trim() ?? "";
16733
+ if (explicit !== "") {
16734
+ if (!exists(explicit)) {
16735
+ return { ok: false, problem: `codegraphPath points at "${explicit}", which does not exist` };
16736
+ }
16737
+ const invocation = invocationOf(explicit, platform, exists);
16738
+ if (invocation === void 0) {
16739
+ return {
16740
+ ok: false,
16741
+ problem: `codegraphPath "${explicit}" is not a runnable codegraph entry point`
16742
+ };
16743
+ }
16744
+ return { ok: true, invocation };
16745
+ }
16746
+ const pathValue = options.pathValue ?? process.env.PATH ?? "";
16747
+ const separator = platform === "win32" ? ";" : ":";
16748
+ const names = platform === "win32" ? WINDOWS_SHIM_NAMES : POSIX_SHIM_NAMES;
16749
+ for (const directory of pathValue.split(separator)) {
16750
+ if (directory === "") continue;
16751
+ for (const name2 of names) {
16752
+ const entry = join10(directory, name2);
16753
+ if (!exists(entry)) continue;
16754
+ const invocation = invocationOf(entry, platform, exists);
16755
+ if (invocation !== void 0) return { ok: true, invocation };
16756
+ }
16757
+ }
16758
+ return { ok: false, problem: "no codegraph executable was found on PATH" };
16759
+ }
16760
+ var CODEGRAPH_TIMEOUT_MS = 12e4;
16761
+ var MAX_CAPTURE_CHARS = 2e6;
16762
+ function runCodegraph(invocation, args, options) {
16763
+ options.signal?.throwIfAborted();
16764
+ const timeoutMs = options.timeoutMs ?? CODEGRAPH_TIMEOUT_MS;
16765
+ const env = {
16766
+ ...process.env,
16767
+ // WHY: the CLI is a machine surface here; ANSI color would corrupt anchored rows.
16768
+ NO_COLOR: "1",
16769
+ FORCE_COLOR: "0",
16770
+ ...options.env
16771
+ };
16772
+ return new Promise((resolve6, reject) => {
16773
+ const child = spawn(invocation.command, [...invocation.prefixArgs, ...args], {
16774
+ cwd: options.cwd,
16775
+ env,
16776
+ windowsHide: true,
16777
+ stdio: ["ignore", "pipe", "pipe"]
16778
+ });
16779
+ let stdout = "";
16780
+ let stderr = "";
16781
+ let timedOut = false;
16782
+ let settled = false;
16783
+ const capture = (current, chunk) => current.length >= MAX_CAPTURE_CHARS ? current : (current + chunk).slice(0, MAX_CAPTURE_CHARS);
16784
+ const stop = () => {
16785
+ if (settled) return;
16786
+ settled = true;
16787
+ clearTimeout(timer);
16788
+ options.signal?.removeEventListener("abort", onAbort);
16789
+ };
16790
+ const onAbort = () => {
16791
+ child.kill();
16792
+ stop();
16793
+ reject(options.signal?.reason ?? new Error("codegraph call aborted"));
16794
+ };
16795
+ const timer = setTimeout(() => {
16796
+ timedOut = true;
16797
+ child.kill();
16798
+ }, timeoutMs);
16799
+ child.stdout?.setEncoding("utf8");
16800
+ child.stderr?.setEncoding("utf8");
16801
+ child.stdout?.on("data", (chunk) => {
16802
+ stdout = capture(stdout, chunk);
16803
+ });
16804
+ child.stderr?.on("data", (chunk) => {
16805
+ stderr = capture(stderr, chunk);
16806
+ });
16807
+ child.on("error", (error) => {
16808
+ stop();
16809
+ reject(error);
16810
+ });
16811
+ child.on("close", (code) => {
16812
+ if (settled) return;
16813
+ stop();
16814
+ resolve6({ stdout, stderr, code, timedOut });
16815
+ });
16816
+ options.signal?.addEventListener("abort", onAbort, { once: true });
16817
+ });
16818
+ }
16819
+
16820
+ // dsh/codegraph/tools.ts
16821
+ import {
16822
+ defineTool as defineTool4
16823
+ } from "@deepseek-ai/dsh-tools";
16824
+
16825
+ // dsh/codegraph/project.ts
16826
+ import { dirname as dirname11, join as join11 } from "node:path";
16827
+ var CODEGRAPH_DIR = ".codegraph";
16828
+ var REPOSITORY_MARKER = ".git";
16829
+ async function resolveProjectPath(io, request) {
16830
+ const start = toCwd(request.requested ?? ".", request.cwd);
16831
+ let directory = start;
16832
+ let distance = 0;
16833
+ for (; ; ) {
16834
+ request.signal?.throwIfAborted();
16835
+ const index = await io.stat(join11(directory, CODEGRAPH_DIR), request.signal);
16836
+ const repository = await io.stat(join11(directory, REPOSITORY_MARKER), request.signal);
16837
+ const isRepository = repository !== void 0;
16838
+ if (index?.isDirectory === true && (distance === 0 || isRepository)) {
16839
+ return { ok: true, projectPath: directory, distance };
16840
+ }
16841
+ if (isRepository) return { ok: false, searchedFrom: start };
16842
+ const parent = dirname11(directory);
16843
+ if (parent === directory) return { ok: false, searchedFrom: start };
16844
+ directory = parent;
16845
+ distance += 1;
16846
+ }
16847
+ }
16848
+
16849
+ // dsh/codegraph/view.ts
16850
+ var FILE_HEADER = /^\*\*`(.+?)`\*\* — /u;
16851
+ var FILE_SUMMARY = /^\*\*(.+)\*\* — /u;
16852
+ var LOCATION = /^\*\*Location:\*\* (.+):(\d+)\b/u;
16853
+ var CONTEXT_HEADER = /^#### .+ \((.+):(\d+)\)$/u;
16854
+ var DRIFT_NOTICE = /^> .*?`([^`]+)` changed on disk/u;
16855
+ var NUMBERED_ROW = /^(\d+)\t(.*)$/u;
16856
+ var FENCE = /^```/u;
16857
+ function contextOf2(line) {
16858
+ const header = FILE_HEADER.exec(line);
16859
+ if (header !== null) return { file: header[1] ?? "", startLine: void 0 };
16860
+ const location = LOCATION.exec(line);
16861
+ if (location !== null) return { file: location[1] ?? "", startLine: void 0 };
16862
+ const summary = FILE_SUMMARY.exec(line);
16863
+ if (summary !== null) return { file: summary[1] ?? "", startLine: void 0 };
16864
+ const section = CONTEXT_HEADER.exec(line);
16865
+ if (section !== null) return { file: section[1] ?? "", startLine: Number(section[2] ?? 0) };
16866
+ const drift = DRIFT_NOTICE.exec(line);
16867
+ if (drift !== null) return { file: drift[1] ?? "", startLine: void 0 };
16868
+ return void 0;
16869
+ }
16870
+ function decodeOnce(state, file) {
16871
+ const cached = state.decoded.get(file);
16872
+ if (cached !== void 0) return cached;
16873
+ const pending = (async () => {
16874
+ try {
16875
+ return await decodeFileLines(state.deps, {
16876
+ path: file,
16877
+ cwd: state.projectPath,
16878
+ signal: state.signal
16879
+ });
16880
+ } catch {
16881
+ return void 0;
16882
+ }
16883
+ })();
16884
+ state.decoded.set(file, pending);
16885
+ return pending;
16886
+ }
16887
+ async function serveVerifiedRows(state, file, lineNumbers, texts) {
16888
+ if (lineNumbers.length === 0 || lineNumbers.length !== texts.length) return void 0;
16889
+ const disk = await decodeOnce(state, file);
16890
+ if (disk === void 0) return void 0;
16891
+ for (let index = 0; index < lineNumbers.length; index += 1) {
16892
+ const line = lineNumbers[index] ?? 0;
16893
+ if (line < 1 || line > disk.length) return void 0;
16894
+ if (disk[line - 1] !== (texts[index] ?? "")) return void 0;
16895
+ }
16896
+ const absolutePath = toCwd(file, state.projectPath);
16897
+ try {
16898
+ const served = await serveFileLines(state.deps, {
16899
+ path: absolutePath,
16900
+ cwd: state.projectPath,
16901
+ sessionKey: state.sessionKey,
16902
+ signal: state.signal,
16903
+ lineNumbers
16904
+ });
16905
+ if (served.length !== lineNumbers.length) return void 0;
16906
+ const hashes = new Map(served.map((row) => [row.line, row.hash]));
16907
+ const rows = [];
16908
+ for (let index = 0; index < lineNumbers.length; index += 1) {
16909
+ const hash = hashes.get(lineNumbers[index] ?? 0);
16910
+ if (hash === void 0) return void 0;
16911
+ rows.push(`${hash}${HASH_SEP}${texts[index] ?? ""}`);
16912
+ }
16913
+ state.served.add(absolutePath);
16914
+ return rows;
16915
+ } catch (error) {
16916
+ reportDiagnostic(
16917
+ "codegraph-view",
16918
+ `Could not serve ${file}; leaving the block as printed:`,
16919
+ error
16920
+ );
16921
+ return void 0;
16922
+ }
16923
+ }
16924
+ async function anchorRun(state, context, rows) {
16925
+ const file = context.file;
16926
+ if (file === void 0 || file === "" || rows.length === 0) return [...rows];
16927
+ const matches = rows.map((row) => NUMBERED_ROW.exec(row));
16928
+ if (matches.every((match) => match !== null)) {
16929
+ const lineNumbers = matches.map((match) => Number(match?.[1] ?? 0));
16930
+ const texts = matches.map((match) => match?.[2] ?? "");
16931
+ return await serveVerifiedRows(state, file, lineNumbers, texts) ?? [...rows];
16932
+ }
16933
+ if (matches.every((match) => match === null) && context.startLine !== void 0) {
16934
+ const startLine = context.startLine;
16935
+ const lineNumbers = rows.map((_row, index) => startLine + index);
16936
+ return await serveVerifiedRows(state, file, lineNumbers, [...rows]) ?? [...rows];
16937
+ }
16938
+ return [...rows];
16939
+ }
16940
+ async function anchorFencedBody(state, context, rows) {
16941
+ const numbered = rows.some((row) => NUMBERED_ROW.test(row));
16942
+ if (!numbered) return anchorRun(state, context, rows);
16943
+ const out = [];
16944
+ let index = 0;
16945
+ while (index < rows.length) {
16946
+ const row = rows[index] ?? "";
16947
+ if (!NUMBERED_ROW.test(row)) {
16948
+ out.push(row);
16949
+ index += 1;
16950
+ continue;
16951
+ }
16952
+ let end = index;
16953
+ while (end < rows.length && NUMBERED_ROW.test(rows[end] ?? "")) end += 1;
16954
+ out.push(...await anchorRun(state, context, rows.slice(index, end)));
16955
+ index = end;
16956
+ }
16957
+ return out;
16958
+ }
16959
+ async function anchorCodegraphView(deps, request) {
16960
+ const state = {
16961
+ deps,
16962
+ projectPath: request.projectPath,
16963
+ sessionKey: request.sessionKey,
16964
+ signal: request.signal,
16965
+ decoded: /* @__PURE__ */ new Map(),
16966
+ served: /* @__PURE__ */ new Set()
16967
+ };
16968
+ const lines = request.text.replace(/\r\n/gu, "\n").split("\n");
16969
+ const out = [];
16970
+ let context = { file: void 0, startLine: void 0 };
16971
+ let index = 0;
16972
+ while (index < lines.length) {
16973
+ const line = lines[index] ?? "";
16974
+ if (FENCE.test(line)) {
16975
+ let close = index + 1;
16976
+ while (close < lines.length && !FENCE.test(lines[close] ?? "")) close += 1;
16977
+ const body = lines.slice(index + 1, close);
16978
+ out.push(line, ...await anchorFencedBody(state, context, body));
16979
+ if (close < lines.length) {
16980
+ out.push(lines[close] ?? "");
16981
+ index = close + 1;
16982
+ } else {
16983
+ index = close;
16984
+ }
16985
+ continue;
16986
+ }
16987
+ const introduced = contextOf2(line);
16988
+ if (introduced !== void 0) {
16989
+ context = introduced;
16990
+ out.push(line);
16991
+ index += 1;
16992
+ continue;
16993
+ }
16994
+ if (context.file !== void 0 && NUMBERED_ROW.test(line)) {
16995
+ let end = index;
16996
+ while (end < lines.length && NUMBERED_ROW.test(lines[end] ?? "")) end += 1;
16997
+ out.push(...await anchorRun(state, context, lines.slice(index, end)));
16998
+ index = end;
16999
+ continue;
17000
+ }
17001
+ out.push(line);
17002
+ index += 1;
17003
+ }
17004
+ for (const absolutePath of state.served) {
17005
+ await deps.observations?.publish(
17006
+ absolutePath,
17007
+ request.exec,
17008
+ request.signal === void 0 ? void 0 : { signal: request.signal }
17009
+ );
17010
+ }
17011
+ return { text: out.join("\n"), servedFiles: [...state.served].sort() };
17012
+ }
17013
+
17014
+ // dsh/codegraph/tools.ts
17015
+ var OUTCOME_SCHEMA = {
17016
+ type: "object",
17017
+ properties: {
17018
+ text: { type: "string", required: true },
17019
+ projectPath: { type: "string" }
17020
+ },
17021
+ additionalProperties: false
17022
+ };
17023
+ var PROJECT_PATH_PARAMETER = {
17024
+ type: "string",
17025
+ description: "Project path whose `.codegraph` index to query. Defaults to the nearest index at or above the session working directory."
17026
+ };
17027
+ function stringArg(args, key) {
17028
+ const value = args[key];
17029
+ return typeof value === "string" && value.trim() !== "" ? value : void 0;
17030
+ }
17031
+ function numberArg(args, key) {
17032
+ const value = args[key];
17033
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
17034
+ }
17035
+ function booleanArg(args, key) {
17036
+ return args[key] === true;
17037
+ }
17038
+ function pushValue(argv, flag, value) {
17039
+ if (value === void 0) return;
17040
+ argv.push(flag, String(value));
17041
+ }
17042
+ function missingCliText(problem) {
17043
+ return [
17044
+ `codegraph is unavailable for this call: ${problem}.`,
17045
+ "Install codegraph 1.6.4 or newer, or point this plugin's `codegraphPath` config at its executable; indexing a repository stays the user's decision (`codegraph init`)."
17046
+ ].join("\n\n");
17047
+ }
17048
+ function missingIndexText(searchedFrom) {
17049
+ return [
17050
+ `No \`.codegraph\` index was found at or above ${searchedFrom}. Nothing is indexed for this workspace, so the codegraph tools cannot answer.`,
17051
+ "Indexing is the user's decision: ask before running `codegraph init` in the repository root."
17052
+ ].join("\n\n");
17053
+ }
17054
+ function timeoutText(subcommand, timeoutMs) {
17055
+ return `codegraph ${subcommand} did not finish within ${timeoutMs} ms and was stopped. Retry a narrower query, or use the built-in search tools for this call.`;
17056
+ }
17057
+ function failureText(subcommand, result) {
17058
+ const detail = result.stderr.trim() === "" ? result.stdout.trim() : result.stderr.trim();
17059
+ return [
17060
+ `codegraph ${subcommand} failed (exit ${result.code === null ? "signal" : result.code}).`,
17061
+ detail === "" ? "It printed no error text." : detail
17062
+ ].join("\n\n");
17063
+ }
17064
+ function emptyText(subcommand) {
17065
+ return [
17066
+ `codegraph ${subcommand} returned no output. That usually means the query matched nothing in the index, or the index is stale.`,
17067
+ "Run `codegraph sync` in the project root to refresh an index that lags the working tree."
17068
+ ].join("\n\n");
17069
+ }
17070
+ function launchFailureText(error) {
17071
+ const message = error instanceof Error ? error.message : String(error);
17072
+ return `codegraph could not be started: ${message}. Check the plugin's \`codegraphPath\` config and that the executable can run.`;
17073
+ }
17074
+ function withProjectNote(text, project) {
17075
+ if (project.distance === 0) return text;
17076
+ return `${text}
17077
+
17078
+ _(codegraph index: ${project.projectPath})_`;
17079
+ }
17080
+ async function executeQuery(deps, options, exec, query, rawArgs) {
17081
+ const args = typeof rawArgs === "object" && rawArgs !== null ? rawArgs : {};
17082
+ const planned = query.command(args);
17083
+ if (planned.problem !== void 0) return { text: planned.problem };
17084
+ const ctx = resolveToolContext(exec);
17085
+ const project = await resolveProjectPath(deps.io, {
17086
+ requested: stringArg(args, "projectPath"),
17087
+ cwd: ctx.cwd,
17088
+ signal: ctx.signal
17089
+ });
17090
+ if (!project.ok) return { text: missingIndexText(project.searchedFrom) };
17091
+ if (!options.resolution.ok) return { text: missingCliText(options.resolution.problem) };
17092
+ const timeoutMs = options.timeoutMs ?? CODEGRAPH_TIMEOUT_MS;
17093
+ let result;
17094
+ try {
17095
+ result = await runCodegraph(
17096
+ options.resolution.invocation,
17097
+ [...planned.args, "-p", project.projectPath],
17098
+ { cwd: ctx.cwd, signal: ctx.signal, timeoutMs }
17099
+ );
17100
+ } catch (error) {
17101
+ ctx.signal?.throwIfAborted();
17102
+ return { text: launchFailureText(error) };
17103
+ }
17104
+ if (result.timedOut) return { text: timeoutText(query.subcommand, timeoutMs) };
17105
+ if (result.code !== 0) return { text: failureText(query.subcommand, result) };
17106
+ const printed = result.stdout.replace(/\r\n/gu, "\n").trimEnd();
17107
+ if (printed === "") return { text: emptyText(query.subcommand) };
17108
+ if (!query.anchors) return { text: withProjectNote(printed, project) };
17109
+ const view = await anchorCodegraphView(deps, {
17110
+ text: printed,
17111
+ projectPath: project.projectPath,
17112
+ sessionKey: ctx.sessionKey,
17113
+ signal: ctx.signal,
17114
+ exec
17115
+ });
17116
+ return { text: withProjectNote(view.text, project), projectPath: project.projectPath };
17117
+ }
17118
+ var SOURCE_NOTE = "The source is served as `HASH\u2502content` rows, so treat these files as already read and edit them by their anchors instead of reading them again.";
17119
+ var QUERIES = [
17120
+ {
17121
+ name: "codegraph_explore",
17122
+ subcommand: "explore",
17123
+ anchors: true,
17124
+ description: `Explore an area: the verbatim current source of the relevant symbols grouped by file, plus the call paths among them and what depends on them. ${SOURCE_NOTE} Prefer this over grep/find for architecture, flow, "where is X" and "what would changing X break" questions whenever the workspace has a \`.codegraph\` index.`,
17125
+ parameters: {
17126
+ query: {
17127
+ type: "string",
17128
+ required: true,
17129
+ description: 'Symbol names, file names or a short natural-language question (e.g. "AuthService loginUser session-manager"). For a flow question, name the symbols spanning the flow.'
17130
+ },
17131
+ maxFiles: {
17132
+ type: "number",
17133
+ description: "Maximum number of files to include source from."
17134
+ },
17135
+ projectPath: PROJECT_PATH_PARAMETER
17136
+ },
17137
+ command: (args) => {
17138
+ const query = stringArg(args, "query") ?? "";
17139
+ const argv = ["explore", query];
17140
+ pushValue(argv, "--max-files", numberArg(args, "maxFiles"));
17141
+ return { args: argv };
17142
+ }
17143
+ },
17144
+ {
17145
+ name: "codegraph_node",
17146
+ subcommand: "node",
17147
+ anchors: true,
17148
+ description: `One symbol's source plus the functions it calls and the functions that call it \u2014 or, in file mode, a line window of one file with its dependents. ${SOURCE_NOTE}`,
17149
+ parameters: {
17150
+ symbol: {
17151
+ type: "string",
17152
+ description: "Symbol name to inspect (function, method, class, interface, type)."
17153
+ },
17154
+ file: {
17155
+ type: "string",
17156
+ description: "File mode: read this file's line window with its dependents; also disambiguates same-named symbols."
17157
+ },
17158
+ offset: { type: "number", description: "File mode: 1-based first line." },
17159
+ limit: { type: "number", description: "File mode: maximum lines." },
17160
+ symbolsOnly: {
17161
+ type: "boolean",
17162
+ description: "File mode: return only the file's symbol map and dependents."
17163
+ },
17164
+ projectPath: PROJECT_PATH_PARAMETER
17165
+ },
17166
+ command: (args) => {
17167
+ const symbol = stringArg(args, "symbol");
17168
+ const file = stringArg(args, "file");
17169
+ if (symbol === void 0 && file === void 0) {
17170
+ return { args: [], problem: "codegraph_node needs `symbol` or `file`." };
17171
+ }
17172
+ const argv = ["node"];
17173
+ if (symbol !== void 0) argv.push(symbol);
17174
+ if (file !== void 0) argv.push("-f", file);
17175
+ pushValue(argv, "--offset", numberArg(args, "offset"));
17176
+ pushValue(argv, "--limit", numberArg(args, "limit"));
17177
+ if (booleanArg(args, "symbolsOnly")) argv.push("--symbols-only");
17178
+ return { args: argv };
17179
+ }
17180
+ },
17181
+ {
17182
+ name: "codegraph_context",
17183
+ subcommand: "context",
17184
+ anchors: true,
17185
+ description: `Build context for a task: entry points, related symbols, their relationships and their code blocks. ${SOURCE_NOTE}`,
17186
+ parameters: {
17187
+ task: {
17188
+ type: "string",
17189
+ required: true,
17190
+ description: 'The task or question to gather context for (e.g. "add a retry to the upload path").'
17191
+ },
17192
+ maxNodes: { type: "number", description: "Maximum number of symbols to include." },
17193
+ noCode: { type: "boolean", description: "Omit code blocks and return structure only." },
17194
+ projectPath: PROJECT_PATH_PARAMETER
17195
+ },
17196
+ command: (args) => {
17197
+ const argv = ["context", stringArg(args, "task") ?? ""];
17198
+ pushValue(argv, "-n", numberArg(args, "maxNodes"));
17199
+ if (booleanArg(args, "noCode")) argv.push("--no-code");
17200
+ return { args: argv };
17201
+ }
17202
+ },
17203
+ {
17204
+ name: "codegraph_search",
17205
+ subcommand: "query",
17206
+ anchors: false,
17207
+ description: "Quick symbol search by name. Returns locations only (no source): use codegraph_explore to understand an area, or codegraph_node for one symbol's served source.",
17208
+ parameters: {
17209
+ query: {
17210
+ type: "string",
17211
+ required: true,
17212
+ description: 'Symbol name or partial name (e.g. "auth", "signIn", "UserService").'
17213
+ },
17214
+ kind: {
17215
+ type: "string",
17216
+ enum: [
17217
+ "function",
17218
+ "method",
17219
+ "class",
17220
+ "interface",
17221
+ "type",
17222
+ "variable",
17223
+ "route",
17224
+ "component"
17225
+ ],
17226
+ description: "Filter by node kind."
17227
+ },
17228
+ limit: { type: "number", description: "Maximum results (default: 10)." },
17229
+ projectPath: PROJECT_PATH_PARAMETER
17230
+ },
17231
+ command: (args) => {
17232
+ const argv = ["query", stringArg(args, "query") ?? ""];
17233
+ const kind = stringArg(args, "kind");
17234
+ if (kind !== void 0) argv.push("-k", kind);
17235
+ pushValue(argv, "-l", numberArg(args, "limit"));
17236
+ return { args: argv };
17237
+ }
17238
+ },
17239
+ {
17240
+ name: "codegraph_callers",
17241
+ subcommand: "callers",
17242
+ anchors: false,
17243
+ description: "List the functions that call a symbol, including callback registrations a text search cannot follow. Returns locations; call codegraph_node or codegraph_explore when the source is needed.",
17244
+ parameters: {
17245
+ symbol: {
17246
+ type: "string",
17247
+ required: true,
17248
+ description: "Function, method or class to find callers for."
17249
+ },
17250
+ file: {
17251
+ type: "string",
17252
+ description: "Narrow to the definition in this file (path or suffix) when several same-named symbols exist."
17253
+ },
17254
+ limit: { type: "number", description: "Maximum number of callers (default: 20)." },
17255
+ projectPath: PROJECT_PATH_PARAMETER
17256
+ },
17257
+ command: (args) => {
17258
+ const argv = ["callers", stringArg(args, "symbol") ?? ""];
17259
+ const file = stringArg(args, "file");
17260
+ if (file !== void 0) argv.push("-f", file);
17261
+ pushValue(argv, "-l", numberArg(args, "limit"));
17262
+ return { args: argv };
17263
+ }
17264
+ },
17265
+ {
17266
+ name: "codegraph_callees",
17267
+ subcommand: "callees",
17268
+ anchors: false,
17269
+ description: "List the functions a symbol calls. Returns locations; call codegraph_node or codegraph_explore when the source is needed.",
17270
+ parameters: {
17271
+ symbol: {
17272
+ type: "string",
17273
+ required: true,
17274
+ description: "Function, method or class to find callees for."
17275
+ },
17276
+ file: {
17277
+ type: "string",
17278
+ description: "Narrow to the definition in this file (path or suffix) when several same-named symbols exist."
17279
+ },
17280
+ limit: { type: "number", description: "Maximum number of callees (default: 20)." },
17281
+ projectPath: PROJECT_PATH_PARAMETER
17282
+ },
17283
+ command: (args) => {
17284
+ const argv = ["callees", stringArg(args, "symbol") ?? ""];
17285
+ const file = stringArg(args, "file");
17286
+ if (file !== void 0) argv.push("-f", file);
17287
+ pushValue(argv, "-l", numberArg(args, "limit"));
17288
+ return { args: argv };
17289
+ }
17290
+ },
17291
+ {
17292
+ name: "codegraph_impact",
17293
+ subcommand: "impact",
17294
+ anchors: false,
17295
+ description: "Analyze what is affected by changing a symbol: the dependents reachable from it within a traversal depth. Returns locations; fetch bodies with codegraph_node.",
17296
+ parameters: {
17297
+ symbol: { type: "string", required: true, description: "Symbol to analyze." },
17298
+ file: {
17299
+ type: "string",
17300
+ description: "Narrow to the definition in this file (path or suffix) when several same-named symbols exist."
17301
+ },
17302
+ depth: { type: "number", description: "Traversal depth (default: 2)." },
17303
+ projectPath: PROJECT_PATH_PARAMETER
17304
+ },
17305
+ command: (args) => {
17306
+ const argv = ["impact", stringArg(args, "symbol") ?? ""];
17307
+ const file = stringArg(args, "file");
17308
+ if (file !== void 0) argv.push("-f", file);
17309
+ pushValue(argv, "-d", numberArg(args, "depth"));
17310
+ return { args: argv };
17311
+ }
17312
+ },
17313
+ {
17314
+ name: "codegraph_implementations",
17315
+ subcommand: "implementations",
17316
+ anchors: false,
17317
+ description: "List the types that implement or extend a trait, interface or class, down to a subtype depth. Returns locations; fetch bodies with codegraph_node.",
17318
+ parameters: {
17319
+ symbol: {
17320
+ type: "string",
17321
+ required: true,
17322
+ description: "Trait, interface or class to find implementors of."
17323
+ },
17324
+ file: {
17325
+ type: "string",
17326
+ description: "Narrow to the definition in this file (path or suffix) when several same-named symbols exist."
17327
+ },
17328
+ depth: { type: "number", description: "Levels of subtypes to list, 1-6 (default: 1)." },
17329
+ projectPath: PROJECT_PATH_PARAMETER
17330
+ },
17331
+ command: (args) => {
17332
+ const argv = ["implementations", stringArg(args, "symbol") ?? ""];
17333
+ const file = stringArg(args, "file");
17334
+ if (file !== void 0) argv.push("-f", file);
17335
+ pushValue(argv, "-d", numberArg(args, "depth"));
17336
+ return { args: argv };
17337
+ }
17338
+ }
17339
+ ];
17340
+ function buildTool(deps, options, query) {
17341
+ return defineTool4({
17342
+ name: query.name,
17343
+ description: query.description,
17344
+ parameters: query.parameters,
17345
+ output: {
17346
+ schema: OUTCOME_SCHEMA,
17347
+ render: (_args, value) => [{ type: "text", text: value.text }]
17348
+ },
17349
+ async execute(args, exec) {
17350
+ const outcome = await executeQuery(deps, options, exec, query, args);
17351
+ return outcome.projectPath === void 0 ? { text: outcome.text } : { text: outcome.text, projectPath: outcome.projectPath };
17352
+ }
17353
+ });
17354
+ }
17355
+ function buildCodegraphTools(deps, options) {
17356
+ return QUERIES.map((query) => buildTool(deps, options, query));
17357
+ }
17358
+
17359
+ // dsh/diagnostics/tools.ts
17360
+ import { dirname as dirname14, join as join13 } from "node:path";
17361
+ import {
17362
+ defineTool as defineTool5
17363
+ } from "@deepseek-ai/dsh-tools";
17364
+
17365
+ // dsh/diagnostics/cli.ts
17366
+ import { spawn as spawn2 } from "node:child_process";
17367
+ import { existsSync as existsSync6 } from "node:fs";
17368
+ import { dirname as dirname12, extname as extname2, join as join12 } from "node:path";
17369
+ var DIAGNOSTICS_TOOL_NAMES = ["cargo-check", "cargo-clippy", "tsc"];
17370
+ var TSC_SCRIPT = join12("node_modules", "typescript", "bin", "tsc");
17371
+ var WINDOWS_CARGO_NAMES = ["cargo.exe", "cargo.cmd", "cargo.bat", "cargo"];
17372
+ var POSIX_CARGO_NAMES = ["cargo"];
17373
+ var WINDOWS_TSC_NAMES = ["tsc.cmd", "tsc.exe", "tsc.bat", "tsc"];
17374
+ var POSIX_TSC_NAMES = ["tsc"];
17375
+ function isDiagnosticsTool(value) {
17376
+ return typeof value === "string" && DIAGNOSTICS_TOOL_NAMES.includes(value);
17377
+ }
17378
+ var PLANNED_ARGS = {
17379
+ "cargo-check": ["check", "--message-format=json", "--quiet"],
17380
+ "cargo-clippy": ["clippy", "--message-format=json", "--quiet"],
17381
+ tsc: ["--noEmit", "--pretty", "false"]
17382
+ };
17383
+ function planDiagnosticsArgs(tool) {
17384
+ return PLANNED_ARGS[tool];
17385
+ }
17386
+ function isScript2(entry) {
17387
+ const ext = extname2(entry).toLowerCase();
17388
+ return ext === ".js" || ext === ".mjs" || ext === ".cjs";
17389
+ }
17390
+ function isCommandShim2(entry) {
17391
+ const lower = entry.toLowerCase();
17392
+ return lower.endsWith(".cmd") || lower.endsWith(".bat");
17393
+ }
17394
+ function pathDirectories(pathValue, platform) {
17395
+ const separator = platform === "win32" ? ";" : ":";
17396
+ return pathValue.split(separator).filter((directory) => directory !== "");
17397
+ }
17398
+ function runnableEntry(entry, platform) {
17399
+ if (isScript2(entry)) return { command: process.execPath, prefixArgs: [entry], source: entry };
17400
+ if (isCommandShim2(entry)) return void 0;
17401
+ const ext = extname2(entry).toLowerCase();
17402
+ if (ext === "" && platform === "win32") return void 0;
17403
+ return { command: entry, prefixArgs: [], source: entry };
17404
+ }
17405
+ function findUpward(start, candidate, exists) {
17406
+ let directory = start;
17407
+ for (; ; ) {
17408
+ const entry = candidate(directory);
17409
+ if (exists(entry)) return entry;
17410
+ const parent = dirname12(directory);
17411
+ if (parent === directory) return void 0;
17412
+ directory = parent;
17413
+ }
17414
+ }
17415
+ function resolveCargoInvocation(options = {}) {
17416
+ const platform = options.platform ?? process.platform;
17417
+ const exists = options.exists ?? existsSync6;
17418
+ const names = platform === "win32" ? WINDOWS_CARGO_NAMES : POSIX_CARGO_NAMES;
17419
+ let shim;
17420
+ for (const directory of pathDirectories(options.pathValue ?? process.env.PATH ?? "", platform)) {
17421
+ for (const name2 of names) {
17422
+ const entry = join12(directory, name2);
17423
+ if (!exists(entry)) continue;
17424
+ if (isCommandShim2(entry)) {
17425
+ const sibling = join12(directory, "cargo.exe");
17426
+ if (!exists(sibling)) {
17427
+ shim ??= entry;
17428
+ continue;
17429
+ }
17430
+ return { ok: true, invocation: { command: sibling, prefixArgs: [], source: sibling } };
17431
+ }
17432
+ const invocation = runnableEntry(entry, platform);
17433
+ if (invocation !== void 0) return { ok: true, invocation };
17434
+ }
17435
+ }
17436
+ if (shim !== void 0) {
17437
+ return {
17438
+ ok: false,
17439
+ problem: `only a shell shim was found at "${shim}", which cannot run without a shell; put the real cargo.exe on PATH`
17440
+ };
17441
+ }
17442
+ return { ok: false, problem: "no cargo executable was found on PATH" };
17443
+ }
17444
+ function resolveTscInvocation(cwd, options = {}) {
17445
+ const platform = options.platform ?? process.platform;
17446
+ const exists = options.exists ?? existsSync6;
17447
+ const local = findUpward(cwd, (directory) => join12(directory, TSC_SCRIPT), exists);
17448
+ if (local !== void 0) {
17449
+ return {
17450
+ ok: true,
17451
+ invocation: { command: process.execPath, prefixArgs: [local], source: local }
17452
+ };
17453
+ }
17454
+ const names = platform === "win32" ? WINDOWS_TSC_NAMES : POSIX_TSC_NAMES;
17455
+ let shim;
17456
+ for (const directory of pathDirectories(options.pathValue ?? process.env.PATH ?? "", platform)) {
17457
+ for (const name2 of names) {
17458
+ const entry = join12(directory, name2);
17459
+ if (!exists(entry)) continue;
17460
+ if (isCommandShim2(entry)) {
17461
+ const binDir = dirname12(entry);
17462
+ for (const root of [binDir, dirname12(binDir)]) {
17463
+ const script = join12(root, TSC_SCRIPT);
17464
+ if (!exists(script)) continue;
17465
+ return {
17466
+ ok: true,
17467
+ invocation: { command: process.execPath, prefixArgs: [script], source: script }
17468
+ };
17469
+ }
17470
+ shim ??= entry;
17471
+ continue;
17472
+ }
17473
+ const invocation = runnableEntry(entry, platform);
17474
+ if (invocation !== void 0) return { ok: true, invocation };
17475
+ }
17476
+ }
17477
+ if (shim !== void 0) {
17478
+ return {
17479
+ ok: false,
17480
+ problem: `only a shell shim was found at "${shim}", which cannot run without a shell; put the real tsc script on PATH`
17481
+ };
17482
+ }
17483
+ return {
17484
+ ok: false,
17485
+ problem: `no TypeScript compiler was found: ${cwd} has no ${TSC_SCRIPT} at or above it, and no tsc is on PATH`
17486
+ };
17487
+ }
17488
+ var DIAGNOSTICS_TIMEOUT_MS = 12e4;
17489
+ var MAX_CAPTURE_CHARS2 = 2e6;
17490
+ function runDiagnosticsCommand(invocation, args, options) {
17491
+ options.signal?.throwIfAborted();
17492
+ const timeoutMs = options.timeoutMs ?? DIAGNOSTICS_TIMEOUT_MS;
17493
+ const env = {
17494
+ ...process.env,
17495
+ // WHY: the diagnostics are a machine surface; a colour escape would corrupt the parsed
17496
+ // WHY: text and the anchored rows served from it.
17497
+ NO_COLOR: "1",
17498
+ FORCE_COLOR: "0",
17499
+ CARGO_TERM_COLOR: "never",
17500
+ ...options.env
17501
+ };
17502
+ return new Promise((resolve6, reject) => {
17503
+ const child = spawn2(invocation.command, [...invocation.prefixArgs, ...args], {
17504
+ cwd: options.cwd,
17505
+ env,
17506
+ windowsHide: true,
17507
+ stdio: ["ignore", "pipe", "pipe"]
17508
+ });
17509
+ let stdout = "";
17510
+ let stderr = "";
17511
+ let timedOut = false;
17512
+ let settled = false;
17513
+ const capture = (current, chunk) => current.length >= MAX_CAPTURE_CHARS2 ? current : (current + chunk).slice(0, MAX_CAPTURE_CHARS2);
17514
+ const stop = () => {
17515
+ if (settled) return;
17516
+ settled = true;
17517
+ clearTimeout(timer);
17518
+ options.signal?.removeEventListener("abort", onAbort);
17519
+ };
17520
+ const onAbort = () => {
17521
+ child.kill();
17522
+ stop();
17523
+ reject(options.signal?.reason ?? new Error("diagnostics run aborted"));
17524
+ };
17525
+ const timer = setTimeout(() => {
17526
+ timedOut = true;
17527
+ child.kill();
17528
+ }, timeoutMs);
17529
+ child.stdout?.setEncoding("utf8");
17530
+ child.stderr?.setEncoding("utf8");
17531
+ child.stdout?.on("data", (chunk) => {
17532
+ stdout = capture(stdout, chunk);
17533
+ });
17534
+ child.stderr?.on("data", (chunk) => {
17535
+ stderr = capture(stderr, chunk);
17536
+ });
17537
+ child.on("error", (error) => {
17538
+ stop();
17539
+ reject(error);
17540
+ });
17541
+ child.on("close", (code) => {
17542
+ if (settled) return;
17543
+ stop();
17544
+ resolve6({ stdout, stderr, code, timedOut });
17545
+ });
17546
+ options.signal?.addEventListener("abort", onAbort, { once: true });
17547
+ });
17548
+ }
17549
+
17550
+ // dsh/diagnostics/messages.ts
17551
+ var TAIL_LINES = 40;
17552
+ function plural(count, noun) {
17553
+ return `${count} ${noun}${count === 1 ? "" : "s"}`;
17554
+ }
17555
+ function tailLines(text, max) {
17556
+ if (text.trim() === "") return "";
17557
+ const lines = text.replace(/\r\n/gu, "\n").replace(/\n+$/u, "").split("\n");
17558
+ return lines.slice(-max).join("\n");
17559
+ }
17560
+ function summaryLine(tool, cwd, counts) {
17561
+ return `${plural(counts.total, "diagnostic")} (${plural(counts.errors, "error")}, ${plural(
17562
+ counts.warnings,
17563
+ "warning"
17564
+ )}) from ${tool} in ${cwd}`;
17565
+ }
17566
+ function showingNote(total, shown) {
17567
+ return `_Showing the first ${shown} of ${plural(total, "diagnostic")}; raise \`maxDiagnostics\` for the rest._`;
17568
+ }
17569
+ function skippedNote(skipped) {
17570
+ return `_${plural(skipped, "diagnostic")} skipped: the file could not be served as rows (unreadable, not UTF-8, binary, or the reported line is outside the file)._`;
17571
+ }
17572
+ function cleanText(tool, cwd) {
17573
+ return `${tool} reported no diagnostics in ${cwd}.`;
17574
+ }
17575
+ function missingToolchainText(tool, problem) {
17576
+ const hint = tool === "tsc" ? "Install the project's TypeScript dependency so `node_modules/typescript/bin/tsc` resolves (for this repository: `pnpm install`), or put a `tsc` on PATH." : "Install the Rust toolchain (rustup) so `cargo` is on PATH, then retry from the project that holds `Cargo.toml`.";
17577
+ return [`${tool} is unavailable for this call: ${problem}.`, hint].join("\n\n");
17578
+ }
17579
+ function missingTsconfigText(cwd) {
17580
+ return [
17581
+ `No tsconfig.json or jsconfig.json was found at or above ${cwd}, so \`tsc\` would have no project to check.`,
17582
+ "Run this from (or pass `cwd`) the directory that holds the project's tsconfig.json."
17583
+ ].join("\n\n");
17584
+ }
17585
+ function unusableCwdText(cwd) {
17586
+ return [
17587
+ `${cwd} is not a readable directory, so no toolchain could run there.`,
17588
+ "Pass `cwd` as the project root that holds Cargo.toml or tsconfig.json, or omit it to use the session working directory."
17589
+ ].join("\n\n");
17590
+ }
17591
+ function timeoutText2(tool, timeoutMs) {
17592
+ return `${tool} did not finish within ${timeoutMs} ms and was stopped. Retry with a narrower \`cwd\` (one crate or package), or run the project's own check script instead.`;
17593
+ }
17594
+ function rawOutputText(tool, result) {
17595
+ const exit = result.code === null ? "stopped on a signal" : `exited with code ${result.code}`;
17596
+ const sections = [
17597
+ `${tool} ${exit} and printed no diagnostics this tool could parse.`,
17598
+ "That usually means the invocation does not match the project (run it from the project root, or pass `cwd`), or the toolchain printed a different output format."
17599
+ ];
17600
+ const stdout = tailLines(result.stdout, TAIL_LINES);
17601
+ const stderr = tailLines(result.stderr, TAIL_LINES);
17602
+ if (stdout !== "") sections.push(`Last lines of stdout:
17603
+
17604
+ ${stdout}`);
17605
+ if (stderr !== "") sections.push(`Last lines of stderr:
17606
+
17607
+ ${stderr}`);
17608
+ if (stdout === "" && stderr === "") sections.push("It printed nothing at all.");
17609
+ return sections.join("\n\n");
17610
+ }
17611
+ function launchFailureText2(tool, error) {
17612
+ const message = error instanceof Error ? error.message : String(error);
17613
+ return `${tool} could not be started: ${message}. Check that the toolchain executable can run in this session.`;
17614
+ }
17615
+
17616
+ // dsh/diagnostics/parse.ts
17617
+ function recordOf(value) {
17618
+ return typeof value === "object" && value !== null ? value : void 0;
17619
+ }
17620
+ function textOf(value) {
17621
+ return typeof value === "string" && value.trim() !== "" ? value : void 0;
17622
+ }
17623
+ function positionOf(value) {
17624
+ return typeof value === "number" && Number.isInteger(value) && value >= 1 ? value : void 0;
17625
+ }
17626
+ function primarySpanOf(message) {
17627
+ const spans = message.spans;
17628
+ if (!Array.isArray(spans)) return void 0;
17629
+ for (const candidate of spans) {
17630
+ const span = recordOf(candidate);
17631
+ if (span === void 0 || span.is_primary !== true) continue;
17632
+ const file = textOf(span.file_name);
17633
+ const line = positionOf(span.line_start);
17634
+ if (file === void 0 || line === void 0) continue;
17635
+ return {
17636
+ file,
17637
+ line,
17638
+ column: positionOf(span.column_start) ?? 1,
17639
+ label: textOf(span.label)
17640
+ };
17641
+ }
17642
+ return void 0;
17643
+ }
17644
+ function parseCargoLine(line) {
17645
+ if (!line.startsWith("{")) return void 0;
17646
+ let parsed;
17647
+ try {
17648
+ parsed = JSON.parse(line);
17649
+ } catch {
17650
+ return void 0;
17651
+ }
17652
+ const record = recordOf(parsed);
17653
+ if (record === void 0 || record.reason !== "compiler-message") return void 0;
17654
+ const message = recordOf(record.message);
17655
+ if (message === void 0) return void 0;
17656
+ const level = textOf(message.level);
17657
+ const headline = textOf(message.message);
17658
+ if (level === void 0 || headline === void 0) return void 0;
17659
+ const span = primarySpanOf(message);
17660
+ if (span === void 0) return void 0;
17661
+ const code = textOf(recordOf(message.code)?.code);
17662
+ return {
17663
+ level,
17664
+ ...code === void 0 ? {} : { code },
17665
+ message: headline,
17666
+ file: span.file,
17667
+ line: span.line,
17668
+ column: span.column,
17669
+ ...span.label === void 0 ? {} : { label: span.label }
17670
+ };
17671
+ }
17672
+ var TSC_DIAGNOSTIC = /^(.+?)\((\d+),(\d+)\): (error|warning) (TS\d+): (.*)$/u;
17673
+ var TSC_CONTINUATION = /^\s+\S/u;
17674
+ function parseCargoOutput(stdout) {
17675
+ const diagnostics = [];
17676
+ for (const line of stdout.replace(/\r\n/gu, "\n").split("\n")) {
17677
+ const diagnostic = parseCargoLine(line);
17678
+ if (diagnostic !== void 0) diagnostics.push(diagnostic);
17679
+ }
17680
+ return diagnostics;
17681
+ }
17682
+ function parseTscOutput(stdout) {
17683
+ const lines = stdout.replace(/\r\n/gu, "\n").split("\n");
17684
+ const diagnostics = [];
17685
+ let index = 0;
17686
+ while (index < lines.length) {
17687
+ const line = lines[index] ?? "";
17688
+ const match = TSC_DIAGNOSTIC.exec(line);
17689
+ if (match === null) {
17690
+ index += 1;
17691
+ continue;
17692
+ }
17693
+ const file = textOf(match[1]);
17694
+ const lineNumber = positionOf(Number(match[2]));
17695
+ const level = textOf(match[4]);
17696
+ const message = textOf(match[6]);
17697
+ if (file === void 0 || lineNumber === void 0 || level === void 0 || message === void 0) {
17698
+ index += 1;
17699
+ continue;
17700
+ }
17701
+ const detail = [];
17702
+ let next = index + 1;
17703
+ while (next < lines.length && TSC_CONTINUATION.test(lines[next] ?? "")) {
17704
+ detail.push((lines[next] ?? "").trimEnd());
17705
+ next += 1;
17706
+ }
17707
+ const column = positionOf(Number(match[3])) ?? 1;
17708
+ diagnostics.push({
17709
+ level,
17710
+ code: match[5] ?? "TS0000",
17711
+ message,
17712
+ file,
17713
+ line: lineNumber,
17714
+ column,
17715
+ ...detail.length === 0 ? {} : { detail }
17716
+ });
17717
+ index = next;
17718
+ }
17719
+ return diagnostics;
17720
+ }
17721
+ function parseDiagnostics(tool, stdout) {
17722
+ return tool === "tsc" ? parseTscOutput(stdout) : parseCargoOutput(stdout);
17723
+ }
17724
+
17725
+ // dsh/diagnostics/view.ts
17726
+ import { dirname as dirname13, isAbsolute as isAbsolute7 } from "node:path";
17727
+ function headerOf(diagnostic) {
17728
+ const code = diagnostic.code === void 0 ? "" : `[${diagnostic.code}]`;
17729
+ return `${diagnostic.level}${code} ${diagnostic.message} \u2014 ${diagnostic.file}:${diagnostic.line}:${diagnostic.column}`;
17730
+ }
17731
+ function detailOf(diagnostic) {
17732
+ const lines = [];
17733
+ if (diagnostic.label !== void 0) lines.push(` ${diagnostic.label}`);
17734
+ for (const line of diagnostic.detail ?? []) lines.push(` ${line.trim()}`);
17735
+ return lines;
17736
+ }
17737
+ async function statOnce(state, candidate) {
17738
+ try {
17739
+ const info = await state.deps.io.stat(candidate, state.signal);
17740
+ return info?.isFile === true;
17741
+ } catch {
17742
+ return false;
17743
+ }
17744
+ }
17745
+ function resolveOnce(state, printed) {
17746
+ const cached = state.resolved.get(printed);
17747
+ if (cached !== void 0) return cached;
17748
+ const pending = (async () => {
17749
+ if (isAbsolute7(printed)) return await statOnce(state, printed) ? printed : void 0;
17750
+ let directory = state.cwd;
17751
+ for (; ; ) {
17752
+ state.signal?.throwIfAborted();
17753
+ const candidate = toCwd(printed, directory);
17754
+ if (await statOnce(state, candidate)) return candidate;
17755
+ const parent = dirname13(directory);
17756
+ if (parent === directory) return void 0;
17757
+ directory = parent;
17758
+ }
17759
+ })();
17760
+ state.resolved.set(printed, pending);
17761
+ return pending;
17762
+ }
17763
+ function decodeOnce2(state, file) {
17764
+ const cached = state.decoded.get(file);
17765
+ if (cached !== void 0) return cached;
17766
+ const pending = (async () => {
17767
+ try {
17768
+ return await decodeFileLines(state.deps, {
17769
+ path: file,
17770
+ cwd: state.cwd,
17771
+ signal: state.signal
17772
+ });
17773
+ } catch {
17774
+ return void 0;
17775
+ }
17776
+ })();
17777
+ state.decoded.set(file, pending);
17778
+ return pending;
17779
+ }
17780
+ function windowOf(start, end) {
17781
+ const lines = [];
17782
+ for (let line = start; line <= end; line += 1) lines.push(line);
17783
+ return lines;
17784
+ }
17785
+ async function rowsOf(state, diagnostic) {
17786
+ const absolutePath = await resolveOnce(state, diagnostic.file);
17787
+ if (absolutePath === void 0) return void 0;
17788
+ const disk = await decodeOnce2(state, absolutePath);
17789
+ if (disk === void 0 || disk.length === 0) return void 0;
17790
+ if (diagnostic.line < 1 || diagnostic.line > disk.length) return void 0;
17791
+ const start = Math.max(1, diagnostic.line - state.contextLines);
17792
+ const end = Math.min(disk.length, diagnostic.line + state.contextLines);
17793
+ const lineNumbers = windowOf(start, end);
17794
+ try {
17795
+ const served = await serveFileLines(state.deps, {
17796
+ path: absolutePath,
17797
+ cwd: state.cwd,
17798
+ sessionKey: state.sessionKey,
17799
+ signal: state.signal,
17800
+ lineNumbers
17801
+ });
17802
+ if (served.length !== lineNumbers.length) return void 0;
17803
+ const rows = [];
17804
+ for (const row of served) {
17805
+ if (disk[row.line - 1] !== row.text) return void 0;
17806
+ rows.push(`${row.hash}${HASH_SEP}${row.text}`);
17807
+ }
17808
+ state.served.add(absolutePath);
17809
+ return rows;
17810
+ } catch (error) {
17811
+ reportDiagnostic(
17812
+ "diagnostics-view",
17813
+ `Could not serve ${diagnostic.file}; skipping that diagnostic:`,
17814
+ error
17815
+ );
17816
+ return void 0;
17817
+ }
17818
+ }
17819
+ async function anchorDiagnosticsView(deps, request) {
17820
+ const state = {
17821
+ deps,
17822
+ cwd: request.cwd,
17823
+ contextLines: request.contextLines,
17824
+ sessionKey: request.sessionKey,
17825
+ signal: request.signal,
17826
+ resolved: /* @__PURE__ */ new Map(),
17827
+ decoded: /* @__PURE__ */ new Map(),
17828
+ served: /* @__PURE__ */ new Set()
17829
+ };
17830
+ const blocks = [];
17831
+ let skipped = 0;
17832
+ for (const diagnostic of request.diagnostics) {
17833
+ request.signal?.throwIfAborted();
17834
+ const rows = await rowsOf(state, diagnostic);
17835
+ if (rows === void 0) {
17836
+ skipped += 1;
17837
+ continue;
17838
+ }
17839
+ blocks.push([headerOf(diagnostic), ...detailOf(diagnostic), ...rows].join("\n"));
17840
+ }
17841
+ for (const absolutePath of state.served) {
17842
+ await deps.observations?.publish(
17843
+ absolutePath,
17844
+ request.exec,
17845
+ request.signal === void 0 ? void 0 : { signal: request.signal }
17846
+ );
17847
+ }
17848
+ return { blocks, skipped, servedFiles: [...state.served].sort() };
17849
+ }
17850
+
17851
+ // dsh/diagnostics/tools.ts
17852
+ var DIAGNOSTICS_TOOL_NAME = "diagnostics";
17853
+ var DEFAULT_CONTEXT_LINES = 2;
17854
+ var DEFAULT_MAX_DIAGNOSTICS = 20;
17855
+ var MIN_CONTEXT_LINES = 1;
17856
+ var MAX_CONTEXT_LINES = 10;
17857
+ var MIN_MAX_DIAGNOSTICS = 1;
17858
+ var MAX_MAX_DIAGNOSTICS = 100;
17859
+ var TSCONFIG_NAMES = ["tsconfig.json", "jsconfig.json"];
17860
+ var OUTCOME_SCHEMA2 = {
17861
+ type: "object",
17862
+ properties: {
17863
+ text: { type: "string", required: true }
17864
+ },
17865
+ additionalProperties: false
17866
+ };
17867
+ var SOURCE_NOTE2 = "Every diagnostic's file is served as `HASH\u2502content` rows around the reported line, so the following `apply_patch` or `edit` needs no separate `read`.";
17868
+ var DESCRIPTION = [
17869
+ "Run a compiler or linter over a project and return its errors and warnings as anchored, editable rows.",
17870
+ "Supported `tool` values: `cargo-check`, `cargo-clippy` (the Rust `cargo` CLI) and `tsc` (the project's `node_modules/typescript`, else a `tsc` on PATH). " + SOURCE_NOTE2 + " The `\u2014 path:line:col` header above each block names the line its diagnostic points at, and the rows themselves stay byte-identical to a `read` page.",
17871
+ "Expected states \u2014 no toolchain, no tsconfig, a timeout, output that carries no parseable diagnostic \u2014 come back as text guidance, not as an error."
17872
+ ].join("\n\n");
17873
+ var PARAMETERS = {
17874
+ tool: {
17875
+ type: "string",
17876
+ required: true,
17877
+ enum: [...DIAGNOSTICS_TOOL_NAMES],
17878
+ description: "Toolchain to run: `cargo-check` (`cargo check`), `cargo-clippy` (`cargo clippy`) or `tsc` (`--noEmit`)."
17879
+ },
17880
+ cwd: {
17881
+ type: "string",
17882
+ description: "Project directory the toolchain runs in. Defaults to the session working directory; the cargo workspace root or the directory holding tsconfig.json is the right choice."
17883
+ },
17884
+ contextLines: {
17885
+ type: "number",
17886
+ description: "Served lines above and below each diagnostic's own line, 1-10 (default 2). Out-of-range values are clamped, not refused."
17887
+ },
17888
+ maxDiagnostics: {
17889
+ type: "number",
17890
+ description: "Maximum diagnostics to serve, 1-100 (default 20). Out-of-range values are clamped, not refused; the header still counts everything the toolchain reported."
17891
+ }
17892
+ };
17893
+ function stringArg2(args, key) {
17894
+ const value = args[key];
17895
+ return typeof value === "string" && value.trim() !== "" ? value : void 0;
17896
+ }
17897
+ function clampedArg(value, min, max, fallback) {
17898
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
17899
+ return Math.min(max, Math.max(min, Math.round(value)));
17900
+ }
17901
+ function defaultResolve(tool, cwd) {
17902
+ return tool === "tsc" ? resolveTscInvocation(cwd) : resolveCargoInvocation();
17903
+ }
17904
+ async function hasProjectConfig(deps, cwd, signal) {
17905
+ let directory = cwd;
17906
+ for (; ; ) {
17907
+ for (const name2 of TSCONFIG_NAMES) {
17908
+ const info = await deps.io.stat(join13(directory, name2), signal).catch(() => void 0);
17909
+ if (info?.isFile === true) return true;
17910
+ }
17911
+ const parent = dirname14(directory);
17912
+ if (parent === directory) return false;
17913
+ directory = parent;
17914
+ }
17915
+ }
17916
+ function countsOf(parsed) {
17917
+ let errors = 0;
17918
+ let warnings = 0;
17919
+ for (const diagnostic of parsed) {
17920
+ if (diagnostic.level === "error") errors += 1;
17921
+ else if (diagnostic.level === "warning") warnings += 1;
17922
+ }
17923
+ return { total: parsed.length, errors, warnings };
17924
+ }
17925
+ function composeText(tool, cwd, parsed, selected, blocks, skipped) {
17926
+ const sections = [summaryLine(tool, cwd, countsOf(parsed))];
17927
+ sections.push(...blocks);
17928
+ if (selected < parsed.length) sections.push(showingNote(parsed.length, selected));
17929
+ if (skipped > 0) sections.push(skippedNote(skipped));
17930
+ return sections.join("\n\n");
17931
+ }
17932
+ async function executeDiagnostics(deps, options, exec, rawArgs) {
17933
+ const args = typeof rawArgs === "object" && rawArgs !== null ? rawArgs : {};
17934
+ const ctx = resolveToolContext(exec);
17935
+ const tool = args.tool;
17936
+ if (!isDiagnosticsTool(tool)) {
17937
+ return `diagnostics needs \`tool\`: one of ${DIAGNOSTICS_TOOL_NAMES.map((name2) => `\`${name2}\``).join(", ")}.`;
17938
+ }
17939
+ const cwd = toCwd(stringArg2(args, "cwd") ?? ".", ctx.cwd);
17940
+ const directory = await deps.io.stat(cwd, ctx.signal).catch(() => void 0);
17941
+ if (directory?.isDirectory !== true) return unusableCwdText(cwd);
17942
+ const contextLines = clampedArg(
17943
+ args.contextLines,
17944
+ MIN_CONTEXT_LINES,
17945
+ MAX_CONTEXT_LINES,
17946
+ DEFAULT_CONTEXT_LINES
17947
+ );
17948
+ const maxDiagnostics = clampedArg(
17949
+ args.maxDiagnostics,
17950
+ MIN_MAX_DIAGNOSTICS,
17951
+ MAX_MAX_DIAGNOSTICS,
17952
+ DEFAULT_MAX_DIAGNOSTICS
17953
+ );
17954
+ const locate = options.resolve ?? defaultResolve;
17955
+ const resolution = locate(tool, cwd);
17956
+ if (!resolution.ok) return missingToolchainText(tool, resolution.problem);
17957
+ if (tool === "tsc" && !await hasProjectConfig(deps, cwd, ctx.signal)) {
17958
+ return missingTsconfigText(cwd);
17959
+ }
17960
+ const timeoutMs = options.timeoutMs ?? DIAGNOSTICS_TIMEOUT_MS;
17961
+ let result;
17962
+ try {
17963
+ result = await runDiagnosticsCommand(resolution.invocation, planDiagnosticsArgs(tool), {
17964
+ cwd,
17965
+ signal: ctx.signal,
17966
+ timeoutMs
17967
+ });
17968
+ } catch (error) {
17969
+ ctx.signal?.throwIfAborted();
17970
+ return launchFailureText2(tool, error);
17971
+ }
17972
+ if (result.timedOut) return timeoutText2(tool, timeoutMs);
17973
+ const parsed = parseDiagnostics(tool, result.stdout);
17974
+ if (parsed.length === 0) {
17975
+ const quiet = `${result.stdout}${result.stderr}`.trim() === "" && result.code === 0;
17976
+ return quiet ? cleanText(tool, cwd) : rawOutputText(tool, result);
17977
+ }
17978
+ const selected = parsed.slice(0, maxDiagnostics);
17979
+ const view = await anchorDiagnosticsView(deps, {
17980
+ diagnostics: selected,
17981
+ cwd,
17982
+ contextLines,
17983
+ sessionKey: ctx.sessionKey,
17984
+ signal: ctx.signal,
17985
+ exec
17986
+ });
17987
+ return composeText(tool, cwd, parsed, selected.length, view.blocks, view.skipped);
17988
+ }
17989
+ function buildDiagnosticsTool(deps, options) {
17990
+ return defineTool5({
17991
+ name: DIAGNOSTICS_TOOL_NAME,
17992
+ description: DESCRIPTION,
17993
+ parameters: PARAMETERS,
17994
+ output: {
17995
+ schema: OUTCOME_SCHEMA2,
17996
+ render: (_args, value) => [{ type: "text", text: value.text }]
17997
+ },
17998
+ async execute(args, exec) {
17999
+ return { text: await executeDiagnostics(deps, options, exec, args) };
18000
+ }
18001
+ });
18002
+ }
18003
+ function buildDiagnosticsTools(deps, options = {}) {
18004
+ return [buildDiagnosticsTool(deps, options)];
18005
+ }
18006
+
15808
18007
  // dsh/write-hook.ts
15809
18008
  var AUTO_READ_HEADING = "--- Auto-read (hashline anchors) ---";
15810
18009
  function errorMessage3(error) {
@@ -15994,7 +18193,10 @@ var inject = ["agents", "tools", "systemPrompt"];
15994
18193
  var Config = Schema.object({
15995
18194
  read: Schema.boolean().default(true).volatile(),
15996
18195
  applyPatch: Schema.boolean().default(true).volatile(),
15997
- edit: Schema.boolean().default(false).volatile()
18196
+ edit: Schema.boolean().default(false).volatile(),
18197
+ codegraph: Schema.boolean().default(false).volatile(),
18198
+ codegraphPath: Schema.string().default("").volatile(),
18199
+ diagnostics: Schema.boolean().default(false).volatile()
15998
18200
  });
15999
18201
  function switchValue(value, fallback) {
16000
18202
  if (typeof value === "boolean") return value;
@@ -16008,12 +18210,27 @@ function switchValue(value, fallback) {
16008
18210
  }
16009
18211
  return fallback;
16010
18212
  }
18213
+ function stringValue(value, fallback) {
18214
+ if (typeof value === "string") return value;
18215
+ if (value !== null && typeof value === "object" && typeof value.get === "function") {
18216
+ try {
18217
+ const inner = value.get();
18218
+ return typeof inner === "string" ? inner : fallback;
18219
+ } catch {
18220
+ return fallback;
18221
+ }
18222
+ }
18223
+ return fallback;
18224
+ }
16011
18225
  function resolveSwitches(config = {}) {
16012
18226
  const fields = config;
16013
18227
  return {
16014
18228
  read: switchValue(fields.read, true),
16015
18229
  applyPatch: switchValue(fields.applyPatch, true),
16016
- edit: switchValue(fields.edit, false)
18230
+ edit: switchValue(fields.edit, false),
18231
+ codegraph: switchValue(fields.codegraph, false),
18232
+ codegraphPath: stringValue(fields.codegraphPath, ""),
18233
+ diagnostics: switchValue(fields.diagnostics, false)
16017
18234
  };
16018
18235
  }
16019
18236
  function toolsOfAgent(agent) {
@@ -16070,6 +18287,21 @@ function installAgentTools(rootCtx, agent, metrics, config = {}) {
16070
18287
  disposers.push(edit.dispose);
16071
18288
  }
16072
18289
  }
18290
+ if (switches.codegraph) {
18291
+ const codegraph = {
18292
+ resolution: resolveCodegraphInvocation({ explicitPath: switches.codegraphPath })
18293
+ };
18294
+ for (const definition of buildCodegraphTools(deps, codegraph)) {
18295
+ const dispose = registerToolQuietly(rootCtx, agent, definition, "codegraph");
18296
+ if (dispose !== void 0) disposers.push(dispose);
18297
+ }
18298
+ }
18299
+ if (switches.diagnostics) {
18300
+ for (const definition of buildDiagnosticsTools(deps)) {
18301
+ const dispose = registerToolQuietly(rootCtx, agent, definition, "diagnostics");
18302
+ if (dispose !== void 0) disposers.push(dispose);
18303
+ }
18304
+ }
16073
18305
  if (registered.length > 0) {
16074
18306
  disposers.push(
16075
18307
  registerNativeToolHiding(rootCtx, agent.ctx, {
@@ -16113,6 +18345,19 @@ function registerMutationTool(rootCtx, agent, deps, build) {
16113
18345
  return null;
16114
18346
  }
16115
18347
  }
18348
+ function registerToolQuietly(rootCtx, agent, definition, lane) {
18349
+ try {
18350
+ const agentTools = toolsOfAgent(agent);
18351
+ if (agentTools === void 0) throw new Error("agent tools registry is unavailable");
18352
+ return agentTools.register(definition);
18353
+ } catch (error) {
18354
+ warnVia3(
18355
+ rootCtx,
18356
+ `${lane} tool registration failed for agent ${agent.id} (${definition.name}): ${error instanceof Error ? error.message : String(error)}; that tool stays off for this agent`
18357
+ );
18358
+ return void 0;
18359
+ }
18360
+ }
16116
18361
  function disposeReverse(disposers) {
16117
18362
  while (disposers.length > 0) {
16118
18363
  const dispose = disposers.pop();
@@ -16172,6 +18417,31 @@ function apply2(rootCtx, config = {}) {
16172
18417
  if (switches.edit) {
16173
18418
  disposers.push(rootCtx.tools.register(buildEditTool(rootDeps)));
16174
18419
  }
18420
+ if (switches.codegraph) {
18421
+ const codegraph = {
18422
+ resolution: resolveCodegraphInvocation({ explicitPath: switches.codegraphPath })
18423
+ };
18424
+ for (const definition of buildCodegraphTools(rootDeps, codegraph)) {
18425
+ try {
18426
+ disposers.push(rootCtx.tools.register(definition));
18427
+ } catch (error) {
18428
+ rootCtx.logger.warn(
18429
+ `dsh-hashline-edit: root codegraph tool registration failed for ${definition.name}: ${error instanceof Error ? error.message : String(error)}`
18430
+ );
18431
+ }
18432
+ }
18433
+ }
18434
+ if (switches.diagnostics) {
18435
+ for (const definition of buildDiagnosticsTools(rootDeps)) {
18436
+ try {
18437
+ disposers.push(rootCtx.tools.register(definition));
18438
+ } catch (error) {
18439
+ rootCtx.logger.warn(
18440
+ `dsh-hashline-edit: root diagnostics tool registration failed for ${definition.name}: ${error instanceof Error ? error.message : String(error)}`
18441
+ );
18442
+ }
18443
+ }
18444
+ }
16175
18445
  } catch (error) {
16176
18446
  disposeReverse(disposers);
16177
18447
  rootCtx.logger.warn(