dsh-better-edit 0.2.1 → 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 +18 -0
  2. package/README.md +327 -238
  3. package/README.zh.md +44 -16
  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 -279
  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 +10 -2
  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 -95
  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 +2 -10
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Resolver: IO-light seam owning "first existing candidate wins, blank=skip,
3
+ * malformed=fallback+report" policy for guidance override files.
4
+ *
5
+ * Tested via temp-home FS; materializer stubs this module.
6
+ * @module dsh-better-edit/guidance/resolve
7
+ */
8
+ import { readFile } from "node:fs/promises";
9
+ import { join } from "node:path";
10
+ import { BATCH_EDIT_GUIDANCE, EDIT_GUIDANCE, READ_GUIDANCE, UNDO_GUIDANCE, } from "../prompts.js";
11
+ import { errCode } from "../utils.js";
12
+ import { isBlankOverride, parseSectionFile } from "./parse.js";
13
+ /**
14
+ * Render one tool's guidance as its intro line, a blank line, then bullets.
15
+ * Uniform across the four sections: no tool-schema description is duplicated
16
+ * (that already reaches the model through the tool catalog).
17
+ */
18
+ function guidanceText(g) {
19
+ return [g.intro, "", bulletLines(g.lines)].join("\n");
20
+ }
21
+ function bulletLines(lines) {
22
+ return lines.map((line) => `- ${line}`).join("\n");
23
+ }
24
+ /** The four sections, in default-order sequence. */
25
+ export const GUIDANCE_SECTIONS = [
26
+ {
27
+ name: "tool:read",
28
+ file: "read.md",
29
+ defaultOrder: 130,
30
+ renderDefault: () => guidanceText(READ_GUIDANCE),
31
+ },
32
+ {
33
+ name: "tool:edit",
34
+ file: "edit.md",
35
+ defaultOrder: 131,
36
+ renderDefault: () => guidanceText(EDIT_GUIDANCE),
37
+ },
38
+ {
39
+ name: "tool:batch_edit",
40
+ file: "batch_edit.md",
41
+ defaultOrder: 132,
42
+ renderDefault: () => guidanceText(BATCH_EDIT_GUIDANCE),
43
+ },
44
+ {
45
+ name: "tool:undo_last_edit",
46
+ file: "undo_last_edit.md",
47
+ defaultOrder: 133,
48
+ renderDefault: () => guidanceText(UNDO_GUIDANCE),
49
+ },
50
+ ];
51
+ const SECTION_BY_NAME = new Map(GUIDANCE_SECTIONS.map((section) => [section.name, section]));
52
+ /** Render the compiled default text for one section. */
53
+ export function renderSectionDefault(name) {
54
+ const section = SECTION_BY_NAME.get(name);
55
+ if (!section)
56
+ throw new Error(`unknown guidance section: ${name}`);
57
+ return section.renderDefault();
58
+ }
59
+ function overrideCandidates(file, options) {
60
+ const candidates = [];
61
+ if (options.presetId !== undefined) {
62
+ candidates.push(join(options.homeDir, options.presetId, file));
63
+ }
64
+ return candidates;
65
+ }
66
+ /**
67
+ * Resolve one section's guidance: the first override file that exists wins,
68
+ * falling back to the compiled default. A missing or blank file (ENOENT, or
69
+ * whitespace-only with no fence) advances the chain; a malformed file resolves
70
+ * to the compiled default and reports itself; any other read error propagates.
71
+ */
72
+ export async function resolveSection(name, options) {
73
+ const section = SECTION_BY_NAME.get(name);
74
+ if (!section)
75
+ throw new Error(`unknown guidance section: ${name}`);
76
+ for (const candidate of overrideCandidates(section.file, options)) {
77
+ const content = await readFile(candidate, "utf-8").catch((error) => {
78
+ if (errCode(error) === "ENOENT")
79
+ return undefined;
80
+ throw error;
81
+ });
82
+ if (content === undefined)
83
+ continue;
84
+ const parsed = parseSectionFile(content);
85
+ if (parsed.malformed) {
86
+ // A broken override must never reach the model. Resolve to the
87
+ // compiled default and report the file + parse reason to the caller.
88
+ return {
89
+ order: section.defaultOrder,
90
+ text: section.renderDefault(),
91
+ malformed: {
92
+ file: candidate,
93
+ reason: parsed.reason ?? "malformed override",
94
+ },
95
+ };
96
+ }
97
+ // Blank (no fence, whitespace-only) means "use the default": advance the
98
+ // fallback chain rather than render an empty section.
99
+ if (isBlankOverride(content))
100
+ continue;
101
+ return { order: parsed.order ?? section.defaultOrder, text: parsed.text };
102
+ }
103
+ return { order: section.defaultOrder, text: section.renderDefault() };
104
+ }
105
+ /**
106
+ * Resolve all four sections for a preset. `presetId === undefined` skips the
107
+ * `<preset>/` layer and resolves straight to the compiled defaults.
108
+ */
109
+ export async function composeSections(presetId, homeDir) {
110
+ return Promise.all(GUIDANCE_SECTIONS.map(async (section) => {
111
+ const resolved = await resolveSection(section.name, {
112
+ presetId,
113
+ homeDir,
114
+ });
115
+ return {
116
+ name: section.name,
117
+ order: resolved.order,
118
+ text: resolved.text,
119
+ malformed: resolved.malformed,
120
+ };
121
+ }));
122
+ }
package/lib/guidance.js CHANGED
@@ -1,282 +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
- * An override file is pure prose unless it opens with a valid YAML front-matter
13
- * fence carrying only an `order` key (`---` / `order: N` / `---`); anything
14
- * else — a missing closing fence, a non-integer `order`, an unknown key —
15
- * degrades the WHOLE file to prose so the mistake stays visible in the
16
- * rendered section.
17
- *
18
- * Resolution is pure: no cordis services, no harness wiring. The installer
19
- * ticket reads the resolved sections once per agent at session-start;
20
- * 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.
21
5
  * @module dsh-better-edit/guidance
22
6
  */
23
- import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
24
- import { join } from "node:path";
25
- import { BATCH_EDIT_GUIDANCE, EDIT_GUIDANCE, READ_GUIDANCE, UNDO_GUIDANCE, } from "./prompts.js";
26
- import { errCode } from "./utils.js";
27
- /** The presets shipped by the harness, each seeded with editable guidance. */
28
- export const DEFAULT_PRESETS = [
29
- "standard",
30
- "code",
31
- "minimal",
32
- "cordis",
33
- ];
34
- /**
35
- * Render one tool's guidance as its intro line, a blank line, then bullets.
36
- * Uniform across the four sections: no tool-schema description is duplicated
37
- * (that already reaches the model through the tool catalog).
38
- */
39
- function guidanceText(g) {
40
- return [g.intro, "", bulletLines(g.lines)].join("\n");
41
- }
42
- function bulletLines(lines) {
43
- return lines.map((line) => `- ${line}`).join("\n");
44
- }
45
- /** The four sections, in default-order sequence. */
46
- export const GUIDANCE_SECTIONS = [
47
- {
48
- name: "tool:read",
49
- file: "read.md",
50
- defaultOrder: 130,
51
- renderDefault: () => guidanceText(READ_GUIDANCE),
52
- },
53
- {
54
- name: "tool:edit",
55
- file: "edit.md",
56
- defaultOrder: 131,
57
- renderDefault: () => guidanceText(EDIT_GUIDANCE),
58
- },
59
- {
60
- name: "tool:batch_edit",
61
- file: "batch_edit.md",
62
- defaultOrder: 132,
63
- renderDefault: () => guidanceText(BATCH_EDIT_GUIDANCE),
64
- },
65
- {
66
- name: "tool:undo_last_edit",
67
- file: "undo_last_edit.md",
68
- defaultOrder: 133,
69
- renderDefault: () => guidanceText(UNDO_GUIDANCE),
70
- },
71
- ];
72
- const SECTION_BY_NAME = new Map(GUIDANCE_SECTIONS.map((section) => [section.name, section]));
73
- /** Render the compiled default text for one section. */
74
- export function renderSectionDefault(name) {
75
- const section = SECTION_BY_NAME.get(name);
76
- if (!section)
77
- throw new Error(`unknown guidance section: ${name}`);
78
- return section.renderDefault();
79
- }
80
- function stripCR(line) {
81
- return line.endsWith("\r") ? line.slice(0, -1) : line;
82
- }
83
- /**
84
- * Parse an override file. Only a leading `---` fence whose lines are empty or
85
- * `order: <integer>` is accepted; every other shape (no fence, no closing
86
- * fence, unknown key, non-integer value) yields the whole file as prose.
87
- */
88
- export function parseSectionFile(content) {
89
- const lines = content.split("\n");
90
- if (lines.length < 3 || stripCR(lines[0]) !== "---") {
91
- return { text: content };
92
- }
93
- const close = lines.findIndex((line, index) => index > 0 && stripCR(line) === "---");
94
- if (close < 0)
95
- return { text: content };
96
- let order;
97
- for (let index = 1; index < close; index++) {
98
- const line = stripCR(lines[index]);
99
- if (line.trim() === "")
100
- continue;
101
- const match = /^order:\s*(-?\d+)\s*$/.exec(line);
102
- if (!match)
103
- return { text: content };
104
- order = Number.parseInt(match[1], 10);
105
- }
106
- // Front-matter body: strip leading blank lines after the closing fence so
107
- // `---\n…\n---\n\nbody` and `---\n…\n---\nbody` parse identically (the
108
- // materialized preset files carry a blank line after the fence).
109
- const body = lines.slice(close + 1);
110
- let bodyStart = 0;
111
- while (bodyStart < body.length && body[bodyStart].trim() === "")
112
- bodyStart++;
113
- return { order, text: body.slice(bodyStart).join("\n") };
114
- }
115
- function overrideCandidates(file, options) {
116
- const candidates = [];
117
- if (options.presetId !== undefined) {
118
- candidates.push(join(options.homeDir, options.presetId, file));
119
- }
120
- return candidates;
121
- }
122
- /**
123
- * Resolve one section's guidance: the first override file that exists wins,
124
- * falling back to the compiled default. A missing file (ENOENT) advances the
125
- * chain; any other read error propagates.
126
- */
127
- export async function resolveSection(name, options) {
128
- const section = SECTION_BY_NAME.get(name);
129
- if (!section)
130
- throw new Error(`unknown guidance section: ${name}`);
131
- for (const candidate of overrideCandidates(section.file, options)) {
132
- const content = await readFile(candidate, "utf-8").catch((error) => {
133
- if (errCode(error) === "ENOENT")
134
- return undefined;
135
- throw error;
136
- });
137
- if (content === undefined)
138
- continue;
139
- const parsed = parseSectionFile(content);
140
- return { order: parsed.order ?? section.defaultOrder, text: parsed.text };
141
- }
142
- return { order: section.defaultOrder, text: section.renderDefault() };
143
- }
144
- /**
145
- * Resolve all four sections for a preset. `presetId === undefined` skips the
146
- * `<preset>/` layer and resolves straight to the compiled defaults.
147
- */
148
- export async function composeSections(presetId, homeDir) {
149
- return Promise.all(GUIDANCE_SECTIONS.map(async (section) => {
150
- const { order, text } = await resolveSection(section.name, {
151
- presetId,
152
- homeDir,
153
- });
154
- return { name: section.name, order, text };
155
- }));
156
- }
157
- /**
158
- * The root README: the per-preset customization convention users see in the
159
- * plugin home.
160
- */
161
- export const GUIDANCE_HOME_README = `# dsh-better-edit guidance
162
-
163
- Each agent preset has its own guidance directory here: \`<preset>/<section>.md\`.
164
- On first boot the plugin seeds the shipped presets (\`standard\`, \`code\`,
165
- \`minimal\`, \`cordis\`) with the compiled defaults; existing files are never
166
- overwritten, so your edits survive.
167
-
168
- Each file is one tool section:
169
-
170
- - \`read.md\` -> \`tool:read\`
171
- - \`edit.md\` -> \`tool:edit\`
172
- - \`batch_edit.md\` -> \`tool:batch_edit\`
173
- - \`undo_last_edit.md\` -> \`tool:undo_last_edit\`
174
-
175
- ## Customize
176
-
177
- Edit the \`<section>.md\` file for the preset and section you want to change —
178
- the file body IS the text the model reads for that section. Files are read once
179
- per agent at session-start, so edits apply to new sessions.
180
-
181
- An optional YAML front-matter fence places the section at a custom position in
182
- the assembled system prompt:
183
-
184
- ---
185
- order: 150
186
- ---
187
-
188
- <section text>
189
-
190
- A file without front-matter keeps the default order. A malformed fence (a
191
- missing closing \`---\`, a non-integer \`order\`, an unknown key) makes the whole
192
- file plain prose.
193
-
194
- ## Fallback
195
-
196
- A preset with no directory here, or a missing section file, falls back to the
197
- compiled defaults in the plugin bundle. To customize a preset that has no
198
- seeded directory, copy a seeded one to its name.
199
- `;
200
- export const GUIDANCE_HOME_README_ZH = `# dsh-better-edit 指引
201
-
202
- 每个 agent preset 在这里都有自己的指引目录:\`<preset>/<section>.md\`。首次启动时
203
- 插件会为随附的 preset(\`standard\`、\`code\`、\`minimal\`、\`cordis\`)写入编译内置的
204
- 默认内容;已有文件绝不被覆盖,因此你的编辑会保留。
205
-
206
- 每个文件对应一个工具片段:
207
-
208
- - \`read.md\` -> \`tool:read\`
209
- - \`edit.md\` -> \`tool:edit\`
210
- - \`batch_edit.md\` -> \`tool:batch_edit\`
211
- - \`undo_last_edit.md\` -> \`tool:undo_last_edit\`
212
-
213
- ## 自定义
214
-
215
- 编辑你想修改的 preset 与片段的 \`<section>.md\` 文件即可——文件正文就是该片段呈
216
- 现给模型的文本。文件在 agent 的 session-start 时读取一次,因此修改只影响新会话。
217
-
218
- 可以用可选的 YAML front-matter 栅栏把片段放到组装后系统提示中的自定义位置:
219
-
220
- ---
221
- order: 150
222
- ---
223
-
224
- <片段文本>
225
-
226
- 没有 front-matter 的文件保持默认顺序。格式错误的栅栏(缺少收尾 \`---\`、非整数
227
- \`order\`、未知键)会让整个文件退化为纯文本。
228
-
229
- ## 回退
230
-
231
- 这里没有对应目录的 preset、或缺失某个片段文件时,会回退到插件包内的编译内置默认
232
- 值。要自定义没有种子目录的 preset,把一个种子目录复制成它的名字即可。
233
- `;
234
- /**
235
- * Materialize per-preset guidance directories in the plugin home.
236
- *
237
- * For each of \`DEFAULT_PRESETS\` creates \`<preset>/{read,edit,batch_edit,
238
- * undo_last_edit}.md\` rendered from the compiled defaults (with order
239
- * front-matter), plus a root \`README.md\` documenting the convention.
240
- * Idempotent: existing files are never rewritten (a user-edited file survives
241
- * repeated calls) and missing directories are created on demand. Each file is
242
- * written exclusively, so two concurrent first runs race safely.
243
- */
244
- export async function ensurePresetGuidance(homeDir) {
245
- await mkdir(homeDir, { recursive: true });
246
- await Promise.all(DEFAULT_PRESETS.map(async (preset) => {
247
- const dir = join(homeDir, preset);
248
- await mkdir(dir, { recursive: true });
249
- const existing = new Set(await readdir(dir));
250
- await Promise.all(GUIDANCE_SECTIONS.map(async (section) => {
251
- if (existing.has(section.file))
252
- return;
253
- const content = `---\norder: ${section.defaultOrder}\n---\n\n${section.renderDefault()}`;
254
- await writeFile(join(dir, section.file), content, {
255
- encoding: "utf-8",
256
- flag: "wx",
257
- }).catch((error) => {
258
- // A concurrent writer landed first; never clobber it.
259
- if (errCode(error) === "EEXIST")
260
- return;
261
- throw error;
262
- });
263
- }));
264
- }));
265
- const homeFiles = new Set(await readdir(homeDir));
266
- const readmes = [
267
- ["README.md", GUIDANCE_HOME_README],
268
- ["README.zh.md", GUIDANCE_HOME_README_ZH],
269
- ];
270
- await Promise.all(readmes.map(async ([file, content]) => {
271
- if (homeFiles.has(file))
272
- return;
273
- await writeFile(join(homeDir, file), content, {
274
- encoding: "utf-8",
275
- flag: "wx",
276
- }).catch((error) => {
277
- if (errCode(error) === "EEXIST")
278
- return;
279
- throw error;
280
- });
281
- }));
282
- }
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. */
@@ -56,7 +56,15 @@ async function resolveAgentSections(rootCtx, agent) {
56
56
  return compiledDefaultSections();
57
57
  try {
58
58
  const presetId = agentPresets.composedPreset(agent.ctx);
59
- return await composeSections(presetId, configDir());
59
+ const sections = await composeSections(presetId, configDir());
60
+ // Warn once per agent install (this runs once per agent, under the
61
+ // WeakSet guard) about any malformed override we had to ignore.
62
+ for (const section of sections) {
63
+ if (section.malformed) {
64
+ rootCtx.logger.warn(`dsh-better-edit: ignoring malformed guidance override ${section.malformed.file}: ${section.malformed.reason}; using compiled default`);
65
+ }
66
+ }
67
+ return sections;
60
68
  }
61
69
  catch (error) {
62
70
  rootCtx.logger.warn(`dsh-better-edit: guidance resolution failed for agent ${agent.id}, using compiled defaults: ${error instanceof Error ? error.message : String(error)}`);
@@ -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
  }