dsh-better-edit 0.8.1 → 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 +162 -97
  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 +2 -2
  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 +59 -24
  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 +10 -4
  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
@@ -14,8 +14,9 @@
14
14
  * hash-store persistence delegation (ServedPersistence).
15
15
  *
16
16
  * Ownership: This file OWNS the served-merge invariant
17
- * (_mergeServedRows with orphan healing per ADR-0008), the
18
- * position-reconstruction math, and the drift computation. Deleting
17
+ * (_mergeServedRows — exact-write: a hash written at a new position leaves the
18
+ * old slot intact, and a duplicate is rejected at verification rather than
19
+ * healed), the position-reconstruction math, and the drift computation. Deleting
19
20
  * it would scatter the served+drift invariant across 4 files — it
20
21
  * concentrates (deep).
21
22
  *
@@ -32,9 +33,11 @@ export type ServedEntry = {
32
33
  /**
33
34
  * Merge served rows into a copy of the stored array. This single helper owns
34
35
  * the served-merge invariant shared by recordServed and recordServedTruncated.
35
- * Eagerly heals orphaned serves: if the same hash is written at a new position
36
- * the old position is nulled (O(n) scan, no extra I/O). This prevents a
37
- * partial re-serve from leaving a stale duplicate behind (ADR-0008).
36
+ *
37
+ * Exact-write rule (ADR-0018, superseding ADR-0004): a hash written at a new position
38
+ * leaves the old position INTACT — the old slot is not nulled and no look-alike is
39
+ * rebound. A duplicate is detected at verification time (`verifyServedRange`) and
40
+ * rejects as `E_UNSERVED_RANGE` instead of being healed here.
38
41
  */
39
42
  export declare function _mergeServedRows(current: (string | null)[], rows: ServedEntry[], options?: {
40
43
  truncateTo?: number;
@@ -44,7 +47,6 @@ export declare function loadServed(sessionKey: string, path: string): Promise<(s
44
47
  /** Anchors that must not be allocated while any session can still remember them. */
45
48
  export declare function loadAnchorReservations(sessionKey: string, path: string): Promise<AnchorReservations>;
46
49
  export declare function loadServedCanons(sessionKey: string, path: string): Promise<(string | null)[]>;
47
- export declare function loadEpochSnapshotId(sessionKey: string, path: string): Promise<string | undefined>;
48
50
  export declare function loadRetiredAnchors(sessionKey: string, path: string): Promise<Set<string>>;
49
51
  /** Keep freed anchors dead for this session until it has seen the whole file again. */
50
52
  export declare function retireAnchors(sessionKey: string, path: string, hashes: Iterable<string>): Promise<void>;
@@ -52,10 +54,37 @@ export declare function retireAnchors(sessionKey: string, path: string, hashes:
52
54
  export interface FullReadContext {
53
55
  hashes: readonly string[];
54
56
  canons?: readonly (string | null)[];
55
- snapshotId?: string;
57
+ /**
58
+ * Full content the hashes were computed from. When present (with `hashes`),
59
+ * recordServed also materializes-or-adopts the serve snapshot and grants
60
+ * leases for `rows` as-is through the store's single transaction.
61
+ */
62
+ content?: string;
56
63
  }
57
- export declare function recordServed(sessionKey: string, path: string, rows: ServedEntry[], lineCount?: number, full?: FullReadContext): Promise<void>;
58
- export declare function recordServedTruncated(sessionKey: string, path: string, rows: ServedEntry[], lineCount: number, clearFrom?: number, fullCanons?: readonly (string | null)[]): Promise<void>;
64
+ /** Serve-snapshot context for lease granting: content parallel to `hashes`. */
65
+ export interface ServeSnapshot {
66
+ content: string;
67
+ hashes: readonly string[];
68
+ }
69
+ /**
70
+ * Record a serve — the `served` row merge and the lease grant derived from it — as ONE unit, and
71
+ * report whether it landed.
72
+ *
73
+ * `false` means the write rolled back and no lease was granted, so the caller must not advertise
74
+ * the rows' anchors as usable: that is a partial failure of the caller's operation, not a failed
75
+ * operation. The best-effort contract is unchanged — this never throws.
76
+ */
77
+ export declare function recordServed(sessionKey: string, path: string, rows: ServedEntry[], lineCount?: number, full?: FullReadContext): Promise<boolean>;
78
+ /**
79
+ * Record a truncated serve — the `served` row merge and the lease grant derived from it — as ONE
80
+ * unit, and report whether it landed.
81
+ *
82
+ * `false` means the write rolled back and no lease was granted, so the caller must not advertise
83
+ * the rows' anchors as usable: that is a partial failure of the caller's operation, not a failed
84
+ * operation. The best-effort contract is unchanged — this never throws; the callers decide what
85
+ * to advertise.
86
+ */
87
+ export declare function recordServedTruncated(sessionKey: string, path: string, rows: ServedEntry[], lineCount: number, clearFrom?: number, fullCanons?: readonly (string | null)[], serveSnapshot?: ServeSnapshot): Promise<boolean>;
59
88
  export declare function driftReported(sessionKey: string, path: string): Promise<Set<string>>;
60
89
  export declare function markDriftReported(sessionKey: string, path: string, hashes: string[]): Promise<void>;
61
90
  export declare function clearDriftReported(sessionKey: string, path: string): Promise<void>;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The `snapshots` table's sole owner: storage detail (SQL, row encoding,
3
+ * hash validation, busy-retry) hides behind a narrow domain interface.
4
+ *
5
+ * Read-order contract: `get` returns hashes in line order (index *i* ↔ line
6
+ * *i* + 1). Storage is a line-ordered JSON array by construction; this module
7
+ * never sorts, reverses or otherwise reorders it — a normalized read must
8
+ * preserve the same contract (e.g. `ORDER BY line_number ASC`).
9
+ * The retention surface (`vacuum.ts`) is re-exported here so consumers never reach into the
10
+ * eviction module directly. See also `./vacuum.js` for the policy constants.
11
+ * @module dsh-better-edit/snapshot-store
12
+ */
13
+ import { DatabaseSync } from "node:sqlite";
14
+ export declare function isValidHashList(value: unknown): value is string[];
15
+ export interface SnapshotStore {
16
+ get(path: string, content: string, deleteCorrupt?: boolean): string[] | undefined;
17
+ upsert(path: string, checksum: string, lineCount: number, hashes: string[]): void;
18
+ allHashes(): {
19
+ path: string;
20
+ hashes: string;
21
+ }[];
22
+ deleteByPath(path: string): void;
23
+ findPathsContaining(hashes: string[]): string[];
24
+ }
25
+ export declare function createSnapshotStore(db: DatabaseSync): SnapshotStore;
26
+ export { reportVacuum, vacuumSnapshots } from "./vacuum.js";
27
+ export type { VacuumOptions, VacuumResult } from "./vacuum.js";
28
+ export { VACUUM_GLOBAL_BUDGET_BYTES, VACUUM_SOFT_OVERFLOW_BYTES, VACUUM_PER_PATH_BUDGET_BYTES, VACUUM_MAX_SNAPSHOTS_PER_PATH, VACUUM_MIN_SNAPSHOTS_PER_PATH, VACUUM_LINEAGE_BYTES_PER_LINE, VACUUM_RETIRED_PIN_MS, REPORT_CONTEXT_CAP, } from "./vacuum.js";
@@ -0,0 +1,96 @@
1
+ /**
2
+ * v7 identity substrate: the single owner of `file_snapshots`, `line_lineage`,
3
+ * `line_id_counters` and the `served_leases` write path. Co-location is
4
+ * deliberate: a snapshot, its lineage and the leases bound to it commit as one
5
+ * unit, so a crash can never leave leases pointing at a snapshot that was
6
+ * never recorded (or lineage without its snapshot row).
7
+ *
8
+ * Transaction semantics: `commitSnapshot` runs adopt-or-insert plus the lease
9
+ * grant inside the store's single re-entrant transaction owner
10
+ * (`snapshot-store/txn.ts`). Outermost it opens ONE `BEGIN IMMEDIATE`; nested it
11
+ * joins the caller's unit, so a failure rolls the whole unit back and propagates.
12
+ * Retry policy: the owner retries only the BEGIN/COMMIT acquisitions, so every
13
+ * `.run` below carries its own `withBusyRetry` — matching `hash-store`'s `stmts`
14
+ * wrappers and `snapshot-store/index.ts`. A transient SQLITE_BUSY on any lineage
15
+ * statement retries instead of aborting the unit.
16
+ *
17
+ * Pairing rule (deterministic): a new snapshot's lines inherit `line_id`s from the path's
18
+ * latest committed snapshot via the scaled recursive patience engine in `./pairing.js` —
19
+ * locally unique canons pin, the minimal-displacement LIS backbone pairs, pinless rigid
20
+ * runs zip positionally, and a bounded leaf interval pairs only on a UNIQUE optimal LCS
21
+ * embedding. Anything the engine cannot prove moved — a duplicate canon, a contested
22
+ * reorder, an over-budget interval — pairs nothing and takes a fresh id. That is
23
+ * fail-closed on purpose: a guessed inheritance would rebind a lease onto a look-alike
24
+ * line. No previous snapshot for the path → every line fresh.
25
+ *
26
+ * @module dsh-better-edit/snapshot-store/lineage-store
27
+ */
28
+ import { DatabaseSync } from "node:sqlite";
29
+ export declare function snapshotHashFor(content: string): string;
30
+ /**
31
+ * A snapshot row whose lineage is missing or malformed. The adopt arm *diagnoses* with this
32
+ * (CP2): an unusable family is discarded and re-materialized fresh, observably, instead of
33
+ * throwing — a permanent throw is what pinned a path into a lease-less state.
34
+ */
35
+ export declare class LineageCorruptError extends Error {
36
+ constructor(message: string);
37
+ }
38
+ export interface CommitLeases {
39
+ sessionKey: string;
40
+ rows: ReadonlyArray<{
41
+ position: number;
42
+ hash: string | null;
43
+ }>;
44
+ }
45
+ export interface CommitSnapshotInput {
46
+ /** Canonical content actually served/hashed. */
47
+ path: string;
48
+ content: string;
49
+ /** Anchors, parallel to splitLines(content). */
50
+ hashes: string[];
51
+ leases?: CommitLeases;
52
+ }
53
+ export interface LineageRow {
54
+ lineNumber: number;
55
+ lineId: number;
56
+ canonHash: string;
57
+ anchor: string;
58
+ }
59
+ export interface LeaseRow {
60
+ lineId: number;
61
+ canonHash: string;
62
+ snapshotHash: string;
63
+ lineNumber: number;
64
+ retiredAt: number | null;
65
+ }
66
+ export interface LineageStore {
67
+ /** Create-or-adopt (path, snapshotHash) and grant leases in ONE BEGIN IMMEDIATE. */
68
+ commitSnapshot(input: CommitSnapshotInput): void;
69
+ lineageFor(path: string, snapshotHash: string): LineageRow[];
70
+ /**
71
+ * `line_id` -> current line number for `content` — the identity map the edit path resolves a
72
+ * leased line through (CP2-r1). Prefers the committed lineage of `content`; otherwise pairs the
73
+ * latest committed snapshot against `content` with the pairing engine, in memory. READ-ONLY: no
74
+ * snapshot row, no `served_leases` write, no retirement stamp — retirement belongs to
75
+ * materialization, never to resolution.
76
+ */
77
+ positionsByIdentity(path: string, content: string): Map<number, number>;
78
+ leaseFor(sessionKey: string, path: string, anchor: string): LeaseRow | undefined;
79
+ /**
80
+ * Other files this session has served one anchor for, excluding `excludePath` (the file being
81
+ * edited) — the `(session_id, anchor)` lookup behind `E_FOREIGN_ANCHOR`. Failure-path only:
82
+ * the edit path calls it exactly when a boundary lease misses. READ-ONLY.
83
+ */
84
+ leaseHomes(sessionKey: string, excludePath: string, anchor: string): string[];
85
+ /**
86
+ * The committed `file_snapshots.snapshot_id` for `(path, snapshotHash)`, or undefined when no
87
+ * such row exists. The vacuum trigger resolves its in-flight protection id through this, since
88
+ * the materialization path never learns the inserted id itself.
89
+ */
90
+ snapshotIdFor(path: string, snapshotHash: string): number | undefined;
91
+ /** Delete a path's whole lineage family (snapshots, lineage, counters, leases). */
92
+ deleteByPath(path: string): void;
93
+ }
94
+ /** Canonical DDL for the four lineage-owned tables (IF NOT EXISTS, additive). */
95
+ export declare function ensureLineageTables(db: DatabaseSync): void;
96
+ export declare function createLineageStore(db: DatabaseSync): LineageStore;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Legacy pre-SQLite JSON file import (`hash-store.json` → `snapshots` shell).
3
+ * Moved verbatim from `hash-store.ts`: same validity rules, same messages,
4
+ * same best-effort I/O handling, same transaction shape, same `.bak` rename.
5
+ * The legacy path stays the caller's business: `openStore` resolves it
6
+ * tenant-aware via `join(dirname(storePath), "hash-store.json")` and passes
7
+ * it in, so this module never touches tenancy or `hash-store`.
8
+ * @module dsh-better-edit/snapshot-store/migrate
9
+ */
10
+ import { DatabaseSync } from "node:sqlite";
11
+ export interface LegacySnapshot {
12
+ content: string;
13
+ hashes: string[];
14
+ }
15
+ export declare function isValidSnapshot(value: unknown): value is LegacySnapshot;
16
+ export declare function migrateLegacyStore(db: DatabaseSync, legacyPath: string): Promise<void>;
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Scaled recursive patience pairing (spec §5.2): aligns a previous snapshot's lines to the
3
+ * current snapshot's lines so `line_id`s survive reorders, inserts, and deletes.
4
+ *
5
+ * The engine has four phases, all fail-closed: an ambiguous interval pairs nothing rather
6
+ * than guessing coordinates.
7
+ *
8
+ * 1. Locally unique canon anchors become candidate pins (`findUniquePins`).
9
+ * 2. The candidate pins' minimal-displacement LIS backbone is their unconditional
10
+ * intersection across every maximum-length, minimum-Δ subsequence
11
+ * (`findStablePinBackbone`, two-pass DP over patience-sorted ranks).
12
+ * 3. Pinless rigid runs with identical canon sequences zip pairwise (Probe N).
13
+ * 4. Bounded leaf intervals align on a unique LCS embedding only: a pairing is emitted when
14
+ * it lies on every maximal traceback path, so an interval with several optimal pairings
15
+ * stays UNPAIRED / RETIRED.
16
+ *
17
+ * When the backbone is empty the interval falls straight through to leaf handling: the
18
+ * engine never recurses on identical bounds, so alignment cannot starve the scan budget.
19
+ *
20
+ * Invariant: `prevLines` and `currLines` are contiguous ascending 1-based line numbers
21
+ * (spec §5.2 descriptor shape), so a descriptor's index + 1 is its line number.
22
+ *
23
+ * @module dsh-better-edit/snapshot-store/pairing
24
+ */
25
+ export interface LineDescriptor {
26
+ lineNumber: number;
27
+ canonHash: string;
28
+ }
29
+ export interface AnchorPin {
30
+ prevLine: number;
31
+ currLine: number;
32
+ }
33
+ export interface PairingOptions {
34
+ /**
35
+ * WHY: production callers omit this so the dynamic `MAX(100000, 4*(prev+curr))` guard
36
+ * WHY: applies; tests inject a tiny budget to prove the guard halts alignment instead of
37
+ * WHY: silently recursing past it.
38
+ */
39
+ scanBudget?: number;
40
+ }
41
+ interface LcsAlignment {
42
+ /** True only when the interval has exactly one maximum pairing, i.e. every optimal pair is forced. */
43
+ isUnique: boolean;
44
+ pairs: [number, number][];
45
+ }
46
+ /** Dynamic scan budget: `MAX(100000, 4 * (prevLines + currLines))` (spec §5.1/§5.2). */
47
+ export declare function pairingScanBudget(prevCount: number, currCount: number): number;
48
+ /**
49
+ * Candidate Anchor Pins: a canon that occurs exactly once in `prev[pStart..pEnd]` and
50
+ * exactly once in `curr[cStart..cEnd]` (spec §3.4.1). Every other line is duplicated or
51
+ * absent on one side, so pairing it would guess.
52
+ */
53
+ export declare function findUniquePins(prevLines: LineDescriptor[], currLines: LineDescriptor[], pStart: number, pEnd: number, cStart: number, cEnd: number): AnchorPin[];
54
+ /**
55
+ * Unconditional intersection of every maximum-length, minimum-displacement increasing
56
+ * subsequence of `pins` (spec §3.4.3). Pins arrive sorted by ascending `prevLine`; the
57
+ * backward pass mirrors the forward pass over negated `currLine` coordinates.
58
+ *
59
+ * A pin belongs to the intersection iff it lies on a minimal-displacement LIS *and* no
60
+ * other minimal-displacement pin shares its rank — otherwise a competing optimal
61
+ * subsequence could bypass it.
62
+ */
63
+ export declare function findStablePinBackbone(pins: AnchorPin[]): AnchorPin[];
64
+ /**
65
+ * Bounded leaf alignment (spec §3.4.4). Uniqueness is **embedding-level**: a pairing survives
66
+ * only when it lies on every maximal traceback path, and an interval with more than one maximum
67
+ * pairing pairs nothing (its lines stay UNPAIRED / RETIRED).
68
+ *
69
+ * `pairingCount` is the exact number of maximum pairings (embeddings) of the optimal LCS in the
70
+ * sub-interval, capped at 2 so the decision stays polynomial. It deliberately counts neither
71
+ * distinct canon strings nor DP orderings:
72
+ * - A repeated canon that can be matched in two places counts twice, although the LCS string is
73
+ * the same: `[A, A, A]` vs `[A, A]` counts 3, not 1.
74
+ * - Two orderings of down/right skips around the same matched lines count once, because they are
75
+ * the same embedding: `[A, X, B]` vs `[A, Y, B]` counts 1, not 2.
76
+ *
77
+ * The recurrence is a first-pair decomposition. For the region starting at `(i, j)` with optimal
78
+ * length `target`, every maximum pairing either matches `i` with `j` (only possible when the
79
+ * canons agree, and then it extends a maximum pairing of `(i + 1, j + 1)`), or leaves at least
80
+ * one of the two lines unmatched, which is a maximum pairing of `(i + 1, j)` and/or `(i, j + 1)`
81
+ * at the same length. The overlap of those two jump regions is subtracted, so each pairing is
82
+ * counted exactly once. The cap is applied after the inclusion-exclusion subtraction, and because
83
+ * `|A ∪ B| == 1` forces `A` and `B` to be the same singleton, the `=== 1` test that drives
84
+ * `isUnique` stays exact under the cap.
85
+ */
86
+ export declare function computeLCSPaths(prevLines: LineDescriptor[], currLines: LineDescriptor[], pStart: number, pEnd: number, cStart: number, cEnd: number): LcsAlignment;
87
+ /**
88
+ * Fail-closed monotonicity assertion (spec §3.8): paired coordinates must be strictly
89
+ * increasing in both snapshots, so a later previous line can never map to an earlier
90
+ * current line.
91
+ */
92
+ export declare function assertMonotonicPairing(pairing: Map<number, number>): void;
93
+ /**
94
+ * Pair previous snapshot lines to current snapshot lines (spec §5.2), returning
95
+ * `prevLineNumber -> currLineNumber`. Unpaired lines are omitted, which retires their
96
+ * `line_id`s fail-closed downstream.
97
+ */
98
+ export declare function pairSnapshots(prevLines: LineDescriptor[], currLines: LineDescriptor[], options?: PairingOptions): Map<number, number>;
99
+ export {};
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The port this owner needs — and nothing more. `DatabaseSync` satisfies it
3
+ * structurally, so every caller is unchanged. Narrowness is the point: the owner
4
+ * cannot prepare statements, read rows, or close handles, and the retry policy can
5
+ * be driven by a plain-object fake instead of a real handle.
6
+ */
7
+ export interface TxnHandle {
8
+ readonly isTransaction: boolean;
9
+ exec(sql: string): void;
10
+ }
11
+ /** Run `fn` in one transaction on `db`, or join the transaction already open on it. */
12
+ export declare function withTransaction(db: TxnHandle, fn: () => void): void;
@@ -0,0 +1,79 @@
1
+ /**
2
+ * The v7 snapshot family's retention owner: the bounded cache of file versions.
3
+ *
4
+ * WHY — global LRU vacuum (spec §3.6.1). The CAS store is a bounded cache: 50 MB globally, and
5
+ * `min(10, max(2, floor(10 MB / snapshot_lineage_bytes)))` versions per path where
6
+ * `snapshot_lineage_bytes ≈ 40 × line_count`. Eviction is global and oldest-`created_at` first
7
+ * across all paths. Identity wins over budget: a snapshot a session can still resolve through —
8
+ * an active lease inside the 7-day TTL, a `file_undo.snapshot_hash` restore target, or a lease
9
+ * retired inside the 1-hour grace — is PINNED and never evicted, so the vacuum only drops versions
10
+ * no live anchor points at. When every remaining candidate is pinned the vacuum defers, permitting
11
+ * a soft overflow that in practice lapses as leases expire; `deferredBytes` / `overSoftOverflow`
12
+ * report that state and the 100 MB ceiling governs only the report.
13
+ *
14
+ * The budgets are the production policy the store that owns `file_snapshots` / `line_lineage`
15
+ * enforces; they are module-level policy, never call-site configuration (ADR-0017).
16
+ *
17
+ * Never touched by the pass, each for a stated reason: `line_id_counters` (the ID-reuse invariant
18
+ * — a surviving lease must never have its `line_id` re-issued), `served_leases` (the pin set is
19
+ * *computed from* this table; the TTL and grace are pin predicates, not pruners), and the legacy
20
+ * `snapshots` row (one row per path, overwritten, and the documented upgrade fallback).
21
+ * @module dsh-better-edit/snapshot-store/vacuum
22
+ */
23
+ import type { DatabaseSync } from "node:sqlite";
24
+ export declare const VACUUM_GLOBAL_BUDGET_BYTES: number;
25
+ export declare const VACUUM_SOFT_OVERFLOW_BYTES: number;
26
+ export declare const VACUUM_PER_PATH_BUDGET_BYTES: number;
27
+ export declare const VACUUM_MAX_SNAPSHOTS_PER_PATH = 10;
28
+ export declare const VACUUM_MIN_SNAPSHOTS_PER_PATH = 2;
29
+ export declare const VACUUM_LINEAGE_BYTES_PER_LINE = 40;
30
+ export declare const VACUUM_RETIRED_PIN_MS: number;
31
+ /** Bounds for one vacuum pass; the policy values are the module-level production constants. */
32
+ export interface VacuumOptions {
33
+ /**
34
+ * Snapshot ids that must survive this pass regardless of budget or per-path retention: the
35
+ * version an in-flight materialization is about to serve. The sweep runs before `served_leases`
36
+ * exists for that version, so without this the freshly materialized row is the unpinned
37
+ * candidate oldest-first eviction takes (spec §3.6.1 — retention must never delete the row the
38
+ * caller is serving, or the next edit is permanently uneditable).
39
+ */
40
+ protectSnapshotIds?: Iterable<number>;
41
+ }
42
+ export interface VacuumResult {
43
+ /** Snapshots deleted by this pass. */
44
+ evicted: number;
45
+ /** Lineage bytes retained after the pass. */
46
+ totalBytes: number;
47
+ /** Lineage bytes retained by pinned snapshots (always retained). */
48
+ pinnedBytes: number;
49
+ /** Overflow past the hard budget that the pinned set forces the store to keep. */
50
+ deferredBytes: number;
51
+ /** Whether that deferred overflow exceeds the tolerated soft cap (spec §3.6.1). */
52
+ overSoftOverflow: boolean;
53
+ /**
54
+ * True when this call found `db.isTransaction` and therefore swept nothing. A skip is NOT a
55
+ * clean sweep: every counter is zero, but the zero means "deferred to the next outermost
56
+ * boundary", so callers must report it as a skip rather than as "nothing to do".
57
+ */
58
+ skippedInTransaction: boolean;
59
+ }
60
+ export declare const REPORT_CONTEXT_CAP = 256;
61
+ /**
62
+ * The single report owner for a vacuum pass: every trigger calls this with the module's result and
63
+ * its stable context. A `skippedInTransaction` pass is reported as a skip — never as a zero
64
+ * result — so "0 bytes deferred" can never be read as "nothing to do". A swept pass is reported
65
+ * when it deferred bytes or crossed the soft cap. Never throws: a diagnostic failure must not fail
66
+ * the caller.
67
+ */
68
+ export declare function reportVacuum(result: VacuumResult, context: string): void;
69
+ /**
70
+ * Enforce store retention across all paths (spec §3.6.1). The pass is one oldest-first sweep of
71
+ * every committed snapshot: a snapshot is deleted when the running total is over the global budget,
72
+ * or when its path already retains more than its retention window. Pinned snapshots are skipped
73
+ * unconditionally — they are the versions a live anchor can still resolve through — and the
74
+ * resulting deferral is reported, never resolved by evicting a pin.
75
+ *
76
+ * The pass is idempotent and safe with no candidates: it returns the zero result and never throws
77
+ * on an empty store.
78
+ */
79
+ export declare function vacuumSnapshots(db: DatabaseSync, options?: VacuumOptions): VacuumResult;
@@ -5,7 +5,6 @@ export declare function setStoresGetter(getS: () => Map<string, {
5
5
  export declare function runCentralJanitorIfDue(): Promise<void>;
6
6
  export declare function onStoreOpen(storePath: string, stmts: {
7
7
  servedPruneOlderThan: (ts: number) => void;
8
- undoPruneOlderThan: (ts: number) => void;
9
8
  }, store: HashStore): Promise<void>;
10
9
  export declare function onAppStart(): Promise<void>;
11
10
  export declare function onSessionStart(): Promise<void>;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Shared sqlite busy-retry policy — a leaf module so `hash-store` and the
3
+ * row-family modules (e.g. `snapshot-store`) use one policy without a cycle.
4
+ * @module dsh-better-edit/store-retry
5
+ */
6
+ export declare function withBusyRetry<T>(fn: () => T): T;
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * The dsh `edit` tool: hash-anchored literal range edits that shadow the
3
3
  * built-in `edit` on the agent's own scope layer. Now the sole mutation tool
4
- * (batch_edit removed, ADR-0007): payload is { path: string|null, edits: [[remove_from,remove_to,replacement_text],...] }
5
- * single-file atomic batch, null path inference via anchors.
4
+ * (batch_edit removed, ADR-0007): payload is { file: string|null, edits: [{anchor_from,anchor_to,replace_with},...] }
5
+ * single-file atomic batch, legacy null file inference via anchors.
6
6
  * @module dsh-better-edit/tool-edit
7
7
  */
8
8
  import type { Context } from "@deepseek-ai/cordis";
@@ -9,19 +9,25 @@
9
9
  * and never records served state (so it can feed `write` round-trips but
10
10
  * cannot authorize hashline `edit` anchors).
11
11
  * - `str_replace` / `insert` without a prior `view`/`read` fail loud with
12
- * `E_BLIND_REPLACE` — no disk write.
12
+ * `E_BAD_PAYLOAD` (unviewed file) — no disk write.
13
13
  * - `create` defaults to UTF-8 without BOM.
14
- * - `undo_edit` is out of scope → `E_UNSUPPORTED` (use `undo_last_edit`).
14
+ * - `undo_edit` is out of scope → `E_BAD_PAYLOAD` (use `undo_last_edit`).
15
+ *
16
+ * - `create` / `str_replace` / `insert` stamp the per-call sandbox policy from
17
+ * `FsSandboxController` (the calling session's workspace root plus any
18
+ * approved one-shot escalation), matching the built-in and the hashline
19
+ * `edit` / `undo_last_edit` paths; unconfined deployments stamp `undefined`.
15
20
  *
16
21
  * See ADR-0015.
17
22
  * @module dsh-better-edit/tool-str-replace-editor
18
23
  */
24
+ import type { FsSandboxController } from "./sandbox.js";
19
25
  import type { FileIO } from "./fs-bridge.js";
20
26
  export declare const STR_REPLACE_EDITOR_DESCRIPTION: string;
21
- export declare function buildStrReplaceEditorTool(io: FileIO): import("@deepseek-ai/dsh-tools").ToolDefinition;
27
+ export declare function buildStrReplaceEditorTool(io: FileIO, sandbox: FsSandboxController): import("@deepseek-ai/dsh-tools").ToolDefinition;
22
28
  /** Register the shadow `str_replace_editor` on the calling agent's scope (own layer). */
23
29
  export declare function registerStrReplaceEditorTool(agentCtx: {
24
30
  tools: {
25
31
  register(def: unknown): () => void;
26
32
  };
27
- }, io: FileIO): () => void;
33
+ }, io: FileIO, sandbox: FsSandboxController): () => void;
@@ -11,10 +11,9 @@ export declare function firstNonEmptyIndex(lines: string[]): number;
11
11
  export declare function lastNonEmpty(lines: string[]): string | undefined;
12
12
  export declare function firstNonEmpty(lines: string[]): string | undefined;
13
13
  export declare function clipLine(line: string, maxLen?: number): string;
14
- /** Machine-readable error-code carrier — bare `E_*` code alongside the human message. */
15
- export declare class CodedError extends Error {
16
- readonly code: string;
17
- constructor(code: string, message: string);
18
- }
19
- /** Structured bare-code read for any tool error: carrier first, `[E_*]` message convention as fallback. */
14
+ /**
15
+ * Structured bare-code read for any tool error: DomainError carrier first,
16
+ * then the `[E_*]` message convention as a legacy fallback
17
+ * registry members route the typed path; the regex is last resort).
18
+ */
20
19
  export declare function codeOf(error: unknown): string | undefined;
@@ -20,4 +20,3 @@ export declare function workspaceCwd(): string | undefined;
20
20
  export declare function sessionKeyFor(sessionId?: string): string;
21
21
  export declare function execCwd(exec: ToolExecution): string;
22
22
  export declare function execSessionKey(exec: ToolExecution): string;
23
- export declare function _resetWorkspaceContextForTests(): void;
package/lib/undo-edit.js CHANGED
@@ -8,20 +8,28 @@
8
8
  * @module dsh-better-edit/undo-edit
9
9
  */
10
10
  import { loadHashStore } from "./hash-store.js";
11
+ import { snapshotHashFor } from "./snapshot-store/lineage-store.js";
11
12
  /** Load the last undo row for a path from the active store, if any. */
12
13
  async function readUndo(path) {
13
14
  const store = await loadHashStore();
14
15
  return store.getUndo(path);
15
16
  }
16
- /** Persist the undo row for a path to the active store. */
17
+ /** Persist the undo rows (legacy + v7 snapshot pin) for a path to the active store. */
17
18
  async function writeUndo(path, entry) {
18
19
  const store = await loadHashStore();
19
- store.upsertUndo(path, entry);
20
+ store.writeUndoPair(path, entry, {
21
+ content: entry.content,
22
+ bom: entry.bom,
23
+ ending: entry.ending,
24
+ hashes: entry.hashes,
25
+ resultContent: entry.resultContent,
26
+ snapshotHash: snapshotHashFor(entry.content),
27
+ });
20
28
  }
21
- /** Drop the undo row for a path from the active store. */
22
- async function removeUndo(path) {
29
+ /** Load the v7 undo row for a path from the active store, if any. */
30
+ async function readFileUndo(path) {
23
31
  const store = await loadHashStore();
24
- store.deleteUndo(path);
32
+ return store.getFileUndo(path);
25
33
  }
26
34
  /**
27
35
  * Persist an undo entry for one path before mutating it.
@@ -32,8 +40,10 @@ async function removeUndo(path) {
32
40
  */
33
41
  export async function saveUndo(path, entry) {
34
42
  let previous;
43
+ let previousFileUndo;
35
44
  try {
36
45
  previous = await readUndo(path);
46
+ previousFileUndo = await readFileUndo(path);
37
47
  await writeUndo(path, {
38
48
  content: entry.content,
39
49
  bom: entry.bom,
@@ -50,10 +60,14 @@ export async function saveUndo(path, entry) {
50
60
  persisted: true,
51
61
  restore: async () => {
52
62
  try {
53
- if (previous)
54
- await writeUndo(path, previous);
55
- else
56
- await removeUndo(path);
63
+ if (previous ?? previousFileUndo) {
64
+ const store = await loadHashStore();
65
+ store.writeUndoPair(path, previous, previousFileUndo);
66
+ }
67
+ else {
68
+ const store = await loadHashStore();
69
+ store.deleteUndoPair(path);
70
+ }
57
71
  }
58
72
  catch (error) {
59
73
  console.error("Failed to restore previous undo entry:", error);
@@ -69,7 +83,8 @@ export async function getUndo(path) {
69
83
  return undefined;
70
84
  const originalEnding = record.ending;
71
85
  if (originalEnding !== "\r\n" && originalEnding !== "\n" && originalEnding !== "\r") {
72
- await removeUndo(path);
86
+ const store = await loadHashStore();
87
+ store.deleteUndoPair(path);
73
88
  return undefined;
74
89
  }
75
90
  return {
@@ -88,7 +103,8 @@ export async function getUndo(path) {
88
103
  /** Drop the undo entry for a path (a write or an undone revert clears history). */
89
104
  export async function clearUndo(path) {
90
105
  try {
91
- await removeUndo(path);
106
+ const store = await loadHashStore();
107
+ store.deleteUndoPair(path);
92
108
  }
93
109
  catch (error) {
94
110
  console.error("Failed to clear undo entry:", error);
package/lib/utils.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { DomainError } from "./domain-errors.js";
1
2
  export function isRec(value) {
2
3
  return typeof value === "object" && value !== null && !Array.isArray(value);
3
4
  }
@@ -23,7 +24,9 @@ export function rejectUnknownFields(obj, allowed, label, hint) {
23
24
  const unknown = Object.keys(obj).filter((key) => !allowed.has(key));
24
25
  if (unknown.length > 0) {
25
26
  const suffix = hint ? ` ${hint}` : "";
26
- throw new Error(`[MODEL] [E_BAD_PAYLOAD] ${label} contains unknown or unsupported fields: ${unknown.join(", ")}.${suffix}`);
27
+ throw new DomainError("E_BAD_PAYLOAD", {
28
+ message: `${label} contains unknown or unsupported fields: ${unknown.join(", ")}.${suffix}`,
29
+ });
27
30
  }
28
31
  }
29
32
  export function cntDiff(diff, marker) {
@@ -42,6 +45,8 @@ export function abortIf(signal) {
42
45
  throw new Error("Operation aborted");
43
46
  }
44
47
  export function errCode(error) {
48
+ if (error instanceof DomainError)
49
+ return error.code;
45
50
  if (error instanceof Error) {
46
51
  return error.code;
47
52
  }
@@ -73,19 +78,14 @@ export function clipLine(line, maxLen = 200) {
73
78
  const flat = line.replace(/\n/g, "\\n");
74
79
  return flat.length > maxLen ? `${flat.slice(0, maxLen)}...` : flat;
75
80
  }
76
- /** Machine-readable error-code carrier — bare `E_*` code alongside the human message. */
77
- export class CodedError extends Error {
78
- code;
79
- constructor(code, message) {
80
- super(message);
81
- this.name = "CodedError";
82
- this.code = code;
83
- }
84
- }
85
81
  const CODED_RE = /\[(E_[A-Z_]+)\]/;
86
- /** Structured bare-code read for any tool error: carrier first, `[E_*]` message convention as fallback. */
82
+ /**
83
+ * Structured bare-code read for any tool error: DomainError carrier first,
84
+ * then the `[E_*]` message convention as a legacy fallback
85
+ * registry members route the typed path; the regex is last resort).
86
+ */
87
87
  export function codeOf(error) {
88
- if (error instanceof CodedError)
88
+ if (error instanceof DomainError)
89
89
  return error.code;
90
90
  if (error instanceof Error) {
91
91
  const m = error.message.match(CODED_RE);