dsh-better-edit 0.2.2 → 0.3.0

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 (44) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +318 -245
  3. package/README.zh.md +20 -11
  4. package/lib/contract.js +40 -1
  5. package/lib/edit-engine.js +4 -4
  6. package/lib/edit-pipeline.js +4 -4
  7. package/lib/file-view.js +63 -0
  8. package/lib/guidance/index.js +8 -0
  9. package/lib/guidance/materialize.js +191 -0
  10. package/lib/guidance/parse.js +80 -0
  11. package/lib/guidance/resolve.js +122 -0
  12. package/lib/guidance.js +6 -388
  13. package/lib/hash-store.js +1 -2
  14. package/lib/hashline/anchor-pipeline.js +23 -0
  15. package/lib/hashline/hash-assign.js +20 -0
  16. package/lib/hashline/index.js +4 -5
  17. package/lib/hashline/resolve.js +5 -0
  18. package/lib/index.js +1 -1
  19. package/lib/mutation.js +58 -0
  20. package/lib/read-and-serve.js +23 -23
  21. package/lib/served-store.js +1 -1
  22. package/lib/session-view.js +34 -0
  23. package/lib/tool-batch-edit.js +9 -10
  24. package/lib/tool-edit.js +9 -11
  25. package/lib/tool-read.js +3 -5
  26. package/lib/tool-undo.js +6 -6
  27. package/lib/types/contract.d.ts +31 -0
  28. package/lib/types/edit-engine.d.ts +2 -2
  29. package/lib/types/edit-pipeline.d.ts +2 -2
  30. package/lib/types/file-view.d.ts +74 -0
  31. package/lib/types/guidance/index.d.ts +8 -0
  32. package/lib/types/guidance/materialize.d.ts +23 -0
  33. package/lib/types/guidance/parse.d.ts +36 -0
  34. package/lib/types/guidance/resolve.d.ts +55 -0
  35. package/lib/types/guidance.d.ts +6 -127
  36. package/lib/types/hashline/anchor-pipeline.d.ts +26 -0
  37. package/lib/types/hashline/hash-assign.d.ts +19 -0
  38. package/lib/types/hashline/index.d.ts +7 -5
  39. package/lib/types/hashline/resolve.d.ts +5 -0
  40. package/lib/types/mutation.d.ts +78 -0
  41. package/lib/types/read-and-serve.d.ts +6 -5
  42. package/lib/types/session-view.d.ts +33 -0
  43. package/lib/write-hook.js +2 -2
  44. package/package.json +1 -1
package/lib/guidance.js CHANGED
@@ -1,391 +1,9 @@
1
1
  /**
2
- * Per-preset guidance overrides for the hashline tool sections.
3
- *
4
- * Each of the four `tool:*` prompt sections the plugin registers has a
5
- * compiled default rendered from `prompts.ts` (byte-identical to the inline
6
- * rendering `src/index.ts` uses today). A user can override any section's text
7
- * and `order` with a plain markdown file keyed by agent preset: the override
8
- * files live in the plugin's shared home (`$DSH_HOME/plugins/dsh-better-edit`,
9
- * never the workspace store) and are resolved per section as
10
- * `<preset>/<section>.md` → compiled default.
11
- *
12
- * fence carrying only an `order` key (`---` / `order: N` / `---`). Any
13
- * well-formed fence — even keyless, even an empty body — is deliberate content
14
- * and wins. A leading `---` that does not parse (a missing closing fence, a
15
- * non-integer `order`, an unknown key) is a MALFORMED override and must never
16
- * reach the model: resolution falls back to the compiled default and reports
17
- * the file and parse reason. An absent or blank override (whitespace-only body,
18
- * no fence) means "use the default" and is re-seeded at boot.
19
- *
20
- * Resolution is pure: no cordis services, no harness wiring. The installer
21
- * ticket reads the resolved sections once per agent at session-start;
22
- * nothing here watches or caches files.
2
+ * Backwards-compat barrel — the real seams live in `src/guidance/`:
3
+ * `parse.ts` (pure), `resolve.ts` (IO-light), `materialize.ts` (IO-heavy).
4
+ * Keeping this file means existing `from "./guidance.js"` imports keep working.
23
5
  * @module dsh-better-edit/guidance
24
6
  */
25
- import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
26
- import { join } from "node:path";
27
- import { BATCH_EDIT_GUIDANCE, EDIT_GUIDANCE, READ_GUIDANCE, UNDO_GUIDANCE, } from "./prompts.js";
28
- import { errCode } from "./utils.js";
29
- /** The presets shipped by the harness, each seeded with editable guidance. */
30
- export const DEFAULT_PRESETS = [
31
- "standard",
32
- "code",
33
- "minimal",
34
- "cordis",
35
- ];
36
- /**
37
- * Render one tool's guidance as its intro line, a blank line, then bullets.
38
- * Uniform across the four sections: no tool-schema description is duplicated
39
- * (that already reaches the model through the tool catalog).
40
- */
41
- function guidanceText(g) {
42
- return [g.intro, "", bulletLines(g.lines)].join("\n");
43
- }
44
- function bulletLines(lines) {
45
- return lines.map((line) => `- ${line}`).join("\n");
46
- }
47
- /** The four sections, in default-order sequence. */
48
- export const GUIDANCE_SECTIONS = [
49
- {
50
- name: "tool:read",
51
- file: "read.md",
52
- defaultOrder: 130,
53
- renderDefault: () => guidanceText(READ_GUIDANCE),
54
- },
55
- {
56
- name: "tool:edit",
57
- file: "edit.md",
58
- defaultOrder: 131,
59
- renderDefault: () => guidanceText(EDIT_GUIDANCE),
60
- },
61
- {
62
- name: "tool:batch_edit",
63
- file: "batch_edit.md",
64
- defaultOrder: 132,
65
- renderDefault: () => guidanceText(BATCH_EDIT_GUIDANCE),
66
- },
67
- {
68
- name: "tool:undo_last_edit",
69
- file: "undo_last_edit.md",
70
- defaultOrder: 133,
71
- renderDefault: () => guidanceText(UNDO_GUIDANCE),
72
- },
73
- ];
74
- const SECTION_BY_NAME = new Map(GUIDANCE_SECTIONS.map((section) => [section.name, section]));
75
- /** Render the compiled default text for one section. */
76
- export function renderSectionDefault(name) {
77
- const section = SECTION_BY_NAME.get(name);
78
- if (!section)
79
- throw new Error(`unknown guidance section: ${name}`);
80
- return section.renderDefault();
81
- }
82
- function stripCR(line) {
83
- return line.endsWith("\r") ? line.slice(0, -1) : line;
84
- }
85
- /**
86
- * Parse an override file. Only a leading `---` fence whose lines are empty or
87
- * `order: <integer>` is accepted. A leading `---` that does not parse (no
88
- * closing fence, unknown key, non-integer value) is a malformed override;
89
- * anything else is pure prose (the whole file as text).
90
- */
91
- export function parseSectionFile(content) {
92
- const lines = content.split("\n");
93
- if (stripCR(lines[0]) !== "---") {
94
- return { text: content };
95
- }
96
- const close = lines.findIndex((line, index) => index > 0 && stripCR(line) === "---");
97
- if (close < 0) {
98
- return { text: content, malformed: true, reason: "missing closing fence" };
99
- }
100
- let order;
101
- for (let index = 1; index < close; index++) {
102
- const line = stripCR(lines[index]);
103
- if (line.trim() === "")
104
- continue;
105
- const key = line.split(":")[0].trim();
106
- const match = /^order:\s*(-?\d+)\s*$/.exec(line);
107
- if (!match) {
108
- if (key === "order") {
109
- const value = line.slice(line.indexOf(":") + 1).trim();
110
- return {
111
- text: content,
112
- malformed: true,
113
- reason: `non-integer order '${value}'`,
114
- };
115
- }
116
- return {
117
- text: content,
118
- malformed: true,
119
- reason: `unknown key '${key}'`,
120
- };
121
- }
122
- order = Number.parseInt(match[1], 10);
123
- }
124
- // Front-matter body: strip leading blank lines after the closing fence so
125
- // `---\n…\n---\n\nbody` and `---\n…\n---\nbody` parse identically (the
126
- // materialized preset files carry a blank line after the fence).
127
- const body = lines.slice(close + 1);
128
- let bodyStart = 0;
129
- while (bodyStart < body.length && body[bodyStart].trim() === "")
130
- bodyStart++;
131
- return { order, text: body.slice(bodyStart).join("\n") };
132
- }
133
- /**
134
- * True when an override file is blank: whitespace-only body and NO front-matter
135
- * fence (the "I want the default" case). The single source of truth for whether
136
- * a boot-time materialization pass should re-seed a file. False for prose with
137
- * content, for any valid fence (including a keyless/empty one — a deliberate
138
- * blank), and for malformed files.
139
- */
140
- export function isBlankOverride(content) {
141
- const parsed = parseSectionFile(content);
142
- return (!parsed.malformed &&
143
- parsed.order === undefined &&
144
- parsed.text.trim() === "" &&
145
- !startsWithFenceLine(content));
146
- }
147
- /** True when an override file opens with a leading `---` fence that is malformed. */
148
- export function isMalformedOverride(content) {
149
- return parseSectionFile(content).malformed === true;
150
- }
151
- function startsWithFenceLine(content) {
152
- return stripCR(content.split("\n")[0]) === "---";
153
- }
154
- function overrideCandidates(file, options) {
155
- const candidates = [];
156
- if (options.presetId !== undefined) {
157
- candidates.push(join(options.homeDir, options.presetId, file));
158
- }
159
- return candidates;
160
- }
161
- /**
162
- * Resolve one section's guidance: the first override file that exists wins,
163
- * falling back to the compiled default. A missing or blank file (ENOENT, or
164
- * whitespace-only with no fence) advances the chain; a malformed file resolves
165
- * to the compiled default and reports itself; any other read error propagates.
166
- */
167
- export async function resolveSection(name, options) {
168
- const section = SECTION_BY_NAME.get(name);
169
- if (!section)
170
- throw new Error(`unknown guidance section: ${name}`);
171
- for (const candidate of overrideCandidates(section.file, options)) {
172
- const content = await readFile(candidate, "utf-8").catch((error) => {
173
- if (errCode(error) === "ENOENT")
174
- return undefined;
175
- throw error;
176
- });
177
- if (content === undefined)
178
- continue;
179
- const parsed = parseSectionFile(content);
180
- if (parsed.malformed) {
181
- // A broken override must never reach the model. Resolve to the
182
- // compiled default and report the file + parse reason to the caller.
183
- return {
184
- order: section.defaultOrder,
185
- text: section.renderDefault(),
186
- malformed: {
187
- file: candidate,
188
- reason: parsed.reason ?? "malformed override",
189
- },
190
- };
191
- }
192
- // Blank (no fence, whitespace-only) means "use the default": advance the
193
- // fallback chain rather than render an empty section.
194
- if (isBlankOverride(content))
195
- continue;
196
- return { order: parsed.order ?? section.defaultOrder, text: parsed.text };
197
- }
198
- return { order: section.defaultOrder, text: section.renderDefault() };
199
- }
200
- /**
201
- * Resolve all four sections for a preset. `presetId === undefined` skips the
202
- * `<preset>/` layer and resolves straight to the compiled defaults.
203
- */
204
- export async function composeSections(presetId, homeDir) {
205
- return Promise.all(GUIDANCE_SECTIONS.map(async (section) => {
206
- const resolved = await resolveSection(section.name, {
207
- presetId,
208
- homeDir,
209
- });
210
- return {
211
- name: section.name,
212
- order: resolved.order,
213
- text: resolved.text,
214
- malformed: resolved.malformed,
215
- };
216
- }));
217
- }
218
- /**
219
- * The root README: the per-preset customization convention users see in the
220
- * plugin home.
221
- */
222
- export const GUIDANCE_HOME_README = `# dsh-better-edit guidance
223
-
224
- Each agent preset has its own guidance directory here: \`<preset>/<section>.md\`.
225
- On first boot the plugin seeds the shipped presets (\`standard\`, \`code\`,
226
- \`minimal\`, \`cordis\`) with the compiled defaults; existing files are never
227
- overwritten, so your edits survive.
228
-
229
- Each file is one tool section:
230
-
231
- - \`read.md\` -> \`tool:read\`
232
- - \`edit.md\` -> \`tool:edit\`
233
- - \`batch_edit.md\` -> \`tool:batch_edit\`
234
- - \`undo_last_edit.md\` -> \`tool:undo_last_edit\`
235
-
236
- ## Customize
237
-
238
- Edit the \`<section>.md\` file for the preset and section you want to change —
239
- the file body IS the text the model reads for that section. Files are read once
240
- per agent at session-start, so edits apply to new sessions.
241
-
242
- An optional YAML front-matter fence places the section at a custom position in
243
- the assembled system prompt:
244
-
245
- ---
246
- order: 150
247
- ---
248
-
249
- <section text>
250
-
251
- A file without front-matter keeps the default order. A malformed fence (a
252
- missing closing \`---\`, a non-integer \`order\`, an unknown key) makes the whole
253
- file plain prose.
254
-
255
- ## Fallback
256
-
257
- A preset with no directory here, or a missing section file, falls back to the
258
- compiled defaults in the plugin bundle. To customize a preset that has no
259
- seeded directory, copy a seeded one to its name.
260
- `;
261
- export const GUIDANCE_HOME_README_ZH = `# dsh-better-edit 指引
262
-
263
- 每个 agent preset 在这里都有自己的指引目录:\`<preset>/<section>.md\`。首次启动时
264
- 插件会为随附的 preset(\`standard\`、\`code\`、\`minimal\`、\`cordis\`)写入编译内置的
265
- 默认内容;已有文件绝不被覆盖,因此你的编辑会保留。
266
-
267
- 每个文件对应一个工具片段:
268
-
269
- - \`read.md\` -> \`tool:read\`
270
- - \`edit.md\` -> \`tool:edit\`
271
- - \`batch_edit.md\` -> \`tool:batch_edit\`
272
- - \`undo_last_edit.md\` -> \`tool:undo_last_edit\`
273
-
274
- ## 自定义
275
-
276
- 编辑你想修改的 preset 与片段的 \`<section>.md\` 文件即可——文件正文就是该片段呈
277
- 现给模型的文本。文件在 agent 的 session-start 时读取一次,因此修改只影响新会话。
278
-
279
- 可以用可选的 YAML front-matter 栅栏把片段放到组装后系统提示中的自定义位置:
280
-
281
- ---
282
- order: 150
283
- ---
284
-
285
- <片段文本>
286
-
287
- 没有 front-matter 的文件保持默认顺序。格式错误的栅栏(缺少收尾 \`---\`、非整数
288
- \`order\`、未知键)会让整个文件退化为纯文本。
289
-
290
- ## 回退
291
-
292
- 这里没有对应目录的 preset、或缺失某个片段文件时,会回退到插件包内的编译内置默认
293
- 值。要自定义没有种子目录的 preset,把一个种子目录复制成它的名字即可。
294
- `;
295
- /**
296
- * Materialize per-preset guidance directories in the plugin home.
297
- *
298
- * For each of \`DEFAULT_PRESETS\` creates \`<preset>/{read,edit,batch_edit,
299
- * undo_last_edit}.md\` rendered from the compiled defaults (with order
300
- * front-matter), plus a root \`README.md\` documenting the convention.
301
- * Idempotent: a user-edited file survives repeated calls. A blank override file
302
- * (whitespace-only body, no fence) is re-seeded with the current compiled
303
- * default; malformed, non-blank, and deliberate-blank (valid-fence) files are
304
- * never touched. Custom preset directories present on disk are scanned the same
305
- * way but never fabricated. Missing directories are created on demand (shipped
306
- * presets only), and shipped files are written exclusively so two concurrent
307
- * first runs race safely.
308
- */
309
- export async function ensurePresetGuidance(homeDir) {
310
- await mkdir(homeDir, { recursive: true });
311
- await Promise.all(DEFAULT_PRESETS.map(async (preset) => {
312
- const dir = join(homeDir, preset);
313
- await mkdir(dir, { recursive: true });
314
- const existing = new Set(await readdir(dir));
315
- await Promise.all(GUIDANCE_SECTIONS.map(async (section) => {
316
- const path = join(dir, section.file);
317
- if (existing.has(section.file)) {
318
- await healBlankOverride(path, section);
319
- return;
320
- }
321
- await writeFile(path, seededContent(section), {
322
- encoding: "utf-8",
323
- flag: "wx",
324
- }).catch((error) => {
325
- // A concurrent writer landed first; never clobber it.
326
- if (errCode(error) === "EEXIST")
327
- return;
328
- throw error;
329
- });
330
- }));
331
- }));
332
- // Custom presets present on disk: heal existing blank section files only.
333
- // Absence is respected — a custom preset's files are never fabricated, and
334
- // malformed / non-blank / deliberate-blank files are left untouched.
335
- const entries = await readdir(homeDir, { withFileTypes: true });
336
- await Promise.all(entries
337
- .filter((entry) => entry.isDirectory() && !DEFAULT_PRESETS.includes(entry.name))
338
- .map(async (entry) => {
339
- const dir = join(homeDir, entry.name);
340
- const existing = new Set(await readdir(dir));
341
- await Promise.all(GUIDANCE_SECTIONS.map(async (section) => {
342
- if (!existing.has(section.file))
343
- return;
344
- await healBlankOverride(join(dir, section.file), section);
345
- }));
346
- }));
347
- const homeFiles = new Set(await readdir(homeDir));
348
- const readmes = [
349
- ["README.md", GUIDANCE_HOME_README],
350
- ["README.zh.md", GUIDANCE_HOME_README_ZH],
351
- ];
352
- await Promise.all(readmes.map(async ([file, content]) => {
353
- if (homeFiles.has(file))
354
- return;
355
- await writeFile(join(homeDir, file), content, {
356
- encoding: "utf-8",
357
- flag: "wx",
358
- }).catch((error) => {
359
- if (errCode(error) === "EEXIST")
360
- return;
361
- throw error;
362
- });
363
- }));
364
- }
365
- /** The content a seeded override file carries, rendered from the current defaults. */
366
- function seededContent(section) {
367
- return `---\norder: ${section.defaultOrder}\n---\n\n${section.renderDefault()}`;
368
- }
369
- /**
370
- * Heal an existing empty override file: a blank file means "use the default",
371
- * so it is rewritten with the current seeded default. Malformed, non-blank, and
372
- * deliberate-blank (valid-fence) files are left untouched — overwriting a
373
- * malformed file would destroy the user's salvageable body. Plain overwrite:
374
- * the file already exists. Errors propagate to the boot caller, which never
375
- * fails init.
376
- */
377
- async function healBlankOverride(path, section) {
378
- let content;
379
- try {
380
- content = await readFile(path, "utf-8");
381
- }
382
- catch (error) {
383
- // Vanished between readdir and read; nothing to heal.
384
- if (errCode(error) === "ENOENT")
385
- return;
386
- throw error;
387
- }
388
- if (!isBlankOverride(content))
389
- return;
390
- await writeFile(path, seededContent(section), { encoding: "utf-8" });
391
- }
7
+ export * from "./guidance/parse.js";
8
+ export * from "./guidance/resolve.js";
9
+ export * from "./guidance/materialize.js";
package/lib/hash-store.js CHANGED
@@ -20,8 +20,7 @@ import { DatabaseSync } from "node:sqlite";
20
20
  import { hashStorePath } from "./paths.js";
21
21
  import { workspaceCwd } from "./workspace.js";
22
22
  import { errCode, splitLines } from "./utils.js";
23
- import { initHasher, contentChecksum } from "./hashline/hasher.js";
24
- import { HASH_RE } from "./hashline/alphabet.js";
23
+ import { initHasher, contentChecksum, HASH_RE } from "./hashline/hash-assign.js";
25
24
  import { HASH_STORE_VERSION, HASH_STORE_BUSY_TIMEOUT, SERVED_TTL_MS } from "./constants.js";
26
25
  export function isValidHashList(value) {
27
26
  if (!Array.isArray(value))
@@ -0,0 +1,23 @@
1
+ /**
2
+ * AnchorPipeline — deep module owning the anchor autofix chain.
3
+ *
4
+ * Single ordering invariant (private):
5
+ * swapReversed → stripBare → stripDiff → valEdit → boundaryDups splice → valEdit → verifyServed → resToSpan
6
+ *
7
+ * Detection (valEdit → boundaryDups[]) and correction (splice + second valEdit)
8
+ * were split across resolve.ts / apply.ts with an implicit coupling.
9
+ * This seam co-locates that invariant. Public surface is two functions:
10
+ * resEdit — pre-validation (tool-layer, no file state)
11
+ * applyEdit — full pipeline (file + hashes + served verification)
12
+ *
13
+ * Private to this seam (not re-exported): stripBarePrefixes, stripDiffPrefixes,
14
+ * swapReversedRanges, valEdit, boundaryDups helpers, warnUnicodeEsc, findNewEdge.
15
+ * They remain exported from resolve.ts for backwards compat but are marked
16
+ * @internal and should be imported via this module only.
17
+ *
18
+ * @module dsh-better-edit/hashline/anchor-pipeline
19
+ */
20
+ export { resEdit } from "./resolve.js";
21
+ export { applyEdit, fmtRegion, changedRange, buildIdx } from "./apply.js";
22
+ export { parseHashRef, parseText } from "./parse.js";
23
+ export { ServedRejectionError, AnchorMismatchError, isServedRejection, isAnchorMismatch, verifyServedRange, buildRangeEcho, fmtServedRows, recordEchoServes, } from "./served.js";
@@ -0,0 +1,20 @@
1
+ /**
2
+ * HashAssign — deep module owning hash assignment.
3
+ *
4
+ * Owns the `HASH_SPACE = 62^3` allocation invariant: every line of a file
5
+ * gets a unique 3-char anchor derived from canonicalized content via xxHash
6
+ * + probe-stride allocation. The triad `alphabet + hasher + pure + hash`
7
+ * is interdependent; this seam hides that coupling.
8
+ *
9
+ * Private internals (not re-exported as public API): ALPH, idxToHash/hashAt,
10
+ * nextZeroBit/assignHash, getBit/setBit, hashToIndex/nearestNew, xxh32 internals.
11
+ * Callers use the deep interface below — one test surface for determinism +
12
+ * stable mapping + persistence.
13
+ *
14
+ * @module dsh-better-edit/hashline/hash-assign
15
+ */
16
+ // --- re-exports from the underlying files (canonical surface is this module) ---
17
+ export { ANCHOR_LEN, HASH_SEP, HASH_SPACE, HASH_PROBE_STRIDE, MAX_HASH_LINES, HL_PREFIX_PLUS_RE, HL_PREFIX_MINUS_RE, HL_BARE_PREFIX_RE, ALPH_RE, HASH_CLASS, HASH_LEN, canon, lineHashesPure, mapStableHashes, initHasher, } from "./pure.js";
18
+ export { HASH_RE } from "./alphabet.js";
19
+ export { contentChecksum } from "./hasher.js";
20
+ export { lineHashes } from "./hash.js";
@@ -1,5 +1,4 @@
1
- export { ANCHOR_LEN, HASH_SEP, HASH_SPACE, HASH_PROBE_STRIDE, MAX_HASH_LINES, lineHashesPure, initHasher, canon, } from "./pure.js";
2
- export { lineHashes } from "./hash.js";
3
- export { parseHashRef, parseText, } from "./parse.js";
4
- export { resEdit, } from "./resolve.js";
5
- export { applyEdit, fmtRegion, changedRange, } from "./apply.js";
1
+ export { ANCHOR_LEN, HASH_SEP, HASH_SPACE, HASH_PROBE_STRIDE, MAX_HASH_LINES, HASH_LEN, HASH_CLASS, HASH_RE, ALPH_RE, HL_PREFIX_PLUS_RE, HL_PREFIX_MINUS_RE, HL_BARE_PREFIX_RE, canon, lineHashesPure, mapStableHashes, initHasher, lineHashes, contentChecksum, } from "./hash-assign.js";
2
+ export { parseHashRef, parseText } from "./parse.js";
3
+ export { resEdit } from "./anchor-pipeline.js";
4
+ export { applyEdit, fmtRegion, changedRange, buildIdx, ServedRejectionError, AnchorMismatchError, isServedRejection, isAnchorMismatch, verifyServedRange, buildRangeEcho, fmtServedRows, } from "./anchor-pipeline.js";
@@ -129,6 +129,7 @@ function warnUnicodeEsc(edit, warnings) {
129
129
  warnings.push("Detected literal \\uDDDD in edit content; no autocorrection applied. Verify whether this should be a real Unicode escape or plain text.");
130
130
  }
131
131
  }
132
+ /** @internal — private to anchor-pipeline seam; do not import directly, use anchor-pipeline.ts */
132
133
  export function stripBarePrefixes(edit, fileHashes, warnings) {
133
134
  const fileHashSet = new Set(fileHashes);
134
135
  const stripped = [];
@@ -154,6 +155,7 @@ export function stripBarePrefixes(edit, fileHashes, warnings) {
154
155
  warnings.push(`[E_BARE_HASH_PREFIX] Autocorrected: stripped "HASH│" prefix copied from read output in ${locations} (${evidence}).${guidance}`);
155
156
  return { ...edit, content_lines: contentLines };
156
157
  }
158
+ /** @internal — private to anchor-pipeline seam */
157
159
  export function stripDiffPrefixes(edit, warnings) {
158
160
  const stripped = [];
159
161
  const contentLines = edit.content_lines.map((line, lineIndex) => {
@@ -177,6 +179,7 @@ export function stripDiffPrefixes(edit, warnings) {
177
179
  warnings.push(`[E_INVALID_PATCH] Autocorrected: stripped diff-preview marker copied from the diff preview in ${locations}.`);
178
180
  return { ...edit, content_lines: contentLines };
179
181
  }
182
+ /** @internal — private to anchor-pipeline seam */
180
183
  export function swapReversedRanges(edit, fileHashes, warnings) {
181
184
  const lineByHash = new Map();
182
185
  for (let i = 0; i < fileHashes.length; i++) {
@@ -288,6 +291,7 @@ function canonCounts(lines) {
288
291
  }
289
292
  return counts;
290
293
  }
294
+ /** @internal — private to anchor-pipeline seam */
291
295
  export function findNewEdge(contentLines, rangeLines, fromEnd) {
292
296
  const multiset = canonCounts(rangeLines);
293
297
  const step = fromEnd ? -1 : 1;
@@ -307,6 +311,7 @@ export function findNewEdge(contentLines, rangeLines, fromEnd) {
307
311
  }
308
312
  return undefined;
309
313
  }
314
+ /** @internal — private to anchor-pipeline seam: detection + boundaryDups belongs to AnchorPipeline ordering */
310
315
  export function valEdit(edit, fileLines, fileHashes, warnings, signal) {
311
316
  assertAligned(fileLines, fileHashes, "valEdit");
312
317
  const mismatches = [];
package/lib/index.js CHANGED
@@ -22,7 +22,7 @@ import { registerEditTool } from "./tool-edit.js";
22
22
  import { registerBatchEditTool } from "./tool-batch-edit.js";
23
23
  import { registerUndoTool } from "./tool-undo.js";
24
24
  import { registerWriteHook } from "./write-hook.js";
25
- import { initHasher } from "./hashline/hasher.js";
25
+ import { initHasher } from "./hashline/hash-assign.js";
26
26
  import { composeSections, ensurePresetGuidance, GUIDANCE_SECTIONS, } from "./guidance.js";
27
27
  import { configDir } from "./paths.js";
28
28
  /** Cordis plugin name used by loader diagnostics. */
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Mutation — deep module owning the full file mutation lifecycle.
3
+ *
4
+ * Previously fragmented: tool-edit → edit-pipeline → edit-engine.applyOne →
5
+ * edit-response/diff/drift, and tool-batch-edit → edit-engine.runFileEdits
6
+ * (loop + unionRange + counters) → persistUndoAndWrite with a boolean flag.
7
+ * Warnings, hadUtf8DecodeErrors, firstChangedLine, driftNotice were threaded
8
+ * by mutation across 5 hops; bugs hid in wiring, not pure helpers.
9
+ *
10
+ * This seam owns: read → normalize → loadServed → applyOne* → stableRehash →
11
+ * drift → persist. Tools become thin adapters: validate → delegate → render.
12
+ * edit-diff, drift, noop-guard are private helpers of this seam.
13
+ *
14
+ * Public surface:
15
+ * applySingle(io, params, {cwd, sessionKey, signal}) → PipelineResult
16
+ * applySequence(io, items, {cwd, sessionKey, signal}) → FileEditResult[]
17
+ * commit(io, files, {exec, sandboxPolicy, signal}) → void
18
+ *
19
+ * Internals (private): verifyServedRange, resToSpan, assemble, scanDrift,
20
+ * boundaryDups, noopGuard. Tested via PipelineResult/FileEditResult, not via split e2e.
21
+ *
22
+ * @module dsh-better-edit/mutation
23
+ */
24
+ import { execPipeline, snapshotIdFor } from "./edit-pipeline.js";
25
+ import { runFileEdits, resolveMissingPath, persistUndoAndWrite, enforceNoopLoop, collectRemovedHashes, countLineChanges, } from "./edit-engine.js";
26
+ import { buildMetrics, buildNoop, buildChanged, buildBatchResult } from "./edit-response.js";
27
+ import { genDiff, restoreEndings, toLF, stripBOM } from "./edit-diff.js";
28
+ import { computeDrift, scanDrift } from "./drift.js";
29
+ import { trackNoopPayload, clearNoopLoop, noopPayloadKey } from "./noop-guard.js";
30
+ // Re-exports for callers that need the underlying types/helpers
31
+ export { execPipeline, snapshotIdFor };
32
+ export { runFileEdits, resolveMissingPath, persistUndoAndWrite, enforceNoopLoop, collectRemovedHashes, countLineChanges };
33
+ export { buildMetrics, buildNoop, buildChanged, buildBatchResult };
34
+ export { genDiff, restoreEndings, toLF, stripBOM };
35
+ export { computeDrift, scanDrift };
36
+ export { trackNoopPayload, clearNoopLoop, noopPayloadKey };
37
+ // --- Deep seam: unified mutation API (one interface, twoAdapters) ---
38
+ /** Apply a single edit — owns read→normalize→loadServed→applyOne→stableRehash→drift. */
39
+ export async function applySingle(io, params, cwd, opts) {
40
+ return execPipeline(io, params, cwd, opts);
41
+ }
42
+ /** Apply a per-file sequence (batch's group) — owns the loop + unionRange + counters. */
43
+ export async function applySequence(io, items, ctx) {
44
+ return runFileEdits(io, items, ctx);
45
+ }
46
+ /** Commit the transaction — owns persist-undo → write → restore. */
47
+ export async function commit(opts) {
48
+ return persistUndoAndWrite({
49
+ io: opts.io,
50
+ files: opts.files,
51
+ exec: opts.exec,
52
+ sandbox: opts.sandbox,
53
+ sandboxPolicy: opts.sandboxPolicy,
54
+ signal: opts.signal,
55
+ undoUnavailableMessage: opts.undoUnavailableMessage,
56
+ restoreUnwrittenUndos: opts.restoreUnwrittenUndos,
57
+ });
58
+ }
@@ -1,15 +1,15 @@
1
1
  /**
2
- * The shared read-and-serve operation: resolve → read → normalize → render
3
- * the hashline preview → record the served rows → clear the drift marks →
4
- * append the UTF-8 rewrite note. Used by the `read` tool and by the write
5
- * auto-read hook, so the model is always shown fresh anchors the same way no
6
- * matter which tool produced the read.
2
+ * The shared read-and-serve operation — now a thin wrapper over FileView.
3
+ *
4
+ * FileView owns normalize → hash → render → truncate → served selection.
5
+ * This module only adds the persistence seam: recordServed + clearDriftReported
6
+ * + UTF-8 rewrite note. Used by the `read` tool and by the write auto-read
7
+ * hook, so the model is always shown fresh anchors the same way.
7
8
  * @module dsh-better-edit/read-and-serve
8
9
  */
9
10
  import { abortIf } from "./utils.js";
10
- import { normFromText } from "./file-reader.js";
11
- import { fmtReadPreview, MAX_HASH_LINES } from "./read-render.js";
12
- import { recordServed, clearDriftReported } from "./served-store.js";
11
+ import { readView } from "./file-view.js";
12
+ import { recordServed, clearDriftReported } from "./session-view.js";
13
13
  /** Appended when the file had non-UTF-8 bytes; editing rewrites it as UTF-8. */
14
14
  export const UTF8_REWRITE_NOTE = "[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]";
15
15
  /**
@@ -25,22 +25,22 @@ export const UTF8_REWRITE_NOTE = "[Non-UTF-8 bytes shown as U+FFFD; editing rewr
25
25
  export async function readAndServe(io, rawPath, cwd, options) {
26
26
  const { sessionKey, signal } = options;
27
27
  abortIf(signal);
28
- const absolutePath = await io.resolve(rawPath, cwd, signal);
29
- const rawText = await io.readText(absolutePath, signal);
30
- const { normalized, fileHashes, hadUtf8DecodeErrors } = await normFromText({
31
- absolutePath,
32
- rawText,
33
- displayPath: rawPath,
28
+ const view = await readView(io, rawPath, cwd, {
29
+ offset: options.offset,
30
+ limit: options.limit,
34
31
  signal,
35
- maxLines: MAX_HASH_LINES,
36
32
  });
37
- const preview = await fmtReadPreview(normalized, { offset: options.offset, limit: options.limit }, fileHashes, absolutePath);
38
- if (preview.served.length > 0) {
39
- await recordServed(sessionKey, absolutePath, preview.served, fileHashes.length);
33
+ if (view.served.length > 0) {
34
+ await recordServed(sessionKey, view.absolutePath, view.served, view.hashes.length);
40
35
  }
41
- await clearDriftReported(sessionKey, absolutePath);
42
- const text = hadUtf8DecodeErrors
43
- ? `${preview.text}\n\n${UTF8_REWRITE_NOTE}`
44
- : preview.text;
45
- return { text, served: preview.served, hadUtf8DecodeErrors, absolutePath };
36
+ await clearDriftReported(sessionKey, view.absolutePath);
37
+ const text = view.hadUtf8DecodeErrors
38
+ ? `${view.text}\n\n${UTF8_REWRITE_NOTE}`
39
+ : view.text;
40
+ return {
41
+ text,
42
+ served: view.served,
43
+ hadUtf8DecodeErrors: view.hadUtf8DecodeErrors,
44
+ absolutePath: view.absolutePath,
45
+ };
46
46
  }
@@ -15,7 +15,7 @@
15
15
  * @module dsh-better-edit/served-store
16
16
  */
17
17
  import { randomUUID } from "node:crypto";
18
- import { HASH_RE } from "./hashline/alphabet.js";
18
+ import { HASH_RE } from "./hashline/hash-assign.js";
19
19
  import { loadHashStore, withStore } from "./hash-store.js";
20
20
  let fallbackSessionKey;
21
21
  /**