dsh-better-edit 0.5.1 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/lib/edit-engine.js +4 -454
  3. package/lib/edit-response.js +24 -2
  4. package/lib/file-encoding-state.js +263 -0
  5. package/lib/file-view.js +5 -1
  6. package/lib/fs-bridge.js +94 -251
  7. package/lib/hash-store.js +180 -2
  8. package/lib/hashline/anchor-pipeline.js +94 -166
  9. package/lib/hashline/hash-assign.js +15 -27
  10. package/lib/hashline/hash.js +5 -5
  11. package/lib/index.js +2 -2
  12. package/lib/mutation/engine.js +415 -0
  13. package/lib/mutation.js +105 -11
  14. package/lib/paths.js +1 -1
  15. package/lib/read-and-serve.js +25 -3
  16. package/lib/session-view.js +107 -58
  17. package/lib/store/index.js +28 -0
  18. package/lib/store-lifecycle.js +1 -1
  19. package/lib/tool-edit.js +2 -2
  20. package/lib/tool-read.js +2 -2
  21. package/lib/tool-undo.js +21 -8
  22. package/lib/types/edit-diff.d.ts +1 -1
  23. package/lib/types/edit-engine.d.ts +4 -176
  24. package/lib/types/edit-response.d.ts +1 -1
  25. package/lib/types/file-encoding-state.d.ts +77 -0
  26. package/lib/types/file-view.d.ts +7 -1
  27. package/lib/types/fs-bridge.d.ts +4 -11
  28. package/lib/types/hash-store.d.ts +15 -0
  29. package/lib/types/hashline/anchor-pipeline.d.ts +12 -21
  30. package/lib/types/hashline/hash-assign.d.ts +2 -2
  31. package/lib/types/hashline/hash.d.ts +1 -1
  32. package/lib/types/hashline/index.d.ts +1 -1
  33. package/lib/types/mutation/engine.d.ts +149 -0
  34. package/lib/types/mutation.d.ts +30 -5
  35. package/lib/types/paths.d.ts +1 -1
  36. package/lib/types/read-and-serve.d.ts +1 -1
  37. package/lib/types/session-view.d.ts +25 -31
  38. package/lib/types/store/index.d.ts +25 -0
  39. package/lib/types/workspace-context.d.ts +23 -0
  40. package/lib/workspace-context.js +44 -0
  41. package/lib/write-hook.js +2 -1
  42. package/package.json +1 -1
@@ -34,12 +34,13 @@ import type { LineEnding } from "./edit-diff.js";
34
34
  import { type NEdit } from "./hashline/anchor-pipeline.js";
35
35
  import type { ResolvedRange } from "./hashline/anchor-pipeline.js";
36
36
  import { scanDrift } from "./session-view.js";
37
- import { runFileEdits, resolveMissingPath, persistUndoAndWrite, enforceNoopLoop, collectRemovedHashes, countLineChanges } from "./edit-engine.js";
38
- import type { FileEditResult, PreparedItem } from "./edit-engine.js";
37
+ import { runFileEdits, resolveMissingPath } from "./mutation/engine.js";
38
+ import type { FileEditResult, PreparedItem } from "./mutation/engine.js";
39
+ import { restoreEndings } from "./edit-diff.js";
39
40
  import { buildMetrics, buildNoop, buildChanged, buildBatchResult } from "./edit-response.js";
40
41
  import type { RMeta, BatchSection } from "./edit-response.js";
41
- import { genDiff, restoreEndings, toLF, stripBOM } from "./edit-diff.js";
42
- import { computeDrift } from "./drift.js";
42
+ import { genDiff, toLF, stripBOM } from "./edit-diff.js";
43
+ import { computeDrift } from "./session-view.js";
43
44
  import { trackNoopPayload, clearNoopLoop, noopPayloadKey } from "./noop-guard.js";
44
45
  export interface PipelineResult {
45
46
  path: string;
@@ -71,13 +72,36 @@ export declare function execPipeline(io: FileIO, params: EditParams, cwd: string
71
72
  export declare function resolveDisplayPath(path: string, cwd: string): string;
72
73
  /** Snapshot bookkeeping for noop/success results (best-effort). */
73
74
  export declare function snapshotIdFor(io: FileIO, absolutePath: string, signal?: AbortSignal): Promise<string | undefined>;
74
- export { runFileEdits, resolveMissingPath, persistUndoAndWrite, enforceNoopLoop, collectRemovedHashes, countLineChanges, };
75
+ export { runFileEdits, resolveMissingPath };
76
+ export { persistUndoAndWrite };
75
77
  export type { FileEditResult, PreparedItem };
76
78
  export { buildMetrics, buildNoop, buildChanged, buildBatchResult };
77
79
  export type { RMeta, BatchSection };
78
80
  export { genDiff, restoreEndings, toLF, stripBOM };
79
81
  export { computeDrift, scanDrift };
80
82
  export { trackNoopPayload, clearNoopLoop, noopPayloadKey };
83
+ interface UndoWriteFile {
84
+ absolutePath: string;
85
+ displayPath: string;
86
+ originalNormalized: string;
87
+ bom: string;
88
+ originalEnding: LineEnding;
89
+ originalHashes: string[];
90
+ result: string;
91
+ }
92
+ interface PersistWriteOptions {
93
+ io: FileIO;
94
+ files: UndoWriteFile[];
95
+ exec: ToolExecution;
96
+ sandbox: FsSandboxController;
97
+ sandboxPolicy: SandboxExecutionPolicy | undefined;
98
+ signal?: AbortSignal;
99
+ undoUnavailableMessage: (displayPath: string) => string;
100
+ restoreUnwrittenUndos: boolean;
101
+ }
102
+ declare function persistUndoAndWrite(opts: PersistWriteOptions): Promise<void>;
103
+ declare function commitSingle(opts: Omit<PersistWriteOptions, "restoreUnwrittenUndos">): Promise<void>;
104
+ declare function commitBatch(opts: Omit<PersistWriteOptions, "restoreUnwrittenUndos">): Promise<void>;
81
105
  /**
82
106
  * Deep seam: execute the full mutation lifecycle.
83
107
  *
@@ -129,3 +153,4 @@ export declare function commit(opts: {
129
153
  undoUnavailableMessage: (displayPath: string) => string;
130
154
  restoreUnwrittenUndos?: boolean;
131
155
  }): Promise<void>;
156
+ export { commitSingle, commitBatch };
@@ -1,4 +1,4 @@
1
- export * from "./store-tenancy.js";
1
+ export * from "./store/index.js";
2
2
  export { canonicalAsync as resolveTarget } from "./canonical-path.js";
3
3
  export { canonicalSync } from "./canonical-path.js";
4
4
  export declare function toCwd(filePath: string, cwd: string): string;
@@ -8,7 +8,7 @@
8
8
  * @module dsh-better-edit/read-and-serve
9
9
  */
10
10
  import type { FileIO } from "./fs-bridge.js";
11
- import type { ServedRow } from "./hashline/served.js";
11
+ import type { ServedRow } from "./hashline/anchor-pipeline.js";
12
12
  /** Appended when the file had non-UTF-8 bytes; editing rewrites it as UTF-8. */
13
13
  export declare const UTF8_REWRITE_NOTE = "[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]";
14
14
  export interface ReadAndServeOptions {
@@ -1,41 +1,28 @@
1
1
  /**
2
2
  * SessionView — deep module owning served rows + drift + position reconstruction.
3
3
  *
4
- * Previously split: served-store (merge invariant, persistence via hash-store)
5
- * and drift (pure computeDrift + IO scanDrift that reads+writes served state).
6
- * The drift notice both *reads* served state and *writes* it (marking reported
7
- * + recording drift rows) — a side effect hidden inside a "notice" module.
4
+ * Previously also owned workspace/session context (AsyncLocalStorage +
5
+ * execCwd/execSessionKey/sessionKeyFor + path re-exports) as
6
+ * "private to this seam, @internal". That mixed two invariants:
7
+ * served-merge+drift vs context propagation. Now this seam owns ONLY
8
+ * served state and drift; WorkspaceContext owns execution context.
8
9
  *
9
- * This seam co-locates that invariant. Public surface:
10
- * view(sessionKey, path) -> {served, reported}
11
- * recordRead(sessionKey, path, rows, lineCount)
12
- * recordEdit(sessionKey, path, rows, lineCount, clearFrom)
13
- * scanDrift(sessionKey, path, resultHashes, resultLines, range) -> notice?
14
- * servedPositionsOf, currentPositionOfDrifted, _mergeServedRows (via served-store)
10
+ * Public surface: _mergeServedRows, loadServed, recordServed,
11
+ * recordServedTruncated, driftReported, markDriftReported,
12
+ * clearDriftReported, wipeServedState, servedPositionsOf,
13
+ * currentPositionOfDrifted, computeDrift, scanDrift, and
14
+ * hash-store persistence delegation (ServedPersistence).
15
15
  *
16
- * Explicit Workspace note: loadHashStore(cwd) now requires cwd. The
17
- * AsyncLocalStorage magic in workspace.ts is @internal — new code should pass
18
- * cwd explicitly through read-and-serve / edit-pipeline / drift. Forgetting
19
- * cwd is now a compile error where callers use this seam; legacy callers
20
- * via served-store still fall back to workspaceCwd() for backwards compat
21
- * but are marked deprecated.
22
- *
23
- * Ownership: This file now OWNS the served-merge invariant
24
- * (_mergeServedRows), the position-reconstruction math, and the drift
25
- * computation. Deleting it would scatter the served+drift invariant
26
- * across 4 files — it concentrates (deep).
16
+ * Ownership: This file OWNS the served-merge invariant
17
+ * (_mergeServedRows with orphan healing per ADR-0008), the
18
+ * position-reconstruction math, and the drift computation. Deleting
19
+ * it would scatter the served+drift invariant across 4 files — it
20
+ * concentrates (deep).
27
21
  *
28
22
  * @module dsh-better-edit/session-view
29
23
  */
30
- import type { ToolExecution } from "@deepseek-ai/dsh-tools";
31
- import type { ServedRow, ResolvedRange } from "./hashline/served.js";
32
- import { configDir, hashStorePath, resolveTarget } from "./paths.js";
33
- export declare function withWorkspace<T>(cwd: string, fn: () => Promise<T>): Promise<T>;
34
- export declare function workspaceCwd(): string | undefined;
35
- export declare function sessionKeyFor(sessionId?: string): string;
36
- export declare function execCwd(exec: ToolExecution): string;
37
- export declare function execSessionKey(exec: ToolExecution): string;
38
- export { configDir, hashStorePath, resolveTarget };
24
+ import { type AnchorReservations } from "./hash-store.js";
25
+ import type { ServedRow, ResolvedRange } from "./hashline/anchor-pipeline.js";
39
26
  export { loadHashStore, loadServedStore, shutdownHashStore, withStore } from "./hash-store.js";
40
27
  export type { HashStore } from "./hash-store.js";
41
28
  export type ServedEntry = {
@@ -54,7 +41,14 @@ export declare function _mergeServedRows(current: (string | null)[], rows: Serve
54
41
  clearFrom?: number;
55
42
  }): (string | null)[];
56
43
  export declare function loadServed(sessionKey: string, path: string): Promise<(string | null)[]>;
57
- export declare function recordServed(sessionKey: string, path: string, rows: ServedEntry[], lineCount?: number): Promise<void>;
44
+ /** Anchors that must not be allocated while any session can still remember them. */
45
+ export declare function loadAnchorReservations(path: string): Promise<AnchorReservations>;
46
+ export declare function loadServedCanons(sessionKey: string, path: string): Promise<(string | null)[]>;
47
+ export declare function loadEpochSnapshotId(sessionKey: string, path: string): Promise<string | undefined>;
48
+ export declare function loadRetiredAnchors(sessionKey: string, path: string): Promise<Set<string>>;
49
+ /** Keep freed anchors dead for this session until it has seen the whole file again. */
50
+ export declare function retireAnchors(sessionKey: string, path: string, hashes: Iterable<string>): Promise<void>;
51
+ export declare function recordServed(sessionKey: string, path: string, rows: ServedEntry[], lineCount?: number, fullReadHashes?: readonly string[], fullReadCanons?: readonly (string | null)[], fullReadSnapshotId?: string): Promise<void>;
58
52
  export declare function recordServedTruncated(sessionKey: string, path: string, rows: ServedEntry[], lineCount: number, clearFrom?: number): Promise<void>;
59
53
  export declare function driftReported(sessionKey: string, path: string): Promise<Set<string>>;
60
54
  export declare function markDriftReported(sessionKey: string, path: string, hashes: string[]): Promise<void>;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Store — deep module owning tenancy + lifecycle + path resolution.
3
+ *
4
+ * Single seam that answers "which store, where, and is it open?"
5
+ * Tenancy (where DB lives) and lifecycle (central GC + row TTL + WAL)
6
+ * are private details of this seam; hash-store keeps only schema +
7
+ * row-family domain logic and imports path resolution from here.
8
+ * StoreConfig remains the config complement seam but its path is
9
+ * resolved via this Store seam.
10
+ *
11
+ * YAGNI-gated: DB plumbing (openDb/buildStore/quarantine/busy-retry/
12
+ * WAL/legacy JSON migration) stays in hash-store for now and is
13
+ * re-exported here for testability without importing domain helpers
14
+ * — full plumbing move is deferred to avoid contract risk. Old
15
+ * store-tenancy/store-lifecycle files are kept as compat shims
16
+ * re-exporting from this seam (reversible).
17
+ *
18
+ * @module dsh-better-edit/store
19
+ */
20
+ export { tenancyFor, configDir, hashStorePath, hashStoreDir, legacyHashStorePath, loadConfig, _resetConfigCache, expand, } from "../store-tenancy.js";
21
+ export type { Tenancy, StoreConfig } from "../store-tenancy.js";
22
+ export { onStoreOpen, onAppStart, onSessionStart, setStoresGetter, runCentralJanitorIfDue, _resetLifecycleForTests, } from "../store-lifecycle.js";
23
+ export { loadConfig as loadStoreConfig } from "../store-config.js";
24
+ export { isCorruptionError, loadHashStore, shutdownHashStore, withStore, findSnapshotPathsByHashes, upsertSnapshotFor, } from "../hash-store.js";
25
+ export type { HashStore, InternalHashStore, ServedPersistence } from "../hash-store.js";
@@ -0,0 +1,23 @@
1
+ /**
2
+ * WorkspaceContext — deep module owning execution context propagation.
3
+ *
4
+ * Single job: propagate `cwd` and `sessionKey` from the DSH tool execution
5
+ * into the plugin's async chain. Previously co-located inside
6
+ * `session-view.ts` (served+drift+workspace+paths re-exports) as
7
+ * "private to this seam, @internal" with an AsyncLocalStorage. That god
8
+ * seam mixed two invariants: served-merge+drift vs context propagation.
9
+ *
10
+ * Deleting this module would scatter `withWorkspace`/`workspaceCwd` and
11
+ * `execCwd`/`execSessionKey`/`sessionKeyFor` across every tool and IO
12
+ * caller — it concentrates (deep). Tested via scoped-execution tests,
13
+ * not drift.
14
+ *
15
+ * @module dsh-better-edit/workspace-context
16
+ */
17
+ import type { ToolExecution } from "@deepseek-ai/dsh-tools";
18
+ export declare function withWorkspace<T>(cwd: string, fn: () => Promise<T>): Promise<T>;
19
+ export declare function workspaceCwd(): string | undefined;
20
+ export declare function sessionKeyFor(sessionId?: string): string;
21
+ export declare function execCwd(exec: ToolExecution): string;
22
+ export declare function execSessionKey(exec: ToolExecution): string;
23
+ export declare function _resetWorkspaceContextForTests(): void;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * WorkspaceContext — deep module owning execution context propagation.
3
+ *
4
+ * Single job: propagate `cwd` and `sessionKey` from the DSH tool execution
5
+ * into the plugin's async chain. Previously co-located inside
6
+ * `session-view.ts` (served+drift+workspace+paths re-exports) as
7
+ * "private to this seam, @internal" with an AsyncLocalStorage. That god
8
+ * seam mixed two invariants: served-merge+drift vs context propagation.
9
+ *
10
+ * Deleting this module would scatter `withWorkspace`/`workspaceCwd` and
11
+ * `execCwd`/`execSessionKey`/`sessionKeyFor` across every tool and IO
12
+ * caller — it concentrates (deep). Tested via scoped-execution tests,
13
+ * not drift.
14
+ *
15
+ * @module dsh-better-edit/workspace-context
16
+ */
17
+ import { randomUUID } from "node:crypto";
18
+ import { AsyncLocalStorage } from "node:async_hooks";
19
+ // --- AsyncLocalStorage for cwd propagation ---
20
+ const current = new AsyncLocalStorage();
21
+ export function withWorkspace(cwd, fn) {
22
+ return current.run(cwd, fn);
23
+ }
24
+ export function workspaceCwd() {
25
+ return current.getStore();
26
+ }
27
+ // --- sessionKey helpers ---
28
+ let fallbackSessionKey;
29
+ export function sessionKeyFor(sessionId) {
30
+ if (sessionId && sessionId.length > 0)
31
+ return sessionId;
32
+ // fallback for previews/tests
33
+ return fallbackSessionKey ??= randomUUID();
34
+ }
35
+ export function execCwd(exec) {
36
+ return exec.agent?.session.header.cwd ?? process.cwd();
37
+ }
38
+ export function execSessionKey(exec) {
39
+ return sessionKeyFor(exec.agent?.session.id);
40
+ }
41
+ // For tests: reset the fallback UUID so tests can be isolated
42
+ export function _resetWorkspaceContextForTests() {
43
+ fallbackSessionKey = undefined;
44
+ }
package/lib/write-hook.js CHANGED
@@ -6,7 +6,8 @@
6
6
  * @module dsh-better-edit/write-hook
7
7
  */
8
8
  import { readAndServe } from './read-and-serve.js';
9
- import { execCwd, execSessionKey, loadServed, withWorkspace } from './session-view.js';
9
+ import { execCwd, execSessionKey, withWorkspace } from './workspace-context.js';
10
+ import { loadServed } from './session-view.js';
10
11
  import { HASH_SEP } from './hashline/hash-assign.js';
11
12
  import { abortIf, splitLines } from './utils.js';
12
13
  const AUTO_READ_HEADING = '--- Auto-read (hashline anchors) ---';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-better-edit",
3
- "version": "0.5.1",
3
+ "version": "0.6.1",
4
4
  "type": "module",
5
5
  "description": "Hash-anchored read/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",