dsh-hashline-edit 0.5.5 → 0.6.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.
- package/README.md +4 -1
- package/lib/client.js +51 -6
- package/lib/index.js +239 -16
- package/lib/types/dsh/index.d.ts +11 -3
- package/lib/types/src/hashline/gutter.d.ts +2 -4
- package/lib/types/src/hashline/row-mode.d.ts +7 -5
- package/lib/types/src/mutation-engine/edit-request.d.ts +10 -0
- package/lib/types/src/payload-contract.d.ts +5 -0
- package/lib/types/src/store-kernel/constants.d.ts +1 -1
- package/package.json +1 -1
- package/prompts/edit.md +1 -0
- package/src/hash-store.ts +48 -0
- package/src/hashline/gutter.ts +8 -13
- package/src/hashline/hash-identity.ts +7 -1
- package/src/hashline/row-mode.ts +9 -6
- package/src/mutation-engine/edit-request.ts +7 -0
- package/src/mutation-engine/pipeline.ts +154 -4
- package/src/payload-contract.ts +67 -1
- package/src/prompts.ts +4 -1
- package/src/snapshot-store/vacuum.ts +6 -0
- package/src/store-kernel/constants.ts +1 -1
package/README.md
CHANGED
|
@@ -36,10 +36,12 @@ Prompt prose is width-neutral: shipped prompt files use the `{{HASH_LEN}}` place
|
|
|
36
36
|
|
|
37
37
|
Measured on the DeepSeek-V4.1 tokenizer, every width-3 anchor is exactly two tokens (the codebook admits only the 157,943 two-token spellings) and a width-4 anchor averages ~3.0 tokens per served line (see [ADR-0034](docs/adr/0034-line-number-gutter-and-two-token-codebook.md)). The default is 3; build with `PI_BETTER_EDIT_ANCHOR_WIDTH=4` to ship the 4-char artifact, whose generation-1 store keeps existing rows valid.
|
|
38
38
|
|
|
39
|
-
### Line-number gutter
|
|
39
|
+
### Line-number gutter, the 2-token codebook, and the bare mode
|
|
40
40
|
|
|
41
41
|
Every served row is prefixed by a **display-only line-number gutter** — `12→` by default (line number, then U+2192), or `12: ` in the opt-in **native** gutter. The gutter is presentation only: the anchor is the build-width characters immediately left of `│`, and the gutter never participates in addressing. `PI_BETTER_EDIT_ROW_GUTTER` selects `arrow` (default) or `native`; native exists only for A/B measurement, because `12: ` merges with the anchor's first token for about 23% of anchors (only ~77% keep the two-token boundary, versus 100% with `12→`).
|
|
42
42
|
|
|
43
|
+
**Bare gutter (`rowGutter: "bare"`).** The `nativeGutter` boolean is now a three-value `rowGutter` switch — `arrow` (default), `native`, or `bare`. `bare` renders no line number at all: every served row is bare `HASH│content`. Because no line number can be confused with an anchor, `bare` drops both the width-3 two-token codebook and the width-4 all-digit reservation, so anchors are drawn from the full `62^N` base62 space (`USABLE_HASH_SPACE = 62^N`). Each mode carries its own anchor generation (width 4: arrow `1`, bare `6`; width 3: arrow `3`, native `4`, bare `5`), so switching re-reads served rows. `PI_BETTER_EDIT_ROW_GUTTER` accepts `arrow` / `native` / `bare`, and `resolveRowGutter` rejects anything else.
|
|
44
|
+
|
|
43
45
|
At width 3 the served anchors are drawn only from the **157,943 base62 three-character spellings that tokenize to exactly two tokens** on DeepSeek-V4.1 (a subset of the 238,328 total `62^3` spellings), so every anchor reads as a stable two-token unit. Width 4 keeps the historical rule (the all-digit sub-cube stays reserved; `62^4 − 10^4 = 14,766,336` usable). The width-3 generation is `3` (width 4 stays `1`), so a width-3 build is a one-time hard cache miss — existing width-3 anchors and stores are re-read once.
|
|
44
46
|
|
|
45
47
|
## Install
|
|
@@ -212,6 +214,7 @@ Each item names one inclusive bare anchor, `anchor_from`, and exactly one payloa
|
|
|
212
214
|
|
|
213
215
|
- **`indent: "auto"`** (default `as-is`) re-bases the payload's indentation: the common leading-whitespace prefix of `text` is stripped and the leading whitespace of the `anchor_from` line is applied instead, with blank lines untouched. It is refused together with `text_ref` or a deletion (`text: ""`), and the applied change is reported in the call's notes channel ([ADR-0030](docs/adr/0030-edit-auto-indent.md)).
|
|
214
216
|
- **`expand: "item"`** replaces the whole innermost enclosing syntax item — leading doc comment and attributes through the matching closing brace — instead of only the named rows. It names only `anchor_from` (an `anchor_to` is refused) and must be the only item in the call; an unsupported file or grammar refuses with `[E_EXPAND_UNAVAILABLE]` and writes nothing. Normal undo, diff and served rows still apply ([ADR-0031](docs/adr/0031-edit-expand-to-item.md)).
|
|
217
|
+
- **String replacement** (`{ old_string, new_string }`) is an alternative to anchors when anchors are unavailable or awkward: the item replaces the exact, unique occurrence of `old_string` with `new_string` character-for-character (a match inside one line is supported). `old_string` must occur exactly once — zero or multiple matches refuse with `[E_UNIQUE_MATCH]` and write nothing. A call may mix anchor items and string items; items apply in order, each to the result of the previous.
|
|
215
218
|
|
|
216
219
|
### `rg`
|
|
217
220
|
|
package/lib/client.js
CHANGED
|
@@ -33,9 +33,18 @@ var SWITCHES = [
|
|
|
33
33
|
{ key: "applyPatch", label: "swApplyPatch", hint: "swApplyPatchHint", fallback: true },
|
|
34
34
|
{ key: "edit", label: "swEdit", hint: "swEditHint", fallback: false },
|
|
35
35
|
{ key: "codegraph", label: "swCodegraph", hint: "swCodegraphHint", fallback: false },
|
|
36
|
-
{ key: "diagnostics", label: "swDiagnostics", hint: "swDiagnosticsHint", fallback: false }
|
|
37
|
-
{ key: "nativeGutter", label: "swNativeGutter", hint: "swNativeGutterHint", fallback: false }
|
|
36
|
+
{ key: "diagnostics", label: "swDiagnostics", hint: "swDiagnosticsHint", fallback: false }
|
|
38
37
|
];
|
|
38
|
+
var ROW_GUTTERS = ["arrow", "native", "bare"];
|
|
39
|
+
function readGutter(value) {
|
|
40
|
+
const raw = value["rowGutter"];
|
|
41
|
+
return raw === "native" || raw === "bare" ? raw : "arrow";
|
|
42
|
+
}
|
|
43
|
+
var GUTTER_LABELS = {
|
|
44
|
+
arrow: "gutterArrow",
|
|
45
|
+
native: "gutterNative",
|
|
46
|
+
bare: "gutterBare"
|
|
47
|
+
};
|
|
39
48
|
var en = {
|
|
40
49
|
swRead: "Read (shadow the host read)",
|
|
41
50
|
swReadHint: "Expose the hashline read tool with hash anchors and shadow the host's read.",
|
|
@@ -57,8 +66,11 @@ var en = {
|
|
|
57
66
|
loading: "Loading host settings\u2026",
|
|
58
67
|
unavailable: "Enable this row with the built-in switch to edit its settings.",
|
|
59
68
|
rowSummary: "Read, apply_patch, edit, codegraph and diagnostics switches.",
|
|
60
|
-
|
|
61
|
-
|
|
69
|
+
gutterGroup: "Row rendering (line-number gutter)",
|
|
70
|
+
gutterGroupHint: "How served rows are prefixed. arrow: `12\u2192HASH\u2502content`; native: `12: HASH\u2502content`; bare: no line numbers \u2014 rows are bare `HASH\u2502content` with full-base62 anchors (a fresh anchor generation).",
|
|
71
|
+
gutterArrow: "Arrow (12\u2192)",
|
|
72
|
+
gutterNative: "Native (12: )",
|
|
73
|
+
gutterBare: "Bare (no line numbers)"
|
|
62
74
|
};
|
|
63
75
|
var zh = {
|
|
64
76
|
swRead: "\u8BFB\u53D6\uFF08\u906E\u853D\u5BBF\u4E3B read\uFF09",
|
|
@@ -81,8 +93,11 @@ var zh = {
|
|
|
81
93
|
loading: "\u6B63\u5728\u52A0\u8F7D\u5BBF\u4E3B\u8BBE\u7F6E\u2026",
|
|
82
94
|
unavailable: "\u8BF7\u5148\u7528\u5185\u7F6E\u5F00\u5173\u542F\u7528\u6B64\u884C\u540E\u518D\u7F16\u8F91\u8BBE\u7F6E\u3002",
|
|
83
95
|
rowSummary: "\u8BFB\u53D6\u3001apply_patch\u3001\u533A\u95F4\u7F16\u8F91\u3001codegraph \u4E0E diagnostics \u5F00\u5173\u3002",
|
|
84
|
-
|
|
85
|
-
|
|
96
|
+
gutterGroup: "\u884C\u53F7\u6E32\u67D3\u6A21\u5F0F",
|
|
97
|
+
gutterGroupHint: "\u670D\u52A1\u884C\u7684\u524D\u7F00\u6837\u5F0F\u3002arrow\uFF1A`12\u2192HASH\u2502content`\uFF1Bnative\uFF1A`12: HASH\u2502content`\uFF1Bbare\uFF1A\u4E0D\u663E\u793A\u884C\u53F7\u2014\u2014\u884C\u4E3A\u88F8 `HASH\u2502content`\uFF0C\u951A\u70B9\u7528\u5B8C\u6574 base62\uFF08\u5168\u65B0\u951A\u70B9 generation\uFF09\u3002",
|
|
98
|
+
gutterArrow: "\u7BAD\u5934\uFF0812\u2192\uFF09",
|
|
99
|
+
gutterNative: "\u539F\u751F\uFF0812: \uFF09",
|
|
100
|
+
gutterBare: "\u65E0\u884C\u53F7\uFF08bare\uFF09"
|
|
86
101
|
};
|
|
87
102
|
var CSS = `
|
|
88
103
|
.hashline-settings { display:flex; flex-direction:column; gap:12px; font:inherit; color:var(--dsw-alias-label-primary,#222); }
|
|
@@ -104,6 +119,10 @@ var CSS = `
|
|
|
104
119
|
.hashline-primary:disabled { opacity:.4; cursor:default; }
|
|
105
120
|
.hashline-reset { border:0; background:none; font:inherit; font-size:12px; color:var(--dsw-alias-label-secondary,#555); cursor:pointer; }
|
|
106
121
|
.hashline-note { margin:0; font-size:12px; line-height:1.6; color:var(--dsw-alias-label-tertiary,#888); }
|
|
122
|
+
.hashline-seg { display:inline-flex; border:.5px solid var(--dsw-alias-border-l2,#ddd); border-radius:6px; overflow:hidden; }
|
|
123
|
+
.hashline-seg button { border:0; background:none; font:inherit; font-size:12px; padding:4px 10px; cursor:pointer; color:var(--dsw-alias-label-secondary,#555); }
|
|
124
|
+
.hashline-seg button + button { border-left:.5px solid var(--dsw-alias-border-l2,#ddd); }
|
|
125
|
+
.hashline-seg button.is-on { background:var(--dsw-alias-label-primary,#222); color:#fff; }
|
|
107
126
|
`;
|
|
108
127
|
function readValues(value) {
|
|
109
128
|
const out = {};
|
|
@@ -138,6 +157,7 @@ function RowForm(props) {
|
|
|
138
157
|
const [draft, setDraft] = (0, import_react.useState)(
|
|
139
158
|
() => readValues(form?.state.value ?? {})
|
|
140
159
|
);
|
|
160
|
+
const [gutter, setGutter] = (0, import_react.useState)(() => readGutter(form?.state.value ?? {}));
|
|
141
161
|
const [baseline, setBaseline] = (0, import_react.useState)(() => form?.state.value ?? {});
|
|
142
162
|
const [revision, setRevision] = (0, import_react.useState)(form?.state.revision);
|
|
143
163
|
const [dirty, setDirty] = (0, import_react.useState)(false);
|
|
@@ -146,6 +166,7 @@ function RowForm(props) {
|
|
|
146
166
|
(0, import_react.useEffect)(() => {
|
|
147
167
|
if (dirty) return;
|
|
148
168
|
setDraft(readValues(form?.state.value ?? {}));
|
|
169
|
+
setGutter(readGutter(form?.state.value ?? {}));
|
|
149
170
|
setBaseline(form?.state.value ?? {});
|
|
150
171
|
setRevision(form?.state.revision);
|
|
151
172
|
}, [form?.state.revision, form?.state.status, dirty]);
|
|
@@ -159,6 +180,7 @@ function RowForm(props) {
|
|
|
159
180
|
};
|
|
160
181
|
const reset = () => {
|
|
161
182
|
setDraft(readValues(baseline));
|
|
183
|
+
setGutter(readGutter(baseline));
|
|
162
184
|
setDirty(false);
|
|
163
185
|
setMessage("");
|
|
164
186
|
};
|
|
@@ -171,6 +193,9 @@ function RowForm(props) {
|
|
|
171
193
|
operations.push({ op: "set", path: [spec.key], value: draft[spec.key] });
|
|
172
194
|
}
|
|
173
195
|
}
|
|
196
|
+
if (gutter !== readGutter(baseline)) {
|
|
197
|
+
operations.push({ op: "set", path: ["rowGutter"], value: gutter });
|
|
198
|
+
}
|
|
174
199
|
setBusy(true);
|
|
175
200
|
setMessage("");
|
|
176
201
|
try {
|
|
@@ -211,6 +236,26 @@ function RowForm(props) {
|
|
|
211
236
|
)
|
|
212
237
|
] }, spec.key)) })
|
|
213
238
|
] }),
|
|
239
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("section", { className: "hashline-card", children: [
|
|
240
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("h4", { className: "hashline-title", children: t("gutterGroup") }),
|
|
241
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "hashline-hint", children: t("gutterGroupHint") }),
|
|
242
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "hashline-seg", role: "group", "aria-label": t("gutterGroup"), children: ROW_GUTTERS.map((mode) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
243
|
+
"button",
|
|
244
|
+
{
|
|
245
|
+
type: "button",
|
|
246
|
+
className: gutter === mode ? "is-on" : "",
|
|
247
|
+
disabled: busy,
|
|
248
|
+
"aria-pressed": gutter === mode,
|
|
249
|
+
onClick: () => {
|
|
250
|
+
setGutter(mode);
|
|
251
|
+
setDirty(true);
|
|
252
|
+
setMessage("");
|
|
253
|
+
},
|
|
254
|
+
children: t(GUTTER_LABELS[mode])
|
|
255
|
+
},
|
|
256
|
+
mode
|
|
257
|
+
)) })
|
|
258
|
+
] }),
|
|
214
259
|
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "hashline-actions", children: [
|
|
215
260
|
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { type: "submit", className: "hashline-primary", disabled: busy || !dirty, children: t(busy ? "saving" : "save") }),
|
|
216
261
|
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { type: "button", className: "hashline-reset", onClick: reset, disabled: busy, children: t("reset") })
|
package/lib/index.js
CHANGED
|
@@ -1744,8 +1744,9 @@ function resolveRowGutter(env) {
|
|
|
1744
1744
|
const value = raw.trim().toLowerCase();
|
|
1745
1745
|
if (value === "arrow") return "arrow";
|
|
1746
1746
|
if (value === "native") return "native";
|
|
1747
|
+
if (value === "bare") return "bare";
|
|
1747
1748
|
throw new Error(
|
|
1748
|
-
`${ROW_GUTTER_ENV_VAR} must be "arrow" or "
|
|
1749
|
+
`${ROW_GUTTER_ENV_VAR} must be "arrow", "native" or "bare" (got ${JSON.stringify(raw)}).`
|
|
1749
1750
|
);
|
|
1750
1751
|
}
|
|
1751
1752
|
var envPinned = (() => {
|
|
@@ -1763,10 +1764,14 @@ function applyConfigRowGutter(mode) {
|
|
|
1763
1764
|
|
|
1764
1765
|
// src/hashline/gutter.ts
|
|
1765
1766
|
function lineGutter(lineNumber) {
|
|
1766
|
-
|
|
1767
|
+
const mode = getRowGutter();
|
|
1768
|
+
if (mode === "bare") return "";
|
|
1769
|
+
return mode === "native" ? `${lineNumber}: ` : `${lineNumber}\u2192`;
|
|
1767
1770
|
}
|
|
1768
1771
|
function rangeGutter(startLine, endLine) {
|
|
1769
|
-
|
|
1772
|
+
const mode = getRowGutter();
|
|
1773
|
+
if (mode === "bare") return "";
|
|
1774
|
+
return mode === "native" ? `${startLine}..${endLine}: ` : `${startLine}..${endLine}\u2192`;
|
|
1770
1775
|
}
|
|
1771
1776
|
var ROW_GUTTER_PREFIX = "(?:[0-9]+(?:[.][.][0-9]+)?(?:\u2192|: ))";
|
|
1772
1777
|
function stripLineGutter(text) {
|
|
@@ -1979,7 +1984,8 @@ function applyReplacements(content, replacements) {
|
|
|
1979
1984
|
}
|
|
1980
1985
|
}
|
|
1981
1986
|
const withWidth = out.split("{{HASH_LEN}}").join(String(HASH_LEN));
|
|
1982
|
-
|
|
1987
|
+
const gutter = getRowGutter();
|
|
1988
|
+
return withWidth.split("{{GUTTER}}").join(gutter === "native" ? ": " : gutter === "bare" ? "" : "\u2192");
|
|
1983
1989
|
}
|
|
1984
1990
|
function loadP(relativePath2, replacements) {
|
|
1985
1991
|
const content = readFileSync(new URL(relativePath2, import.meta.url), "utf-8").trim();
|
|
@@ -2422,6 +2428,7 @@ function popcount32(value) {
|
|
|
2422
2428
|
}
|
|
2423
2429
|
function buildReservedBits() {
|
|
2424
2430
|
const bits = new Uint32Array(BITSET_WORDS);
|
|
2431
|
+
if (getRowGutter() === "bare") return bits;
|
|
2425
2432
|
if (HASH_LEN === ANCHOR_CODEBOOK_WIDTH) {
|
|
2426
2433
|
const allowed = Buffer.from(
|
|
2427
2434
|
getRowGutter() === "native" ? ANCHOR_CODEBOOK_NATIVE_B64 : ANCHOR_CODEBOOK_ARROW_B64,
|
|
@@ -2460,6 +2467,7 @@ var HASH_SPACE_EXHAUSTED_PAYLOAD = {
|
|
|
2460
2467
|
var HASH_PROBE_STRIDE = ALPHA.length ** 2 + ALPHA.length + 1;
|
|
2461
2468
|
var CANON_VERSION = 3;
|
|
2462
2469
|
function anchorGenerationFor(width, gutter = getRowGutter()) {
|
|
2470
|
+
if (gutter === "bare") return width === 4 ? 6 : width === 3 ? 5 : 200 + width;
|
|
2463
2471
|
if (width === 4) return 1;
|
|
2464
2472
|
if (width === 3) return gutter === "native" ? 4 : 3;
|
|
2465
2473
|
return 100 + width;
|
|
@@ -2913,7 +2921,7 @@ import { join as join6, dirname as dirname5 } from "node:path";
|
|
|
2913
2921
|
|
|
2914
2922
|
// src/store-kernel/constants.ts
|
|
2915
2923
|
var HASH_STORE_BUSY_TIMEOUT = 250;
|
|
2916
|
-
var HASH_STORE_VERSION =
|
|
2924
|
+
var HASH_STORE_VERSION = 12;
|
|
2917
2925
|
var BUSY_MAX_ATTEMPTS = 8;
|
|
2918
2926
|
var BUSY_BACKOFF_BASE_MS = 50;
|
|
2919
2927
|
var BUSY_BACKOFF_CAP_MS = 400;
|
|
@@ -3226,6 +3234,9 @@ function ensureSnapshotTables(db) {
|
|
|
3226
3234
|
db.exec(`DELETE FROM served_leases WHERE ${FOREIGN_GENERATION_LEASE_SQL}`);
|
|
3227
3235
|
}
|
|
3228
3236
|
db.exec(`DELETE FROM file_snapshots WHERE ${FOREIGN_GENERATION_SNAPSHOT_SQL}`);
|
|
3237
|
+
if (hasTable("file_undo") && readTableColumns(db, "file_undo").has("anchor_generation")) {
|
|
3238
|
+
db.exec(`DELETE FROM file_undo WHERE anchor_generation NOT IN (0, ${ANCHOR_GENERATION})`);
|
|
3239
|
+
}
|
|
3229
3240
|
db.exec(`DELETE FROM line_lineage WHERE ${ORPHAN_LINEAGE_SQL}`);
|
|
3230
3241
|
if (hasLeases) {
|
|
3231
3242
|
db.exec(`DELETE FROM served_leases WHERE ${DANGLING_LEASE_SQL}`);
|
|
@@ -3270,6 +3281,37 @@ function ensureFileUndoSchema(db) {
|
|
|
3270
3281
|
db.exec(CUT_INTENT_DDL);
|
|
3271
3282
|
addColumnIfMissing(db, "cut_intent", "direction");
|
|
3272
3283
|
}
|
|
3284
|
+
function reclaimStoreSpace(db) {
|
|
3285
|
+
try {
|
|
3286
|
+
db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
3287
|
+
} catch {
|
|
3288
|
+
}
|
|
3289
|
+
try {
|
|
3290
|
+
const total = Number(
|
|
3291
|
+
db.prepare("PRAGMA page_count").get().page_count ?? 0
|
|
3292
|
+
);
|
|
3293
|
+
const free = Number(
|
|
3294
|
+
db.prepare("PRAGMA freelist_count").get().freelist_count ?? 0
|
|
3295
|
+
);
|
|
3296
|
+
if (total > 0 && free > 2048 && free / total > 0.2) {
|
|
3297
|
+
try {
|
|
3298
|
+
db.exec("PRAGMA auto_vacuum = INCREMENTAL");
|
|
3299
|
+
} catch {
|
|
3300
|
+
}
|
|
3301
|
+
db.exec("VACUUM");
|
|
3302
|
+
try {
|
|
3303
|
+
db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
3304
|
+
} catch {
|
|
3305
|
+
}
|
|
3306
|
+
} else {
|
|
3307
|
+
try {
|
|
3308
|
+
db.exec("PRAGMA incremental_vacuum");
|
|
3309
|
+
} catch {
|
|
3310
|
+
}
|
|
3311
|
+
}
|
|
3312
|
+
} catch {
|
|
3313
|
+
}
|
|
3314
|
+
}
|
|
3273
3315
|
function buildStore(db) {
|
|
3274
3316
|
const stampDue = !storeStampMatches(db);
|
|
3275
3317
|
db.exec("PRAGMA journal_mode = WAL");
|
|
@@ -3318,6 +3360,7 @@ function buildStore(db) {
|
|
|
3318
3360
|
addColumnIfMissing(db, "served", "snapshotId");
|
|
3319
3361
|
addColumnIfMissing(db, "undo", "result_content");
|
|
3320
3362
|
if (!stampDue) return false;
|
|
3363
|
+
reclaimStoreSpace(db);
|
|
3321
3364
|
db.prepare(
|
|
3322
3365
|
"INSERT INTO meta (key, value) VALUES ('version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
|
|
3323
3366
|
).run(String(HASH_STORE_VERSION));
|
|
@@ -5395,6 +5438,10 @@ function vacuumSnapshots(db, options = {}) {
|
|
|
5395
5438
|
}
|
|
5396
5439
|
}
|
|
5397
5440
|
if (evict.length > 0) deleteVacuumSnapshots(db, evict);
|
|
5441
|
+
try {
|
|
5442
|
+
db.exec("PRAGMA incremental_vacuum");
|
|
5443
|
+
} catch {
|
|
5444
|
+
}
|
|
5398
5445
|
const deferredBytes = Math.max(0, total - VACUUM_GLOBAL_BUDGET_BYTES);
|
|
5399
5446
|
return {
|
|
5400
5447
|
evicted: evict.length,
|
|
@@ -14496,6 +14543,69 @@ function autoIndentedEdit(input, identity) {
|
|
|
14496
14543
|
}
|
|
14497
14544
|
};
|
|
14498
14545
|
}
|
|
14546
|
+
function lineOfOffset(content, offset) {
|
|
14547
|
+
let line = 1;
|
|
14548
|
+
for (let i = 0; i < offset; i++) if (content.charCodeAt(i) === 10) line += 1;
|
|
14549
|
+
return line;
|
|
14550
|
+
}
|
|
14551
|
+
async function applyStringEdit(input) {
|
|
14552
|
+
abortIf(input.signal);
|
|
14553
|
+
const { old_string, new_string } = input.target;
|
|
14554
|
+
let first = -1;
|
|
14555
|
+
let count = 0;
|
|
14556
|
+
for (let at = input.content.indexOf(old_string); at !== -1; at = input.content.indexOf(old_string, at + old_string.length)) {
|
|
14557
|
+
if (first === -1) first = at;
|
|
14558
|
+
count += 1;
|
|
14559
|
+
}
|
|
14560
|
+
if (count === 0) {
|
|
14561
|
+
throw new DomainError("E_UNIQUE_MATCH", {
|
|
14562
|
+
message: 'The "old_string" to replace was not found in the file. Nothing was written.'
|
|
14563
|
+
});
|
|
14564
|
+
}
|
|
14565
|
+
if (count > 1) {
|
|
14566
|
+
throw new DomainError("E_UNIQUE_MATCH", {
|
|
14567
|
+
message: `The "old_string" to replace matches ${count} places; it must match exactly once. Add surrounding content so it is unique. Nothing was written.`
|
|
14568
|
+
});
|
|
14569
|
+
}
|
|
14570
|
+
const start = first;
|
|
14571
|
+
const end = first + old_string.length;
|
|
14572
|
+
const nextContent = input.content.slice(0, start) + new_string + input.content.slice(end);
|
|
14573
|
+
if (nextContent === input.content) return { kind: "noop" };
|
|
14574
|
+
const preLines = splitLines(input.content);
|
|
14575
|
+
const startLine = lineOfOffset(input.content, start);
|
|
14576
|
+
const endLine = lineOfOffset(input.content, end - 1);
|
|
14577
|
+
const removedHashes = /* @__PURE__ */ new Set();
|
|
14578
|
+
for (let line = startLine; line <= endLine; line++) {
|
|
14579
|
+
const hash = input.hashes[line - 1];
|
|
14580
|
+
if (hash !== void 0) removedHashes.add(hash);
|
|
14581
|
+
}
|
|
14582
|
+
const removedLines = endLine - startLine + 1;
|
|
14583
|
+
const nextLineCount = splitLines(nextContent).length;
|
|
14584
|
+
const addedLines = nextLineCount - preLines.length + removedLines;
|
|
14585
|
+
const range = {
|
|
14586
|
+
startLine,
|
|
14587
|
+
endLine,
|
|
14588
|
+
startHash: input.hashes[startLine - 1] ?? "",
|
|
14589
|
+
endHash: input.hashes[endLine - 1] ?? "",
|
|
14590
|
+
delta: nextLineCount - preLines.length
|
|
14591
|
+
};
|
|
14592
|
+
const hashes = await lineHashes(
|
|
14593
|
+
nextContent,
|
|
14594
|
+
input.absolutePath,
|
|
14595
|
+
{ content: input.content, hashes: input.hashes, removedHashes },
|
|
14596
|
+
snapshotIOFor(input.store),
|
|
14597
|
+
false,
|
|
14598
|
+
input.blockedHashes
|
|
14599
|
+
);
|
|
14600
|
+
return {
|
|
14601
|
+
kind: "applied",
|
|
14602
|
+
content: nextContent,
|
|
14603
|
+
hashes,
|
|
14604
|
+
removedHashes,
|
|
14605
|
+
range,
|
|
14606
|
+
stats: { addedLines, removedLines }
|
|
14607
|
+
};
|
|
14608
|
+
}
|
|
14499
14609
|
async function applyOneEdit(input) {
|
|
14500
14610
|
abortIf(input.signal);
|
|
14501
14611
|
const identity = leaseSpanSource({
|
|
@@ -14623,6 +14733,10 @@ function parseEdits(items, path, itemNumbers) {
|
|
|
14623
14733
|
const failures = [];
|
|
14624
14734
|
for (let index = 0; index < items.length; index++) {
|
|
14625
14735
|
const item = items[index];
|
|
14736
|
+
if (item.string !== void 0) {
|
|
14737
|
+
parsed.push({ stringItem: item.string });
|
|
14738
|
+
continue;
|
|
14739
|
+
}
|
|
14626
14740
|
const number = itemNumbers?.[index] ?? index;
|
|
14627
14741
|
try {
|
|
14628
14742
|
const payload = item.payload;
|
|
@@ -14969,9 +15083,56 @@ async function runMutations(request, cwd, options, itemNumbers) {
|
|
|
14969
15083
|
);
|
|
14970
15084
|
continue;
|
|
14971
15085
|
}
|
|
14972
|
-
|
|
15086
|
+
let edit;
|
|
14973
15087
|
let outcome;
|
|
14974
|
-
if (
|
|
15088
|
+
if ("stringItem" in parsedItem) {
|
|
15089
|
+
try {
|
|
15090
|
+
const replaced = await applyStringEdit({
|
|
15091
|
+
target: parsedItem.stringItem,
|
|
15092
|
+
content: currentContent,
|
|
15093
|
+
hashes: currentHashes,
|
|
15094
|
+
signal: options?.signal,
|
|
15095
|
+
absolutePath,
|
|
15096
|
+
store: hashStore,
|
|
15097
|
+
blockedHashes: batchBlockedHashes
|
|
15098
|
+
});
|
|
15099
|
+
if (replaced.kind === "noop") {
|
|
15100
|
+
noopCount += 1;
|
|
15101
|
+
warnings.push(
|
|
15102
|
+
`edit[${number}] (${path}) was a noop: "old_string" equals "new_string"; nothing changed.`
|
|
15103
|
+
);
|
|
15104
|
+
continue;
|
|
15105
|
+
}
|
|
15106
|
+
outcome = {
|
|
15107
|
+
kind: "applied",
|
|
15108
|
+
content: replaced.content,
|
|
15109
|
+
hashes: replaced.hashes,
|
|
15110
|
+
removedHashes: replaced.removedHashes,
|
|
15111
|
+
range: replaced.range,
|
|
15112
|
+
firstChangedLine: replaced.range.startLine,
|
|
15113
|
+
lastChangedLine: replaced.range.endLine,
|
|
15114
|
+
anchorWarnings: void 0,
|
|
15115
|
+
literalBypass: false,
|
|
15116
|
+
neverServedCount: 0,
|
|
15117
|
+
sourceRange: void 0,
|
|
15118
|
+
mutationSpans: void 0,
|
|
15119
|
+
mutationStats: replaced.stats
|
|
15120
|
+
};
|
|
15121
|
+
} catch (error) {
|
|
15122
|
+
if (!(error instanceof DomainError)) throw error;
|
|
15123
|
+
await recordRejectionServe({
|
|
15124
|
+
error,
|
|
15125
|
+
sessionKey,
|
|
15126
|
+
absolutePath,
|
|
15127
|
+
isPreview,
|
|
15128
|
+
lineCount: currentHashes.length,
|
|
15129
|
+
contentHash: isPreview ? void 0 : snapshotHashFor(currentContent)
|
|
15130
|
+
});
|
|
15131
|
+
if (items.length === 1) throw error;
|
|
15132
|
+
throw batchAbortFor({ error, index: number, path });
|
|
15133
|
+
}
|
|
15134
|
+
} else if (item.expand === "item") {
|
|
15135
|
+
edit = parsedItem.edit;
|
|
14975
15136
|
try {
|
|
14976
15137
|
outcome = await applyExpandedItem({
|
|
14977
15138
|
edit,
|
|
@@ -15010,6 +15171,7 @@ async function runMutations(request, cwd, options, itemNumbers) {
|
|
|
15010
15171
|
throw batchAbortFor({ error, index: number, path });
|
|
15011
15172
|
}
|
|
15012
15173
|
} else {
|
|
15174
|
+
edit = parsedItem.edit;
|
|
15013
15175
|
outcome = await applyOneEdit({
|
|
15014
15176
|
content: currentContent,
|
|
15015
15177
|
hashes: currentHashes,
|
|
@@ -16474,7 +16636,7 @@ function isRec(value) {
|
|
|
16474
16636
|
function isNormalizedEdit(input) {
|
|
16475
16637
|
return isRec(input) && input[normalizedEdit] === true;
|
|
16476
16638
|
}
|
|
16477
|
-
var ITEM_SHAPE = 'an item is one payload over its anchor pair \u2014 `text` (optionally with `indent: "auto"` and, alone, `expand: "item"`), `text_ref`, or one insertion slot `after`/`before` (optionally with `indent: "auto"`) \u2014 plus optional `at`';
|
|
16639
|
+
var ITEM_SHAPE = 'an item is one payload over its anchor pair \u2014 `text` (optionally with `indent: "auto"` and, alone, `expand: "item"`), `text_ref`, or one insertion slot `after`/`before` (optionally with `indent: "auto"`) \u2014 plus optional `at`; OR a string-replacement item `{ old_string, new_string }` that replaces the unique occurrence of `old_string`';
|
|
16478
16640
|
var EDIT_PAYLOAD_HINT = `Edit must be called with exactly one payload per item, and each call edits ONE file. Use the canonical payload {"file": file, "edits": [{ "anchor_from": anchor_from, "anchor_to": anchor_to, "text": text }, ...], "mode"?: "general" | "literal"}: "file" is the text file to edit (a non-empty string, never a directory); each item names the bare-${HASH_LEN}-char anchor "anchor_from" (the first line of the range, and the whole range of a single-line edit), an optional second bare anchor "anchor_to" (the last line of a multi-line range; omit it to edit "anchor_from" alone) and exactly one payload \u2014 "text" (bare replacement content; an empty string deletes the range), "text_ref" ({ anchor_from, anchor_to, file?, mode (required): "copy" | "cut" } \u2014 the served span's bytes, whose two bounds are always required, and whose "file" may name another served file as the copy/cut source), or an insertion slot "after"/"before" (the exact lines to insert below/above the single anchor line, which is never restated); optional "at" is "in-place" (default), "before" or "after" (single-line resolved target only); optional "mode" is "general" (default, reproduced served rows are refused) or "literal" (declared literal content); optional "indent": "auto" re-bases a "text"/"after"/"before" payload on the leading whitespace of the line "anchor_from" names, and optional "expand": "item" replaces the whole syntax item around "anchor_from" (in-place "text" only: "anchor_to" is refused because the AST decides the end).`;
|
|
16479
16641
|
function describeReceived(input) {
|
|
16480
16642
|
if (input === void 0) return "Received no arguments.";
|
|
@@ -16535,7 +16697,8 @@ var ITEM_KEY_SETS = [
|
|
|
16535
16697
|
["anchor_from", "after"],
|
|
16536
16698
|
["anchor_from", "after", "anchor_to"],
|
|
16537
16699
|
["anchor_from", "before"],
|
|
16538
|
-
["anchor_from", "before", "anchor_to"]
|
|
16700
|
+
["anchor_from", "before", "anchor_to"],
|
|
16701
|
+
["old_string", "new_string"]
|
|
16539
16702
|
];
|
|
16540
16703
|
function keySetEquals(keys, shape) {
|
|
16541
16704
|
if (keys.size !== shape.length) return false;
|
|
@@ -16558,7 +16721,9 @@ function foldAbsentSlots(item) {
|
|
|
16558
16721
|
"after",
|
|
16559
16722
|
"before",
|
|
16560
16723
|
"indent",
|
|
16561
|
-
"expand"
|
|
16724
|
+
"expand",
|
|
16725
|
+
"old_string",
|
|
16726
|
+
"new_string"
|
|
16562
16727
|
]) {
|
|
16563
16728
|
if (isAbsentValue(folded[key])) delete folded[key];
|
|
16564
16729
|
}
|
|
@@ -16569,12 +16734,37 @@ function foldAbsentSlots(item) {
|
|
|
16569
16734
|
}
|
|
16570
16735
|
return folded;
|
|
16571
16736
|
}
|
|
16737
|
+
function analyzeStringItem(value, index, keys) {
|
|
16738
|
+
if (!keys.has("new_string")) {
|
|
16739
|
+
return `edit[${index}] "new_string" is required for string replacement: use "" to delete the matched text.`;
|
|
16740
|
+
}
|
|
16741
|
+
if (!keys.has("old_string")) {
|
|
16742
|
+
return `edit[${index}] "old_string" is required: the exact text to replace (it must occur exactly once in the file).`;
|
|
16743
|
+
}
|
|
16744
|
+
if (!keySetEquals(keys, ["old_string", "new_string"])) {
|
|
16745
|
+
return `edit[${index}] string replacement takes exactly "old_string" and "new_string" \u2014 delete any anchor, payload, "at", "indent" or "expand" field. (${ITEM_SHAPE})`;
|
|
16746
|
+
}
|
|
16747
|
+
if (value.indent !== void 0 || value.expand !== void 0) {
|
|
16748
|
+
return `edit[${index}] "old_string"/"new_string" string replacement takes no "indent" or "expand".`;
|
|
16749
|
+
}
|
|
16750
|
+
const { old_string, new_string } = value;
|
|
16751
|
+
if (typeof old_string !== "string" || old_string.length === 0) {
|
|
16752
|
+
return `edit[${index}] "old_string" must be a non-empty string: the exact text to replace, which must occur exactly once in the file.`;
|
|
16753
|
+
}
|
|
16754
|
+
if (typeof new_string !== "string") {
|
|
16755
|
+
return `edit[${index}] "new_string" must be a string (use "" to delete the matched text).`;
|
|
16756
|
+
}
|
|
16757
|
+
return void 0;
|
|
16758
|
+
}
|
|
16572
16759
|
function analyzeItem(value, index) {
|
|
16573
16760
|
if (!isRec(value)) {
|
|
16574
16761
|
return `edit[${index}] must be an object: ${ITEM_SHAPE}.`;
|
|
16575
16762
|
}
|
|
16576
16763
|
const modifierKeys = /* @__PURE__ */ new Set(["indent", "expand"]);
|
|
16577
16764
|
const keys = new Set(Object.keys(value).filter((key) => !modifierKeys.has(key)));
|
|
16765
|
+
if (keys.has("old_string") || keys.has("new_string")) {
|
|
16766
|
+
return analyzeStringItem(value, index, keys);
|
|
16767
|
+
}
|
|
16578
16768
|
const hasText = keys.has("text");
|
|
16579
16769
|
const hasRef = keys.has("text_ref");
|
|
16580
16770
|
const hasAfter = keys.has("after");
|
|
@@ -16770,6 +16960,14 @@ function analyzeRequest(input) {
|
|
|
16770
16960
|
return { ok: true, request: { file, edits: edited } };
|
|
16771
16961
|
}
|
|
16772
16962
|
function normalizedItemFrom(item) {
|
|
16963
|
+
if (item.old_string !== void 0) {
|
|
16964
|
+
return {
|
|
16965
|
+
target: { anchor_from: "", anchor_to: "" },
|
|
16966
|
+
at: "in-place",
|
|
16967
|
+
payload: { kind: "empty" },
|
|
16968
|
+
string: { old_string: item.old_string, new_string: item.new_string ?? "" }
|
|
16969
|
+
};
|
|
16970
|
+
}
|
|
16773
16971
|
const at = item.at ?? "in-place";
|
|
16774
16972
|
const payload = item.text_ref !== void 0 ? { kind: "reference", span: item.text_ref, mode: item.text_ref.mode } : item.after !== void 0 ? { kind: "insert", side: "after", text: item.after } : item.before !== void 0 ? { kind: "insert", side: "before", text: item.before } : item.text === "" ? { kind: "empty" } : { kind: "literal", text: item.text ?? "" };
|
|
16775
16973
|
const target = {
|
|
@@ -16811,6 +17009,10 @@ function isNormalizedEditItem(value) {
|
|
|
16811
17009
|
if (!isRec(value)) return false;
|
|
16812
17010
|
if (value.indent !== void 0 && value.indent !== "auto") return false;
|
|
16813
17011
|
if (value.expand !== void 0 && value.expand !== "item") return false;
|
|
17012
|
+
if (isRec(value.string)) {
|
|
17013
|
+
const s = value.string;
|
|
17014
|
+
return typeof s.old_string === "string" && s.old_string.length > 0 && typeof s.new_string === "string";
|
|
17015
|
+
}
|
|
16814
17016
|
const { target, at, payload } = value;
|
|
16815
17017
|
if (!isRec(target)) return false;
|
|
16816
17018
|
if (typeof target.anchor_from !== "string" || typeof target.anchor_to !== "string") return false;
|
|
@@ -17153,8 +17355,7 @@ var EDIT_PARAMETERS = {
|
|
|
17153
17355
|
properties: {
|
|
17154
17356
|
anchor_from: {
|
|
17155
17357
|
type: "string",
|
|
17156
|
-
|
|
17157
|
-
description: "Bare hash anchor of the first range line (inclusive)"
|
|
17358
|
+
description: "Bare hash anchor of the first range line (inclusive); omit it to use old_string/new_string string replacement instead"
|
|
17158
17359
|
},
|
|
17159
17360
|
anchor_to: {
|
|
17160
17361
|
oneOf: [
|
|
@@ -17257,6 +17458,24 @@ var EDIT_PARAMETERS = {
|
|
|
17257
17458
|
},
|
|
17258
17459
|
{ type: "null" }
|
|
17259
17460
|
]
|
|
17461
|
+
},
|
|
17462
|
+
old_string: {
|
|
17463
|
+
oneOf: [
|
|
17464
|
+
{
|
|
17465
|
+
type: "string",
|
|
17466
|
+
description: "Exact text to replace (must occur exactly once in the file); use it together with new_string, instead of anchor_from+text, for native str_replace-style string replacement"
|
|
17467
|
+
},
|
|
17468
|
+
{ type: "null" }
|
|
17469
|
+
]
|
|
17470
|
+
},
|
|
17471
|
+
new_string: {
|
|
17472
|
+
oneOf: [
|
|
17473
|
+
{
|
|
17474
|
+
type: "string",
|
|
17475
|
+
description: 'Replacement text for old_string (use "" to delete the matched text); a call may mix this with anchor items'
|
|
17476
|
+
},
|
|
17477
|
+
{ type: "null" }
|
|
17478
|
+
]
|
|
17260
17479
|
}
|
|
17261
17480
|
}
|
|
17262
17481
|
}
|
|
@@ -18939,7 +19158,7 @@ var Config = Schema.object({
|
|
|
18939
19158
|
rg: Schema.boolean().default(true).volatile(),
|
|
18940
19159
|
rgPath: Schema.string().default("").volatile(),
|
|
18941
19160
|
writeAutoRead: Schema.boolean().default(false).volatile(),
|
|
18942
|
-
|
|
19161
|
+
rowGutter: Schema.string().default("arrow").volatile()
|
|
18943
19162
|
});
|
|
18944
19163
|
function switchValue(value, fallback) {
|
|
18945
19164
|
if (typeof value === "boolean") return value;
|
|
@@ -18965,6 +19184,10 @@ function stringValue(value, fallback) {
|
|
|
18965
19184
|
}
|
|
18966
19185
|
return fallback;
|
|
18967
19186
|
}
|
|
19187
|
+
function rowGutterValue(value) {
|
|
19188
|
+
const raw = stringValue(value, "arrow");
|
|
19189
|
+
return raw === "native" || raw === "bare" ? raw : "arrow";
|
|
19190
|
+
}
|
|
18968
19191
|
function resolveSwitches(config = {}) {
|
|
18969
19192
|
const fields = config;
|
|
18970
19193
|
return {
|
|
@@ -18977,7 +19200,7 @@ function resolveSwitches(config = {}) {
|
|
|
18977
19200
|
rg: switchValue(fields.rg, true),
|
|
18978
19201
|
rgPath: stringValue(fields.rgPath, ""),
|
|
18979
19202
|
writeAutoRead: switchValue(fields.writeAutoRead, false),
|
|
18980
|
-
|
|
19203
|
+
rowGutter: rowGutterValue(fields.rowGutter)
|
|
18981
19204
|
};
|
|
18982
19205
|
}
|
|
18983
19206
|
function toolsOfAgent(agent) {
|
|
@@ -18996,7 +19219,7 @@ function toolsOfAgent(agent) {
|
|
|
18996
19219
|
}
|
|
18997
19220
|
function installAgentTools(rootCtx, agent, metrics, config = {}) {
|
|
18998
19221
|
const switches = resolveSwitches(config);
|
|
18999
|
-
applyConfigRowGutter(switches.
|
|
19222
|
+
applyConfigRowGutter(switches.rowGutter);
|
|
19000
19223
|
configureAnchorSpace();
|
|
19001
19224
|
return agent.ctx.effect(() => {
|
|
19002
19225
|
const agentTools = toolsOfAgent(agent);
|
|
@@ -19143,7 +19366,7 @@ function liveAgentsFrom(rootCtx) {
|
|
|
19143
19366
|
}
|
|
19144
19367
|
function apply2(rootCtx, config = {}) {
|
|
19145
19368
|
const switches = resolveSwitches(config);
|
|
19146
|
-
applyConfigRowGutter(switches.
|
|
19369
|
+
applyConfigRowGutter(switches.rowGutter);
|
|
19147
19370
|
configureAnchorSpace();
|
|
19148
19371
|
if (typeof rootCtx.systemPrompt?.section === "function") {
|
|
19149
19372
|
rootCtx.effect(
|
package/lib/types/dsh/index.d.ts
CHANGED
|
@@ -21,6 +21,7 @@ import type { Context } from "@deepseek-ai/cordis";
|
|
|
21
21
|
import type { Agent } from "@deepseek-ai/dsh-agent";
|
|
22
22
|
import Schema from "@deepseek-ai/schemastery";
|
|
23
23
|
import { type ToolMetrics } from "./metrics/instrument.js";
|
|
24
|
+
import { type RowGutter } from "../src/hashline/row-mode.js";
|
|
24
25
|
/** Cordis plugin name used by loader diagnostics. */
|
|
25
26
|
export declare const name = "dsh-hashline-edit";
|
|
26
27
|
/**
|
|
@@ -43,7 +44,7 @@ export declare const Config: Schema<Schemastery.ObjectS<NoInfer<{
|
|
|
43
44
|
rg: Schema<boolean, boolean, "volatile-defined">;
|
|
44
45
|
rgPath: Schema<string, string, "volatile-defined">;
|
|
45
46
|
writeAutoRead: Schema<boolean, boolean, "volatile-defined">;
|
|
46
|
-
|
|
47
|
+
rowGutter: Schema<string, string, "volatile-defined">;
|
|
47
48
|
}>>, Schemastery.ObjectT<NoInfer<{
|
|
48
49
|
read: Schema<boolean, boolean, "volatile-defined">;
|
|
49
50
|
applyPatch: Schema<boolean, boolean, "volatile-defined">;
|
|
@@ -54,7 +55,7 @@ export declare const Config: Schema<Schemastery.ObjectS<NoInfer<{
|
|
|
54
55
|
rg: Schema<boolean, boolean, "volatile-defined">;
|
|
55
56
|
rgPath: Schema<string, string, "volatile-defined">;
|
|
56
57
|
writeAutoRead: Schema<boolean, boolean, "volatile-defined">;
|
|
57
|
-
|
|
58
|
+
rowGutter: Schema<string, string, "volatile-defined">;
|
|
58
59
|
}>>, "plain">;
|
|
59
60
|
/** The plugin configuration the loader passes as the second `apply` argument. */
|
|
60
61
|
export interface PluginConfig {
|
|
@@ -118,6 +119,13 @@ export interface PluginConfig {
|
|
|
118
119
|
* refusal guard runs either way.
|
|
119
120
|
*/
|
|
120
121
|
writeAutoRead?: boolean;
|
|
122
|
+
/**
|
|
123
|
+
* Row rendering mode. `arrow` (default) prefixes each served row with `12→`; `native` uses
|
|
124
|
+
* `12: `; `bare` shows no line numbers at all — rows are bare `HASH│content` and anchors are
|
|
125
|
+
* drawn from the full base62 space (no codebook, no digit reservation). Changing the mode is a
|
|
126
|
+
* fresh anchor generation, so served rows are simply re-read.
|
|
127
|
+
*/
|
|
128
|
+
rowGutter?: "arrow" | "native" | "bare";
|
|
121
129
|
}
|
|
122
130
|
/** The feature switches after the shipped defaults are applied. */
|
|
123
131
|
export interface ResolvedSwitches {
|
|
@@ -130,7 +138,7 @@ export interface ResolvedSwitches {
|
|
|
130
138
|
readonly rg: boolean;
|
|
131
139
|
readonly rgPath: string;
|
|
132
140
|
readonly writeAutoRead: boolean;
|
|
133
|
-
readonly
|
|
141
|
+
readonly rowGutter: RowGutter;
|
|
134
142
|
}
|
|
135
143
|
/** Resolve the plugin's switches with the shipped defaults: read, apply_patch and rg on; edit, codegraph, diagnostics and the write auto-read off. */
|
|
136
144
|
export declare function resolveSwitches(config?: PluginConfig): ResolvedSwitches;
|
|
@@ -1,8 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
export { ROW_GUTTER_ENV_VAR, ROW_GUTTER_DEFAULT, resolveRowGutter, getRowGutter, applyConfigRowGutter, } from "./row-mode.js";
|
|
3
|
-
/** The prefix one numbered row carries before its anchor/content: `12→` (arrow) or `12: ` (native). */
|
|
1
|
+
/** The prefix one numbered row carries before its anchor/content: `12→` (arrow), `12: ` (native), or "" (bare: no line numbers). */
|
|
4
2
|
export declare function lineGutter(lineNumber: number): string;
|
|
5
|
-
/** The prefix a folded range row carries: `12..30→` (arrow)
|
|
3
|
+
/** The prefix a folded range row carries: `12..30→` (arrow), `12..30: ` (native), or "" (bare: no line numbers). */
|
|
6
4
|
export declare function rangeGutter(startLine: number, endLine: number): string;
|
|
7
5
|
/**
|
|
8
6
|
* Regex source for one optional row gutter prefix (arrow or native, single line or folded range),
|
|
@@ -2,12 +2,14 @@
|
|
|
2
2
|
* The active line-number gutter mode, shared by every renderer and by the anchor codebook.
|
|
3
3
|
*
|
|
4
4
|
* WHY module state + a setter rather than a load-time constant: the mode is a live plugin setting
|
|
5
|
-
* (the `
|
|
6
|
-
* calls `applyConfigRowGutter()` then `configureAnchorSpace()` so the
|
|
7
|
-
* generation all follow the switch.
|
|
8
|
-
*
|
|
5
|
+
* (the `rowGutter` Volatile switch: `arrow` / `native` / `bare`). The host re-mounts agents on a
|
|
6
|
+
* volatile update, and the plugin calls `applyConfigRowGutter()` then `configureAnchorSpace()` so the
|
|
7
|
+
* codebook, capacity and anchor generation all follow the switch. A `bare` switch additionally drops
|
|
8
|
+
* the two-token codebook and the all-digit reservation (full base62, no line numbers). Changing the
|
|
9
|
+
* mode invalidates old anchors (new generation) — the caller opens a fresh session.
|
|
10
|
+
* `PI_BETTER_EDIT_ROW_GUTTER` pins the mode for tests/CI and wins over config.
|
|
9
11
|
*/
|
|
10
|
-
export type RowGutter = "arrow" | "native";
|
|
12
|
+
export type RowGutter = "arrow" | "native" | "bare";
|
|
11
13
|
export declare const ROW_GUTTER_ENV_VAR = "PI_BETTER_EDIT_ROW_GUTTER";
|
|
12
14
|
/** Arrow is the default: it does not merge with the following anchor token. */
|
|
13
15
|
export declare const ROW_GUTTER_DEFAULT: RowGutter;
|
|
@@ -33,6 +33,16 @@ export type NormalizedEditItem = {
|
|
|
33
33
|
indent?: "auto";
|
|
34
34
|
/** Admitted `expand` mode (ADR-0031): the AST decides the target span's end. */
|
|
35
35
|
expand?: "item";
|
|
36
|
+
/**
|
|
37
|
+
* String-replacement target: present only for a native str_replace-style item. When set, the
|
|
38
|
+
* engine matches `old_string` (must be unique) against the working buffer and splices
|
|
39
|
+
* `new_string` character-for-character, ignoring `target`/`payload`/`at`. A call may mix these
|
|
40
|
+
* with anchor items.
|
|
41
|
+
*/
|
|
42
|
+
string?: {
|
|
43
|
+
old_string: string;
|
|
44
|
+
new_string: string;
|
|
45
|
+
};
|
|
36
46
|
};
|
|
37
47
|
export type NormalizedEditRequest = {
|
|
38
48
|
file: string;
|
|
@@ -59,6 +59,11 @@ type NormalizedEditItem = {
|
|
|
59
59
|
indent?: "auto";
|
|
60
60
|
/** Admitted `expand` mode (ADR-0031): the AST decides the target span's end. */
|
|
61
61
|
expand?: "item";
|
|
62
|
+
/** String-replacement target (present only on a string item; exclusive with anchor addressing). */
|
|
63
|
+
string?: {
|
|
64
|
+
old_string: string;
|
|
65
|
+
new_string: string;
|
|
66
|
+
};
|
|
62
67
|
};
|
|
63
68
|
export type NormalizedEditRequest = {
|
|
64
69
|
file: string;
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* WHY: beside the DDL, so the retry model and the stamp cannot be read from two modules that drift.
|
|
7
7
|
*/
|
|
8
8
|
export declare const HASH_STORE_BUSY_TIMEOUT = 250;
|
|
9
|
-
export declare const HASH_STORE_VERSION =
|
|
9
|
+
export declare const HASH_STORE_VERSION = 12;
|
|
10
10
|
declare const BUSY_MAX_ATTEMPTS = 8;
|
|
11
11
|
declare const BUSY_BACKOFF_BASE_MS = 50;
|
|
12
12
|
declare const BUSY_BACKOFF_CAP_MS = 400;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-hashline-edit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Hash-anchored read/apply_patch/edit tools for DeepSeek Harness (dsh). Every line gets a unique 3- or 4-char hash (A-Za-z0-9, configurable) that stays stable across edits; apply_patch and the anchored range edit tool are the file-mutation entry points, each committing its whole batch as one transaction.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"anchors",
|
package/prompts/edit.md
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
Change one or more line ranges in one target text file with hash anchors: pass `file`, `edits` (one item per change), and optional top-level `mode` (`"general"` by default, or `"literal"`). Each item names one inclusive bare `{{HASH_LEN}}`-character anchor from before `│` in served rows (`anchor_from`), an optional second one closing a multi-line range (`anchor_to` — omit it to edit the single line `anchor_from` names; pass the identical hash to spell a single line explicitly), optional `at` (`"in-place"` by default; `"before"` or `"after"` inserts at a single-line target), and exactly one payload — `text` for replacement content (`""` deletes the span when `at` is `"in-place"`, and is a no-op with `"before"`/`"after"`) or `text_ref` (`{ anchor_from, anchor_to, file?, mode: "copy" | "cut" }`, whose two bounds are always required, where required `mode` `"copy"` re-inserts the served span's bytes and `"cut"` also deletes the source lines). One call targets one `file`; only `text_ref.file` may reference another served file as the copy/cut source (with `"cut"` deleting those source lines in the same correlated transaction). A rejected call writes nothing. Two shortcuts cover the common pure insertions: `after` and `before` each carry the exact lines to place immediately below or above the single line `anchor_from` names, instead of spelling `at` plus `text`. An item still carries exactly one payload — `text`, `text_ref`, `after`, or `before`.
|
|
2
2
|
|
|
3
3
|
Two optional modifiers change where and how much the payload replaces. `indent: "auto"` (default `"as-is"`) re-bases a `text`/`after`/`before` payload on the leading whitespace of the line `anchor_from` names: write the snippet flush-left — or at any uniform extra indentation — and the tool drops the snippet's own shared leading-whitespace prefix, then writes every non-blank line at the anchor line's depth. Tabs and spaces stay literal (no conversion), blank lines are left as written, and `text_ref` refuses `indent` because those bytes are copied verbatim; the result's notes name the depth it landed at. `expand: "item"` replaces the whole syntax item that contains `anchor_from` — its leading doc comment/attributes/decorators and its matching closing brace — instead of a range you spell out: name only `anchor_from` (`anchor_to` is refused, because the AST decides the end) with a `text` payload, on a shipped code grammar (rust, typescript, tsx, vue, python, go, java). Prefer `expand` over hand-writing a whole function, class or method: you never have to reproduce the doc comment or the closing brace, and the diff shows the expanded range it replaced. A non-code file, an unavailable grammar, or an anchor outside any syntax item refuses and writes nothing. An expanded item must be the only item in its call.
|
|
4
|
+
String replacement (native `str_replace` style) is an alternative when anchors are unavailable or awkward: an item may instead be `{ old_string, new_string }`, which replaces the exact, unique occurrence of `old_string` with `new_string` character-for-character (a match inside one line is fine). `old_string` must occur exactly once — zero or multiple matches refuse and write nothing — so include surrounding content to make it unique. A call may mix anchor items and string items: each item is one or the other, and items apply in order, each to the result of the previous.
|
package/src/hash-store.ts
CHANGED
|
@@ -545,6 +545,9 @@ export function ensureSnapshotTables(db: DatabaseSync): void {
|
|
|
545
545
|
db.exec(`DELETE FROM served_leases WHERE ${FOREIGN_GENERATION_LEASE_SQL}`);
|
|
546
546
|
}
|
|
547
547
|
db.exec(`DELETE FROM file_snapshots WHERE ${FOREIGN_GENERATION_SNAPSHOT_SQL}`);
|
|
548
|
+
if (hasTable("file_undo") && readTableColumns(db, "file_undo").has("anchor_generation")) {
|
|
549
|
+
db.exec(`DELETE FROM file_undo WHERE anchor_generation NOT IN (0, ${ANCHOR_GENERATION})`);
|
|
550
|
+
}
|
|
548
551
|
db.exec(`DELETE FROM line_lineage WHERE ${ORPHAN_LINEAGE_SQL}`);
|
|
549
552
|
// WHY: one provenance rule as of this sweep — a lease that names no surviving
|
|
550
553
|
// WHY: snapshot for its own path is dangling (same-generation pre-column rows read
|
|
@@ -651,6 +654,50 @@ export function ensureFileUndoSchema(db: DatabaseSync): void {
|
|
|
651
654
|
addColumnIfMissing(db, "cut_intent", "direction");
|
|
652
655
|
}
|
|
653
656
|
|
|
657
|
+
/**
|
|
658
|
+
* WHY: deleted rows leave free pages SQLite never returns to the OS without a VACUUM, so a large
|
|
659
|
+
* generation/schema migration (or months of TTL pruning) can leave the file tens of times its live
|
|
660
|
+
* size — the 1.16GB-for-100MB case that made every open of a big store crawl. After the slow-path
|
|
661
|
+
* sweep we checkpoint the WAL and, when free pages dominate, switch to incremental auto-vacuum and
|
|
662
|
+
* VACUUM once; later TTL deletes are then reclaimed cheaply by `PRAGMA incremental_vacuum`.
|
|
663
|
+
*/
|
|
664
|
+
function reclaimStoreSpace(db: DatabaseSync): void {
|
|
665
|
+
try {
|
|
666
|
+
db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
667
|
+
} catch {
|
|
668
|
+
// WHY: best-effort: a held reader only defers the truncate
|
|
669
|
+
}
|
|
670
|
+
try {
|
|
671
|
+
const total = Number(
|
|
672
|
+
(db.prepare("PRAGMA page_count").get() as { page_count?: number }).page_count ?? 0,
|
|
673
|
+
);
|
|
674
|
+
const free = Number(
|
|
675
|
+
(db.prepare("PRAGMA freelist_count").get() as { freelist_count?: number }).freelist_count ??
|
|
676
|
+
0,
|
|
677
|
+
);
|
|
678
|
+
if (total > 0 && free > 2048 && free / total > 0.2) {
|
|
679
|
+
try {
|
|
680
|
+
db.exec("PRAGMA auto_vacuum = INCREMENTAL");
|
|
681
|
+
} catch {
|
|
682
|
+
// WHY: pre-existing auto_vacuum cannot always be changed; the standalone VACUUM below still reclaims
|
|
683
|
+
}
|
|
684
|
+
db.exec("VACUUM");
|
|
685
|
+
try {
|
|
686
|
+
db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
687
|
+
} catch {
|
|
688
|
+
// WHY: best-effort
|
|
689
|
+
}
|
|
690
|
+
} else {
|
|
691
|
+
try {
|
|
692
|
+
db.exec("PRAGMA incremental_vacuum");
|
|
693
|
+
} catch {
|
|
694
|
+
// WHY: best-effort
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
} catch {
|
|
698
|
+
// WHY: best-effort: space reclamation must never fail an otherwise-good open
|
|
699
|
+
}
|
|
700
|
+
}
|
|
654
701
|
function buildStore(db: DatabaseSync): boolean {
|
|
655
702
|
// WHY: the open's stamp-due decision is made ONCE here and handed back through `openDb`: it gates the
|
|
656
703
|
// WHY: sweep below and the `version` upsert at the end, and it is what `openStore` owes a stamp write
|
|
@@ -772,6 +819,7 @@ function buildStore(db: DatabaseSync): boolean {
|
|
|
772
819
|
// WHY: its value is a build constant, so it belongs to the build. The halves that certify the WHOLE
|
|
773
820
|
// WHY: open are owed to `openStore` instead: written here they would certify hook work that has not run.
|
|
774
821
|
if (!stampDue) return false;
|
|
822
|
+
reclaimStoreSpace(db);
|
|
775
823
|
db.prepare(
|
|
776
824
|
"INSERT INTO meta (key, value) VALUES ('version', ?) " +
|
|
777
825
|
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
package/src/hashline/gutter.ts
CHANGED
|
@@ -4,23 +4,18 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import { getRowGutter } from "./row-mode.js";
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
export {
|
|
9
|
-
ROW_GUTTER_ENV_VAR,
|
|
10
|
-
ROW_GUTTER_DEFAULT,
|
|
11
|
-
resolveRowGutter,
|
|
12
|
-
getRowGutter,
|
|
13
|
-
applyConfigRowGutter,
|
|
14
|
-
} from "./row-mode.js";
|
|
15
|
-
|
|
16
|
-
/** The prefix one numbered row carries before its anchor/content: `12→` (arrow) or `12: ` (native). */
|
|
7
|
+
/** The prefix one numbered row carries before its anchor/content: `12→` (arrow), `12: ` (native), or "" (bare: no line numbers). */
|
|
17
8
|
export function lineGutter(lineNumber: number): string {
|
|
18
|
-
|
|
9
|
+
const mode = getRowGutter();
|
|
10
|
+
if (mode === "bare") return "";
|
|
11
|
+
return mode === "native" ? `${lineNumber}: ` : `${lineNumber}→`;
|
|
19
12
|
}
|
|
20
13
|
|
|
21
|
-
/** The prefix a folded range row carries: `12..30→` (arrow)
|
|
14
|
+
/** The prefix a folded range row carries: `12..30→` (arrow), `12..30: ` (native), or "" (bare: no line numbers). */
|
|
22
15
|
export function rangeGutter(startLine: number, endLine: number): string {
|
|
23
|
-
|
|
16
|
+
const mode = getRowGutter();
|
|
17
|
+
if (mode === "bare") return "";
|
|
18
|
+
return mode === "native" ? `${startLine}..${endLine}: ` : `${startLine}..${endLine}→`;
|
|
24
19
|
}
|
|
25
20
|
|
|
26
21
|
/**
|
|
@@ -82,6 +82,9 @@ function popcount32(value: number): number {
|
|
|
82
82
|
|
|
83
83
|
function buildReservedBits(): Uint32Array {
|
|
84
84
|
const bits = new Uint32Array(BITSET_WORDS);
|
|
85
|
+
// WHY: bare mode renders no line-number gutter, so neither the all-digit subcube reservation
|
|
86
|
+
// WHY: nor the width-3 two-token codebook applies — every base62 spelling is usable.
|
|
87
|
+
if (getRowGutter() === "bare") return bits;
|
|
85
88
|
if (HASH_LEN === ANCHOR_CODEBOOK_WIDTH) {
|
|
86
89
|
// WHY: the codebook artifact is an ALLOWED bitmap; reserve its complement.
|
|
87
90
|
const allowed = Buffer.from(
|
|
@@ -113,7 +116,7 @@ function buildReservedBits(): Uint32Array {
|
|
|
113
116
|
}
|
|
114
117
|
|
|
115
118
|
// WHY: the active codebook follows the runtime gutter mode, so these are live `let` bindings that
|
|
116
|
-
// WHY: `configureAnchorSpace()` refreshes when the plugin's `
|
|
119
|
+
// WHY: `configureAnchorSpace()` refreshes when the plugin's `rowGutter` switch changes (Volatile config).
|
|
117
120
|
let RESERVED_BITS: Uint32Array = buildReservedBits();
|
|
118
121
|
export let USABLE_HASH_SPACE = HASH_SPACE - RESERVED_BITS.reduce((t, w) => t + popcount32(w), 0);
|
|
119
122
|
export let MAX_HASH_LINES = USABLE_HASH_SPACE;
|
|
@@ -166,6 +169,9 @@ export const CANON_VERSION = 3;
|
|
|
166
169
|
* their anchors; width 3 gets generation 2, and any future width gets `100 + width`.
|
|
167
170
|
*/
|
|
168
171
|
export function anchorGenerationFor(width: number, gutter: RowGutter = getRowGutter()): number {
|
|
172
|
+
// WHY: bare mode reserves nothing (full base62), so its anchor assignment differs from arrow and
|
|
173
|
+
// WHY: native at the same width — each needs its own generation so their stores never mix.
|
|
174
|
+
if (gutter === "bare") return width === 4 ? 6 : width === 3 ? 5 : 200 + width;
|
|
169
175
|
if (width === 4) return 1;
|
|
170
176
|
if (width === 3) return gutter === "native" ? 4 : 3;
|
|
171
177
|
return 100 + width;
|
package/src/hashline/row-mode.ts
CHANGED
|
@@ -2,12 +2,14 @@
|
|
|
2
2
|
* The active line-number gutter mode, shared by every renderer and by the anchor codebook.
|
|
3
3
|
*
|
|
4
4
|
* WHY module state + a setter rather than a load-time constant: the mode is a live plugin setting
|
|
5
|
-
* (the `
|
|
6
|
-
* calls `applyConfigRowGutter()` then `configureAnchorSpace()` so the
|
|
7
|
-
* generation all follow the switch.
|
|
8
|
-
*
|
|
5
|
+
* (the `rowGutter` Volatile switch: `arrow` / `native` / `bare`). The host re-mounts agents on a
|
|
6
|
+
* volatile update, and the plugin calls `applyConfigRowGutter()` then `configureAnchorSpace()` so the
|
|
7
|
+
* codebook, capacity and anchor generation all follow the switch. A `bare` switch additionally drops
|
|
8
|
+
* the two-token codebook and the all-digit reservation (full base62, no line numbers). Changing the
|
|
9
|
+
* mode invalidates old anchors (new generation) — the caller opens a fresh session.
|
|
10
|
+
* `PI_BETTER_EDIT_ROW_GUTTER` pins the mode for tests/CI and wins over config.
|
|
9
11
|
*/
|
|
10
|
-
export type RowGutter = "arrow" | "native";
|
|
12
|
+
export type RowGutter = "arrow" | "native" | "bare";
|
|
11
13
|
|
|
12
14
|
export const ROW_GUTTER_ENV_VAR = "PI_BETTER_EDIT_ROW_GUTTER";
|
|
13
15
|
|
|
@@ -20,8 +22,9 @@ export function resolveRowGutter(env: Record<string, string | undefined>): RowGu
|
|
|
20
22
|
const value = raw.trim().toLowerCase();
|
|
21
23
|
if (value === "arrow") return "arrow";
|
|
22
24
|
if (value === "native") return "native";
|
|
25
|
+
if (value === "bare") return "bare";
|
|
23
26
|
throw new Error(
|
|
24
|
-
`${ROW_GUTTER_ENV_VAR} must be "arrow" or "
|
|
27
|
+
`${ROW_GUTTER_ENV_VAR} must be "arrow", "native" or "bare" (got ${JSON.stringify(raw)}).`,
|
|
25
28
|
);
|
|
26
29
|
}
|
|
27
30
|
|
|
@@ -29,6 +29,13 @@ export type NormalizedEditItem = {
|
|
|
29
29
|
indent?: "auto";
|
|
30
30
|
/** Admitted `expand` mode (ADR-0031): the AST decides the target span's end. */
|
|
31
31
|
expand?: "item";
|
|
32
|
+
/**
|
|
33
|
+
* String-replacement target: present only for a native str_replace-style item. When set, the
|
|
34
|
+
* engine matches `old_string` (must be unique) against the working buffer and splices
|
|
35
|
+
* `new_string` character-for-character, ignoring `target`/`payload`/`at`. A call may mix these
|
|
36
|
+
* with anchor items.
|
|
37
|
+
*/
|
|
38
|
+
string?: { old_string: string; new_string: string };
|
|
32
39
|
};
|
|
33
40
|
|
|
34
41
|
export type NormalizedEditRequest = {
|
|
@@ -248,6 +248,102 @@ function autoIndentedEdit(
|
|
|
248
248
|
};
|
|
249
249
|
}
|
|
250
250
|
|
|
251
|
+
/** One string-replacement item's resolved effect on the working buffer. */
|
|
252
|
+
type StringEditResolution =
|
|
253
|
+
| { kind: "noop" }
|
|
254
|
+
| {
|
|
255
|
+
kind: "applied";
|
|
256
|
+
content: string;
|
|
257
|
+
hashes: string[];
|
|
258
|
+
removedHashes: Set<string>;
|
|
259
|
+
range: ResolvedRange;
|
|
260
|
+
stats: { addedLines: number; removedLines: number };
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
/** 1-based line number of the character at `offset` in `content`. */
|
|
264
|
+
function lineOfOffset(content: string, offset: number): number {
|
|
265
|
+
let line = 1;
|
|
266
|
+
for (let i = 0; i < offset; i++) if (content.charCodeAt(i) === 10) line += 1;
|
|
267
|
+
return line;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Native str_replace-style item: replace the unique occurrence of `old_string` with `new_string`
|
|
272
|
+
* character-for-character on the working buffer. No anchor lease is consulted — the match itself
|
|
273
|
+
* is the safety: zero matches and multiple matches are refused and nothing is written. Hashes are
|
|
274
|
+
* recomputed with the same stable remap the anchor path uses, so unchanged lines keep their anchors.
|
|
275
|
+
*/
|
|
276
|
+
async function applyStringEdit(input: {
|
|
277
|
+
target: { old_string: string; new_string: string };
|
|
278
|
+
content: string;
|
|
279
|
+
hashes: string[];
|
|
280
|
+
signal?: AbortSignal | undefined;
|
|
281
|
+
absolutePath: string;
|
|
282
|
+
store: HashStore;
|
|
283
|
+
blockedHashes?: ReadonlySet<string>;
|
|
284
|
+
}): Promise<StringEditResolution> {
|
|
285
|
+
abortIf(input.signal);
|
|
286
|
+
const { old_string, new_string } = input.target;
|
|
287
|
+
let first = -1;
|
|
288
|
+
let count = 0;
|
|
289
|
+
for (
|
|
290
|
+
let at = input.content.indexOf(old_string);
|
|
291
|
+
at !== -1;
|
|
292
|
+
at = input.content.indexOf(old_string, at + old_string.length)
|
|
293
|
+
) {
|
|
294
|
+
if (first === -1) first = at;
|
|
295
|
+
count += 1;
|
|
296
|
+
}
|
|
297
|
+
if (count === 0) {
|
|
298
|
+
throw new DomainError("E_UNIQUE_MATCH", {
|
|
299
|
+
message: 'The "old_string" to replace was not found in the file. Nothing was written.',
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
if (count > 1) {
|
|
303
|
+
throw new DomainError("E_UNIQUE_MATCH", {
|
|
304
|
+
message: `The "old_string" to replace matches ${count} places; it must match exactly once. Add surrounding content so it is unique. Nothing was written.`,
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
const start = first;
|
|
308
|
+
const end = first + old_string.length;
|
|
309
|
+
const nextContent = input.content.slice(0, start) + new_string + input.content.slice(end);
|
|
310
|
+
if (nextContent === input.content) return { kind: "noop" };
|
|
311
|
+
const preLines = splitLines(input.content);
|
|
312
|
+
const startLine = lineOfOffset(input.content, start);
|
|
313
|
+
const endLine = lineOfOffset(input.content, end - 1);
|
|
314
|
+
const removedHashes = new Set<string>();
|
|
315
|
+
for (let line = startLine; line <= endLine; line++) {
|
|
316
|
+
const hash = input.hashes[line - 1];
|
|
317
|
+
if (hash !== undefined) removedHashes.add(hash);
|
|
318
|
+
}
|
|
319
|
+
const removedLines = endLine - startLine + 1;
|
|
320
|
+
const nextLineCount = splitLines(nextContent).length;
|
|
321
|
+
const addedLines = nextLineCount - preLines.length + removedLines;
|
|
322
|
+
const range: ResolvedRange = {
|
|
323
|
+
startLine,
|
|
324
|
+
endLine,
|
|
325
|
+
startHash: input.hashes[startLine - 1] ?? "",
|
|
326
|
+
endHash: input.hashes[endLine - 1] ?? "",
|
|
327
|
+
delta: nextLineCount - preLines.length,
|
|
328
|
+
};
|
|
329
|
+
const hashes = await lineHashes(
|
|
330
|
+
nextContent,
|
|
331
|
+
input.absolutePath,
|
|
332
|
+
{ content: input.content, hashes: input.hashes, removedHashes },
|
|
333
|
+
snapshotIOFor(input.store),
|
|
334
|
+
false,
|
|
335
|
+
input.blockedHashes,
|
|
336
|
+
);
|
|
337
|
+
return {
|
|
338
|
+
kind: "applied",
|
|
339
|
+
content: nextContent,
|
|
340
|
+
hashes,
|
|
341
|
+
removedHashes,
|
|
342
|
+
range,
|
|
343
|
+
stats: { addedLines, removedLines },
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
|
|
251
347
|
async function applyOneEdit(input: ApplyOneEditInput): Promise<ApplyOneEditOutcome> {
|
|
252
348
|
abortIf(input.signal);
|
|
253
349
|
|
|
@@ -410,7 +506,10 @@ function replacementTextForPayload(payload: DesiredContent): string {
|
|
|
410
506
|
* WHY: never reaches `applyEdit` and never consults the noop-loop tracker (no bytes are rewritten,
|
|
411
507
|
* WHY: so there is no repeated-content episode to count).
|
|
412
508
|
*/
|
|
413
|
-
type ParsedItem =
|
|
509
|
+
type ParsedItem =
|
|
510
|
+
| { edit: HEdit }
|
|
511
|
+
| { noopInsert: true }
|
|
512
|
+
| { stringItem: { old_string: string; new_string: string } };
|
|
414
513
|
|
|
415
514
|
function parseEdits(
|
|
416
515
|
items: NormalizedEditRequest["edits"],
|
|
@@ -424,6 +523,10 @@ function parseEdits(
|
|
|
424
523
|
const failures: { error: Error; index: number }[] = [];
|
|
425
524
|
for (let index = 0; index < items.length; index++) {
|
|
426
525
|
const item = items[index]!;
|
|
526
|
+
if (item.string !== undefined) {
|
|
527
|
+
parsed.push({ stringItem: item.string });
|
|
528
|
+
continue;
|
|
529
|
+
}
|
|
427
530
|
// WHY: the number the CALLER submitted — a per-file plan keeps its items' global positions,
|
|
428
531
|
// WHY: so a multi-file refusal still names the item the model sent, not a per-file 0.
|
|
429
532
|
const number = itemNumbers?.[index] ?? index;
|
|
@@ -960,10 +1063,56 @@ async function runMutations(
|
|
|
960
1063
|
);
|
|
961
1064
|
continue;
|
|
962
1065
|
}
|
|
963
|
-
|
|
964
|
-
|
|
1066
|
+
let edit!: HEdit;
|
|
965
1067
|
let outcome: ApplyOneEditOutcome;
|
|
966
|
-
if (
|
|
1068
|
+
if ("stringItem" in parsedItem) {
|
|
1069
|
+
try {
|
|
1070
|
+
const replaced = await applyStringEdit({
|
|
1071
|
+
target: parsedItem.stringItem,
|
|
1072
|
+
content: currentContent,
|
|
1073
|
+
hashes: currentHashes,
|
|
1074
|
+
signal: options?.signal,
|
|
1075
|
+
absolutePath,
|
|
1076
|
+
store: hashStore,
|
|
1077
|
+
blockedHashes: batchBlockedHashes,
|
|
1078
|
+
});
|
|
1079
|
+
if (replaced.kind === "noop") {
|
|
1080
|
+
noopCount += 1;
|
|
1081
|
+
warnings.push(
|
|
1082
|
+
`edit[${number}] (${path}) was a noop: "old_string" equals "new_string"; nothing changed.`,
|
|
1083
|
+
);
|
|
1084
|
+
continue;
|
|
1085
|
+
}
|
|
1086
|
+
outcome = {
|
|
1087
|
+
kind: "applied",
|
|
1088
|
+
content: replaced.content,
|
|
1089
|
+
hashes: replaced.hashes,
|
|
1090
|
+
removedHashes: replaced.removedHashes,
|
|
1091
|
+
range: replaced.range,
|
|
1092
|
+
firstChangedLine: replaced.range.startLine,
|
|
1093
|
+
lastChangedLine: replaced.range.endLine,
|
|
1094
|
+
anchorWarnings: undefined,
|
|
1095
|
+
literalBypass: false,
|
|
1096
|
+
neverServedCount: 0,
|
|
1097
|
+
sourceRange: undefined,
|
|
1098
|
+
mutationSpans: undefined,
|
|
1099
|
+
mutationStats: replaced.stats,
|
|
1100
|
+
};
|
|
1101
|
+
} catch (error) {
|
|
1102
|
+
if (!(error instanceof DomainError)) throw error;
|
|
1103
|
+
await recordRejectionServe({
|
|
1104
|
+
error,
|
|
1105
|
+
sessionKey,
|
|
1106
|
+
absolutePath,
|
|
1107
|
+
isPreview,
|
|
1108
|
+
lineCount: currentHashes.length,
|
|
1109
|
+
contentHash: isPreview ? undefined : snapshotHashFor(currentContent),
|
|
1110
|
+
});
|
|
1111
|
+
if (items.length === 1) throw error;
|
|
1112
|
+
throw batchAbortFor({ error, index: number, path });
|
|
1113
|
+
}
|
|
1114
|
+
} else if (item.expand === "item") {
|
|
1115
|
+
edit = parsedItem.edit;
|
|
967
1116
|
// WHY: (ADR-0031) an expanded item is applied by its own seam: the AST decides the span, the
|
|
968
1117
|
// WHY: licensing anchor still resolves through the leases, and the outcome re-enters this loop so
|
|
969
1118
|
// WHY: identity bookkeeping, counting, drift, undo, commit and serve stay shared.
|
|
@@ -1005,6 +1154,7 @@ async function runMutations(
|
|
|
1005
1154
|
throw batchAbortFor({ error, index: number, path });
|
|
1006
1155
|
}
|
|
1007
1156
|
} else {
|
|
1157
|
+
edit = parsedItem.edit;
|
|
1008
1158
|
outcome = await applyOneEdit({
|
|
1009
1159
|
content: currentContent,
|
|
1010
1160
|
hashes: currentHashes,
|
package/src/payload-contract.ts
CHANGED
|
@@ -45,6 +45,13 @@ type EditItem = {
|
|
|
45
45
|
* end, so `anchor_to` is refused and only an in-place `text` payload is accepted.
|
|
46
46
|
*/
|
|
47
47
|
expand?: "item";
|
|
48
|
+
/**
|
|
49
|
+
* Native str_replace-style string targeting: replace the unique occurrence of `old_string`
|
|
50
|
+
* character-for-character with `new_string`, instead of anchor addressing. Mutually exclusive
|
|
51
|
+
* with `anchor_from`/`anchor_to` and every payload slot; a call may mix anchor and string items.
|
|
52
|
+
*/
|
|
53
|
+
old_string?: string;
|
|
54
|
+
new_string?: string;
|
|
48
55
|
};
|
|
49
56
|
|
|
50
57
|
type EditMode = "general" | "literal";
|
|
@@ -92,6 +99,8 @@ type NormalizedEditItem = {
|
|
|
92
99
|
indent?: "auto";
|
|
93
100
|
/** Admitted `expand` mode (ADR-0031): the AST decides the target span's end. */
|
|
94
101
|
expand?: "item";
|
|
102
|
+
/** String-replacement target (present only on a string item; exclusive with anchor addressing). */
|
|
103
|
+
string?: { old_string: string; new_string: string };
|
|
95
104
|
};
|
|
96
105
|
|
|
97
106
|
export type NormalizedEditRequest = {
|
|
@@ -123,7 +132,7 @@ function isNormalizedEdit(input: unknown): input is Record<string, unknown> {
|
|
|
123
132
|
}
|
|
124
133
|
|
|
125
134
|
const ITEM_SHAPE =
|
|
126
|
-
'an item is one payload over its anchor pair — `text` (optionally with `indent: "auto"` and, alone, `expand: "item"`), `text_ref`, or one insertion slot `after`/`before` (optionally with `indent: "auto"`) — plus optional `at`';
|
|
135
|
+
'an item is one payload over its anchor pair — `text` (optionally with `indent: "auto"` and, alone, `expand: "item"`), `text_ref`, or one insertion slot `after`/`before` (optionally with `indent: "auto"`) — plus optional `at`; OR a string-replacement item `{ old_string, new_string }` that replaces the unique occurrence of `old_string`';
|
|
127
136
|
|
|
128
137
|
const EDIT_PAYLOAD_HINT =
|
|
129
138
|
"Edit must be called with exactly one payload per item, and each call edits ONE file. Use the canonical payload " +
|
|
@@ -216,6 +225,7 @@ const ITEM_KEY_SETS: readonly (readonly string[])[] = [
|
|
|
216
225
|
["anchor_from", "after", "anchor_to"],
|
|
217
226
|
["anchor_from", "before"],
|
|
218
227
|
["anchor_from", "before", "anchor_to"],
|
|
228
|
+
["old_string", "new_string"],
|
|
219
229
|
];
|
|
220
230
|
|
|
221
231
|
function keySetEquals(keys: Set<string>, shape: readonly string[]): boolean {
|
|
@@ -256,6 +266,8 @@ function foldAbsentSlots(item: Record<string, unknown>): Record<string, unknown>
|
|
|
256
266
|
"before",
|
|
257
267
|
"indent",
|
|
258
268
|
"expand",
|
|
269
|
+
"old_string",
|
|
270
|
+
"new_string",
|
|
259
271
|
] as const) {
|
|
260
272
|
if (isAbsentValue(folded[key])) delete folded[key];
|
|
261
273
|
}
|
|
@@ -266,6 +278,36 @@ function foldAbsentSlots(item: Record<string, unknown>): Record<string, unknown>
|
|
|
266
278
|
}
|
|
267
279
|
return folded;
|
|
268
280
|
}
|
|
281
|
+
function analyzeStringItem(
|
|
282
|
+
value: Record<string, unknown>,
|
|
283
|
+
index: number,
|
|
284
|
+
keys: Set<string>,
|
|
285
|
+
): string | undefined {
|
|
286
|
+
if (!keys.has("new_string")) {
|
|
287
|
+
return `edit[${index}] "new_string" is required for string replacement: use "" to delete the matched text.`;
|
|
288
|
+
}
|
|
289
|
+
if (!keys.has("old_string")) {
|
|
290
|
+
return `edit[${index}] "old_string" is required: the exact text to replace (it must occur exactly once in the file).`;
|
|
291
|
+
}
|
|
292
|
+
if (!keySetEquals(keys, ["old_string", "new_string"])) {
|
|
293
|
+
return (
|
|
294
|
+
`edit[${index}] string replacement takes exactly "old_string" and "new_string" — ` +
|
|
295
|
+
`delete any anchor, payload, "at", "indent" or "expand" field. (${ITEM_SHAPE})`
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
if (value.indent !== undefined || value.expand !== undefined) {
|
|
299
|
+
return `edit[${index}] "old_string"/"new_string" string replacement takes no "indent" or "expand".`;
|
|
300
|
+
}
|
|
301
|
+
const { old_string, new_string } = value;
|
|
302
|
+
if (typeof old_string !== "string" || old_string.length === 0) {
|
|
303
|
+
return `edit[${index}] "old_string" must be a non-empty string: the exact text to replace, which must occur exactly once in the file.`;
|
|
304
|
+
}
|
|
305
|
+
if (typeof new_string !== "string") {
|
|
306
|
+
return `edit[${index}] "new_string" must be a string (use "" to delete the matched text).`;
|
|
307
|
+
}
|
|
308
|
+
return undefined;
|
|
309
|
+
}
|
|
310
|
+
|
|
269
311
|
function analyzeItem(value: unknown, index: number): string | undefined {
|
|
270
312
|
if (!isRec(value)) {
|
|
271
313
|
return `edit[${index}] must be an object: ${ITEM_SHAPE}.`;
|
|
@@ -278,6 +320,11 @@ function analyzeItem(value: unknown, index: number): string | undefined {
|
|
|
278
320
|
// WHY: validated as their own two-value enums. Keeping them out of every shape keeps the gate finite.
|
|
279
321
|
const modifierKeys = new Set(["indent", "expand"]);
|
|
280
322
|
const keys = new Set(Object.keys(value).filter((key) => !modifierKeys.has(key)));
|
|
323
|
+
// WHY: a string-replacement item targets by exact text, not anchors: it is its own shape and
|
|
324
|
+
// WHY: never carries anchor fields, payload slots, `indent` or `expand`. Mixing with anchors is ok.
|
|
325
|
+
if (keys.has("old_string") || keys.has("new_string")) {
|
|
326
|
+
return analyzeStringItem(value, index, keys);
|
|
327
|
+
}
|
|
281
328
|
const hasText = keys.has("text");
|
|
282
329
|
const hasRef = keys.has("text_ref");
|
|
283
330
|
const hasAfter = keys.has("after");
|
|
@@ -532,6 +579,16 @@ function analyzeRequest(input: unknown): Admission {
|
|
|
532
579
|
}
|
|
533
580
|
|
|
534
581
|
function normalizedItemFrom(item: EditItem): NormalizedEditItem {
|
|
582
|
+
// WHY: a string-replacement item carries its own target; the anchor placeholder is never read by
|
|
583
|
+
// WHY: the engine (the mutate loop dispatches string items before any anchor resolution).
|
|
584
|
+
if (item.old_string !== undefined) {
|
|
585
|
+
return {
|
|
586
|
+
target: { anchor_from: "", anchor_to: "" },
|
|
587
|
+
at: "in-place",
|
|
588
|
+
payload: { kind: "empty" },
|
|
589
|
+
string: { old_string: item.old_string, new_string: item.new_string ?? "" },
|
|
590
|
+
};
|
|
591
|
+
}
|
|
535
592
|
const at = item.at ?? "in-place";
|
|
536
593
|
const payload: DesiredContent =
|
|
537
594
|
item.text_ref !== undefined
|
|
@@ -600,6 +657,15 @@ function isNormalizedEditItem(value: unknown): value is NormalizedEditItem {
|
|
|
600
657
|
// WHY: hand-built item cannot smuggle an unspellable mode past `assertReq`.
|
|
601
658
|
if (value.indent !== undefined && value.indent !== "auto") return false;
|
|
602
659
|
if (value.expand !== undefined && value.expand !== "item") return false;
|
|
660
|
+
// WHY: a string-replacement item carries `string` instead of an anchor target/payload.
|
|
661
|
+
if (isRec(value.string)) {
|
|
662
|
+
const s = value.string;
|
|
663
|
+
return (
|
|
664
|
+
typeof s.old_string === "string" &&
|
|
665
|
+
s.old_string.length > 0 &&
|
|
666
|
+
typeof s.new_string === "string"
|
|
667
|
+
);
|
|
668
|
+
}
|
|
603
669
|
const { target, at, payload } = value;
|
|
604
670
|
if (!isRec(target)) return false;
|
|
605
671
|
if (typeof target.anchor_from !== "string" || typeof target.anchor_to !== "string") return false;
|
package/src/prompts.ts
CHANGED
|
@@ -16,7 +16,10 @@ function applyReplacements(content: string, replacements?: Record<string, string
|
|
|
16
16
|
}
|
|
17
17
|
}
|
|
18
18
|
const withWidth = out.split("{{HASH_LEN}}").join(String(HASH_LEN));
|
|
19
|
-
|
|
19
|
+
const gutter = getRowGutter();
|
|
20
|
+
return withWidth
|
|
21
|
+
.split("{{GUTTER}}")
|
|
22
|
+
.join(gutter === "native" ? ": " : gutter === "bare" ? "" : "→");
|
|
20
23
|
}
|
|
21
24
|
|
|
22
25
|
export function loadP(relativePath: string, replacements?: Record<string, string>): string {
|
|
@@ -185,6 +185,12 @@ export function vacuumSnapshots(db: DatabaseSync, options: VacuumOptions = {}):
|
|
|
185
185
|
}
|
|
186
186
|
|
|
187
187
|
if (evict.length > 0) deleteVacuumSnapshots(db, evict);
|
|
188
|
+
try {
|
|
189
|
+
// WHY: with incremental auto-vacuum (set on first upgrade reclaim) this returns freed TTL pages cheaply.
|
|
190
|
+
db.exec("PRAGMA incremental_vacuum");
|
|
191
|
+
} catch {
|
|
192
|
+
// WHY: best-effort: a legacy auto_vacuum=0 store reclaims on the next slow open instead.
|
|
193
|
+
}
|
|
188
194
|
const deferredBytes = Math.max(0, total - VACUUM_GLOBAL_BUDGET_BYTES);
|
|
189
195
|
return {
|
|
190
196
|
evicted: evict.length,
|
|
@@ -29,7 +29,7 @@ export const HASH_STORE_BUSY_TIMEOUT = 250;
|
|
|
29
29
|
// WHY: needs to stay covered. Without it every materialization re-scanned each path's lease set.
|
|
30
30
|
// WHY: v11 adds `file_snapshots.stat_key` plus `idx_snapshots_path_stat` — the stat identity a read
|
|
31
31
|
// WHY: materialization saw, so an unchanged file's next read adopts on `stat(2)` alone (ADR-0043).
|
|
32
|
-
export const HASH_STORE_VERSION =
|
|
32
|
+
export const HASH_STORE_VERSION = 12;
|
|
33
33
|
|
|
34
34
|
const BUSY_MAX_ATTEMPTS = 8;
|
|
35
35
|
const BUSY_BACKOFF_BASE_MS = 50;
|