dsh-hashline-edit 0.5.0 → 0.5.2

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 (53) hide show
  1. package/README.md +84 -7
  2. package/cordis.patch.yml +20 -2
  3. package/lib/client.js +13 -3
  4. package/lib/index.js +2643 -78
  5. package/lib/types/dsh/codegraph/cli.d.ts +61 -0
  6. package/lib/types/dsh/codegraph/project.d.ts +27 -0
  7. package/lib/types/dsh/codegraph/tools.d.ts +36 -0
  8. package/lib/types/dsh/codegraph/view.d.ts +25 -0
  9. package/lib/types/dsh/diagnostics/cli.d.ts +76 -0
  10. package/lib/types/dsh/diagnostics/messages.d.ts +37 -0
  11. package/lib/types/dsh/diagnostics/parse.d.ts +39 -0
  12. package/lib/types/dsh/diagnostics/tools.d.ts +20 -0
  13. package/lib/types/dsh/diagnostics/view.d.ts +31 -0
  14. package/lib/types/dsh/guidance.d.ts +10 -4
  15. package/lib/types/dsh/hide.d.ts +6 -0
  16. package/lib/types/dsh/index.d.ts +51 -3
  17. package/lib/types/dsh/rg/cli.d.ts +67 -0
  18. package/lib/types/dsh/rg/command.d.ts +70 -0
  19. package/lib/types/dsh/rg/tools.d.ts +47 -0
  20. package/lib/types/dsh/rg/view.d.ts +81 -0
  21. package/lib/types/dsh/shell-view.d.ts +2 -2
  22. package/lib/types/dsh/tools/edit.d.ts +15 -1
  23. package/lib/types/dsh/tools/read-folded.d.ts +85 -0
  24. package/lib/types/src/domain-errors.d.ts +12 -1
  25. package/lib/types/src/edit-tool.d.ts +9 -1
  26. package/lib/types/src/mutation-engine/edit-expand.d.ts +36 -0
  27. package/lib/types/src/mutation-engine/edit-indent.d.ts +49 -0
  28. package/lib/types/src/mutation-engine/edit-request.d.ts +4 -0
  29. package/lib/types/src/mutation-engine/types.d.ts +57 -0
  30. package/lib/types/src/payload-contract.d.ts +4 -0
  31. package/lib/types/src/read-expansion/fold-skeleton.d.ts +32 -0
  32. package/lib/types/src/read-expansion/span-expansion.d.ts +26 -0
  33. package/package.json +1 -1
  34. package/prompts/codegraph-guidelines.md +8 -0
  35. package/prompts/diagnostics-guidelines.md +8 -0
  36. package/prompts/edit-guidelines.md +3 -1
  37. package/prompts/edit.md +3 -1
  38. package/prompts/read-description.md +1 -1
  39. package/prompts/read-guidelines.md +3 -1
  40. package/prompts/rg-guidelines.md +8 -0
  41. package/src/domain-errors.ts +52 -1
  42. package/src/edit-tool.ts +12 -1
  43. package/src/mutation-engine/edit-expand.ts +328 -0
  44. package/src/mutation-engine/edit-indent.ts +121 -0
  45. package/src/mutation-engine/edit-request.ts +4 -0
  46. package/src/mutation-engine/pipeline.ts +134 -48
  47. package/src/mutation-engine/types.ts +54 -0
  48. package/src/payload-contract.ts +74 -4
  49. package/src/read-expansion/ast-provider.ts +32 -0
  50. package/src/read-expansion/fold-skeleton.ts +56 -0
  51. package/src/read-expansion/qualified-names.ts +7 -0
  52. package/src/read-expansion/read-provider.ts +9 -0
  53. package/src/read-expansion/span-expansion.ts +26 -0
@@ -68,7 +68,12 @@ import { loadHashStore } from "../hash-store.js";
68
68
  import { snapshotIOFor, upsertSnapshotFor, snapshotHashFor } from "../snapshot-store";
69
69
  import { applyEdit } from "../hashline/apply.js";
70
70
  import { buildNeverServedEditHint } from "../served-session/serve-render.js";
71
- import { resEdit, type EditPlacement, type HEdit, type NEdit } from "../hashline/resolve.js";
71
+ import {
72
+ resEdit,
73
+ type EditPlacement,
74
+ type HEdit,
75
+ type LeaseSpanSource,
76
+ } from "../hashline/resolve.js";
72
77
  import { defaultHashIdentity, lineHashes } from "../hashline/hash-identity.js";
73
78
  import { HASH_LEN } from "../hashline/alphabet.js";
74
79
  import { denseServeRows, type ResolvedRange } from "../served-session/serve-render.js";
@@ -110,6 +115,14 @@ import type {
110
115
  MemberLifecycle,
111
116
  TransactionRecoveryReport,
112
117
  } from "./types.js";
118
+ import type { ItemApplyOutcome } from "./types.js";
119
+ import { applyExpandedItem } from "./edit-expand.js";
120
+ import {
121
+ applyAutoIndent,
122
+ buildIndentNote,
123
+ leadingWhitespaceOf,
124
+ type IndentSummary,
125
+ } from "./edit-indent.js";
113
126
  import {
114
127
  loadEditFile,
115
128
  loadForeignServedView,
@@ -192,34 +205,48 @@ interface ApplyOneEditInput {
192
205
  */
193
206
  currentIds?: (number | null)[];
194
207
  onRejected: (error: DomainError) => Promise<never>;
208
+ /** The item's admitted `indent` mode (ADR-0030); absent writes the payload as submitted. */
209
+ indent?: "auto";
195
210
  }
196
211
 
197
- type ApplyOneEditOutcome =
198
- | {
199
- kind: "applied";
200
- content: string;
201
- hashes: string[];
202
- removedHashes: Set<string>;
203
- range: ResolvedRange;
204
- firstChangedLine: number | undefined;
205
- lastChangedLine: number | undefined;
206
- anchorWarnings: string[] | undefined;
207
- literalBypass: boolean;
208
- neverServedCount: number;
209
- /** Span-ref move: the retired source span in pre-item coordinates. */
210
- sourceRange: ResolvedRange | undefined;
211
- /** Span-ref item: the mutated line regions the identity splice must apply. */
212
- mutationSpans: { startLine: number; endLine: number; inserted: number }[] | undefined;
213
- mutationStats: { addedLines: number; removedLines: number } | undefined;
214
- }
215
- | {
216
- kind: "noop";
217
- range: ResolvedRange;
218
- noopEdit: NEdit | undefined;
219
- anchorWarnings: string[] | undefined;
220
- literalBypass: boolean;
221
- neverServedCount: number;
222
- };
212
+ /** One item's outcome: the range path and the `expand: "item"` path return the same shape. */
213
+ type ApplyOneEditOutcome = ItemApplyOutcome;
214
+
215
+ /**
216
+ * Re-base one item's payload on the anchor line's indentation (`indent: "auto"`, ADR-0030).
217
+ *
218
+ * The anchor line is resolved through the same lease seam the apply path uses, on the same working
219
+ * buffer, so an anchor that cannot resolve rejects with the identical diagnostic before anything is
220
+ * written and a chained batch aligns against the buffer positions its anchors now name.
221
+ */
222
+ function autoIndentedEdit(
223
+ input: ApplyOneEditInput,
224
+ identity: LeaseSpanSource,
225
+ ): { edit: HEdit; indent?: IndentSummary } {
226
+ if (input.edit.content_lines.length === 0) return { edit: input.edit };
227
+ const fileLines = splitLines(input.content);
228
+ const leased = resolveLeasedEdit({
229
+ edit: {
230
+ content_lines: [],
231
+ hash_bounds: [input.edit.hash_bounds[0], input.edit.hash_bounds[0]],
232
+ },
233
+ snapshot: { fileHashes: input.hashes, fileLines, filePath: input.absolutePath },
234
+ served: input.served,
235
+ source: identity,
236
+ });
237
+ const anchorLine = leased.resolved.hash_bounds[0].line;
238
+ const baseIndent = leadingWhitespaceOf(fileLines[anchorLine - 1] ?? "");
239
+ const rebased = applyAutoIndent(input.edit.content_lines.join("\n"), baseIndent);
240
+ if (!rebased.changed) return { edit: input.edit };
241
+ return {
242
+ edit: { ...input.edit, content_lines: rebased.text.split("\n") },
243
+ indent: {
244
+ baseIndent,
245
+ strippedPrefix: rebased.strippedPrefix,
246
+ changedLines: rebased.changedLines,
247
+ },
248
+ };
249
+ }
223
250
 
224
251
  async function applyOneEdit(input: ApplyOneEditInput): Promise<ApplyOneEditOutcome> {
225
252
  abortIf(input.signal);
@@ -232,9 +259,13 @@ async function applyOneEdit(input: ApplyOneEditInput): Promise<ApplyOneEditOutco
232
259
  ...(input.currentIds !== undefined ? { currentIds: input.currentIds } : {}),
233
260
  });
234
261
 
262
+ let indent: IndentSummary | undefined;
235
263
  let anchorResult: ReturnType<typeof applyEdit>;
236
264
  try {
237
- anchorResult = applyEdit(input.content, input.edit, input.signal, input.hashes, {
265
+ const prepared =
266
+ input.indent === "auto" ? autoIndentedEdit(input, identity) : { edit: input.edit };
267
+ indent = prepared.indent;
268
+ anchorResult = applyEdit(input.content, prepared.edit, input.signal, input.hashes, {
238
269
  // WHY: read/write agreement — the verify path is literally the same
239
270
  // WHY: canonical absolute path the `hashesFor` call below uses (one field).
240
271
  filePath: input.absolutePath,
@@ -272,6 +303,7 @@ async function applyOneEdit(input: ApplyOneEditInput): Promise<ApplyOneEditOutco
272
303
  anchorWarnings,
273
304
  literalBypass,
274
305
  neverServedCount,
306
+ ...(indent !== undefined ? { indent } : {}),
275
307
  };
276
308
  }
277
309
 
@@ -308,6 +340,7 @@ async function applyOneEdit(input: ApplyOneEditInput): Promise<ApplyOneEditOutco
308
340
  sourceRange: anchorResult.sourceRange,
309
341
  mutationSpans: anchorResult.mutationSpans,
310
342
  mutationStats: anchorResult.mutationStats,
343
+ ...(indent !== undefined ? { indent } : {}),
311
344
  };
312
345
  }
313
346
 
@@ -808,6 +841,7 @@ async function runMutations(
808
841
  hadUtf8DecodeErrors,
809
842
  absolutePath,
810
843
  served,
844
+ canonDigests,
811
845
  } = await loadEditFile({
812
846
  path,
813
847
  cwd,
@@ -928,28 +962,80 @@ async function runMutations(
928
962
  }
929
963
  const edit = parsedItem.edit;
930
964
 
931
- const outcome = await applyOneEdit({
932
- content: currentContent,
933
- hashes: currentHashes,
934
- edit,
935
- ...(options?.signal !== undefined ? { signal: options.signal } : {}),
936
- served,
937
- blockedHashes: batchBlockedHashes,
938
- canonDigests: baseCanonDigests,
939
- sessionKey,
940
- absolutePath,
941
- store: hashStore,
942
- isPreview,
943
- mode,
944
- // WHY: the intermediate buffer is in-memory only, so its identities come from the buffer map
945
- // WHY: (`null` lines are the batch's own creations) — a re-diff of it against S_latest cannot
946
- // WHY: tell which of two byte-identical lines carries a leased line_id.
947
- ...(isPreview ? {} : { currentIds }),
948
- onRejected: async (error) => {
965
+ let outcome: ApplyOneEditOutcome;
966
+ if (item.expand === "item") {
967
+ // WHY: (ADR-0031) an expanded item is applied by its own seam: the AST decides the span, the
968
+ // WHY: licensing anchor still resolves through the leases, and the outcome re-enters this loop so
969
+ // WHY: identity bookkeeping, counting, drift, undo, commit and serve stay shared.
970
+ try {
971
+ outcome = await applyExpandedItem({
972
+ edit,
973
+ ...(item.indent !== undefined ? { indent: item.indent } : {}),
974
+ content: currentContent,
975
+ hashes: currentHashes,
976
+ served,
977
+ canonDigests,
978
+ identity: leaseSpanSource({
979
+ store: hashStore,
980
+ sessionKey,
981
+ absolutePath,
982
+ content: currentContent,
983
+ ...(isPreview ? {} : { currentIds }),
984
+ }),
985
+ absolutePath,
986
+ filePath: path,
987
+ mode,
988
+ sessionKey,
989
+ store: hashStore,
990
+ blockedHashes: batchBlockedHashes,
991
+ provider: options?.spanProvider,
992
+ ...(options?.signal !== undefined ? { signal: options.signal } : {}),
993
+ });
994
+ } catch (error) {
995
+ if (!(error instanceof DomainError)) throw error;
996
+ await recordRejectionServe({
997
+ error,
998
+ sessionKey,
999
+ absolutePath,
1000
+ isPreview,
1001
+ lineCount: currentHashes.length,
1002
+ contentHash: isPreview ? undefined : snapshotHashFor(currentContent),
1003
+ });
949
1004
  if (items.length === 1) throw error;
950
1005
  throw batchAbortFor({ error, index: number, path });
951
- },
952
- });
1006
+ }
1007
+ } else {
1008
+ outcome = await applyOneEdit({
1009
+ content: currentContent,
1010
+ hashes: currentHashes,
1011
+ edit,
1012
+ ...(options?.signal !== undefined ? { signal: options.signal } : {}),
1013
+ served,
1014
+ blockedHashes: batchBlockedHashes,
1015
+ canonDigests: baseCanonDigests,
1016
+ sessionKey,
1017
+ absolutePath,
1018
+ store: hashStore,
1019
+ isPreview,
1020
+ mode,
1021
+ ...(item.indent !== undefined ? { indent: item.indent } : {}),
1022
+ // WHY: the intermediate buffer is in-memory only, so its identities come from the buffer map
1023
+ // WHY: (`null` lines are the batch's own creations) — a re-diff of it against S_latest cannot
1024
+ // WHY: tell which of two byte-identical lines carries a leased line_id.
1025
+ ...(isPreview ? {} : { currentIds }),
1026
+ onRejected: async (error) => {
1027
+ if (items.length === 1) throw error;
1028
+ throw batchAbortFor({ error, index: number, path });
1029
+ },
1030
+ });
1031
+ }
1032
+
1033
+ // WHY: (ADR-0030) the applied re-indentation is reported through the warnings channel: the diff
1034
+ // WHY: shows the bytes but not that `indent: "auto"` is what produced them, and the model must not
1035
+ // WHY: have to re-read to learn the depth it landed at.
1036
+ if (outcome.kind === "applied" && outcome.indent !== undefined) {
1037
+ warnings.push(buildIndentNote({ ref: `edit[${number}] (${path})`, summary: outcome.indent }));
1038
+ }
953
1039
 
954
1040
  const range = outcome.range;
955
1041
  // WHY: (ticket-02) a move's retired source is an edited interval too: the drift scan must
@@ -8,6 +8,8 @@
8
8
  import type { LineEnding } from "../edit-diff.js";
9
9
  import type { ResolvedRange } from "../served-session/serve-render.js";
10
10
  import type { HashStore } from "../hash-store.js";
11
+ import type { SpanProvider } from "../read-expansion/span-expansion.js";
12
+ import type { IndentSummary } from "./edit-indent.js";
11
13
 
12
14
  // WHY: Re-export pipeline-facing options — validated once at admission (edit.ts),
13
15
  // WHY: trusted inside the engine. No `any`.
@@ -40,6 +42,11 @@ export interface PipelineOptions {
40
42
  * destination content is rewritten, so the rollback of that in-flight member is exercised.
41
43
  */
42
44
  onAfterMoveRename?: (toAbsolutePath: string) => void | Promise<void>;
45
+ /**
46
+ * Override seam for `expand: "item"` (ADR-0031): the AST span provider the expansion reads. Absent
47
+ * uses the lazily created AST provider, so a caller that never expands a node wires nothing.
48
+ */
49
+ spanProvider?: SpanProvider;
43
50
  }
44
51
 
45
52
  /**
@@ -135,3 +142,50 @@ export interface ProcessedEditFile {
135
142
  */
136
143
  lifecycle?: MemberLifecycle;
137
144
  }
145
+
146
+ /** Where one item's replacement landed, in pre-item coordinates. */
147
+ interface ItemMutationSpan {
148
+ startLine: number;
149
+ endLine: number;
150
+ inserted: number;
151
+ }
152
+
153
+ /**
154
+ * The outcome of applying ONE edit item. Both the range path (`applyOneEdit`) and the
155
+ * `expand: "item"` path (`applyExpandedItem`) return it, so the mutate loop's identity bookkeeping,
156
+ * counting, drift scan and commit are shared rather than forked per payload shape.
157
+ */
158
+ interface AppliedItemOutcome {
159
+ kind: "applied";
160
+ content: string;
161
+ hashes: string[];
162
+ removedHashes: Set<string>;
163
+ range: ResolvedRange;
164
+ firstChangedLine: number | undefined;
165
+ lastChangedLine: number | undefined;
166
+ anchorWarnings: string[] | undefined;
167
+ literalBypass: boolean;
168
+ neverServedCount: number;
169
+ /** A span-ref move's retired source span, in pre-item coordinates. */
170
+ sourceRange: ResolvedRange | undefined;
171
+ /** Every line region the item mutated; the identity map splices exactly these. */
172
+ mutationSpans: ItemMutationSpan[] | undefined;
173
+ /** Honest per-item line counts for a span-ref item. */
174
+ mutationStats: { addedLines: number; removedLines: number } | undefined;
175
+ /** The applied auto-indentation, when `indent: "auto"` changed the payload. */
176
+ indent?: IndentSummary;
177
+ }
178
+
179
+ /** The outcome of an item whose replacement left the bytes unchanged. */
180
+ interface NoopItemOutcome {
181
+ kind: "noop";
182
+ range: ResolvedRange;
183
+ noopEdit: { loc: string; currentContent: string } | undefined;
184
+ anchorWarnings: string[] | undefined;
185
+ literalBypass: boolean;
186
+ neverServedCount: number;
187
+ indent?: IndentSummary;
188
+ }
189
+
190
+ /** One item's outcome: applied, or a noop that wrote nothing. */
191
+ export type ItemApplyOutcome = AppliedItemOutcome | NoopItemOutcome;
@@ -35,6 +35,16 @@ type EditItem = {
35
35
  after?: string;
36
36
  /** Insertion content placed immediately BEFORE the target line; the line itself is never rewritten. */
37
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";
38
48
  };
39
49
 
40
50
  type EditMode = "general" | "literal";
@@ -78,6 +88,10 @@ type NormalizedEditItem = {
78
88
  target: AnchorSpan;
79
89
  at: Placement;
80
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";
81
95
  };
82
96
 
83
97
  export type NormalizedEditRequest = {
@@ -109,7 +123,7 @@ function isNormalizedEdit(input: unknown): input is Record<string, unknown> {
109
123
  }
110
124
 
111
125
  const ITEM_SHAPE =
112
- "an item is exactly { anchor_from, anchor_to?, text[, at] }, { anchor_from, anchor_to?, text_ref[, at] }, or { anchor_from, anchor_to?, after | before }";
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`';
113
127
 
114
128
  const EDIT_PAYLOAD_HINT =
115
129
  "Edit must be called with exactly one payload per item, and each call edits ONE file. Use the canonical payload " +
@@ -122,7 +136,10 @@ const EDIT_PAYLOAD_HINT =
122
136
  'always required, and whose "file" may name another served file as the copy/cut source), or an insertion slot ' +
123
137
  '"after"/"before" (the exact lines to insert below/above the single anchor line, which is never restated); optional ' +
124
138
  '"at" is "in-place" (default), "before" or "after" (single-line resolved target only); optional "mode" is ' +
125
- '"general" (default, reproduced served rows are refused) or "literal" (declared literal content).';
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).';
126
143
  function describeReceived(input: unknown): string {
127
144
  if (input === undefined) return "Received no arguments.";
128
145
  if (input === null) return "Received null.";
@@ -230,7 +247,16 @@ function isAbsentValue(value: unknown): value is null | undefined {
230
247
  // WHY: shape `analyzeRequest` stores and nothing downstream can see an absent value as present.
231
248
  function foldAbsentSlots(item: Record<string, unknown>): Record<string, unknown> {
232
249
  const folded: Record<string, unknown> = { ...item };
233
- for (const key of ["text", "text_ref", "at", "anchor_to", "after", "before"] 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) {
234
260
  if (isAbsentValue(folded[key])) delete folded[key];
235
261
  }
236
262
  if (isRec(folded.text_ref)) {
@@ -247,7 +273,11 @@ function analyzeItem(value: unknown, index: number): string | undefined {
247
273
  // WHY: (ticket-75) `value` arrives already folded by `foldAbsentSlots`: an absent optional slot
248
274
  // WHY: is gone, nested `text_ref.file` included, so this key set IS the declaration the gate
249
275
  // WHY: reads and no second fold site can disagree with the one that stored the item.
250
- 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)));
251
281
  const hasText = keys.has("text");
252
282
  const hasRef = keys.has("text_ref");
253
283
  const hasAfter = keys.has("after");
@@ -322,6 +352,31 @@ function analyzeItem(value: unknown, index: number): string | undefined {
322
352
  return `edit[${index}] "at" must be "in-place", "before" or "after" when present.`;
323
353
  }
324
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
+ }
325
380
  // WHY: (ADR-0025) an insertion is validated before `text` so the refusal can tell the model it
326
381
  // WHY: sent the right shape with the wrong value, instead of reporting a missing payload.
327
382
  if (hasInsert) {
@@ -460,6 +515,15 @@ function analyzeRequest(input: unknown): Admission {
460
515
  // SAFETY: item has the `EditItem` shape; TypeScript cannot narrow a `Record<string, unknown>` member.
461
516
  edited.push(item as unknown as EditItem);
462
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
+
463
527
  if (failures.length > 0) {
464
528
  return { ok: false, message: `${failures.join(" ")} ${describeReceived(input)}` };
465
529
  }
@@ -490,6 +554,8 @@ function normalizedItemFrom(item: EditItem): NormalizedEditItem {
490
554
  target,
491
555
  at,
492
556
  payload,
557
+ ...(item.indent === "auto" ? { indent: item.indent } : {}),
558
+ ...(item.expand === "item" ? { expand: item.expand } : {}),
493
559
  };
494
560
  }
495
561
 
@@ -530,6 +596,10 @@ function isPlacementValue(value: string): value is Placement {
530
596
 
531
597
  function isNormalizedEditItem(value: unknown): value is NormalizedEditItem {
532
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;
533
603
  const { target, at, payload } = value;
534
604
  if (!isRec(target)) return false;
535
605
  if (typeof target.anchor_from !== "string" || typeof target.anchor_to !== "string") return false;
@@ -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
+ }
@@ -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
  /**