dsh-hashline-edit 0.5.4 → 0.5.5

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.
@@ -1,7 +1,7 @@
1
1
  import { abortIf, splitLines } from "../utils.js";
2
2
  import { DomainError, formatWarning } from "../domain-errors.js";
3
- import { HASH_SEP, defaultHashIdentity } from "./hash-identity.js";
4
- import { type ResolvedRange } from "../served-session/serve-render.js";
3
+ import { defaultHashIdentity } from "./hash-identity.js";
4
+ import { type ResolvedRange, formatServedRow } from "../served-session/serve-render.js";
5
5
  import {
6
6
  findServedHashEcho,
7
7
  findServedPrefixMismatches,
@@ -725,13 +725,19 @@ function resolvedRange(resolved: RHEdit): ResolvedRange {
725
725
  };
726
726
  }
727
727
 
728
- export function fmtRegion(hashes: readonly string[], lines: readonly string[]): string {
728
+ export function fmtRegion(
729
+ startLine: number,
730
+ hashes: readonly string[],
731
+ lines: readonly string[],
732
+ ): string {
729
733
  if (hashes.length !== lines.length) {
730
734
  throw new Error(
731
735
  `fmtRegion: hashes.length (${hashes.length}) must match lines.length (${lines.length}).`,
732
736
  );
733
737
  }
734
- return lines.map((line, index) => `${hashes[index]}${HASH_SEP}${line}`).join("\n");
738
+ return lines
739
+ .map((line, index) => formatServedRow(startLine + index, hashes[index], line))
740
+ .join("\n");
735
741
  }
736
742
 
737
743
  export function changedRange(
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The display-only line-number gutter helpers, plus the shared prefix regex every parser reads back.
3
+ * The active mode lives in ./row-mode.ts (a live setting); these are pure conveniences over it.
4
+ */
5
+ import { getRowGutter } from "./row-mode.js";
6
+
7
+ export type { RowGutter } from "./row-mode.js";
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). */
17
+ export function lineGutter(lineNumber: number): string {
18
+ return getRowGutter() === "native" ? `${lineNumber}: ` : `${lineNumber}→`;
19
+ }
20
+
21
+ /** The prefix a folded range row carries: `12..30→` (arrow) or `12..30: ` (native). */
22
+ export function rangeGutter(startLine: number, endLine: number): string {
23
+ return getRowGutter() === "native" ? `${startLine}..${endLine}: ` : `${startLine}..${endLine}→`;
24
+ }
25
+
26
+ /**
27
+ * Regex source for one optional row gutter prefix (arrow or native, single line or folded range),
28
+ * shared by every parser and test helper that reads a served row back. No escapes: `[0-9]`/`[.]`.
29
+ */
30
+ export const ROW_GUTTER_PREFIX = "(?:[0-9]+(?:[.][.][0-9]+)?(?:→|: ))";
31
+
32
+ /** Strip one leading row gutter prefix (arrow or native) from a row-like line, if present. */
33
+ export function stripLineGutter(text: string): string {
34
+ return text.replace(/^(?:[0-9]+(?:[.][.][0-9]+)?(?:→|: ))/, "");
35
+ }
@@ -5,6 +5,12 @@ import { SERVED_MAX_LINES } from "../constants.js";
5
5
  import type { HashSnapshotIO, HashSnapshotUpsertOptions } from "../snapshot-store";
6
6
  import { xxh32, contentChecksum, initHasher } from "./hasher.js";
7
7
  import { HASH_LEN, ALPHA, ALPHA_RE, HASH_CLASS } from "./alphabet.js";
8
+ import {
9
+ ANCHOR_CODEBOOK_ARROW_B64,
10
+ ANCHOR_CODEBOOK_NATIVE_B64,
11
+ ANCHOR_CODEBOOK_WIDTH,
12
+ } from "./anchor-codebook.js";
13
+ import { getRowGutter, type RowGutter } from "./row-mode.js";
8
14
  import { reportDiagnostic } from "../diagnostics.js";
9
15
 
10
16
  export { initHasher, HASH_LEN, ALPHA_RE, HASH_CLASS };
@@ -58,24 +64,41 @@ export const ANCHOR_LEN = HASH_LEN;
58
64
  export const HASH_SEP = "│";
59
65
  export const HASH_SPACE = ALPHA.length ** HASH_LEN;
60
66
  const BITSET_WORDS = Math.ceil(HASH_SPACE / 32);
61
- // WHY: an all-digit anchor is structurally confusable with a line number, and a
62
- // WHY: served one pasted back resolves to a legitimate line and verifies —
63
- // WHY: undetectable after the fact. So the digit subcube is reserved at
64
- // WHY: allocation time and never served; the set derives from ALPHA (no new
65
- // WHY: width/size literals) so a width or alphabet change recomputes it.
67
+ // WHY: served anchors must read as stable two-token units. For width 3 the allowed spellings come
68
+ // WHY: from anchor-codebook.ts (arrow: 157,943 two-token; native: 21,330 strictly-separated two-token);
69
+ // WHY: every other spelling is reserved and never allocated. Any other width keeps the historical rule:
70
+ // WHY: the all-digit subcube is reserved (a pure-number anchor is confusable with a line number).
71
+ // WHY: Reserved index -> set bit in RESERVED_BITS, so the probe skips it and exhaustion stays exact.
66
72
  const DIGIT_CHARS = ALPHA.split("").filter((c) => c >= "0" && c <= "9");
67
- const RESERVED_HASH_SPELLINGS = DIGIT_CHARS.length ** HASH_LEN;
68
- export const USABLE_HASH_SPACE = HASH_SPACE - RESERVED_HASH_SPELLINGS;
69
73
  // SAFETY: fixed digit set from the trusted alphabet at the configured width, no user input, linear character class, no ReDoS.
70
74
  export const DIGIT_ANCHOR_RE = new RegExp(`^[${DIGIT_CHARS.join("")}]{${HASH_LEN}}$`);
71
- // WHY: the reservation is a fixed pre-set bit mask, so allocation still derives
72
- // WHY: the base index from content and identical content keeps identical anchors.
73
- const RESERVED_BITS: Uint32Array = (() => {
75
+
76
+ function popcount32(value: number): number {
77
+ let v = value >>> 0;
78
+ v = v - ((v >>> 1) & 0x55555555);
79
+ v = (v & 0x33333333) + ((v >>> 2) & 0x33333333);
80
+ return (((v + (v >>> 4)) & 0x0f0f0f0f) * 0x01010101) >>> 24;
81
+ }
82
+
83
+ function buildReservedBits(): Uint32Array {
84
+ const bits = new Uint32Array(BITSET_WORDS);
85
+ if (HASH_LEN === ANCHOR_CODEBOOK_WIDTH) {
86
+ // WHY: the codebook artifact is an ALLOWED bitmap; reserve its complement.
87
+ const allowed = Buffer.from(
88
+ getRowGutter() === "native" ? ANCHOR_CODEBOOK_NATIVE_B64 : ANCHOR_CODEBOOK_ARROW_B64,
89
+ "base64",
90
+ );
91
+ for (let idx = 0; idx < HASH_SPACE; idx++) {
92
+ const isAllowed = ((allowed[idx >>> 3]! >>> (idx & 7)) & 1) !== 0;
93
+ if (!isAllowed) bits[idx >>> 5] |= 1 << (idx & 31);
94
+ }
95
+ return bits;
96
+ }
74
97
  const digitIdx = DIGIT_CHARS.map((c) => ALPHA.indexOf(c));
75
98
  const radix = digitIdx.length;
76
99
  const base = ALPHA.length;
77
- const bits = new Uint32Array(BITSET_WORDS);
78
- for (let n = 0; n < RESERVED_HASH_SPELLINGS; n++) {
100
+ const digitSpellings = radix ** HASH_LEN;
101
+ for (let n = 0; n < digitSpellings; n++) {
79
102
  let idx = 0;
80
103
  let mult = 1;
81
104
  let m = n;
@@ -87,14 +110,22 @@ const RESERVED_BITS: Uint32Array = (() => {
87
110
  bits[idx >>> 5] |= 1 << (idx & 31);
88
111
  }
89
112
  return bits;
90
- })();
91
- export const MAX_HASH_LINES = USABLE_HASH_SPACE;
113
+ }
114
+
115
+ // WHY: the active codebook follows the runtime gutter mode, so these are live `let` bindings that
116
+ // WHY: `configureAnchorSpace()` refreshes when the plugin's `nativeGutter` switch changes (Volatile config).
117
+ let RESERVED_BITS: Uint32Array = buildReservedBits();
118
+ export let USABLE_HASH_SPACE = HASH_SPACE - RESERVED_BITS.reduce((t, w) => t + popcount32(w), 0);
119
+ export let MAX_HASH_LINES = USABLE_HASH_SPACE;
92
120
  // WHY: single owner of the space-exhaustion payload — the producer throws it
93
121
  // WHY: and the capacity tests assert it, so the binding cannot drift.
94
- export const HASH_SPACE_EXHAUSTED_PAYLOAD = {
122
+ export let HASH_SPACE_EXHAUSTED_PAYLOAD: {
123
+ readonly limitKind: "hash-space";
124
+ readonly limit: number;
125
+ } = {
95
126
  limitKind: "hash-space",
96
127
  limit: USABLE_HASH_SPACE,
97
- } as const;
128
+ };
98
129
 
99
130
  // WHY: the stride stays coprime with both the raw space and the usable space
100
131
  // WHY: (see the stride pin) — the probe cycles the raw bitset where reserved
@@ -134,11 +165,22 @@ export const CANON_VERSION = 3;
134
165
  * another. Width 4 stays generation 1 — the original persisted generation — so existing stores keep
135
166
  * their anchors; width 3 gets generation 2, and any future width gets `100 + width`.
136
167
  */
137
- export function anchorGenerationFor(width: number): number {
138
- return width === 4 ? 1 : width === 3 ? 2 : 100 + width;
168
+ export function anchorGenerationFor(width: number, gutter: RowGutter = getRowGutter()): number {
169
+ if (width === 4) return 1;
170
+ if (width === 3) return gutter === "native" ? 4 : 3;
171
+ return 100 + width;
139
172
  }
140
173
 
141
- export const ANCHOR_GENERATION = anchorGenerationFor(HASH_LEN);
174
+ export let ANCHOR_GENERATION = anchorGenerationFor(HASH_LEN);
175
+
176
+ /** Recompute the active codebook, capacity, exhaustion payload and generation for the current gutter mode. */
177
+ export function configureAnchorSpace(): void {
178
+ RESERVED_BITS = buildReservedBits();
179
+ USABLE_HASH_SPACE = HASH_SPACE - RESERVED_BITS.reduce((t, w) => t + popcount32(w), 0);
180
+ MAX_HASH_LINES = USABLE_HASH_SPACE;
181
+ HASH_SPACE_EXHAUSTED_PAYLOAD = { limitKind: "hash-space", limit: USABLE_HASH_SPACE };
182
+ ANCHOR_GENERATION = anchorGenerationFor(HASH_LEN);
183
+ }
142
184
 
143
185
  /**
144
186
  * WHY: an explicit code-point list, never a Unicode property escape — \p{White_Space} and \p{Cf}
@@ -1,4 +1,5 @@
1
1
  import { ANCHOR_LEN, ALPHA_RE, HASH_CLASS } from "./hash-identity.js";
2
+ import { stripLineGutter } from "./gutter.js";
2
3
  import { DomainError } from "../domain-errors.js";
3
4
 
4
5
  export type Anchor = { hash: string };
@@ -22,8 +23,8 @@ function diagPayload(ref: string): { rawAnchor: string; reason: string } {
22
23
 
23
24
  if (trimmed.includes("│") && trimmed.includes("\n")) {
24
25
  const lines = trimmed.split("\n");
25
- const first = lines[0] ?? "";
26
- const last = lines.at(-1) ?? "";
26
+ const first = stripLineGutter(lines[0] ?? "");
27
+ const last = stripLineGutter(lines.at(-1) ?? "");
27
28
  // SAFETY: HASH_CLASS is derived from the trusted alphabet at the configured width, bounded linear search — no user-controlled pattern, no ReDoS.
28
29
  const hashRe = new RegExp(HASH_CLASS);
29
30
  const firstMatch = first.match(hashRe);
@@ -1,6 +1,7 @@
1
1
  import { abortIf, rejectUnknownFields } from "../utils.js";
2
2
  import { DomainError, formatWarning } from "../domain-errors.js";
3
3
  import { HASH_CLASS, HASH_LEN } from "./hash-identity.js";
4
+ import { ROW_GUTTER_PREFIX, stripLineGutter } from "./gutter.js";
4
5
  import { parseHashRef, parseText, type Anchor } from "./parse.js";
5
6
  import type { ServedRow } from "../served-session/serve-render.js";
6
7
  import type { FileSnapshotContext } from "../served-session/serve-render.js";
@@ -410,14 +411,15 @@ function assertItem(edit: Record<string, unknown>): void {
410
411
  }
411
412
 
412
413
  // SAFETY: HASH_CLASS is derived from the trusted alphabet at the configured width, linear row prefix — bounded, no user input, no ReDoS.
413
- const ANCHOR_ROW_RE = new RegExp(`^([+-]?)(${HASH_CLASS})│`);
414
+ const ANCHOR_ROW_RE = new RegExp(`^([+-]?)(?:${ROW_GUTTER_PREFIX})?(${HASH_CLASS})│`);
414
415
  function firstHashFromBlock(block: string): string | undefined {
415
416
  for (const line of block.split("\n")) {
416
417
  const m = line.match(ANCHOR_ROW_RE);
417
418
  if (m) return m[2]!;
418
- // SAFETY: HASH_CLASS is derived from the trusted alphabet at the configured width, bounded linear search — no user-controlled pattern, no ReDoS.
419
- const bare = line.match(new RegExp(HASH_CLASS));
420
- if (bare) return bare[0]!;
419
+ // WHY: strip the display-only gutter and reject an all-digit run (a line number, never a served
420
+ // WHY: anchor) so a pasted `12: abcd│…` resolves to `abcd`, not the leading digits.
421
+ const bare = stripLineGutter(line).match(new RegExp(HASH_CLASS));
422
+ if (bare && !/^\d+$/.test(bare[0]!)) return bare[0]!;
421
423
  }
422
424
  return undefined;
423
425
  }
@@ -449,7 +451,7 @@ export function resEdit(edit: HTEdit): HEdit {
449
451
  } else if (match[1] === "-") {
450
452
  reason = `anchor carries a leading "-" marker ("${trimmed}"). Nothing was written; pass the bare ${HASH_LEN}-char anchor and retry.`;
451
453
  } else {
452
- reason = `anchor carries a "HASH│" prefix ("${trimmed}"). Nothing was written; copy only the ${HASH_LEN} chars before │ and retry.`;
454
+ reason = `anchor carries a served-row prefix ("${trimmed}"). Nothing was written; copy only the ${HASH_LEN}-char anchor immediately left of │ and retry.`;
453
455
  }
454
456
  throw new DomainError("E_MALFORMED_ANCHOR", { rawAnchor: trimmed, reason });
455
457
  }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * The active line-number gutter mode, shared by every renderer and by the anchor codebook.
3
+ *
4
+ * WHY module state + a setter rather than a load-time constant: the mode is a live plugin setting
5
+ * (the `nativeGutter` Volatile switch). The host re-mounts agents on a volatile update, and the plugin
6
+ * calls `applyConfigRowGutter()` then `configureAnchorSpace()` so the codebook, capacity and anchor
7
+ * generation all follow the switch. Changing it invalidates old anchors (new generation) — the caller
8
+ * opens a fresh session. `PI_BETTER_EDIT_ROW_GUTTER` pins the mode for tests/CI and wins over config.
9
+ */
10
+ export type RowGutter = "arrow" | "native";
11
+
12
+ export const ROW_GUTTER_ENV_VAR = "PI_BETTER_EDIT_ROW_GUTTER";
13
+
14
+ /** Arrow is the default: it does not merge with the following anchor token. */
15
+ export const ROW_GUTTER_DEFAULT: RowGutter = "arrow";
16
+
17
+ export function resolveRowGutter(env: Record<string, string | undefined>): RowGutter {
18
+ const raw = env[ROW_GUTTER_ENV_VAR];
19
+ if (raw === undefined || raw.trim() === "") return ROW_GUTTER_DEFAULT;
20
+ const value = raw.trim().toLowerCase();
21
+ if (value === "arrow") return "arrow";
22
+ if (value === "native") return "native";
23
+ throw new Error(
24
+ `${ROW_GUTTER_ENV_VAR} must be "arrow" or "native" (got ${JSON.stringify(raw)}).`,
25
+ );
26
+ }
27
+
28
+ const envPinned = (() => {
29
+ const raw = process.env[ROW_GUTTER_ENV_VAR];
30
+ return raw !== undefined && raw.trim() !== "";
31
+ })();
32
+
33
+ let current: RowGutter = resolveRowGutter(process.env);
34
+
35
+ export function getRowGutter(): RowGutter {
36
+ return current;
37
+ }
38
+
39
+ /** Apply a config-driven mode unless the env var is set (tests/CI pin it). */
40
+ export function applyConfigRowGutter(mode: RowGutter): RowGutter {
41
+ if (!envPinned) current = mode;
42
+ return current;
43
+ }
package/src/prompts.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { readFileSync } from "node:fs";
2
2
 
3
3
  import { HASH_LEN } from "./hashline/alphabet.js";
4
+ import { getRowGutter } from "./hashline/row-mode.js";
4
5
 
5
6
  /**
6
7
  * Resolve template variables in shipped prompt prose. Beyond caller-supplied replacements, the
@@ -14,7 +15,8 @@ function applyReplacements(content: string, replacements?: Record<string, string
14
15
  out = out.split(`{{${key}}}`).join(value);
15
16
  }
16
17
  }
17
- return out.split("{{HASH_LEN}}").join(String(HASH_LEN));
18
+ const withWidth = out.split("{{HASH_LEN}}").join(String(HASH_LEN));
19
+ return withWidth.split("{{GUTTER}}").join(getRowGutter() === "native" ? ": " : "→");
18
20
  }
19
21
 
20
22
  export function loadP(relativePath: string, replacements?: Record<string, string>): string {
@@ -30,6 +30,7 @@
30
30
  */
31
31
  import { HASH_LEN, HASH_RE } from "../hashline/alphabet.js";
32
32
  import { HASH_SEP } from "../hashline/hash-identity.js";
33
+ import { lineGutter as gutterLine, stripLineGutter } from "../hashline/gutter.js";
33
34
  import { canonDigest } from "../hashline/hash-identity.js";
34
35
  import { SERVED_ROWS_CAP } from "../constants.js";
35
36
  import {
@@ -84,8 +85,22 @@ export function denseServeRows(hashes: readonly string[]): ServedRow[] {
84
85
  return hashes.map((hash, position) => ({ position, hash }));
85
86
  }
86
87
 
88
+ export function lineGutter(lineNumber: number): string {
89
+ return gutterLine(lineNumber);
90
+ }
91
+
92
+ /**
93
+ * One served row: `12: abc│content`. WHY: line numbers are display-only, never part of the anchor —
94
+ * the anchor stays the HASH immediately left of the separator.
95
+ */
96
+ export function formatServedRow(lineNumber: number, hash: string, content: string): string {
97
+ return `${lineGutter(lineNumber)}${hash}${HASH_SEP}${content}`;
98
+ }
99
+
87
100
  export function fmtServedRows(rows: ServedRow[], fileLines: string[]): string {
88
- return rows.map((row) => `${row.hash}${HASH_SEP}${fileLines[row.position] ?? ""}`).join("\n");
101
+ return rows
102
+ .map((row) => formatServedRow(row.position + 1, row.hash, fileLines[row.position] ?? ""))
103
+ .join("\n");
89
104
  }
90
105
 
91
106
  // WHY: the one continuation a rejected edit offers (read-chrome): the `windows` offset, not a bare
@@ -448,6 +463,8 @@ function anchorShapeFromLine(line: string): { anchor: string; tail: string } | u
448
463
  if (text.length > 0 && (text[0] === "+" || text[0] === "-" || text[0] === " ")) {
449
464
  text = text.slice(1);
450
465
  }
466
+ // WHY: a served row may carry the display-only line-number gutter (`12: `); it is not part of the anchor.
467
+ text = stripLineGutter(text);
451
468
  if (text.length < HASH_LEN + 1) return undefined;
452
469
  if (text[HASH_LEN] !== HASH_SEP) return undefined;
453
470
  const anchor = text.slice(0, HASH_LEN);