dsh-better-edit 1.2.3 → 1.2.5

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 (105) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +39 -20
  3. package/README.zh.md +39 -31
  4. package/lib/contract.js +53 -22
  5. package/lib/domain-errors.js +18 -10
  6. package/lib/edit-mode.js +11 -0
  7. package/lib/encoding.js +2 -0
  8. package/lib/file-encoding-state.js +138 -44
  9. package/lib/file-view.js +26 -205
  10. package/lib/fs-bridge.js +53 -71
  11. package/lib/hashline/anchor-pipeline.js +8 -499
  12. package/lib/hashline/hash-assign.js +55 -4
  13. package/lib/hashline/index.js +5 -2
  14. package/lib/hashline/served-evidence.js +531 -0
  15. package/lib/index.js +177 -33
  16. package/lib/mutation/engine.js +19 -61
  17. package/lib/mutation.js +63 -105
  18. package/lib/noop-guard.js +24 -38
  19. package/lib/paths.js +9 -5
  20. package/lib/preset-toolset.js +144 -0
  21. package/lib/prompts.js +3 -3
  22. package/lib/read-and-serve.js +51 -53
  23. package/lib/reclaim.js +65 -0
  24. package/lib/self-heal.js +14 -13
  25. package/lib/session-view.js +79 -49
  26. package/lib/store/index.js +14 -14
  27. package/lib/store-config.js +4 -5
  28. package/lib/store-lifecycle.js +1 -1
  29. package/lib/tool-edit.js +14 -56
  30. package/lib/tool-read.js +2 -8
  31. package/lib/tool-str-replace-editor.js +34 -18
  32. package/lib/tool-undo.js +42 -24
  33. package/lib/types/contract.d.ts +11 -20
  34. package/lib/types/domain-errors.d.ts +14 -10
  35. package/lib/types/edit-mode.d.ts +11 -0
  36. package/lib/types/encoding.d.ts +1 -0
  37. package/lib/types/file-encoding-state.d.ts +51 -14
  38. package/lib/types/file-view.d.ts +18 -56
  39. package/lib/types/fs-bridge.d.ts +0 -1
  40. package/lib/types/hashline/anchor-pipeline.d.ts +6 -128
  41. package/lib/types/hashline/hash-assign.d.ts +40 -0
  42. package/lib/types/hashline/index.d.ts +6 -4
  43. package/lib/types/hashline/served-evidence.d.ts +152 -0
  44. package/lib/types/mutation/engine.d.ts +4 -12
  45. package/lib/types/mutation.d.ts +10 -58
  46. package/lib/types/noop-guard.d.ts +2 -33
  47. package/lib/types/paths.d.ts +0 -1
  48. package/lib/types/preset-toolset.d.ts +61 -0
  49. package/lib/types/reclaim.d.ts +36 -0
  50. package/lib/types/self-heal.d.ts +9 -3
  51. package/lib/types/session-view.d.ts +38 -8
  52. package/lib/types/store/index.d.ts +12 -11
  53. package/lib/types/store-config.d.ts +1 -1
  54. package/lib/types/store-lifecycle.d.ts +12 -2
  55. package/lib/types/tool-edit.d.ts +2 -4
  56. package/lib/types/tool-read.d.ts +0 -5
  57. package/lib/types/tool-str-replace-editor.d.ts +0 -6
  58. package/lib/types/tool-undo.d.ts +0 -5
  59. package/package.json +3 -2
  60. package/lib/drift.js +0 -5
  61. package/lib/dsh-context.js +0 -5
  62. package/lib/edit-engine.js +0 -7
  63. package/lib/edit-normalize.js +0 -9
  64. package/lib/edit-pipeline.js +0 -6
  65. package/lib/file-kind.js +0 -6
  66. package/lib/file-reader.js +0 -6
  67. package/lib/guidance/index.js +0 -8
  68. package/lib/hashline/alphabet.js +0 -2
  69. package/lib/hashline/apply.js +0 -2
  70. package/lib/hashline/hasher.js +0 -2
  71. package/lib/hashline/parse.js +0 -2
  72. package/lib/hashline/pure.js +0 -2
  73. package/lib/hashline/resolve.js +0 -3
  74. package/lib/hashline/served.js +0 -2
  75. package/lib/preview-controller.js +0 -65
  76. package/lib/read-render.js +0 -6
  77. package/lib/schema.js +0 -24
  78. package/lib/served-store.js +0 -5
  79. package/lib/tool-batch-edit.js +0 -190
  80. package/lib/truncate.js +0 -6
  81. package/lib/types/drift.d.ts +0 -5
  82. package/lib/types/dsh-context.d.ts +0 -5
  83. package/lib/types/edit-engine.d.ts +0 -7
  84. package/lib/types/edit-normalize.d.ts +0 -1
  85. package/lib/types/edit-pipeline.d.ts +0 -6
  86. package/lib/types/file-kind.d.ts +0 -6
  87. package/lib/types/file-reader.d.ts +0 -6
  88. package/lib/types/guidance/index.d.ts +0 -8
  89. package/lib/types/hashline/alphabet.d.ts +0 -1
  90. package/lib/types/hashline/apply.d.ts +0 -1
  91. package/lib/types/hashline/hasher.d.ts +0 -1
  92. package/lib/types/hashline/parse.d.ts +0 -1
  93. package/lib/types/hashline/pure.d.ts +0 -1
  94. package/lib/types/hashline/resolve.d.ts +0 -1
  95. package/lib/types/hashline/served.d.ts +0 -1
  96. package/lib/types/preview-controller.d.ts +0 -33
  97. package/lib/types/read-render.d.ts +0 -6
  98. package/lib/types/schema.d.ts +0 -25
  99. package/lib/types/served-store.d.ts +0 -5
  100. package/lib/types/tool-batch-edit.d.ts +0 -25
  101. package/lib/types/truncate.d.ts +0 -6
  102. package/lib/types/validation.d.ts +0 -6
  103. package/lib/types/workspace.d.ts +0 -5
  104. package/lib/validation.js +0 -6
  105. package/lib/workspace.js +0 -5
@@ -14,11 +14,15 @@
14
14
  * for backwards compat but are marked @internal and should be imported via this
15
15
  * module only.
16
16
  *
17
+ * The served-evidence verdict lives in served-evidence.ts (ADR-0037): this seam
18
+ * calls `verifyServedRange` and owns nothing it decides.
19
+ *
17
20
  * @module dsh-better-edit/hashline/anchor-pipeline
18
21
  */
19
22
  import { DomainError } from "../domain-errors.js";
20
- import type { ErrorPayloadMap, ServedRow, DomainErrorCode, RangeCause } from "../domain-errors.js";
21
- import type { EditMode } from "../contract.js";
23
+ import type { ErrorPayloadMap, DomainErrorCode } from "../domain-errors.js";
24
+ import type { LeaseSpanSource, ResolvedRange } from "./served-evidence.js";
25
+ import type { EditMode } from "../edit-mode.js";
22
26
  export type Anchor = {
23
27
  hash: string;
24
28
  };
@@ -48,27 +52,7 @@ export type HTEdit = {
48
52
  anchor_to: string;
49
53
  };
50
54
  export declare function resEdit(edit: HTEdit, _warnings?: string[]): HEdit;
51
- export type ServedCode = "E_STALE_RANGE" | "E_UNSERVED_RANGE";
52
55
  export type { ServedRow, RangeCause } from "../domain-errors.js";
53
- export declare class ServedRejectionError extends DomainError<DomainErrorCode> {
54
- readonly code: ServedCode;
55
- readonly unservedKind: "boundary" | "interior" | undefined;
56
- constructor(opts: {
57
- code: "E_STALE_RANGE";
58
- headline: string;
59
- servedRows: ServedRow[];
60
- servedBlock: string;
61
- cause?: RangeCause;
62
- firstOffendingLine?: number;
63
- } | {
64
- code: "E_UNSERVED_RANGE";
65
- headline: string;
66
- servedRows: ServedRow[];
67
- servedBlock: string;
68
- unservedKind: "boundary" | "interior";
69
- firstOffendingLine?: number;
70
- });
71
- }
72
56
  export declare class AnchorMismatchError extends DomainError<DomainErrorCode> {
73
57
  constructor(code: "E_STALE_ANCHOR" | "E_SUSPICIOUS_TEXT", payload: ErrorPayloadMap[typeof code]);
74
58
  }
@@ -87,112 +71,6 @@ export declare function findEditHashEcho(replacementLines: string[], served: rea
87
71
  export declare class EditHashEchoError extends AnchorMismatchError {
88
72
  constructor(payload: ErrorPayloadMap["E_SUSPICIOUS_TEXT"]);
89
73
  }
90
- export declare function buildRangeEcho(startLine: number, endLine: number, fileHashes: string[]): ServedRow[];
91
- export declare function fmtServedRows(rows: ServedRow[], fileLines: string[]): string;
92
- /**
93
- * SAFETY: the read-only identity seam the edit path resolves a served anchor through (CP2-r1,
94
- * obligation (c)). Production wires it to `served_leases` + `line_lineage`; tests inject plain
95
- * maps. Nothing here writes: the authoritative `retired_at` writer is materialization.
96
- */
97
- export interface LeaseIdentityView {
98
- lineId: number;
99
- servedLineNumber: number;
100
- servedSnapshotHash: string;
101
- retiredAt: number | null;
102
- }
103
- /**
104
- * The lease source a served span is verified against when identity is available.
105
- * `leaseFor` is a per-anchor lookup; `rebasedLineOf` answers where a leased `line_id` lives in the
106
- * buffer being edited (the store's `positionsByIdentity`).
107
- */
108
- export interface LeaseSpanSource {
109
- leaseFor(anchor: string): LeaseIdentityView | undefined;
110
- rebasedLineOf(lineId: number): number | undefined;
111
- /**
112
- * Other files this session served one anchor for, excluding the file being edited.
113
- * Backed by the store's `(session_id, anchor)` lookup; it runs on the failure path only,
114
- * so the happy path pays nothing (upstream b92e0ec:src/hashline/resolve.ts:41-49).
115
- */
116
- anchorHomes(anchor: string): string[];
117
- }
118
- /**
119
- * The served-evidence route: which evidence owns verification of a served span. Constructed
120
- * EXACTLY ONCE per `verifyServedRange` call from the opt-in `leaseSource` seam, so the
121
- * leased/mirror conjunction — boundary interception, never-served interior scan, identity-gate
122
- * route, position-check null handling, and the gate's interior-hole rule — is one value's
123
- * decisions instead of five comment-enforced presence-tests.
124
- *
125
- * The union answers exactly three questions (below): `owesInteriorScan`, `acceptsInteriorHole`
126
- * and `checksPosition`. The `kind` discriminator itself routes the boundary interception and
127
- * the identity gate (obligation (c)).
128
- */
129
- export type ServedEvidenceRoute = {
130
- kind: "leased";
131
- source: LeaseSpanSource;
132
- } | {
133
- kind: "mirror";
134
- };
135
- /**
136
- * The identity gate for a served span (obligation (c)) — replaces the unconditional position check
137
- * when a lease source is present.
138
- *
139
- * A **benign shift** — the intended line's bytes are unchanged and only its position moved (exterior
140
- * drift above the served span) — passes: the served anchor's live lease resolves to the rebased
141
- * coordinate the edit targets, so the edit applies there with no re-read. A **look-alike rebind** —
142
- * the named line was deleted and a different line now holds the same bytes — rejects: the leased
143
- * `line_id` no longer lives at the rebased coordinate, or is gone from the buffer's identity map
144
- * entirely, so the anchor cannot be reconciled with the line it named.
145
- *
146
- * Fail-closed arms, all `E_STALE_RANGE` with the echo rows: a window length that changed because
147
- * an external insert/delete landed strictly inside the span, a truncated mirror slot (no served row
148
- * left to reconcile), a never-served boundary row (the named anchor itself, unverifiable without a
149
- * served row), an unleased served row (a serve predating lease granting), a retired lease, or a
150
- * coordinate no leased identity occupies. An interior mirror row the span never served (`null`) is
151
- * accepted (upstream ADR-0024 decision 1, adopted; supersedes ADR-0019's decline): it carries no
152
- * identity to verify and the two boundary leases plus the window-length check pin the span's extent.
153
- * Throwing happens before any write, so a rejection leaves the file byte-identical.
154
- */
155
- export declare function verifyRebasedSpan(args: {
156
- served: (string | null)[];
157
- servedStart: number;
158
- servedEnd: number;
159
- rebasedStart: number;
160
- rebasedEnd: number;
161
- /** The leased evidence route — this gate is what the leased kind owns. */
162
- route: Extract<ServedEvidenceRoute, {
163
- kind: "leased";
164
- }>;
165
- echo: string;
166
- echoRows: ServedRow[];
167
- where: string;
168
- }): void;
169
- export declare function verifyServedRange(args: {
170
- served: (string | null)[];
171
- startHash: string;
172
- endHash: string;
173
- startLine: number;
174
- endLine: number;
175
- fileHashes: string[];
176
- fileLines: string[];
177
- filePath?: string;
178
- servedCanons?: (string | null)[];
179
- retired?: ReadonlySet<string>;
180
- /**
181
- * Present => the leased evidence route (identity gate `verifyRebasedSpan` replaces the position
182
- * check below, obligation (c)); absent => the mirror route with its unconditional position
183
- * check. Identity only, never a weaker position check. Turns into the single
184
- * `ServedEvidenceRoute` value at the top of the body — the rest of the function never
185
- * presence-tests this argument.
186
- */
187
- leaseSource?: LeaseSpanSource;
188
- }): void;
189
- export interface ResolvedRange {
190
- startLine: number;
191
- endLine: number;
192
- startHash: string;
193
- endHash: string;
194
- delta: number;
195
- }
196
74
  type LIdx = {
197
75
  fileLines: string[];
198
76
  lineStarts: number[];
@@ -22,6 +22,46 @@ export declare class AnchorSpaceExhaustedError extends DomainError<"E_LARGE_FILE
22
22
  readonly servedCount: number;
23
23
  constructor(retiredCount: number, servedCount: number);
24
24
  }
25
+ /**
26
+ * The ONE anchor-space-exhaustion test, owned by the error's own module: "is this
27
+ * exhaustion?" (a typing question).
28
+ *
29
+ * WHY single: the classification lives beside the error it classifies, and no site keeps a private
30
+ * copy — the two translate blocks below ask exactly this question, and the promotion sites ask its
31
+ * strict subset (`isPromotableAnchorSpaceExhaustion`). Each of the five sites used to carry its own
32
+ * copy (or an inline variant) of the test; a rewording of the allocator's probe message in one copy
33
+ * would silently change a decision at the others, and the failure mode is a raw `Error` reaching
34
+ * the model instead of the typed refusal.
35
+ *
36
+ * Members: the typed `AnchorSpaceExhaustedError` (already translated), the allocator wording
37
+ * `nextZeroBit` raises when the probe wraps the whole space ("probing failed over"), and that
38
+ * same refusal's formatted headline ("Cannot allocate a unique hash anchor", which survives a
39
+ * re-wrap that costs the error its class).
40
+ */
41
+ export declare function isAnchorSpaceExhaustion(e: unknown): boolean;
42
+ /**
43
+ * Promotion's narrower question: is this an exhaustion that clearing retired anchors and
44
+ * retrying could actually cure?
45
+ *
46
+ * WHY a second predicate, not the one above: `isAnchorSpaceExhaustion` answers "is this
47
+ * exhaustion" — a typing question, asked by the two translate blocks that must turn any
48
+ * allocator wording into the typed `E_LARGE_FILE`. Promotion asks a different question, and the
49
+ * two answers differ on every refusal whose subject is the file's line count rather than the
50
+ * anchor space: exhaustion and the line cap are the same diagnosis (a file too long to hash),
51
+ * but promotion cannot out-grow the line cap, because the retry re-reads the same oversized file
52
+ * and throws the identical error — with this `(session, path)`'s retired anchors now cleared, so
53
+ * the failed read has also degraded its own stale-anchor checks. "Can promotion help?" is
54
+ * therefore the strict subset: the probe wrapping the whole space.
55
+ *
56
+ * The line cap is a capacity refusal, never an identity one, and its wording is not the hash-space
57
+ * one: `eLargeFileMsg` formats with `limitKind: "lines"` ("<path> has N lines, exceeding the
58
+ * N-line limit"), so `isAnchorSpaceExhaustion` already declines it; "Cannot allocate a unique hash
59
+ * anchor" is `AnchorSpaceExhaustedError`'s own headline, reachable as message-only text on a
60
+ * re-wrap. Declining both keeps promotion off every refusal a retry cannot out-grow, and leaves
61
+ * the line cap free to be re-formatted through the hash-space wording without promotion silently
62
+ * becoming a hazard-clear.
63
+ */
64
+ export declare function isPromotableAnchorSpaceExhaustion(e: unknown): boolean;
25
65
  export declare function idxToHash(idx: number): string;
26
66
  export declare function hashAt(idx: number): string;
27
67
  export declare const HL_PREFIX_PLUS_RE: RegExp;
@@ -5,9 +5,11 @@
5
5
  */
6
6
  export { CANON_VERSION, ANCHOR_LEN, HASH_SEP, HASH_SPACE, HASH_PROBE_STRIDE, MAX_HASH_LINES, HASH_LEN, HASH_CLASS, HASH_RE, ALPH_RE, HL_PREFIX_PLUS_RE, HL_PREFIX_MINUS_RE, HL_BARE_PREFIX_RE, canon, lineHashesPure, mapStableHashes, initHasher, contentChecksum, } from "./hash-assign.js";
7
7
  export { lineHashes } from "./hash.js";
8
- export { parseHashRef, parseText } from "./parse.js";
9
- export type { Anchor } from "./parse.js";
8
+ export { parseHashRef, parseText } from "./anchor-pipeline.js";
9
+ export type { Anchor } from "./anchor-pipeline.js";
10
10
  export { resEdit } from "./anchor-pipeline.js";
11
11
  export type { HEdit, HTEdit, NEdit } from "./anchor-pipeline.js";
12
- export { applyEdit, fmtRegion, changedRange, buildIdx, ServedRejectionError, AnchorMismatchError, EditHashEchoError, findEditHashEcho, isAnchorMismatch, verifyServedRange, verifyRebasedSpan, buildRangeEcho, fmtServedRows, } from "./anchor-pipeline.js";
13
- export type { ServedRow, ResolvedRange, LeaseSpanSource, LeaseIdentityView, } from "./anchor-pipeline.js";
12
+ export { applyEdit, fmtRegion, changedRange, buildIdx, AnchorMismatchError, EditHashEchoError, findEditHashEcho, isAnchorMismatch, } from "./anchor-pipeline.js";
13
+ export type { ServedRow } from "./anchor-pipeline.js";
14
+ export { ServedRejectionError, verifyServedRange, verifyRebasedSpan, buildRangeEcho, fmtServedRows, moreRowsHint, } from "./served-evidence.js";
15
+ export type { ResolvedRange, LeaseSpanSource, LeaseIdentityView } from "./served-evidence.js";
@@ -0,0 +1,152 @@
1
+ /**
2
+ * ServedEvidence — deep module owning what a served range can still prove.
3
+ *
4
+ * One entry point: `verifyServedRange` decides whether the anchor pair an edit
5
+ * names is still grounded in the evidence this session was served, and rejects
6
+ * with the echoed window when it is not. Every other decision here is private to
7
+ * that call — the `ServedEvidenceRoute` union answers its three route questions
8
+ * (`owesInteriorScan`, `acceptsInteriorHole`, `checksPosition`), the leased
9
+ * route's boundary interception loses identity before any content question is
10
+ * asked, and `throwUnknownOrForeign` refuses anchors the lease seam cannot place.
11
+ *
12
+ * `verifyRebasedSpan` is exported because two cells pin the leased route directly;
13
+ * it is not a second entry point. `buildRangeEcho`/`fmtServedRows`/`moreRowsHint`
14
+ * render the echo, and `ResolvedRange` is the shape both sides of the edit path
15
+ * carry, so neither side has to import the other.
16
+ *
17
+ * WHY here: the verifier is read-side evidence, but the write path calls it. Kept
18
+ * in anchor-pipeline it closed a cycle through the served mirror and the request
19
+ * contract; as a leaf (domain registry, hash-assign, constants) it closes none.
20
+ *
21
+ * @module dsh-better-edit/hashline/served-evidence
22
+ */
23
+ import { DomainError } from "../domain-errors.js";
24
+ import type { DomainErrorCode, RangeCause, ServedRow } from "../domain-errors.js";
25
+ export type ServedCode = "E_STALE_RANGE" | "E_UNSERVED_RANGE";
26
+ export declare class ServedRejectionError extends DomainError<DomainErrorCode> {
27
+ readonly code: ServedCode;
28
+ readonly unservedKind: "boundary" | "interior" | undefined;
29
+ constructor(opts: {
30
+ code: "E_STALE_RANGE";
31
+ headline: string;
32
+ servedRows: ServedRow[];
33
+ servedBlock: string;
34
+ cause?: RangeCause;
35
+ firstOffendingLine?: number;
36
+ } | {
37
+ code: "E_UNSERVED_RANGE";
38
+ headline: string;
39
+ servedRows: ServedRow[];
40
+ servedBlock: string;
41
+ unservedKind: "boundary" | "interior";
42
+ firstOffendingLine?: number;
43
+ });
44
+ }
45
+ export declare function servedPositionsOf(served: (string | null)[], hash: string): number[];
46
+ export declare function buildRangeEcho(startLine: number, endLine: number, fileHashes: string[]): ServedRow[];
47
+ export declare function fmtServedRows(rows: ServedRow[], fileLines: string[]): string;
48
+ export declare function moreRowsHint(count: number, tail: string): string;
49
+ /**
50
+ * SAFETY: the read-only identity seam the edit path resolves a served anchor through (CP2-r1,
51
+ * obligation (c)). Production wires it to `served_leases` + `line_lineage`; tests inject plain
52
+ * maps. Nothing here writes: the authoritative `retired_at` writer is materialization.
53
+ */
54
+ export interface LeaseIdentityView {
55
+ lineId: number;
56
+ servedLineNumber: number;
57
+ servedSnapshotHash: string;
58
+ retiredAt: number | null;
59
+ }
60
+ /**
61
+ * The lease source a served span is verified against when identity is available.
62
+ * `leaseFor` is a per-anchor lookup; `rebasedLineOf` answers where a leased `line_id` lives in the
63
+ * buffer being edited (the store's `positionsByIdentity`).
64
+ */
65
+ export interface LeaseSpanSource {
66
+ leaseFor(anchor: string): LeaseIdentityView | undefined;
67
+ rebasedLineOf(lineId: number): number | undefined;
68
+ /**
69
+ * Other files this session served one anchor for, excluding the file being edited.
70
+ * Backed by the store's `(session_id, anchor)` lookup; it runs on the failure path only,
71
+ * so the happy path pays nothing (upstream b92e0ec:src/hashline/resolve.ts:41-49).
72
+ */
73
+ anchorHomes(anchor: string): string[];
74
+ }
75
+ /**
76
+ * The served-evidence route: which evidence owns verification of a served span. Constructed
77
+ * EXACTLY ONCE per `verifyServedRange` call from the opt-in `leaseSource` seam, so the
78
+ * leased/mirror conjunction — boundary interception, never-served interior scan, identity-gate
79
+ * route, position-check null handling, and the gate's interior-hole rule — is one value's
80
+ * decisions instead of five comment-enforced presence-tests.
81
+ *
82
+ * The union answers exactly three questions (below): `owesInteriorScan`, `acceptsInteriorHole`
83
+ * and `checksPosition`. The `kind` discriminator itself routes the boundary interception and
84
+ * the identity gate (obligation (c)).
85
+ */
86
+ export type ServedEvidenceRoute = {
87
+ kind: "leased";
88
+ source: LeaseSpanSource;
89
+ } | {
90
+ kind: "mirror";
91
+ };
92
+ /**
93
+ * The identity gate for a served span (obligation (c)) — replaces the unconditional position check
94
+ * when a lease source is present.
95
+ *
96
+ * A **benign shift** — the intended line's bytes are unchanged and only its position moved (exterior
97
+ * drift above the served span) — passes: the served anchor's live lease resolves to the rebased
98
+ * coordinate the edit targets, so the edit applies there with no re-read. A **look-alike rebind** —
99
+ * the named line was deleted and a different line now holds the same bytes — rejects: the leased
100
+ * `line_id` no longer lives at the rebased coordinate, or is gone from the buffer's identity map
101
+ * entirely, so the anchor cannot be reconciled with the line it named.
102
+ *
103
+ * Fail-closed arms, all `E_STALE_RANGE` with the echo rows: a window length that changed because
104
+ * an external insert/delete landed strictly inside the span, a truncated mirror slot (no served row
105
+ * left to reconcile), a never-served boundary row (the named anchor itself, unverifiable without a
106
+ * served row), an unleased served row (a serve predating lease granting), a retired lease, or a
107
+ * coordinate no leased identity occupies. An interior mirror row the span never served (`null`) is
108
+ * accepted (upstream ADR-0024 decision 1, adopted; supersedes ADR-0019's decline): it carries no
109
+ * identity to verify and the two boundary leases plus the window-length check pin the span's extent.
110
+ * Throwing happens before any write, so a rejection leaves the file byte-identical.
111
+ */
112
+ export declare function verifyRebasedSpan(args: {
113
+ served: (string | null)[];
114
+ servedStart: number;
115
+ servedEnd: number;
116
+ rebasedStart: number;
117
+ rebasedEnd: number;
118
+ /** The leased evidence route — this gate is what the leased kind owns. */
119
+ route: Extract<ServedEvidenceRoute, {
120
+ kind: "leased";
121
+ }>;
122
+ echo: string;
123
+ echoRows: ServedRow[];
124
+ where: string;
125
+ }): void;
126
+ export declare function verifyServedRange(args: {
127
+ served: (string | null)[];
128
+ startHash: string;
129
+ endHash: string;
130
+ startLine: number;
131
+ endLine: number;
132
+ fileHashes: string[];
133
+ fileLines: string[];
134
+ filePath?: string;
135
+ servedCanons?: (string | null)[];
136
+ retired?: ReadonlySet<string>;
137
+ /**
138
+ * Present => the leased evidence route (identity gate `verifyRebasedSpan` replaces the position
139
+ * check below, obligation (c)); absent => the mirror route with its unconditional position
140
+ * check. Identity only, never a weaker position check. Turns into the single
141
+ * `ServedEvidenceRoute` value at the top of the body — the rest of the function never
142
+ * presence-tests this argument.
143
+ */
144
+ leaseSource?: LeaseSpanSource;
145
+ }): void;
146
+ export interface ResolvedRange {
147
+ startLine: number;
148
+ endLine: number;
149
+ startHash: string;
150
+ endHash: string;
151
+ delta: number;
152
+ }
@@ -14,8 +14,10 @@
14
14
  import type { FileIO } from "../fs-bridge.js";
15
15
  import { type HashStore } from "../hash-store.js";
16
16
  import type { LineEnding } from "../edit-diff.js";
17
- import { type HEdit, type NEdit, type LeaseSpanSource } from "../hashline/anchor-pipeline.js";
18
- import { type ResolvedRange, type ServedRow } from "../hashline/anchor-pipeline.js";
17
+ import { type HEdit, type NEdit } from "../hashline/anchor-pipeline.js";
18
+ import type { LeaseSpanSource } from "../hashline/served-evidence.js";
19
+ import type { ResolvedRange } from "../hashline/served-evidence.js";
20
+ import type { ServedRow } from "../hashline/anchor-pipeline.js";
19
21
  import type { EditMode } from "../contract.js";
20
22
  export interface PreparedItem {
21
23
  index: number;
@@ -24,7 +26,6 @@ export interface PreparedItem {
24
26
  anchor_from: string;
25
27
  anchor_to: string;
26
28
  replace_with: string;
27
- fileWarning?: string;
28
29
  /** Request-level edit mode ("general" default, "literal" bypasses served-echo). */
29
30
  mode?: EditMode;
30
31
  }
@@ -51,15 +52,6 @@ export interface FileEditResult {
51
52
  newlyRetired: string[];
52
53
  range: ResolvedRange;
53
54
  }
54
- /**
55
- * Resolve a request's missing `path` from its anchors: the only file whose
56
- * stored hashes contain both anchors. Returns the path plus an autocorrect
57
- * warning, or undefined when no resolution is possible.
58
- */
59
- export declare function resolveMissingPath(request: Record<string, unknown>): Promise<{
60
- path: string;
61
- warning: string;
62
- } | undefined>;
63
55
  /** The hashes a range edit removes, for stable re-hash bookkeeping. */
64
56
  export declare function collectRemovedHashes(edit: HEdit, originalHashes: string[]): Set<string>;
65
57
  /** Added/removed line counts for one resolved edit against a file's original hashes. */
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * Mutation — deep module owning the full file mutation lifecycle.
3
3
  *
4
- * Previously fragmented: tool-edit → edit-pipeline → edit-engine.applyOne →
5
- * edit-response/diff/drift, and tool-batch-edit → edit-engine.runFileEdits
4
+ * Previously fragmented: tool-edit → edit-pipeline → engine.applyOne →
5
+ * edit-response/diff/drift, and tool-batch-edit → engine.runFileEdits
6
6
  * (loop + unionRange + counters) → persistUndoAndWrite with a boolean flag.
7
7
  * Warnings, hadUtf8DecodeErrors, firstChangedLine, driftNotice were threaded
8
8
  * by mutation across 5 hops; bugs hid in wiring, not pure helpers.
@@ -13,13 +13,12 @@
13
13
  *
14
14
  * Public surface:
15
15
  * execute(io, items, {sessionKey, exec, sandbox, signal}) → string — deep seam: ONE interface
16
- * applySequence(io, items, ctx) → FileEditResult — per-file sequencer
17
- * commit(io, files, {exec, sandboxPolicy, signal}) → void — transaction
16
+ * persistUndoAndWrite(opts) → void — transaction (exported for tests)
18
17
  *
19
18
  * Depth: small interface (execute) with large implementation — locality and leverage.
20
19
  *
21
- * Internals (private): verifyServedRange, resToSpan, assemble, scanDrift,
22
- * boundaryDups, noopGuard. Tested via FileEditResult, not via split e2e.
20
+ * Internals (private): verifyServedRange, resToSpan, assemble, boundaryDups,
21
+ * noopGuard. Tested via FileEditResult, not via split e2e.
23
22
  *
24
23
  * @module dsh-better-edit/mutation
25
24
  */
@@ -28,27 +27,7 @@ import type { ToolExecution } from "@deepseek-ai/dsh-tools";
28
27
  import type { SandboxExecutionPolicy } from "@deepseek-ai/dsh-sandbox";
29
28
  import type { FsSandboxController } from "./sandbox.js";
30
29
  import type { LineEnding } from "./edit-diff.js";
31
- import { scanDrift } from "./session-view.js";
32
- import { runFileEdits, resolveMissingPath } from "./mutation/engine.js";
33
- import type { FileEditResult, PreparedItem } from "./mutation/engine.js";
34
- import { restoreEndings } from "./edit-diff.js";
35
- import { buildMetrics, buildNoop, buildChanged, buildBatchResult } from "./edit-response.js";
36
- import type { RMeta, BatchSection } from "./edit-response.js";
37
- import { genDiff, toLF, stripBOM } from "./edit-diff.js";
38
- import { computeDrift } from "./session-view.js";
39
- import { trackNoopPayload, clearNoopLoop, noopPayloadKey } from "./noop-guard.js";
40
- /** Resolve the display path a caller names against the session cwd. */
41
- export declare function resolveDisplayPath(path: string, cwd: string): string;
42
- /** Snapshot bookkeeping for noop/success results (best-effort). */
43
- export declare function snapshotIdFor(io: FileIO, absolutePath: string, signal?: AbortSignal): Promise<string | undefined>;
44
- export { runFileEdits, resolveMissingPath };
45
- export { persistUndoAndWrite };
46
- export type { FileEditResult, PreparedItem };
47
- export { buildMetrics, buildNoop, buildChanged, buildBatchResult };
48
- export type { RMeta, BatchSection };
49
- export { genDiff, restoreEndings, toLF, stripBOM };
50
- export { computeDrift, scanDrift };
51
- export { trackNoopPayload, clearNoopLoop, noopPayloadKey };
30
+ import type { PreparedItem } from "./mutation/engine.js";
52
31
  interface UndoWriteFile {
53
32
  absolutePath: string;
54
33
  displayPath: string;
@@ -66,18 +45,15 @@ interface PersistWriteOptions {
66
45
  sandboxPolicy: SandboxExecutionPolicy | undefined;
67
46
  signal?: AbortSignal;
68
47
  undoUnavailableMessage: (displayPath: string) => string;
69
- restoreUnwrittenUndos: boolean;
70
48
  }
71
- declare function persistUndoAndWrite(opts: PersistWriteOptions): Promise<void>;
72
- declare function commitSingle(opts: Omit<PersistWriteOptions, "restoreUnwrittenUndos">): Promise<void>;
73
- declare function commitBatch(opts: Omit<PersistWriteOptions, "restoreUnwrittenUndos">): Promise<void>;
49
+ export declare function persistUndoAndWrite(opts: PersistWriteOptions): Promise<void>;
74
50
  /**
75
51
  * Deep seam: execute the full mutation lifecycle.
76
52
  *
77
- * Owns: applySequence → branch (single/multi × noop/applied) → commit →
53
+ * Owns: runFileEdits → branch (single/multi × noop/applied) → commit →
78
54
  * buildBatchResult → recordServedTruncated → return text.
79
55
  *
80
- * The tool layer (adapter) only validates and resolves the nullable path; all
56
+ * The tool layer (adapter) only validates and delegates; all
81
57
  * lifecycle branching concentrates here (locality). One interface serves N
82
58
  * call sites (leverage). Deleting this module would scatter the lifecycle
83
59
  * across every tool — it concentrates (deep).
@@ -91,28 +67,4 @@ export declare function execute(opts: {
91
67
  sandbox: FsSandboxController;
92
68
  sandboxPolicy: SandboxExecutionPolicy | undefined;
93
69
  }): Promise<string>;
94
- /** Apply a per-file sequence (batch's group) — owns the loop + unionRange + counters. */
95
- export declare function applySequence(io: FileIO, items: PreparedItem[], ctx: {
96
- sessionKey: string;
97
- signal?: AbortSignal;
98
- }): Promise<FileEditResult>;
99
- /** Commit the transaction — owns persist-undo → write → restore. */
100
- export declare function commit(opts: {
101
- io: FileIO;
102
- files: Array<{
103
- absolutePath: string;
104
- displayPath: string;
105
- originalNormalized: string;
106
- bom: string;
107
- originalEnding: import("./edit-diff.js").LineEnding;
108
- originalHashes: string[];
109
- result: string;
110
- }>;
111
- exec: ToolExecution;
112
- sandbox: FsSandboxController;
113
- sandboxPolicy: SandboxExecutionPolicy | undefined;
114
- signal?: AbortSignal;
115
- undoUnavailableMessage: (displayPath: string) => string;
116
- restoreUnwrittenUndos?: boolean;
117
- }): Promise<void>;
118
- export { commitSingle, commitBatch };
70
+ export {};
@@ -1,34 +1,3 @@
1
- import { NOOP_LOOP_THRESHOLD } from "./constants.js";
2
1
  export declare function noopPayloadKey(absolutePath: string, anchorFrom: string, anchorTo: string, replaceWith: string): string;
3
- export declare function trackNoopPayload(absolutePath: string, payload: string): number;
4
- export declare function clearNoopLoop(absolutePath: string): void;
5
- export { NOOP_LOOP_THRESHOLD };
6
- export interface NoopPolicyInput {
7
- absolutePath: string;
8
- anchorFrom: string;
9
- anchorTo: string;
10
- replaceWith: string;
11
- ref: string;
12
- batch: boolean;
13
- range: {
14
- startLine: number;
15
- endLine: number;
16
- };
17
- hashes: string[];
18
- lines: string[];
19
- sessionKey: string;
20
- }
21
- export type NoopPolicyOutcome = {
22
- action: "proceed";
23
- count: number;
24
- } | {
25
- action: "warn";
26
- count: number;
27
- notice: string;
28
- } | {
29
- action: "reject";
30
- count: number;
31
- message: string;
32
- };
33
- export declare function runNoopPolicySync(input: NoopPolicyInput, count: number): NoopPolicyOutcome;
34
- export declare function runNoopPolicy(input: NoopPolicyInput): Promise<NoopPolicyOutcome>;
2
+ export declare function trackNoopPayload(sessionKey: string, absolutePath: string, payload: string): number;
3
+ export declare function clearNoopLoop(sessionKey: string, absolutePath: string): void;
@@ -1,4 +1,3 @@
1
- export * from "./store/index.js";
2
1
  export { canonicalAsync as resolveTarget } from "./canonical-path.js";
3
2
  export { canonicalSync } from "./canonical-path.js";
4
3
  export declare function toCwd(filePath: string, cwd: string): string;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Preset tool-policy gate: which hashline-owned tools one agent install may
3
+ * register. The registry cannot enforce a preset's policy for this plugin —
4
+ * scope restrictions filter only *inherited* tools, never a scope's own
5
+ * registrations (Rianico/dsh-better-edit#110) — so the install consults the
6
+ * composed preset's own layer instead.
7
+ *
8
+ * `read` is unconditional: it is the plugin's core capability and the source of
9
+ * every anchor. Every mutating tool is installed only when the preset's layer
10
+ * resolves the matching tool, which keeps `edit` paired with `read` and never
11
+ * shadows a tool the preset did not compose.
12
+ *
13
+ * The probe is an optional-service seam: no `agentPresets` service, no composed
14
+ * preset (preset-free composition), or no scope-read API (`acquireScope` on
15
+ * 0.2.x, `standingKeyFor` on older registries) keeps today's unconditional
16
+ * install, so a host that predates 0.2.1 keeps its pre-gate behavior.
17
+ * @module dsh-better-edit/preset-toolset
18
+ */
19
+ import type { Context } from "@deepseek-ai/cordis";
20
+ /** The hashline-owned tools one install may register. `read` is always installed. */
21
+ export interface HashlineToolset {
22
+ /** The hashline `edit` (also gates `undo`). */
23
+ edit: boolean;
24
+ /** The governed `str_replace_editor` shadow (ADR-0015). */
25
+ strReplaceEditor: boolean;
26
+ /** `undo_last_edit` — follows {@link HashlineToolset.edit}, see {@link toolsetFor}. */
27
+ undo: boolean;
28
+ /** A preset that neither resolves `write` nor composed one needs no guard. */
29
+ writeHook: boolean;
30
+ }
31
+ /** Today's install — the fallback for every composition the gate cannot read. */
32
+ export declare const UNCONDITIONAL_TOOLSET: HashlineToolset;
33
+ /**
34
+ * Derive the toolset from one predicate over preset tool names. `undo` follows
35
+ * `edit` because `undo_last_edit` reverts only hashline edits: installing it
36
+ * beside no `edit` would advertise a history that can never exist.
37
+ */
38
+ export declare function toolsetFor(resolves: (name: string) => boolean): HashlineToolset;
39
+ /**
40
+ * Keep only the guidance sections whose tool was installed. `tool:read` always
41
+ * stays; the edit and undo sections follow their tools so the prompt never
42
+ * advertises a catalog entry the agent does not have.
43
+ */
44
+ export declare function sectionsForToolset<T extends {
45
+ name: string;
46
+ }>(sections: readonly T[], toolset: HashlineToolset): T[];
47
+ /** The host surface the probe touches; `logger` is optional so a bare host works. */
48
+ export interface PresetProbeHost {
49
+ get(service: string): object | undefined;
50
+ logger?: {
51
+ warn(message: string): void;
52
+ };
53
+ }
54
+ /**
55
+ * Resolve the toolset for one agent from its composed preset. Every failure —
56
+ * a missing service, an unreadable preset, a rejected scope read, or a throwing
57
+ * registry — falls back to {@link UNCONDITIONAL_TOOLSET} (and warns), never to a
58
+ * smaller set: the gate may only ever remove a tool it has positively seen the
59
+ * preset decline.
60
+ */
61
+ export declare function resolveToolset(host: PresetProbeHost, agentCtx: Context): Promise<HashlineToolset>;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Shared tool reclamation utility for DSH scoped layers.
3
+ * Used by installAgentTools and createSelfHealWatcher.
4
+ * @module dsh-better-edit/reclaim
5
+ */
6
+ export interface ScopedToolLayer {
7
+ get?: (name: string) => unknown;
8
+ data?: Map<string, unknown>;
9
+ }
10
+ export interface LoggerChannel {
11
+ warn(msg: string): void;
12
+ error?(msg: string): void;
13
+ }
14
+ /**
15
+ * Resolve the agent's scoped tool layer from the DSH tools service.
16
+ */
17
+ export declare function getAgentScopedToolLayer(toolsSvc: unknown, agent: unknown): ScopedToolLayer | undefined;
18
+ /**
19
+ * Reclaim an entry by deleting it from the scoped layer's data map.
20
+ */
21
+ export declare function reclaimToolEntry(layer: ScopedToolLayer | undefined, name: string): boolean;
22
+ /**
23
+ * Register a tool with collision detection, guarded reclaim, and single retry.
24
+ */
25
+ export declare function registerWithReclaim(options: {
26
+ toolsSvc: unknown;
27
+ agent: unknown;
28
+ agentCtx: {
29
+ tools: {
30
+ register(def: unknown): () => void;
31
+ };
32
+ };
33
+ name: string;
34
+ def: unknown;
35
+ logger?: LoggerChannel;
36
+ }): (() => void) | undefined;