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
@@ -0,0 +1,410 @@
1
+ /**
2
+ * Domain error registry — the closed, type-safe contract for every
3
+ * model-facing diagnostic. Zero dependencies: no imports, so any seam can
4
+ * throw without wiring a store, session, or hasher.
5
+ *
6
+ * INVARIANT (the point of this module): a code is never declared without a
7
+ * producer. Every `DomainErrorCode` member must have at least one
8
+ * `new DomainError(code, …)` / `formatError(code, …)` producer in src/
9
+ * (subclass constructions `new EditHashEchoError` / `new BadAnchorError` /
10
+ * `new AnchorMismatchError("E_STALE_ANCHOR", …)` /
11
+ * `new ServedRejectionError({ code, … })` /
12
+ * `new AnchorSpaceExhaustedError(…)` count as producers of their code), or be
13
+ * listed in `DEFERRED_PRODUCERS`, and every code passed at a producer site
14
+ * must be a union member. Asserted BOTH directions in
15
+ * test/arch/domain-error-registry.test.ts. This is what makes the registry a
16
+ * contract instead of a list.
17
+ *
18
+ * COUNT DEVIATION (F4, ratified): this registry's E_* vocabulary is larger
19
+ * than upstream's 19. Upstream has no str_replace_editor shadow; the six
20
+ * shadow codes (E_BLIND_REPLACE, E_UNSUPPORTED, E_BAD_COMMAND, E_FILE_EXISTS,
21
+ * E_NO_MATCH, E_AMBIGUOUS_MATCH) are live model-facing contract per accepted
22
+ * ADR-0015, and E_UNSERVED_RANGE is live contract too (T4 declined its
23
+ * retirement — its producers are reachable, CP1 H1 → `SR@790`). A closed
24
+ * vocabulary that omits live codes is not closed — it just pushes them
25
+ * outside the contract (T4 also deleted four declarations that had no local
26
+ * producer at all; see `DEFERRED_PRODUCERS`).
27
+ * WHY payloads carry facts, not pre-baked strings: the producer already holds
28
+ * the evidence (line numbers, hashes, paths, counts), so the registry owns the
29
+ * neutral sentence and the producer passes values. The one deliberate
30
+ * exception is `E_BAD_PAYLOAD`, whose payload is `{ message }` rendered
31
+ * verbatim — admission-boundary rejections are too heterogeneous for a fixed
32
+ * shape, and the message is the fact.
33
+ *
34
+ * WHY a remedy clause may appear only when it is helpful, unharmful and
35
+ * fail-closed, AND the evidence pins a single cause. When the intent is
36
+ * ambiguous the payload states the fact and carries NO remedy, because an
37
+ * intent-guessing suggestion steers the model's next action. Remedy-free by
38
+ * rule (no `remedy` field on the registry entry):
39
+ * - `E_UNKNOWN`: no cause is knowable at all.
40
+ * - `E_NOOP_LOOP`: the refusal's evidence pins the fact (the range already
41
+ * contains the text) but not the model's intent, so a remedy clause would
42
+ * dress a status fact as an action.
43
+ *
44
+ * WHY `remedy` is declaration-only and never rendered into the message: the
45
+ * `format` strings already carry their own retry prose where the evidence pins
46
+ * it. Do not "fix" this by appending `remedy` to the rendered text. The
47
+ * declaration is owned by `DECLARATION_ONLY_FIELDS` below, which the arch oracle
48
+ * pins by identity AND checks for readers (0 today) — so it cannot rot quietly.
49
+ *
50
+ * @module dsh-better-edit/domain-errors
51
+ */
52
+ /**
53
+ * Message channel: `formatError` prefixes every rendered error with
54
+ * `[TO <AUDIENCE>]` — the `TO` marks the addressee (who must act), while the
55
+ * remedy text names the action.
56
+ */
57
+ export type Audience = "MODEL" | "USER";
58
+ /**
59
+ * One served row — position is 0-based, hash is the 3-char anchor. Declared
60
+ * here (not in anchor-pipeline) so the registry stays zero-dependency and the
61
+ * pipeline imports it from here.
62
+ */
63
+ export interface ServedRow {
64
+ position: number;
65
+ hash: string;
66
+ }
67
+ /** WHY: user-facing diagnosis carried as `details.cause` on range-family rejections. */
68
+ export type RangeCause = "retirement" | "tombstone" | "never-served" | "served-range staleness" | "anchor staleness" | "served span";
69
+ export type DomainErrorCode = "E_BAD_PAYLOAD" | "E_EMPTY_RANGE" | "E_STALE_ANCHOR" | "E_UNKNOWN_ANCHOR" | "E_FOREIGN_ANCHOR" | "E_STALE_RANGE" | "E_TARGET_LOST" | "E_UNVERIFIED_RANGE" | "E_MALFORMED_ANCHOR" | "E_SUSPICIOUS_TEXT" | "E_BATCH_ABORT" | "E_NOOP_LOOP" | "E_UNSUPPORTED_FILE" | "E_ACCESS" | "E_NOT_FOUND" | "E_UNDO_STALE" | "E_UNDO_UNAVAILABLE" | "E_UNDO_NOT_RECORDED" | "E_UNKNOWN" | "E_LARGE_FILE" | "E_UNSERVED_RANGE" | "E_BLIND_REPLACE" | "E_UNSUPPORTED" | "E_BAD_COMMAND" | "E_FILE_EXISTS" | "E_NO_MATCH" | "E_AMBIGUOUS_MATCH" | "E_STORE_NEWER_VERSION";
70
+ /**
71
+ * Applied-tier warning codes. A `[W_*]` line reports an applied mutation;
72
+ * `[E_*]` reports a rejection. `formatWarning` is the sole producer of
73
+ * `[W_*]` headers and `formatError` the sole composer of `[E_*]` headers:
74
+ * no raw `[E_*]`/`[W_*]` header literal may exist outside this module
75
+ * (asserted in test/arch/domain-error-registry.test.ts).
76
+ */
77
+ export type DomainWarningCode = "W_NEVER_SERVED_SHAPE" | "W_SERVED_PREFIX_MISMATCH" | "W_REVERSED_ANCHORS" | "W_UNICODE_LITERAL" | "W_LITERAL_BYPASS" | "W_NOOP";
78
+ export interface ErrorPayloadMap {
79
+ E_BAD_PAYLOAD: {
80
+ message: string;
81
+ };
82
+ E_EMPTY_RANGE: Record<string, never>;
83
+ E_STALE_ANCHOR: {
84
+ headline: string;
85
+ servedRows?: ServedRow[];
86
+ servedBlock?: string;
87
+ cause?: RangeCause;
88
+ };
89
+ E_UNKNOWN_ANCHOR: {
90
+ path: string;
91
+ anchors: string[];
92
+ };
93
+ E_FOREIGN_ANCHOR: {
94
+ path: string;
95
+ anchors: string[];
96
+ homes: string[];
97
+ };
98
+ E_STALE_RANGE: {
99
+ headline: string;
100
+ servedRows: ServedRow[];
101
+ servedBlock: string;
102
+ cause?: RangeCause;
103
+ firstOffendingLine?: number;
104
+ };
105
+ E_TARGET_LOST: {
106
+ servedLine: number;
107
+ path?: string;
108
+ cause: RangeCause;
109
+ firstOffendingLine?: number;
110
+ };
111
+ E_UNVERIFIED_RANGE: {
112
+ servedRows: ServedRow[];
113
+ servedBlock: string;
114
+ cause: RangeCause;
115
+ firstOffendingLine?: number;
116
+ };
117
+ E_MALFORMED_ANCHOR: {
118
+ rawAnchor: string;
119
+ reason: string;
120
+ };
121
+ E_SUSPICIOUS_TEXT: {
122
+ target: "edit" | "write";
123
+ path: string;
124
+ line: number;
125
+ hash: string;
126
+ servedLine: number;
127
+ /**
128
+ * Submission tally. Optional: the edit/write producers hold no tally
129
+ * state, so they omit it and the refusal renders without the submission
130
+ * clause. Present only when a caller tracks resubmissions.
131
+ */
132
+ count?: number;
133
+ };
134
+ E_BATCH_ABORT: {
135
+ /** First failing item: routes the typed path and keeps the single-failure envelope byte-identical. */
136
+ index: number;
137
+ path: string;
138
+ /** The first failing item's inner failure message (already header-bearing). */
139
+ inner: string;
140
+ /**
141
+ * Range context for the failed item: either the current on-disk range
142
+ * block or the "Call read()…" fallback. Empty when no range context
143
+ * exists (non-anchor failures) — the merge hint is omitted with it.
144
+ */
145
+ echoBlock: string;
146
+ /**
147
+ * Every failing item in order; present only when more than one failed
148
+ * (C: one resubmission fixes every failure). Each item keeps its own
149
+ * `[E_*]` inline in `inner`.
150
+ */
151
+ failures?: Array<{
152
+ index: number;
153
+ inner: string;
154
+ }>;
155
+ /** Union of every failing item's rows, in item order. */
156
+ servedRows: ServedRow[];
157
+ /** Every failing item's block joined in item order ("" when none). */
158
+ servedBlock: string;
159
+ /** Carried only when every failing item agrees on one diagnosis. */
160
+ cause?: RangeCause;
161
+ };
162
+ E_NOOP_LOOP: {
163
+ ref: string;
164
+ anchorFrom: string;
165
+ anchorTo: string;
166
+ count: number;
167
+ batch: boolean;
168
+ servedBlock: string;
169
+ /**
170
+ * Present on engine single rejects: the display path ("in <path>" flavor).
171
+ * The batch ref already names the item, so no index is needed.
172
+ */
173
+ path?: string;
174
+ };
175
+ E_UNSUPPORTED_FILE: {
176
+ path: string;
177
+ kind: "directory" | "binary" | "image";
178
+ description?: string;
179
+ };
180
+ E_ACCESS: {
181
+ path: string;
182
+ kind: "denied" | "symlink-loop" | "unreachable";
183
+ access?: "read" | "write";
184
+ };
185
+ E_NOT_FOUND: {
186
+ path: string;
187
+ };
188
+ E_UNDO_STALE: {
189
+ path: string;
190
+ reason?: "deleted" | "modified";
191
+ };
192
+ E_UNDO_UNAVAILABLE: {
193
+ path: string;
194
+ batch?: boolean;
195
+ };
196
+ E_UNDO_NOT_RECORDED: {
197
+ path: string;
198
+ };
199
+ E_UNKNOWN: {
200
+ errorName: string;
201
+ message: string;
202
+ };
203
+ E_LARGE_FILE: {
204
+ path?: string;
205
+ limitKind: "lines" | "hash-space";
206
+ lineCount?: number;
207
+ limit: number;
208
+ };
209
+ E_UNSERVED_RANGE: {
210
+ headline: string;
211
+ servedRows: ServedRow[];
212
+ servedBlock: string;
213
+ unservedKind: "boundary" | "interior";
214
+ firstOffendingLine?: number;
215
+ cause?: RangeCause;
216
+ };
217
+ E_BLIND_REPLACE: {
218
+ path: string;
219
+ /** The tool whose observation gate fired: the shadow or the write policy. */
220
+ command: string;
221
+ };
222
+ E_UNSUPPORTED: {
223
+ /** The known-but-unimplemented command (undo_edit). */
224
+ command: string;
225
+ };
226
+ E_BAD_COMMAND: {
227
+ /** The unknown command value (any JSON value the caller sent). */
228
+ command: unknown;
229
+ };
230
+ E_FILE_EXISTS: {
231
+ path: string;
232
+ };
233
+ E_NO_MATCH: {
234
+ path: string;
235
+ };
236
+ E_AMBIGUOUS_MATCH: {
237
+ path: string;
238
+ matches: number;
239
+ };
240
+ E_STORE_NEWER_VERSION: {
241
+ path: string;
242
+ storedVersion: number;
243
+ supportedVersion: number;
244
+ };
245
+ }
246
+ export interface CodeSpec<P> {
247
+ audience: Audience;
248
+ format: (payload: P) => string;
249
+ remedy?: string;
250
+ }
251
+ export declare function numericAnchorNote(anchors: string[]): string;
252
+ /** SAFETY: exact heading for an unverified fresh-read serve — machine-checkable. */
253
+ export declare const FRESH_READ_HEADING = "Current range (fresh read):";
254
+ /** SAFETY: one general headline clause for an unplaceable bound — no narration. */
255
+ export declare const UNVERIFIED_HEADLINE = "a bound of this range no longer resolves to the line identity it was served with.";
256
+ /** SAFETY: recovery sentence for a target-lost rejection — the only retry is a read. */
257
+ export declare const TARGET_LOST_RECOVERY = "The line you targeted was deleted or replaced; your anchors describe a version of this file that no longer exists. Read the file and re-target.";
258
+ export declare const ERROR_REGISTRY: {
259
+ [K in DomainErrorCode]: CodeSpec<ErrorPayloadMap[K]>;
260
+ };
261
+ export interface WarningPayloadMap {
262
+ W_NEVER_SERVED_SHAPE: {
263
+ count: number;
264
+ };
265
+ W_SERVED_PREFIX_MISMATCH: {
266
+ k: number;
267
+ anchor: string;
268
+ servedLine: number;
269
+ };
270
+ W_REVERSED_ANCHORS: {
271
+ fromHash: string;
272
+ toHash: string;
273
+ };
274
+ W_UNICODE_LITERAL: {
275
+ line: number;
276
+ };
277
+ W_LITERAL_BYPASS: Record<string, never>;
278
+ W_NOOP: {
279
+ ref: string;
280
+ anchorFrom: string;
281
+ anchorTo: string;
282
+ batch: boolean;
283
+ count: number;
284
+ /** Present on engine single warns: the display path ("in <path>" flavor). */
285
+ path?: string;
286
+ };
287
+ }
288
+ export declare const WARNING_REGISTRY: {
289
+ [K in DomainWarningCode]: CodeSpec<WarningPayloadMap[K]>;
290
+ };
291
+ /**
292
+ * SAFETY: the sole producer of `[W_*]` headers. Renders
293
+ * `[<AUDIENCE>] [<W_CODE>] <neutral-observation>` from the registry, so every
294
+ * applied-tier warning carries its machine-readable code and audience by
295
+ * construction.
296
+ *
297
+ * PURE by contract (T6 CP2, F2): a formatter carries no state. The deferral
298
+ * witnesses below are INJECTED (`AllowlistTrigger.holds(fired)`), never accumulated —
299
+ * a module-global "did it fire?" latch made a guard's verdict depend on whether an
300
+ * earlier test happened to render the warning, so a witness satisfiable by another
301
+ * test's side effect proved nothing about the guard that consumed it. The witness is
302
+ * derived by the test layer from a source scan (`test/support/arch-scan.ts`,
303
+ * `firedWarnings`) — a READ, so the verdict is a pure function of the tree and cannot
304
+ * depend on evaluation order or on a test-only reset hook.
305
+ */
306
+ export declare function formatWarning<K extends DomainWarningCode>(code: K, payload: WarningPayloadMap[K]): string;
307
+ /**
308
+ * SAFETY: the sole composer of `[TO <AUDIENCE>] [<E_CODE>]` prefixes for errors.
309
+ * `DomainError` delegates here, so header construction has exactly one site.
310
+ */
311
+ export declare function formatError<K extends DomainErrorCode>(code: K, payload: ErrorPayloadMap[K]): string;
312
+ export declare class DomainError<K extends DomainErrorCode = DomainErrorCode> extends Error {
313
+ readonly code: K;
314
+ readonly audience: Audience;
315
+ readonly payload: ErrorPayloadMap[K];
316
+ readonly servedRows: ServedRow[];
317
+ readonly servedBlock: string;
318
+ readonly cause?: RangeCause;
319
+ readonly firstOffendingLine?: number;
320
+ readonly details: {
321
+ cause?: RangeCause;
322
+ code: K;
323
+ };
324
+ constructor(code: K, payload: ErrorPayloadMap[K]);
325
+ }
326
+ export declare function isDomainErrorCode(code: unknown): code is DomainErrorCode;
327
+ /** Warning analogue of `isDomainErrorCode`: only registry members qualify. */
328
+ export declare function isDomainWarningCode(code: unknown): code is DomainWarningCode;
329
+ /**
330
+ * A trigger must be CHECKABLE, not a phrase. `text` names the artifact whose
331
+ * change makes this entry actionable — a queue line (`Q-T<n>`), an issue
332
+ * (`#NN`), an absorb branch (`absorb/<branch>`), or a `src/` path — and
333
+ * `holds(fired)` is a predicate that must remain true while the entry exists. The
334
+ * witness is INJECTED, never read from module state: production carries no latch, so
335
+ * the same source yields the same verdict in any evaluation order (T6 CP2, F2). The
336
+ * arch oracle supplies its own, independently derived witness and asserts both
337
+ * (`AllowlistEntry` is the two-referents rule in type form; see
338
+ * `test/support/arch-scan.ts`).
339
+ */
340
+ export interface AllowlistTrigger {
341
+ readonly text: string;
342
+ /** `fired` = codes whose producer became visible to the caller's witness scan. */
343
+ readonly holds: (fired: ReadonlySet<string>) => boolean;
344
+ }
345
+ /**
346
+ * An allowlist entry. `owner` must be an ADDRESSABLE identity — **a bare `T6` is
347
+ * not an identity**: `docs/absorption-plan.md:35` gives T6 to the README+CONTEXT
348
+ * merge while the T4 brief gives it to multi-window read, so the id collides
349
+ * across lanes (T4 CP1-r5 G7).
350
+ */
351
+ export interface AllowlistEntry {
352
+ readonly owner: string;
353
+ readonly trigger: AllowlistTrigger;
354
+ }
355
+ /** Owners and trigger texts must start with one of these addressable forms. */
356
+ export declare const ADDRESSABLE_OWNER_RE: RegExp;
357
+ /**
358
+ * Registry fields that are declared but never rendered, keyed by field name.
359
+ * `owner`/`trigger` are identities (see `AllowlistEntry`); the arch oracle pins
360
+ * this map by identity against its own copy **and** independently computes the
361
+ * "still declaration-only" predicate (0 readers of `.<field>` across `src/`).
362
+ */
363
+ export declare const DECLARATION_ONLY_FIELDS: Readonly<Record<string, AllowlistEntry>>;
364
+ /**
365
+ * Codes declared by the contract but produced by a later ticket. Shrink-only:
366
+ * a code that gains a producer MUST be removed from this map (the arch oracle
367
+ * fails otherwise).
368
+ *
369
+ * Upstream parity is NOT a reason to keep a code nothing can produce — and it
370
+ * is not a reason to hide one either. T4 (CP1-r3) removed four declarations
371
+ * that had zero local producers, zero reachable messages and no nameable local
372
+ * owner. FU-4 (absorb/follow-upstream, upstream `pi-better-edit@b92e0ec`)
373
+ * re-introduced all four WITH their producers — per-code decision: **adopt the
374
+ * upstream diagnostic** (the alternative, mapping onto `E_STALE_RANGE` /
375
+ * `E_UNSERVED_RANGE`, is what ADR-0022 recorded and what this absorb
376
+ * supersedes):
377
+ *
378
+ * | ported upstream diagnostic | upstream producer (pi-better-edit@b92e0ec) | local producer |
379
+ * |---|---|---|
380
+ * | `E_FOREIGN_ANCHOR` | `lease-resolve.ts:116` | `anchor-pipeline.ts` (`throwUnknownOrForeign`, boundary placement) |
381
+ * | `E_UNKNOWN_ANCHOR` | `lease-resolve.ts:118`, `served-verification.ts:745` | `anchor-pipeline.ts` (boundary placement, pre-gate) |
382
+ * | `E_UNVERIFIED_RANGE` | `lease-resolve.ts:186`, `served-verification.ts:187` | `anchor-pipeline.ts` (pre-gate stale-boundary arm) |
383
+ * | `E_TARGET_LOST` | `served-verification.ts:170`, `lease-resolve.ts:196` | `anchor-pipeline.ts` (pre-gate stale-boundary arm) |
384
+ *
385
+ * Their owner is `"upstream absorb"` and their trigger is the absorb that
386
+ * ports the corresponding producer. When that happens, reintroduce the code
387
+ * WITH its producer: the union member is gone, so the port will not compile
388
+ * until the absorber records a per-code decision (adopt the upstream
389
+ * diagnostic, or map it onto `E_STALE_RANGE` / `E_UNSERVED_RANGE` /
390
+ * `E_STALE_ANCHOR`). `docs/absorption-plan.md` ("Debt — T4 …") carries the
391
+ * same record for the next absorb.
392
+ *
393
+ * ── IDENTITY, NOT SHAPE (T4 CP1-r4/r5; T6 R15) ──
394
+ * `owner` and `trigger.text` below are pinned BY IDENTITY in
395
+ * `test/arch/domain-error-registry.test.ts` (C7/C16), so changing one is a
396
+ * deliberate edit that must touch the test — never a silent one. T6 replaced the
397
+ * lane-letter owner (`Q-T6`) with the addressable producer seam, and the
398
+ * `holds: () => isDomainWarningCode(…)` with a predicate over an INJECTED witness:
399
+ * `holds(fired)` is false exactly when a producer for that code is visible to the
400
+ * caller's scan (T6 CP2 F2). Production keeps no state, so the verdict cannot be
401
+ * satisfied by another test's earlier firing — the defect the first form had. The arch
402
+ * oracle derives the witness from source (a read) and recomputes the same producer scan
403
+ * as its independent second referent.
404
+ *
405
+ * FU-5 (absorb/follow-upstream, upstream `pi-better-edit@b92e0ec` §4.7) landed the
406
+ * two deferred `W_*` producers in `src/hashline/served-guard.ts` — per the shrink-only
407
+ * rule above both entries are removed. The map is empty; the mechanism and the
408
+ * identity pins stay for the next deferral.
409
+ */
410
+ export declare const DEFERRED_PRODUCERS: Readonly<Record<string, AllowlistEntry>>;
@@ -1,7 +1,7 @@
1
1
  import type { ServedRow } from "./hashline/anchor-pipeline.js";
2
2
  export type EditDetails = {
3
3
  diff: string;
4
- /** Bare `E_*` code for the primary error signal, if any (no `[MODEL]` prefix). Structured counterpart to message-string codes. */
4
+ /** Bare `E_*` code for the primary error signal, if any (no `[TO MODEL]` prefix). Structured counterpart to message-string codes. */
5
5
  errCode?: string;
6
6
  /** Disambiguator for `E_UNSERVED_RANGE`: boundary miss vs interior hole. */
7
7
  unservedKind?: "boundary" | "interior";
@@ -30,6 +30,7 @@ export declare function setAutoGuessFooter(targetKey: string, footer: string): v
30
30
  export declare function clearAutoGuessFooter(targetKey?: string): void;
31
31
  /** Invalidate memo when FsVersion drifted (ADR-0012). */
32
32
  export declare function invalidateIfStale(targetKey: string, currentVersion: string | undefined): void;
33
+ export declare function buildTop3Description(candidates: CandidatePreview[]): string;
33
34
  export declare function buildTop3ErrorMessage(displayPath: string, candidates: CandidatePreview[]): string;
34
35
  export interface DecodeAdmissionConfig {
35
36
  autoGuessEncoding: boolean;
@@ -24,6 +24,7 @@ import type { HashStore } from "./hash-store.js";
24
24
  export declare const MAX_HASH_LINES: number;
25
25
  export declare const DEFAULT_MAX_LINES = 2000;
26
26
  export declare const DEFAULT_MAX_BYTES: number;
27
+ export declare const MAX_READ_WINDOWS = 16;
27
28
  export interface TruncationResult {
28
29
  content: string;
29
30
  truncated: boolean;
@@ -42,16 +43,25 @@ export declare function truncateHead(content: string, options?: {
42
43
  maxLines?: number;
43
44
  maxBytes?: number;
44
45
  }): TruncationResult;
46
+ /** Snapshot identity and size: the only `fs.Stats` fields this codebase reads. */
47
+ export interface FileStats {
48
+ ino: number;
49
+ size: number;
50
+ mtimeMs: number;
51
+ ctimeMs: number;
52
+ }
53
+ export interface LFileText {
54
+ kind: "text";
55
+ text: string;
56
+ stats?: FileStats;
57
+ hadUtf8DecodeErrors?: true;
58
+ }
45
59
  export type LFile = {
46
60
  kind: "directory";
47
61
  } | {
48
62
  kind: "image";
49
63
  mimeType: string;
50
- } | {
51
- kind: "text";
52
- text: string;
53
- hadUtf8DecodeErrors?: true;
54
- } | {
64
+ } | LFileText | {
55
65
  kind: "binary";
56
66
  description: string;
57
67
  };
@@ -81,7 +91,7 @@ export type SnapInfo = {
81
91
  ctimeMs: number;
82
92
  size: number;
83
93
  };
84
- export declare function fileSnap(absolutePath: string): Promise<SnapInfo>;
94
+ export declare function fileSnap(absolutePath: string, preloadedStats?: FileStats): Promise<SnapInfo>;
85
95
  export interface ReadNormOptions {
86
96
  signal?: AbortSignal;
87
97
  accessMode?: number;
@@ -115,10 +125,27 @@ export declare function normFromText(input: {
115
125
  };
116
126
  }): Promise<NormFile>;
117
127
  export declare function readNormFile(path: string, cwd: string, options?: ReadNormOptions): Promise<NormFile>;
128
+ /** One requested line range of a multi-window read (FU-6, port of pi-better-edit@2334352). */
129
+ export interface ReadWindow {
130
+ offset: number;
131
+ limit: number;
132
+ }
133
+ /**
134
+ * The windows rule, owned here so the preview and the serve-side full-read contract
135
+ * cannot disagree: `undefined` and `[]` both mean "no windows" — the caller falls back to the
136
+ * single-window `offset`/`limit` contract, so an empty array stays backward compatible.
137
+ *
138
+ * WHY (moved with the rule from read-and-serve): `windows: []` falls back to a
139
+ * full read in the preview, so the full-read contract has to follow the same rule — otherwise an
140
+ * empty array silently skips the drift clear that a full read owes. A non-empty multi-window
141
+ * read serves sparse rows, never the full file.
142
+ */
143
+ export declare function hasRequestedWindows(windows: readonly ReadWindow[] | undefined): windows is readonly ReadWindow[];
118
144
  export declare function formatPaginationHint(startLine: number, endLine: number, totalLines: number, nextOffset: number, byteLimit?: number): string;
119
145
  export declare function fmtReadPreview(text: string, options: {
120
146
  offset?: number;
121
147
  limit?: number;
148
+ windows?: ReadWindow[];
122
149
  }, precomputedHashes?: string[], path?: string, maxLineBytes?: number, maxTruncLines?: number): Promise<{
123
150
  text: string;
124
151
  truncation?: TruncationResult;
@@ -140,6 +167,8 @@ export interface FileView {
140
167
  export interface PreviewOpts {
141
168
  offset?: number;
142
169
  limit?: number;
170
+ /** FU-6 (2334352): disjoint ranges in one call; wins over offset/limit when non-empty. */
171
+ windows?: ReadWindow[];
143
172
  }
144
173
  export interface ReadViewOpts extends PreviewOpts {
145
174
  encoding?: string;
@@ -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>;