dsh-hashline-edit 0.5.0 → 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 (47) hide show
  1. package/CHANGELOG.md +345 -0
  2. package/README.md +56 -3
  3. package/cordis.patch.yml +11 -1
  4. package/lib/client.js +13 -3
  5. package/lib/index.js +2108 -59
  6. package/lib/types/dsh/codegraph/cli.d.ts +61 -0
  7. package/lib/types/dsh/codegraph/project.d.ts +27 -0
  8. package/lib/types/dsh/codegraph/tools.d.ts +36 -0
  9. package/lib/types/dsh/codegraph/view.d.ts +25 -0
  10. package/lib/types/dsh/diagnostics/cli.d.ts +76 -0
  11. package/lib/types/dsh/diagnostics/messages.d.ts +37 -0
  12. package/lib/types/dsh/diagnostics/parse.d.ts +39 -0
  13. package/lib/types/dsh/diagnostics/tools.d.ts +20 -0
  14. package/lib/types/dsh/diagnostics/view.d.ts +31 -0
  15. package/lib/types/dsh/guidance.d.ts +7 -3
  16. package/lib/types/dsh/index.d.ts +32 -3
  17. package/lib/types/dsh/tools/edit.d.ts +15 -1
  18. package/lib/types/dsh/tools/read-folded.d.ts +85 -0
  19. package/lib/types/src/domain-errors.d.ts +12 -1
  20. package/lib/types/src/edit-tool.d.ts +9 -1
  21. package/lib/types/src/mutation-engine/edit-expand.d.ts +36 -0
  22. package/lib/types/src/mutation-engine/edit-indent.d.ts +49 -0
  23. package/lib/types/src/mutation-engine/edit-request.d.ts +4 -0
  24. package/lib/types/src/mutation-engine/types.d.ts +57 -0
  25. package/lib/types/src/payload-contract.d.ts +4 -0
  26. package/lib/types/src/read-expansion/fold-skeleton.d.ts +32 -0
  27. package/lib/types/src/read-expansion/span-expansion.d.ts +26 -0
  28. package/package.json +19 -22
  29. package/prompts/codegraph-guidelines.md +8 -0
  30. package/prompts/diagnostics-guidelines.md +8 -0
  31. package/prompts/edit-guidelines.md +3 -1
  32. package/prompts/edit.md +3 -1
  33. package/prompts/read-description.md +1 -1
  34. package/prompts/read-guidelines.md +3 -1
  35. package/src/domain-errors.ts +52 -1
  36. package/src/edit-tool.ts +12 -1
  37. package/src/mutation-engine/edit-expand.ts +328 -0
  38. package/src/mutation-engine/edit-indent.ts +121 -0
  39. package/src/mutation-engine/edit-request.ts +4 -0
  40. package/src/mutation-engine/pipeline.ts +134 -48
  41. package/src/mutation-engine/types.ts +54 -0
  42. package/src/payload-contract.ts +74 -4
  43. package/src/read-expansion/ast-provider.ts +32 -0
  44. package/src/read-expansion/fold-skeleton.ts +56 -0
  45. package/src/read-expansion/qualified-names.ts +7 -0
  46. package/src/read-expansion/read-provider.ts +9 -0
  47. 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,6 +8405,24 @@ 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
8428
  import { existsSync as existsSync3, mkdirSync as mkdirSync5, readFileSync as readFileSync3, renameSync as renameSync4, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
@@ -8993,6 +9040,35 @@ function createAstSpanProvider(options = {}) {
8993
9040
  return runtimeAbsent;
8994
9041
  },
8995
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
+ },
8996
9072
  async enclosingSpan(file, window) {
8997
9073
  if (!isOffsetWindow(window)) return decline("provider_declined");
8998
9074
  const language = grammarLanguageForFile(file);
@@ -9404,6 +9480,12 @@ function withQualifiedNames(provider, resolver, timeoutMs = DEFAULT_QUALIFIED_NA
9404
9480
  } catch {
9405
9481
  }
9406
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);
9407
9489
  }
9408
9490
  };
9409
9491
  }
@@ -9433,6 +9515,13 @@ function createReadSpanProvider(options = {}) {
9433
9515
  if (isPlainTextPath(file)) return paragraph.enclosingSpan(file, window);
9434
9516
  if (isShellPath(file)) return bash.enclosingSpan(file, window);
9435
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);
9436
9525
  }
9437
9526
  };
9438
9527
  return withQualifiedNames(
@@ -9999,10 +10088,127 @@ async function publishPluginWrites(deps, requestPaths, ctx, exec) {
9999
10088
  }
10000
10089
  }
10001
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
+
10002
10208
  // dsh/tools/read.ts
10003
10209
  var READ_TOOL_NAME = "read";
10004
10210
  var READ_DESCRIPTION = loadP("../prompts/read-description.md");
10005
- var RENDER_MODES = ["served", "verbatim"];
10211
+ var READ_MODES = ["served", "verbatim", "folded"];
10006
10212
  function createDefaultReadSpanProvider(io) {
10007
10213
  const readTextFile = io === void 0 ? void 0 : async (path) => {
10008
10214
  try {
@@ -10304,7 +10510,8 @@ async function serveFileLines(deps, request) {
10304
10510
  async function readAndServe(deps, rawArgs, exec, spanProvider) {
10305
10511
  const ctx = resolveToolContext(exec);
10306
10512
  const raw = rawArgs;
10307
- const request = admitReadRequest(raw);
10513
+ const folded = admitFoldedRequest(raw);
10514
+ const request = folded === void 0 ? admitReadRequest(raw) : folded.request;
10308
10515
  const mode = request.mode;
10309
10516
  const absolutePath = toCwd(request.file, ctx.cwd);
10310
10517
  ctx.signal?.throwIfAborted();
@@ -10330,6 +10537,18 @@ async function readAndServe(deps, rawArgs, exec, spanProvider) {
10330
10537
  })();
10331
10538
  return resolvedText;
10332
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
+ }
10333
10552
  const wantsAnchor = request.windows?.some((window) => window.kind === "anchor") === true;
10334
10553
  const store = mode === "served" || wantsAnchor ? await loadHashStore() : void 0;
10335
10554
  const anchorText = wantsAnchor ? await normalized() : void 0;
@@ -10388,6 +10607,49 @@ async function readAndServe(deps, rawArgs, exec, spanProvider) {
10388
10607
  ...presentation === void 0 ? {} : { presentation }
10389
10608
  };
10390
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
+ }
10391
10653
  var MAX_PRESENTATION_LINES = 400;
10392
10654
  var MAX_PRESENTATION_LINE_CHARS = 2048;
10393
10655
  function capPresentationLine(text) {
@@ -10498,8 +10760,12 @@ function buildReadTool(deps, options = {}) {
10498
10760
  },
10499
10761
  mode: {
10500
10762
  type: "string",
10501
- enum: RENDER_MODES,
10502
- 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`."
10503
10769
  }
10504
10770
  },
10505
10771
  output: {
@@ -13187,6 +13453,251 @@ async function repairCutIntents(store) {
13187
13453
  }
13188
13454
  }
13189
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
+
13190
13701
  // src/mutation-engine/pipeline.ts
13191
13702
  function collectRemovedHashes(edit, originalHashes) {
13192
13703
  const removedHashes = /* @__PURE__ */ new Set();
@@ -13223,6 +13734,31 @@ function countLineChanges(edit, originalHashes, isNoop) {
13223
13734
  totalRemovedLines
13224
13735
  };
13225
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
+ }
13226
13762
  async function applyOneEdit(input) {
13227
13763
  abortIf(input.signal);
13228
13764
  const identity = leaseSpanSource({
@@ -13232,9 +13768,12 @@ async function applyOneEdit(input) {
13232
13768
  content: input.content,
13233
13769
  ...input.currentIds !== void 0 ? { currentIds: input.currentIds } : {}
13234
13770
  });
13771
+ let indent;
13235
13772
  let anchorResult;
13236
13773
  try {
13237
- 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, {
13238
13777
  // WHY: read/write agreement — the verify path is literally the same
13239
13778
  // WHY: canonical absolute path the `hashesFor` call below uses (one field).
13240
13779
  filePath: input.absolutePath,
@@ -13270,7 +13809,8 @@ async function applyOneEdit(input) {
13270
13809
  noopEdit: anchorResult.noopEdit,
13271
13810
  anchorWarnings,
13272
13811
  literalBypass,
13273
- neverServedCount
13812
+ neverServedCount,
13813
+ ...indent !== void 0 ? { indent } : {}
13274
13814
  };
13275
13815
  }
13276
13816
  if (!input.hashes || input.hashes.length === 0)
@@ -13305,7 +13845,8 @@ async function applyOneEdit(input) {
13305
13845
  neverServedCount,
13306
13846
  sourceRange: anchorResult.sourceRange,
13307
13847
  mutationSpans: anchorResult.mutationSpans,
13308
- mutationStats: anchorResult.mutationStats
13848
+ mutationStats: anchorResult.mutationStats,
13849
+ ...indent !== void 0 ? { indent } : {}
13309
13850
  };
13310
13851
  }
13311
13852
  async function recordRejectionServe(args) {
@@ -13602,7 +14143,8 @@ async function runMutations(request, cwd, options, itemNumbers) {
13602
14143
  fileHashes: originalHashes,
13603
14144
  hadUtf8DecodeErrors,
13604
14145
  absolutePath,
13605
- served
14146
+ served,
14147
+ canonDigests
13606
14148
  } = await loadEditFile({
13607
14149
  path,
13608
14150
  cwd,
@@ -13691,28 +14233,73 @@ async function runMutations(request, cwd, options, itemNumbers) {
13691
14233
  continue;
13692
14234
  }
13693
14235
  const edit = parsedItem.edit;
13694
- const outcome = await applyOneEdit({
13695
- content: currentContent,
13696
- hashes: currentHashes,
13697
- edit,
13698
- ...options?.signal !== void 0 ? { signal: options.signal } : {},
13699
- served,
13700
- blockedHashes: batchBlockedHashes,
13701
- canonDigests: baseCanonDigests,
13702
- sessionKey,
13703
- absolutePath,
13704
- store: hashStore,
13705
- isPreview,
13706
- mode,
13707
- // WHY: the intermediate buffer is in-memory only, so its identities come from the buffer map
13708
- // WHY: (`null` lines are the batch's own creations) — a re-diff of it against S_latest cannot
13709
- // WHY: tell which of two byte-identical lines carries a leased line_id.
13710
- ...isPreview ? {} : { currentIds },
13711
- 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
+ });
13712
14272
  if (items.length === 1) throw error;
13713
14273
  throw batchAbortFor({ error, index: number, path });
13714
14274
  }
13715
- });
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
+ }
13716
14303
  const range = outcome.range;
13717
14304
  const coveredRanges = outcome.kind === "applied" && outcome.sourceRange ? [range, outcome.sourceRange] : [range];
13718
14305
  editedIntervals.push(...coveredRanges);
@@ -15150,8 +15737,8 @@ function isRec(value) {
15150
15737
  function isNormalizedEdit(input) {
15151
15738
  return isRec(input) && input[normalizedEdit] === true;
15152
15739
  }
15153
- var ITEM_SHAPE = "an item is exactly { anchor_from, anchor_to?, text[, at] }, { anchor_from, anchor_to?, text_ref[, at] }, or { anchor_from, anchor_to?, after | before }";
15154
- var EDIT_PAYLOAD_HINT = `Edit must be called with exactly one payload per item, and each call edits ONE file. Use the canonical payload {"file": file, "edits": [{ "anchor_from": anchor_from, "anchor_to": anchor_to, "text": text }, ...], "mode"?: "general" | "literal"}: "file" is the text file to edit (a non-empty string, never a directory); each item names the bare-${HASH_LEN}-char anchor "anchor_from" (the first line of the range, and the whole range of a single-line edit), an optional second bare anchor "anchor_to" (the last line of a multi-line range; omit it to edit "anchor_from" alone) and exactly one payload \u2014 "text" (bare replacement content; an empty string deletes the range), "text_ref" ({ anchor_from, anchor_to, file?, mode (required): "copy" | "cut" } \u2014 the served span's bytes, whose two bounds are always required, and whose "file" may name another served file as the copy/cut source), or an insertion slot "after"/"before" (the exact lines to insert below/above the single anchor line, which is never restated); optional "at" is "in-place" (default), "before" or "after" (single-line resolved target only); optional "mode" is "general" (default, reproduced served rows are refused) or "literal" (declared literal content).`;
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).`;
15155
15742
  function describeReceived(input) {
15156
15743
  if (input === void 0) return "Received no arguments.";
15157
15744
  if (input === null) return "Received null.";
@@ -15226,7 +15813,16 @@ function isAbsentValue(value) {
15226
15813
  }
15227
15814
  function foldAbsentSlots(item) {
15228
15815
  const folded = { ...item };
15229
- for (const key of ["text", "text_ref", "at", "anchor_to", "after", "before"]) {
15816
+ for (const key of [
15817
+ "text",
15818
+ "text_ref",
15819
+ "at",
15820
+ "anchor_to",
15821
+ "after",
15822
+ "before",
15823
+ "indent",
15824
+ "expand"
15825
+ ]) {
15230
15826
  if (isAbsentValue(folded[key])) delete folded[key];
15231
15827
  }
15232
15828
  if (isRec(folded.text_ref)) {
@@ -15240,7 +15836,8 @@ function analyzeItem(value, index) {
15240
15836
  if (!isRec(value)) {
15241
15837
  return `edit[${index}] must be an object: ${ITEM_SHAPE}.`;
15242
15838
  }
15243
- 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)));
15244
15841
  const hasText = keys.has("text");
15245
15842
  const hasRef = keys.has("text_ref");
15246
15843
  const hasAfter = keys.has("after");
@@ -15295,6 +15892,28 @@ function analyzeItem(value, index) {
15295
15892
  return `edit[${index}] "at" must be "in-place", "before" or "after" when present.`;
15296
15893
  }
15297
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
+ }
15298
15917
  if (hasInsert) {
15299
15918
  if (hasAfter && hasBefore) {
15300
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.`;
@@ -15402,6 +16021,11 @@ function analyzeRequest(input) {
15402
16021
  }
15403
16022
  edited.push(item);
15404
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
+ }
15405
16029
  if (failures.length > 0) {
15406
16030
  return { ok: false, message: `${failures.join(" ")} ${describeReceived(input)}` };
15407
16031
  }
@@ -15418,7 +16042,9 @@ function normalizedItemFrom(item) {
15418
16042
  return {
15419
16043
  target,
15420
16044
  at,
15421
- payload
16045
+ payload,
16046
+ ...item.indent === "auto" ? { indent: item.indent } : {},
16047
+ ...item.expand === "item" ? { expand: item.expand } : {}
15422
16048
  };
15423
16049
  }
15424
16050
  function normReq(input) {
@@ -15446,6 +16072,8 @@ function isPlacementValue(value) {
15446
16072
  }
15447
16073
  function isNormalizedEditItem(value) {
15448
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;
15449
16077
  const { target, at, payload } = value;
15450
16078
  if (!isRec(target)) return false;
15451
16079
  if (typeof target.anchor_from !== "string" || typeof target.anchor_to !== "string") return false;
@@ -15608,7 +16236,7 @@ function isMutationSuccess(r) {
15608
16236
  }
15609
16237
 
15610
16238
  // src/edit-tool.ts
15611
- function createEditTool() {
16239
+ function createEditTool(options = {}) {
15612
16240
  return {
15613
16241
  async execute(params, signal, ctx) {
15614
16242
  const canonical = normReq(params);
@@ -15620,7 +16248,8 @@ function createEditTool() {
15620
16248
  accessMode: constants7.R_OK | constants7.W_OK,
15621
16249
  // SAFETY: signal is AbortSignal | undefined at pi boundary — runtime check via engine's abortIf
15622
16250
  ...signal !== void 0 ? { signal } : {},
15623
- sessionKey
16251
+ sessionKey,
16252
+ ...options.spanProvider !== void 0 ? { spanProvider: options.spanProvider } : {}
15624
16253
  });
15625
16254
  if (isMutationSuccess(result)) {
15626
16255
  return result.toolResult;
@@ -15643,7 +16272,8 @@ function createEditTool() {
15643
16272
  assertReq(normalized);
15644
16273
  const result = await preview(normalized, cwd, {
15645
16274
  accessMode: constants7.R_OK,
15646
- sessionKey: sessionKeyFor(ctx)
16275
+ sessionKey: sessionKeyFor(ctx),
16276
+ ...options.spanProvider !== void 0 ? { spanProvider: options.spanProvider } : {}
15647
16277
  });
15648
16278
  if (!isMutationSuccess(result)) {
15649
16279
  return { error: result.message };
@@ -15870,6 +16500,26 @@ var EDIT_PARAMETERS = {
15870
16500
  },
15871
16501
  { type: "null" }
15872
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
+ ]
15873
16523
  }
15874
16524
  }
15875
16525
  }
@@ -15903,8 +16553,10 @@ function writtenMemberFiles(admitted) {
15903
16553
  return files;
15904
16554
  }
15905
16555
  var EDIT_TOOL_DESCRIPTION = loadP("../prompts/edit.md");
15906
- function buildEditTool(deps) {
15907
- const tool = createEditTool();
16556
+ function buildEditTool(deps, options = {}) {
16557
+ const tool = createEditTool(
16558
+ options.spanProvider === void 0 ? {} : { spanProvider: options.spanProvider }
16559
+ );
15908
16560
  const sandboxFields = deps.sandbox.escalationModes.length > 0 ? deps.sandbox.schemaFields() : {};
15909
16561
  return defineTool3({
15910
16562
  name: EDIT_TOOL_NAME,
@@ -16026,26 +16678,1352 @@ function admit2(args) {
16026
16678
  }
16027
16679
  }
16028
16680
 
16029
- // dsh/write-hook.ts
16030
- var AUTO_READ_HEADING = "--- Auto-read (hashline anchors) ---";
16031
- function errorMessage3(error) {
16032
- return error instanceof Error ? error.message : String(error);
16033
- }
16034
- function writeRequest(exec) {
16035
- const args = exec.arguments;
16036
- const rawPath = args?.file_path ?? args?.path;
16037
- const content = args?.content;
16038
- if (typeof rawPath !== "string" || typeof content !== "string") return void 0;
16039
- return { rawPath, content };
16040
- }
16041
- function execContext2(exec) {
16042
- const agent = exec.agent;
16043
- const session = agent?.session;
16044
- const get = agent?.ctx?.get;
16045
- const workingDirectory = typeof get === "function" && agent?.ctx !== void 0 ? get.call(agent.ctx, "workingDirectory") : void 0;
16046
- const cwd = session !== void 0 && workingDirectory !== void 0 && typeof workingDirectory.get === "function" ? workingDirectory.get(session) : session?.header?.cwd ?? process.cwd();
16047
- const sessionKey = session?.id !== void 0 && session.id.length > 0 ? session.id : void 0;
16048
- return { cwd, sessionKey };
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
+
18007
+ // dsh/write-hook.ts
18008
+ var AUTO_READ_HEADING = "--- Auto-read (hashline anchors) ---";
18009
+ function errorMessage3(error) {
18010
+ return error instanceof Error ? error.message : String(error);
18011
+ }
18012
+ function writeRequest(exec) {
18013
+ const args = exec.arguments;
18014
+ const rawPath = args?.file_path ?? args?.path;
18015
+ const content = args?.content;
18016
+ if (typeof rawPath !== "string" || typeof content !== "string") return void 0;
18017
+ return { rawPath, content };
18018
+ }
18019
+ function execContext2(exec) {
18020
+ const agent = exec.agent;
18021
+ const session = agent?.session;
18022
+ const get = agent?.ctx?.get;
18023
+ const workingDirectory = typeof get === "function" && agent?.ctx !== void 0 ? get.call(agent.ctx, "workingDirectory") : void 0;
18024
+ const cwd = session !== void 0 && workingDirectory !== void 0 && typeof workingDirectory.get === "function" ? workingDirectory.get(session) : session?.header?.cwd ?? process.cwd();
18025
+ const sessionKey = session?.id !== void 0 && session.id.length > 0 ? session.id : void 0;
18026
+ return { cwd, sessionKey };
16049
18027
  }
16050
18028
  async function servedHashEchoReason(deps, rawPath, content, cwd, sessionKey, signal) {
16051
18029
  signal?.throwIfAborted();
@@ -16215,7 +18193,10 @@ var inject = ["agents", "tools", "systemPrompt"];
16215
18193
  var Config = Schema.object({
16216
18194
  read: Schema.boolean().default(true).volatile(),
16217
18195
  applyPatch: Schema.boolean().default(true).volatile(),
16218
- 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()
16219
18200
  });
16220
18201
  function switchValue(value, fallback) {
16221
18202
  if (typeof value === "boolean") return value;
@@ -16229,12 +18210,27 @@ function switchValue(value, fallback) {
16229
18210
  }
16230
18211
  return fallback;
16231
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
+ }
16232
18225
  function resolveSwitches(config = {}) {
16233
18226
  const fields = config;
16234
18227
  return {
16235
18228
  read: switchValue(fields.read, true),
16236
18229
  applyPatch: switchValue(fields.applyPatch, true),
16237
- 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)
16238
18234
  };
16239
18235
  }
16240
18236
  function toolsOfAgent(agent) {
@@ -16291,6 +18287,21 @@ function installAgentTools(rootCtx, agent, metrics, config = {}) {
16291
18287
  disposers.push(edit.dispose);
16292
18288
  }
16293
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
+ }
16294
18305
  if (registered.length > 0) {
16295
18306
  disposers.push(
16296
18307
  registerNativeToolHiding(rootCtx, agent.ctx, {
@@ -16334,6 +18345,19 @@ function registerMutationTool(rootCtx, agent, deps, build) {
16334
18345
  return null;
16335
18346
  }
16336
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
+ }
16337
18361
  function disposeReverse(disposers) {
16338
18362
  while (disposers.length > 0) {
16339
18363
  const dispose = disposers.pop();
@@ -16393,6 +18417,31 @@ function apply2(rootCtx, config = {}) {
16393
18417
  if (switches.edit) {
16394
18418
  disposers.push(rootCtx.tools.register(buildEditTool(rootDeps)));
16395
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
+ }
16396
18445
  } catch (error) {
16397
18446
  disposeReverse(disposers);
16398
18447
  rootCtx.logger.warn(