dsh-better-edit 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,391 @@
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.
23
+ * @module dsh-better-edit/guidance
24
+ */
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
+ }
package/lib/index.js CHANGED
@@ -9,6 +9,10 @@
9
9
  * automatically when the agent is disposed. The built-in `write` stays in
10
10
  * place; a scoped `tools/post-execute` listener appends the fresh hashline
11
11
  * preview to write results.
12
+ *
13
+ * The four `tool:*` guidance sections resolve per agent preset from override
14
+ * files in the shared home (see `src/guidance.ts`); deployments without the
15
+ * `agentPresets` service keep the compiled defaults unchanged.
12
16
  * @module dsh-better-edit
13
17
  */
14
18
  import { ctxFsIO } from "./fs-bridge.js";
@@ -19,7 +23,8 @@ import { registerBatchEditTool } from "./tool-batch-edit.js";
19
23
  import { registerUndoTool } from "./tool-undo.js";
20
24
  import { registerWriteHook } from "./write-hook.js";
21
25
  import { initHasher } from "./hashline/hasher.js";
22
- import { EDIT_DESCRIPTION, EDIT_GUIDELINES, READ_GUIDELINES, BATCH_EDIT_GUIDELINES, UNDO_GUIDELINES, } from "./prompts.js";
26
+ import { composeSections, ensurePresetGuidance, GUIDANCE_SECTIONS, } from "./guidance.js";
27
+ import { configDir } from "./paths.js";
23
28
  /** Cordis plugin name used by loader diagnostics. */
24
29
  export const name = "dsh-better-edit";
25
30
  /**
@@ -30,8 +35,44 @@ export const name = "dsh-better-edit";
30
35
  * session-start.
31
36
  */
32
37
  export const inject = ["tools", "systemPrompt", "fs"];
38
+ /** The four sections as compiled, byte-identical to the pre-guidance install. */
39
+ function compiledDefaultSections() {
40
+ return GUIDANCE_SECTIONS.map((section) => ({
41
+ name: section.name,
42
+ order: section.defaultOrder,
43
+ text: section.renderDefault(),
44
+ }));
45
+ }
46
+ /**
47
+ * Resolve the four guidance sections for one agent. Without the `agentPresets`
48
+ * service the fast path returns the compiled defaults untouched. With it, the
49
+ * agent's preset id drives `composeSections` against the shared home; any
50
+ * resolution failure degrades to compiled defaults so a bad override file can
51
+ * never fail the install.
52
+ */
53
+ async function resolveAgentSections(rootCtx, agent) {
54
+ const agentPresets = rootCtx.get("agentPresets");
55
+ if (!agentPresets)
56
+ return compiledDefaultSections();
57
+ try {
58
+ const presetId = agentPresets.composedPreset(agent.ctx);
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;
68
+ }
69
+ catch (error) {
70
+ rootCtx.logger.warn(`dsh-better-edit: guidance resolution failed for agent ${agent.id}, using compiled defaults: ${error instanceof Error ? error.message : String(error)}`);
71
+ return compiledDefaultSections();
72
+ }
73
+ }
33
74
  function installAgentTools(rootCtx, agent) {
34
- return agent.ctx.effect(() => {
75
+ agent.ctx.effect(async () => {
35
76
  // `fs` is host-plane: use the plugin's own context (covered by
36
77
  // inject) rather than the agent's scoped one, whose fiber chain does
37
78
  // not declare it. Session cwd still reaches the bridge per call via
@@ -44,36 +85,13 @@ function installAgentTools(rootCtx, agent) {
44
85
  disposers.push(registerBatchEditTool(rootCtx, agent.ctx, io, sandbox));
45
86
  disposers.push(registerUndoTool(rootCtx, agent.ctx, io, sandbox));
46
87
  disposers.push(registerWriteHook(rootCtx, agent.ctx, io));
47
- // Shadow the preset's built-in tool guidance with the hashline contract.
48
- // Same section names on the agent's own layer win over the preset's.
49
- disposers.push(agent.ctx.systemPrompt.section({
50
- name: "tool:edit",
51
- order: 102,
52
- text: [
53
- EDIT_DESCRIPTION,
54
- "",
55
- EDIT_GUIDELINES.map((line) => `- ${line}`).join("\n"),
56
- ].join("\n"),
57
- }));
58
- disposers.push(agent.ctx.systemPrompt.section({
59
- name: "tool:read",
60
- order: 100,
61
- text: [
62
- "Use the read tool — not shell commands like cat — to inspect text files.",
63
- "",
64
- READ_GUIDELINES.map((line) => `- ${line}`).join("\n"),
65
- ].join("\n"),
66
- }));
67
- disposers.push(agent.ctx.systemPrompt.section({
68
- name: "tool:batch_edit",
69
- order: 103,
70
- text: BATCH_EDIT_GUIDELINES.map((line) => `- ${line}`).join("\n"),
71
- }));
72
- disposers.push(agent.ctx.systemPrompt.section({
73
- name: "tool:undo_last_edit",
74
- order: 104,
75
- text: UNDO_GUIDELINES.map((line) => `- ${line}`).join("\n"),
76
- }));
88
+ // Shadow the preset's built-in tool guidance with the hashline
89
+ // contract. Same section names on the agent's own layer win over the
90
+ // preset's; text and order come from the per-preset resolution.
91
+ const sections = await resolveAgentSections(rootCtx, agent);
92
+ for (const section of sections) {
93
+ disposers.push(agent.ctx.systemPrompt.section(section));
94
+ }
77
95
  return () => {
78
96
  for (const dispose of disposers)
79
97
  dispose();
@@ -88,6 +106,12 @@ export function apply(rootCtx) {
88
106
  initHasher().catch((error) => {
89
107
  rootCtx.logger.warn(`dsh-better-edit: hasher warm-up failed: ${error instanceof Error ? error.message : String(error)}`);
90
108
  });
109
+ // Seed each shipped preset's guidance directory once, so users have
110
+ // editable per-preset overrides (idempotent: never rewrites existing
111
+ // files). A failure must never fail the boot.
112
+ ensurePresetGuidance(configDir()).catch((error) => {
113
+ rootCtx.logger.warn(`dsh-better-edit: guidance materialization failed: ${error instanceof Error ? error.message : String(error)}`);
114
+ });
91
115
  const registered = new WeakSet();
92
116
  rootCtx.on("agent/session-start", ({ agent }) => {
93
117
  if (registered.has(agent))
package/lib/prompts.js CHANGED
@@ -1,54 +1,58 @@
1
1
  /**
2
2
  * Model-facing prompt text for the hashline tools, embedded so the bundle
3
- * ships no external prompt files. Each tool's description is short; the
4
- * `tool:*` system-prompt sections carry the full usage guidance the model
5
- * reads when the tools are presented.
3
+ * ships no external prompt files. Each tool's schema `description` is short;
4
+ * the `tool:*` system-prompt sections carry the brief guidance the model
5
+ * reads when the tools are presented. Guidance is uniform: a one-line opener
6
+ * followed by tight bullets.
6
7
  * @module dsh-better-edit/prompts
7
8
  */
8
- export const EDIT_DESCRIPTION = 'Edit a range of lines in a text file, targeted by the 3-char HASH anchors from read output. ' +
9
- 'remove_from and remove_to must each be a BARE 3-character hash: copy only the hash from the ' +
9
+ export const EDIT_DESCRIPTION = "Edit a range of lines in a text file, targeted by the 3-char HASH anchors from read output. " +
10
+ "remove_from and remove_to must each be a BARE 3-character hash: copy only the hash from the " +
10
11
  'leftmost column of a read row (row `ve7│function hello() {` means `"remove_from": "ve7"`). ' +
11
- 'Never pass the line content, a code line, or a paragraph into these fields.';
12
- export const EDIT_SNIPPET = 'Edit lines in a text file via bare 3-char HASH anchors from read — hash only, never line content; anchor exactly the lines that change; one edit per tool call';
13
- export const EDIT_GUIDELINES = [
14
- '`edit`: remove_from and remove_to take ONLY the bare 3-char hash — read row `ve7│function hello() {` means `"remove_from": "ve7"`. Never paste the line content, a code line, a paragraph, or the whole `HASH│content` row into these fields.',
15
- '`edit`: remove_from and remove_to mark the exact lines that are REMOVED, and replacement_text is their complete replacement applied in order; nothing outside the range changes. Every line inside the range that is not reproduced byte-exact in replacement_text is deleted from the file.',
16
- '`edit`: keep the range as tight as the change — anchor only the first and last line that actually change, never a whole function, class, or import block when only part of it changes.',
17
- '`edit`: to edit a single line, set both remove_from and remove_to to the same hash: remove_from: "<HASH>", remove_to: "<HASH>".',
18
- '`edit`: when copying a line from read output, remove its HASH│ prefix and keep the leading whitespace exactly as shown.',
19
- '`edit`: every `\\n` in replacement_text separates lines, so a trailing `\\n` adds a final empty line. Mirror the removed lines exactly: a range that ends on a blank line must end replacement_text with `\\n` (e.g. `"code\\n"`), and a replacement whose last line is not blank must not end with `\\n`. To add a blank line after a line, end replacement_text with an explicit empty line after it (e.g. `"X\\n"` adds a blank after X). A replacement that is only blank lines is written as one `\\n` per blank line.',
20
- '`edit`: when the tool shows the post-edit diff, its rows are the fresh anchors for the new file — `+HASH│` and ` HASH│` rows carry current hashes and unchanged lines keep their previous hashes, so you can anchor follow-up edits on the diff.',
21
- '`edit`: the tool verifies every line of your range against what it served you. If the file changed since it was served, or a line was never served, the edit is hard-rejected — `[E_RANGE_STALE]` or `[E_RANGE_UNSERVED]` names the first offending line and echoes the current range as fresh `HASH│content` rows. Copy remove_from/remove_to from those echoed rows and retry — the rows count as serves.',
22
- '`edit`: only rows the tool delivered count as serves — read output, post-edit diffs, and rejection echoes. Content you saw through bash or another channel is not served state; a range over it is rejected as never-served or unverifiable, and there is no way to waive that check.',
23
- '`edit`: do not issue multiple edit calls on the same file in one message. Use `batch_edit` for multiple edits — it validates every edit before writing anything, applies the whole batch all-or-nothing, and returns one combined diff per file.',
24
- ];
25
- export const READ_DESCRIPTION = 'Read a text file; each line returned as HASH│content with a 3-char alphanumeric hash. ' +
26
- 'No line numbers — use the HASH as the anchor in edit calls. Binary/directory → rejected; ' +
27
- 'empty → HASH│ (edit to insert); pageable with offset/limit; BOM stripped; non-UTF-8 shown as U+FFFD.';
28
- export const READ_SNIPPET = 'Read a file; each line returned as HASH│content';
29
- export const READ_GUIDELINES = [
30
- '`read`: call only when you need information the tool never served you — a page you never saw, content past the post-edit diff. `edit` verifies every line of your range against what the tool served; a rejection echoes the current range as fresh `HASH│content` rows to retry on.',
31
- '`read`: the post-edit diff rows from edit/undo and the drift-notice rows also carry fresh anchors for the lines they show.',
32
- ];
33
- export const BATCH_EDIT_DESCRIPTION = 'Apply several edits in one atomic call. Each item is exactly like the edit tool: ' +
34
- '{ path?, remove_from, remove_to, replacement_text }, where remove_from and remove_to are ' +
35
- 'bare 3-char hashes from read or diff output. Items targeting the same file are applied in order. ' +
36
- 'Every item is verified against what the tool served you before ANYTHING is written: if any item ' +
37
- 'fails — stale or ambiguous anchor, changed range interior, never-served line — the whole batch ' +
38
- 'is rejected and no file changes. The failing item\u2019s current range is served back as fresh ' +
39
- 'HASH│content rows so you can retry without a read. Use batch_edit whenever you have multiple ' +
40
- 'edits; do not issue several edit calls in one message.';
41
- export const BATCH_EDIT_GUIDELINES = [
42
- 'batch_edit: each item takes the same fields as edit — { path?, remove_from, remove_to, replacement_text }. remove_from and remove_to take ONLY the bare 3-char hash from read/diff output; never the line content.',
43
- 'batch_edit: items are applied in order. Edits to the same file must not overlap — an item whose range was changed by an earlier item in the batch is rejected.',
44
- 'batch_edit: the whole batch is all-or-nothing. If any item fails validation, nothing is written anywhere; the failing item\u2019s current range is echoed as fresh HASH│content rows that count as serves.',
45
- 'batch_edit: every item is verified against what the tool served you — stale anchors, changed interiors, or never-served lines reject the batch.',
46
- 'batch_edit: a noop item (the range already contains the replacement text) is reported without failing the batch; an all-noop batch reports no changes.',
47
- 'batch_edit: the result is one combined diff per file with fresh anchors — anchor follow-up edits on those rows without re-reading.',
48
- ];
49
- export const UNDO_DESCRIPTION = 'Undo the last edit on a file, reverting it to its previous state. Use when an edit produced ' +
50
- 'incorrect results (e.g., wrong content, duplicated lines, broken syntax).';
51
- export const UNDO_GUIDELINES = [
52
- '`undo_last_edit`: reverts only the most recent edit on the file — any write to the file clears the undo history, so call it immediately after a bad edit. An edit is bad when its post-edit diff shows `-HASH│` rows for lines you meant to keep (a closing brace, import, or declaration).',
53
- '`undo_last_edit`: when the tool shows the post-edit diff, its `+HASH│` and ` HASH│` rows are the fresh anchors for the restored file, so follow-up edits can anchor on the diff.',
54
- ];
12
+ "Never pass the line content, a code line, or a paragraph into these fields.";
13
+ export const EDIT_GUIDANCE = {
14
+ intro: "Edit a range of lines via a bare 3-char HASH anchor from read output — never by line content.",
15
+ lines: [
16
+ "`edit`: anchor the exact first and last lines that change by their stripped hash (`ve7`, not `ve7│function…`). A single line uses the same hash in both fields; never anchor a whole function or import block when part of it changes.",
17
+ "`edit`: replacement_text is byte-exact for the whole range — every line inside it you do not reproduce byte-exact is deleted, and leading whitespace is preserved exactly.",
18
+ "`edit`: `\\n` is a line break, so a range ending on a blank line must end replacement_text with `\\n` and a non-blank last line must not; a blank-line run is one `\\n` per blank line.",
19
+ "`edit`: the post-edit diff rows carry fresh anchors for follow-ups. A stale or never-served range is hard-rejected (`[E_RANGE_STALE]` / `[E_RANGE_UNSERVED]`); copy the echoed rows and retry — only tool-served rows count.",
20
+ "`edit`: for multiple edits to one file, use batch_edit — it validates every item before writing and applies them all-or-nothing.",
21
+ ],
22
+ };
23
+ export const READ_DESCRIPTION = "Read a text file; each line returned as HASH│content with a 3-char alphanumeric hash. " +
24
+ "No line numbers — use the HASH as the anchor in edit calls. Binary/directory → rejected; " +
25
+ "empty → HASH│ (edit to insert); pageable with offset/limit; BOM stripped; non-UTF-8 shown as U+FFFD.";
26
+ export const READ_GUIDANCE = {
27
+ intro: "Use read, not shell commands, to inspect text files and obtain the HASH anchors the editing tools require.",
28
+ lines: [
29
+ "`read`: call it only for content the tools have not served — a page you never saw, or lines past the post-edit diff.",
30
+ "`read`: each row is `HASH│content`; the HASH is the anchor (no line numbers). Rejection echoes return fresh rows that count as serves.",
31
+ "`read`: binary/directory rejects; page large files with offset/limit.",
32
+ ],
33
+ };
34
+ export const BATCH_EDIT_DESCRIPTION = "Apply several edits in one atomic call. Each item is exactly like the edit tool: " +
35
+ "{ path?, remove_from, remove_to, replacement_text }, where remove_from and remove_to are " +
36
+ "bare 3-char hashes from read or diff output. Items targeting the same file are applied in order. " +
37
+ "Every item is verified against what the tool served you before ANYTHING is written: if any item " +
38
+ "fails — stale or ambiguous anchor, changed range interior, never-served line — the whole batch " +
39
+ "is rejected and no file changes. The failing item\u2019s current range is served back as fresh " +
40
+ "HASH│content rows so you can retry without a read. Use batch_edit whenever you have multiple " +
41
+ "edits; do not issue several edit calls in one message.";
42
+ export const BATCH_EDIT_GUIDANCE = {
43
+ intro: "Apply several edits in one atomic call.",
44
+ lines: [
45
+ "`batch_edit`: each item is edit\u2019s shape — { path?, remove_from, remove_to, replacement_text } — with bare hash anchors; items apply in order, and same-file ranges must not overlap.",
46
+ "`batch_edit`: all-or-nothing — any failing item writes nothing anywhere and echoes its current range as fresh rows that count as serves.",
47
+ "`batch_edit`: a no-op item is reported without failing; the result is one combined diff per file with fresh anchors.",
48
+ ],
49
+ };
50
+ export const UNDO_DESCRIPTION = "Undo the last edit on a file, reverting it to its previous state. Use when an edit produced " +
51
+ "incorrect results (e.g., wrong content, duplicated lines, broken syntax).";
52
+ export const UNDO_GUIDANCE = {
53
+ intro: "Revert the last edit on a file.",
54
+ lines: [
55
+ "`undo_last_edit`: reverts only the most recent edit — any write clears history, so call it immediately after a bad edit.",
56
+ "`undo_last_edit`: the restored diff\u2019s `+HASH│` and ` HASH│` rows are fresh anchors for follow-up edits.",
57
+ ],
58
+ };