dsh-better-edit 0.2.2 → 0.3.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 (85) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +317 -240
  3. package/README.zh.md +19 -11
  4. package/lib/constants.js +3 -1
  5. package/lib/contract.js +159 -63
  6. package/lib/drift.js +5 -98
  7. package/lib/dsh-context.js +2 -24
  8. package/lib/edit-engine.js +9 -8
  9. package/lib/edit-pipeline.js +3 -121
  10. package/lib/edit-response.js +16 -8
  11. package/lib/file-kind.js +6 -121
  12. package/lib/file-reader.js +4 -77
  13. package/lib/file-view.js +486 -0
  14. package/lib/guidance/index.js +8 -0
  15. package/lib/guidance/materialize.js +212 -0
  16. package/lib/guidance/parse.js +80 -0
  17. package/lib/guidance/resolve.js +116 -0
  18. package/lib/guidance.js +6 -388
  19. package/lib/hash-store.js +6 -4
  20. package/lib/hashline/alphabet.js +2 -6
  21. package/lib/hashline/anchor-pipeline.js +786 -0
  22. package/lib/hashline/apply.js +2 -223
  23. package/lib/hashline/hash-assign.js +255 -0
  24. package/lib/hashline/hash.js +67 -29
  25. package/lib/hashline/hasher.js +2 -23
  26. package/lib/hashline/index.js +9 -4
  27. package/lib/hashline/parse.js +2 -35
  28. package/lib/hashline/pure.js +2 -213
  29. package/lib/hashline/resolve.js +3 -361
  30. package/lib/hashline/served.js +2 -120
  31. package/lib/index.js +1 -3
  32. package/lib/mutation.js +266 -0
  33. package/lib/noop-guard.js +20 -0
  34. package/lib/preview-controller.js +65 -0
  35. package/lib/prompts.js +14 -20
  36. package/lib/read-and-serve.js +23 -23
  37. package/lib/read-render.js +3 -139
  38. package/lib/served-store.js +2 -216
  39. package/lib/session-view.js +332 -0
  40. package/lib/tool-batch-edit.js +9 -10
  41. package/lib/tool-edit.js +73 -129
  42. package/lib/tool-read.js +3 -5
  43. package/lib/tool-undo.js +16 -10
  44. package/lib/truncate.js +3 -95
  45. package/lib/types/constants.d.ts +2 -0
  46. package/lib/types/contract.d.ts +120 -15
  47. package/lib/types/drift.d.ts +5 -29
  48. package/lib/types/dsh-context.d.ts +2 -20
  49. package/lib/types/edit-engine.d.ts +2 -2
  50. package/lib/types/edit-pipeline.d.ts +3 -44
  51. package/lib/types/file-kind.d.ts +6 -18
  52. package/lib/types/file-reader.d.ts +4 -45
  53. package/lib/types/file-view.d.ts +139 -0
  54. package/lib/types/guidance/index.d.ts +8 -0
  55. package/lib/types/guidance/materialize.d.ts +23 -0
  56. package/lib/types/guidance/parse.d.ts +36 -0
  57. package/lib/types/guidance/resolve.d.ts +55 -0
  58. package/lib/types/guidance.d.ts +6 -127
  59. package/lib/types/hashline/alphabet.d.ts +1 -5
  60. package/lib/types/hashline/anchor-pipeline.d.ts +127 -0
  61. package/lib/types/hashline/apply.d.ts +1 -22
  62. package/lib/types/hashline/hash-assign.d.ts +25 -0
  63. package/lib/types/hashline/hash.d.ts +8 -9
  64. package/lib/types/hashline/hasher.d.ts +1 -8
  65. package/lib/types/hashline/index.d.ts +12 -4
  66. package/lib/types/hashline/parse.d.ts +1 -7
  67. package/lib/types/hashline/pure.d.ts +1 -26
  68. package/lib/types/hashline/resolve.d.ts +1 -58
  69. package/lib/types/hashline/served.d.ts +1 -43
  70. package/lib/types/mutation.d.ts +131 -0
  71. package/lib/types/noop-guard.d.ts +29 -0
  72. package/lib/types/preview-controller.d.ts +33 -0
  73. package/lib/types/prompts.d.ts +9 -9
  74. package/lib/types/read-and-serve.d.ts +6 -5
  75. package/lib/types/read-render.d.ts +3 -18
  76. package/lib/types/served-store.d.ts +2 -81
  77. package/lib/types/session-view.d.ts +92 -0
  78. package/lib/types/tool-edit.d.ts +3 -14
  79. package/lib/types/truncate.d.ts +3 -29
  80. package/lib/types/validation.d.ts +6 -7
  81. package/lib/types/workspace.d.ts +2 -21
  82. package/lib/validation.js +6 -33
  83. package/lib/workspace.js +2 -27
  84. package/lib/write-hook.js +2 -2
  85. package/package.json +2 -2
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, CANON_VERSION } 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))
@@ -52,6 +51,9 @@ export function isValidServedList(value) {
52
51
  }
53
52
  return true;
54
53
  }
54
+ function cacheKey(checksum) {
55
+ return `${CANON_VERSION}:${checksum}`;
56
+ }
55
57
  // ---- db plumbing (private) --------------------------------------------------
56
58
  export function isCorruptionError(error) {
57
59
  if (error && typeof error === "object") {
@@ -255,7 +257,7 @@ function makeDomainStore(stmts) {
255
257
  return {
256
258
  engine: "node:sqlite",
257
259
  getSnapshot(path, content, deleteCorrupt = true) {
258
- const checksum = contentChecksum(content);
260
+ const checksum = cacheKey(contentChecksum(content));
259
261
  const lineCount = splitLines(content).length;
260
262
  const row = stmts.get(path, checksum, lineCount);
261
263
  if (!row)
@@ -275,7 +277,7 @@ function makeDomainStore(stmts) {
275
277
  }
276
278
  },
277
279
  upsertSnapshot(path, checksum, lineCount, hashes) {
278
- stmts.upsert(path, checksum, lineCount, JSON.stringify(hashes), Date.now());
280
+ stmts.upsert(path, cacheKey(checksum), lineCount, JSON.stringify(hashes), Date.now());
279
281
  },
280
282
  allKnownPaths() {
281
283
  return stmts.allPaths();
@@ -1,6 +1,2 @@
1
- export const HASH_LEN = 3;
2
- export const ALPH = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
3
- const ALPH_SAFE = ALPH.replace(/-/g, "\\-");
4
- export const ALPH_RE = new RegExp(`^[${ALPH_SAFE}]+$`);
5
- export const HASH_CLASS = `[${ALPH_SAFE}]{${HASH_LEN}}`;
6
- export const HASH_RE = new RegExp(`^${HASH_CLASS}$`);
1
+ // @deprecated — private to HashAssign seam. Use `from "./hash-assign.js"` instead.
2
+ export * from "./hash-assign.js";