@criogaid/pi-hashline-edit 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +166 -61
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +459 -313
  4. package/src/core/apply.ts +251 -215
  5. package/src/core/errors.ts +9 -0
  6. package/src/core/hash.test.ts +61 -23
  7. package/src/core/hash.ts +49 -20
  8. package/src/core/lines.test.ts +46 -27
  9. package/src/core/lines.ts +36 -28
  10. package/src/core/ranges.test.ts +73 -19
  11. package/src/core/ranges.ts +15 -15
  12. package/src/core/replace.ts +109 -0
  13. package/src/core/text.test.ts +3 -3
  14. package/src/core/text.ts +26 -9
  15. package/src/core/types.ts +56 -41
  16. package/src/index.ts +23 -19
  17. package/src/integration/config-registration.test.ts +206 -0
  18. package/src/integration/grep-rg.test.ts +879 -251
  19. package/src/integration/large-text.test.ts +63 -0
  20. package/src/integration/replace-package.test.ts +41 -0
  21. package/src/pi/action-fusion.test.ts +612 -207
  22. package/src/pi/action-fusion.ts +442 -254
  23. package/src/pi/anchor-format.test.ts +53 -21
  24. package/src/pi/anchor-format.ts +48 -20
  25. package/src/pi/budgets.ts +25 -0
  26. package/src/pi/config.test.ts +178 -35
  27. package/src/pi/config.ts +96 -37
  28. package/src/pi/directory-sync.test.ts +55 -0
  29. package/src/pi/e2e-scenarios.test.ts +360 -0
  30. package/src/pi/edit-tool.ts +307 -279
  31. package/src/pi/error-text.ts +26 -0
  32. package/src/pi/execute.test.ts +1718 -713
  33. package/src/pi/failure-context.test.ts +110 -83
  34. package/src/pi/failure-context.ts +232 -73
  35. package/src/pi/failure-path.test.ts +180 -66
  36. package/src/pi/file-commit.test.ts +446 -233
  37. package/src/pi/file-commit.ts +348 -203
  38. package/src/pi/fusion-card.test.ts +118 -83
  39. package/src/pi/fusion-card.ts +203 -87
  40. package/src/pi/grep-output.ts +225 -0
  41. package/src/pi/grep-render.ts +59 -0
  42. package/src/pi/grep-scope.ts +139 -0
  43. package/src/pi/grep-search.ts +231 -0
  44. package/src/pi/grep-tool.ts +215 -774
  45. package/src/pi/grep.test.ts +825 -376
  46. package/src/pi/mutation-outcome.testing.ts +22 -0
  47. package/src/pi/mutation-result.test.ts +86 -0
  48. package/src/pi/mutation-result.ts +118 -63
  49. package/src/pi/mutation-runner.ts +151 -0
  50. package/src/pi/path.ts +20 -12
  51. package/src/pi/pi.test.ts +100 -52
  52. package/src/pi/read-tool.ts +245 -134
  53. package/src/pi/registration.test.ts +271 -114
  54. package/src/pi/render.test.ts +227 -84
  55. package/src/pi/render.ts +86 -116
  56. package/src/pi/replace-regex.ts +54 -0
  57. package/src/pi/replace-tool.ts +247 -241
  58. package/src/pi/replace-worker.mjs +4 -0
  59. package/src/pi/replace-worker.ts +10 -0
  60. package/src/pi/replace.test.ts +778 -390
  61. package/src/pi/result-safety.test.ts +821 -344
  62. package/src/pi/rg-line-ranges.test.ts +57 -31
  63. package/src/pi/rg-line-ranges.ts +45 -82
  64. package/src/pi/rg-process.test.ts +113 -0
  65. package/src/pi/{rg-line-filter.ts → rg-process.ts} +72 -125
  66. package/src/pi/rg-text-view.ts +102 -48
  67. package/src/pi/schema.ts +19 -0
  68. package/src/pi/text-stream.test.ts +118 -0
  69. package/src/pi/text-stream.ts +136 -0
  70. package/src/pi/tool-call.testing.ts +37 -0
  71. package/src/pi/write-tool.ts +114 -52
  72. package/src/pi/write.test.ts +250 -97
  73. package/src/core/index.ts +0 -14
  74. package/src/pi/rg-line-filter.test.ts +0 -85
  75. package/src/pi/state.ts +0 -26
@@ -1,30 +1,62 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { test } from "node:test";
3
3
  import { computeLineHash } from "../core/hash.ts";
4
- import { ANCHOR_PATTERN, createAnchorFormatter } from "./anchor-format.ts";
5
- import { getState } from "./state.ts";
4
+ import {
5
+ anchorPattern,
6
+ createAnchorFormatter,
7
+ parseAnchorToken,
8
+ parseHashline,
9
+ } from "./anchor-format.ts";
6
10
 
7
- test("anchor formatter snapshots configured hash length and hashes undisplayed content", () => {
8
- const state = getState();
9
- const previous = state.config;
10
- try {
11
- state.config = { ...previous, hashLen: 6 };
12
- const formatter = createAnchorFormatter();
13
- state.config = { ...previous, hashLen: 4 };
11
+ test("anchor formatter binds the supplied hash length and hashes undisplayed content", () => {
12
+ const formatter = createAnchorFormatter(6);
13
+ const shortFormatter = createAnchorFormatter(4);
14
14
 
15
- assert.equal(formatter.hashLen, 6);
16
- assert.equal(formatter.token(3, "full content"), `3#${computeLineHash(3, "full content", 6)}`);
17
- assert.equal(formatter.reference(3, "ABCDEF"), "3#ABCDEF");
18
- assert.match(formatter.token(3, "full content"), new RegExp(ANCHOR_PATTERN));
19
- assert.equal(formatter.row(3, "full content", "full…"), `3#${computeLineHash(3, "full content", 6)}│full…`);
20
- assert.equal(createAnchorFormatter().hashLen, 4);
21
- } finally {
22
- state.config = previous;
23
- }
15
+ assert.equal(formatter.token(3, "full content"), `3#${computeLineHash(3, "full content", 6)}`);
16
+ assert.equal(formatter.reference(3, "ABCDEF"), "3#ABCDEF");
17
+ assert.match(formatter.token(3, "full content"), new RegExp(anchorPattern(6)));
18
+ assert.doesNotMatch(formatter.token(3, "full content"), new RegExp(anchorPattern(4)));
19
+ assert.equal(
20
+ formatter.row(3, "full content", "full…"),
21
+ `3#${computeLineHash(3, "full content", 6)}│full…`,
22
+ );
23
+ assert.equal(
24
+ shortFormatter.token(3, "full content"),
25
+ `3#${computeLineHash(3, "full content", 4)}`,
26
+ );
27
+ });
28
+
29
+ test("anchor tokens parse at any hash length so wrong lengths can be explained", () => {
30
+ assert.deepEqual(parseAnchorToken("12#GF"), { line: 12, hash: "GF" });
31
+ assert.deepEqual(parseAnchorToken("12#GFYR"), { line: 12, hash: "GFYR" });
32
+ assert.equal(parseAnchorToken("12#gfyr"), undefined);
33
+ assert.equal(parseAnchorToken("0#GFYR"), undefined);
24
34
  });
25
35
 
26
36
  test("anchor rows expose carriage returns while checksums retain source content", () => {
27
- const formatter = createAnchorFormatter(4);
28
- assert.equal(formatter.row(1, "a\rb"), `1#${computeLineHash(1, "a\rb", 4)}│a␍b`);
29
- assert.notEqual(formatter.token(1, "a\rb"), formatter.token(1, "a␍b"));
37
+ const formatter = createAnchorFormatter(4);
38
+ assert.equal(formatter.row(1, "a\rb"), `1#${computeLineHash(1, "a\rb", 4)}│a␍b`);
39
+ assert.notEqual(formatter.token(1, "a\rb"), formatter.token(1, "a␍b"));
40
+ });
41
+
42
+ test("anchor syntax rejects characters absent from the checksum alphabet", () => {
43
+ const pattern = new RegExp(anchorPattern(4));
44
+ for (const hash of ["IIII", "LLLL", "OOOO", "UUUU", "abcd"]) {
45
+ assert.doesNotMatch(`1#${hash}`, pattern);
46
+ assert.equal(parseAnchorToken(`1#${hash}`), undefined);
47
+ assert.equal(parseHashline(`1#${hash}│content`), null);
48
+ }
49
+ });
50
+
51
+ test("display rows accept supported hash lengths and preserve nested anchor-like content", () => {
52
+ for (const hashLen of [2, 4, 6, 8]) {
53
+ const formatter = createAnchorFormatter(hashLen);
54
+ assert.deepEqual(parseHashline(formatter.row(12, "12#abc│content")), {
55
+ lineNo: "12",
56
+ content: "12#abc│content",
57
+ });
58
+ }
59
+ for (const row of ["0#ABCD│text", "01#ABCD│text", "12#A│text", "12#AAAAAAAAA│text"]) {
60
+ assert.equal(parseHashline(row), null);
61
+ }
30
62
  });
@@ -1,28 +1,56 @@
1
- import { computeLineHash } from "../core/hash.ts";
2
- import { getState } from "./state.ts";
1
+ import { computeLineHash, HASH_ALPHABET, HASH_LEN_MIN, HASH_LEN_MAX } from "../core/hash.ts";
3
2
 
4
- export const ANCHOR_PATTERN = "^([1-9][0-9]*)#([0-9A-Z]{2,8})$";
3
+ function anchorSource(hashQuantifier: string): string {
4
+ return `([1-9][0-9]*)#([${HASH_ALPHABET}]${hashQuantifier})`;
5
+ }
6
+
7
+ /** Schema pattern for a `LINE#HASH` anchor whose hash has exactly `hashLen` characters. */
8
+ export function anchorPattern(hashLen: number): string {
9
+ return `^${anchorSource(`{${hashLen}}`)}$`;
10
+ }
11
+
12
+ const ANCHOR_TOKEN = new RegExp(`^${anchorSource("+")}$`);
13
+ const HASHLINE_ROW = new RegExp(`^${anchorSource(`{${HASH_LEN_MIN},${HASH_LEN_MAX}}`)}│(.*)$`);
14
+
15
+ /** Split a `LINE#HASH` token of any hash length; undefined when the shape is wrong. */
16
+ export function parseAnchorToken(value: string): { line: number; hash: string } | undefined {
17
+ const match = ANCHOR_TOKEN.exec(value);
18
+ return match ? { line: Number(match[1]), hash: match[2]! } : undefined;
19
+ }
5
20
 
6
- /** Anchor serialization bound to one hash-length snapshot. */
21
+ export interface HashlineRow {
22
+ /** Line number as written in the anchor (string form). */
23
+ lineNo: string;
24
+ /** Line content with the `LINE#HASH│` prefix removed. */
25
+ content: string;
26
+ }
27
+
28
+ /** Parse a display row at any supported hash length; return null for non-anchor text. */
29
+ export function parseHashline(line: string): HashlineRow | null {
30
+ const match = HASHLINE_ROW.exec(line);
31
+ return match ? { lineNo: match[1], content: match[3] } : null;
32
+ }
33
+
34
+ /** Anchor serialization bound to a caller-supplied hash length. */
7
35
  export interface AnchorFormatter {
8
- readonly hashLen: number;
9
- reference(line: number, hash: string): string;
10
- token(line: number, content: string): string;
11
- row(line: number, content: string, displayContent?: string): string;
36
+ reference(line: number, hash: string): string;
37
+ token(line: number, content: string): string;
38
+ row(line: number, content: string, displayContent?: string): string;
12
39
  }
13
40
 
14
41
  /** Make CR visible without changing the source text used for checksums or patches. */
15
42
  export function displayCarriageReturns(text: string): string {
16
- return text.replace(/\r/g, "␍");
17
- }
18
-
19
- export function createAnchorFormatter(hashLen = getState().config.hashLen): AnchorFormatter {
20
- const reference = (line: number, hash: string) => `${line}#${hash}`;
21
- const token = (line: number, content: string) => reference(line, computeLineHash(line, content, hashLen));
22
- return {
23
- hashLen,
24
- token,
25
- reference,
26
- row: (line, content, displayContent = content) => `${token(line, content)}│${displayCarriageReturns(displayContent)}`,
27
- };
43
+ return text.replace(/\r/g, "␍");
44
+ }
45
+
46
+ export function createAnchorFormatter(hashLen: number): AnchorFormatter {
47
+ const reference = (line: number, hash: string) => `${line}#${hash}`;
48
+ const token = (line: number, content: string) =>
49
+ reference(line, computeLineHash(line, content, hashLen));
50
+ return {
51
+ token,
52
+ reference,
53
+ row: (line, content, displayContent = content) =>
54
+ `${token(line, content)}│${displayCarriageReturns(displayContent)}`,
55
+ };
28
56
  }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Fixed model-facing output budgets.
3
+ *
4
+ * README "Output budgets" documents each value; change both together. Result
5
+ * and notice text derive their size wording from these constants. Budgets that
6
+ * users can configure (read line and byte limits, grep line limit) live in the
7
+ * settings schema in config.ts; Pi's own total-output limit stays with Pi.
8
+ *
9
+ * @module pi-hashline-edit/pi
10
+ */
11
+
12
+ /** grep line preview, in UTF-16 units, excluding its partial-line label. */
13
+ export const GREP_MAX_LINE_LENGTH = 500;
14
+
15
+ /** Each diagnostic or anchor block: failure details, input-anchor checks, candidate neighborhoods, mutation anchors. */
16
+ export const MAX_BLOCK_BYTES = 16 * 1024;
17
+ /** One recovery-candidate or cited row inside a failure diagnostic. */
18
+ export const MAX_RECOVERY_CANDIDATE_BYTES = 4 * 1024;
19
+ /** grep search diagnostics appended to a result. */
20
+ export const MAX_SEARCH_DIAGNOSTIC_BYTES = 4 * 1024;
21
+
22
+ /** Size wording for notices, e.g. `16 KiB`. */
23
+ export function formatKiB(bytes: number): string {
24
+ return `${bytes / 1024} KiB`;
25
+ }
@@ -3,40 +3,183 @@ import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import assert from "node:assert/strict";
5
5
  import { test } from "node:test";
6
- import { loadConfig } from "./config.ts";
7
-
8
- test("actionFusion defaults on and honors explicit disabling", async () => {
9
- const root = await mkdtemp(join(tmpdir(), "hashline-config-"));
10
- try {
11
- await mkdir(join(root, ".pi"));
12
- for (const [actionFusion, expected] of [[undefined, true], [false, false], [true, true], [null, true], ["false", true], [0, true]]) {
13
- await writeFile(join(root, ".pi", "settings.json"), JSON.stringify({ hashlineEdit: { actionFusion } }));
14
- assert.deepEqual(loadConfig(root), { enabled: true, actionFusion: expected, hashLen: 4, shiftRadius: 15 });
15
- }
16
- } finally {
17
- await rm(root, { recursive: true, force: true });
18
- }
19
- });
6
+ import { DEFAULT_CONFIG, loadConfig } from "./config.ts";
7
+
8
+ async function withSettings(
9
+ fn: (
10
+ write: (settings: unknown) => Promise<void>,
11
+ root: string,
12
+ agentDir: string,
13
+ ) => Promise<void>,
14
+ ) {
15
+ const root = await mkdtemp(join(tmpdir(), "hashline-config-"));
16
+ const agentDir = join(root, "agent");
17
+ const previousAgentDir = process.env.PI_CODING_AGENT_DIR;
18
+ try {
19
+ process.env.PI_CODING_AGENT_DIR = agentDir;
20
+ await mkdir(agentDir);
21
+ await mkdir(join(root, ".pi"));
22
+ const path = join(root, ".pi", "settings.json");
23
+ await fn((settings) => writeFile(path, JSON.stringify(settings)), root, agentDir);
24
+ } finally {
25
+ if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
26
+ else process.env.PI_CODING_AGENT_DIR = previousAgentDir;
27
+ await rm(root, { recursive: true, force: true });
28
+ }
29
+ }
20
30
 
21
- test("config rejects fractional values and tolerates malformed settings shapes", async () => {
22
- const root = await mkdtemp(join(tmpdir(), "hashline-config-"));
23
- try {
24
- await mkdir(join(root, ".pi"));
25
- const path = join(root, ".pi", "settings.json");
26
- for (const value of [3.5, -1, "4", null]) {
27
- await writeFile(path, JSON.stringify({ hashlineEdit: { hashLen: value, shiftRadius: value } }));
28
- assert.deepEqual(loadConfig(root), { enabled: true, actionFusion: true, hashLen: 4, shiftRadius: 15 });
29
- }
30
- for (const rootValue of [null, [], 42, "settings", { hashlineEdit: [] }, { hashlineEdit: "invalid" }]) {
31
- await writeFile(path, JSON.stringify(rootValue));
32
- const config = loadConfig(root);
33
- assert.ok(Number.isInteger(config.hashLen));
34
- assert.ok(Number.isInteger(config.shiftRadius));
35
- }
36
- await writeFile(path, JSON.stringify({ hashlineEdit: { hashLen: 8, shiftRadius: 0 } }));
37
- assert.equal(loadConfig(root).hashLen, 8);
38
- assert.equal(loadConfig(root).shiftRadius, 0);
39
- } finally {
40
- await rm(root, { recursive: true, force: true });
41
- }
31
+ test("defaults come from the settings schema", () => {
32
+ assert.deepEqual(DEFAULT_CONFIG, {
33
+ enabled: true,
34
+ actionFusion: true,
35
+ hashLen: 4,
36
+ shiftRadius: 15,
37
+ read: { defaultLimit: 500, maxKiB: 256 },
38
+ grep: { defaultLimit: 100, defaultContext: 0 },
39
+ replace: { regexTimeoutMs: 5_000 },
40
+ });
42
41
  });
42
+
43
+ test("actionFusion defaults on and honors explicit disabling", () =>
44
+ withSettings(async (write, root) => {
45
+ for (const [actionFusion, expected] of [
46
+ [undefined, true],
47
+ [false, false],
48
+ [true, true],
49
+ [null, true],
50
+ ["false", true],
51
+ [0, true],
52
+ ]) {
53
+ await write({ hashlineEdit: { actionFusion } });
54
+ assert.deepEqual(loadConfig(root), { ...DEFAULT_CONFIG, actionFusion: expected });
55
+ }
56
+ }));
57
+
58
+ test("config rejects fractional values and tolerates malformed settings shapes", () =>
59
+ withSettings(async (write, root) => {
60
+ for (const value of [3.5, -1, "4", null]) {
61
+ await write({ hashlineEdit: { hashLen: value, shiftRadius: value } });
62
+ assert.deepEqual(loadConfig(root), DEFAULT_CONFIG);
63
+ }
64
+ for (const rootValue of [
65
+ null,
66
+ [],
67
+ 42,
68
+ "settings",
69
+ { hashlineEdit: [] },
70
+ { hashlineEdit: "invalid" },
71
+ ]) {
72
+ await write(rootValue);
73
+ assert.deepEqual(loadConfig(root), DEFAULT_CONFIG);
74
+ }
75
+ await write({ hashlineEdit: { hashLen: 8, shiftRadius: 0 } });
76
+ assert.equal(loadConfig(root).hashLen, 8);
77
+ assert.equal(loadConfig(root).shiftRadius, 0);
78
+ }));
79
+
80
+ test("tool groups resolve each setting independently", () =>
81
+ withSettings(async (write, root) => {
82
+ await write({
83
+ hashlineEdit: {
84
+ read: { defaultLimit: 50, maxKiB: 0 },
85
+ grep: { defaultContext: 21, defaultLimit: 7 },
86
+ replace: "fast",
87
+ },
88
+ });
89
+ assert.deepEqual(loadConfig(root), {
90
+ ...DEFAULT_CONFIG,
91
+ read: { defaultLimit: 50, maxKiB: DEFAULT_CONFIG.read.maxKiB },
92
+ grep: { defaultLimit: 7, defaultContext: DEFAULT_CONFIG.grep.defaultContext },
93
+ });
94
+ await write({ hashlineEdit: { replace: { regexTimeoutMs: 20_000 } } });
95
+ assert.equal(loadConfig(root).replace.regexTimeoutMs, 20_000);
96
+ }));
97
+
98
+ test("project settings replace global groups while absent project settings use global values", () =>
99
+ withSettings(async (write, root, agentDir) => {
100
+ const globalConfig = {
101
+ ...DEFAULT_CONFIG,
102
+ enabled: false,
103
+ actionFusion: false,
104
+ hashLen: 8,
105
+ shiftRadius: 0,
106
+ read: { defaultLimit: 7, maxKiB: 2 },
107
+ grep: { defaultLimit: 3, defaultContext: 2 },
108
+ replace: { regexTimeoutMs: 1_000 },
109
+ };
110
+ await writeFile(
111
+ join(agentDir, "settings.json"),
112
+ JSON.stringify({ hashlineEdit: globalConfig }),
113
+ );
114
+ assert.deepEqual(loadConfig(), globalConfig);
115
+ assert.deepEqual(loadConfig(root), globalConfig);
116
+ for (const settings of [{}, null, [], 42, "settings"]) {
117
+ await write(settings);
118
+ assert.deepEqual(loadConfig(root), globalConfig);
119
+ }
120
+ await write({ hashlineEdit: { read: { defaultLimit: 2 } } });
121
+ assert.deepEqual(loadConfig(root), {
122
+ ...DEFAULT_CONFIG,
123
+ read: { defaultLimit: 2, maxKiB: DEFAULT_CONFIG.read.maxKiB },
124
+ });
125
+ await write({ hashlineEdit: {} });
126
+ assert.deepEqual(loadConfig(root), DEFAULT_CONFIG);
127
+ }));
128
+
129
+ test("invalid tool groups default independently without discarding valid sibling groups", () =>
130
+ withSettings(async (write, root) => {
131
+ const configured = {
132
+ ...DEFAULT_CONFIG,
133
+ enabled: false,
134
+ hashLen: 6,
135
+ shiftRadius: 0,
136
+ read: { defaultLimit: 2, maxKiB: 1 },
137
+ grep: { defaultLimit: 3, defaultContext: 2 },
138
+ replace: { regexTimeoutMs: 1_000 },
139
+ };
140
+ for (const group of ["read", "grep", "replace"] as const) {
141
+ for (const value of [null, [], 42, "invalid", true]) {
142
+ await write({ hashlineEdit: { ...configured, [group]: value } });
143
+ assert.deepEqual(loadConfig(root), { ...configured, [group]: DEFAULT_CONFIG[group] });
144
+ }
145
+ }
146
+ }));
147
+
148
+ test("tool settings accept their boundary values and default invalid leaves", () =>
149
+ withSettings(async (write, root) => {
150
+ const cases = [
151
+ {
152
+ group: "read",
153
+ key: "defaultLimit",
154
+ valid: [1, Number.MAX_SAFE_INTEGER],
155
+ invalid: [0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1, "2", null],
156
+ },
157
+ { group: "read", key: "maxKiB", valid: [1, 4096], invalid: [0, 4097, 1.5, "2", null] },
158
+ {
159
+ group: "grep",
160
+ key: "defaultLimit",
161
+ valid: [1, Number.MAX_SAFE_INTEGER],
162
+ invalid: [0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1, "2", null],
163
+ },
164
+ { group: "grep", key: "defaultContext", valid: [0, 20], invalid: [-1, 21, 1.5, "2", null] },
165
+ {
166
+ group: "replace",
167
+ key: "regexTimeoutMs",
168
+ valid: [1_000, 300_000],
169
+ invalid: [999, 300_001, 1000.5, "1000", null],
170
+ },
171
+ ] as const;
172
+ for (const { group, key, valid, invalid } of cases) {
173
+ for (const value of valid) {
174
+ await write({ hashlineEdit: { [group]: { [key]: value } } });
175
+ assert.deepEqual(loadConfig(root), {
176
+ ...DEFAULT_CONFIG,
177
+ [group]: { ...DEFAULT_CONFIG[group], [key]: value },
178
+ });
179
+ }
180
+ for (const value of invalid) {
181
+ await write({ hashlineEdit: { [group]: { [key]: value } } });
182
+ assert.deepEqual(loadConfig(root), DEFAULT_CONFIG);
183
+ }
184
+ }
185
+ }));
package/src/pi/config.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
- * Config loading: project `.pi/settings.json` replaces global, per-field `??`
3
- * falls back to DEFAULT. Config field `hashlineEdit` (drop the `pi-` prefix,
4
- * camelCase).
2
+ * Config loading: project `.pi/settings.json` replaces global, and each setting
3
+ * that is missing or invalid falls back to its schema default. Config field
4
+ * `hashlineEdit` (drop the `pi-` prefix, camelCase).
5
5
  *
6
6
  * @module pi-hashline-edit/pi
7
7
  */
@@ -9,50 +9,109 @@
9
9
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
10
10
  import * as fs from "node:fs";
11
11
  import * as path from "node:path";
12
+ import { Type, type Static, type TSchema } from "typebox";
13
+ import { Value } from "typebox/value";
14
+ import { HASH_LEN_MAX, HASH_LEN_MIN } from "../core/hash.ts";
15
+ import { GREP_CONTEXT_RANGE, integerRange, POSITIVE_SAFE_INTEGER } from "./schema.ts";
12
16
 
13
- export interface HashlineEditConfig {
14
- /** Master switch: when false the extension registers no tools — pi's built-ins remain. */
15
- enabled: boolean;
16
- /** Expose optional commands after edit/replace/write. Enabled by default; false disables them. */
17
- actionFusion: boolean;
18
- /** Line hash length (default 4). */
19
- hashLen: number;
20
- /** First-pass ±line radius before full-file recovery (default 15; 0 disables recovery). */
21
- shiftRadius: number;
17
+ function integerSetting(
18
+ range: ReturnType<typeof integerRange>,
19
+ value: number,
20
+ description: string,
21
+ ) {
22
+ return Type.Number({ ...range, default: value, description });
22
23
  }
23
24
 
24
- export const DEFAULT_CONFIG: HashlineEditConfig = { enabled: true, actionFusion: true, hashLen: 4, shiftRadius: 15 };
25
+ /** Settings schema: the single source of setting types, bounds, and defaults. */
26
+ export const configSchema = Type.Object({
27
+ enabled: Type.Boolean({
28
+ default: true,
29
+ description:
30
+ "Master switch: when false the extension registers no tools; Pi's built-ins remain.",
31
+ }),
32
+ actionFusion: Type.Boolean({
33
+ default: true,
34
+ description: "Expose optional then_run commands after edit/replace/write.",
35
+ }),
36
+ hashLen: integerSetting(
37
+ integerRange(HASH_LEN_MIN, HASH_LEN_MAX),
38
+ 4,
39
+ "Line hash length shared by every anchored tool.",
40
+ ),
41
+ shiftRadius: integerSetting(
42
+ integerRange(0, 100),
43
+ 15,
44
+ "First-pass ±line radius before full-file recovery; 0 disables recovery.",
45
+ ),
46
+ read: Type.Object({
47
+ defaultLimit: integerSetting(
48
+ POSITIVE_SAFE_INTEGER,
49
+ 500,
50
+ "Lines returned when limit is omitted.",
51
+ ),
52
+ maxKiB: integerSetting(integerRange(1, 4096), 256, "Anchored text returned per call, in KiB."),
53
+ }),
54
+ grep: Type.Object({
55
+ defaultLimit: integerSetting(
56
+ POSITIVE_SAFE_INTEGER,
57
+ 100,
58
+ "Matching lines returned when limit is omitted.",
59
+ ),
60
+ defaultContext: integerSetting(
61
+ GREP_CONTEXT_RANGE,
62
+ 0,
63
+ "Context lines shown when context is omitted.",
64
+ ),
65
+ }),
66
+ replace: Type.Object({
67
+ regexTimeoutMs: integerSetting(
68
+ integerRange(1_000, 300_000),
69
+ 5_000,
70
+ "Time limit for one regex batch, in milliseconds.",
71
+ ),
72
+ }),
73
+ });
74
+
75
+ export type HashlineEditConfig = Static<typeof configSchema>;
76
+
77
+ function asRecord(value: unknown): Record<string, unknown> {
78
+ return value !== null && typeof value === "object" && !Array.isArray(value)
79
+ ? (value as Record<string, unknown>)
80
+ : {};
81
+ }
82
+
83
+ /** Keep each valid leaf; replace a missing or invalid leaf with its default. */
84
+ function resolveSetting<T extends TSchema>(schema: T, value: unknown): Static<T> {
85
+ if (Type.IsObject(schema)) {
86
+ const source = asRecord(value);
87
+ return Object.fromEntries(
88
+ Object.entries(schema.properties).map(([key, property]) => [
89
+ key,
90
+ resolveSetting(property, source[key]),
91
+ ]),
92
+ ) as Static<T>;
93
+ }
94
+ return (Value.Check(schema, value) ? value : Value.Create(schema)) as Static<T>;
95
+ }
96
+
97
+ export const DEFAULT_CONFIG: HashlineEditConfig = resolveSetting(configSchema, {});
25
98
 
26
99
  /** Parse JSON directly without stripping comments (standard JSON forbids comments; on error fall back to default). */
27
100
  function readSettings(filePath: string): Record<string, unknown> {
28
- try {
29
- if (!fs.existsSync(filePath)) return {};
30
- const value: unknown = JSON.parse(fs.readFileSync(filePath, "utf-8"));
31
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
32
- } catch {
33
- return {};
34
- }
101
+ try {
102
+ if (!fs.existsSync(filePath)) return {};
103
+ return asRecord(JSON.parse(fs.readFileSync(filePath, "utf-8")));
104
+ } catch {
105
+ return {};
106
+ }
35
107
  }
36
108
 
37
109
  /**
38
110
  * Load config. The `hashlineEdit` in project `cwd/.pi/settings.json` replaces
39
- * the global one wholesale; missing fields fall back to DEFAULT_CONFIG.
111
+ * the global one wholesale; missing or invalid settings use their defaults.
40
112
  */
41
113
  export function loadConfig(cwd?: string): HashlineEditConfig {
42
- const globalSettings = readSettings(path.join(getAgentDir(), "settings.json"));
43
- const projectSettings = cwd ? readSettings(path.join(cwd, ".pi", "settings.json")) : {};
44
- const value = projectSettings.hashlineEdit ?? globalSettings.hashlineEdit;
45
- const raw = value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
46
- return {
47
- enabled: typeof raw.enabled === "boolean" ? raw.enabled : DEFAULT_CONFIG.enabled,
48
- actionFusion: typeof raw.actionFusion === "boolean" ? raw.actionFusion : DEFAULT_CONFIG.actionFusion,
49
- hashLen:
50
- typeof raw.hashLen === "number" && Number.isInteger(raw.hashLen) && raw.hashLen >= 2 && raw.hashLen <= 8
51
- ? raw.hashLen
52
- : DEFAULT_CONFIG.hashLen,
53
- shiftRadius:
54
- typeof raw.shiftRadius === "number" && Number.isInteger(raw.shiftRadius) && raw.shiftRadius >= 0 && raw.shiftRadius <= 100
55
- ? raw.shiftRadius
56
- : DEFAULT_CONFIG.shiftRadius,
57
- };
114
+ const globalSettings = readSettings(path.join(getAgentDir(), "settings.json"));
115
+ const projectSettings = cwd ? readSettings(path.join(cwd, ".pi", "settings.json")) : {};
116
+ return resolveSetting(configSchema, projectSettings.hashlineEdit ?? globalSettings.hashlineEdit);
58
117
  }
@@ -0,0 +1,55 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import fs from "node:fs/promises";
4
+ import { syncBuiltinESMExports } from "node:module";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { commitFile, FileMutationError } from "./file-commit.ts";
8
+
9
+ test("macOS attempts directory sync, tolerates unsupported operations, and preserves published I/O failures", async (t) => {
10
+ const directory = await fs.mkdtemp(join(tmpdir(), "hashline-directory-sync-"));
11
+ const nativeOpen = fs.open;
12
+ const platform = Object.getOwnPropertyDescriptor(process, "platform")!;
13
+ let syncs = 0;
14
+ let closes = 0;
15
+ let failure: string | undefined;
16
+ try {
17
+ Object.defineProperty(process, "platform", { value: "darwin" });
18
+ t.mock.method(fs, "open", async (...args: Parameters<typeof fs.open>) => {
19
+ if (args[0] !== directory) return nativeOpen(...args);
20
+ return {
21
+ async sync() {
22
+ syncs++;
23
+ if (failure) throw Object.assign(new Error(failure), { code: failure });
24
+ },
25
+ async close() {
26
+ closes++;
27
+ },
28
+ } as Awaited<ReturnType<typeof fs.open>>;
29
+ });
30
+ syncBuiltinESMExports();
31
+ for (failure of [undefined, "EINVAL", "ENOTSUP", "EIO"]) {
32
+ const path = join(directory, failure ?? "success");
33
+ const commit = commitFile(path, "published\n");
34
+ if (failure === "EIO") {
35
+ await assert.rejects(
36
+ commit,
37
+ (error: unknown) =>
38
+ error instanceof FileMutationError &&
39
+ error.publication === "PUBLISHED" &&
40
+ /EIO/.test(error.message),
41
+ );
42
+ } else {
43
+ assert.equal((await commit).publication, "PUBLISHED");
44
+ }
45
+ assert.equal(await fs.readFile(path, "utf8"), "published\n");
46
+ }
47
+ assert.equal(syncs, 4);
48
+ assert.equal(closes, 4);
49
+ } finally {
50
+ Object.defineProperty(process, "platform", platform);
51
+ t.mock.restoreAll();
52
+ syncBuiltinESMExports();
53
+ await fs.rm(directory, { recursive: true, force: true });
54
+ }
55
+ });