dsh-better-edit 0.5.1 → 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.
package/lib/mutation.js CHANGED
@@ -29,13 +29,16 @@ import { toCwd } from "./paths.js";
29
29
  import { resEdit } from "./hashline/anchor-pipeline.js";
30
30
  import { MAX_HASH_LINES } from "./hashline/hash-assign.js";
31
31
  import { AnchorMismatchError, ServedRejectionError, recordEchoServes, } from "./hashline/anchor-pipeline.js";
32
- import { loadServed, sessionKeyFor, scanDrift, recordServedTruncated } from "./session-view.js";
32
+ import { sessionKeyFor } from "./workspace-context.js";
33
+ import { loadServed, scanDrift, recordServedTruncated } from "./session-view.js";
33
34
  import { abortIf, splitLines } from "./utils.js";
34
- import { applyOne } from "./edit-engine.js";
35
- import { runFileEdits, resolveMissingPath, persistUndoAndWrite, enforceNoopLoop, collectRemovedHashes, countLineChanges, } from "./edit-engine.js";
35
+ import { applyOne } from "./mutation/engine.js";
36
+ import { runFileEdits, resolveMissingPath, } from "./mutation/engine.js";
37
+ import { saveUndo } from "./undo-edit.js";
38
+ import { restoreEndings } from "./edit-diff.js";
36
39
  import { buildMetrics, buildNoop, buildChanged, buildBatchResult } from "./edit-response.js";
37
- import { genDiff, restoreEndings, toLF, stripBOM } from "./edit-diff.js";
38
- import { computeDrift } from "./drift.js";
40
+ import { genDiff, toLF, stripBOM } from "./edit-diff.js";
41
+ import { computeDrift } from "./session-view.js";
39
42
  import { trackNoopPayload, clearNoopLoop, noopPayloadKey } from "./noop-guard.js";
40
43
  export async function execPipeline(io, params, cwd, options) {
41
44
  const path = params.path;
@@ -142,11 +145,82 @@ export async function snapshotIdFor(io, absolutePath, signal) {
142
145
  }
143
146
  }
144
147
  }
145
- export { runFileEdits, resolveMissingPath, persistUndoAndWrite, enforceNoopLoop, collectRemovedHashes, countLineChanges, };
148
+ // Engine helpers are private to Mutation — not re-exported for new code.
149
+ // Deprecated re-exports kept for existing tests (commitlint: ignore):
150
+ export { runFileEdits, resolveMissingPath };
151
+ export { persistUndoAndWrite };
146
152
  export { buildMetrics, buildNoop, buildChanged, buildBatchResult };
147
153
  export { genDiff, restoreEndings, toLF, stripBOM };
148
154
  export { computeDrift, scanDrift };
149
155
  export { trackNoopPayload, clearNoopLoop, noopPayloadKey };
156
+ async function persistUndoAndWrite(opts) {
157
+ const { io, files } = opts;
158
+ const undos = [];
159
+ for (const file of files) {
160
+ const undo = await saveUndo(file.absolutePath, {
161
+ content: file.originalNormalized,
162
+ bom: file.bom,
163
+ originalEnding: file.originalEnding,
164
+ hashes: file.originalHashes,
165
+ resultContent: file.result,
166
+ });
167
+ if (!undo.persisted) {
168
+ for (const u of undos) {
169
+ try {
170
+ await u.restore();
171
+ }
172
+ catch (e) {
173
+ console.error("Failed to restore undo entry after abort:", e);
174
+ }
175
+ }
176
+ throw new Error(opts.undoUnavailableMessage(file.displayPath));
177
+ }
178
+ undos.push({ file, restore: undo.restore });
179
+ }
180
+ const written = [];
181
+ try {
182
+ for (const u of undos) {
183
+ abortIf(opts.signal);
184
+ await io.writeText(u.file.absolutePath, u.file.bom + restoreEndings(u.file.result, u.file.originalEnding), opts.signal, opts.exec, opts.sandboxPolicy);
185
+ written.push(u);
186
+ }
187
+ }
188
+ catch (error) {
189
+ for (const w of written) {
190
+ try {
191
+ await io.writeText(w.file.absolutePath, w.file.bom + restoreEndings(w.file.originalNormalized, w.file.originalEnding), undefined, opts.exec, opts.sandboxPolicy);
192
+ }
193
+ catch (e) {
194
+ console.error("Failed to restore file after write failure:", e);
195
+ }
196
+ try {
197
+ await w.restore();
198
+ }
199
+ catch (e) {
200
+ console.error("Failed to restore undo entry after write failure:", e);
201
+ }
202
+ }
203
+ if (opts.restoreUnwrittenUndos) {
204
+ for (const u of undos) {
205
+ if (written.includes(u))
206
+ continue;
207
+ try {
208
+ await u.restore();
209
+ }
210
+ catch (e) {
211
+ console.error("Failed to restore undo entry after write failure:", e);
212
+ }
213
+ }
214
+ }
215
+ throw opts.sandbox.mapError(error, opts.sandboxPolicy);
216
+ }
217
+ }
218
+ async function commitSingle(opts) {
219
+ return persistUndoAndWrite({ ...opts, restoreUnwrittenUndos: true });
220
+ }
221
+ async function commitBatch(opts) {
222
+ return persistUndoAndWrite({ ...opts, restoreUnwrittenUndos: false });
223
+ }
150
224
  // --- Deep seam: unified mutation API (one interface, thin adapters) ---
151
225
  /**
152
226
  * Deep seam: execute the full mutation lifecycle.
@@ -190,7 +264,7 @@ export async function execute(opts) {
190
264
  await recordIfNeeded(built);
191
265
  return built.content[0].text;
192
266
  }
193
- await commit({
267
+ await commitSingle({
194
268
  io,
195
269
  files: [
196
270
  {
@@ -208,7 +282,6 @@ export async function execute(opts) {
208
282
  sandboxPolicy,
209
283
  signal,
210
284
  undoUnavailableMessage: (displayPath) => `[E_UNDO_UNAVAILABLE] Cannot persist undo history to the hash store; the edit was NOT applied and ${displayPath} is unchanged. Retry the edit, or use write if the store cannot be recovered.`,
211
- restoreUnwrittenUndos: true,
212
285
  });
213
286
  const built = buildBatchResult([toSection()]);
214
287
  await recordIfNeeded(built);
@@ -218,7 +291,7 @@ export async function execute(opts) {
218
291
  // all noops — no commit
219
292
  }
220
293
  else if (fileResult.appliedCount > 0) {
221
- await commit({
294
+ await commitBatch({
222
295
  io,
223
296
  files: [
224
297
  {
@@ -236,7 +309,6 @@ export async function execute(opts) {
236
309
  sandboxPolicy,
237
310
  signal,
238
311
  undoUnavailableMessage: () => "[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.",
239
- restoreUnwrittenUndos: false,
240
312
  });
241
313
  }
242
314
  const built = buildBatchResult([toSection()]);
@@ -261,6 +333,7 @@ export async function commit(opts) {
261
333
  sandboxPolicy: opts.sandboxPolicy,
262
334
  signal: opts.signal,
263
335
  undoUnavailableMessage: opts.undoUnavailableMessage,
264
- restoreUnwrittenUndos: opts.restoreUnwrittenUndos,
336
+ restoreUnwrittenUndos: opts.restoreUnwrittenUndos ?? false,
265
337
  });
266
338
  }
339
+ export { commitSingle, commitBatch };
package/lib/paths.js CHANGED
@@ -9,7 +9,7 @@
9
9
  import { isAbsolute } from "node:path";
10
10
  import { resolve as resolvePath } from "node:path";
11
11
  import { expand } from "./store-tenancy.js";
12
- export * from "./store-tenancy.js";
12
+ export * from "./store/index.js"; // Store seam — single answer for "which store, where" (tenancy+lifecycle+path)
13
13
  export { canonicalAsync as resolveTarget } from "./canonical-path.js";
14
14
  export { canonicalSync } from "./canonical-path.js";
15
15
  export function toCwd(filePath, cwd) {
@@ -1,63 +1,30 @@
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 { randomUUID } from "node:crypto";
31
- import { AsyncLocalStorage } from "node:async_hooks";
32
24
  import { HASH_RE } from "./hashline/hash-assign.js";
33
25
  import { loadHashStore, loadServedStore, withStore } from "./hash-store.js";
34
26
  import { SERVED_ECHO_CAP } from "./constants.js";
35
- import { fmtServedRows } from "./hashline/served.js";
36
- import { configDir, hashStorePath, resolveTarget } from "./paths.js";
37
- // --- workspace (private to this seam, @internal) ---
38
- const current = new AsyncLocalStorage();
39
- export function withWorkspace(cwd, fn) {
40
- return current.run(cwd, fn);
41
- }
42
- export function workspaceCwd() {
43
- return current.getStore();
44
- }
45
- // --- dsh-context (private to this seam) ---
46
- let fallbackSessionKey;
47
- export function sessionKeyFor(sessionId) {
48
- if (sessionId && sessionId.length > 0)
49
- return sessionId;
50
- // fallback for previews/tests
51
- return fallbackSessionKey ??= randomUUID();
52
- }
53
- export function execCwd(exec) {
54
- return exec.agent?.session.header.cwd ?? process.cwd();
55
- }
56
- export function execSessionKey(exec) {
57
- return sessionKeyFor(exec.agent?.session.id);
58
- }
59
- // --- paths re-export (seam visibility) ---
60
- export { configDir, hashStorePath, resolveTarget };
27
+ import { fmtServedRows } from "./hashline/anchor-pipeline.js";
61
28
  // --- hash-store re-export (persistence note) ---
62
29
  export { loadHashStore, loadServedStore, shutdownHashStore, withStore } from "./hash-store.js";
63
30
  /**
@@ -0,0 +1,28 @@
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
+ // Tenancy — re-export as seam ownership (private details, public via Store)
21
+ export { tenancyFor, configDir, hashStorePath, hashStoreDir, legacyHashStorePath, loadConfig, _resetConfigCache, expand, } from "../store-tenancy.js";
22
+ // Lifecycle — re-export as seam ownership
23
+ export { onStoreOpen, onAppStart, onSessionStart, setStoresGetter, runCentralJanitorIfDue, _resetLifecycleForTests, } from "../store-lifecycle.js";
24
+ // StoreConfig path helper — canonical Store seam entry for config consumers
25
+ export { loadConfig as loadStoreConfig } from "../store-config.js";
26
+ // Hash-store plumbing re-exported for testability without domain coupling
27
+ // (future: move openDb/buildStore/quarantine/busy-retry here)
28
+ export { isCorruptionError, loadHashStore, shutdownHashStore, withStore, findSnapshotPathsByHashes, upsertSnapshotFor, } from "../hash-store.js";
@@ -16,7 +16,7 @@ import { dirname, join } from "node:path";
16
16
  import { DatabaseSync } from "node:sqlite";
17
17
  import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
18
18
  import { hashStorePath, loadConfig } from "./paths.js";
19
- import { workspaceCwd } from "./workspace.js";
19
+ import { workspaceCwd } from "./workspace-context.js";
20
20
  import { errCode, splitLines } from "./utils.js";
21
21
  import { HASH_STORE_BUSY_TIMEOUT, SERVED_TTL_MS } from "./constants.js";
22
22
  // ---- throttling state (owned here) ----
package/lib/tool-edit.js CHANGED
@@ -10,8 +10,8 @@ import { normalizeRequest as normReq, assertEditRequest, } from "./contract.js";
10
10
  import { abortIf } from "./utils.js";
11
11
  import { execute } from "./mutation.js";
12
12
  import { EDIT_DESCRIPTION } from "./prompts.js";
13
- import { execCwd, execSessionKey } from "./session-view.js";
14
- import { withWorkspace } from "./session-view.js";
13
+ import { execCwd, execSessionKey } from "./workspace-context.js";
14
+ import { withWorkspace } from "./workspace-context.js";
15
15
  import { findSnapshotPathsByHashes } from "./hash-store.js";
16
16
  import { parseHashRef } from "./hashline/anchor-pipeline.js";
17
17
  async function resolveNullPath(edits) {
package/lib/tool-read.js CHANGED
@@ -10,8 +10,8 @@ import { normalizeRequest as normReq, assertReadRequest, pathSchema } from "./co
10
10
  import { readAndServe } from "./read-and-serve.js";
11
11
  import { READ_DESCRIPTION } from "./prompts.js";
12
12
  import { normalizeEncoding } from "./encoding.js";
13
- import { execCwd, execSessionKey } from "./session-view.js";
14
- import { withWorkspace } from "./session-view.js";
13
+ import { execCwd, execSessionKey } from "./workspace-context.js";
14
+ import { withWorkspace } from "./workspace-context.js";
15
15
  /**
16
16
  * Register the hash-anchored `read` tool on the calling agent's scope.
17
17
  * @param _rootCtx - host context.
package/lib/tool-undo.js CHANGED
@@ -16,8 +16,8 @@ import { changedRange } from "./hashline/anchor-pipeline.js";
16
16
  import { getUndo, clearUndo } from "./undo-edit.js";
17
17
  import { recordServedTruncated } from "./session-view.js";
18
18
  import { UNDO_DESCRIPTION } from "./prompts.js";
19
- import { execCwd, execSessionKey } from "./session-view.js";
20
- import { withWorkspace } from "./session-view.js";
19
+ import { execCwd, execSessionKey } from "./workspace-context.js";
20
+ import { withWorkspace } from "./workspace-context.js";
21
21
  /**
22
22
  * Register the `undo_last_edit` tool on the calling agent's scope.
23
23
  * @param _rootCtx - host context.
@@ -1,4 +1,4 @@
1
- import type { ServedRow } from "./hashline/served.js";
1
+ import type { ServedRow } from "./hashline/anchor-pipeline.js";
2
2
  export type LineEnding = "\r\n" | "\n" | "\r";
3
3
  export declare function detectEnding(content: string): LineEnding;
4
4
  export declare function toLF(text: string): string;
@@ -1,179 +1,7 @@
1
1
  /**
2
- * The edit-sequence engine shared by `edit`, `batch_edit`, and previews:
3
- * apply-one-edit against in-memory content with served verification, the
4
- * multi-edit sequencer that drives a whole file's item list against evolving
5
- * content, the noop-loop guard, and the persist-undo → write → restore
6
- * transaction both mutating tools run.
7
- *
8
- * The model-facing contract lives here unchanged: [E_BATCH_ABORT],
9
- * [E_NOOP_LOOP], [E_UNDO_UNAVAILABLE] carry byte-identical messages, and
10
- * reject-and-serve records the same echo serves.
2
+ * @deprecated — private to Mutation seam. Use `from "./mutation/engine.js"` instead.
3
+ * Thin shim re-exporting the engine now owned by Mutation.
11
4
  * @module dsh-better-edit/edit-engine
12
5
  */
13
- import type { ToolExecution } from "@deepseek-ai/dsh-tools";
14
- import type { SandboxExecutionPolicy } from "@deepseek-ai/dsh-sandbox";
15
- import type { FileIO } from "./fs-bridge.js";
16
- import type { HashStore } from "./hash-store.js";
17
- import type { LineEnding } from "./edit-diff.js";
18
- import { type HEdit, type NEdit } from "./hashline/anchor-pipeline.js";
19
- import { type ResolvedRange, type ServeRecordPolicy, type ServedRow } from "./hashline/anchor-pipeline.js";
20
- import type { FsSandboxController } from "./sandbox.js";
21
- export interface PreparedItem {
22
- index: number;
23
- path: string;
24
- absolutePath: string;
25
- remove_from: string;
26
- remove_to: string;
27
- replacement_text: string;
28
- pathWarning?: string;
29
- }
30
- export interface FileEditResult {
31
- displayPath: string;
32
- absolutePath: string;
33
- originalNormalized: string;
34
- result: string;
35
- bom: string;
36
- originalEnding: LineEnding;
37
- hadUtf8DecodeErrors: boolean;
38
- warnings: string[];
39
- originalHashes: string[];
40
- resultHashes: string[];
41
- appliedCount: number;
42
- noopCount: number;
43
- totalAddedLines: number;
44
- totalRemovedLines: number;
45
- driftNotice: string | undefined;
46
- range: ResolvedRange;
47
- }
48
- /**
49
- * Resolve a request's missing `path` from its anchors: the only file whose
50
- * stored hashes contain both anchors. Returns the path plus an autocorrect
51
- * warning, or undefined when no resolution is possible.
52
- */
53
- export declare function resolveMissingPath(request: Record<string, unknown>): Promise<{
54
- path: string;
55
- warning: string;
56
- } | undefined>;
57
- /** The hashes a range edit removes, for stable re-hash bookkeeping. */
58
- export declare function collectRemovedHashes(edit: HEdit, originalHashes: string[]): Set<string>;
59
- /** Added/removed line counts for one resolved edit against a file's original hashes. */
60
- export declare function countLineChanges(edit: HEdit, originalHashes: string[], isNoop: boolean, removedAutoFixes: number): {
61
- totalAddedLines: number;
62
- totalRemovedLines: number;
63
- };
64
- export interface ApplyOneInput {
65
- content: string;
66
- hashes: string[];
67
- served: (string | null)[];
68
- removeFrom: string;
69
- removeTo: string;
70
- replacementText: string;
71
- absolutePath: string;
72
- displayPath: string;
73
- signal?: AbortSignal;
74
- /** Shared warnings array; resEdit warnings are pushed here. */
75
- warnings: string[];
76
- /**
77
- * The hashes to count added/removed lines against. Defaults to `hashes`;
78
- * the batch sequencer passes the file's ORIGINAL hashes so later edits in
79
- * a sequence still count against the file as first served.
80
- */
81
- countHashes?: string[];
82
- store?: HashStore;
83
- persist: boolean;
84
- /** Pre-resolved edit (single path keeps resEdit before IO for error order). */
85
- edit?: HEdit;
86
- }
87
- export interface ApplyOneResult {
88
- result: string;
89
- /** Stable re-hash after the edit (equals `hashes` for a noop). */
90
- hashes: string[];
91
- range: ResolvedRange;
92
- noop: boolean;
93
- edit: HEdit;
94
- noopEdit?: NEdit;
95
- firstChangedLine?: number;
96
- lastChangedLine?: number;
97
- removedHashes: Set<string> | undefined;
98
- totalAddedLines: number;
99
- totalRemovedLines: number;
100
- anchorWarnings: string[] | undefined;
101
- }
102
- /**
103
- * One edit against in-memory content: resolve (unless a pre-resolved edit was
104
- * given) → apply with served verification → stable re-hash → line counts.
105
- *
106
- * `onReject` owns the reject-and-serve policy: it receives resolve/verify
107
- * failures (and the edit that failed, when resolved) and MUST throw. The
108
- * single path rethrows the original anchor error after recording echo serves;
109
- * the batch path wraps with [E_BATCH_ABORT] plus the current-range echo.
110
- */
111
- export declare function applyOne(input: ApplyOneInput, onReject: (error: unknown, edit: HEdit | undefined) => Promise<never>): Promise<ApplyOneResult>;
112
- export interface NoopLoopOptions {
113
- absolutePath: string;
114
- removeFrom: string;
115
- removeTo: string;
116
- replacementText: string;
117
- displayPath: string;
118
- /** Batch item index; undefined = single-edit flavor. */
119
- index?: number;
120
- count: number;
121
- sessionKey: string;
122
- originalHashes: string[];
123
- originalNormalized: string;
124
- /** Single-edit flavor only: the edit's range, for the echo rows. */
125
- range?: ResolvedRange;
126
- /** Batch flavor: precomputed echo rows for the failed item (may be absent). */
127
- echoRows?: ServedRow[];
128
- }
129
- /**
130
- * The shared noop-loop guard. Returns the "twice in a row" notice for the
131
- * caller to append to warnings, or throws [E_NOOP_LOOP] (after recording the
132
- * echo serves) once the payload has been submitted NOOP_LOOP_THRESHOLD times
133
- * with no change. Messages are byte-identical to the pre-engine tools.
134
- */
135
- export declare function enforceNoopLoop(opts: NoopLoopOptions): Promise<string | undefined>;
136
- /**
137
- * Run a file's item list against freshly-read content with served
138
- * verification, evolving content/hashes, union range, noop tracking, and a
139
- * per-file drift notice. All-or-nothing is enforced by the caller's
140
- * transaction ({@link persistUndoAndWrite}): nothing here writes to disk.
141
- */
142
- export declare function runFileEdits(io: FileIO, items: PreparedItem[], opts: {
143
- signal?: AbortSignal;
144
- sessionKey: string;
145
- }): Promise<FileEditResult>;
146
- export interface UndoWriteFile {
147
- absolutePath: string;
148
- displayPath: string;
149
- originalNormalized: string;
150
- bom: string;
151
- originalEnding: LineEnding;
152
- originalHashes: string[];
153
- result: string;
154
- }
155
- export interface PersistWriteOptions {
156
- io: FileIO;
157
- files: UndoWriteFile[];
158
- exec: ToolExecution;
159
- sandbox: FsSandboxController;
160
- sandboxPolicy: SandboxExecutionPolicy | undefined;
161
- signal?: AbortSignal;
162
- /** [E_UNDO_UNAVAILABLE] message builder, per tool flavor. */
163
- undoUnavailableMessage: (displayPath: string) => string;
164
- /**
165
- * On write failure, also restore undo entries of files that were saved but
166
- * never written. The single-edit tool restores its one entry; the batch
167
- * tool keeps current behavior and restores only written files.
168
- */
169
- restoreUnwrittenUndos?: boolean;
170
- }
171
- /**
172
- * The persist-undo → write-all → restore-on-failure transaction shared by
173
- * `edit` (one file) and `batch_edit` (many files). Every file's undo entry is
174
- * persisted before anything is written; if a write fails, already-written
175
- * files are restored (original content written back, undo entry restored) and
176
- * the sandbox-mapped error rethrown.
177
- */
178
- export declare function persistUndoAndWrite(opts: PersistWriteOptions): Promise<void>;
179
- export type { ServeRecordPolicy };
6
+ export * from "./mutation/engine.js";
7
+ export { persistUndoAndWrite, commit, commitSingle, commitBatch } from "./mutation.js";
@@ -1,4 +1,4 @@
1
- import type { ServedRow } from "./hashline/served.js";
1
+ import type { ServedRow } from "./hashline/anchor-pipeline.js";
2
2
  export type EditDetails = {
3
3
  diff: string;
4
4
  firstChangedLine?: number;
@@ -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;
@@ -18,6 +18,10 @@ 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. */
@@ -53,17 +57,6 @@ export interface FileIO {
53
57
  * @returns the mapped error, rethrown.
54
58
  */
55
59
  export declare function mapFsError(error: unknown, displayPath: string): never;
56
- export interface FileEncodingState {
57
- encoding: string;
58
- hasBOM: boolean;
59
- version: string | undefined;
60
- }
61
- export declare function getAutoGuessFooter(targetKey: string): string | undefined;
62
- export declare function setAutoGuessFooter(targetKey: string, footer: string): void;
63
- export declare function clearAutoGuessFooter(targetKey?: string): void;
64
- export declare function getEncodingState(targetKey: string): FileEncodingState | undefined;
65
- export declare function setEncodingState(targetKey: string, state: FileEncodingState): void;
66
- export declare function clearEncodingState(targetKey?: string): void;
67
60
  /** FileIO over the deployment's `ctx.fs` service. */
68
61
  export declare function ctxFsIO(fs: FileSystem, ctx: Context): FileIO;
69
62
  /** FileIO over the host filesystem directly (tests, previews, fallback). */