dsh-better-edit 0.1.1 → 0.1.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.
package/README.md CHANGED
@@ -137,13 +137,20 @@ hash store).
137
137
  ## Store
138
138
 
139
139
  Hash snapshots, served-state rows, and undo history live in one SQLite store
140
- under the DeepSeek Harness home:
140
+ **co-located with the workspace being edited** — one store per session cwd:
141
141
 
142
- - `$DSH_HOME/plugins/dsh-better-edit/hash-store.sqlite` (default
143
- `~/.dsh/plugins/dsh-better-edit/hash-store.sqlite`)
142
+ - `<workspace>/.dsh_better_edit/hash-store.sqlite`
143
+
144
+ Parallel sessions in different workspaces keep separate stores (the session
145
+ cwd is carried through each tool call), so one project's anchors and undo
146
+ history never leak into another's. Outside a tool call (tests, previews) the
147
+ store falls back to the shared DeepSeek Harness home
148
+ (`$DSH_HOME/plugins/dsh-better-edit/hash-store.sqlite`).
144
149
 
145
150
  A 7-day TTL prunes served rows; missing-file snapshots are pruned at startup.
146
- Corrupt stores are quarantined and rebuilt automatically.
151
+ Corrupt stores are quarantined and rebuilt automatically. Moving to the
152
+ per-workspace layout does not migrate earlier undo history from the shared
153
+ home — treat any pre-0.1.2 undo entries as gone.
147
154
 
148
155
  ## Error codes
149
156
 
package/lib/hash-store.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import { existsSync } from "node:fs";
2
- import { readFile, rename, mkdir } from "fs/promises";
2
+ import { readFile, rename, mkdir } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
3
4
  import { DatabaseSync } from "node:sqlite";
4
- import { hashStorePath, hashStoreDir, legacyHashStorePath } from "./paths.js";
5
+ import { hashStorePath } from "./paths.js";
6
+ import { workspaceCwd } from "./workspace.js";
5
7
  import { errCode, splitLines } from "./utils.js";
6
8
  import { initHasher, contentChecksum } from "./hashline/hasher.js";
7
9
  import { HASH_STORE_VERSION, HASH_STORE_BUSY_TIMEOUT, SERVED_TTL_MS } from "./constants.js";
@@ -51,8 +53,9 @@ function withBusyRetry(fn) {
51
53
  function openDbWithBusyRetry(storePath) {
52
54
  return withBusyRetry(() => openDb(storePath));
53
55
  }
54
- let cachedDb = null;
55
- let opening = null;
56
+ /** One open store per store path (per workspace); parallel sessions share per-workspace dbs. */
57
+ const stores = new Map();
58
+ const openings = new Map();
56
59
  let exitHandlerRegistered = false;
57
60
  function openDb(storePath) {
58
61
  const db = new DatabaseSync(storePath, {
@@ -232,9 +235,9 @@ function shutdownDb(db) {
232
235
  db.close();
233
236
  }
234
237
  async function openStore(storePath) {
235
- shutdownHashStore();
238
+ // Multi-store: never close another workspace's store when opening this one.
236
239
  await initHasher();
237
- await mkdir(hashStoreDir(), { recursive: true });
240
+ await mkdir(dirname(storePath), { recursive: true });
238
241
  let existed = existsSync(storePath);
239
242
  let opened;
240
243
  try {
@@ -256,12 +259,12 @@ async function openStore(storePath) {
256
259
  }
257
260
  const { db, stmts } = opened;
258
261
  if (!existed) {
259
- await migrateLegacy(db);
262
+ await migrateLegacy(db, storePath);
260
263
  }
261
264
  withBusyRetry(() => {
262
265
  stmts.servedPruneOlderThan(Date.now() - SERVED_TTL_MS);
263
266
  });
264
- cachedDb = { path: storePath, db, stmts };
267
+ stores.set(storePath, { path: storePath, db, stmts });
265
268
  if (!exitHandlerRegistered) {
266
269
  exitHandlerRegistered = true;
267
270
  process.once("exit", () => shutdownHashStore());
@@ -274,38 +277,60 @@ async function openStore(storePath) {
274
277
  }
275
278
  return { stmts, engine: "node:sqlite" };
276
279
  }
277
- export function loadHashStore() {
278
- const storePath = hashStorePath();
279
- if (cachedDb && cachedDb.path === storePath && cachedDb.db.isOpen) {
280
- return Promise.resolve({ stmts: cachedDb.stmts, engine: "node:sqlite" });
281
- }
282
- if (opening && opening.path === storePath) {
283
- return opening.promise;
280
+ /** Resolve the store path for this call: explicit cwd, the active workspace, or the shared-home fallback. */
281
+ function storePathFor(cwd) {
282
+ return hashStorePath(cwd ?? workspaceCwd());
283
+ }
284
+ /**
285
+ * Load (and cache) the hash store for the given cwd — or, when omitted, the
286
+ * workspace active for this async execution (`withWorkspace`), falling back to
287
+ * the shared `$DSH_HOME` store outside a tool call.
288
+ * @param cwd - optional explicit workspace root; defaults to the active workspace.
289
+ */
290
+ export function loadHashStore(cwd) {
291
+ const storePath = storePathFor(cwd);
292
+ const cached = stores.get(storePath);
293
+ if (cached && cached.db.isOpen) {
294
+ return Promise.resolve({ stmts: cached.stmts, engine: "node:sqlite" });
284
295
  }
296
+ const existing = openings.get(storePath);
297
+ if (existing)
298
+ return existing;
285
299
  const promise = openStore(storePath).finally(() => {
286
- if (opening?.path === storePath)
287
- opening = null;
300
+ openings.delete(storePath);
288
301
  });
289
- opening = { path: storePath, promise };
302
+ openings.set(storePath, promise);
290
303
  return promise;
291
304
  }
305
+ /** The cached store for the active workspace (or the shared-home fallback), if open. */
306
+ function currentStore() {
307
+ return stores.get(storePathFor())?.db.isOpen ? stores.get(storePathFor()) : undefined;
308
+ }
309
+ /** Close every open store (process exit, HMR, tests). */
292
310
  export function shutdownHashStore() {
293
- if (cachedDb) {
294
- shutdownDb(cachedDb.db);
295
- cachedDb = null;
311
+ for (const [, entry] of stores) {
312
+ shutdownDb(entry.db);
296
313
  }
314
+ stores.clear();
315
+ openings.clear();
297
316
  }
317
+ /**
318
+ * Run `fn` inside one BEGIN IMMEDIATE transaction on the active workspace's
319
+ * store. Without an open store for this context the call runs bare (the
320
+ * caller has already loaded the store in every in-process path).
321
+ */
298
322
  export function withStore(fn) {
299
- if (cachedDb) {
323
+ const store = currentStore();
324
+ if (store) {
300
325
  withBusyRetry(() => {
301
- cachedDb.db.exec("BEGIN IMMEDIATE");
326
+ store.db.exec("BEGIN IMMEDIATE");
302
327
  try {
303
328
  fn();
304
- cachedDb.db.exec("COMMIT");
329
+ store.db.exec("COMMIT");
305
330
  }
306
331
  catch (e) {
307
332
  try {
308
- cachedDb.db.exec("ROLLBACK");
333
+ store.db.exec("ROLLBACK");
309
334
  }
310
335
  catch { }
311
336
  throw e;
@@ -316,8 +341,8 @@ export function withStore(fn) {
316
341
  fn();
317
342
  }
318
343
  }
319
- async function migrateLegacy(db) {
320
- const legacyPath = legacyHashStorePath();
344
+ async function migrateLegacy(db, storePath) {
345
+ const legacyPath = join(dirname(storePath), "hash-store.json");
321
346
  let content;
322
347
  try {
323
348
  content = await readFile(legacyPath, "utf-8");
package/lib/index.js CHANGED
@@ -11,17 +11,16 @@
11
11
  * preview to write results.
12
12
  * @module dsh-better-edit
13
13
  */
14
- import { ctxFsIO } from './fs-bridge.js';
15
- import { registerReadTool } from './tool-read.js';
16
- import { registerEditTool } from './tool-edit.js';
17
- import { registerBatchEditTool } from './tool-batch-edit.js';
18
- import { registerUndoTool } from './tool-undo.js';
19
- import { registerWriteHook } from './write-hook.js';
20
- import { initHasher } from './hashline/hasher.js';
21
- import { pruneMissingAll } from './snapshot-store.js';
22
- import { EDIT_DESCRIPTION, EDIT_GUIDELINES, READ_GUIDELINES, BATCH_EDIT_GUIDELINES, UNDO_GUIDELINES, } from './prompts.js';
14
+ import { ctxFsIO } from "./fs-bridge.js";
15
+ import { registerReadTool } from "./tool-read.js";
16
+ import { registerEditTool } from "./tool-edit.js";
17
+ import { registerBatchEditTool } from "./tool-batch-edit.js";
18
+ import { registerUndoTool } from "./tool-undo.js";
19
+ import { registerWriteHook } from "./write-hook.js";
20
+ import { initHasher } from "./hashline/hasher.js";
21
+ import { EDIT_DESCRIPTION, EDIT_GUIDELINES, READ_GUIDELINES, BATCH_EDIT_GUIDELINES, UNDO_GUIDELINES, } from "./prompts.js";
23
22
  /** Cordis plugin name used by loader diagnostics. */
24
- export const name = 'dsh-better-edit';
23
+ export const name = "dsh-better-edit";
25
24
  /**
26
25
  * Services the plugin's per-agent install touches: `tools` and `systemPrompt`
27
26
  * for the shadow registrations, `fs` for the IO bridge. Cordis refuses
@@ -29,7 +28,7 @@ export const name = 'dsh-better-edit';
29
28
  * inject"), so these MUST be listed or every agent install fails at
30
29
  * session-start.
31
30
  */
32
- export const inject = ['tools', 'systemPrompt', 'fs'];
31
+ export const inject = ["tools", "systemPrompt", "fs"];
33
32
  function installAgentTools(rootCtx, agent) {
34
33
  return agent.ctx.effect(() => {
35
34
  // `fs` is host-plane: use the plugin's own context (covered by
@@ -46,32 +45,32 @@ function installAgentTools(rootCtx, agent) {
46
45
  // Shadow the preset's built-in tool guidance with the hashline contract.
47
46
  // Same section names on the agent's own layer win over the preset's.
48
47
  disposers.push(agent.ctx.systemPrompt.section({
49
- name: 'tool:edit',
48
+ name: "tool:edit",
50
49
  order: 102,
51
50
  text: [
52
51
  EDIT_DESCRIPTION,
53
- '',
54
- EDIT_GUIDELINES.map((line) => `- ${line}`).join('\n'),
55
- ].join('\n'),
52
+ "",
53
+ EDIT_GUIDELINES.map((line) => `- ${line}`).join("\n"),
54
+ ].join("\n"),
56
55
  }));
57
56
  disposers.push(agent.ctx.systemPrompt.section({
58
- name: 'tool:read',
57
+ name: "tool:read",
59
58
  order: 100,
60
59
  text: [
61
- 'Use the read tool — not shell commands like cat — to inspect text files.',
62
- '',
63
- READ_GUIDELINES.map((line) => `- ${line}`).join('\n'),
64
- ].join('\n'),
60
+ "Use the read tool — not shell commands like cat — to inspect text files.",
61
+ "",
62
+ READ_GUIDELINES.map((line) => `- ${line}`).join("\n"),
63
+ ].join("\n"),
65
64
  }));
66
65
  disposers.push(agent.ctx.systemPrompt.section({
67
- name: 'tool:batch_edit',
66
+ name: "tool:batch_edit",
68
67
  order: 103,
69
- text: BATCH_EDIT_GUIDELINES.map((line) => `- ${line}`).join('\n'),
68
+ text: BATCH_EDIT_GUIDELINES.map((line) => `- ${line}`).join("\n"),
70
69
  }));
71
70
  disposers.push(agent.ctx.systemPrompt.section({
72
- name: 'tool:undo_last_edit',
71
+ name: "tool:undo_last_edit",
73
72
  order: 104,
74
- text: UNDO_GUIDELINES.map((line) => `- ${line}`).join('\n'),
73
+ text: UNDO_GUIDELINES.map((line) => `- ${line}`).join("\n"),
75
74
  }));
76
75
  return () => {
77
76
  for (const dispose of disposers)
@@ -81,15 +80,14 @@ function installAgentTools(rootCtx, agent) {
81
80
  }
82
81
  /** Mount the bundle: initialize the store, then install tools per agent. */
83
82
  export function apply(rootCtx) {
84
- // Warm the hasher and prune missing snapshots once; failures are non-fatal
85
- // (each store operation retries on demand).
86
- initHasher()
87
- .then(() => pruneMissingAll())
88
- .catch((error) => {
89
- rootCtx.logger.warn(`dsh-better-edit: hash-store warm-up failed: ${error instanceof Error ? error.message : String(error)}`);
83
+ // Warm the hasher once; the per-workspace stores are opened lazily on the
84
+ // first tool call in each workspace (there is no shared store to prune at
85
+ // boot anymore).
86
+ initHasher().catch((error) => {
87
+ rootCtx.logger.warn(`dsh-better-edit: hasher warm-up failed: ${error instanceof Error ? error.message : String(error)}`);
90
88
  });
91
89
  const registered = new WeakSet();
92
- rootCtx.on('agent/session-start', ({ agent }) => {
90
+ rootCtx.on("agent/session-start", ({ agent }) => {
93
91
  if (registered.has(agent))
94
92
  return;
95
93
  registered.add(agent);
package/lib/paths.js CHANGED
@@ -2,22 +2,28 @@ import { homedir } from "node:os";
2
2
  import { isAbsolute, resolve as resolvePath, join, dirname } from "node:path";
3
3
  import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
4
4
  /**
5
- * On-disk home for dsh-better-edit state, under the DeepSeek Harness home
6
- * ($DSH_HOME, defaulting to ~/.dsh). The hashline hash snapshots, served-state
7
- * rows, and undo history live under a plugin-owned subdirectory so multiple
8
- * dsh installs on one machine share one coherent store keyed by absolute path.
5
+ * On-disk home for dsh-better-edit state. Inside a tool call the store lives
6
+ * co-located with the files being edited: `<workspace>/.dsh_better_edit/` (the
7
+ * workspace is the session cwd, carried through the execution by
8
+ * `withWorkspace`). Outside a tool call — tests, previews, startup — the store
9
+ * falls back to the shared DeepSeek Harness home
10
+ * (`$DSH_HOME/plugins/dsh-better-edit`, default `~/.dsh/plugins/dsh-better-edit`),
11
+ * so a caller without a workspace never writes into an arbitrary cwd.
12
+ * @param cwd - the workspace root, or undefined for the shared-home fallback.
9
13
  */
10
- export function configDir() {
11
- return join(resolveDshHome(), "plugins", "dsh-better-edit");
14
+ export function configDir(cwd) {
15
+ return cwd !== undefined
16
+ ? join(resolvePath(cwd), ".dsh_better_edit")
17
+ : join(resolveDshHome(), "plugins", "dsh-better-edit");
12
18
  }
13
- export function hashStorePath() {
14
- return join(configDir(), "hash-store.sqlite");
19
+ export function hashStorePath(cwd) {
20
+ return join(configDir(cwd), "hash-store.sqlite");
15
21
  }
16
- export function legacyHashStorePath() {
17
- return join(configDir(), "hash-store.json");
22
+ export function legacyHashStorePath(cwd) {
23
+ return join(configDir(cwd), "hash-store.json");
18
24
  }
19
- export function hashStoreDir() {
20
- return dirname(hashStorePath());
25
+ export function hashStoreDir(cwd) {
26
+ return dirname(hashStorePath(cwd));
21
27
  }
22
28
  function homeBase() {
23
29
  const envHome = process.env.HOME;
@@ -22,6 +22,7 @@ import { clearNoopLoop, noopPayloadKey, trackNoopPayload, } from "./noop-guard.j
22
22
  import { BATCH_EDIT_DESCRIPTION } from "./prompts.js";
23
23
  import { pathSchema, removeFromSchema, removeToSchema, replacementTextSchema, } from "./schema.js";
24
24
  import { execCwd, execSessionKey } from "./dsh-context.js";
25
+ import { withWorkspace } from "./workspace.js";
25
26
  const BATCH_ITEM_KS = new Set([
26
27
  "path",
27
28
  "remove_from",
@@ -341,93 +342,95 @@ export function buildBatchEditTool(io) {
341
342
  render: (_args, value) => [{ type: "text", text: value }],
342
343
  },
343
344
  async execute(args, exec) {
344
- const cwd = execCwd(exec);
345
- const sessionKey = execSessionKey(exec);
346
- const signal = exec.signal;
347
- const canonical = normReq(args);
348
- if (isRec(canonical) && Array.isArray(canonical.edits)) {
349
- canonical.edits = canonical.edits.map((item) => {
350
- if (!isRec(item))
351
- return item;
352
- const cloned = { ...item };
353
- normalizeFilePath(cloned);
354
- return cloned;
355
- });
356
- }
357
- assertBatchReq(canonical);
358
- const items = await prepareItems(io, canonical, cwd, signal);
359
- const groups = groupByPath(items);
360
- const processed = [];
361
- for (const groupItems of groups.values()) {
362
- abortIf(signal);
363
- processed.push(await processFile(io, groupItems, cwd, {
364
- signal,
365
- sessionKey,
366
- }));
367
- }
368
- const undos = [];
369
- for (const file of processed) {
370
- if (file.appliedCount === 0)
371
- continue;
372
- const undo = await saveUndo(file.absolutePath, {
373
- content: file.originalNormalized,
374
- bom: file.bom,
375
- originalEnding: file.originalEnding,
376
- hashes: file.originalHashes,
377
- resultContent: file.result,
378
- });
379
- if (!undo.persisted) {
380
- for (const u of undos) {
381
- try {
382
- await u.restore();
383
- }
384
- catch (error) {
385
- console.error("Failed to restore undo entry after batch abort:", error);
386
- }
387
- }
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.");
345
+ return withWorkspace(execCwd(exec), async () => {
346
+ const cwd = execCwd(exec);
347
+ const sessionKey = execSessionKey(exec);
348
+ const signal = exec.signal;
349
+ const canonical = normReq(args);
350
+ if (isRec(canonical) && Array.isArray(canonical.edits)) {
351
+ canonical.edits = canonical.edits.map((item) => {
352
+ if (!isRec(item))
353
+ return item;
354
+ const cloned = { ...item };
355
+ normalizeFilePath(cloned);
356
+ return cloned;
357
+ });
389
358
  }
390
- undos.push({ file, restore: undo.restore });
391
- }
392
- const written = [];
393
- try {
394
- for (const u of undos) {
359
+ assertBatchReq(canonical);
360
+ const items = await prepareItems(io, canonical, cwd, signal);
361
+ const groups = groupByPath(items);
362
+ const processed = [];
363
+ for (const groupItems of groups.values()) {
395
364
  abortIf(signal);
396
- await io.writeText(u.file.absolutePath, u.file.bom + restoreEndings(u.file.result, u.file.originalEnding), signal, exec);
397
- written.push(u);
365
+ processed.push(await processFile(io, groupItems, cwd, {
366
+ signal,
367
+ sessionKey,
368
+ }));
398
369
  }
399
- }
400
- catch (error) {
401
- for (const w of written) {
402
- try {
403
- await io.writeText(w.file.absolutePath, w.file.bom +
404
- restoreEndings(w.file.originalNormalized, w.file.originalEnding), undefined, exec);
405
- }
406
- catch (restoreError) {
407
- console.error("Failed to restore file after batch write failure:", restoreError);
370
+ const undos = [];
371
+ for (const file of processed) {
372
+ if (file.appliedCount === 0)
373
+ continue;
374
+ const undo = await saveUndo(file.absolutePath, {
375
+ content: file.originalNormalized,
376
+ bom: file.bom,
377
+ originalEnding: file.originalEnding,
378
+ hashes: file.originalHashes,
379
+ resultContent: file.result,
380
+ });
381
+ if (!undo.persisted) {
382
+ for (const u of undos) {
383
+ try {
384
+ await u.restore();
385
+ }
386
+ catch (error) {
387
+ console.error("Failed to restore undo entry after batch abort:", error);
388
+ }
389
+ }
390
+ 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.");
408
391
  }
409
- try {
410
- await w.restore();
392
+ undos.push({ file, restore: undo.restore });
393
+ }
394
+ const written = [];
395
+ try {
396
+ for (const u of undos) {
397
+ abortIf(signal);
398
+ await io.writeText(u.file.absolutePath, u.file.bom + restoreEndings(u.file.result, u.file.originalEnding), signal, exec);
399
+ written.push(u);
411
400
  }
412
- catch (restoreError) {
413
- console.error("Failed to restore undo entry after batch write failure:", restoreError);
401
+ }
402
+ catch (error) {
403
+ for (const w of written) {
404
+ try {
405
+ await io.writeText(w.file.absolutePath, w.file.bom +
406
+ restoreEndings(w.file.originalNormalized, w.file.originalEnding), undefined, exec);
407
+ }
408
+ catch (restoreError) {
409
+ console.error("Failed to restore file after batch write failure:", restoreError);
410
+ }
411
+ try {
412
+ await w.restore();
413
+ }
414
+ catch (restoreError) {
415
+ console.error("Failed to restore undo entry after batch write failure:", restoreError);
416
+ }
414
417
  }
418
+ throw error;
415
419
  }
416
- throw error;
417
- }
418
- const result = buildBatchResult(processed.map(toSection));
419
- if (result.details.servedRows && result.details.servedRows.length > 0) {
420
- const byPath = result.details.servedByPath ?? [];
421
- for (const entry of byPath) {
422
- if (entry.servedRows.length === 0)
423
- continue;
424
- const file = processed.find((f) => f.displayPath === entry.path);
425
- if (file) {
426
- await recordServedTruncated(sessionKey, file.absolutePath, entry.servedRows, splitLines(file.result).length, file.range.startLine - 1);
420
+ const result = buildBatchResult(processed.map(toSection));
421
+ if (result.details.servedRows && result.details.servedRows.length > 0) {
422
+ const byPath = result.details.servedByPath ?? [];
423
+ for (const entry of byPath) {
424
+ if (entry.servedRows.length === 0)
425
+ continue;
426
+ const file = processed.find((f) => f.displayPath === entry.path);
427
+ if (file) {
428
+ await recordServedTruncated(sessionKey, file.absolutePath, entry.servedRows, splitLines(file.result).length, file.range.startLine - 1);
429
+ }
427
430
  }
428
431
  }
429
- }
430
- return result.content[0].text;
432
+ return result.content[0].text;
433
+ });
431
434
  },
432
435
  });
433
436
  }
package/lib/tool-edit.js CHANGED
@@ -19,6 +19,7 @@ import { NOOP_LOOP_THRESHOLD } from "./constants.js";
19
19
  import { EDIT_DESCRIPTION } from "./prompts.js";
20
20
  import { pathSchema, removeFromSchema, removeToSchema, replacementTextSchema, } from "./schema.js";
21
21
  import { execCwd, execSessionKey } from "./dsh-context.js";
22
+ import { withWorkspace } from "./workspace.js";
22
23
  /**
23
24
  * Register the hash-anchored `edit` tool on the calling agent's scope.
24
25
  * @param _rootCtx - host context (logger, lifecycle).
@@ -42,105 +43,107 @@ export function buildEditTool(io) {
42
43
  render: (_args, value) => [{ type: "text", text: value }],
43
44
  },
44
45
  async execute(args, exec) {
45
- const cwd = execCwd(exec);
46
- const sessionKey = execSessionKey(exec);
47
- const signal = exec.signal;
48
- const canonical = normReq(args);
49
- const resolution = isRec(canonical)
50
- ? await resolveMissingPath(canonical)
51
- : undefined;
52
- if (resolution && isRec(canonical)) {
53
- canonical.path = resolution.path;
54
- }
55
- assertReq(canonical);
56
- const normalizedParams = canonical;
57
- const path = normalizedParams.path;
58
- abortIf(signal);
59
- const pipeline = await execPipeline(io, normalizedParams, cwd, {
60
- signal,
61
- sessionKey,
62
- });
63
- const { originalNormalized, originalHashes, result, bom, originalEnding, hadUtf8DecodeErrors, warnings, noopEdit, firstChangedLine, lastChangedLine, resultHashes, totalAddedLines, totalRemovedLines, driftNotice, range, absolutePath, } = pipeline;
64
- if (resolution) {
65
- warnings.unshift(resolution.warning);
66
- }
67
- const editsAttempted = 1;
68
- if (originalNormalized === result) {
69
- const payload = noopPayloadKey(absolutePath, canonical.remove_from, canonical.remove_to, canonical.replacement_text);
70
- const count = trackNoopPayload(absolutePath, payload);
71
- if (count >= NOOP_LOOP_THRESHOLD) {
72
- const echoRows = buildRangeEcho(range.startLine, range.endLine, originalHashes);
73
- const echo = fmtServedRows(echoRows, splitLines(originalNormalized));
74
- await recordEchoServes(sessionKey, absolutePath, echoRows, "live");
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}`);
46
+ return withWorkspace(execCwd(exec), async () => {
47
+ const cwd = execCwd(exec);
48
+ const sessionKey = execSessionKey(exec);
49
+ const signal = exec.signal;
50
+ const canonical = normReq(args);
51
+ const resolution = isRec(canonical)
52
+ ? await resolveMissingPath(canonical)
53
+ : undefined;
54
+ if (resolution && isRec(canonical)) {
55
+ canonical.path = resolution.path;
56
+ }
57
+ assertReq(canonical);
58
+ const normalizedParams = canonical;
59
+ const path = normalizedParams.path;
60
+ abortIf(signal);
61
+ const pipeline = await execPipeline(io, normalizedParams, cwd, {
62
+ signal,
63
+ sessionKey,
64
+ });
65
+ const { originalNormalized, originalHashes, result, bom, originalEnding, hadUtf8DecodeErrors, warnings, noopEdit, firstChangedLine, lastChangedLine, resultHashes, totalAddedLines, totalRemovedLines, driftNotice, range, absolutePath, } = pipeline;
66
+ if (resolution) {
67
+ warnings.unshift(resolution.warning);
76
68
  }
77
- if (count === 2) {
78
- warnings.push(`[E_NOOP_LOOP] Notice: this exact edit (anchors ${canonical.remove_from} to ${canonical.remove_to} in ${path}) has produced no changes twice in a row. The range already contains the replacement text; resending it again will be rejected.`);
69
+ const editsAttempted = 1;
70
+ if (originalNormalized === result) {
71
+ const payload = noopPayloadKey(absolutePath, canonical.remove_from, canonical.remove_to, canonical.replacement_text);
72
+ const count = trackNoopPayload(absolutePath, payload);
73
+ if (count >= NOOP_LOOP_THRESHOLD) {
74
+ const echoRows = buildRangeEcho(range.startLine, range.endLine, originalHashes);
75
+ const echo = fmtServedRows(echoRows, splitLines(originalNormalized));
76
+ await recordEchoServes(sessionKey, absolutePath, echoRows, "live");
77
+ 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}`);
78
+ }
79
+ if (count === 2) {
80
+ warnings.push(`[E_NOOP_LOOP] Notice: this exact edit (anchors ${canonical.remove_from} to ${canonical.remove_to} in ${path}) has produced no changes twice in a row. The range already contains the replacement text; resending it again will be rejected.`);
81
+ }
82
+ const noopSnapshotId = await snapshotIdFor(io, absolutePath, signal);
83
+ const noopResult = buildNoop({
84
+ path,
85
+ noopEdit,
86
+ snapshotId: noopSnapshotId,
87
+ editMeta: {
88
+ editsAttempted,
89
+ noopEditsCount: noopEdit ? 1 : 0,
90
+ addedLines: 0,
91
+ removedLines: 0,
92
+ },
93
+ warnings,
94
+ driftNotice,
95
+ });
96
+ return noopResult.content[0].text;
79
97
  }
80
- const noopSnapshotId = await snapshotIdFor(io, absolutePath, signal);
81
- const noopResult = buildNoop({
98
+ clearNoopLoop(absolutePath);
99
+ if (hadUtf8DecodeErrors) {
100
+ warnings.push("Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.");
101
+ }
102
+ abortIf(signal);
103
+ const undo = await saveUndo(absolutePath, {
104
+ content: originalNormalized,
105
+ bom,
106
+ originalEnding,
107
+ hashes: originalHashes,
108
+ resultContent: result,
109
+ });
110
+ if (!undo.persisted) {
111
+ throw new Error(`[E_UNDO_UNAVAILABLE] Cannot persist undo history to the hash store; the edit was NOT applied and ${path} is unchanged. Retry the edit, or use write if the store cannot be recovered.`);
112
+ }
113
+ try {
114
+ abortIf(signal);
115
+ await io.writeText(absolutePath, bom + restoreEndings(result, originalEnding), signal, exec);
116
+ }
117
+ catch (error) {
118
+ await undo.restore();
119
+ throw error;
120
+ }
121
+ const updatedSnapshotId = await snapshotIdFor(io, absolutePath, signal);
122
+ const editMeta = {
123
+ editsAttempted,
124
+ noopEditsCount: noopEdit ? 1 : 0,
125
+ firstChangedLine,
126
+ lastChangedLine,
127
+ addedLines: totalAddedLines,
128
+ removedLines: totalRemovedLines,
129
+ };
130
+ const successInput = {
82
131
  path,
83
- noopEdit,
84
- snapshotId: noopSnapshotId,
85
- editMeta: {
86
- editsAttempted,
87
- noopEditsCount: noopEdit ? 1 : 0,
88
- addedLines: 0,
89
- removedLines: 0,
90
- },
132
+ originalNormalized,
133
+ originalHashes,
134
+ result,
135
+ resultHashes,
91
136
  warnings,
137
+ snapshotId: updatedSnapshotId,
138
+ editMeta,
92
139
  driftNotice,
93
- });
94
- return noopResult.content[0].text;
95
- }
96
- clearNoopLoop(absolutePath);
97
- if (hadUtf8DecodeErrors) {
98
- warnings.push("Non-UTF-8 bytes were shown as U+FFFD; this edit rewrote the file as UTF-8.");
99
- }
100
- abortIf(signal);
101
- const undo = await saveUndo(absolutePath, {
102
- content: originalNormalized,
103
- bom,
104
- originalEnding,
105
- hashes: originalHashes,
106
- resultContent: result,
140
+ };
141
+ const changed = buildChanged(successInput);
142
+ if (changed.details.servedRows && changed.details.servedRows.length > 0) {
143
+ await recordServedTruncated(sessionKey, absolutePath, changed.details.servedRows, splitLines(result).length, range.startLine - 1);
144
+ }
145
+ return changed.content[0].text;
107
146
  });
108
- if (!undo.persisted) {
109
- throw new Error(`[E_UNDO_UNAVAILABLE] Cannot persist undo history to the hash store; the edit was NOT applied and ${path} is unchanged. Retry the edit, or use write if the store cannot be recovered.`);
110
- }
111
- try {
112
- abortIf(signal);
113
- await io.writeText(absolutePath, bom + restoreEndings(result, originalEnding), signal, exec);
114
- }
115
- catch (error) {
116
- await undo.restore();
117
- throw error;
118
- }
119
- const updatedSnapshotId = await snapshotIdFor(io, absolutePath, signal);
120
- const editMeta = {
121
- editsAttempted,
122
- noopEditsCount: noopEdit ? 1 : 0,
123
- firstChangedLine,
124
- lastChangedLine,
125
- addedLines: totalAddedLines,
126
- removedLines: totalRemovedLines,
127
- };
128
- const successInput = {
129
- path,
130
- originalNormalized,
131
- originalHashes,
132
- result,
133
- resultHashes,
134
- warnings,
135
- snapshotId: updatedSnapshotId,
136
- editMeta,
137
- driftNotice,
138
- };
139
- const changed = buildChanged(successInput);
140
- if (changed.details.servedRows && changed.details.servedRows.length > 0) {
141
- await recordServedTruncated(sessionKey, absolutePath, changed.details.servedRows, splitLines(result).length, range.startLine - 1);
142
- }
143
- return changed.content[0].text;
144
147
  },
145
148
  });
146
149
  }
package/lib/tool-read.js CHANGED
@@ -14,6 +14,7 @@ import { recordServed, clearDriftReported } from "./served-store.js";
14
14
  import { READ_DESCRIPTION } from "./prompts.js";
15
15
  import { pathSchema } from "./schema.js";
16
16
  import { execCwd, execSessionKey } from "./dsh-context.js";
17
+ import { withWorkspace } from "./workspace.js";
17
18
  const ROOT_KS = new Set(["path", "offset", "limit"]);
18
19
  function assertReadReq(request) {
19
20
  if (!isRec(request)) {
@@ -51,34 +52,36 @@ export function buildReadTool(io) {
51
52
  render: (_args, value) => [{ type: "text", text: value }],
52
53
  },
53
54
  async execute(args, exec) {
54
- const cwd = execCwd(exec);
55
- const sessionKey = execSessionKey(exec);
56
- const signal = exec.signal;
57
- const canonical = normReq(args);
58
- assertReadReq(canonical);
59
- const rawPath = canonical.path;
60
- abortIf(signal);
61
- const absolutePath = await io.resolve(rawPath, cwd, signal);
62
- const rawText = await io.readText(absolutePath, signal);
63
- const { normalized, fileHashes, hadUtf8DecodeErrors } = await normFromText({
64
- absolutePath,
65
- rawText,
66
- displayPath: rawPath,
67
- signal,
68
- maxLines: MAX_HASH_LINES,
55
+ return withWorkspace(execCwd(exec), async () => {
56
+ const cwd = execCwd(exec);
57
+ const sessionKey = execSessionKey(exec);
58
+ const signal = exec.signal;
59
+ const canonical = normReq(args);
60
+ assertReadReq(canonical);
61
+ const rawPath = canonical.path;
62
+ abortIf(signal);
63
+ const absolutePath = await io.resolve(rawPath, cwd, signal);
64
+ const rawText = await io.readText(absolutePath, signal);
65
+ const { normalized, fileHashes, hadUtf8DecodeErrors } = await normFromText({
66
+ absolutePath,
67
+ rawText,
68
+ displayPath: rawPath,
69
+ signal,
70
+ maxLines: MAX_HASH_LINES,
71
+ });
72
+ const preview = await fmtReadPreview(normalized, { offset: canonical.offset, limit: canonical.limit }, fileHashes, absolutePath);
73
+ if (preview.served.length > 0) {
74
+ await recordServed(sessionKey, absolutePath, preview.served);
75
+ }
76
+ await clearDriftReported(sessionKey, absolutePath);
77
+ // Record the present observation with the fs policy gate so later
78
+ // built-in write/edit calls see this file as observed at the
79
+ // version the model just read (a no-op when no policy listens).
80
+ await io.emitObserved(absolutePath, exec, signal);
81
+ return hadUtf8DecodeErrors
82
+ ? `${preview.text}\n\n[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]`
83
+ : preview.text;
69
84
  });
70
- const preview = await fmtReadPreview(normalized, { offset: canonical.offset, limit: canonical.limit }, fileHashes, absolutePath);
71
- if (preview.served.length > 0) {
72
- await recordServed(sessionKey, absolutePath, preview.served);
73
- }
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);
79
- return hadUtf8DecodeErrors
80
- ? `${preview.text}\n\n[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]`
81
- : preview.text;
82
85
  },
83
86
  });
84
87
  }
package/lib/tool-undo.js CHANGED
@@ -15,6 +15,7 @@ import { getUndo, clearUndo } from "./undo-edit.js";
15
15
  import { recordServedTruncated } from "./served-store.js";
16
16
  import { UNDO_DESCRIPTION } from "./prompts.js";
17
17
  import { execCwd, execSessionKey } from "./dsh-context.js";
18
+ import { withWorkspace } from "./workspace.js";
18
19
  function assertUndoReq(request) {
19
20
  if (!isRec(request)) {
20
21
  throw new Error("[E_BAD_SHAPE] undo_last_edit request must be an object.");
@@ -47,60 +48,62 @@ export function buildUndoTool(io) {
47
48
  render: (_args, value) => [{ type: "text", text: value }],
48
49
  },
49
50
  async execute(args, exec) {
50
- const cwd = execCwd(exec);
51
- const sessionKey = execSessionKey(exec);
52
- const signal = exec.signal;
53
- const canonical = normReq(args);
54
- assertUndoReq(canonical);
55
- const path = canonical.path;
56
- const absolutePath = await io.resolve(path, cwd, signal);
57
- const undo = await getUndo(absolutePath);
58
- if (!undo) {
59
- return `No undo history for ${path}. There is no previous edit to revert.`;
60
- }
61
- let currentRaw;
62
- try {
63
- currentRaw = await io.readText(absolutePath, signal);
64
- }
65
- catch (error) {
66
- const message = error instanceof Error ? error.message : String(error);
67
- if (message.includes("[E_NOT_FOUND]")) {
51
+ return withWorkspace(execCwd(exec), async () => {
52
+ const cwd = execCwd(exec);
53
+ const sessionKey = execSessionKey(exec);
54
+ const signal = exec.signal;
55
+ const canonical = normReq(args);
56
+ assertUndoReq(canonical);
57
+ const path = canonical.path;
58
+ const absolutePath = await io.resolve(path, cwd, signal);
59
+ const undo = await getUndo(absolutePath);
60
+ if (!undo) {
61
+ return `No undo history for ${path}. There is no previous edit to revert.`;
62
+ }
63
+ let currentRaw;
64
+ try {
65
+ currentRaw = await io.readText(absolutePath, signal);
66
+ }
67
+ catch (error) {
68
+ const message = error instanceof Error ? error.message : String(error);
69
+ if (message.includes("[E_NOT_FOUND]")) {
70
+ await clearUndo(absolutePath);
71
+ return `[E_UNDO_STALE] Cannot undo last edit on ${path}: the file no longer exists. Call read() to inspect the current state.`;
72
+ }
73
+ throw error;
74
+ }
75
+ if (currentRaw !==
76
+ undo.bom + restoreEndings(undo.resultContent, undo.originalEnding)) {
68
77
  await clearUndo(absolutePath);
69
- return `[E_UNDO_STALE] Cannot undo last edit on ${path}: the file no longer exists. Call read() to inspect the current state.`;
78
+ return `[E_UNDO_STALE] Cannot undo last edit on ${path}: the file was modified after the edit, so undoing would overwrite those changes. Call read() to inspect the current state.`;
79
+ }
80
+ const { text: currentStripped } = stripBOM(currentRaw);
81
+ const currentNormalized = toLF(currentStripped);
82
+ const currentHashes = await lineHashes(currentNormalized, absolutePath);
83
+ const diffResult = genDiff(undo.content, currentNormalized, 0, undefined, undo.hashes);
84
+ const linesAddedByEdit = cntDiff(diffResult.diff, "+");
85
+ const linesRemovedByEdit = cntDiff(diffResult.diff, "-");
86
+ const undoDiffResult = genDiff(currentNormalized, undo.content, 1, undo.hashes, currentHashes);
87
+ const undoDiff = undoDiffResult.diff;
88
+ const restoredRange = changedRange(currentNormalized, undo.content);
89
+ await io.writeText(absolutePath, undo.bom + restoreEndings(undo.content, undo.originalEnding), signal, exec);
90
+ try {
91
+ await upsertSnapshotFor(absolutePath, contentChecksum(undo.content), splitLines(undo.content).length, undo.hashes);
92
+ }
93
+ catch (error) {
94
+ console.error("Failed to restore hash store snapshot after undo:", error);
70
95
  }
71
- throw error;
72
- }
73
- if (currentRaw !==
74
- undo.bom + restoreEndings(undo.resultContent, undo.originalEnding)) {
75
96
  await clearUndo(absolutePath);
76
- return `[E_UNDO_STALE] Cannot undo last edit on ${path}: the file was modified after the edit, so undoing would overwrite those changes. Call read() to inspect the current state.`;
77
- }
78
- const { text: currentStripped } = stripBOM(currentRaw);
79
- const currentNormalized = toLF(currentStripped);
80
- const currentHashes = await lineHashes(currentNormalized, absolutePath);
81
- const diffResult = genDiff(undo.content, currentNormalized, 0, undefined, undo.hashes);
82
- const linesAddedByEdit = cntDiff(diffResult.diff, "+");
83
- const linesRemovedByEdit = cntDiff(diffResult.diff, "-");
84
- const undoDiffResult = genDiff(currentNormalized, undo.content, 1, undo.hashes, currentHashes);
85
- const undoDiff = undoDiffResult.diff;
86
- const restoredRange = changedRange(currentNormalized, undo.content);
87
- await io.writeText(absolutePath, undo.bom + restoreEndings(undo.content, undo.originalEnding), signal, exec);
88
- try {
89
- await upsertSnapshotFor(absolutePath, contentChecksum(undo.content), splitLines(undo.content).length, undo.hashes);
90
- }
91
- catch (error) {
92
- console.error("Failed to restore hash store snapshot after undo:", error);
93
- }
94
- await clearUndo(absolutePath);
95
- const parts = [`Undone last edit on ${path}.`];
96
- if (linesAddedByEdit > 0 || linesRemovedByEdit > 0) {
97
- parts.push(`Removed ${linesAddedByEdit} line(s) that were added and restored ${linesRemovedByEdit} line(s) that were removed.`);
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.");
100
- if (undoDiffResult.servedRows.length > 0) {
101
- await recordServedTruncated(sessionKey, absolutePath, undoDiffResult.servedRows, splitLines(undo.content).length, restoredRange?.firstChangedLine ?? 0);
102
- }
103
- return [parts.join("\n"), "", "Diff of the revert:", "", undoDiff].join("\n");
97
+ const parts = [`Undone last edit on ${path}.`];
98
+ if (linesAddedByEdit > 0 || linesRemovedByEdit > 0) {
99
+ parts.push(`Removed ${linesAddedByEdit} line(s) that were added and restored ${linesRemovedByEdit} line(s) that were removed.`);
100
+ }
101
+ parts.push("File reverted to previous state. The post-edit diff rows carry the restored file\u2019s fresh anchors for follow-up edits.");
102
+ if (undoDiffResult.servedRows.length > 0) {
103
+ await recordServedTruncated(sessionKey, absolutePath, undoDiffResult.servedRows, splitLines(undo.content).length, restoredRange?.firstChangedLine ?? 0);
104
+ }
105
+ return [parts.join("\n"), "", "Diff of the revert:", "", undoDiff].join("\n");
106
+ });
104
107
  },
105
108
  });
106
109
  }
@@ -22,8 +22,20 @@ export interface HashStore {
22
22
  readonly engine: "node:sqlite";
23
23
  }
24
24
  export declare function isCorruptionError(error: unknown): boolean;
25
- export declare function loadHashStore(): Promise<HashStore>;
25
+ /**
26
+ * Load (and cache) the hash store for the given cwd — or, when omitted, the
27
+ * workspace active for this async execution (`withWorkspace`), falling back to
28
+ * the shared `$DSH_HOME` store outside a tool call.
29
+ * @param cwd - optional explicit workspace root; defaults to the active workspace.
30
+ */
31
+ export declare function loadHashStore(cwd?: string): Promise<HashStore>;
32
+ /** Close every open store (process exit, HMR, tests). */
26
33
  export declare function shutdownHashStore(): void;
34
+ /**
35
+ * Run `fn` inside one BEGIN IMMEDIATE transaction on the active workspace's
36
+ * store. Without an open store for this context the call runs bare (the
37
+ * caller has already loaded the store in every in-process path).
38
+ */
27
39
  export declare function withStore(fn: () => void): void;
28
40
  export { getSnapshot, upsertSnapshot, findSnapshotPaths, pruneMissing, isValidHashList, isValidSnapshot, } from "./snapshot-store.js";
29
41
  export type { LegacySnapshot } from "./snapshot-store.js";
@@ -11,7 +11,7 @@
11
11
  * preview to write results.
12
12
  * @module dsh-better-edit
13
13
  */
14
- import type { Context } from '@deepseek-ai/cordis';
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
17
  /**
@@ -1,11 +1,15 @@
1
1
  /**
2
- * On-disk home for dsh-better-edit state, under the DeepSeek Harness home
3
- * ($DSH_HOME, defaulting to ~/.dsh). The hashline hash snapshots, served-state
4
- * rows, and undo history live under a plugin-owned subdirectory so multiple
5
- * dsh installs on one machine share one coherent store keyed by absolute path.
2
+ * On-disk home for dsh-better-edit state. Inside a tool call the store lives
3
+ * co-located with the files being edited: `<workspace>/.dsh_better_edit/` (the
4
+ * workspace is the session cwd, carried through the execution by
5
+ * `withWorkspace`). Outside a tool call — tests, previews, startup — the store
6
+ * falls back to the shared DeepSeek Harness home
7
+ * (`$DSH_HOME/plugins/dsh-better-edit`, default `~/.dsh/plugins/dsh-better-edit`),
8
+ * so a caller without a workspace never writes into an arbitrary cwd.
9
+ * @param cwd - the workspace root, or undefined for the shared-home fallback.
6
10
  */
7
- export declare function configDir(): string;
8
- export declare function hashStorePath(): string;
9
- export declare function legacyHashStorePath(): string;
10
- export declare function hashStoreDir(): string;
11
+ export declare function configDir(cwd?: string): string;
12
+ export declare function hashStorePath(cwd?: string): string;
13
+ export declare function legacyHashStorePath(cwd?: string): string;
14
+ export declare function hashStoreDir(cwd?: string): string;
11
15
  export declare function toCwd(filePath: string, cwd: string): string;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Per-call workspace context. dsh serves several sessions in one process, each
3
+ * with its own cwd, and only the tool execution knows which one it belongs to —
4
+ * so a module-global "current cwd" would race between parallel sessions. The
5
+ * store path is derived per tool call from the session cwd; this module carries
6
+ * that cwd through the async execution so every store access inside the call
7
+ * (served rows, undo, hash snapshots) lands in the right per-workspace store.
8
+ * @module dsh-better-edit/workspace
9
+ */
10
+ /**
11
+ * Run `fn` with the given workspace cwd active for this async execution.
12
+ * Every `loadHashStore()` (and any store access) inside `fn` resolves the
13
+ * `<cwd>/.dsh_better_edit` store.
14
+ * @param cwd - the session workspace root (absolute).
15
+ * @param fn - the tool body.
16
+ * @returns the body's result.
17
+ */
18
+ export declare function withWorkspace<T>(cwd: string, fn: () => Promise<T>): Promise<T>;
19
+ /**
20
+ * The workspace cwd active for this async execution, or undefined outside a
21
+ * tool call (tests, previews, startup) — callers fall back to the shared
22
+ * `$DSH_HOME` store then.
23
+ */
24
+ export declare function workspaceCwd(): string | undefined;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Per-call workspace context. dsh serves several sessions in one process, each
3
+ * with its own cwd, and only the tool execution knows which one it belongs to —
4
+ * so a module-global "current cwd" would race between parallel sessions. The
5
+ * store path is derived per tool call from the session cwd; this module carries
6
+ * that cwd through the async execution so every store access inside the call
7
+ * (served rows, undo, hash snapshots) lands in the right per-workspace store.
8
+ * @module dsh-better-edit/workspace
9
+ */
10
+ import { AsyncLocalStorage } from 'node:async_hooks';
11
+ const current = new AsyncLocalStorage();
12
+ /**
13
+ * Run `fn` with the given workspace cwd active for this async execution.
14
+ * Every `loadHashStore()` (and any store access) inside `fn` resolves the
15
+ * `<cwd>/.dsh_better_edit` store.
16
+ * @param cwd - the session workspace root (absolute).
17
+ * @param fn - the tool body.
18
+ * @returns the body's result.
19
+ */
20
+ export function withWorkspace(cwd, fn) {
21
+ return current.run(cwd, fn);
22
+ }
23
+ /**
24
+ * The workspace cwd active for this async execution, or undefined outside a
25
+ * tool call (tests, previews, startup) — callers fall back to the shared
26
+ * `$DSH_HOME` store then.
27
+ */
28
+ export function workspaceCwd() {
29
+ return current.getStore();
30
+ }
package/lib/write-hook.js CHANGED
@@ -9,6 +9,7 @@ import { normFromText } from './file-reader.js';
9
9
  import { fmtReadPreview, MAX_HASH_LINES } from './read-render.js';
10
10
  import { recordServed, clearDriftReported } from './served-store.js';
11
11
  import { execCwd, execSessionKey } from './dsh-context.js';
12
+ import { withWorkspace } from './workspace.js';
12
13
  const AUTO_READ_HEADING = '--- Auto-read (hashline anchors) ---';
13
14
  /**
14
15
  * Register the post-write auto-read listener on the calling agent's scope.
@@ -23,50 +24,54 @@ const AUTO_READ_HEADING = '--- Auto-read (hashline anchors) ---';
23
24
  */
24
25
  export function registerWriteHook(rootCtx, agentCtx, io) {
25
26
  return agentCtx.on('tools/post-execute', async (exec, result, next) => {
26
- const decision = await next();
27
- if (exec.name !== 'write' ||
28
- result.isError ||
29
- decision.kind !== 'accept') {
30
- return decision;
31
- }
32
- const decisionContent = decision.content ?? result.content;
33
- const rawPath = exec.arguments
34
- ?.file_path ?? exec.arguments
35
- ?.path;
36
- if (typeof rawPath !== 'string')
37
- return decision;
38
- try {
39
- const cwd = execCwd(exec);
40
- const sessionKey = execSessionKey(exec);
41
- const signal = exec.signal;
42
- const absolutePath = await io.resolve(rawPath, cwd, signal);
43
- const rawText = await io.readText(absolutePath, signal);
44
- const { normalized, fileHashes, hadUtf8DecodeErrors } = await normFromText({
45
- absolutePath,
46
- rawText,
47
- displayPath: rawPath,
48
- signal,
49
- maxLines: MAX_HASH_LINES,
27
+ return withWorkspace(execCwd(exec), async () => {
28
+ return withWorkspace(execCwd(exec), async () => {
29
+ const decision = await next();
30
+ if (exec.name !== 'write' ||
31
+ result.isError ||
32
+ decision.kind !== 'accept') {
33
+ return decision;
34
+ }
35
+ const decisionContent = decision.content ?? result.content;
36
+ const rawPath = exec.arguments
37
+ ?.file_path ?? exec.arguments
38
+ ?.path;
39
+ if (typeof rawPath !== 'string')
40
+ return decision;
41
+ try {
42
+ const cwd = execCwd(exec);
43
+ const sessionKey = execSessionKey(exec);
44
+ const signal = exec.signal;
45
+ const absolutePath = await io.resolve(rawPath, cwd, signal);
46
+ const rawText = await io.readText(absolutePath, signal);
47
+ const { normalized, fileHashes, hadUtf8DecodeErrors } = await normFromText({
48
+ absolutePath,
49
+ rawText,
50
+ displayPath: rawPath,
51
+ signal,
52
+ maxLines: MAX_HASH_LINES,
53
+ });
54
+ const preview = await fmtReadPreview(normalized, {}, fileHashes, absolutePath);
55
+ if (preview.served.length > 0) {
56
+ await recordServed(sessionKey, absolutePath, preview.served);
57
+ }
58
+ await clearDriftReported(sessionKey, absolutePath);
59
+ const text = hadUtf8DecodeErrors
60
+ ? `${preview.text}\n\n[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]`
61
+ : preview.text;
62
+ return {
63
+ kind: 'accept',
64
+ content: [
65
+ ...(decisionContent),
66
+ { type: 'text', text: `\n\n${AUTO_READ_HEADING}\n${text}` },
67
+ ],
68
+ };
69
+ }
70
+ catch (error) {
71
+ rootCtx.logger.warn(`dsh-better-edit: auto-read after write failed: ${error instanceof Error ? error.message : String(error)}`);
72
+ return decision;
73
+ }
50
74
  });
51
- const preview = await fmtReadPreview(normalized, {}, fileHashes, absolutePath);
52
- if (preview.served.length > 0) {
53
- await recordServed(sessionKey, absolutePath, preview.served);
54
- }
55
- await clearDriftReported(sessionKey, absolutePath);
56
- const text = hadUtf8DecodeErrors
57
- ? `${preview.text}\n\n[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]`
58
- : preview.text;
59
- return {
60
- kind: 'accept',
61
- content: [
62
- ...(decisionContent),
63
- { type: 'text', text: `\n\n${AUTO_READ_HEADING}\n${text}` },
64
- ],
65
- };
66
- }
67
- catch (error) {
68
- rootCtx.logger.warn(`dsh-better-edit: auto-read after write failed: ${error instanceof Error ? error.message : String(error)}`);
69
- return decision;
70
- }
75
+ });
71
76
  });
72
77
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-better-edit",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
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",