dsh-better-edit 0.5.0 → 0.6.0

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 (44) hide show
  1. package/CHANGELOG.md +20 -2
  2. package/README.md +1 -1
  3. package/lib/contract.js +1 -1
  4. package/lib/edit-engine.js +4 -454
  5. package/lib/edit-response.js +24 -2
  6. package/lib/encoding.js +308 -0
  7. package/lib/file-encoding-state.js +263 -0
  8. package/lib/file-view.js +1 -1
  9. package/lib/fs-bridge.js +124 -19
  10. package/lib/hash-store.js +1 -2
  11. package/lib/hashline/anchor-pipeline.js +19 -165
  12. package/lib/index.js +2 -2
  13. package/lib/mutation/engine.js +388 -0
  14. package/lib/mutation.js +84 -11
  15. package/lib/paths.js +1 -1
  16. package/lib/read-and-serve.js +5 -0
  17. package/lib/session-view.js +16 -49
  18. package/lib/store/index.js +28 -0
  19. package/lib/store-config.js +132 -2
  20. package/lib/store-lifecycle.js +1 -1
  21. package/lib/tool-edit.js +2 -2
  22. package/lib/tool-read.js +26 -6
  23. package/lib/tool-undo.js +2 -2
  24. package/lib/types/contract.d.ts +1 -0
  25. package/lib/types/edit-diff.d.ts +1 -1
  26. package/lib/types/edit-engine.d.ts +4 -176
  27. package/lib/types/edit-response.d.ts +1 -1
  28. package/lib/types/encoding.d.ts +46 -0
  29. package/lib/types/file-encoding-state.d.ts +77 -0
  30. package/lib/types/file-view.d.ts +2 -1
  31. package/lib/types/fs-bridge.d.ts +5 -1
  32. package/lib/types/hashline/anchor-pipeline.d.ts +6 -20
  33. package/lib/types/hashline/index.d.ts +1 -1
  34. package/lib/types/mutation/engine.d.ts +143 -0
  35. package/lib/types/mutation.d.ts +30 -5
  36. package/lib/types/paths.d.ts +1 -1
  37. package/lib/types/read-and-serve.d.ts +4 -1
  38. package/lib/types/session-view.d.ts +16 -30
  39. package/lib/types/store/index.d.ts +25 -0
  40. package/lib/types/store-config.d.ts +10 -1
  41. package/lib/types/workspace-context.d.ts +23 -0
  42. package/lib/workspace-context.js +44 -0
  43. package/lib/write-hook.js +2 -1
  44. package/package.json +5 -1
@@ -0,0 +1,77 @@
1
+ /**
2
+ * FileEncodingState — deep module owning the file encoding state round-trip.
3
+ *
4
+ * Single seam for deterministic admission (BOM → strict UTF-8 → autoGuess gate
5
+ * → Top-3 always pushed), canonical encoding enum, version-invalidated memo,
6
+ * and BOM+lineEnding round-trip. Previously scattered across fs-bridge
7
+ * (branching + fallback Map + Top-3), encoding.ts (pure scoring), and
8
+ * file-view/fs-write (stripBOM/detectEnding/encode back). Now one file owns
9
+ * the invariant; deleting it would scatter round-trip fidelity (deep).
10
+ *
11
+ * Interface is the test surface: pure decode is tested without filesystem,
12
+ * IO adapters (fs-bridge) are thin. `store-config.autoGuessEncoding` stays the
13
+ * only config knob — this module reads it but does not own it.
14
+ *
15
+ * @module dsh-better-edit/file-encoding-state
16
+ */
17
+ import type { CandidatePreview } from "./encoding.js";
18
+ import { type LineEnding } from "./edit-diff.js";
19
+ export interface FileEncodingState {
20
+ encoding: string;
21
+ hasBOM: boolean;
22
+ lineEnding?: LineEnding;
23
+ version: string | undefined;
24
+ }
25
+ export declare function getEncodingState(targetKey: string): FileEncodingState | undefined;
26
+ export declare function setEncodingState(targetKey: string, state: FileEncodingState): void;
27
+ export declare function clearEncodingState(targetKey?: string): void;
28
+ export declare function getAutoGuessFooter(targetKey: string): string | undefined;
29
+ export declare function setAutoGuessFooter(targetKey: string, footer: string): void;
30
+ export declare function clearAutoGuessFooter(targetKey?: string): void;
31
+ /** Invalidate memo when FsVersion drifted (ADR-0012). */
32
+ export declare function invalidateIfStale(targetKey: string, currentVersion: string | undefined): void;
33
+ export declare function buildTop3ErrorMessage(displayPath: string, candidates: CandidatePreview[]): string;
34
+ export interface DecodeAdmissionConfig {
35
+ autoGuessEncoding: boolean;
36
+ supportedEncodings: string[];
37
+ }
38
+ export interface DecodeForOpenResult {
39
+ text: string;
40
+ encoding: string;
41
+ hasBOM: boolean;
42
+ lineEnding: LineEnding;
43
+ footer?: string;
44
+ candidates: CandidatePreview[];
45
+ }
46
+ export interface DecodeForOpenOptions {
47
+ encodingHint?: string;
48
+ displayPath?: string;
49
+ }
50
+ /**
51
+ * Deterministic admission for a raw byte buffer. No IO, no side effects
52
+ * except Top-3 scoring. Caller owns recording the returned state via
53
+ * `recordOpenState` and handling the footer vs E_NOT_TEXT split.
54
+ *
55
+ * Order is fixed: BOM sniff always precedes strict UTF-8, which always
56
+ * precedes guessing. Probabilistic encodings are last resort, gated by
57
+ * `autoGuessEncoding`, but Top-3 is always computed for the error/ footer.
58
+ */
59
+ export declare function decodeForOpen(bytes: Uint8Array, config: DecodeAdmissionConfig, opts?: DecodeForOpenOptions): Promise<DecodeForOpenResult>;
60
+ export declare function recordOpenState(targetKey: string, text: string, encoding: string, hasBOM: boolean, version: string | undefined): FileEncodingState;
61
+ export declare function recordFooter(targetKey: string, footer: string | undefined): void;
62
+ export interface EncodeForSaveOptions {
63
+ encodingHint?: string;
64
+ normalizeToUtf8?: boolean;
65
+ currentVersion?: string | undefined;
66
+ }
67
+ /**
68
+ * Decide what bytes (as text, since provider expects string) to write and
69
+ * what new state to record. BOM and lineEnding are restored here when a
70
+ * previous state exists; otherwise defaults are UTF-8 without BOM and LF.
71
+ * For legacy encodings with normalizeToUtf8:false, we preserve the memo
72
+ * (provider will write UTF-8 string, next read re-detects via version bump).
73
+ */
74
+ export declare function prepareForSave(content: string, existingState: FileEncodingState | undefined, opts?: EncodeForSaveOptions): {
75
+ textToWrite: string;
76
+ newState?: FileEncodingState;
77
+ };
@@ -19,7 +19,7 @@
19
19
  */
20
20
  import { type LineEnding } from "./edit-diff.js";
21
21
  import type { FileIO } from "./fs-bridge.js";
22
- import type { ServedRow } from "./hashline/served.js";
22
+ import type { ServedRow } from "./hashline/anchor-pipeline.js";
23
23
  import type { HashStore } from "./hash-store.js";
24
24
  export declare const MAX_HASH_LINES: number;
25
25
  export declare const DEFAULT_MAX_LINES = 2000;
@@ -128,6 +128,7 @@ export interface PreviewOpts {
128
128
  limit?: number;
129
129
  }
130
130
  export interface ReadViewOpts extends PreviewOpts {
131
+ encoding?: string;
131
132
  signal?: AbortSignal;
132
133
  }
133
134
  export declare function preview(content: string, hashes: string[], opts?: PreviewOpts, absolutePath?: string): Promise<{
@@ -18,12 +18,16 @@ import type { Context } from "@deepseek-ai/cordis";
18
18
  import type { FileSystem } from "@deepseek-ai/dsh-fs";
19
19
  import type { ToolExecution } from "@deepseek-ai/dsh-tools";
20
20
  import type { SandboxExecutionPolicy } from "@deepseek-ai/dsh-sandbox";
21
+ import { getEncodingState as _getEncodingState, setEncodingState as _setEncodingState, clearEncodingState as _clearEncodingState, getAutoGuessFooter as _getAutoGuessFooter, setAutoGuessFooter as _setAutoGuessFooter, clearAutoGuessFooter as _clearAutoGuessFooter } from "./file-encoding-state.js";
22
+ export type { FileEncodingState } from "./file-encoding-state.js";
23
+ export { _getEncodingState as getEncodingState, _setEncodingState as setEncodingState, _clearEncodingState as clearEncodingState, _getAutoGuessFooter as getAutoGuessFooter, _setAutoGuessFooter as setAutoGuessFooter, _clearAutoGuessFooter as clearAutoGuessFooter, };
24
+ export declare function getAutoGuessFooterCompat(k: string): string | undefined;
21
25
  /** Text-IO operations the hashline tools need, keyed by canonical absolute path. */
22
26
  export interface FileIO {
23
27
  /** Resolve a (possibly relative) request path against the session cwd to a canonical absolute path. */
24
28
  resolve(path: string, cwd: string, signal?: AbortSignal): Promise<string>;
25
29
  /** Read whole text; missing files, directories, and binary content throw. */
26
- readText(absolutePath: string, signal?: AbortSignal): Promise<string>;
30
+ readText(absolutePath: string, signal?: AbortSignal, encoding?: string): Promise<string>;
27
31
  /**
28
32
  * Atomically write whole text, preserving mode when the file exists. On the
29
33
  * dsh backend this dispatches `fs/write-intent` (policy guard), stamps the
@@ -2,16 +2,14 @@
2
2
  * AnchorPipeline — deep module owning the anchor autofix chain.
3
3
  *
4
4
  * Single ordering invariant (private):
5
- * swapReversed → stripBare → stripDiff → valEdit → boundaryDups splice → valEdit → verifyServed → resToSpan
5
+ * swapReversed → stripBare → stripDiff → valEdit → verifyServed → resToSpan
6
6
  *
7
- * Detection (valEdit → boundaryDups[]) and correction (splice + second valEdit)
8
- * were split across resolve.ts / apply.ts with an implicit coupling.
9
- * This seam co-locates that invariant. Public surface is two functions:
7
+ * This seam co-locates the ordering invariant. Public surface is two functions:
10
8
  * resEdit — pre-validation (tool-layer, no file state)
11
9
  * applyEdit — full pipeline (file + hashes + served verification)
12
10
  *
13
11
  * Private to this seam (not re-exported): stripBarePrefixes, stripDiffPrefixes,
14
- * swapReversedRanges, valEdit, boundaryDups helpers, warnUnicodeEsc, findNewEdge,
12
+ * swapReversedRanges, valEdit, warnUnicodeEsc,
15
13
  * resAnchorFromMap, assertAligned, etc. They remain exported from resolve.ts
16
14
  * for backwards compat but are marked @internal and should be imported via this
17
15
  * module only.
@@ -37,15 +35,6 @@ export type RHEdit = {
37
35
  content_lines: string[];
38
36
  hash_bounds: [RAnchor, RAnchor];
39
37
  };
40
- export interface BDup {
41
- kind: "trailing" | "leading" | "first-new-after" | "last-new-before";
42
- replacementLineIndex: number;
43
- }
44
- export interface AutoFix {
45
- kind: "trailing" | "leading" | "first-new-after" | "last-new-before";
46
- removedLine: string;
47
- removedLineIndex: number;
48
- }
49
38
  export interface NEdit {
50
39
  loc: string;
51
40
  currentContent: string;
@@ -57,11 +46,7 @@ export type HTEdit = {
57
46
  };
58
47
  export declare function resEdit(edit: HTEdit, warnings?: string[]): HEdit;
59
48
  declare function warnUnicodeEsc(edit: HEdit, warnings: string[]): void;
60
- /** @internal — private to anchor-pipeline seam */
61
- export declare function findNewEdge(contentLines: string[], rangeLines: string[], fromEnd: boolean): {
62
- index: number;
63
- line: string;
64
- } | undefined;
49
+ export declare function findNewEdge(): undefined;
65
50
  export { warnUnicodeEsc };
66
51
  export type ServedCode = "E_RANGE_STALE" | "E_RANGE_UNSERVED" | "E_RANGE_UNVERIFIED";
67
52
  export interface ServedRow {
@@ -125,10 +110,11 @@ export declare function applyEdit(content: string, edit: HEdit, signal?: AbortSi
125
110
  range: ResolvedRange;
126
111
  warnings?: string[];
127
112
  noopEdit?: NEdit;
128
- autoFixes?: AutoFix[];
129
113
  };
130
114
  export declare function fmtRegion(hashes: string[], lines: string[]): string;
131
115
  export declare function changedRange(original: string, result: string): {
132
116
  firstChangedLine: number;
133
117
  lastChangedLine: number;
134
118
  } | null;
119
+ export { HASH_RE, HASH_CLASS, HASH_SEP, ANCHOR_LEN, ALPH_RE, ALPH, HASH_LEN, HASH_SPACE, MAX_HASH_LINES, HASH_PROBE_STRIDE, CANON_VERSION, canon, lineHashesPure, mapStableHashes, initHasher, contentChecksum, getCanonForHash, rememberHashCanon, } from "./hash-assign.js";
120
+ export { lineHashes } from "./hash.js";
@@ -8,6 +8,6 @@ export { lineHashes } from "./hash.js";
8
8
  export { parseHashRef, parseText } from "./parse.js";
9
9
  export type { Anchor } from "./parse.js";
10
10
  export { resEdit } from "./anchor-pipeline.js";
11
- export type { HEdit, HTEdit, NEdit, BDup, AutoFix } from "./anchor-pipeline.js";
11
+ export type { HEdit, HTEdit, NEdit } from "./anchor-pipeline.js";
12
12
  export { applyEdit, fmtRegion, changedRange, buildIdx, ServedRejectionError, AnchorMismatchError, EditHashEchoError, findEditHashEcho, isServedRejection, isAnchorMismatch, verifyServedRange, buildRangeEcho, fmtServedRows, } from "./anchor-pipeline.js";
13
13
  export type { ServedRow, ResolvedRange, ServedCode, } from "./anchor-pipeline.js";
@@ -0,0 +1,143 @@
1
+ /**
2
+ * @internal — private to Mutation seam. Do not import from outside src/mutation.
3
+ * The edit-sequence engine private to Mutation:
4
+ * apply-one-edit against in-memory content with served verification and the
5
+ * multi-edit sequencer that drives a whole file's item list against evolving
6
+ * content, the noop-loop guard, and the persist-undo → write → restore
7
+ * Transaction (persist-undo → write → restore) is owned by Mutation, not this engine.
8
+ *
9
+ * The model-facing contract lives here unchanged: [E_BATCH_ABORT],
10
+ * [E_NOOP_LOOP], [E_UNDO_UNAVAILABLE] carry byte-identical messages, and
11
+ * reject-and-serve records the same echo serves.
12
+ * @module dsh-better-edit/mutation/engine
13
+ */
14
+ import type { FileIO } from "../fs-bridge.js";
15
+ import type { HashStore } from "../hash-store.js";
16
+ import type { LineEnding } from "../edit-diff.js";
17
+ import { type HEdit, type NEdit } from "../hashline/anchor-pipeline.js";
18
+ import { type ResolvedRange, type ServedRow } from "../hashline/anchor-pipeline.js";
19
+ export interface PreparedItem {
20
+ index: number;
21
+ path: string;
22
+ absolutePath: string;
23
+ remove_from: string;
24
+ remove_to: string;
25
+ replacement_text: string;
26
+ pathWarning?: string;
27
+ }
28
+ export interface FileEditResult {
29
+ displayPath: string;
30
+ absolutePath: string;
31
+ originalNormalized: string;
32
+ result: string;
33
+ bom: string;
34
+ originalEnding: LineEnding;
35
+ hadUtf8DecodeErrors: boolean;
36
+ warnings: string[];
37
+ originalHashes: string[];
38
+ resultHashes: string[];
39
+ appliedCount: number;
40
+ noopCount: number;
41
+ totalAddedLines: number;
42
+ totalRemovedLines: number;
43
+ driftNotice: string | undefined;
44
+ range: ResolvedRange;
45
+ }
46
+ /**
47
+ * Resolve a request's missing `path` from its anchors: the only file whose
48
+ * stored hashes contain both anchors. Returns the path plus an autocorrect
49
+ * warning, or undefined when no resolution is possible.
50
+ */
51
+ export declare function resolveMissingPath(request: Record<string, unknown>): Promise<{
52
+ path: string;
53
+ warning: string;
54
+ } | undefined>;
55
+ /** The hashes a range edit removes, for stable re-hash bookkeeping. */
56
+ export declare function collectRemovedHashes(edit: HEdit, originalHashes: string[]): Set<string>;
57
+ /** Added/removed line counts for one resolved edit against a file's original hashes. */
58
+ export declare function countLineChanges(edit: HEdit, originalHashes: string[], isNoop: boolean, removedAutoFixes: number): {
59
+ totalAddedLines: number;
60
+ totalRemovedLines: number;
61
+ };
62
+ export interface ApplyOneInput {
63
+ content: string;
64
+ hashes: string[];
65
+ served: (string | null)[];
66
+ removeFrom: string;
67
+ removeTo: string;
68
+ replacementText: string;
69
+ absolutePath: string;
70
+ displayPath: string;
71
+ signal?: AbortSignal;
72
+ /** Shared warnings array; resEdit warnings are pushed here. */
73
+ warnings: string[];
74
+ /**
75
+ * The hashes to count added/removed lines against. Defaults to `hashes`;
76
+ * the batch sequencer passes the file's ORIGINAL hashes so later edits in
77
+ * a sequence still count against the file as first served.
78
+ */
79
+ countHashes?: string[];
80
+ store?: HashStore;
81
+ persist: boolean;
82
+ /** Pre-resolved edit (single path keeps resEdit before IO for error order). */
83
+ edit?: HEdit;
84
+ }
85
+ export interface ApplyOneResult {
86
+ result: string;
87
+ /** Stable re-hash after the edit (equals `hashes` for a noop). */
88
+ hashes: string[];
89
+ range: ResolvedRange;
90
+ noop: boolean;
91
+ edit: HEdit;
92
+ noopEdit?: NEdit;
93
+ firstChangedLine?: number;
94
+ lastChangedLine?: number;
95
+ removedHashes: Set<string> | undefined;
96
+ totalAddedLines: number;
97
+ totalRemovedLines: number;
98
+ anchorWarnings: string[] | undefined;
99
+ }
100
+ /**
101
+ * One edit against in-memory content: resolve (unless a pre-resolved edit was
102
+ * given) → apply with served verification → stable re-hash → line counts.
103
+ *
104
+ * `onReject` owns the reject-and-serve policy: it receives resolve/verify
105
+ * failures (and the edit that failed, when resolved) and MUST throw. The
106
+ * single path rethrows the original anchor error after recording echo serves;
107
+ * the batch path wraps with [E_BATCH_ABORT] plus the current-range echo.
108
+ */
109
+ export declare function applyOne(input: ApplyOneInput, onReject: (error: unknown, edit: HEdit | undefined) => Promise<never>): Promise<ApplyOneResult>;
110
+ export interface NoopLoopOptions {
111
+ absolutePath: string;
112
+ removeFrom: string;
113
+ removeTo: string;
114
+ replacementText: string;
115
+ displayPath: string;
116
+ /** Batch item index; undefined = single-edit flavor. */
117
+ index?: number;
118
+ count: number;
119
+ sessionKey: string;
120
+ originalHashes: string[];
121
+ originalNormalized: string;
122
+ /** Single-edit flavor only: the edit's range, for the echo rows. */
123
+ range?: ResolvedRange;
124
+ /** Batch flavor: precomputed echo rows for the failed item (may be absent). */
125
+ echoRows?: ServedRow[];
126
+ }
127
+ /**
128
+ * The shared noop-loop guard. Returns the "twice in a row" notice for the
129
+ * caller to append to warnings, or throws [E_NOOP_LOOP] (after recording the
130
+ * echo serves) once the payload has been submitted NOOP_LOOP_THRESHOLD times
131
+ * with no change. Messages are byte-identical to the pre-engine tools.
132
+ */
133
+ export declare function enforceNoopLoop(opts: NoopLoopOptions): Promise<string | undefined>;
134
+ /**
135
+ * Run a file's item list against freshly-read content with served
136
+ * verification, evolving content/hashes, union range, noop tracking, and a
137
+ * per-file drift notice. All-or-nothing is enforced by the caller's
138
+ * transaction ({@link persistUndoAndWrite}): nothing here writes to disk.
139
+ */
140
+ export declare function runFileEdits(io: FileIO, items: PreparedItem[], opts: {
141
+ signal?: AbortSignal;
142
+ sessionKey: string;
143
+ }): Promise<FileEditResult>;
@@ -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,10 +8,11 @@
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 {
15
+ encoding?: string;
15
16
  /** The session whose served rows these lines belong to. */
16
17
  sessionKey: string;
17
18
  signal?: AbortSignal;
@@ -20,6 +21,8 @@ export interface ReadAndServeOptions {
20
21
  limit?: number;
21
22
  }
22
23
  export interface ReadAndServeResult {
24
+ /** Optional auto-guess warning, separate block. */
25
+ warning?: string;
23
26
  /** The model-facing read text, including the UTF-8 note when applicable. */
24
27
  text: string;
25
28
  /** The rows recorded as served (empty when nothing was shown). */
@@ -1,41 +1,27 @@
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 { ServedRow, ResolvedRange } from "./hashline/anchor-pipeline.js";
39
25
  export { loadHashStore, loadServedStore, shutdownHashStore, withStore } from "./hash-store.js";
40
26
  export type { HashStore } from "./hash-store.js";
41
27
  export type ServedEntry = {
@@ -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";
@@ -3,25 +3,34 @@ export declare function expand(filePath: string): string;
3
3
  declare const StoreConfigSchema: z.ZodObject<{
4
4
  storeDir: z.ZodEffects<z.ZodDefault<z.ZodString>, string, string | undefined>;
5
5
  autoGitignore: z.ZodDefault<z.ZodBoolean>;
6
+ autoGuessEncoding: z.ZodDefault<z.ZodBoolean>;
7
+ normalizeToUtf8: z.ZodDefault<z.ZodBoolean>;
8
+ supportedEncodings: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
6
9
  undo_ttl_s: z.ZodDefault<z.ZodNumber>;
7
10
  storeMaxAgeS: z.ZodDefault<z.ZodNumber>;
8
11
  storeMaxTotalBytes: z.ZodDefault<z.ZodNumber>;
9
12
  }, "strip", z.ZodTypeAny, {
10
13
  storeDir: string;
11
14
  autoGitignore: boolean;
15
+ autoGuessEncoding: boolean;
16
+ normalizeToUtf8: boolean;
17
+ supportedEncodings: string[];
12
18
  undo_ttl_s: number;
13
19
  storeMaxAgeS: number;
14
20
  storeMaxTotalBytes: number;
15
21
  }, {
16
22
  storeDir?: string | undefined;
17
23
  autoGitignore?: boolean | undefined;
24
+ autoGuessEncoding?: boolean | undefined;
25
+ normalizeToUtf8?: boolean | undefined;
26
+ supportedEncodings?: string[] | undefined;
18
27
  undo_ttl_s?: number | undefined;
19
28
  storeMaxAgeS?: number | undefined;
20
29
  storeMaxTotalBytes?: number | undefined;
21
30
  }>;
22
31
  export type StoreConfig = z.infer<typeof StoreConfigSchema>;
23
32
  /** Default config.yaml content with comments — generated when the file does not exist. */
24
- export declare const DEFAULT_CONFIG_YAML = "# dsh-better-edit config\n# Location: $DSH_HOME/plugins/dsh-better-edit/config.yaml\n# Docs: https://github.com/Rianico/dsh-better-edit#configuration\n# Generated with defaults on first load \u2014 edit or delete freely.\n# DB files are disposable caches \u2014 safe to delete, rebuilt on next `read`.\n\n# where the store lives: \"central\" (default, in $DSH_HOME/.../runtime/<name>-<hash8>/) | \"workspace\" (legacy <ws>/.dsh_better_edit/) | \"/abs/path\" (custom root)\nstoreDir: central\n\n# workspace only: when .git exists but .gitignore lacks .dsh_better_edit/, true = auto-append \".dsh_better_edit/\", false = warn once\nautoGitignore: false\n\n# undo history TTL in seconds; -1 = keep forever (default 604800 = 7 days)\nundo_ttl_s: 604800\n\n# central janitor: max idle age in seconds before evicting runtime/<name>-<hash8>/ (default 2592000 = 30 days)\nstoreMaxAgeS: 2592000\n\n# central janitor: max total bytes under runtime/ before LRU eviction (default 524288000 = 500 MB)\nstoreMaxTotalBytes: 524288000\n";
33
+ export declare const DEFAULT_CONFIG_YAML = "# dsh-better-edit config\n# Location: $DSH_HOME/plugins/dsh-better-edit/config.yaml\n# Docs: https://github.com/Rianico/dsh-better-edit#configuration\n# Generated with defaults on first load \u2014 edit or delete freely.\n# DB files are disposable caches \u2014 safe to delete, rebuilt on next `read`.\n\n# where the store lives: \"central\" (default, in $DSH_HOME/.../runtime/<name>-<hash8>/) | \"workspace\" (legacy <ws>/.dsh_better_edit/) | \"/abs/path\" (custom root)\nstoreDir: central\n\n# workspace only: when .git exists but .gitignore lacks .dsh_better_edit/, true = auto-append \".dsh_better_edit/\", false = warn once\nautoGitignore: false\n\n# encoding: deterministic BOM\u2192UTF-8 first, guessing only when autoGuessEncoding:true\n# when true, FS_NOT_TEXT scores supportedEncodings and surfaces top-3 previews for model pick\nautoGuessEncoding: false\n# when true, legacy files (GBK etc.) migrate to UTF-8 on first write\nnormalizeToUtf8: false\n# allowlist scored for top-3 previews when autoGuessEncoding:true\nsupportedEncodings: [gbk, big5, shift_jis, euc-kr, windows-1251, iso-8859-1]\n\n# undo history TTL in seconds; -1 = keep forever (default 604800 = 7 days)\nundo_ttl_s: 604800\n\n# central janitor: max idle age in seconds before evicting runtime/<name>-<hash8>/ (default 2592000 = 30 days)\nstoreMaxAgeS: 2592000\n\n# central janitor: max total bytes under runtime/ before LRU eviction (default 524288000 = 500 MB)\nstoreMaxTotalBytes: 524288000\n";
25
34
  /**
26
35
  * Ensure a default config.yaml exists in the plugin home.
27
36
  * Idempotent and concurrent-safe (wx) — never overwrites an existing file.
@@ -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.0",
3
+ "version": "0.6.0",
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",
@@ -56,6 +56,7 @@
56
56
  "dependencies": {
57
57
  "diff": "^8.0.2",
58
58
  "file-type": "^21.3.0",
59
+ "iconv-lite": "^0.6.3",
59
60
  "xxhash-wasm": "^1.1.0",
60
61
  "zod": "^3.25.76"
61
62
  },
@@ -100,5 +101,8 @@
100
101
  "semantic-release": "^25.0.9",
101
102
  "typescript": "^5.8.0",
102
103
  "vitest": "^4.1.8"
104
+ },
105
+ "optionalDependencies": {
106
+ "chardet": "2.2.0"
103
107
  }
104
108
  }