dsh-better-edit 0.8.2 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/CHANGELOG.md +158 -99
  2. package/README.md +2 -2
  3. package/README.zh.md +3 -3
  4. package/cordis.patch.yml +1 -1
  5. package/lib/constants.js +19 -4
  6. package/lib/contract.js +136 -79
  7. package/lib/domain-errors.js +570 -0
  8. package/lib/edit-diff.js +33 -7
  9. package/lib/file-encoding-state.js +27 -7
  10. package/lib/file-view.js +305 -82
  11. package/lib/fs-bridge.js +23 -7
  12. package/lib/hash-store.js +404 -278
  13. package/lib/hashline/anchor-pipeline.js +586 -378
  14. package/lib/hashline/hash-assign.js +21 -22
  15. package/lib/hashline/hash.js +6 -6
  16. package/lib/hashline/index.js +1 -1
  17. package/lib/hashline/resolve.js +1 -1
  18. package/lib/hashline/served-guard.js +181 -0
  19. package/lib/index.js +1 -1
  20. package/lib/mutation/engine.js +392 -96
  21. package/lib/mutation.js +22 -130
  22. package/lib/noop-guard.js +20 -9
  23. package/lib/prompts.js +20 -18
  24. package/lib/read-and-serve.js +44 -20
  25. package/lib/sandbox.js +1 -1
  26. package/lib/session-view.js +57 -43
  27. package/lib/snapshot-store/index.js +97 -0
  28. package/lib/snapshot-store/lineage-store.js +400 -0
  29. package/lib/snapshot-store/migrate.js +80 -0
  30. package/lib/snapshot-store/pairing.js +412 -0
  31. package/lib/snapshot-store/txn.js +63 -0
  32. package/lib/snapshot-store/vacuum.js +243 -0
  33. package/lib/store-lifecycle.js +13 -1
  34. package/lib/store-retry.js +34 -0
  35. package/lib/tool-edit.js +90 -44
  36. package/lib/tool-read.js +29 -1
  37. package/lib/tool-str-replace-editor.js +26 -18
  38. package/lib/tool-undo.js +25 -8
  39. package/lib/types/constants.d.ts +5 -2
  40. package/lib/types/contract.d.ts +76 -71
  41. package/lib/types/domain-errors.d.ts +410 -0
  42. package/lib/types/edit-response.d.ts +1 -1
  43. package/lib/types/file-encoding-state.d.ts +1 -0
  44. package/lib/types/file-view.d.ts +35 -6
  45. package/lib/types/hash-store.d.ts +38 -19
  46. package/lib/types/hashline/anchor-pipeline.d.ts +117 -36
  47. package/lib/types/hashline/hash-assign.d.ts +5 -5
  48. package/lib/types/hashline/hash.d.ts +1 -1
  49. package/lib/types/hashline/index.d.ts +2 -2
  50. package/lib/types/hashline/served-guard.d.ts +100 -0
  51. package/lib/types/index.d.ts +2 -2
  52. package/lib/types/mutation/engine.d.ts +49 -30
  53. package/lib/types/mutation.d.ts +1 -39
  54. package/lib/types/noop-guard.d.ts +4 -4
  55. package/lib/types/prompts.d.ts +1 -1
  56. package/lib/types/read-and-serve.d.ts +6 -0
  57. package/lib/types/sandbox.d.ts +1 -1
  58. package/lib/types/session-view.d.ts +38 -9
  59. package/lib/types/snapshot-store/index.d.ts +28 -0
  60. package/lib/types/snapshot-store/lineage-store.d.ts +96 -0
  61. package/lib/types/snapshot-store/migrate.d.ts +16 -0
  62. package/lib/types/snapshot-store/pairing.d.ts +99 -0
  63. package/lib/types/snapshot-store/txn.d.ts +12 -0
  64. package/lib/types/snapshot-store/vacuum.d.ts +79 -0
  65. package/lib/types/store-lifecycle.d.ts +0 -1
  66. package/lib/types/store-retry.d.ts +6 -0
  67. package/lib/types/tool-edit.d.ts +2 -2
  68. package/lib/types/tool-str-replace-editor.d.ts +2 -2
  69. package/lib/types/utils.d.ts +5 -6
  70. package/lib/types/workspace-context.d.ts +0 -1
  71. package/lib/undo-edit.js +27 -11
  72. package/lib/utils.js +12 -12
  73. package/lib/workspace-context.js +4 -8
  74. package/lib/write-hook.js +13 -4
  75. package/package.json +9 -10
@@ -16,7 +16,9 @@
16
16
  *
17
17
  * @module dsh-better-edit/hashline/anchor-pipeline
18
18
  */
19
- import { CodedError } from "../utils.js";
19
+ import { DomainError } from "../domain-errors.js";
20
+ import type { ErrorPayloadMap, ServedRow, DomainErrorCode, RangeCause } from "../domain-errors.js";
21
+ import type { EditMode } from "../contract.js";
20
22
  export type Anchor = {
21
23
  hash: string;
22
24
  };
@@ -41,54 +43,129 @@ export interface NEdit {
41
43
  currentContent: string;
42
44
  }
43
45
  export type HTEdit = {
44
- replacement_text: string;
45
- remove_from: string;
46
- remove_to: string;
46
+ replace_with: string;
47
+ anchor_from: string;
48
+ anchor_to: string;
47
49
  };
48
50
  export declare function resEdit(edit: HTEdit, _warnings?: string[]): HEdit;
49
- declare function warnUnicodeEsc(edit: HEdit, warnings: string[]): void;
50
- export declare function findNewEdge(): undefined;
51
- export { warnUnicodeEsc };
52
51
  export type ServedCode = "E_STALE_RANGE" | "E_UNSERVED_RANGE";
53
- export interface ServedRow {
54
- position: number;
55
- hash: string;
56
- }
57
- export declare class ServedRejectionError extends CodedError {
52
+ export type { ServedRow, RangeCause } from "../domain-errors.js";
53
+ export declare class ServedRejectionError extends DomainError<DomainErrorCode> {
58
54
  readonly code: ServedCode;
59
55
  readonly unservedKind: "boundary" | "interior" | undefined;
60
- readonly firstOffendingLine: number | undefined;
61
- readonly servedRows: ServedRow[];
62
56
  constructor(opts: {
63
- code: ServedCode;
64
- unservedKind?: "boundary" | "interior";
65
- message: string;
57
+ code: "E_STALE_RANGE";
58
+ headline: string;
59
+ servedRows: ServedRow[];
60
+ servedBlock: string;
61
+ cause?: RangeCause;
66
62
  firstOffendingLine?: number;
63
+ } | {
64
+ code: "E_UNSERVED_RANGE";
65
+ headline: string;
67
66
  servedRows: ServedRow[];
67
+ servedBlock: string;
68
+ unservedKind: "boundary" | "interior";
69
+ firstOffendingLine?: number;
68
70
  });
69
71
  }
70
- export declare function isServedRejection(error: unknown): error is ServedRejectionError;
71
- export declare class AnchorMismatchError extends CodedError {
72
- readonly servedRows: ServedRow[];
73
- constructor(message: string, servedRows: ServedRow[]);
74
- }
75
- /** Thrown when replacement_text carries anchor-syntax garbage (HASH│/diff-preview prefixes).
76
- * Carries the stripped edit so applyEdit can distinguish served-echo (→ E_SERVED_ECHO
77
- * denial downstream) from garbage (→ E_BAD_ANCHOR stands). */
78
- export declare class BadAnchorError extends CodedError {
79
- readonly stripped: HEdit;
80
- constructor(message: string, stripped: HEdit);
72
+ export declare class AnchorMismatchError extends DomainError<DomainErrorCode> {
73
+ constructor(code: "E_STALE_ANCHOR" | "E_SUSPICIOUS_TEXT", payload: ErrorPayloadMap[typeof code]);
81
74
  }
82
75
  export declare function isAnchorMismatch(error: unknown): error is AnchorMismatchError;
83
76
  export declare function findEditHashEcho(replacementLines: string[], served: readonly (string | null)[], startLine: number): {
84
77
  k: number;
85
78
  hash: string;
86
79
  } | undefined;
80
+ /**
81
+ * Served-echo refusal: the replacement reproduces a row actually served for
82
+ * this session, path, and line. A DomainError<"E_SUSPICIOUS_TEXT"> whose
83
+ * code, message header and audience agree — while staying instanceof
84
+ * AnchorMismatchError so the existing reject-and-serve branches (which catch
85
+ * AnchorMismatchError / ServedRejectionError) keep recognising it.
86
+ */
87
87
  export declare class EditHashEchoError extends AnchorMismatchError {
88
- constructor(message: string, servedRows?: ServedRow[]);
88
+ constructor(payload: ErrorPayloadMap["E_SUSPICIOUS_TEXT"]);
89
89
  }
90
90
  export declare function buildRangeEcho(startLine: number, endLine: number, fileHashes: string[]): ServedRow[];
91
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;
92
169
  export declare function verifyServedRange(args: {
93
170
  served: (string | null)[];
94
171
  startHash: string;
@@ -100,9 +177,14 @@ export declare function verifyServedRange(args: {
100
177
  filePath?: string;
101
178
  servedCanons?: (string | null)[];
102
179
  retired?: ReadonlySet<string>;
103
- epochSnapshotId?: string;
104
- curSnapshotId?: string;
105
- strictPos?: boolean;
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;
106
188
  }): void;
107
189
  export interface ResolvedRange {
108
190
  startLine: number;
@@ -111,25 +193,24 @@ export interface ResolvedRange {
111
193
  endHash: string;
112
194
  delta: number;
113
195
  }
114
- export type ServeRecordPolicy = "live" | "preview";
115
- export declare function recordEchoServes(sessionKey: string, path: string, rows: ServedRow[], policy: ServeRecordPolicy, lineCount?: number): Promise<void>;
116
196
  type LIdx = {
117
197
  fileLines: string[];
118
198
  lineStarts: number[];
119
199
  };
120
200
  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)[], servedCanons?: (string | null)[], retired?: ReadonlySet<string>, epochSnapshotId?: string, curSnapshotId?: string, strictPos?: boolean): {
201
+ export declare function applyEdit(content: string, edit: HEdit, signal?: AbortSignal, precomputedHashes?: string[], filePath?: string, served?: (string | null)[], servedCanons?: (string | null)[], retired?: ReadonlySet<string>, mode?: EditMode, leaseSource?: LeaseSpanSource): {
122
202
  content: string;
123
203
  firstChangedLine: number | undefined;
124
204
  lastChangedLine: number | undefined;
125
205
  range: ResolvedRange;
126
206
  warnings?: string[];
127
207
  noopEdit?: NEdit;
208
+ neverServedCount?: number;
128
209
  };
129
210
  export declare function fmtRegion(hashes: string[], lines: string[]): string;
130
211
  export declare function changedRange(original: string, result: string): {
131
212
  firstChangedLine: number;
132
213
  lastChangedLine: number;
133
214
  } | null;
134
- 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";
215
+ 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, } from "./hash-assign.js";
135
216
  export { lineHashes } from "./hash.js";
@@ -1,3 +1,4 @@
1
+ import { DomainError } from "../domain-errors.js";
1
2
  export type Hasher = {
2
3
  h32(input: string, seed?: number): number;
3
4
  h64ToString(input: string, seed?: bigint): string;
@@ -16,20 +17,19 @@ export declare const HASH_SEP = "\u2502";
16
17
  export declare const HASH_SPACE: number;
17
18
  export declare const MAX_HASH_LINES: number;
18
19
  export declare const HASH_PROBE_STRIDE: number;
19
- export declare class AnchorSpaceExhaustedError extends Error {
20
- readonly code = "E_ANCHOR_SPACE_EXHAUSTED";
20
+ export declare class AnchorSpaceExhaustedError extends DomainError<"E_LARGE_FILE"> {
21
21
  readonly retiredCount: number;
22
22
  readonly servedCount: number;
23
- constructor(retiredCount: number, servedCount: number, reservedCount: number);
23
+ constructor(retiredCount: number, servedCount: number);
24
24
  }
25
25
  export declare function idxToHash(idx: number): string;
26
26
  export declare function hashAt(idx: number): string;
27
- export declare function rememberHashCanon(hash: string, canonText: string): void;
28
- export declare function getCanonForHash(hash: string): string | undefined;
29
27
  export declare const HL_PREFIX_PLUS_RE: RegExp;
30
28
  export declare const HL_PREFIX_MINUS_RE: RegExp;
31
29
  export declare const HL_BARE_PREFIX_RE: RegExp;
32
30
  export declare const CANON_VERSION = 2;
33
31
  export declare function canon(line: string): string;
32
+ /** Single definition of served_leases.canon_hash / line_lineage.canon_hash (CP2). */
33
+ export declare function canonDigest(line: string): string;
34
34
  export declare function lineHashesPure(content: string, reservedHashes?: ReadonlySet<string>, retiredCount?: number, servedCount?: number): string[];
35
35
  export declare function mapStableHashes(oldContent: string, oldHashes: string[], newContent: string, removedHashes?: Set<string>, reservedHashes?: ReadonlySet<string>, retiredCount?: number, servedCount?: number): string[];
@@ -1,7 +1,7 @@
1
1
  import { type HashStore } from "../hash-store.js";
2
2
  export interface HashSnapshotIO {
3
3
  get(path: string, content: string, deleteCorrupt: boolean): Promise<string[] | undefined>;
4
- upsert(path: string, checksum: string, lineCount: number, hashes: string[]): Promise<void>;
4
+ upsert(path: string, checksum: string, lineCount: number, hashes: string[], content?: string): Promise<void>;
5
5
  }
6
6
  export declare function setDefaultHashSnapshotIO(io: HashSnapshotIO | undefined): void;
7
7
  export declare function snapshotIOFor(store?: HashStore): HashSnapshotIO | undefined;
@@ -9,5 +9,5 @@ export { parseHashRef, parseText } from "./parse.js";
9
9
  export type { Anchor } from "./parse.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, isServedRejection, isAnchorMismatch, verifyServedRange, buildRangeEcho, fmtServedRows, } from "./anchor-pipeline.js";
13
- export type { ServedRow, ResolvedRange, ServedCode } 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";
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Served-prefix guard tiers — FU-5 port of upstream
3
+ * `pi-better-edit@b92e0ec:src/hashline/served-guard.ts`.
4
+ *
5
+ * Three tiers beside the served-echo refusal gate (owned by
6
+ * `anchor-pipeline.ts`'s `findEditHashEcho`, unchanged here):
7
+ * - exact reproduction of a served line → the gate refuses (E_SUSPICIOUS_TEXT);
8
+ * - served anchor, differing content (`W_SERVED_PREFIX_MISMATCH`) → applied-only
9
+ * note, fires per occurrence, never blocks, never rewrites;
10
+ * - anchor-shaped prefix never served (`W_NEVER_SERVED_SHAPE`) → shape-only soft
11
+ * hint, fires regardless of the literal declaration.
12
+ *
13
+ * Evidence adaptation (disclosed in ADR-0025's FU-5 amendment): upstream judges
14
+ * the remainder against lease-derived canon DIGESTS (#151,
15
+ * `canonDigest(remainder) === served_leases.canon_hash`); this tree's parallel
16
+ * evidence is `servedCanons` — raw canon STRINGS recorded at serve time
17
+ * (`read-and-serve.ts:173`), so the comparison is `canon(tail) === servedCanons[pos]`.
18
+ * The tier semantics are identical; only the comparison space differs.
19
+ *
20
+ * Not ported (measured): upstream's `buildServedWritePrefixNote` stage
21
+ * (`lifecycle-hooks/index.ts:188-197`) — the local write channel
22
+ * (`src/write-hook.ts`) is outside this lane's target files; `findServedHashEcho`
23
+ * — the local gate stays `findEditHashEcho`.
24
+ *
25
+ * @module dsh-better-edit/hashline/served-guard
26
+ */
27
+ interface ServedPrefixMismatch {
28
+ /** SAFETY: 1-based candidate index within the submitted lines. */
29
+ k: number;
30
+ /** SAFETY: absolute candidate line (`start + k - 1`); equals `k` when `start` is 1. */
31
+ line: number;
32
+ /** SAFETY: the anchor served for this session and file that opens the candidate. */
33
+ anchor: string;
34
+ /** SAFETY: 1-based served position the anchor was served for. */
35
+ servedLine: number;
36
+ }
37
+ /**
38
+ * SAFETY: Served prefix mismatch — the middle tier beside the served-echo gate.
39
+ *
40
+ * A candidate reports here when it opens with an anchor served for this session
41
+ * and file, yet its remainder canon matches none of the canons recorded for
42
+ * that anchor's served line. Position-agnostic like the gate: `start` only
43
+ * shifts the reported `line` and never narrows matching. Empty or all-null
44
+ * `servedCanons` means no served content to compare against, so the result
45
+ * stays empty — never a shape-only report. Exact reproductions are excluded
46
+ * (the gate owns them), so callers scan for this tier only after the gate stays
47
+ * silent. Pure with no retained state: fires per occurrence, never suppressed.
48
+ */
49
+ export declare function findServedPrefixMismatches(lines: readonly string[], served: readonly (string | null)[], servedCanons: readonly (string | null)[], start?: number): ServedPrefixMismatch[];
50
+ /**
51
+ * SAFETY: the canonical remedy shared verbatim by both applied-hint builders:
52
+ * the bytes were applied, so a retry is knowably safe, and the remedy names the
53
+ * exact failing shape. Pinned byte-identical by test so builders cannot drift.
54
+ */
55
+ export declare const ANCHOR_PREFIX_REMEDY: string;
56
+ /**
57
+ * SAFETY: Model note for an applied edit carrying a served prefix mismatch.
58
+ * Applied-only, bytes untouched, never blocks: the post-edit diff already
59
+ * carries the written line, this note only tells the model the prefix
60
+ * reproduces a served anchor with differing content and names the remedy.
61
+ */
62
+ export declare function buildServedEditPrefixNote(args: {
63
+ k: number;
64
+ anchor: string;
65
+ servedLine: number;
66
+ }): string;
67
+ interface NeverServedAnchorShape {
68
+ /** SAFETY: 1-based candidate index within the submitted lines. */
69
+ k: number;
70
+ /** SAFETY: absolute candidate line (`start + k - 1`); equals `k` when `start` is 1. */
71
+ line: number;
72
+ /** SAFETY: the anchor-shaped prefix never served for this session and file. */
73
+ anchor: string;
74
+ }
75
+ /**
76
+ * SAFETY: Never-served anchor-shaped lines — the soft-hint tier beside the
77
+ * refusal gate and the served prefix mismatch tier.
78
+ *
79
+ * A candidate reports here when it opens with an anchor-shaped prefix
80
+ * (3 alphanumerics plus the separator, after one optional leading diff marker)
81
+ * whose anchor was never served for this session and file. Shape-only by design:
82
+ * the hint never blocks and never rewrites, so evidence gating does not apply.
83
+ * Served anchors are excluded (the gate and the mismatch tier own them).
84
+ * Pure with no retained state: fires per occurrence, never suppressed.
85
+ */
86
+ export declare function findNeverServedAnchorShapes(lines: readonly string[], served: readonly (string | null)[], start?: number): NeverServedAnchorShape[];
87
+ /**
88
+ * SAFETY: Soft hint for an applied edit carrying never-served anchor-shaped lines.
89
+ * Applied-only, bytes untouched, never blocks: the bytes were written as-is with
90
+ * no rewrite. `count` states how many replacement lines match the tool's own row
91
+ * shape with anchors never served for this session and file. The trailing clause
92
+ * is gated on `if ... unintended` — a conditional reference, not an order.
93
+ * The per-item count travels as data (`neverServedCount`, anchor-pipeline); the batch engine
94
+ * aggregates, rendering ONE counted hint per CALL.
95
+ * Surfaced through the warnings seam (rendered by warnBlock) on the model-visible channel.
96
+ */
97
+ export declare function buildNeverServedEditHint(args: {
98
+ count: number;
99
+ }): string;
100
+ export {};
@@ -1,9 +1,9 @@
1
1
  /**
2
- * dsh-better-edit — hash-anchored read/edit/batch_edit/undo_last_edit for
2
+ * dsh-better-edit — hash-anchored read/edit/undo_last_edit for
3
3
  * DeepSeek Harness, a dsh port of pi-hashline-edit-lsz.
4
4
  *
5
5
  * Cordis host-plane plugin (mounted by the bundle's cordis.patch.yml). On
6
- * `agent/session-start` it registers the hashline tools and prompt sections on
6
+ * `agent/created` it registers the hashline tools and prompt sections on
7
7
  * the AGENT's own scope layer, so they shadow the preset's built-in `read` /
8
8
  * `edit` for that agent (nearest layer wins in dsh's tool registry) and unwind
9
9
  * automatically when the agent is disposed. The built-in `write` stays in
@@ -6,24 +6,27 @@
6
6
  * content, the noop-loop guard, and the persist-undo → write → restore
7
7
  * Transaction (persist-undo → write → restore) is owned by Mutation, not this engine.
8
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.
9
+ * The model-facing contract lives here unchanged: E_BATCH_ABORT,
10
+ * E_NOOP_LOOP, E_UNDO_UNAVAILABLE carry byte-identical messages, and
11
+ * a rejection rethrows with the current-range echo and records/grants nothing.
12
12
  * @module dsh-better-edit/mutation/engine
13
13
  */
14
14
  import type { FileIO } from "../fs-bridge.js";
15
- import type { HashStore } from "../hash-store.js";
15
+ import { type HashStore } from "../hash-store.js";
16
16
  import type { LineEnding } from "../edit-diff.js";
17
- import { type HEdit, type NEdit } from "../hashline/anchor-pipeline.js";
17
+ import { type HEdit, type NEdit, type LeaseSpanSource } from "../hashline/anchor-pipeline.js";
18
18
  import { type ResolvedRange, type ServedRow } from "../hashline/anchor-pipeline.js";
19
+ import type { EditMode } from "../contract.js";
19
20
  export interface PreparedItem {
20
21
  index: number;
21
- path: string;
22
+ file: string;
22
23
  absolutePath: string;
23
- remove_from: string;
24
- remove_to: string;
25
- replacement_text: string;
26
- pathWarning?: string;
24
+ anchor_from: string;
25
+ anchor_to: string;
26
+ replace_with: string;
27
+ fileWarning?: string;
28
+ /** Request-level edit mode ("general" default, "literal" bypasses served-echo). */
29
+ mode?: EditMode;
27
30
  }
28
31
  export interface FileEditResult {
29
32
  displayPath: string;
@@ -63,9 +66,9 @@ export interface ApplyOneInput {
63
66
  content: string;
64
67
  hashes: string[];
65
68
  served: (string | null)[];
66
- removeFrom: string;
67
- removeTo: string;
68
- replacementText: string;
69
+ anchorFrom: string;
70
+ anchorTo: string;
71
+ replaceWith: string;
69
72
  absolutePath: string;
70
73
  displayPath: string;
71
74
  signal?: AbortSignal;
@@ -82,9 +85,13 @@ export interface ApplyOneInput {
82
85
  reservedHashes?: ReadonlySet<string>;
83
86
  servedCanons?: (string | null)[];
84
87
  retired?: ReadonlySet<string>;
85
- epochSnapshotId?: string;
86
- curSnapshotId?: string;
87
- strictPos?: boolean;
88
+ /** Request-level edit mode ("general" default, "literal" bypasses served-echo). */
89
+ mode?: EditMode;
90
+ /**
91
+ * The lease-identity source for this item's buffer. Present => the identity gate replaces the
92
+ * position check; absent => the unconditional position check (preview/no-store).
93
+ */
94
+ leaseSource?: LeaseSpanSource;
88
95
  sessionKey?: string;
89
96
  /** Pre-resolved edit (single path keeps resEdit before IO for error order). */
90
97
  edit?: HEdit;
@@ -103,6 +110,8 @@ export interface ApplyOneResult {
103
110
  totalAddedLines: number;
104
111
  totalRemovedLines: number;
105
112
  anchorWarnings: string[] | undefined;
113
+ /** Offending never-served anchor-shaped lines, as data (FU-R, upstream pipeline.ts:261,269); the batch renders one counted hint per call. */
114
+ neverServedCount: number;
106
115
  }
107
116
  /**
108
117
  * One edit against in-memory content: resolve (unless a pre-resolved edit was
@@ -110,34 +119,44 @@ export interface ApplyOneResult {
110
119
  *
111
120
  * `onReject` owns the reject-and-serve policy: it receives resolve/verify
112
121
  * failures (and the edit that failed, when resolved) and MUST throw. The
113
- * single path rethrows the original anchor error after recording echo serves;
114
- * the batch path wraps with [E_BATCH_ABORT] plus the current-range echo.
122
+ * single path rethrows the original anchor error; the batch path wraps with
123
+ * E_BATCH_ABORT plus the current-range echo. A rejection records and grants
124
+ * nothing — the recovery is the re-read the message already instructs.
115
125
  */
116
126
  export declare function applyOne(input: ApplyOneInput, onReject: (error: unknown, edit: HEdit | undefined) => Promise<never>): Promise<ApplyOneResult>;
117
127
  export interface NoopLoopOptions {
118
- absolutePath: string;
119
- removeFrom: string;
120
- removeTo: string;
121
- replacementText: string;
128
+ anchorFrom: string;
129
+ anchorTo: string;
122
130
  displayPath: string;
123
- /** Batch item index; undefined = single-edit flavor. */
124
- index?: number;
131
+ /** Batch item index. */
132
+ index: number;
125
133
  count: number;
126
- sessionKey: string;
127
- originalHashes: string[];
128
134
  originalNormalized: string;
129
- /** Single-edit flavor only: the edit's range, for the echo rows. */
130
- range?: ResolvedRange;
131
135
  /** Batch flavor: precomputed echo rows for the failed item (may be absent). */
132
136
  echoRows?: ServedRow[];
133
137
  }
134
138
  /**
135
139
  * The shared noop-loop guard. Returns the "twice in a row" notice for the
136
- * caller to append to warnings, or throws [E_NOOP_LOOP] (after recording the
137
- * echo serves) once the payload has been submitted NOOP_LOOP_THRESHOLD times
140
+ * caller to append to warnings, or throws E_NOOP_LOOP (with the current-range
141
+ * echo) once the payload has been submitted NOOP_LOOP_THRESHOLD times
138
142
  * with no change. Messages are byte-identical to the pre-engine tools.
139
143
  */
140
144
  export declare function enforceNoopLoop(opts: NoopLoopOptions): Promise<string | undefined>;
145
+ /**
146
+ * The read-only lease-identity source for one buffer, or undefined when it cannot be built.
147
+ *
148
+ * Leases come from `served_leases`; the `line_id` -> current-line map comes from the store's
149
+ * `positionsByIdentity` over the buffer the edit is applied to. Nothing is written: the edit path
150
+ * never re-stamps a lease and never retires one.
151
+ *
152
+ * For a buffer that is not a committed snapshot — batch item k > 0 — the caller passes the map it
153
+ * already advanced (`leaseSourceFrom` + `spliceWorkingBufferIds`) rather than re-deriving it here.
154
+ *
155
+ * UPGRADE CONSEQUENCE: a session whose `served` rows predate lease granting (a pre-T2b store) holds
156
+ * no lease for those anchors, so its first edit rejects and needs one re-read. Fail-closed and
157
+ * one-time; it goes in the CP3 ADR and the T7 CHANGELOG note.
158
+ */
159
+ export declare function makeLeaseSource(store: HashStore, sessionKey: string, absolutePath: string, content: string): LeaseSpanSource | undefined;
141
160
  /**
142
161
  * Run a file's item list against freshly-read content with served
143
162
  * verification, evolving content/hashes, union range, noop tracking, and a
@@ -13,26 +13,21 @@
13
13
  *
14
14
  * Public surface:
15
15
  * execute(io, items, {sessionKey, exec, sandbox, signal}) → string — deep seam: ONE interface
16
- * applySingle(io, params, cwd, opts) → PipelineResult — single-edit helper
17
16
  * applySequence(io, items, ctx) → FileEditResult — per-file sequencer
18
17
  * commit(io, files, {exec, sandboxPolicy, signal}) → void — transaction
19
18
  *
20
19
  * Depth: small interface (execute) with large implementation — locality and leverage.
21
20
  *
22
21
  * Internals (private): verifyServedRange, resToSpan, assemble, scanDrift,
23
- * boundaryDups, noopGuard. Tested via PipelineResult/FileEditResult, not via split e2e.
22
+ * boundaryDups, noopGuard. Tested via FileEditResult, not via split e2e.
24
23
  *
25
24
  * @module dsh-better-edit/mutation
26
25
  */
27
26
  import type { FileIO } from "./fs-bridge.js";
28
- import type { EditParams } from "./contract.js";
29
- import type { HashStore } from "./hash-store.js";
30
27
  import type { ToolExecution } from "@deepseek-ai/dsh-tools";
31
28
  import type { SandboxExecutionPolicy } from "@deepseek-ai/dsh-sandbox";
32
29
  import type { FsSandboxController } from "./sandbox.js";
33
30
  import type { LineEnding } from "./edit-diff.js";
34
- import { type NEdit } from "./hashline/anchor-pipeline.js";
35
- import type { ResolvedRange } from "./hashline/anchor-pipeline.js";
36
31
  import { scanDrift } from "./session-view.js";
37
32
  import { runFileEdits, resolveMissingPath } from "./mutation/engine.js";
38
33
  import type { FileEditResult, PreparedItem } from "./mutation/engine.js";
@@ -42,32 +37,6 @@ import type { RMeta, BatchSection } from "./edit-response.js";
42
37
  import { genDiff, toLF, stripBOM } from "./edit-diff.js";
43
38
  import { computeDrift } from "./session-view.js";
44
39
  import { trackNoopPayload, clearNoopLoop, noopPayloadKey } from "./noop-guard.js";
45
- export interface PipelineResult {
46
- path: string;
47
- absolutePath: string;
48
- originalNormalized: string;
49
- result: string;
50
- bom: string;
51
- originalEnding: LineEnding;
52
- hadUtf8DecodeErrors: boolean;
53
- warnings: string[];
54
- noopEdit?: NEdit;
55
- firstChangedLine?: number;
56
- lastChangedLine?: number;
57
- originalHashes: string[];
58
- resultHashes: string[];
59
- totalAddedLines: number;
60
- totalRemovedLines: number;
61
- driftNotice?: string;
62
- range: ResolvedRange;
63
- }
64
- export interface ExecPipelineOptions {
65
- signal?: AbortSignal;
66
- store?: HashStore;
67
- noPersist?: boolean;
68
- sessionKey?: string;
69
- }
70
- export declare function execPipeline(io: FileIO, params: EditParams, cwd: string, options?: ExecPipelineOptions): Promise<PipelineResult>;
71
40
  /** Resolve the display path a caller names against the session cwd. */
72
41
  export declare function resolveDisplayPath(path: string, cwd: string): string;
73
42
  /** Snapshot bookkeeping for noop/success results (best-effort). */
@@ -122,13 +91,6 @@ export declare function execute(opts: {
122
91
  sandbox: FsSandboxController;
123
92
  sandboxPolicy: SandboxExecutionPolicy | undefined;
124
93
  }): Promise<string>;
125
- /** Apply a single edit — owns read→normalize→loadServed→applyOne→stableRehash→drift. */
126
- export declare function applySingle(io: FileIO, params: EditParams, cwd: string, opts?: {
127
- sessionKey?: string;
128
- signal?: AbortSignal;
129
- store?: HashStore;
130
- noPersist?: boolean;
131
- }): Promise<PipelineResult>;
132
94
  /** Apply a per-file sequence (batch's group) — owns the loop + unionRange + counters. */
133
95
  export declare function applySequence(io: FileIO, items: PreparedItem[], ctx: {
134
96
  sessionKey: string;
@@ -1,13 +1,13 @@
1
1
  import { NOOP_LOOP_THRESHOLD } from "./constants.js";
2
- export declare function noopPayloadKey(absolutePath: string, removeFrom: string, removeTo: string, replacementText: string): string;
2
+ export declare function noopPayloadKey(absolutePath: string, anchorFrom: string, anchorTo: string, replaceWith: string): string;
3
3
  export declare function trackNoopPayload(absolutePath: string, payload: string): number;
4
4
  export declare function clearNoopLoop(absolutePath: string): void;
5
5
  export { NOOP_LOOP_THRESHOLD };
6
6
  export interface NoopPolicyInput {
7
7
  absolutePath: string;
8
- removeFrom: string;
9
- removeTo: string;
10
- replacementText: string;
8
+ anchorFrom: string;
9
+ anchorTo: string;
10
+ replaceWith: string;
11
11
  ref: string;
12
12
  batch: boolean;
13
13
  range: {
@@ -18,7 +18,7 @@ export declare const UNDO_DESCRIPTION: string;
18
18
  export declare const UNDO_GUIDANCE: ToolGuidance;
19
19
  /**
20
20
  * @deprecated batch_edit guidance seam was removed with ADR-0003 (payload contract
21
- * merged batch_edit into edit's {path, edits:[[hash,hash,text]]} arity). This alias
21
+ * merged batch_edit into edit's {file, edits:[...]} arity). This alias
22
22
  * is kept for backwards compat — use EDIT_DESCRIPTION. The guidance system no
23
23
  * longer includes tool:batch_edit.
24
24
  */
@@ -8,6 +8,7 @@
8
8
  * @module dsh-better-edit/read-and-serve
9
9
  */
10
10
  import type { FileIO } from "./fs-bridge.js";
11
+ import type { ReadWindow } from "./file-view.js";
11
12
  import type { ServedRow } from "./hashline/anchor-pipeline.js";
12
13
  /** Appended when the file had non-UTF-8 bytes; editing rewrites it as UTF-8. */
13
14
  export declare const UTF8_REWRITE_NOTE = "[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]";
@@ -19,6 +20,11 @@ export interface ReadAndServeOptions {
19
20
  /** Pagination for the rendered preview (undefined = from the start). */
20
21
  offset?: number;
21
22
  limit?: number;
23
+ /**
24
+ * FU-6 (port of pi-better-edit@2334352): disjoint ranges served in one call; wins over
25
+ * offset/limit when non-empty, `[]` falls back to the plain (full-read) contract.
26
+ */
27
+ windows?: ReadWindow[];
22
28
  }
23
29
  export interface ReadAndServeResult {
24
30
  /** Optional auto-guess warning, separate block. */
@@ -2,7 +2,7 @@
2
2
  * The sandbox-escalation API for the hashline mutating tools, mirroring
3
3
  * `@deepseek-ai/dsh-tool-fs`'s `FsSandboxController` (same vocabulary, same
4
4
  * fail-closed approval sequence, shared `@deepseek-ai/dsh-sandbox` pieces) so
5
- * `edit`/`batch_edit`/`undo_last_edit` escalate exactly like the built-in
5
+ * `edit`/`undo_last_edit` escalate exactly like the built-in
6
6
  * `write`/`edit` — and, critically, stamp the per-call policy with the SESSION
7
7
  * workspace root. Without the policy the sandbox backend falls back to the
8
8
  * deployment default root, so an edit inside the session workspace is denied