dsh-better-edit 0.8.2 → 1.1.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 (79) hide show
  1. package/CHANGELOG.md +173 -99
  2. package/README.md +61 -33
  3. package/README.zh.md +20 -17
  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/guidance/materialize.js +7 -7
  13. package/lib/guidance/resolve.js +13 -8
  14. package/lib/hash-store.js +404 -278
  15. package/lib/hashline/anchor-pipeline.js +586 -378
  16. package/lib/hashline/hash-assign.js +21 -22
  17. package/lib/hashline/hash.js +6 -6
  18. package/lib/hashline/index.js +1 -1
  19. package/lib/hashline/resolve.js +1 -1
  20. package/lib/hashline/served-guard.js +181 -0
  21. package/lib/index.js +37 -11
  22. package/lib/mutation/engine.js +392 -96
  23. package/lib/mutation.js +22 -130
  24. package/lib/noop-guard.js +20 -9
  25. package/lib/prompts.js +20 -18
  26. package/lib/read-and-serve.js +44 -20
  27. package/lib/sandbox.js +1 -1
  28. package/lib/session-view.js +57 -43
  29. package/lib/snapshot-store/index.js +97 -0
  30. package/lib/snapshot-store/lineage-store.js +400 -0
  31. package/lib/snapshot-store/migrate.js +80 -0
  32. package/lib/snapshot-store/pairing.js +412 -0
  33. package/lib/snapshot-store/txn.js +63 -0
  34. package/lib/snapshot-store/vacuum.js +243 -0
  35. package/lib/store-lifecycle.js +13 -1
  36. package/lib/store-retry.js +34 -0
  37. package/lib/tool-edit.js +90 -44
  38. package/lib/tool-read.js +29 -1
  39. package/lib/tool-str-replace-editor.js +26 -18
  40. package/lib/tool-undo.js +25 -8
  41. package/lib/types/constants.d.ts +5 -2
  42. package/lib/types/contract.d.ts +76 -71
  43. package/lib/types/domain-errors.d.ts +410 -0
  44. package/lib/types/edit-response.d.ts +1 -1
  45. package/lib/types/file-encoding-state.d.ts +1 -0
  46. package/lib/types/file-view.d.ts +35 -6
  47. package/lib/types/guidance/materialize.d.ts +2 -2
  48. package/lib/types/guidance/resolve.d.ts +14 -2
  49. package/lib/types/hash-store.d.ts +38 -19
  50. package/lib/types/hashline/anchor-pipeline.d.ts +117 -36
  51. package/lib/types/hashline/hash-assign.d.ts +5 -5
  52. package/lib/types/hashline/hash.d.ts +1 -1
  53. package/lib/types/hashline/index.d.ts +2 -2
  54. package/lib/types/hashline/served-guard.d.ts +100 -0
  55. package/lib/types/index.d.ts +3 -3
  56. package/lib/types/mutation/engine.d.ts +49 -30
  57. package/lib/types/mutation.d.ts +1 -39
  58. package/lib/types/noop-guard.d.ts +4 -4
  59. package/lib/types/prompts.d.ts +1 -1
  60. package/lib/types/read-and-serve.d.ts +6 -0
  61. package/lib/types/sandbox.d.ts +1 -1
  62. package/lib/types/session-view.d.ts +38 -9
  63. package/lib/types/snapshot-store/index.d.ts +28 -0
  64. package/lib/types/snapshot-store/lineage-store.d.ts +96 -0
  65. package/lib/types/snapshot-store/migrate.d.ts +16 -0
  66. package/lib/types/snapshot-store/pairing.d.ts +99 -0
  67. package/lib/types/snapshot-store/txn.d.ts +12 -0
  68. package/lib/types/snapshot-store/vacuum.d.ts +79 -0
  69. package/lib/types/store-lifecycle.d.ts +0 -1
  70. package/lib/types/store-retry.d.ts +6 -0
  71. package/lib/types/tool-edit.d.ts +2 -2
  72. package/lib/types/tool-str-replace-editor.d.ts +2 -2
  73. package/lib/types/utils.d.ts +5 -6
  74. package/lib/types/workspace-context.d.ts +10 -1
  75. package/lib/undo-edit.js +27 -11
  76. package/lib/utils.js +12 -12
  77. package/lib/workspace-context.js +27 -9
  78. package/lib/write-hook.js +13 -4
  79. package/package.json +28 -30
@@ -2,9 +2,10 @@
2
2
  * The hash store — ONE deep persistence module for the hashline domain.
3
3
  *
4
4
  * Owns the sqlite db, the schema and migrations, corruption quarantine,
5
- * busy-retry, WAL, the legacy-JSON migration, AND the three narrow row APIs
6
- * the rest of the plugin needs: hash snapshots, undo entries, and served
7
- * rows. The prepared statements are a private implementation detail — callers
5
+ * Owns the sqlite db, the schema and migrations, corruption quarantine, WAL,
6
+ * the legacy-JSON migration, and the undo/served row APIs. Hash snapshots
7
+ * live in snapshot-store (shared busy-retry policy in store-retry), adapted
8
+ * here so the HashStore surface stays stable for its duck-typed callers.
8
9
  * use domain methods, never SQL.
9
10
  *
10
11
  * Corrupt-row handling (parse the JSON column → validate against the hash
@@ -13,13 +14,8 @@
13
14
  * reaches into another family's rows.
14
15
  * @module dsh-better-edit/hash-store
15
16
  */
16
- /** The legacy JSON snapshot shape (pre-sqlite stores). */
17
- export interface LegacySnapshot {
18
- content: string;
19
- hashes: string[];
20
- }
21
- export declare function isValidHashList(value: unknown): value is string[];
22
- export declare function isValidSnapshot(value: unknown): value is LegacySnapshot;
17
+ import { type VacuumResult } from "./snapshot-store/index.js";
18
+ import { type LineageStore } from "./snapshot-store/lineage-store.js";
23
19
  /** A served-row array: per-position hash, or null for never-served slots. */
24
20
  export declare function isValidCanonsList(value: unknown): value is (string | null)[];
25
21
  export declare function isValidServedList(value: unknown): value is (string | null)[];
@@ -31,6 +27,22 @@ export interface UndoRecord {
31
27
  hashes: string[];
32
28
  resultContent: string;
33
29
  }
30
+ /** The v7 undo row contract: legacy state plus the snapshot pin. */
31
+ export interface FileUndoRecord {
32
+ content: string;
33
+ bom: string;
34
+ ending: string;
35
+ hashes: string[];
36
+ resultContent: string;
37
+ snapshotHash: string | null;
38
+ updatedAt: number;
39
+ }
40
+ /**
41
+ * The v7 undo WRITE input: everything `writeUndoPair` stores except `updatedAt`.
42
+ * The pair's stamp is a pair property owned by the store clock (`writeUndoPairImpl`),
43
+ * so a caller-supplied timestamp would be a required field that is never read.
44
+ */
45
+ export type FileUndoWrite = Omit<FileUndoRecord, "updatedAt">;
34
46
  /**
35
47
  * The domain face of the hash store. Each row family gets a narrow API;
36
48
  * corruption healing (parse → validate → delete) happens inside the getters.
@@ -39,7 +51,7 @@ export interface HashStore {
39
51
  readonly engine: "node:sqlite";
40
52
  /** The stored hashes for a path+content, or undefined on a miss; a corrupt row is deleted (when deleteCorrupt) and treated as a miss. */
41
53
  getSnapshot(path: string, content: string, deleteCorrupt?: boolean): string[] | undefined;
42
- upsertSnapshot(path: string, checksum: string, lineCount: number, hashes: string[]): void;
54
+ upsertSnapshot(path: string, checksum: string, lineCount: number, hashes: string[], content?: string): void;
43
55
  /** Every path referenced by any row family (snapshots ∪ undo ∪ served). */
44
56
  allKnownPaths(): {
45
57
  path: string;
@@ -54,11 +66,20 @@ export interface HashStore {
54
66
  findSnapshotPaths(hashes: string[]): string[];
55
67
  /** The undo row for a path, healing a corrupt row (parse → validate → delete). */
56
68
  getUndo(path: string): UndoRecord | undefined;
57
- upsertUndo(path: string, entry: UndoRecord): void;
58
- deleteUndo(path: string): void;
59
69
  pruneUndoOlderThan(ts: number): void;
70
+ /** The single undo writer: write-back-or-delete each side in one transaction. */
71
+ writeUndoPair(path: string, legacy: UndoRecord | undefined, v7: FileUndoWrite | undefined): void;
72
+ /** Both undo rows in one transaction. */
73
+ deleteUndoPair(path: string): void;
74
+ /** The v7 undo row for a path, same healing contract as the legacy row. Sole consumer: undo-edit readFileUndo (rg-verified); kept on the store face beside getUndo because both readers share the pair-healing closures. */
75
+ getFileUndo(path: string): FileUndoRecord | undefined;
60
76
  /** Delete every row family's entries for paths that no longer exist on disk. */
61
77
  pruneMissing(): Promise<void>;
78
+ /**
79
+ * Run the snapshot retention pass and return its result. The caller (a trigger) owns the report:
80
+ * it calls `reportVacuum(result, context)` so exactly one site decides what an operator sees.
81
+ */
82
+ vacuumSnapshots(): VacuumResult;
62
83
  }
63
84
  /**
64
85
  * Served persistence — internal, owned by SessionView. Not part of the public HashStore API.
@@ -71,7 +92,6 @@ export interface ServedPersistence {
71
92
  getRetiredAnchors(sessionKey: string, path: string): Set<string>;
72
93
  getRetiredEntries(sessionKey: string, path: string): RetiredEntry[];
73
94
  getServedCanons(sessionKey: string, path: string): (string | null)[];
74
- getEpochSnapshotId(sessionKey: string, path: string): string | undefined;
75
95
  getCards(sessionKey: string, path: string): Set<number>;
76
96
  upsertCards(sessionKey: string, path: string, cardsJson: string): void;
77
97
  clearCards(sessionKey: string, path: string): void;
@@ -82,8 +102,6 @@ export interface ServedPersistence {
82
102
  clearRetiredAnchors(sessionKey: string, path: string): void;
83
103
  upsertServedCanons(sessionKey: string, path: string, canonsJson: string): void;
84
104
  clearServedCanons(sessionKey: string, path: string): void;
85
- upsertEpochSnapshotId(sessionKey: string, path: string, snapshotId: string): void;
86
- clearEpochSnapshotId(sessionKey: string, path: string): void;
87
105
  deleteServed(sessionKey: string, path: string): void;
88
106
  deleteServedByPath(path: string): void;
89
107
  wipeServed(sessionKey: string): void;
@@ -100,7 +118,7 @@ export interface RetiredEntry {
100
118
  }
101
119
  export declare function isValidRetiredEntry(value: unknown): value is RetiredEntry;
102
120
  export declare function isValidRetiredEntries(value: unknown): value is RetiredEntry[];
103
- export type InternalHashStore = HashStore & ServedPersistence;
121
+ export type InternalHashStore = HashStore & ServedPersistence & LineageStore;
104
122
  /** Load the store as served persistence — internal, for SessionView only. */
105
123
  export declare function loadServedStore(cwd?: string): Promise<ServedPersistence>;
106
124
  export declare function isCorruptionError(error: unknown): boolean;
@@ -116,10 +134,11 @@ export declare function shutdownHashStore(): void;
116
134
  /**
117
135
  * Run `fn` inside one BEGIN IMMEDIATE transaction on the active workspace's
118
136
  * store. Without an open store for this context the call runs bare (the
119
- * caller has already loaded the store in every in-process path).
137
+ * caller has already loaded the store in every in-process path). Re-entrant:
138
+ * when a store already has a transaction open, `fn` joins it.
120
139
  */
121
140
  export declare function withStore(fn: () => void): void;
122
141
  /** Find files whose stored snapshot hashes contain every given anchor. */
123
142
  export declare function findSnapshotPathsByHashes(hashes: string[]): Promise<string[]>;
124
143
  /** Persist a hash snapshot for one path (async over the active store). */
125
- export declare function upsertSnapshotFor(path: string, checksum: string, lineCount: number, hashes: string[]): Promise<void>;
144
+ export declare function upsertSnapshotFor(path: string, checksum: string, lineCount: number, hashes: string[], content?: string): Promise<void>;
@@ -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,16 +1,16 @@
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
10
10
  * place; scoped pre/post listeners reject copied same-line served anchors
11
11
  * before dispatch and append a fresh hashline preview after successful writes.
12
12
  *
13
- * The four `tool:*` guidance sections resolve per agent preset from override
13
+ * The three `tool:*` guidance sections resolve per agent preset from override
14
14
  * files in the shared home (see `src/guidance.ts`); deployments without the
15
15
  * `agentPresets` service keep the compiled defaults unchanged.
16
16
  * @module dsh-better-edit
@@ -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