dsh-hashline-edit 0.4.3 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/CHANGELOG.md +345 -0
  2. package/README.md +58 -5
  3. package/cordis.patch.yml +11 -1
  4. package/grammars/go-0.25.0-9504573f352b20be.wasm +0 -0
  5. package/grammars/java-0.23.5-4fdeac4ca6ca089f.wasm +0 -0
  6. package/grammars/python-0.25.0-16108b50df4ee9a3.wasm +0 -0
  7. package/grammars/rust-0.24.2-24c89bd9252255e4.wasm +0 -0
  8. package/grammars/tsx-0.23.2-79e5da75ea62855a.wasm +0 -0
  9. package/grammars/typescript-0.23.2-778025db5a8be0e7.wasm +0 -0
  10. package/grammars/vue-0.1.0-193c01119229352f.wasm +0 -0
  11. package/lib/client.js +13 -3
  12. package/lib/index.js +2345 -75
  13. package/lib/types/dsh/codegraph/cli.d.ts +61 -0
  14. package/lib/types/dsh/codegraph/project.d.ts +27 -0
  15. package/lib/types/dsh/codegraph/tools.d.ts +36 -0
  16. package/lib/types/dsh/codegraph/view.d.ts +25 -0
  17. package/lib/types/dsh/diagnostics/cli.d.ts +76 -0
  18. package/lib/types/dsh/diagnostics/messages.d.ts +37 -0
  19. package/lib/types/dsh/diagnostics/parse.d.ts +39 -0
  20. package/lib/types/dsh/diagnostics/tools.d.ts +20 -0
  21. package/lib/types/dsh/diagnostics/view.d.ts +31 -0
  22. package/lib/types/dsh/guidance.d.ts +7 -3
  23. package/lib/types/dsh/index.d.ts +32 -3
  24. package/lib/types/dsh/syntax-health.d.ts +60 -0
  25. package/lib/types/dsh/tools/edit.d.ts +15 -1
  26. package/lib/types/dsh/tools/output.d.ts +10 -0
  27. package/lib/types/dsh/tools/read-folded.d.ts +85 -0
  28. package/lib/types/src/bundled-assets.d.ts +13 -0
  29. package/lib/types/src/domain-errors.d.ts +12 -1
  30. package/lib/types/src/edit-tool.d.ts +9 -1
  31. package/lib/types/src/mutation-engine/edit-expand.d.ts +36 -0
  32. package/lib/types/src/mutation-engine/edit-indent.d.ts +49 -0
  33. package/lib/types/src/mutation-engine/edit-request.d.ts +8 -0
  34. package/lib/types/src/mutation-engine/types.d.ts +57 -0
  35. package/lib/types/src/payload-contract.d.ts +8 -0
  36. package/lib/types/src/read-expansion/fold-skeleton.d.ts +32 -0
  37. package/lib/types/src/read-expansion/grammar-manifest.d.ts +3 -1
  38. package/lib/types/src/read-expansion/grammar-runtime.d.ts +1 -1
  39. package/lib/types/src/read-expansion/span-expansion.d.ts +26 -0
  40. package/package.json +21 -23
  41. package/prompts/codegraph-guidelines.md +8 -0
  42. package/prompts/diagnostics-guidelines.md +8 -0
  43. package/prompts/edit-guidelines.md +6 -2
  44. package/prompts/edit.md +3 -1
  45. package/prompts/read-description.md +1 -1
  46. package/prompts/read-guidelines.md +3 -1
  47. package/src/bundled-assets.ts +23 -0
  48. package/src/domain-errors.ts +52 -1
  49. package/src/edit-tool.ts +12 -1
  50. package/src/mutation-engine/edit-expand.ts +328 -0
  51. package/src/mutation-engine/edit-indent.ts +121 -0
  52. package/src/mutation-engine/edit-request.ts +8 -1
  53. package/src/mutation-engine/pipeline.ts +150 -48
  54. package/src/mutation-engine/types.ts +54 -0
  55. package/src/payload-contract.ts +165 -19
  56. package/src/read-expansion/ast-provider.ts +32 -0
  57. package/src/read-expansion/fold-skeleton.ts +56 -0
  58. package/src/read-expansion/grammar-cache.ts +33 -1
  59. package/src/read-expansion/grammar-manifest.ts +3 -1
  60. package/src/read-expansion/grammar-runtime.ts +1 -1
  61. package/src/read-expansion/qualified-names.ts +7 -0
  62. package/src/read-expansion/read-provider.ts +9 -0
  63. package/src/read-expansion/span-expansion.ts +26 -0
package/src/edit-tool.ts CHANGED
@@ -17,6 +17,15 @@ import { execute as engineExecute, preview as enginePreview } from "./mutation-e
17
17
  import { isMutationSuccess } from "./mutation-result.js";
18
18
  import { attachEnvelope } from "./error-envelope.js";
19
19
 
20
+ import type { SpanProvider } from "./read-expansion/span-expansion.js";
21
+ /**
22
+ * The optional seams of the edit use case. `spanProvider` overrides the AST span provider an
23
+ * `expand: "item"` payload reads (ADR-0031); absent uses the engine's lazily created AST provider.
24
+ */
25
+ export interface EditToolOptions {
26
+ spanProvider?: SpanProvider;
27
+ }
28
+
20
29
  type EditToolContext = {
21
30
  cwd: string;
22
31
  sessionManager?: { getSessionId(): string };
@@ -42,7 +51,7 @@ export interface EditTool {
42
51
  preview(request: unknown, cwd: string, ctx: PreviewContext): Promise<PreviewResult>;
43
52
  }
44
53
 
45
- export function createEditTool(): EditTool {
54
+ export function createEditTool(options: EditToolOptions = {}): EditTool {
46
55
  return {
47
56
  async execute(params, signal, ctx) {
48
57
  const canonical = normReq(params);
@@ -57,6 +66,7 @@ export function createEditTool(): EditTool {
57
66
  // SAFETY: signal is AbortSignal | undefined at pi boundary — runtime check via engine's abortIf
58
67
  ...(signal !== undefined ? { signal } : {}),
59
68
  sessionKey,
69
+ ...(options.spanProvider !== undefined ? { spanProvider: options.spanProvider } : {}),
60
70
  });
61
71
  if (isMutationSuccess(result)) {
62
72
  // SAFETY: toolResult is validated by isMutationSuccess discriminated union guard
@@ -92,6 +102,7 @@ export function createEditTool(): EditTool {
92
102
  const result = await enginePreview(normalized as NormalizedEditRequest, cwd, {
93
103
  accessMode: constants.R_OK,
94
104
  sessionKey: sessionKeyFor(ctx),
105
+ ...(options.spanProvider !== undefined ? { spanProvider: options.spanProvider } : {}),
95
106
  });
96
107
  if (!isMutationSuccess(result)) {
97
108
  return { error: result.message };
@@ -0,0 +1,328 @@
1
+ /**
2
+ * `expand: "item"` — replace the whole syntax item that contains the anchor line (ADR-0031).
3
+ *
4
+ * One anchor is the model's entire act of naming a target: the AST decides where the item starts and
5
+ * ends, so the model never restates a closing brace it cannot see and never hand-writes a doc comment
6
+ * it would have to reproduce byte-exactly.
7
+ *
8
+ * Two authorities meet here and neither is inferred:
9
+ *
10
+ * - the licensing anchor still resolves through the session's leases — the same seam a range edit
11
+ * uses — so an anchor that was never served, or whose line identity is gone, still fails closed with
12
+ * the standard reject-and-serve rejection;
13
+ * - the expanded start..end is the explicit authorization to replace the interior rows the model has
14
+ * not seen, computed from the same Tree-sitter machinery the read path expands with
15
+ * (`src/read-expansion/`): the innermost item whose span contains the anchor line, including its
16
+ * leading documentation/attributes and its closing delimiter.
17
+ *
18
+ * The replacement is written through the one line-list serializer the edit path uses
19
+ * (`serializeLineList`), so the EOF and trailing-newline conventions are shared rather than copied.
20
+ */
21
+ import { DomainError, type ExpandUnavailableReason } from "../domain-errors.js";
22
+ import { serializeLineList, changedRange } from "../hashline/apply.js";
23
+ import { defaultHashIdentity } from "../hashline/hash-identity.js";
24
+ import { resolveLeasedEdit } from "../hashline/lease-resolve.js";
25
+ import { warnUnicodeEsc, type HEdit, type LeaseSpanSource } from "../hashline/resolve.js";
26
+ import { createAstSpanProvider } from "../read-expansion/ast-provider.js";
27
+ import type { SpanProvider } from "../read-expansion/span-expansion.js";
28
+ import type { HashStore } from "../hash-store.js";
29
+ import {
30
+ LITERAL_BYPASS_NOTICE,
31
+ findNeverServedAnchorShapes,
32
+ findServedHashEcho,
33
+ trackServedEditRefusal,
34
+ type ResolvedRange,
35
+ } from "../served-session/serve-render.js";
36
+ import { snapshotIOFor } from "../snapshot-store";
37
+ import { abortIf, splitLines } from "../utils.js";
38
+ import { applyAutoIndent, leadingWhitespaceOf, type IndentSummary } from "./edit-indent.js";
39
+ import type { ItemApplyOutcome } from "./types.js";
40
+
41
+ /**
42
+ * The one provider an `expand` item reads through, created lazily so a session that never expands a
43
+ * node pays nothing for the wasm runtime or the grammar cache. The read path composes its own provider
44
+ * (Markdown, plain text, shell, optional qualified names); expansion is code-only by design, so the AST
45
+ * provider alone is injected, and the dsh adapter may override it.
46
+ */
47
+ let sharedProvider: SpanProvider | undefined;
48
+
49
+ function defaultExpandProvider(): SpanProvider {
50
+ if (sharedProvider === undefined) sharedProvider = createAstSpanProvider();
51
+ return sharedProvider;
52
+ }
53
+
54
+ /** The provider answer shape, named from the seam so no read-expansion type has to be re-declared. */
55
+ type SpanAnswer = Awaited<ReturnType<SpanProvider["enclosingSpan"]>>;
56
+
57
+ /** The innermost syntax item the provider placed around one line. */
58
+ interface ExpandedItem {
59
+ startLine: number;
60
+ endLine: number;
61
+ }
62
+
63
+ /**
64
+ * The refusal a declined provider answer becomes. WHY one reason per condition instead of passing the
65
+ * provider's internal word through: the model acts on the three causes differently (no grammar for this
66
+ * file / the host has no grammar / no item owns the line), and the seam's own refusal vocabulary is an
67
+ * audit concern, not a model-facing one.
68
+ */
69
+ function refusalReasonOf(answer: SpanAnswer): ExpandUnavailableReason {
70
+ if (answer === null) return "no-enclosing-item";
71
+ if (!("refusal" in answer)) return "no-enclosing-item";
72
+ switch (answer.refusal) {
73
+ case "no_provider":
74
+ case "not_text":
75
+ case "toggle_off":
76
+ return "non-code";
77
+ case "grammar_unavailable":
78
+ case "cold_grammar":
79
+ case "runtime_absent":
80
+ return "grammar-unavailable";
81
+ default:
82
+ return "no-enclosing-item";
83
+ }
84
+ }
85
+
86
+ function expandUnavailable(args: {
87
+ path: string;
88
+ line: number;
89
+ reason: ExpandUnavailableReason;
90
+ }): DomainError {
91
+ return new DomainError("E_EXPAND_UNAVAILABLE", {
92
+ path: args.path,
93
+ line: args.line,
94
+ reason: args.reason,
95
+ });
96
+ }
97
+
98
+ /** Resolve the innermost item around `anchorLine`, refusing every answer that is not one closed item. */
99
+ async function resolveEnclosingItem(args: {
100
+ provider: SpanProvider;
101
+ absolutePath: string;
102
+ filePath: string;
103
+ anchorLine: number;
104
+ totalLines: number;
105
+ }): Promise<ExpandedItem> {
106
+ const answer = await args.provider.enclosingSpan(args.absolutePath, {
107
+ offset: args.anchorLine,
108
+ limit: 1,
109
+ });
110
+ if (answer === null || "refusal" in answer) {
111
+ throw expandUnavailable({
112
+ path: args.filePath,
113
+ line: args.anchorLine,
114
+ reason: refusalReasonOf(answer),
115
+ });
116
+ }
117
+ const startLine = answer.start;
118
+ const endLine = answer.end;
119
+ // WHY: the provider's contract already pins the window; re-checking it here keeps a future provider
120
+ // WHY: (or a mis-keyed fake) from moving the splice onto lines the anchor never licensed.
121
+ if (
122
+ !Number.isInteger(startLine) ||
123
+ !Number.isInteger(endLine) ||
124
+ startLine < 1 ||
125
+ endLine < startLine ||
126
+ startLine > args.anchorLine ||
127
+ endLine < args.anchorLine ||
128
+ endLine > args.totalLines
129
+ ) {
130
+ throw expandUnavailable({
131
+ path: args.filePath,
132
+ line: args.anchorLine,
133
+ reason: "stale-content",
134
+ });
135
+ }
136
+ return { startLine, endLine };
137
+ }
138
+
139
+ /**
140
+ * Replace one whole line range of `content` with `lines`, reusing the edit path's own serializer for the
141
+ * trailing-newline and EOF conventions. The returned text is byte-identical outside the range.
142
+ */
143
+ function replaceItemSpan(
144
+ content: string,
145
+ startLine: number,
146
+ endLine: number,
147
+ lines: readonly string[],
148
+ ): string {
149
+ const fileLines = splitLines(content);
150
+ const out = [...fileLines.slice(0, startLine - 1), ...lines, ...fileLines.slice(endLine)];
151
+ return serializeLineList(content, fileLines, undefined, out);
152
+ }
153
+
154
+ /** Everything the expansion needs from the pipeline's per-item state. */
155
+ export interface ExpandedItemInput {
156
+ /** The parsed item: its bounds name the licensing anchor, its `content_lines` the replacement. */
157
+ edit: HEdit;
158
+ /** The item's admitted `indent` mode, when it carried one. */
159
+ indent?: "auto";
160
+ /** The working buffer this item applies to. */
161
+ content: string;
162
+ /** Content hashes of `content`, indexed by line. */
163
+ hashes: string[];
164
+ /** The session's served mirror, used by the served hash echo gate only. */
165
+ served: (string | null)[];
166
+ /** Canon digests parallel to `served`; empty means no evidence. */
167
+ canonDigests: (string | null)[];
168
+ identity: LeaseSpanSource;
169
+ absolutePath: string;
170
+ /** The path the model named, for refusal text. */
171
+ filePath: string;
172
+ mode: "general" | "literal";
173
+ sessionKey: string;
174
+ store: HashStore;
175
+ blockedHashes?: ReadonlySet<string>;
176
+ /** Override seam; absent means the lazily created AST provider. */
177
+ provider: SpanProvider | undefined;
178
+ signal?: AbortSignal;
179
+ }
180
+
181
+ /**
182
+ * Apply one `expand: "item"` item: license the anchor, resolve the enclosing item, splice the
183
+ * replacement, and return the same outcome shape a range edit returns so every later stage (identity
184
+ * bookkeeping, drift, undo, commit, serve) is shared.
185
+ */
186
+ export async function applyExpandedItem(input: ExpandedItemInput): Promise<ItemApplyOutcome> {
187
+ abortIf(input.signal);
188
+
189
+ const lines = splitLines(input.content);
190
+ // WHY: the licensing anchor is resolved through the leases, never by content: an anchor the session
191
+ // WHY: never held must fail with the standard rejection instead of being re-found by spelling.
192
+ const leased = resolveLeasedEdit({
193
+ edit: {
194
+ content_lines: [],
195
+ hash_bounds: [input.edit.hash_bounds[0], input.edit.hash_bounds[0]],
196
+ },
197
+ snapshot: {
198
+ fileHashes: input.hashes,
199
+ fileLines: lines,
200
+ filePath: input.absolutePath,
201
+ },
202
+ served: input.served,
203
+ source: input.identity,
204
+ });
205
+ const anchorLine = leased.resolved.hash_bounds[0].line;
206
+
207
+ const provider = input.provider ?? defaultExpandProvider();
208
+ const item = await resolveEnclosingItem({
209
+ provider,
210
+ absolutePath: input.absolutePath,
211
+ filePath: input.filePath,
212
+ anchorLine,
213
+ totalLines: input.hashes.length,
214
+ });
215
+
216
+ let replacement = input.edit.content_lines;
217
+ let indent: IndentSummary | undefined;
218
+ if (input.indent === "auto" && replacement.length > 0) {
219
+ const anchorText = lines[anchorLine - 1] ?? "";
220
+ const rebased = applyAutoIndent(replacement.join("\n"), leadingWhitespaceOf(anchorText));
221
+ if (rebased.changed) {
222
+ replacement = rebased.text.split("\n");
223
+ indent = {
224
+ baseIndent: leadingWhitespaceOf(anchorText),
225
+ strippedPrefix: rebased.strippedPrefix,
226
+ changedLines: rebased.changedLines,
227
+ };
228
+ }
229
+ }
230
+
231
+ const nextContent = replaceItemSpan(input.content, item.startLine, item.endLine, replacement);
232
+ const range: ResolvedRange = {
233
+ startLine: item.startLine,
234
+ endLine: item.endLine,
235
+ startHash: input.hashes[item.startLine - 1]!,
236
+ endHash: input.hashes[item.endLine - 1]!,
237
+ delta: replacement.length - (item.endLine - item.startLine + 1),
238
+ };
239
+
240
+ const warnings: string[] = [];
241
+ // WHY: the replacement reproduces served rows exactly like a range edit's `text`, so the same gate
242
+ // WHY: reads it: one position-agnostic scan of the lines that will be written, no shape refusal.
243
+ const echo = findServedHashEcho(replacement, input.served, input.canonDigests, 1);
244
+ let literalBypass = false;
245
+ if (echo !== undefined) {
246
+ if (input.mode === "literal") {
247
+ literalBypass = true;
248
+ warnings.push(LITERAL_BYPASS_NOTICE);
249
+ } else {
250
+ const count = trackServedEditRefusal(
251
+ input.sessionKey,
252
+ input.absolutePath,
253
+ input.edit.hash_bounds[0].hash,
254
+ input.edit.hash_bounds[1].hash,
255
+ replacement[echo.k - 1] ?? "",
256
+ );
257
+ throw new DomainError("E_SUSPICIOUS_TEXT", {
258
+ target: "edit",
259
+ path: input.filePath,
260
+ line: echo.k,
261
+ hash: echo.hash,
262
+ servedLine: echo.servedLine,
263
+ count,
264
+ });
265
+ }
266
+ }
267
+
268
+ const payloadEdit: HEdit = { ...input.edit, content_lines: replacement };
269
+ warnUnicodeEsc(payloadEdit, warnings);
270
+ const neverServedCount = findNeverServedAnchorShapes(replacement, input.served, 1).length;
271
+
272
+ if (nextContent === input.content) {
273
+ return {
274
+ kind: "noop",
275
+ range,
276
+ noopEdit: {
277
+ loc: input.edit.hash_bounds[0].hash,
278
+ currentContent: lines.slice(item.startLine - 1, item.endLine).join("\n"),
279
+ },
280
+ anchorWarnings: warnings.length > 0 ? warnings : undefined,
281
+ literalBypass,
282
+ neverServedCount,
283
+ ...(indent !== undefined ? { indent } : {}),
284
+ };
285
+ }
286
+
287
+ // WHY: moving the file to zero bytes is refused for the same reason a range deletion is: the tool
288
+ // WHY: has no empty-file write path, and the honest answer names the range instead of truncating.
289
+ if (input.content !== "" && nextContent === "") {
290
+ throw new DomainError("E_EMPTY_RANGE", {});
291
+ }
292
+
293
+ const removedHashes = new Set(input.hashes.slice(item.startLine - 1, item.endLine));
294
+ // WHY: the working buffer is in-memory only — no snapshot and no lease is written here (spec
295
+ // WHY: §3.2.4); the single materialization runs after `writeAtomic` in `apply`.
296
+ const nextHashes = await defaultHashIdentity.hashesFor(nextContent, {
297
+ path: input.absolutePath,
298
+ prior: { content: input.content, hashes: input.hashes, removedHashes },
299
+ persist: false,
300
+ snapshotIO: snapshotIOFor(input.store),
301
+ // SAFETY: the options object is typed by HashIdentity's internal parameter shape, which the caller
302
+ // SAFETY: never sees; every field above is already typed, so the cast widens nothing.
303
+ blockedHashes: input.blockedHashes as unknown as ReadonlySet<string> | undefined,
304
+ } as unknown as Parameters<typeof defaultHashIdentity.hashesFor>[1]);
305
+ const changed = changedRange(input.content, nextContent);
306
+
307
+ return {
308
+ kind: "applied",
309
+ content: nextContent,
310
+ hashes: nextHashes,
311
+ removedHashes,
312
+ range,
313
+ firstChangedLine: changed?.firstChangedLine,
314
+ lastChangedLine: changed?.lastChangedLine,
315
+ anchorWarnings: warnings.length > 0 ? warnings : undefined,
316
+ literalBypass,
317
+ neverServedCount,
318
+ sourceRange: undefined,
319
+ mutationSpans: undefined,
320
+ // WHY: the loop's fallback counts the item's own target span, which for an expansion is the one
321
+ // WHY: anchor line rather than the whole item; the expansion reports its honest counts instead.
322
+ mutationStats: {
323
+ addedLines: replacement.length,
324
+ removedLines: item.endLine - item.startLine + 1,
325
+ },
326
+ ...(indent !== undefined ? { indent } : {}),
327
+ };
328
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Auto relative indentation for `edit` payloads (`indent: "auto"`, ADR-0030).
3
+ *
4
+ * The anchor line supplies the base indentation; the payload supplies the block. A snippet written
5
+ * flush-left — or uniformly indented, as a model naturally writes one — is re-based onto the anchor
6
+ * line so the written bytes land at the depth the model meant, without the model having to count the
7
+ * anchor's columns and without a re-read to learn them.
8
+ *
9
+ * The transform is pure and literal: the common prefix is measured over the payload's own characters,
10
+ * so a tab stays a tab and a space stays a space, and an empty (or whitespace-only) line is never
11
+ * padded. Nothing here mutates; the pipeline decides where the result goes.
12
+ */
13
+
14
+ /** The leading whitespace of one line — spaces and tabs only, matched as written. */
15
+ export function leadingWhitespaceOf(line: string): string {
16
+ let end = 0;
17
+ while (end < line.length && (line[end] === " " || line[end] === "\t")) end += 1;
18
+ return line.slice(0, end);
19
+ }
20
+
21
+ /** A payload line that carries no content, so it is neither measured nor re-indented. */
22
+ function isBlankLine(line: string): boolean {
23
+ return line.trim() === "";
24
+ }
25
+
26
+ /**
27
+ * The longest common leading-whitespace literal prefix of the non-blank lines, or `""` when they do
28
+ * not share one. A blank line is excluded: it has no content to align and keeping it out is what lets
29
+ * a blank separator inside the snippet survive verbatim.
30
+ */
31
+ function commonIndentPrefix(lines: readonly string[]): string {
32
+ let prefix: string | undefined;
33
+ for (const line of lines) {
34
+ if (isBlankLine(line)) continue;
35
+ const indent = leadingWhitespaceOf(line);
36
+ if (prefix === undefined) {
37
+ prefix = indent;
38
+ if (prefix === "") return "";
39
+ continue;
40
+ }
41
+ let shared = 0;
42
+ while (shared < prefix.length && shared < indent.length && prefix[shared] === indent[shared]) {
43
+ shared += 1;
44
+ }
45
+ prefix = prefix.slice(0, shared);
46
+ if (prefix === "") return "";
47
+ }
48
+ return prefix ?? "";
49
+ }
50
+
51
+ /** What one `indent: "auto"` transform did, so the model channel can report it without a re-read. */
52
+ export interface AutoIndentResult {
53
+ /** The payload text with the shared prefix removed and the base indent written onto every line. */
54
+ text: string;
55
+ /** True when at least one byte of the payload changed. */
56
+ changed: boolean;
57
+ /** How many non-blank payload lines differ from the submitted ones. */
58
+ changedLines: number;
59
+ /** The literal prefix removed from every non-blank line (`""` when none was shared). */
60
+ strippedPrefix: string;
61
+ }
62
+
63
+ /**
64
+ * Re-base `text` onto `baseIndent`: strip the payload's own longest common leading-whitespace prefix,
65
+ * then prefix every non-blank line with the base indent. Blank lines are carried through untouched
66
+ * (they are written as the model wrote them, never padded).
67
+ */
68
+ export function applyAutoIndent(text: string, baseIndent: string): AutoIndentResult {
69
+ const lines = text.split("\n");
70
+ const strippedPrefix = commonIndentPrefix(lines);
71
+ let changedLines = 0;
72
+ const rebased = lines.map((line) => {
73
+ if (isBlankLine(line)) return line;
74
+ const next = `${baseIndent}${line.slice(strippedPrefix.length)}`;
75
+ if (next !== line) changedLines += 1;
76
+ return next;
77
+ });
78
+ const nextText = rebased.join("\n");
79
+ return {
80
+ text: nextText,
81
+ changed: nextText !== text,
82
+ changedLines,
83
+ strippedPrefix,
84
+ };
85
+ }
86
+
87
+ /** A human-readable rendering of one indentation prefix (spaces/tabs counted; anything else quoted). */
88
+ function describeIndent(indent: string): string {
89
+ if (indent === "") return "no indentation";
90
+ if (/^ +$/.test(indent)) {
91
+ return indent.length === 1 ? "1 space" : `${indent.length} spaces`;
92
+ }
93
+ if (/^\t+$/.test(indent)) {
94
+ return indent.length === 1 ? "1 tab" : `${indent.length} tabs`;
95
+ }
96
+ return `the exact prefix ${JSON.stringify(indent)}`;
97
+ }
98
+
99
+ /** The applied-indentation facts one item reports through the warnings channel. */
100
+ export interface IndentSummary {
101
+ /** The anchor line's leading whitespace the payload was aligned to. */
102
+ baseIndent: string;
103
+ /** The payload's own shared prefix that was removed before the base indent was written. */
104
+ strippedPrefix: string;
105
+ /** How many non-blank payload lines moved. */
106
+ changedLines: number;
107
+ }
108
+
109
+ /**
110
+ * The model-facing note for one applied auto-indent. It reports facts only (the anchor's indentation,
111
+ * the removed prefix, the number of lines) so the model can see the written indentation without a
112
+ * re-read; it never asks the model to do anything.
113
+ */
114
+ export function buildIndentNote(args: { ref: string; summary: IndentSummary }): string {
115
+ const { ref, summary } = args;
116
+ const stripped =
117
+ summary.strippedPrefix === ""
118
+ ? ""
119
+ : `; a shared ${describeIndent(summary.strippedPrefix)} prefix was dropped from the payload`;
120
+ return `${ref}: "indent": "auto" re-indented ${summary.changedLines} line(s) to the anchor line's ${describeIndent(summary.baseIndent)}${stripped}.`;
121
+ }
@@ -15,13 +15,20 @@ type Placement = "in-place" | "before" | "after";
15
15
  export type DesiredContent =
16
16
  | { kind: "literal"; text: string }
17
17
  | { kind: "reference"; span: SpanRef; mode: "copy" | "cut" }
18
- | { kind: "empty" };
18
+ | { kind: "empty" }
19
+ // WHY: (ADR-0025) a pure insertion carries its own side; it is never folded into `literal` +
20
+ // WHY: `at`, so nothing downstream can turn an insert into a rewrite of the anchor line.
21
+ | { kind: "insert"; side: "before" | "after"; text: string };
19
22
 
20
23
  export type NormalizedEditItem = {
21
24
  target: { anchor_from: string; anchor_to: string };
22
25
  at: Placement;
23
26
  payload: DesiredContent;
24
27
  file?: string;
28
+ /** Admitted `indent` mode (ADR-0030); absent is `"as-is"`. */
29
+ indent?: "auto";
30
+ /** Admitted `expand` mode (ADR-0031): the AST decides the target span's end. */
31
+ expand?: "item";
25
32
  };
26
33
 
27
34
  export type NormalizedEditRequest = {