dsh-better-edit 0.1.0 → 0.1.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.
package/lib/fs-bridge.js CHANGED
@@ -1,14 +1,23 @@
1
1
  /**
2
2
  * IO seam for the hashline tool layer. The tools resolve, read, and write
3
3
  * through this bridge so they honor the deployment's `ctx.fs` backend — a
4
- * sandboxed or remote filesystem — instead of reaching around it. The local
5
- * implementation exists for tests and for pure-pipeline verification.
4
+ * sandboxed or remote filesystem — instead of reaching around it.
5
+ *
6
+ * The bridge also participates in dsh's `fs/*` event gate exactly like the
7
+ * built-in tools: writes dispatch `fs/write-intent` (so the observation policy
8
+ * derives its create/replace guard and stale-version checks) and every
9
+ * successful read/mutation emits `fs/observed` with the resulting version. A
10
+ * hashline tool that silently skipped those events would leave the policy's
11
+ * observed state stale, and the next built-in `write` on the same file would
12
+ * fail with `FS_NOT_OBSERVED` / `FS_STALE_VERSION`.
13
+ *
14
+ * The local implementation exists for tests and pure-pipeline verification.
6
15
  * @module dsh-better-edit/fs-bridge
7
16
  */
8
- import { readFile } from 'node:fs/promises';
9
- import { resolveTarget, writeAtomic } from './fs-write.js';
10
- import { fileSnap } from './file-reader.js';
11
- import { toCwd } from './paths.js';
17
+ import { readFile } from "node:fs/promises";
18
+ import { resolveTarget, writeAtomic } from "./fs-write.js";
19
+ import { fileSnap } from "./file-reader.js";
20
+ import { toCwd } from "./paths.js";
12
21
  /**
13
22
  * Map an `ctx.fs` failure onto the hashline model-facing vocabulary so the
14
23
  * model sees the same structured error codes as the pure pipeline.
@@ -17,25 +26,32 @@ import { toCwd } from './paths.js';
17
26
  * @returns the mapped error, rethrown.
18
27
  */
19
28
  export function mapFsError(error, displayPath) {
20
- if (error instanceof Error && typeof error.code === 'string') {
29
+ if (error instanceof Error &&
30
+ typeof error.code === "string") {
21
31
  const code = error.code;
22
- if (code === 'FS_NOT_FOUND') {
32
+ if (code === "FS_NOT_FOUND") {
23
33
  throw new Error(`[E_NOT_FOUND] File not found: ${displayPath}`);
24
34
  }
25
- if (code === 'FS_PERMISSION_DENIED') {
35
+ if (code === "FS_PERMISSION_DENIED") {
26
36
  throw new Error(`[E_ACCESS] Cannot access file: ${displayPath}`);
27
37
  }
28
- if (code === 'FS_NOT_TEXT' || code === 'FS_NOT_REGULAR_FILE') {
38
+ if (code === "FS_NOT_TEXT" || code === "FS_NOT_REGULAR_FILE") {
29
39
  throw new Error(`[E_NOT_TEXT] Path is not a readable UTF-8 text file: ${displayPath}. Hashline editing only supports text files.`);
30
40
  }
31
- if (code === 'FS_ABORTED') {
32
- throw new Error('Operation aborted');
41
+ if (code === "FS_STALE_VERSION") {
42
+ throw new Error(`[E_RANGE_STALE] The file changed on disk since it was read (version guard rejected the write). Call read() to get fresh anchors, then retry.`);
43
+ }
44
+ if (code === "FS_NOT_OBSERVED") {
45
+ throw new Error(`[E_NOT_OBSERVED] The file has not been observed in this session (read-before-write policy). Call read() first, then retry the edit.`);
46
+ }
47
+ if (code === "FS_ABORTED") {
48
+ throw new Error("Operation aborted");
33
49
  }
34
50
  }
35
51
  throw error;
36
52
  }
37
53
  /** FileIO over the deployment's `ctx.fs` service. */
38
- export function ctxFsIO(fs, _ctx) {
54
+ export function ctxFsIO(fs, ctx) {
39
55
  return {
40
56
  async resolve(path, cwd, signal) {
41
57
  const target = await fs.resolve(path, {
@@ -55,17 +71,39 @@ export function ctxFsIO(fs, _ctx) {
55
71
  return mapFsError(error, absolutePath);
56
72
  }
57
73
  },
58
- async writeText(absolutePath, content, signal) {
74
+ async writeText(absolutePath, content, signal, exec) {
59
75
  try {
60
76
  const target = await fs.resolve(absolutePath, {
61
77
  ...(signal !== undefined ? { signal } : {}),
62
78
  });
63
- await fs.writeText(target, content, undefined, signal);
79
+ // Single-slot decision: the observation policy produces
80
+ // createIfAbsent / replaceIfVersion; the bare default is
81
+ // undefined (unconditional) when no policy is mounted.
82
+ const intent = await ctx.waterfall("fs/write-intent", target, exec, () => undefined);
83
+ const outcome = await fs.writeText(target, content, intent, signal);
84
+ // Record the present observation (a no-op when no policy
85
+ // plugin listens), so later built-in tools see the new version.
86
+ ctx.emit("fs/observed", target, { kind: "present", version: outcome.version }, exec);
64
87
  }
65
88
  catch (error) {
66
89
  return mapFsError(error, absolutePath);
67
90
  }
68
91
  },
92
+ async emitObserved(absolutePath, exec, signal) {
93
+ try {
94
+ const target = await fs.resolve(absolutePath, {
95
+ ...(signal !== undefined ? { signal } : {}),
96
+ });
97
+ const info = await fs.stat(target, signal);
98
+ if (info !== undefined) {
99
+ ctx.emit("fs/observed", target, { kind: "present", version: info.version }, exec);
100
+ }
101
+ }
102
+ catch (error) {
103
+ // A failed observation must not fail the read that preceded it.
104
+ console.error(`dsh-better-edit: fs/observed emission failed for ${absolutePath}: ${error instanceof Error ? error.message : String(error)}`);
105
+ }
106
+ },
69
107
  async statVersion(absolutePath, signal) {
70
108
  try {
71
109
  const target = await fs.resolve(absolutePath, {
@@ -88,12 +126,15 @@ export function localIO() {
88
126
  },
89
127
  async readText(absolutePath, signal) {
90
128
  signal?.throwIfAborted();
91
- return readFile(absolutePath, 'utf-8');
129
+ return readFile(absolutePath, "utf-8");
92
130
  },
93
131
  async writeText(absolutePath, content, signal) {
94
132
  signal?.throwIfAborted();
95
133
  await writeAtomic(absolutePath, content);
96
134
  },
135
+ async emitObserved() {
136
+ // No policy event gate on the host filesystem; nothing to record.
137
+ },
97
138
  async statVersion(absolutePath) {
98
139
  try {
99
140
  return (await fileSnap(absolutePath)).snapshotId;
package/lib/index.js CHANGED
@@ -22,9 +22,21 @@ import { pruneMissingAll } from './snapshot-store.js';
22
22
  import { EDIT_DESCRIPTION, EDIT_GUIDELINES, READ_GUIDELINES, BATCH_EDIT_GUIDELINES, UNDO_GUIDELINES, } from './prompts.js';
23
23
  /** Cordis plugin name used by loader diagnostics. */
24
24
  export const name = 'dsh-better-edit';
25
+ /**
26
+ * Services the plugin's per-agent install touches: `tools` and `systemPrompt`
27
+ * for the shadow registrations, `fs` for the IO bridge. Cordis refuses
28
+ * property access to an undeclared service ("cannot get property X without
29
+ * inject"), so these MUST be listed or every agent install fails at
30
+ * session-start.
31
+ */
32
+ export const inject = ['tools', 'systemPrompt', 'fs'];
25
33
  function installAgentTools(rootCtx, agent) {
26
34
  return agent.ctx.effect(() => {
27
- const io = ctxFsIO(agent.ctx.fs, agent.ctx);
35
+ // `fs` is host-plane: use the plugin's own context (covered by
36
+ // inject) rather than the agent's scoped one, whose fiber chain does
37
+ // not declare it. Session cwd still reaches the bridge per call via
38
+ // exec.agent.session.header.cwd.
39
+ const io = ctxFsIO(rootCtx.fs, rootCtx);
28
40
  const disposers = [];
29
41
  disposers.push(registerReadTool(rootCtx, agent.ctx, io));
30
42
  disposers.push(registerEditTool(rootCtx, agent.ctx, io));
@@ -5,29 +5,34 @@
5
5
  * the failing item's current range is echoed as fresh serves.
6
6
  * @module dsh-better-edit/tool-batch-edit
7
7
  */
8
- import { defineTool } from '@deepseek-ai/dsh-tools';
9
- import { restoreEndings } from './edit-diff.js';
10
- import { normFromText } from './file-reader.js';
11
- import { scanDrift } from './drift.js';
12
- import { abortIf, isRec, normalizeFilePath, rejectUnknownFields, splitLines } from './utils.js';
13
- import { normReq } from './edit-normalize.js';
14
- import { applyEdit, lineHashes, resEdit, MAX_HASH_LINES, } from './hashline/index.js';
15
- import { AnchorMismatchError, ServedRejectionError, buildRangeEcho, fmtServedRows, recordEchoServes, } from './hashline/served.js';
16
- import { buildBatchResult } from './edit-response.js';
17
- import { saveUndo } from './undo-edit.js';
18
- import { loadServed, recordServedTruncated } from './served-store.js';
19
- import { BATCH_EDIT_MAX_ITEMS, NOOP_LOOP_THRESHOLD } from './constants.js';
20
- import { collectRemovedHashes, countLineChanges, resolveMissingPath, } from './edit-pipeline.js';
21
- import { clearNoopLoop, noopPayloadKey, trackNoopPayload } from './noop-guard.js';
22
- import { BATCH_EDIT_DESCRIPTION } from './prompts.js';
23
- import { pathSchema, removeFromSchema, removeToSchema, replacementTextSchema } from './schema.js';
24
- import { execCwd, execSessionKey } from './dsh-context.js';
25
- const BATCH_ITEM_KS = new Set(['path', 'remove_from', 'remove_to', 'replacement_text']);
8
+ import { defineTool } from "@deepseek-ai/dsh-tools";
9
+ import { restoreEndings } from "./edit-diff.js";
10
+ import { normFromText } from "./file-reader.js";
11
+ import { scanDrift } from "./drift.js";
12
+ import { abortIf, isRec, normalizeFilePath, rejectUnknownFields, splitLines, } from "./utils.js";
13
+ import { normReq } from "./edit-normalize.js";
14
+ import { applyEdit, lineHashes, resEdit, MAX_HASH_LINES, } from "./hashline/index.js";
15
+ import { AnchorMismatchError, ServedRejectionError, buildRangeEcho, fmtServedRows, recordEchoServes, } from "./hashline/served.js";
16
+ import { buildBatchResult } from "./edit-response.js";
17
+ import { saveUndo } from "./undo-edit.js";
18
+ import { loadServed, recordServedTruncated } from "./served-store.js";
19
+ import { BATCH_EDIT_MAX_ITEMS, NOOP_LOOP_THRESHOLD } from "./constants.js";
20
+ import { collectRemovedHashes, countLineChanges, resolveMissingPath, } from "./edit-pipeline.js";
21
+ import { clearNoopLoop, noopPayloadKey, trackNoopPayload, } from "./noop-guard.js";
22
+ import { BATCH_EDIT_DESCRIPTION } from "./prompts.js";
23
+ import { pathSchema, removeFromSchema, removeToSchema, replacementTextSchema, } from "./schema.js";
24
+ import { execCwd, execSessionKey } from "./dsh-context.js";
25
+ const BATCH_ITEM_KS = new Set([
26
+ "path",
27
+ "remove_from",
28
+ "remove_to",
29
+ "replacement_text",
30
+ ]);
26
31
  function assertBatchReq(request) {
27
32
  if (!isRec(request)) {
28
33
  throw new Error('[E_BAD_SHAPE] batch_edit request must be an object with an "edits" array.');
29
34
  }
30
- rejectUnknownFields(request, new Set(['edits']), 'batch_edit request');
35
+ rejectUnknownFields(request, new Set(["edits"]), "batch_edit request");
31
36
  if (!Array.isArray(request.edits) || request.edits.length === 0) {
32
37
  throw new Error('[E_BAD_SHAPE] batch_edit request requires a non-empty "edits" array.');
33
38
  }
@@ -39,13 +44,13 @@ function assertBatchReq(request) {
39
44
  throw new Error(`[E_BAD_SHAPE] edits[${index}] must be an object with remove_from, remove_to, and replacement_text.`);
40
45
  }
41
46
  rejectUnknownFields(item, BATCH_ITEM_KS, `edits[${index}]`);
42
- if (typeof item.remove_from !== 'string' ||
43
- typeof item.remove_to !== 'string' ||
44
- typeof item.replacement_text !== 'string') {
47
+ if (typeof item.remove_from !== "string" ||
48
+ typeof item.remove_to !== "string" ||
49
+ typeof item.replacement_text !== "string") {
45
50
  throw new Error(`[E_BAD_SHAPE] edits[${index}] requires "remove_from", "remove_to", and "replacement_text" strings.`);
46
51
  }
47
52
  if (item.path !== undefined &&
48
- (typeof item.path !== 'string' || item.path.length === 0)) {
53
+ (typeof item.path !== "string" || item.path.length === 0)) {
49
54
  throw new Error(`[E_BAD_SHAPE] edits[${index}].path must be a non-empty string.`);
50
55
  }
51
56
  });
@@ -56,7 +61,7 @@ async function prepareItems(io, params, cwd, signal) {
56
61
  const raw = params.edits[index];
57
62
  const record = { ...raw };
58
63
  normalizeFilePath(record);
59
- let path = typeof record.path === 'string' ? record.path : undefined;
64
+ let path = typeof record.path === "string" ? record.path : undefined;
60
65
  let pathWarning;
61
66
  if (!path) {
62
67
  let resolution;
@@ -131,8 +136,8 @@ async function processFile(io, items, _cwd, opts) {
131
136
  let totalRemovedLines = 0;
132
137
  let unionStartLine = Infinity;
133
138
  let unionEndLine = -Infinity;
134
- let unionStartHash = '';
135
- let unionEndHash = '';
139
+ let unionStartHash = "";
140
+ let unionEndHash = "";
136
141
  let lastApplied;
137
142
  for (const item of items) {
138
143
  abortIf(opts.signal);
@@ -147,7 +152,7 @@ async function processFile(io, items, _cwd, opts) {
147
152
  catch (error) {
148
153
  const message = error instanceof Error ? error.message : String(error);
149
154
  throw new Error(`[E_BATCH_ABORT] edits[${item.index}] (${item.path}) failed: ${message}\n` +
150
- 'The whole batch was rejected and NOTHING was written — no file changed and earlier items in the batch were NOT applied.');
155
+ "The whole batch was rejected and NOTHING was written — no file changed and earlier items in the batch were NOT applied.");
151
156
  }
152
157
  let anchorResult;
153
158
  try {
@@ -161,13 +166,13 @@ async function processFile(io, items, _cwd, opts) {
161
166
  ? error.servedRows
162
167
  : echoRowsForItem(edit, originalHashes);
163
168
  if (echoRows) {
164
- await recordEchoServes(opts.sessionKey, absolutePath, echoRows, 'live');
169
+ await recordEchoServes(opts.sessionKey, absolutePath, echoRows, "live");
165
170
  }
166
171
  const echoBlock = echoRows
167
172
  ? ` Current on-disk range for edits[${item.index}] (unchanged — nothing was written):\n${fmtServedRows(echoRows, originalLines)}`
168
- : ' Call read() to get fresh anchors.';
173
+ : " Call read() to get fresh anchors.";
169
174
  throw new Error(`[E_BATCH_ABORT] edits[${item.index}] (${item.path}) failed: ${error.message}${echoBlock}\n` +
170
- 'The whole batch was rejected and NOTHING was written — no file changed and earlier items in the batch were NOT applied. Fix the failing edit (and any later edit that depends on it), then resubmit the batch.');
175
+ "The whole batch was rejected and NOTHING was written — no file changed and earlier items in the batch were NOT applied. Fix the failing edit (and any later edit that depends on it), then resubmit the batch.");
171
176
  }
172
177
  throw error;
173
178
  }
@@ -190,12 +195,12 @@ async function processFile(io, items, _cwd, opts) {
190
195
  const originalLines = splitLines(originalNormalized);
191
196
  const echoRows = echoRowsForItem(edit, originalHashes);
192
197
  if (echoRows) {
193
- await recordEchoServes(opts.sessionKey, absolutePath, echoRows, 'live');
198
+ await recordEchoServes(opts.sessionKey, absolutePath, echoRows, "live");
194
199
  }
195
200
  throw new Error(`[E_NOOP_LOOP] edits[${item.index}] (${item.path}): this exact edit (anchors ${item.remove_from} to ${item.remove_to}) has been submitted ${count} times and produced no changes each time — the range already contains the replacement text. Do not resend it; it will never change the file. The whole batch was rejected and nothing was written.` +
196
201
  (echoRows
197
202
  ? ` Current on-disk range:\n${fmtServedRows(echoRows, originalLines)}`
198
- : ''));
203
+ : ""));
199
204
  }
200
205
  if (count === 2) {
201
206
  warnings.push(`[E_NOOP_LOOP] Notice: edits[${item.index}] (${item.path}) — this exact edit has produced no changes twice in a row; the range already contains the replacement text. Resending it again will reject the batch.`);
@@ -232,7 +237,7 @@ async function processFile(io, items, _cwd, opts) {
232
237
  }, undefined, true);
233
238
  }
234
239
  if (hadUtf8DecodeErrors) {
235
- warnings.push('Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.');
240
+ warnings.push("Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.");
236
241
  }
237
242
  if (first.pathWarning)
238
243
  warnings.unshift(first.pathWarning);
@@ -257,7 +262,7 @@ async function processFile(io, items, _cwd, opts) {
257
262
  });
258
263
  }
259
264
  catch (error) {
260
- console.error('Failed to compute drift notice:', error);
265
+ console.error("Failed to compute drift notice:", error);
261
266
  }
262
267
  }
263
268
  return {
@@ -309,18 +314,18 @@ function toSection(file) {
309
314
  */
310
315
  export function buildBatchEditTool(io) {
311
316
  return defineTool({
312
- name: 'batch_edit',
317
+ name: "batch_edit",
313
318
  description: BATCH_EDIT_DESCRIPTION,
314
319
  parameters: {
315
320
  edits: {
316
- type: 'array',
321
+ type: "array",
317
322
  required: true,
318
323
  description: `Ordered list of edits, each with the same shape as the edit tool: { path?, remove_from, remove_to, replacement_text }. ` +
319
- 'Edits to the same file are applied in order and verified against what was served before anything is written. ' +
320
- 'The batch is all-or-nothing: if any edit fails validation, nothing is written and the failing edit\u2019s current range is served back. ' +
321
- 'Use batch_edit when you have multiple edits; do not issue several edit calls in one message.',
324
+ "Edits to the same file are applied in order and verified against what was served before anything is written. " +
325
+ "The batch is all-or-nothing: if any edit fails validation, nothing is written and the failing edit\u2019s current range is served back. " +
326
+ "Use batch_edit when you have multiple edits; do not issue several edit calls in one message.",
322
327
  items: {
323
- type: 'object',
328
+ type: "object",
324
329
  additionalProperties: false,
325
330
  properties: {
326
331
  path: pathSchema,
@@ -332,8 +337,8 @@ export function buildBatchEditTool(io) {
332
337
  },
333
338
  },
334
339
  output: {
335
- schema: { type: 'string' },
336
- render: (_args, value) => [{ type: 'text', text: value }],
340
+ schema: { type: "string" },
341
+ render: (_args, value) => [{ type: "text", text: value }],
337
342
  },
338
343
  async execute(args, exec) {
339
344
  const cwd = execCwd(exec);
@@ -377,10 +382,10 @@ export function buildBatchEditTool(io) {
377
382
  await u.restore();
378
383
  }
379
384
  catch (error) {
380
- console.error('Failed to restore undo entry after batch abort:', error);
385
+ console.error("Failed to restore undo entry after batch abort:", error);
381
386
  }
382
387
  }
383
- throw new Error('[E_UNDO_UNAVAILABLE] Cannot persist undo history to the hash store; the batch was NOT applied and no file was written. Retry the batch, or use write if the store cannot be recovered.');
388
+ throw new Error("[E_UNDO_UNAVAILABLE] Cannot persist undo history to the hash store; the batch was NOT applied and no file was written. Retry the batch, or use write if the store cannot be recovered.");
384
389
  }
385
390
  undos.push({ file, restore: undo.restore });
386
391
  }
@@ -388,7 +393,7 @@ export function buildBatchEditTool(io) {
388
393
  try {
389
394
  for (const u of undos) {
390
395
  abortIf(signal);
391
- await io.writeText(u.file.absolutePath, u.file.bom + restoreEndings(u.file.result, u.file.originalEnding), signal);
396
+ await io.writeText(u.file.absolutePath, u.file.bom + restoreEndings(u.file.result, u.file.originalEnding), signal, exec);
392
397
  written.push(u);
393
398
  }
394
399
  }
@@ -396,16 +401,16 @@ export function buildBatchEditTool(io) {
396
401
  for (const w of written) {
397
402
  try {
398
403
  await io.writeText(w.file.absolutePath, w.file.bom +
399
- restoreEndings(w.file.originalNormalized, w.file.originalEnding));
404
+ restoreEndings(w.file.originalNormalized, w.file.originalEnding), undefined, exec);
400
405
  }
401
406
  catch (restoreError) {
402
- console.error('Failed to restore file after batch write failure:', restoreError);
407
+ console.error("Failed to restore file after batch write failure:", restoreError);
403
408
  }
404
409
  try {
405
410
  await w.restore();
406
411
  }
407
412
  catch (restoreError) {
408
- console.error('Failed to restore undo entry after batch write failure:', restoreError);
413
+ console.error("Failed to restore undo entry after batch write failure:", restoreError);
409
414
  }
410
415
  }
411
416
  throw error;
package/lib/tool-edit.js CHANGED
@@ -5,20 +5,20 @@
5
5
  * served-range verification, reject-and-serve) replaces the built-in one.
6
6
  * @module dsh-better-edit/tool-edit
7
7
  */
8
- import { defineTool } from '@deepseek-ai/dsh-tools';
9
- import { restoreEndings } from './edit-diff.js';
10
- import { normReq } from './edit-normalize.js';
11
- import { abortIf, isRec, splitLines } from './utils.js';
12
- import { assertReq, execPipeline, resolveMissingPath, snapshotIdFor, } from './edit-pipeline.js';
13
- import { buildRangeEcho, fmtServedRows, recordEchoServes, } from './hashline/served.js';
14
- import { saveUndo } from './undo-edit.js';
15
- import { clearNoopLoop, noopPayloadKey, trackNoopPayload } from './noop-guard.js';
16
- import { buildNoop, buildChanged } from './edit-response.js';
17
- import { recordServedTruncated } from './served-store.js';
18
- import { NOOP_LOOP_THRESHOLD } from './constants.js';
19
- import { EDIT_DESCRIPTION } from './prompts.js';
20
- import { pathSchema, removeFromSchema, removeToSchema, replacementTextSchema } from './schema.js';
21
- import { execCwd, execSessionKey } from './dsh-context.js';
8
+ import { defineTool } from "@deepseek-ai/dsh-tools";
9
+ import { restoreEndings } from "./edit-diff.js";
10
+ import { normReq } from "./edit-normalize.js";
11
+ import { abortIf, isRec, splitLines } from "./utils.js";
12
+ import { assertReq, execPipeline, resolveMissingPath, snapshotIdFor, } from "./edit-pipeline.js";
13
+ import { buildRangeEcho, fmtServedRows, recordEchoServes, } from "./hashline/served.js";
14
+ import { saveUndo } from "./undo-edit.js";
15
+ import { clearNoopLoop, noopPayloadKey, trackNoopPayload, } from "./noop-guard.js";
16
+ import { buildNoop, buildChanged } from "./edit-response.js";
17
+ import { recordServedTruncated } from "./served-store.js";
18
+ import { NOOP_LOOP_THRESHOLD } from "./constants.js";
19
+ import { EDIT_DESCRIPTION } from "./prompts.js";
20
+ import { pathSchema, removeFromSchema, removeToSchema, replacementTextSchema, } from "./schema.js";
21
+ import { execCwd, execSessionKey } from "./dsh-context.js";
22
22
  /**
23
23
  * Register the hash-anchored `edit` tool on the calling agent's scope.
24
24
  * @param _rootCtx - host context (logger, lifecycle).
@@ -29,7 +29,7 @@ import { execCwd, execSessionKey } from './dsh-context.js';
29
29
  */
30
30
  export function buildEditTool(io) {
31
31
  return defineTool({
32
- name: 'edit',
32
+ name: "edit",
33
33
  description: EDIT_DESCRIPTION,
34
34
  parameters: {
35
35
  path: pathSchema,
@@ -38,8 +38,8 @@ export function buildEditTool(io) {
38
38
  replacement_text: replacementTextSchema,
39
39
  },
40
40
  output: {
41
- schema: { type: 'string' },
42
- render: (_args, value) => [{ type: 'text', text: value }],
41
+ schema: { type: "string" },
42
+ render: (_args, value) => [{ type: "text", text: value }],
43
43
  },
44
44
  async execute(args, exec) {
45
45
  const cwd = execCwd(exec);
@@ -71,7 +71,7 @@ export function buildEditTool(io) {
71
71
  if (count >= NOOP_LOOP_THRESHOLD) {
72
72
  const echoRows = buildRangeEcho(range.startLine, range.endLine, originalHashes);
73
73
  const echo = fmtServedRows(echoRows, splitLines(originalNormalized));
74
- await recordEchoServes(sessionKey, absolutePath, echoRows, 'live');
74
+ await recordEchoServes(sessionKey, absolutePath, echoRows, "live");
75
75
  throw new Error(`[E_NOOP_LOOP] This exact edit (anchors ${canonical.remove_from} to ${canonical.remove_to} in ${path}) has been submitted ${count} times and produced no changes each time — the range already contains the replacement text. Do not resend this edit; it will never change the file. Current range:\n${echo}`);
76
76
  }
77
77
  if (count === 2) {
@@ -95,7 +95,7 @@ export function buildEditTool(io) {
95
95
  }
96
96
  clearNoopLoop(absolutePath);
97
97
  if (hadUtf8DecodeErrors) {
98
- warnings.push('Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.');
98
+ warnings.push("Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.");
99
99
  }
100
100
  abortIf(signal);
101
101
  const undo = await saveUndo(absolutePath, {
@@ -110,7 +110,7 @@ export function buildEditTool(io) {
110
110
  }
111
111
  try {
112
112
  abortIf(signal);
113
- await io.writeText(absolutePath, bom + restoreEndings(result, originalEnding), signal);
113
+ await io.writeText(absolutePath, bom + restoreEndings(result, originalEnding), signal, exec);
114
114
  }
115
115
  catch (error) {
116
116
  await undo.restore();
package/lib/tool-read.js CHANGED
@@ -5,22 +5,22 @@
5
5
  * shown the lines it targets.
6
6
  * @module dsh-better-edit/tool-read
7
7
  */
8
- import { defineTool } from '@deepseek-ai/dsh-tools';
9
- import { normReq } from './edit-normalize.js';
10
- import { abortIf, isRec, rejectUnknownFields } from './utils.js';
11
- import { normFromText } from './file-reader.js';
12
- import { fmtReadPreview, MAX_HASH_LINES } from './read-render.js';
13
- import { recordServed, clearDriftReported } from './served-store.js';
14
- import { READ_DESCRIPTION } from './prompts.js';
15
- import { pathSchema } from './schema.js';
16
- import { execCwd, execSessionKey } from './dsh-context.js';
17
- const ROOT_KS = new Set(['path', 'offset', 'limit']);
8
+ import { defineTool } from "@deepseek-ai/dsh-tools";
9
+ import { normReq } from "./edit-normalize.js";
10
+ import { abortIf, isRec, rejectUnknownFields } from "./utils.js";
11
+ import { normFromText } from "./file-reader.js";
12
+ import { fmtReadPreview, MAX_HASH_LINES } from "./read-render.js";
13
+ import { recordServed, clearDriftReported } from "./served-store.js";
14
+ import { READ_DESCRIPTION } from "./prompts.js";
15
+ import { pathSchema } from "./schema.js";
16
+ import { execCwd, execSessionKey } from "./dsh-context.js";
17
+ const ROOT_KS = new Set(["path", "offset", "limit"]);
18
18
  function assertReadReq(request) {
19
19
  if (!isRec(request)) {
20
- throw new Error('[E_BAD_SHAPE] Read request must be an object.');
20
+ throw new Error("[E_BAD_SHAPE] Read request must be an object.");
21
21
  }
22
- rejectUnknownFields(request, ROOT_KS, 'Read request');
23
- if (typeof request.path !== 'string' || request.path.length === 0) {
22
+ rejectUnknownFields(request, ROOT_KS, "Read request");
23
+ if (typeof request.path !== "string" || request.path.length === 0) {
24
24
  throw new Error('[E_BAD_SHAPE] Read request requires a non-empty "path" string.');
25
25
  }
26
26
  }
@@ -33,22 +33,22 @@ function assertReadReq(request) {
33
33
  */
34
34
  export function buildReadTool(io) {
35
35
  return defineTool({
36
- name: 'read',
36
+ name: "read",
37
37
  description: READ_DESCRIPTION,
38
38
  parameters: {
39
39
  path: pathSchema,
40
40
  offset: {
41
- type: 'number',
42
- description: 'Line number to start reading from (1-indexed)',
41
+ type: "number",
42
+ description: "Line number to start reading from (1-indexed)",
43
43
  },
44
44
  limit: {
45
- type: 'number',
46
- description: 'Maximum number of lines to read',
45
+ type: "number",
46
+ description: "Maximum number of lines to read",
47
47
  },
48
48
  },
49
49
  output: {
50
- schema: { type: 'string' },
51
- render: (_args, value) => [{ type: 'text', text: value }],
50
+ schema: { type: "string" },
51
+ render: (_args, value) => [{ type: "text", text: value }],
52
52
  },
53
53
  async execute(args, exec) {
54
54
  const cwd = execCwd(exec);
@@ -72,6 +72,10 @@ export function buildReadTool(io) {
72
72
  await recordServed(sessionKey, absolutePath, preview.served);
73
73
  }
74
74
  await clearDriftReported(sessionKey, absolutePath);
75
+ // Record the present observation with the fs policy gate so later
76
+ // built-in write/edit calls see this file as observed at the
77
+ // version the model just read (a no-op when no policy listens).
78
+ await io.emitObserved(absolutePath, exec, signal);
75
79
  return hadUtf8DecodeErrors
76
80
  ? `${preview.text}\n\n[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]`
77
81
  : preview.text;
package/lib/tool-undo.js CHANGED
@@ -4,23 +4,23 @@
4
4
  * external write clears the history instead of being overwritten.
5
5
  * @module dsh-better-edit/tool-undo
6
6
  */
7
- import { defineTool } from '@deepseek-ai/dsh-tools';
8
- import { toLF, stripBOM, genDiff, restoreEndings } from './edit-diff.js';
9
- import { cntDiff, splitLines, isRec, normalizeFilePath } from './utils.js';
10
- import { normReq } from './edit-normalize.js';
11
- import { upsertSnapshotFor } from './snapshot-store.js';
12
- import { contentChecksum } from './hashline/hasher.js';
13
- import { lineHashes, changedRange } from './hashline/index.js';
14
- import { getUndo, clearUndo } from './undo-edit.js';
15
- import { recordServedTruncated } from './served-store.js';
16
- import { UNDO_DESCRIPTION } from './prompts.js';
17
- import { execCwd, execSessionKey } from './dsh-context.js';
7
+ import { defineTool } from "@deepseek-ai/dsh-tools";
8
+ import { toLF, stripBOM, genDiff, restoreEndings } from "./edit-diff.js";
9
+ import { cntDiff, splitLines, isRec, normalizeFilePath } from "./utils.js";
10
+ import { normReq } from "./edit-normalize.js";
11
+ import { upsertSnapshotFor } from "./snapshot-store.js";
12
+ import { contentChecksum } from "./hashline/hasher.js";
13
+ import { lineHashes, changedRange } from "./hashline/index.js";
14
+ import { getUndo, clearUndo } from "./undo-edit.js";
15
+ import { recordServedTruncated } from "./served-store.js";
16
+ import { UNDO_DESCRIPTION } from "./prompts.js";
17
+ import { execCwd, execSessionKey } from "./dsh-context.js";
18
18
  function assertUndoReq(request) {
19
19
  if (!isRec(request)) {
20
- throw new Error('[E_BAD_SHAPE] undo_last_edit request must be an object.');
20
+ throw new Error("[E_BAD_SHAPE] undo_last_edit request must be an object.");
21
21
  }
22
22
  normalizeFilePath(request);
23
- if (typeof request.path !== 'string' || request.path.length === 0) {
23
+ if (typeof request.path !== "string" || request.path.length === 0) {
24
24
  throw new Error('[E_BAD_SHAPE] undo_last_edit request requires a non-empty "path" string.');
25
25
  }
26
26
  }
@@ -33,18 +33,18 @@ function assertUndoReq(request) {
33
33
  */
34
34
  export function buildUndoTool(io) {
35
35
  return defineTool({
36
- name: 'undo_last_edit',
36
+ name: "undo_last_edit",
37
37
  description: UNDO_DESCRIPTION,
38
38
  parameters: {
39
39
  path: {
40
- type: 'string',
40
+ type: "string",
41
41
  required: true,
42
- description: 'Path to the file to undo',
42
+ description: "Path to the file to undo",
43
43
  },
44
44
  },
45
45
  output: {
46
- schema: { type: 'string' },
47
- render: (_args, value) => [{ type: 'text', text: value }],
46
+ schema: { type: "string" },
47
+ render: (_args, value) => [{ type: "text", text: value }],
48
48
  },
49
49
  async execute(args, exec) {
50
50
  const cwd = execCwd(exec);
@@ -64,7 +64,7 @@ export function buildUndoTool(io) {
64
64
  }
65
65
  catch (error) {
66
66
  const message = error instanceof Error ? error.message : String(error);
67
- if (message.includes('[E_NOT_FOUND]')) {
67
+ if (message.includes("[E_NOT_FOUND]")) {
68
68
  await clearUndo(absolutePath);
69
69
  return `[E_UNDO_STALE] Cannot undo last edit on ${path}: the file no longer exists. Call read() to inspect the current state.`;
70
70
  }
@@ -79,34 +79,28 @@ export function buildUndoTool(io) {
79
79
  const currentNormalized = toLF(currentStripped);
80
80
  const currentHashes = await lineHashes(currentNormalized, absolutePath);
81
81
  const diffResult = genDiff(undo.content, currentNormalized, 0, undefined, undo.hashes);
82
- const linesAddedByEdit = cntDiff(diffResult.diff, '+');
83
- const linesRemovedByEdit = cntDiff(diffResult.diff, '-');
82
+ const linesAddedByEdit = cntDiff(diffResult.diff, "+");
83
+ const linesRemovedByEdit = cntDiff(diffResult.diff, "-");
84
84
  const undoDiffResult = genDiff(currentNormalized, undo.content, 1, undo.hashes, currentHashes);
85
85
  const undoDiff = undoDiffResult.diff;
86
86
  const restoredRange = changedRange(currentNormalized, undo.content);
87
- await io.writeText(absolutePath, undo.bom + restoreEndings(undo.content, undo.originalEnding), signal);
87
+ await io.writeText(absolutePath, undo.bom + restoreEndings(undo.content, undo.originalEnding), signal, exec);
88
88
  try {
89
89
  await upsertSnapshotFor(absolutePath, contentChecksum(undo.content), splitLines(undo.content).length, undo.hashes);
90
90
  }
91
91
  catch (error) {
92
- console.error('Failed to restore hash store snapshot after undo:', error);
92
+ console.error("Failed to restore hash store snapshot after undo:", error);
93
93
  }
94
94
  await clearUndo(absolutePath);
95
95
  const parts = [`Undone last edit on ${path}.`];
96
96
  if (linesAddedByEdit > 0 || linesRemovedByEdit > 0) {
97
97
  parts.push(`Removed ${linesAddedByEdit} line(s) that were added and restored ${linesRemovedByEdit} line(s) that were removed.`);
98
98
  }
99
- parts.push('File reverted to previous state. The post-edit diff rows carry the restored file\u2019s fresh anchors for follow-up edits.');
99
+ parts.push("File reverted to previous state. The post-edit diff rows carry the restored file\u2019s fresh anchors for follow-up edits.");
100
100
  if (undoDiffResult.servedRows.length > 0) {
101
101
  await recordServedTruncated(sessionKey, absolutePath, undoDiffResult.servedRows, splitLines(undo.content).length, restoredRange?.firstChangedLine ?? 0);
102
102
  }
103
- return [
104
- parts.join('\n'),
105
- '',
106
- 'Diff of the revert:',
107
- '',
108
- undoDiff,
109
- ].join('\n');
103
+ return [parts.join("\n"), "", "Diff of the revert:", "", undoDiff].join("\n");
110
104
  },
111
105
  });
112
106
  }
@@ -1,20 +1,42 @@
1
1
  /**
2
2
  * IO seam for the hashline tool layer. The tools resolve, read, and write
3
3
  * through this bridge so they honor the deployment's `ctx.fs` backend — a
4
- * sandboxed or remote filesystem — instead of reaching around it. The local
5
- * implementation exists for tests and for pure-pipeline verification.
4
+ * sandboxed or remote filesystem — instead of reaching around it.
5
+ *
6
+ * The bridge also participates in dsh's `fs/*` event gate exactly like the
7
+ * built-in tools: writes dispatch `fs/write-intent` (so the observation policy
8
+ * derives its create/replace guard and stale-version checks) and every
9
+ * successful read/mutation emits `fs/observed` with the resulting version. A
10
+ * hashline tool that silently skipped those events would leave the policy's
11
+ * observed state stale, and the next built-in `write` on the same file would
12
+ * fail with `FS_NOT_OBSERVED` / `FS_STALE_VERSION`.
13
+ *
14
+ * The local implementation exists for tests and pure-pipeline verification.
6
15
  * @module dsh-better-edit/fs-bridge
7
16
  */
8
- import type { Context } from '@deepseek-ai/cordis';
9
- import type { FileSystem } from '@deepseek-ai/dsh-fs';
17
+ import type { Context } from "@deepseek-ai/cordis";
18
+ import type { FileSystem } from "@deepseek-ai/dsh-fs";
19
+ import type { ToolExecution } from "@deepseek-ai/dsh-tools";
10
20
  /** Text-IO operations the hashline tools need, keyed by canonical absolute path. */
11
21
  export interface FileIO {
12
22
  /** Resolve a (possibly relative) request path against the session cwd to a canonical absolute path. */
13
23
  resolve(path: string, cwd: string, signal?: AbortSignal): Promise<string>;
14
24
  /** Read whole text; missing files, directories, and binary content throw. */
15
25
  readText(absolutePath: string, signal?: AbortSignal): Promise<string>;
16
- /** Atomically write whole text, preserving mode when the file exists. */
17
- writeText(absolutePath: string, content: string, signal?: AbortSignal): Promise<void>;
26
+ /**
27
+ * Atomically write whole text, preserving mode when the file exists. On the
28
+ * dsh backend this dispatches `fs/write-intent` (policy guard) and emits
29
+ * `fs/observed` with the new version on success, so later built-in tools
30
+ * see a fresh observation.
31
+ * @param exec - the calling execution; carries the session the policy keys by.
32
+ */
33
+ writeText(absolutePath: string, content: string, signal?: AbortSignal, exec?: ToolExecution): Promise<void>;
34
+ /**
35
+ * Emit `fs/observed` (present at the current version) for a successful
36
+ * read, so the policy records that this session has seen the file.
37
+ * @param exec - the calling execution; carries the session the policy keys by.
38
+ */
39
+ emitObserved(absolutePath: string, exec?: ToolExecution, signal?: AbortSignal): Promise<void>;
18
40
  /** Opaque change-version for snapshot bookkeeping, or undefined when unavailable. */
19
41
  statVersion(absolutePath: string, signal?: AbortSignal): Promise<string | undefined>;
20
42
  }
@@ -27,6 +49,6 @@ export interface FileIO {
27
49
  */
28
50
  export declare function mapFsError(error: unknown, displayPath: string): never;
29
51
  /** FileIO over the deployment's `ctx.fs` service. */
30
- export declare function ctxFsIO(fs: FileSystem, _ctx: Context): FileIO;
52
+ export declare function ctxFsIO(fs: FileSystem, ctx: Context): FileIO;
31
53
  /** FileIO over the host filesystem directly (tests, previews, fallback). */
32
54
  export declare function localIO(): FileIO;
@@ -14,6 +14,14 @@
14
14
  import type { Context } from '@deepseek-ai/cordis';
15
15
  /** Cordis plugin name used by loader diagnostics. */
16
16
  export declare const name = "dsh-better-edit";
17
+ /**
18
+ * Services the plugin's per-agent install touches: `tools` and `systemPrompt`
19
+ * for the shadow registrations, `fs` for the IO bridge. Cordis refuses
20
+ * property access to an undeclared service ("cannot get property X without
21
+ * inject"), so these MUST be listed or every agent install fails at
22
+ * session-start.
23
+ */
24
+ export declare const inject: string[];
17
25
  /** One per-agent registration bundle, disposed with the agent. */
18
26
  interface AgentTools {
19
27
  dispose(): void;
@@ -5,8 +5,8 @@
5
5
  * the failing item's current range is echoed as fresh serves.
6
6
  * @module dsh-better-edit/tool-batch-edit
7
7
  */
8
- import type { Context } from '@deepseek-ai/cordis';
9
- import type { FileIO } from './fs-bridge.js';
8
+ import type { Context } from "@deepseek-ai/cordis";
9
+ import type { FileIO } from "./fs-bridge.js";
10
10
  /**
11
11
  * Register the `batch_edit` tool on the calling agent's scope.
12
12
  * @param _rootCtx - host context.
@@ -5,8 +5,8 @@
5
5
  * served-range verification, reject-and-serve) replaces the built-in one.
6
6
  * @module dsh-better-edit/tool-edit
7
7
  */
8
- import type { Context } from '@deepseek-ai/cordis';
9
- import type { FileIO } from './fs-bridge.js';
8
+ import type { Context } from "@deepseek-ai/cordis";
9
+ import type { FileIO } from "./fs-bridge.js";
10
10
  /**
11
11
  * Register the hash-anchored `edit` tool on the calling agent's scope.
12
12
  * @param _rootCtx - host context (logger, lifecycle).
@@ -5,8 +5,8 @@
5
5
  * shown the lines it targets.
6
6
  * @module dsh-better-edit/tool-read
7
7
  */
8
- import type { Context } from '@deepseek-ai/cordis';
9
- import type { FileIO } from './fs-bridge.js';
8
+ import type { Context } from "@deepseek-ai/cordis";
9
+ import type { FileIO } from "./fs-bridge.js";
10
10
  /**
11
11
  * Register the hash-anchored `read` tool on the calling agent's scope.
12
12
  * @param _rootCtx - host context.
@@ -4,8 +4,8 @@
4
4
  * external write clears the history instead of being overwritten.
5
5
  * @module dsh-better-edit/tool-undo
6
6
  */
7
- import type { Context } from '@deepseek-ai/cordis';
8
- import type { FileIO } from './fs-bridge.js';
7
+ import type { Context } from "@deepseek-ai/cordis";
8
+ import type { FileIO } from "./fs-bridge.js";
9
9
  /**
10
10
  * Register the `undo_last_edit` tool on the calling agent's scope.
11
11
  * @param _rootCtx - host context.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-better-edit",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
5
  "description": "Hash-anchored read/edit/batch_edit/undo_last_edit tools for DeepSeek Harness (dsh). Every line gets a unique 3-char hash (A-Za-z0-9) that stays stable across edits; stale or ambiguous anchors are rejected, never fuzzy-matched. Undo persists across restarts.",
6
6
  "main": "lib/index.js",