dsh-hashline-edit 0.4.3 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/CHANGELOG.md +345 -0
  2. package/README.md +58 -5
  3. package/cordis.patch.yml +11 -1
  4. package/grammars/go-0.25.0-9504573f352b20be.wasm +0 -0
  5. package/grammars/java-0.23.5-4fdeac4ca6ca089f.wasm +0 -0
  6. package/grammars/python-0.25.0-16108b50df4ee9a3.wasm +0 -0
  7. package/grammars/rust-0.24.2-24c89bd9252255e4.wasm +0 -0
  8. package/grammars/tsx-0.23.2-79e5da75ea62855a.wasm +0 -0
  9. package/grammars/typescript-0.23.2-778025db5a8be0e7.wasm +0 -0
  10. package/grammars/vue-0.1.0-193c01119229352f.wasm +0 -0
  11. package/lib/client.js +13 -3
  12. package/lib/index.js +2345 -75
  13. package/lib/types/dsh/codegraph/cli.d.ts +61 -0
  14. package/lib/types/dsh/codegraph/project.d.ts +27 -0
  15. package/lib/types/dsh/codegraph/tools.d.ts +36 -0
  16. package/lib/types/dsh/codegraph/view.d.ts +25 -0
  17. package/lib/types/dsh/diagnostics/cli.d.ts +76 -0
  18. package/lib/types/dsh/diagnostics/messages.d.ts +37 -0
  19. package/lib/types/dsh/diagnostics/parse.d.ts +39 -0
  20. package/lib/types/dsh/diagnostics/tools.d.ts +20 -0
  21. package/lib/types/dsh/diagnostics/view.d.ts +31 -0
  22. package/lib/types/dsh/guidance.d.ts +7 -3
  23. package/lib/types/dsh/index.d.ts +32 -3
  24. package/lib/types/dsh/syntax-health.d.ts +60 -0
  25. package/lib/types/dsh/tools/edit.d.ts +15 -1
  26. package/lib/types/dsh/tools/output.d.ts +10 -0
  27. package/lib/types/dsh/tools/read-folded.d.ts +85 -0
  28. package/lib/types/src/bundled-assets.d.ts +13 -0
  29. package/lib/types/src/domain-errors.d.ts +12 -1
  30. package/lib/types/src/edit-tool.d.ts +9 -1
  31. package/lib/types/src/mutation-engine/edit-expand.d.ts +36 -0
  32. package/lib/types/src/mutation-engine/edit-indent.d.ts +49 -0
  33. package/lib/types/src/mutation-engine/edit-request.d.ts +8 -0
  34. package/lib/types/src/mutation-engine/types.d.ts +57 -0
  35. package/lib/types/src/payload-contract.d.ts +8 -0
  36. package/lib/types/src/read-expansion/fold-skeleton.d.ts +32 -0
  37. package/lib/types/src/read-expansion/grammar-manifest.d.ts +3 -1
  38. package/lib/types/src/read-expansion/grammar-runtime.d.ts +1 -1
  39. package/lib/types/src/read-expansion/span-expansion.d.ts +26 -0
  40. package/package.json +21 -23
  41. package/prompts/codegraph-guidelines.md +8 -0
  42. package/prompts/diagnostics-guidelines.md +8 -0
  43. package/prompts/edit-guidelines.md +6 -2
  44. package/prompts/edit.md +3 -1
  45. package/prompts/read-description.md +1 -1
  46. package/prompts/read-guidelines.md +3 -1
  47. package/src/bundled-assets.ts +23 -0
  48. package/src/domain-errors.ts +52 -1
  49. package/src/edit-tool.ts +12 -1
  50. package/src/mutation-engine/edit-expand.ts +328 -0
  51. package/src/mutation-engine/edit-indent.ts +121 -0
  52. package/src/mutation-engine/edit-request.ts +8 -1
  53. package/src/mutation-engine/pipeline.ts +150 -48
  54. package/src/mutation-engine/types.ts +54 -0
  55. package/src/payload-contract.ts +165 -19
  56. package/src/read-expansion/ast-provider.ts +32 -0
  57. package/src/read-expansion/fold-skeleton.ts +56 -0
  58. package/src/read-expansion/grammar-cache.ts +33 -1
  59. package/src/read-expansion/grammar-manifest.ts +3 -1
  60. package/src/read-expansion/grammar-runtime.ts +1 -1
  61. package/src/read-expansion/qualified-names.ts +7 -0
  62. package/src/read-expansion/read-provider.ts +9 -0
  63. package/src/read-expansion/span-expansion.ts +26 -0
@@ -19,10 +19,10 @@ type SpanRef = {
19
19
  };
20
20
 
21
21
  /**
22
- * Wire item (ticket-04): exactly one payload per item — `text` or `text_ref` — over the inclusive
23
- * anchor pair, with optional `at` placement. There is no `op` field and no verbs: the key set IS
24
- * the vocabulary (ADR-0007 line 26; content comes from the copy of another served file, which the
25
- * wire expresses as `text_ref.file`).
22
+ * Wire item (ticket-04): exactly one payload per item — `text`, `text_ref`, or one insertion slot
23
+ * (`after` / `before`, ADR-0025) — over the inclusive anchor pair, with optional `at` placement.
24
+ * There is no `op` field and no verbs: the key set IS the vocabulary (ADR-0007 line 26; content
25
+ * comes from the copy of another served file, which the wire expresses as `text_ref.file`).
26
26
  */
27
27
  type EditItem = {
28
28
  anchor_from: string;
@@ -31,6 +31,20 @@ type EditItem = {
31
31
  at?: "in-place" | "before" | "after";
32
32
  text?: string;
33
33
  text_ref?: SpanRef;
34
+ /** Insertion content placed immediately AFTER the target line; the line itself is never rewritten. */
35
+ after?: string;
36
+ /** Insertion content placed immediately BEFORE the target line; the line itself is never rewritten. */
37
+ before?: string;
38
+ /**
39
+ * (ADR-0030) Re-base a `text` / `after` / `before` payload on the leading whitespace of the line
40
+ * `anchor_from` names. Absent (or `"as-is"`) writes the payload exactly as submitted.
41
+ */
42
+ indent?: "as-is" | "auto";
43
+ /**
44
+ * (`ADR-0031`) Replace the whole syntax item that contains `anchor_from`: the AST decides the span's
45
+ * end, so `anchor_to` is refused and only an in-place `text` payload is accepted.
46
+ */
47
+ expand?: "item";
34
48
  };
35
49
 
36
50
  type EditMode = "general" | "literal";
@@ -65,12 +79,19 @@ type AnchorSpan = { anchor_from: string; anchor_to: string };
65
79
  type DesiredContent =
66
80
  | { kind: "literal"; text: string }
67
81
  | { kind: "reference"; span: SpanRef; mode: "copy" | "cut" }
68
- | { kind: "empty" };
69
-
82
+ | { kind: "empty" }
83
+ // WHY: (ADR-0025) an insertion is its own payload kind, not a `text` plus a placement: the
84
+ // WHY: model names only where the new lines go and never restates the anchor line, so this
85
+ // WHY: kind is structurally incapable of rewriting the line it is anchored to.
86
+ | { kind: "insert"; side: "before" | "after"; text: string };
70
87
  type NormalizedEditItem = {
71
88
  target: AnchorSpan;
72
89
  at: Placement;
73
90
  payload: DesiredContent;
91
+ /** Admitted `indent` mode (ADR-0030); absent is `"as-is"`. */
92
+ indent?: "auto";
93
+ /** Admitted `expand` mode (ADR-0031): the AST decides the target span's end. */
94
+ expand?: "item";
74
95
  };
75
96
 
76
97
  export type NormalizedEditRequest = {
@@ -102,7 +123,7 @@ function isNormalizedEdit(input: unknown): input is Record<string, unknown> {
102
123
  }
103
124
 
104
125
  const ITEM_SHAPE =
105
- "an item is exactly { anchor_from, anchor_to?, text[, at] } or { anchor_from, anchor_to?, text_ref[, at] }";
126
+ 'an item is one payload over its anchor pair — `text` (optionally with `indent: "auto"` and, alone, `expand: "item"`), `text_ref`, or one insertion slot `after`/`before` (optionally with `indent: "auto"`) — plus optional `at`';
106
127
 
107
128
  const EDIT_PAYLOAD_HINT =
108
129
  "Edit must be called with exactly one payload per item, and each call edits ONE file. Use the canonical payload " +
@@ -110,11 +131,15 @@ const EDIT_PAYLOAD_HINT =
110
131
  '"file" is the text file to edit (a non-empty string, never a directory); each item names the bare-' +
111
132
  `${HASH_LEN}-char anchor "anchor_from" (the first line of the range, and the whole range of a single-line edit), an optional ` +
112
133
  'second bare anchor "anchor_to" (the last line of a multi-line range; omit it to edit "anchor_from" alone) and exactly one ' +
113
- 'payload — "text" (bare replacement content; an empty string deletes the range) or "text_ref" ' +
134
+ 'payload — "text" (bare replacement content; an empty string deletes the range), "text_ref" ' +
114
135
  '({ anchor_from, anchor_to, file?, mode (required): "copy" | "cut" } — the served span\'s bytes, whose two bounds are ' +
115
- 'always required, and whose "file" may name another served file as the copy/cut source); optional "at" is "in-place" ' +
116
- '(default), "before" or "after" (single-line resolved target only); optional "mode" is "general" (default, reproduced ' +
117
- 'served rows are refused) or "literal" (declared literal content).';
136
+ 'always required, and whose "file" may name another served file as the copy/cut source), or an insertion slot ' +
137
+ '"after"/"before" (the exact lines to insert below/above the single anchor line, which is never restated); optional ' +
138
+ '"at" is "in-place" (default), "before" or "after" (single-line resolved target only); optional "mode" is ' +
139
+ '"general" (default, reproduced served rows are refused) or "literal" (declared literal content); optional ' +
140
+ '"indent": "auto" re-bases a "text"/"after"/"before" payload on the leading whitespace of the line ' +
141
+ '"anchor_from" names, and optional "expand": "item" replaces the whole syntax item around "anchor_from" ' +
142
+ '(in-place "text" only: "anchor_to" is refused because the AST decides the end).';
118
143
  function describeReceived(input: unknown): string {
119
144
  if (input === undefined) return "Received no arguments.";
120
145
  if (input === null) return "Received null.";
@@ -187,6 +212,10 @@ const ITEM_KEY_SETS: readonly (readonly string[])[] = [
187
212
  ["anchor_from", "text_ref"],
188
213
  ["anchor_from", "anchor_to", "at", "text_ref"],
189
214
  ["anchor_from", "at", "text_ref"],
215
+ ["anchor_from", "after"],
216
+ ["anchor_from", "after", "anchor_to"],
217
+ ["anchor_from", "before"],
218
+ ["anchor_from", "before", "anchor_to"],
190
219
  ];
191
220
 
192
221
  function keySetEquals(keys: Set<string>, shape: readonly string[]): boolean {
@@ -218,7 +247,16 @@ function isAbsentValue(value: unknown): value is null | undefined {
218
247
  // WHY: shape `analyzeRequest` stores and nothing downstream can see an absent value as present.
219
248
  function foldAbsentSlots(item: Record<string, unknown>): Record<string, unknown> {
220
249
  const folded: Record<string, unknown> = { ...item };
221
- for (const key of ["text", "text_ref", "at", "anchor_to"] as const) {
250
+ for (const key of [
251
+ "text",
252
+ "text_ref",
253
+ "at",
254
+ "anchor_to",
255
+ "after",
256
+ "before",
257
+ "indent",
258
+ "expand",
259
+ ] as const) {
222
260
  if (isAbsentValue(folded[key])) delete folded[key];
223
261
  }
224
262
  if (isRec(folded.text_ref)) {
@@ -235,10 +273,27 @@ function analyzeItem(value: unknown, index: number): string | undefined {
235
273
  // WHY: (ticket-75) `value` arrives already folded by `foldAbsentSlots`: an absent optional slot
236
274
  // WHY: is gone, nested `text_ref.file` included, so this key set IS the declaration the gate
237
275
  // WHY: reads and no second fold site can disagree with the one that stored the item.
238
- const keys = new Set(Object.keys(value));
276
+ // WHY: (ADR-0030/ADR-0031) `indent` and `expand` are item MODIFIERS, not payload slots: the finite
277
+ // WHY: key-set gate admits exactly one payload shape, so the modifiers are peeled off here and
278
+ // WHY: validated as their own two-value enums. Keeping them out of every shape keeps the gate finite.
279
+ const modifierKeys = new Set(["indent", "expand"]);
280
+ const keys = new Set(Object.keys(value).filter((key) => !modifierKeys.has(key)));
239
281
  const hasText = keys.has("text");
240
282
  const hasRef = keys.has("text_ref");
283
+ const hasAfter = keys.has("after");
284
+ const hasBefore = keys.has("before");
285
+ const hasInsert = hasAfter || hasBefore;
286
+ // WHY: (ADR-0025) `after` and `before` are two placements of ONE payload, so carrying both is
287
+ // WHY: as illegal as carrying two payloads; the refusal names every payload key it found.
288
+ const carried = [
289
+ hasText ? "text" : undefined,
290
+ hasRef ? "text_ref" : undefined,
291
+ hasAfter ? "after" : undefined,
292
+ hasBefore ? "before" : undefined,
293
+ ].filter((key) => key !== undefined);
241
294
  if (!isLegalItemKeySet(keys)) {
295
+ // WHY: (ADR-0024/0025) `text` and `text_ref` is the classic pair and keeps its two-choice
296
+ // WHY: phrasing; any other collision gets the full menu so every payload key is named once.
242
297
  if (hasText && hasRef) {
243
298
  return (
244
299
  `edit[${index}] carries both "text" and "text_ref" fields: choose exactly one payload field per item (${ITEM_SHAPE}). ` +
@@ -246,9 +301,24 @@ function analyzeItem(value: unknown, index: number): string | undefined {
246
301
  `Choice B (copy/cut served span): keep "text_ref" and delete "text" from the JSON object.`
247
302
  );
248
303
  }
304
+ if (carried.length > 1) {
305
+ const names = carried.map((key) => `"${key}"`).join(" and ");
306
+ return (
307
+ `edit[${index}] carries ${carried.length} payload fields (${names}): choose exactly one payload field per item (${ITEM_SHAPE}). ` +
308
+ `Keep one of "text" (literal content), "text_ref" (copy/cut a served span), "after" or "before" (insert next to the anchor line) and delete the rest.`
309
+ );
310
+ }
249
311
  // WHY: (§9.3) an illegal key set is often also MISSING a required key; the unsupported-field
250
312
  // WHY: list alone renders blank there, so the refusal must name the missing keys too.
251
- const payloadKeys = new Set(["anchor_from", "anchor_to", "at", "text", "text_ref"]);
313
+ const payloadKeys = new Set([
314
+ "anchor_from",
315
+ "anchor_to",
316
+ "at",
317
+ "text",
318
+ "text_ref",
319
+ "after",
320
+ "before",
321
+ ]);
252
322
  const offending = [...keys].filter((key) => !payloadKeys.has(key));
253
323
  // WHY: `anchor_to` is optional at the wire — a single-line target needs no second bound — so a
254
324
  // WHY: missing `anchor_to` is not a refusal; the normalizer folds it onto `anchor_from`.
@@ -256,7 +326,9 @@ function analyzeItem(value: unknown, index: number): string | undefined {
256
326
  const clauses: string[] = [];
257
327
  if (offending.length > 0) clauses.push(`unsupported field(s) ${quoted(offending)}`);
258
328
  if (missing.length > 0) clauses.push(`missing required field(s) ${quoted(missing)}`);
259
- if (!hasText && !hasRef) {
329
+ // WHY: (ADR-0025) the insertion slots are payloads too, so "no payload" must count them —
330
+ // WHY: an item carrying only `after` is a pure insert, not an empty item.
331
+ if (!hasText && !hasRef && !hasInsert) {
260
332
  const named = clauses.length > 0 ? `${clauses.join(";")} — ` : "";
261
333
  return (
262
334
  `edit[${index}] carries no payload (neither "text" nor "text_ref" fields): ${named}choose exactly one payload field per item (${ITEM_SHAPE}) — ` +
@@ -280,6 +352,56 @@ function analyzeItem(value: unknown, index: number): string | undefined {
280
352
  return `edit[${index}] "at" must be "in-place", "before" or "after" when present.`;
281
353
  }
282
354
  }
355
+ // WHY: (ADR-0030) `indent` and (ADR-0031) `expand` are validated here, after the payload gate and
356
+ // WHY: before the payload-specific rules: a modifier the item cannot use is a payload mistake, and
357
+ // WHY: the refusal must name the field the model has to drop instead of the payload it already sent.
358
+ const indentValue = (value as Record<string, unknown>).indent;
359
+ if (indentValue !== undefined && indentValue !== "auto") {
360
+ return `edit[${index}] "indent" must be "auto" when present ("as-is" is the default and may be omitted).`;
361
+ }
362
+ const expandValue = (value as Record<string, unknown>).expand;
363
+ if (expandValue !== undefined && expandValue !== "item") {
364
+ return `edit[${index}] "expand" must be "item" when present: it replaces the whole syntax item that contains "anchor_from".`;
365
+ }
366
+ const wantsAutoIndent = indentValue === "auto";
367
+ const wantsExpand = expandValue === "item";
368
+ if (wantsExpand && anchor_to !== undefined) {
369
+ 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.`;
370
+ }
371
+ if (wantsExpand && (hasRef || hasInsert || (at !== undefined && at !== "in-place"))) {
372
+ 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.`;
373
+ }
374
+ if (wantsAutoIndent && hasRef) {
375
+ 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.`;
376
+ }
377
+ if (wantsAutoIndent && hasText && text === "") {
378
+ return `edit[${index}] "indent" has no lines to indent: "text": "" is the deletion payload. Delete "indent" from the item.`;
379
+ }
380
+ // WHY: (ADR-0025) an insertion is validated before `text` so the refusal can tell the model it
381
+ // WHY: sent the right shape with the wrong value, instead of reporting a missing payload.
382
+ if (hasInsert) {
383
+ if (hasAfter && hasBefore) {
384
+ 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.`;
385
+ }
386
+ const side = hasAfter ? "after" : "before";
387
+ const insertion = hasAfter
388
+ ? (value as Record<string, unknown>).after
389
+ : (value as Record<string, unknown>).before;
390
+ if (typeof insertion !== "string") {
391
+ return `edit[${index}] "${side}" must be a string with \\n line separators: the exact lines to insert next to the anchor line.`;
392
+ }
393
+ // WHY: an empty insertion would report success while changing nothing, which trains the model
394
+ // WHY: to trust a no-op; refuse it at admission instead of folding it into a silent noop item.
395
+ if (insertion === "") {
396
+ return `edit[${index}] "${side}" is empty: an insertion must carry at least one line. To delete a line use "text": "" with that line's anchor.`;
397
+ }
398
+ // WHY: a multi-line anchor range has no single side to insert against, so the target must be one
399
+ // WHY: line — the same constraint `at` carries on a resolved span.
400
+ if (anchor_to !== undefined && anchor_to !== anchor_from) {
401
+ return `edit[${index}] "${side}" inserts next to ONE line, but "anchor_from"/"anchor_to" name a range. Omit "anchor_to" (or make it equal "anchor_from") to insert next to a single line.`;
402
+ }
403
+ return undefined;
404
+ }
283
405
  if (hasText) {
284
406
  if (typeof text !== "string") {
285
407
  return `edit[${index}] "text" must be a string with \\n line separators, not an array. An empty string deletes the range.`;
@@ -343,7 +465,7 @@ function analyzeRequest(input: unknown): Admission {
343
465
  ok: false,
344
466
  message:
345
467
  `Edit request has unsupported field(s) ${quoted(rootOffending)}; it is exactly ` +
346
- `{ file, edits: [{ anchor_from, anchor_to, text | text_ref[, at] }, ...], mode?: "general" | "literal" }. ` +
468
+ `{ file, edits: [{ anchor_from, anchor_to, text | text_ref | after | before[, at] }, ...], mode?: "general" | "literal" }. ` +
347
469
  describeReceived(input),
348
470
  };
349
471
  }
@@ -393,6 +515,15 @@ function analyzeRequest(input: unknown): Admission {
393
515
  // SAFETY: item has the `EditItem` shape; TypeScript cannot narrow a `Record<string, unknown>` member.
394
516
  edited.push(item as unknown as EditItem);
395
517
  }
518
+ // WHY: (ADR-0031) an expand item's span is computed against the buffer it names, so combining it
519
+ // WHY: with other items would need remapping a computed range through earlier items' deltas — refuse
520
+ // WHY: the shape instead of guessing: one expand item per call.
521
+ if (items.length > 1 && edited.some((item) => item.expand === "item")) {
522
+ failures.push(
523
+ `Edit request carries "expand": "item" in a call with ${items.length} items: an expanded item must be the only item in the call — send one expand edit per call.`,
524
+ );
525
+ }
526
+
396
527
  if (failures.length > 0) {
397
528
  return { ok: false, message: `${failures.join(" ")} ${describeReceived(input)}` };
398
529
  }
@@ -405,9 +536,13 @@ function normalizedItemFrom(item: EditItem): NormalizedEditItem {
405
536
  const payload: DesiredContent =
406
537
  item.text_ref !== undefined
407
538
  ? { kind: "reference", span: item.text_ref, mode: item.text_ref.mode }
408
- : item.text === ""
409
- ? { kind: "empty" }
410
- : { kind: "literal", text: item.text ?? "" };
539
+ : item.after !== undefined
540
+ ? { kind: "insert", side: "after", text: item.after }
541
+ : item.before !== undefined
542
+ ? { kind: "insert", side: "before", text: item.before }
543
+ : item.text === ""
544
+ ? { kind: "empty" }
545
+ : { kind: "literal", text: item.text ?? "" };
411
546
  // WHY: the wire may omit `anchor_to`; the target is then the single line `anchor_from` names.
412
547
  // WHY: The engine always receives a closed pair, so this one defaulting point keeps every
413
548
  // WHY: downstream consumer shape-stable and nothing has to test for an absent bound.
@@ -419,6 +554,8 @@ function normalizedItemFrom(item: EditItem): NormalizedEditItem {
419
554
  target,
420
555
  at,
421
556
  payload,
557
+ ...(item.indent === "auto" ? { indent: item.indent } : {}),
558
+ ...(item.expand === "item" ? { expand: item.expand } : {}),
422
559
  };
423
560
  }
424
561
 
@@ -459,6 +596,10 @@ function isPlacementValue(value: string): value is Placement {
459
596
 
460
597
  function isNormalizedEditItem(value: unknown): value is NormalizedEditItem {
461
598
  if (!isRec(value)) return false;
599
+ // WHY: (ADR-0030/ADR-0031) the engine seam receives the admitted modifiers and nothing else, so a
600
+ // WHY: hand-built item cannot smuggle an unspellable mode past `assertReq`.
601
+ if (value.indent !== undefined && value.indent !== "auto") return false;
602
+ if (value.expand !== undefined && value.expand !== "item") return false;
462
603
  const { target, at, payload } = value;
463
604
  if (!isRec(target)) return false;
464
605
  if (typeof target.anchor_from !== "string" || typeof target.anchor_to !== "string") return false;
@@ -474,6 +615,11 @@ function isNormalizedEditItem(value: unknown): value is NormalizedEditItem {
474
615
  (payload.mode === "copy" || payload.mode === "cut")
475
616
  );
476
617
  }
618
+ if (payload.kind === "insert") {
619
+ return (
620
+ (payload.side === "before" || payload.side === "after") && typeof payload.text === "string"
621
+ );
622
+ }
477
623
  return false;
478
624
  }
479
625
 
@@ -14,6 +14,7 @@ import {
14
14
  type GrammarHandle,
15
15
  type GrammarLanguageLoader,
16
16
  } from "./ast-span.js";
17
+ import { collectSkeletonItems } from "./fold-skeleton.js";
17
18
  import { discardCachedGrammar, requestGrammar, type GrammarCacheOptions } from "./grammar-cache.js";
18
19
  import { GRAMMAR_MANIFEST, grammarLanguageForFile } from "./grammar-manifest.js";
19
20
  import { hasWebTreeSitterRuntime, loadWebTreeSitterGrammar } from "./grammar-runtime.js";
@@ -192,6 +193,37 @@ export function createAstSpanProvider(options: AstSpanProviderOptions = {}): Spa
192
193
  return runtimeAbsent;
193
194
  },
194
195
  prefetch,
196
+ /**
197
+ * The whole file's structural skeleton: every item the language's kind table owns, at its
198
+ * nesting depth. WHY it reuses the boundary policy: the same handle cache, the same decline
199
+ * vocabulary and the same decoration tables mean a folded read and a widened read can never
200
+ * disagree about what an item is.
201
+ */
202
+ async skeleton(file: string) {
203
+ const language = grammarLanguageForFile(file);
204
+ if (language === undefined) return decline("no_provider");
205
+ const languageScope = LANGUAGES[language];
206
+ if (languageScope === undefined) return decline("no_provider", language);
207
+ const source = await readText(file);
208
+ if (source === undefined) return decline("provider_declined", language);
209
+ const outcome = await handleFor(language);
210
+ if (outcome.kind === "decline") return outcome.decline;
211
+ const tree = outcome.handle.parse(source);
212
+ if (tree === null) return decline("grammar_unavailable", language);
213
+ try {
214
+ // WHY: a tree the grammar flagged as erroneous cannot name reliable item spans, and a
215
+ // WHY: half-believed skeleton is worse than the exact page — folding degrades to served.
216
+ if (tree.rootNode.hasError) return decline("provider_declined", language);
217
+ return {
218
+ items: collectSkeletonItems(tree.rootNode, languageScope.kinds, languageScope.decorate),
219
+ };
220
+ } catch {
221
+ outcome.handle.onFailure?.();
222
+ return decline("provider_declined", language);
223
+ } finally {
224
+ tree.delete?.();
225
+ }
226
+ },
195
227
  async enclosingSpan(file: string, window: SpanWindow) {
196
228
  if (!isOffsetWindow(window)) return decline("provider_declined");
197
229
  const language = grammarLanguageForFile(file);
@@ -0,0 +1,56 @@
1
+ /**
2
+ * The folded read's grammar side: which of a parsed file's nodes are its items, and how deeply each
3
+ * one nests.
4
+ *
5
+ * WHY the walk lives here and not in the read path: the answer is a property of the language's
6
+ * grammar and its decoration tables, exactly like the enclosing-scope seam beside it, so another
7
+ * grammar gains a skeleton by adding a kind table — never by teaching `read` a second tree walk.
8
+ *
9
+ * The walk reuses the enclosing-scope rules: only a node type the language's table owns is an item,
10
+ * and the file root is never one (it is the whole file, not a member of it).
11
+ *
12
+ * @module dsh-hashline-edit/read-expansion/fold-skeleton
13
+ */
14
+ import type { SyntaxNodeLike } from "./ast-span.js";
15
+ import type { ScopeDecorator } from "./scope-decoration.js";
16
+ import type { SkeletonItem } from "./span-expansion.js";
17
+ import type { SpanKindTable } from "./span-kind.js";
18
+
19
+ /**
20
+ * Collect one parsed file's items in file order, each with its nesting level.
21
+ *
22
+ * A node is an item when the language's kind table owns its grammar type; the decorator then widens
23
+ * that node to the declaration's wrappers and leading documentation, so an item's span is the same
24
+ * span an enclosing-scope read would serve. Every other node is walked through unchanged, which is
25
+ * how a declaration wrapped in `export_statement` or reached through a `variable_declarator` is
26
+ * still found at the top level of its file.
27
+ *
28
+ * @param root - the parsed file's root node.
29
+ * @param kinds - the language's grammar-type to note-kind table.
30
+ * @param decorate - the language's scope decorator (wrapper ascent plus leading decoration).
31
+ * @returns every item, in file order, at its 1-based nesting depth.
32
+ */
33
+ export function collectSkeletonItems(
34
+ root: SyntaxNodeLike,
35
+ kinds: SpanKindTable,
36
+ decorate: ScopeDecorator,
37
+ ): SkeletonItem[] {
38
+ const items: SkeletonItem[] = [];
39
+
40
+ const visit = (node: SyntaxNodeLike, depth: number): void => {
41
+ for (const child of node.namedChildren) {
42
+ if (!Object.hasOwn(kinds, child.type)) {
43
+ visit(child, depth);
44
+ continue;
45
+ }
46
+ const decorated = decorate(child);
47
+ items.push({ startLine: decorated.startLine, endLine: decorated.endLine, depth });
48
+ // WHY: an item's own subtree is one level deeper, so members are only revealed by a fold depth
49
+ // WHY: that asks for them — the depth of an item is structural, never a line count.
50
+ visit(child, depth + 1);
51
+ }
52
+ };
53
+
54
+ visit(root, 1);
55
+ return items;
56
+ }
@@ -1,7 +1,9 @@
1
1
  /**
2
2
  * Lazy, hash-pinned grammar cache.
3
3
  *
4
- * WHY fetch on first use instead of bundling: the full grammar set measured megabytes against a
4
+ * WHY bundled first and fetched only as a fallback: ADR-0026 ships all seven grammars inside the
5
+ * package (`grammars/`), so a first read never waits on — and never needs — the network. Bytes are
6
+ * digest-verified whichever source they come from; the committed manifest stays the trust anchor.
5
7
  * small extension bundle, and most sessions never touch most languages. The committed manifest is
6
8
  * the trust anchor: bytes are cached only after their SHA-256 matches, and a cache entry whose
7
9
  * digest no longer matches is deleted rather than parsed.
@@ -14,6 +16,7 @@ import { createHash } from "node:crypto";
14
16
  import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
15
17
  import { dirname, join } from "node:path";
16
18
  import { stateRoot } from "../config-dir.js";
19
+ import { readBundledAsset } from "../bundled-assets.js";
17
20
  import {
18
21
  GRAMMAR_MANIFEST,
19
22
  type GrammarManifest,
@@ -179,6 +182,13 @@ export async function requestGrammar(
179
182
  const path = grammarCachePath(language, entry, options.cacheRoot);
180
183
  const cached = readVerifiedCache(path, entry.sha256);
181
184
  if (cached !== undefined) return { status: "ready", artifact: { language, path, bytes: cached } };
185
+ // WHY: bundled before the network — the shipped grammars are the common path now, so a first
186
+ // WHY: read never waits on a fetch. A miss falls through to the lazy download below.
187
+ const bundled = bundledGrammarBytes(language, entry);
188
+ if (bundled !== undefined) {
189
+ writeCache(path, bundled);
190
+ return { status: "ready", artifact: { language, path, bytes: bundled } };
191
+ }
182
192
 
183
193
  let pending = inFlight.get(path);
184
194
  if (pending === undefined) {
@@ -207,3 +217,25 @@ export async function ensureGrammar(
207
217
  const result = await requestGrammar(language, options);
208
218
  return result.status === "ready" ? result.artifact : undefined;
209
219
  }
220
+
221
+ /**
222
+ * Verified bytes taken from this package's own `grammars/` directory, or undefined.
223
+ *
224
+ * WHY bundle AND keep the fetch: the shipped artifact must work offline and instantly, but a
225
+ * language can enter the manifest before it enters the tarball, so the download stays as the
226
+ * fallback for that window.
227
+ * @param language - manifest key.
228
+ * @param entry - the pinned version and digest for that key.
229
+ * @returns the verified bytes, or undefined when the asset is absent or no longer matches the pin.
230
+ */
231
+ function bundledGrammarBytes(
232
+ language: string,
233
+ entry: GrammarManifestEntry,
234
+ ): Uint8Array | undefined {
235
+ const name = `${language}-${entry.version}-${entry.sha256.slice(0, 16)}.wasm`;
236
+ const bytes = readBundledAsset(`grammars/${name}`);
237
+ if (bytes === undefined) return undefined;
238
+ // WHY: bundled bytes are verified too — a truncated download, a bad publish or a hand-edited
239
+ // WHY: file in the tarball must never reach the parser, exactly as for a fetched grammar.
240
+ return sha256Hex(bytes) === entry.sha256 ? bytes : undefined;
241
+ }
@@ -6,7 +6,9 @@
6
6
  * cache file, so a manifest bump cannot keep serving the previous grammar.
7
7
  *
8
8
  * WHY nothing here is imported as a module: the runtime (`web-tree-sitter`) is the only dependency;
9
- * grammar `.wasm` files are fetched on first use and are never part of the published package.
9
+ * WHY nothing here is imported as a module: the runtime (`web-tree-sitter`) is the only dependency;
10
+ * the pinned `.wasm` files ship inside this package under `grammars/` (ADR-0026) and are fetched only
11
+ * when that copy is missing, so a first read parses offline and never waits on the network.
10
12
  */
11
13
  export interface GrammarManifestEntry {
12
14
  readonly language: string;
@@ -6,7 +6,7 @@
6
6
  * the wasm host. `hasWebTreeSitterRuntime` is the cheap preflight; grammar bytes are only fetched
7
7
  * after it answered yes, and a resolution failure is the same answer as an offline grammar.
8
8
  *
9
- * WHY the runtime is the only dependency: grammars are fetched bytes, so the package grows only by
9
+ * WHY the runtime is the only DEPENDENCY: grammar bytes ship in this package (`grammars/`, ADR-0026)
10
10
  * the wasm host, never by a grammar set. `Language.load` accepts the verified bytes directly, so no
11
11
  * second disk read is needed after the cache check.
12
12
  */
@@ -3,6 +3,7 @@
3
3
  * when one is injected; it never discovers, starts, installs or proposes a server.
4
4
  */
5
5
  import type { SpanProvider } from "./span-expansion.js";
6
+ import type { SkeletonAnswer } from "./span-expansion.js";
6
7
 
7
8
  export interface QualifiedNameRequest {
8
9
  readonly file: string;
@@ -77,5 +78,11 @@ export function withQualifiedNames(
77
78
  }
78
79
  return span;
79
80
  },
81
+ // WHY: a name resolver has nothing to say about an item list, so the skeleton is forwarded
82
+ // WHY: untouched instead of being dropped with the other members.
83
+ skeleton(file: string): SkeletonAnswer | Promise<SkeletonAnswer> {
84
+ const derive = provider.skeleton;
85
+ return derive === undefined ? { refusal: "no_provider" } : derive(file);
86
+ },
80
87
  };
81
88
  }
@@ -43,6 +43,15 @@ export function createReadSpanProvider(options: ReadSpanProviderOptions = {}): S
43
43
  if (isShellPath(file)) return bash.enclosingSpan(file, window);
44
44
  return ast.enclosingSpan(file, window);
45
45
  },
46
+ skeleton(file) {
47
+ // WHY: only the AST lane derives items; Markdown sections, paragraphs, data files and shell
48
+ // WHY: scripts carry no item grammar in this seam, so a folded read of one falls open.
49
+ if (isMarkdownPath(file) || isDataPath(file) || isPlainTextPath(file) || isShellPath(file)) {
50
+ return { refusal: "no_provider" };
51
+ }
52
+ const derive = ast.skeleton;
53
+ return derive === undefined ? { refusal: "no_provider" } : derive(file);
54
+ },
46
55
  };
47
56
  return withQualifiedNames(
48
57
  base,
@@ -46,6 +46,26 @@ interface AnchorWindow {
46
46
  /** The window shape the seam accepts; `read` delegates anchor resolution to admission. */
47
47
  export type SpanWindow = OffsetWindow | AnchorWindow;
48
48
 
49
+ /**
50
+ * One retained syntax item of a folded read: the 1-indexed, inclusive lines its span covers and its
51
+ * nesting level. The span is the language's decorated item — wrappers and leading documentation
52
+ * included — so a range built from it is the whole item an edit replaces or deletes.
53
+ */
54
+ export interface SkeletonItem {
55
+ /** 1-indexed first line of the item's span. */
56
+ readonly startLine: number;
57
+ /** 1-indexed last line of the item's span. */
58
+ readonly endLine: number;
59
+ /** 1 is a top-level item; a declaration nested inside another item is one deeper. */
60
+ readonly depth: number;
61
+ }
62
+
63
+ /**
64
+ * What a skeleton attempt answered: the file's items in file order, or the typed reason it has no
65
+ * skeleton. A decline is not an error — the folded read renders the exact served page instead.
66
+ */
67
+ export type SkeletonAnswer = { readonly items: readonly SkeletonItem[] } | SpanDecline;
68
+
49
69
  /**
50
70
  * The boundary provider seam. A provider may answer synchronously now and asynchronously once a
51
71
  * grammar has to be fetched, so the read path always awaits it. `around_anchor` windows reach the
@@ -58,6 +78,12 @@ export interface SpanProvider {
58
78
  readonly runtimeAbsent?: boolean;
59
79
  /** Start grammar fetches off the read path; session_start calls this without awaiting. */
60
80
  prefetch?: (cwd?: string) => void | Promise<void>;
81
+ /**
82
+ * Optional: the whole file's structural skeleton, for the folded read mode. A provider that can
83
+ * name a file's items answers them in file order; one that cannot declines with the same typed
84
+ * vocabulary `enclosingSpan` uses.
85
+ */
86
+ skeleton?(file: string): SkeletonAnswer | Promise<SkeletonAnswer>;
61
87
  }
62
88
 
63
89
  /**