dsh-better-edit 0.1.0 → 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/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/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,20 +11,31 @@
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";
24
+ /**
25
+ * Services the plugin's per-agent install touches: `tools` and `systemPrompt`
26
+ * for the shadow registrations, `fs` for the IO bridge. Cordis refuses
27
+ * property access to an undeclared service ("cannot get property X without
28
+ * inject"), so these MUST be listed or every agent install fails at
29
+ * session-start.
30
+ */
31
+ export const inject = ["tools", "systemPrompt", "fs"];
25
32
  function installAgentTools(rootCtx, agent) {
26
33
  return agent.ctx.effect(() => {
27
- const io = ctxFsIO(agent.ctx.fs, agent.ctx);
34
+ // `fs` is host-plane: use the plugin's own context (covered by
35
+ // inject) rather than the agent's scoped one, whose fiber chain does
36
+ // not declare it. Session cwd still reaches the bridge per call via
37
+ // exec.agent.session.header.cwd.
38
+ const io = ctxFsIO(rootCtx.fs, rootCtx);
28
39
  const disposers = [];
29
40
  disposers.push(registerReadTool(rootCtx, agent.ctx, io));
30
41
  disposers.push(registerEditTool(rootCtx, agent.ctx, io));
@@ -34,32 +45,32 @@ function installAgentTools(rootCtx, agent) {
34
45
  // Shadow the preset's built-in tool guidance with the hashline contract.
35
46
  // Same section names on the agent's own layer win over the preset's.
36
47
  disposers.push(agent.ctx.systemPrompt.section({
37
- name: 'tool:edit',
48
+ name: "tool:edit",
38
49
  order: 102,
39
50
  text: [
40
51
  EDIT_DESCRIPTION,
41
- '',
42
- EDIT_GUIDELINES.map((line) => `- ${line}`).join('\n'),
43
- ].join('\n'),
52
+ "",
53
+ EDIT_GUIDELINES.map((line) => `- ${line}`).join("\n"),
54
+ ].join("\n"),
44
55
  }));
45
56
  disposers.push(agent.ctx.systemPrompt.section({
46
- name: 'tool:read',
57
+ name: "tool:read",
47
58
  order: 100,
48
59
  text: [
49
- 'Use the read tool — not shell commands like cat — to inspect text files.',
50
- '',
51
- READ_GUIDELINES.map((line) => `- ${line}`).join('\n'),
52
- ].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"),
53
64
  }));
54
65
  disposers.push(agent.ctx.systemPrompt.section({
55
- name: 'tool:batch_edit',
66
+ name: "tool:batch_edit",
56
67
  order: 103,
57
- text: BATCH_EDIT_GUIDELINES.map((line) => `- ${line}`).join('\n'),
68
+ text: BATCH_EDIT_GUIDELINES.map((line) => `- ${line}`).join("\n"),
58
69
  }));
59
70
  disposers.push(agent.ctx.systemPrompt.section({
60
- name: 'tool:undo_last_edit',
71
+ name: "tool:undo_last_edit",
61
72
  order: 104,
62
- text: UNDO_GUIDELINES.map((line) => `- ${line}`).join('\n'),
73
+ text: UNDO_GUIDELINES.map((line) => `- ${line}`).join("\n"),
63
74
  }));
64
75
  return () => {
65
76
  for (const dispose of disposers)
@@ -69,15 +80,14 @@ function installAgentTools(rootCtx, agent) {
69
80
  }
70
81
  /** Mount the bundle: initialize the store, then install tools per agent. */
71
82
  export function apply(rootCtx) {
72
- // Warm the hasher and prune missing snapshots once; failures are non-fatal
73
- // (each store operation retries on demand).
74
- initHasher()
75
- .then(() => pruneMissingAll())
76
- .catch((error) => {
77
- 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)}`);
78
88
  });
79
89
  const registered = new WeakSet();
80
- rootCtx.on('agent/session-start', ({ agent }) => {
90
+ rootCtx.on("agent/session-start", ({ agent }) => {
81
91
  if (registered.has(agent))
82
92
  return;
83
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;