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
@@ -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;
@@ -89,6 +89,8 @@ export interface ReadNormOptions {
89
89
  maxLines?: number;
90
90
  store?: HashStore;
91
91
  noPersist?: boolean;
92
+ reservedHashes?: ReadonlySet<string>;
93
+ retiredHashes?: ReadonlySet<string>;
92
94
  }
93
95
  export declare function normFromText(input: {
94
96
  absolutePath: string;
@@ -98,6 +100,8 @@ export declare function normFromText(input: {
98
100
  maxLines?: number;
99
101
  store?: HashStore;
100
102
  noPersist?: boolean;
103
+ reservedHashes?: ReadonlySet<string>;
104
+ retiredHashes?: ReadonlySet<string>;
101
105
  hadUtf8DecodeErrors?: boolean;
102
106
  }): Promise<NormFile>;
103
107
  export declare function readNormFile(path: string, cwd: string, options?: ReadNormOptions): Promise<NormFile>;
@@ -130,6 +134,8 @@ export interface PreviewOpts {
130
134
  export interface ReadViewOpts extends PreviewOpts {
131
135
  encoding?: string;
132
136
  signal?: AbortSignal;
137
+ reservedHashes?: ReadonlySet<string>;
138
+ retiredHashes?: ReadonlySet<string>;
133
139
  }
134
140
  export declare function preview(content: string, hashes: string[], opts?: PreviewOpts, absolutePath?: string): Promise<{
135
141
  text: string;
@@ -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). */
@@ -21,6 +21,7 @@ export interface LegacySnapshot {
21
21
  export declare function isValidHashList(value: unknown): value is string[];
22
22
  export declare function isValidSnapshot(value: unknown): value is LegacySnapshot;
23
23
  /** A served-row array: per-position hash, or null for never-served slots. */
24
+ export declare function isValidCanonsList(value: unknown): value is (string | null)[];
24
25
  export declare function isValidServedList(value: unknown): value is (string | null)[];
25
26
  /** The undo row contract shared by undo-edit and the store. */
26
27
  export interface UndoRecord {
@@ -66,14 +67,28 @@ export interface HashStore {
66
67
  export interface ServedPersistence {
67
68
  getServed(sessionKey: string, path: string): (string | null)[];
68
69
  getServedReported(sessionKey: string, path: string): Set<string>;
70
+ getAnchorReservations(path: string): AnchorReservations;
71
+ getRetiredAnchors(sessionKey: string, path: string): Set<string>;
72
+ getServedCanons(sessionKey: string, path: string): (string | null)[];
73
+ getEpochSnapshotId(sessionKey: string, path: string): string | undefined;
69
74
  upsertServed(sessionKey: string, path: string, hashesJson: string): void;
70
75
  upsertServedReported(sessionKey: string, path: string, reportedJson: string): void;
71
76
  clearServedReported(sessionKey: string, path: string): void;
77
+ upsertRetiredAnchors(sessionKey: string, path: string, hashesJson: string): void;
78
+ clearRetiredAnchors(sessionKey: string, path: string): void;
79
+ upsertServedCanons(sessionKey: string, path: string, canonsJson: string): void;
80
+ clearServedCanons(sessionKey: string, path: string): void;
81
+ upsertEpochSnapshotId(sessionKey: string, path: string, snapshotId: string): void;
82
+ clearEpochSnapshotId(sessionKey: string, path: string): void;
72
83
  deleteServed(sessionKey: string, path: string): void;
73
84
  deleteServedByPath(path: string): void;
74
85
  wipeServed(sessionKey: string): void;
75
86
  pruneServedOlderThan(ts: number): void;
76
87
  }
88
+ export interface AnchorReservations {
89
+ reservedHashes: Set<string>;
90
+ retiredHashes: Set<string>;
91
+ }
77
92
  export type InternalHashStore = HashStore & ServedPersistence;
78
93
  /** Load the store as served persistence — internal, for SessionView only. */
79
94
  export declare function loadServedStore(cwd?: string): Promise<ServedPersistence>;
@@ -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 {
@@ -103,6 +88,11 @@ export declare function verifyServedRange(args: {
103
88
  fileHashes: string[];
104
89
  fileLines: string[];
105
90
  filePath?: string;
91
+ servedCanons?: (string | null)[];
92
+ tombstone?: ReadonlySet<string>;
93
+ epochSnapshotId?: string;
94
+ curSnapshotId?: string;
95
+ strictPos?: boolean;
106
96
  }): void;
107
97
  export interface ResolvedRange {
108
98
  startLine: number;
@@ -118,17 +108,18 @@ type LIdx = {
118
108
  lineStarts: number[];
119
109
  };
120
110
  export declare function buildIdx(content: string): LIdx;
121
- export declare function applyEdit(content: string, edit: HEdit, signal?: AbortSignal, precomputedHashes?: string[], filePath?: string, served?: (string | null)[]): {
111
+ export declare function applyEdit(content: string, edit: HEdit, signal?: AbortSignal, precomputedHashes?: string[], filePath?: string, served?: (string | null)[], servedCanons?: (string | null)[], tombstone?: ReadonlySet<string>, epochSnapshotId?: string, curSnapshotId?: string, strictPos?: boolean): {
122
112
  content: string;
123
113
  firstChangedLine: number | undefined;
124
114
  lastChangedLine: number | undefined;
125
115
  range: ResolvedRange;
126
116
  warnings?: string[];
127
117
  noopEdit?: NEdit;
128
- autoFixes?: AutoFix[];
129
118
  };
130
119
  export declare function fmtRegion(hashes: string[], lines: string[]): string;
131
120
  export declare function changedRange(original: string, result: string): {
132
121
  firstChangedLine: number;
133
122
  lastChangedLine: number;
134
123
  } | null;
124
+ 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";
125
+ export { lineHashes } from "./hash.js";
@@ -23,5 +23,5 @@ export declare const HL_PREFIX_MINUS_RE: RegExp;
23
23
  export declare const HL_BARE_PREFIX_RE: RegExp;
24
24
  export declare const CANON_VERSION = 2;
25
25
  export declare function canon(line: string): string;
26
- export declare function lineHashesPure(content: string): string[];
27
- export declare function mapStableHashes(oldContent: string, oldHashes: string[], newContent: string, removedHashes?: Set<string>): string[];
26
+ export declare function lineHashesPure(content: string, reservedHashes?: ReadonlySet<string>): string[];
27
+ export declare function mapStableHashes(oldContent: string, oldHashes: string[], newContent: string, removedHashes?: Set<string>, reservedHashes?: ReadonlySet<string>): string[];
@@ -10,4 +10,4 @@ export declare function lineHashes(content: string, path?: string, previous?: {
10
10
  content: string;
11
11
  hashes: string[];
12
12
  removedHashes?: Set<string>;
13
- }, ioOrStore?: HashStore | HashSnapshotIO, persist?: boolean): Promise<string[]>;
13
+ }, ioOrStore?: HashStore | HashSnapshotIO, persist?: boolean, reservedHashes?: ReadonlySet<string>, retiredHashes?: ReadonlySet<string>): Promise<string[]>;
@@ -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,149 @@
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
+ reservedHashes?: ReadonlySet<string>;
83
+ servedCanons?: (string | null)[];
84
+ tombstone?: ReadonlySet<string>;
85
+ epochSnapshotId?: string;
86
+ curSnapshotId?: string;
87
+ strictPos?: boolean;
88
+ /** Pre-resolved edit (single path keeps resEdit before IO for error order). */
89
+ edit?: HEdit;
90
+ }
91
+ export interface ApplyOneResult {
92
+ result: string;
93
+ /** Stable re-hash after the edit (equals `hashes` for a noop). */
94
+ hashes: string[];
95
+ range: ResolvedRange;
96
+ noop: boolean;
97
+ edit: HEdit;
98
+ noopEdit?: NEdit;
99
+ firstChangedLine?: number;
100
+ lastChangedLine?: number;
101
+ removedHashes: Set<string> | undefined;
102
+ totalAddedLines: number;
103
+ totalRemovedLines: number;
104
+ anchorWarnings: string[] | undefined;
105
+ }
106
+ /**
107
+ * One edit against in-memory content: resolve (unless a pre-resolved edit was
108
+ * given) → apply with served verification → stable re-hash → line counts.
109
+ *
110
+ * `onReject` owns the reject-and-serve policy: it receives resolve/verify
111
+ * failures (and the edit that failed, when resolved) and MUST throw. The
112
+ * single path rethrows the original anchor error after recording echo serves;
113
+ * the batch path wraps with [E_BATCH_ABORT] plus the current-range echo.
114
+ */
115
+ export declare function applyOne(input: ApplyOneInput, onReject: (error: unknown, edit: HEdit | undefined) => Promise<never>): Promise<ApplyOneResult>;
116
+ export interface NoopLoopOptions {
117
+ absolutePath: string;
118
+ removeFrom: string;
119
+ removeTo: string;
120
+ replacementText: string;
121
+ displayPath: string;
122
+ /** Batch item index; undefined = single-edit flavor. */
123
+ index?: number;
124
+ count: number;
125
+ sessionKey: string;
126
+ originalHashes: string[];
127
+ originalNormalized: string;
128
+ /** Single-edit flavor only: the edit's range, for the echo rows. */
129
+ range?: ResolvedRange;
130
+ /** Batch flavor: precomputed echo rows for the failed item (may be absent). */
131
+ echoRows?: ServedRow[];
132
+ }
133
+ /**
134
+ * The shared noop-loop guard. Returns the "twice in a row" notice for the
135
+ * caller to append to warnings, or throws [E_NOOP_LOOP] (after recording the
136
+ * echo serves) once the payload has been submitted NOOP_LOOP_THRESHOLD times
137
+ * with no change. Messages are byte-identical to the pre-engine tools.
138
+ */
139
+ export declare function enforceNoopLoop(opts: NoopLoopOptions): Promise<string | undefined>;
140
+ /**
141
+ * Run a file's item list against freshly-read content with served
142
+ * verification, evolving content/hashes, union range, noop tracking, and a
143
+ * per-file drift notice. All-or-nothing is enforced by the caller's
144
+ * transaction ({@link persistUndoAndWrite}): nothing here writes to disk.
145
+ */
146
+ export declare function runFileEdits(io: FileIO, items: PreparedItem[], opts: {
147
+ signal?: AbortSignal;
148
+ sessionKey: string;
149
+ }): Promise<FileEditResult>;