@criogaid/pi-hashline-edit 0.11.0 → 0.13.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/LICENSE +1 -0
- package/README.md +73 -17
- package/README.zh-CN.md +74 -18
- package/package.json +8 -7
- package/src/core/AGENTS.md +2 -2
- package/src/core/apply.test.ts +15 -2
- package/src/core/apply.ts +6 -10
- package/src/core/case-fold.test.ts +16 -25
- package/src/core/case-fold.ts +4 -4
- package/src/core/character-set.test.ts +1 -6
- package/src/core/character-set.ts +7 -61
- package/src/core/regex.ts +2 -32
- package/src/core/replace.test.ts +51 -0
- package/src/core/replace.ts +10 -4
- package/src/core/search-analysis.test.ts +66 -61
- package/src/core/search-analysis.ts +24 -39
- package/src/core/search-matrix.test.ts +2 -2
- package/src/core/search-matrix.testing.ts +6 -16
- package/src/core/search-schema.ts +0 -1
- package/src/core/search.test.ts +6 -19
- package/src/core/search.ts +10 -8
- package/src/index.ts +28 -3
- package/src/integration/config-registration.test.ts +77 -4
- package/src/integration/fusion-dispatch.test.ts +47 -2
- package/src/integration/grep-errors.test.ts +31 -0
- package/src/integration/grep-flags.test.ts +13 -196
- package/src/integration/grep-js-completeness.test.ts +41 -8
- package/src/integration/grep-line-candidates.test.ts +4 -33
- package/src/integration/grep-matrix.test.ts +1 -1
- package/src/integration/grep-path-matrix.test.ts +59 -65
- package/src/integration/grep-prefilter-coverage.test.ts +26 -8
- package/src/integration/grep-process-limits.test.ts +46 -0
- package/src/integration/grep-regex.test.ts +7 -2
- package/src/integration/grep-rg.test.ts +106 -12
- package/src/integration/grep-translation.test.ts +14 -7
- package/src/integration/model-budget-lifecycle.test.ts +41 -2
- package/src/integration/npm-package.test.ts +12 -10
- package/src/integration/npm-package.testing.ts +147 -1
- package/src/integration/replace-package.testing.ts +2 -2
- package/src/integration/report-replay.test.ts +4 -0
- package/src/pi/AGENTS.md +23 -15
- package/src/pi/action-fusion.test.ts +38 -4
- package/src/pi/action-fusion.ts +23 -19
- package/src/pi/argument-diagnostics.ts +28 -48
- package/src/pi/argument-validation.test.ts +103 -6
- package/src/pi/argument-validation.ts +55 -31
- package/src/pi/budgets.ts +19 -10
- package/src/pi/config.test.ts +1 -1
- package/src/pi/diagnostic-buffer.test.ts +1 -0
- package/src/pi/edit-tool.ts +3 -3
- package/src/pi/execute.test.ts +4 -0
- package/src/pi/failure-context.test.ts +24 -3
- package/src/pi/failure-context.ts +36 -42
- package/src/pi/failure-path.test.ts +8 -3
- package/src/pi/file-commit.test.ts +109 -52
- package/src/pi/file-commit.ts +62 -56
- package/src/pi/fusion-card.ts +12 -7
- package/src/pi/grep-candidates.test.ts +5 -5
- package/src/pi/grep-candidates.ts +80 -48
- package/src/pi/grep-matrix.test.ts +14 -29
- package/src/pi/grep-order.test.ts +132 -9
- package/src/pi/grep-output.ts +173 -48
- package/src/pi/grep-render.ts +40 -34
- package/src/pi/grep-rg.testing.ts +9 -6
- package/src/pi/grep-scope.ts +51 -29
- package/src/pi/grep-search.ts +96 -71
- package/src/pi/grep-tool.ts +28 -34
- package/src/pi/grep.test.ts +348 -83
- package/src/pi/model-budgets.test.ts +56 -6
- package/src/pi/model-budgets.ts +7 -4
- package/src/pi/mutation-result.test.ts +25 -1
- package/src/pi/mutation-result.ts +7 -2
- package/src/pi/mutation-runner.ts +4 -5
- package/src/pi/output-budgets.test.ts +3 -1
- package/src/pi/path.ts +18 -4
- package/src/pi/pi.test.ts +22 -0
- package/src/pi/read-delegation.test.ts +119 -0
- package/src/pi/read-tool.ts +109 -61
- package/src/pi/read.test.ts +351 -17
- package/src/pi/regex-worker.test.ts +42 -0
- package/src/pi/regex-worker.ts +17 -11
- package/src/pi/registration.test.ts +157 -102
- package/src/pi/render.test.ts +97 -0
- package/src/pi/render.ts +9 -9
- package/src/pi/replace-tool.ts +5 -2
- package/src/pi/report-schema.ts +75 -37
- package/src/pi/report.test.ts +73 -31
- package/src/pi/report.ts +12 -5
- package/src/pi/rg-process.ts +41 -5
- package/src/pi/rg-regex.test.ts +12 -39
- package/src/pi/rg-regex.ts +31 -79
- package/src/pi/text-stream.test.ts +3 -0
- package/src/pi/text-stream.ts +1 -1
- package/src/testing/regex-translation-corpus.ts +39 -96
|
@@ -63,6 +63,11 @@ function projectValueSchema(
|
|
|
63
63
|
}
|
|
64
64
|
return schema;
|
|
65
65
|
}
|
|
66
|
+
// A field can be forbidden by the operation regardless of its value's type.
|
|
67
|
+
if (!IsObject(schema) && projection.explained.has(path)) {
|
|
68
|
+
projection.applicable.add(path);
|
|
69
|
+
return Type.Unknown();
|
|
70
|
+
}
|
|
66
71
|
if ("type" in schema && !Value.Check(Type.Unknown({ type: schema.type }), value)) return schema;
|
|
67
72
|
projection.applicable.add(path);
|
|
68
73
|
// An issue on a whole object, such as a choice between its fields, explains
|
|
@@ -79,7 +84,6 @@ function projectValueSchema(
|
|
|
79
84
|
);
|
|
80
85
|
return Type.Object(properties, ObjectOptions(schema));
|
|
81
86
|
}
|
|
82
|
-
if (projection.explained.has(path)) return Type.Unknown();
|
|
83
87
|
if (IsArray(schema) && Array.isArray(value)) {
|
|
84
88
|
const items = value.map((item, index) =>
|
|
85
89
|
projectSchema(schema.items, item, `${path}[${index}]`, projection),
|
|
@@ -99,46 +103,19 @@ function propertyPath(path: string, key: string): string {
|
|
|
99
103
|
: `${path}[${JSON.stringify(key)}]`;
|
|
100
104
|
}
|
|
101
105
|
|
|
102
|
-
|
|
103
|
-
|
|
106
|
+
/** Declared tool fields do not contain slashes or tildes. TypeBox emits unknown keys verbatim. */
|
|
104
107
|
function pointerParts(pointer: string): readonly string[] {
|
|
105
|
-
return pointer.split("/").slice(1)
|
|
108
|
+
return pointer.split("/").slice(1);
|
|
106
109
|
}
|
|
107
110
|
|
|
108
|
-
|
|
109
|
-
* The projection paths of the value at `pointer` and of its parent; the root is "". Pi's TypeBox
|
|
110
|
-
* leaves `/` and `~` in property names unescaped, so a name spans the fewest segments that form
|
|
111
|
-
* an own key, read escaped or as is.
|
|
112
|
-
*/
|
|
113
|
-
function valuePaths(pointer: string, prepared: unknown): { path: string; parent: string } {
|
|
114
|
-
const segments = pointer.split("/").slice(1);
|
|
111
|
+
function valuePath(parts: readonly string[], prepared: unknown): string {
|
|
115
112
|
let value = prepared;
|
|
116
113
|
let path = "";
|
|
117
|
-
|
|
118
|
-
for (let index = 0; index < segments.length; index++) {
|
|
119
|
-
let part = unescapePointer(segments[index]);
|
|
120
|
-
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
|
|
121
|
-
const object = value;
|
|
122
|
-
for (let end = index + 1; end <= segments.length; end++) {
|
|
123
|
-
const raw = segments.slice(index, end).join("/");
|
|
124
|
-
const key = [unescapePointer(raw), raw].find((name) => Object.hasOwn(object, name));
|
|
125
|
-
if (key !== undefined) {
|
|
126
|
-
part = key;
|
|
127
|
-
index = end - 1;
|
|
128
|
-
break;
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
parent = path;
|
|
114
|
+
for (const part of parts) {
|
|
133
115
|
path = Array.isArray(value) ? `${path}[${part}]` : propertyPath(path, part);
|
|
134
116
|
value = typeof value === "object" && value !== null ? Reflect.get(value, part) : undefined;
|
|
135
117
|
}
|
|
136
|
-
return
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
function fieldPath(pointer: string, prepared: unknown, key?: string): string {
|
|
140
|
-
const { path } = valuePaths(pointer, prepared);
|
|
141
|
-
return (key === undefined ? path : propertyPath(path, key)) || "$";
|
|
118
|
+
return path;
|
|
142
119
|
}
|
|
143
120
|
|
|
144
121
|
/** One declaration's meaning: its description, labeled with its values when it is a choice. */
|
|
@@ -206,36 +183,39 @@ function aggregateErrors(
|
|
|
206
183
|
const add = (field: string, reason: string, fix?: string) =>
|
|
207
184
|
issues.push(fix === undefined ? { field, reason } : { field, reason, fix });
|
|
208
185
|
for (const error of errors) {
|
|
186
|
+
const parts = pointerParts(error.instancePath);
|
|
209
187
|
switch (error.keyword) {
|
|
210
188
|
case "required": {
|
|
211
|
-
const parts = pointerParts(error.instancePath);
|
|
212
189
|
for (const key of error.params.requiredProperties)
|
|
213
190
|
add(
|
|
214
|
-
|
|
191
|
+
propertyPath(valuePath(parts, prepared), key),
|
|
215
192
|
"is required",
|
|
216
193
|
fieldExplanation(parameters, [...parts, key]),
|
|
217
194
|
);
|
|
218
195
|
break;
|
|
219
196
|
}
|
|
220
197
|
case "additionalProperties": {
|
|
221
|
-
const
|
|
198
|
+
const path = valuePath(parts, prepared);
|
|
222
199
|
const fix = shapeExplanation(objects.get(path));
|
|
223
200
|
for (const key of error.params.additionalProperties)
|
|
224
|
-
add(
|
|
201
|
+
add(propertyPath(path, key), "is not allowed", fix);
|
|
225
202
|
break;
|
|
226
203
|
}
|
|
227
204
|
case "pattern":
|
|
228
|
-
add(
|
|
229
|
-
fieldPath(error.instancePath, prepared),
|
|
230
|
-
error.message,
|
|
231
|
-
fieldExplanation(parameters, pointerParts(error.instancePath)),
|
|
232
|
-
);
|
|
205
|
+
add(valuePath(parts, prepared) || "$", error.message, fieldExplanation(parameters, parts));
|
|
233
206
|
break;
|
|
234
207
|
case "boolean": {
|
|
235
|
-
//
|
|
236
|
-
|
|
208
|
+
// TypeBox emits a false-schema error per unknown key before its grouped error.
|
|
209
|
+
// Count declared path steps to preserve the entire unknown key, even if it contains '/'.
|
|
210
|
+
const depth = error.schemaPath
|
|
211
|
+
.split("/")
|
|
212
|
+
.filter(
|
|
213
|
+
(segment) =>
|
|
214
|
+
segment === "properties" || segment === "items" || segment === "prefixItems",
|
|
215
|
+
).length;
|
|
216
|
+
const parent = valuePath(parts.slice(0, depth), prepared);
|
|
237
217
|
add(
|
|
238
|
-
|
|
218
|
+
propertyPath(parent, parts.slice(depth).join("/")),
|
|
239
219
|
"is not allowed",
|
|
240
220
|
shapeExplanation(objects.get(parent)),
|
|
241
221
|
);
|
|
@@ -243,13 +223,13 @@ function aggregateErrors(
|
|
|
243
223
|
}
|
|
244
224
|
case "enum":
|
|
245
225
|
add(
|
|
246
|
-
|
|
226
|
+
valuePath(parts, prepared) || "$",
|
|
247
227
|
`expected one of: ${error.params.allowedValues.map((value) => JSON.stringify(value)).join(", ")}`,
|
|
248
|
-
fieldExplanation(parameters,
|
|
228
|
+
fieldExplanation(parameters, parts),
|
|
249
229
|
);
|
|
250
230
|
break;
|
|
251
231
|
default:
|
|
252
|
-
add(
|
|
232
|
+
add(valuePath(parts, prepared) || "$", error.message);
|
|
253
233
|
}
|
|
254
234
|
}
|
|
255
235
|
return combineIssues(issues);
|
|
@@ -26,6 +26,32 @@ const {
|
|
|
26
26
|
makeWriteOverride,
|
|
27
27
|
} = await import("./tool-factories.testing.ts");
|
|
28
28
|
|
|
29
|
+
test('grep receives flags: "i" → rejects INVALID_ARGUMENTS before searching', async () => {
|
|
30
|
+
let searches = 0;
|
|
31
|
+
const discover = async () => {
|
|
32
|
+
searches++;
|
|
33
|
+
return { code: 1, stderr: "", stopped: false };
|
|
34
|
+
};
|
|
35
|
+
const tool = makeMockGrep(process.cwd(), DEFAULT_CONFIG, {
|
|
36
|
+
runRgPaths: discover,
|
|
37
|
+
runRgLines: discover,
|
|
38
|
+
});
|
|
39
|
+
await assert.rejects(
|
|
40
|
+
callTool(tool, { pattern: ["text"], literal: true, flags: "i" }),
|
|
41
|
+
(error: unknown) => {
|
|
42
|
+
const report = argumentError(error);
|
|
43
|
+
assert.equal(report.error, "INVALID_ARGUMENTS");
|
|
44
|
+
assert.deepEqual(
|
|
45
|
+
report.issues.map((issue) => issue.field),
|
|
46
|
+
["flags"],
|
|
47
|
+
);
|
|
48
|
+
assert.match(report.issues[0].reason, /not allowed/);
|
|
49
|
+
return true;
|
|
50
|
+
},
|
|
51
|
+
);
|
|
52
|
+
assert.equal(searches, 0);
|
|
53
|
+
});
|
|
54
|
+
|
|
29
55
|
const invalidCommand = { command: "", timeout: 0 };
|
|
30
56
|
const anchorHash = "A".repeat(DEFAULT_CONFIG.hashLen);
|
|
31
57
|
const cases = [
|
|
@@ -196,16 +222,11 @@ test("blank then_run command with Fusion → reports exactly one command issue",
|
|
|
196
222
|
}
|
|
197
223
|
});
|
|
198
224
|
|
|
199
|
-
test("
|
|
225
|
+
test("replace flags → accept V8 modes and reject invalid flags before patterns or file reads", async (t) => {
|
|
200
226
|
const cwd = await mkdtemp(join(tmpdir(), "hashline-flags-"));
|
|
201
227
|
t.after(() => rm(cwd, { recursive: true, force: true }));
|
|
202
228
|
const path = join(cwd, "missing.txt");
|
|
203
229
|
const tools = [
|
|
204
|
-
{
|
|
205
|
-
tool: makeGrepOverride(cwd, DEFAULT_CONFIG),
|
|
206
|
-
args: (find: string, literal: boolean, flags: string) => ({ pattern: find, literal, flags }),
|
|
207
|
-
field: "flags",
|
|
208
|
-
},
|
|
209
230
|
{
|
|
210
231
|
tool: makeReplaceTool(cwd, DEFAULT_CONFIG),
|
|
211
232
|
args: (find: string, literal: boolean, flags: string) => ({
|
|
@@ -240,6 +261,46 @@ test("grep and replace flags → accept V8 modes and reject invalid flags before
|
|
|
240
261
|
}
|
|
241
262
|
});
|
|
242
263
|
|
|
264
|
+
test("invalid regex pattern → explains literal recovery without changing the requested mode", async (t) => {
|
|
265
|
+
const cwd = await mkdtemp(join(tmpdir(), "hashline-regex-recovery-"));
|
|
266
|
+
t.after(() => rm(cwd, { recursive: true, force: true }));
|
|
267
|
+
const path = join(cwd, "missing.txt");
|
|
268
|
+
const cases = [
|
|
269
|
+
{
|
|
270
|
+
tool: makeGrepOverride(cwd, DEFAULT_CONFIG),
|
|
271
|
+
args: (find: string, literal: boolean) => ({ pattern: [find], literal }),
|
|
272
|
+
field: "pattern[0]",
|
|
273
|
+
},
|
|
274
|
+
{
|
|
275
|
+
tool: makeReplaceTool(cwd, DEFAULT_CONFIG),
|
|
276
|
+
args: (find: string, literal: boolean) => ({
|
|
277
|
+
replacements: [{ find, literal, replace: "updated" }],
|
|
278
|
+
}),
|
|
279
|
+
field: "replacements[0].find",
|
|
280
|
+
},
|
|
281
|
+
];
|
|
282
|
+
for (const { tool, args, field } of cases) {
|
|
283
|
+
await t.test(tool.name, async () => {
|
|
284
|
+
const input = { path, ...args("call(", false) };
|
|
285
|
+
const original = structuredClone(input);
|
|
286
|
+
await assert.rejects(callTool(tool, input), (error: unknown) => {
|
|
287
|
+
const { issues } = argumentError(error);
|
|
288
|
+
assert.equal(issues.length, 1);
|
|
289
|
+
assert.equal(issues[0].field, field);
|
|
290
|
+
assert.match(issues[0].reason, /Invalid regular expression/);
|
|
291
|
+
assert.match(issues[0].fix ?? "", /literal.*true.*otherwise.*regex/);
|
|
292
|
+
return true;
|
|
293
|
+
});
|
|
294
|
+
assert.deepEqual(input, original);
|
|
295
|
+
for (const corrected of [args("call(", true), args("call\\(", false)]) {
|
|
296
|
+
const result = await callTool(tool, { path, ...corrected });
|
|
297
|
+
assert.equal(reportOf(result, tool.name)?.error, "PATH_NOT_FOUND");
|
|
298
|
+
}
|
|
299
|
+
await assert.rejects(readFile(path), { code: "ENOENT" });
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
});
|
|
303
|
+
|
|
243
304
|
const editFields = ["anchor", "end", "lines"] as const;
|
|
244
305
|
type EditField = (typeof editFields)[number];
|
|
245
306
|
const fieldValues = {
|
|
@@ -579,6 +640,24 @@ test("one field violates independent constraints → combine its reasons without
|
|
|
579
640
|
);
|
|
580
641
|
});
|
|
581
642
|
|
|
643
|
+
test("edit receives a forbidden field with the wrong type → reports the field prohibition", async () => {
|
|
644
|
+
const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
|
|
645
|
+
await assert.rejects(
|
|
646
|
+
callTool(tool, {
|
|
647
|
+
path: "unused.txt",
|
|
648
|
+
steps: [{ action: "append", lines: ["text"], anchor: {} }],
|
|
649
|
+
}),
|
|
650
|
+
(error: unknown) => {
|
|
651
|
+
const { issues } = argumentError(error);
|
|
652
|
+
assert.equal(issues.length, 1);
|
|
653
|
+
assert.equal(issues[0].field, "steps[0].anchor");
|
|
654
|
+
assert.equal(issues[0].reason, "is not allowed");
|
|
655
|
+
assert.ok(issues[0].fix);
|
|
656
|
+
return true;
|
|
657
|
+
},
|
|
658
|
+
);
|
|
659
|
+
});
|
|
660
|
+
|
|
582
661
|
test("edit fields contain semantic errors → checks only fields accepted by their action", async (t) => {
|
|
583
662
|
const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
|
|
584
663
|
for (const scenario of actionCases) {
|
|
@@ -908,3 +987,21 @@ test("20 unknown keys including a slash → bounded issues retain one accepted-f
|
|
|
908
987
|
},
|
|
909
988
|
);
|
|
910
989
|
});
|
|
990
|
+
|
|
991
|
+
test("bounded additional-property diagnostics → preserve exact keys despite pointer-like spelling", async () => {
|
|
992
|
+
const extras = Object.fromEntries([
|
|
993
|
+
...["a/b", "a", "a~1b"].map((key) => [key, true]),
|
|
994
|
+
...Array.from({ length: 20 }, (_, index) => [`extra${index}`, true]),
|
|
995
|
+
]);
|
|
996
|
+
const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
|
|
997
|
+
await assert.rejects(
|
|
998
|
+
callTool(tool, { path: "unused.txt", steps: [{ action: "append", lines: ["ok"], ...extras }] }),
|
|
999
|
+
(error: unknown) => {
|
|
1000
|
+
const report = argumentError(error);
|
|
1001
|
+
assert.equal(report.schemaLimited, true);
|
|
1002
|
+
const fields = report.issues.map((issue) => issue.field);
|
|
1003
|
+
assert.deepEqual(fields.slice(0, 3), ['steps[0]["a/b"]', "steps[0].a", 'steps[0]["a~1b"]']);
|
|
1004
|
+
return true;
|
|
1005
|
+
},
|
|
1006
|
+
);
|
|
1007
|
+
});
|
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Shared tool argument boundary. Pi owns preparation and acceptance; tool checks
|
|
3
|
-
* report semantic issues. Failure-only diagnostics
|
|
3
|
+
* report semantic issues. Failure-only diagnostics use pi-schema's public coercer,
|
|
4
4
|
* then project and aggregate the declared schema in argument-diagnostics.ts.
|
|
5
5
|
* Pi still validates returned arguments in its mandatory tool-call pipeline.
|
|
6
6
|
* Tool schemas have no cross-field constraints.
|
|
7
7
|
*/
|
|
8
8
|
import { validateToolArguments, type ToolCall } from "@earendil-works/pi-ai";
|
|
9
|
-
import {
|
|
9
|
+
import { compile } from "@earendil-works/pi-schema";
|
|
10
|
+
import { formats } from "@earendil-works/pi-schema/formats";
|
|
11
|
+
import type { Static, TObject } from "typebox";
|
|
10
12
|
import { errorMessage } from "../core/errors.ts";
|
|
13
|
+
import { buildRegex } from "../core/regex.ts";
|
|
11
14
|
import { diagnoseArguments } from "./argument-diagnostics.ts";
|
|
12
15
|
import { formatArgumentError } from "./argument-error.ts";
|
|
13
16
|
import type { OutputBudgetProvider } from "./budgets.ts";
|
|
@@ -17,6 +20,39 @@ import type { ArgumentIssue, ReportTool } from "./report-schema.ts";
|
|
|
17
20
|
export type ReportArgumentIssue = (field: string, reason: string, fix?: string) => void;
|
|
18
21
|
export type CheckArguments = (args: unknown, report: ReportArgumentIssue) => void;
|
|
19
22
|
|
|
23
|
+
/**
|
|
24
|
+
* Report V8's diagnostics for a rule's flags and, in regex mode, for each pattern that
|
|
25
|
+
* buildRegex would reject. Invalid flags stop the check, since every pattern compiles with
|
|
26
|
+
* them; values that are not strings are left to schema validation.
|
|
27
|
+
*/
|
|
28
|
+
export function checkRegexArguments(
|
|
29
|
+
flagsField: string,
|
|
30
|
+
flags: string | undefined,
|
|
31
|
+
literal: boolean,
|
|
32
|
+
patterns: readonly (readonly [field: string, value: unknown])[],
|
|
33
|
+
report: ReportArgumentIssue,
|
|
34
|
+
): void {
|
|
35
|
+
try {
|
|
36
|
+
buildRegex("", true, flags);
|
|
37
|
+
} catch (error) {
|
|
38
|
+
report(flagsField, errorMessage(error));
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
if (literal) return;
|
|
42
|
+
for (const [field, value] of patterns) {
|
|
43
|
+
if (typeof value !== "string") continue;
|
|
44
|
+
try {
|
|
45
|
+
buildRegex(value, false, flags);
|
|
46
|
+
} catch (error) {
|
|
47
|
+
report(
|
|
48
|
+
field,
|
|
49
|
+
errorMessage(error),
|
|
50
|
+
"For an exact-text match, set literal to true; otherwise correct the regex syntax.",
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
20
56
|
/** Inspect arrays and the singleton objects Pi may coerce, without changing input. */
|
|
21
57
|
export function argumentItems(value: unknown): readonly unknown[] {
|
|
22
58
|
return Array.isArray(value) ? value : value !== null && typeof value === "object" ? [value] : [];
|
|
@@ -28,45 +64,34 @@ export function createArgumentPreparer<T extends TObject>(
|
|
|
28
64
|
check: CheckArguments | undefined,
|
|
29
65
|
budgets: OutputBudgetProvider,
|
|
30
66
|
): (args: unknown) => Static<T> {
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
type: "toolCall",
|
|
37
|
-
id: "argument-validation",
|
|
38
|
-
name,
|
|
39
|
-
arguments: args as ToolCall["arguments"],
|
|
40
|
-
},
|
|
41
|
-
);
|
|
67
|
+
const diagnosticValidator = compile(parameters, {
|
|
68
|
+
formats,
|
|
69
|
+
coerce: true,
|
|
70
|
+
unresolvedRefs: "reject",
|
|
71
|
+
});
|
|
42
72
|
|
|
43
73
|
return (args) => {
|
|
44
74
|
let checked: unknown = args;
|
|
45
75
|
let schemaFailure: unknown;
|
|
46
76
|
try {
|
|
47
|
-
checked =
|
|
77
|
+
checked = validateToolArguments(
|
|
78
|
+
{ name, parameters, description: "" },
|
|
79
|
+
// Pi owns shape checking and coercion at this external boundary.
|
|
80
|
+
{
|
|
81
|
+
type: "toolCall",
|
|
82
|
+
id: "argument-validation",
|
|
83
|
+
name,
|
|
84
|
+
arguments: args as ToolCall["arguments"],
|
|
85
|
+
},
|
|
86
|
+
);
|
|
48
87
|
} catch (error) {
|
|
49
88
|
schemaFailure = error;
|
|
50
89
|
}
|
|
51
90
|
if (schemaFailure !== undefined) {
|
|
52
|
-
let observation: { readonly value: unknown } | undefined;
|
|
53
|
-
// Pi does not expose failed prepared values. A successful allOf refinement
|
|
54
|
-
// observes its error pass without changing coercion, null handling or acceptance.
|
|
55
|
-
const observer = Type.Object(parameters.properties, {
|
|
56
|
-
...ObjectOptions(parameters),
|
|
57
|
-
allOf: [
|
|
58
|
-
Type.Refine(Type.Unknown(), (value: unknown) => {
|
|
59
|
-
observation = { value };
|
|
60
|
-
return true;
|
|
61
|
-
}),
|
|
62
|
-
],
|
|
63
|
-
});
|
|
64
91
|
try {
|
|
65
|
-
|
|
92
|
+
checked = diagnosticValidator.coerce(structuredClone(args));
|
|
66
93
|
} catch {
|
|
67
|
-
//
|
|
68
|
-
}
|
|
69
|
-
if (!observation) {
|
|
94
|
+
// Preparation failures retain Pi's original cause in the shared error envelope.
|
|
70
95
|
throw new Error(
|
|
71
96
|
formatArgumentError(
|
|
72
97
|
[{ field: "$", reason: errorMessage(schemaFailure) }],
|
|
@@ -76,7 +101,6 @@ export function createArgumentPreparer<T extends TObject>(
|
|
|
76
101
|
{ cause: schemaFailure },
|
|
77
102
|
);
|
|
78
103
|
}
|
|
79
|
-
checked = observation.value;
|
|
80
104
|
}
|
|
81
105
|
const issues: ArgumentIssue[] = [];
|
|
82
106
|
check?.(checked, (field, reason, fix) =>
|
package/src/pi/budgets.ts
CHANGED
|
@@ -3,25 +3,33 @@
|
|
|
3
3
|
* The context window is a capacity hint, not a tokenizer or remaining-context counter.
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
+
// A read is a chosen window of one file; a grep is a probe whose size the caller cannot predict.
|
|
7
|
+
// At four bytes per token a full read spends about a sixteenth of the window, a full grep a
|
|
8
|
+
// thirty-second.
|
|
9
|
+
const READ_SHARE = 4;
|
|
10
|
+
const GREP_SHARE = 8;
|
|
11
|
+
// A preview grows with the payload: one UTF-16 unit per this many payload bytes.
|
|
12
|
+
const GREP_PREVIEW_SHARE = 100;
|
|
13
|
+
// Pi's built-in grep keeps this many characters of a line. A narrower preview cuts a row in
|
|
14
|
+
// far more calls and keeps almost none of them within the payload budget.
|
|
15
|
+
const MIN_GREP_PREVIEW_UNITS = 500;
|
|
6
16
|
const BLOCK_SHARE = 4;
|
|
7
17
|
const FIELD_SHARE = 4;
|
|
8
|
-
const UTF16_PREVIEW_BYTES = 4;
|
|
9
18
|
// Keep JSON envelopes and diagnostic omission markers usable for tiny declared windows.
|
|
10
19
|
const MIN_BLOCK_BYTES = 512;
|
|
11
20
|
const MIN_FIELD_BYTES = 128;
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
// not surpass what a user could configure, keeping one absolute bound per call.
|
|
21
|
+
// Capacity counted toward the budgets stops here; config.ts reuses this constant for the
|
|
22
|
+
// read.maxKiB range, so automatic sizing never surpasses what a user could configure.
|
|
15
23
|
export const MAX_CONTENT_KIB = 4096;
|
|
16
24
|
const MAX_CONTENT_BYTES = MAX_CONTENT_KIB * 1024;
|
|
17
25
|
|
|
18
26
|
// Declared apart so Object.freeze keeps these as numbers rather than literal types.
|
|
19
27
|
const fallbackBudgets = {
|
|
20
|
-
readBytes:
|
|
28
|
+
readBytes: 64 * 1024,
|
|
21
29
|
grepBytes: 50 * 1024,
|
|
22
30
|
blockBytes: 16 * 1024,
|
|
23
31
|
fieldBytes: 4 * 1024,
|
|
24
|
-
grepPreviewUnits:
|
|
32
|
+
grepPreviewUnits: MIN_GREP_PREVIEW_UNITS,
|
|
25
33
|
};
|
|
26
34
|
const DEFAULT_OUTPUT_BUDGETS = Object.freeze(fallbackBudgets);
|
|
27
35
|
export type OutputBudgets = typeof DEFAULT_OUTPUT_BUDGETS;
|
|
@@ -32,16 +40,17 @@ export function outputBudgetsFor(contextWindow: number | undefined): OutputBudge
|
|
|
32
40
|
if (contextWindow === undefined || !Number.isSafeInteger(contextWindow) || contextWindow <= 0) {
|
|
33
41
|
return DEFAULT_OUTPUT_BUDGETS;
|
|
34
42
|
}
|
|
35
|
-
// One byte per declared context token.
|
|
43
|
+
// One byte per declared context token, shared out below.
|
|
36
44
|
const contentBytes = Math.min(contextWindow, MAX_CONTENT_BYTES);
|
|
45
|
+
const grepBytes = Math.max(MIN_BLOCK_BYTES, Math.floor(contentBytes / GREP_SHARE));
|
|
37
46
|
const blockBytes = Math.max(MIN_BLOCK_BYTES, Math.floor(contentBytes / BLOCK_SHARE));
|
|
38
47
|
const fieldBytes = Math.max(MIN_FIELD_BYTES, Math.floor(blockBytes / FIELD_SHARE));
|
|
39
48
|
return Object.freeze({
|
|
40
|
-
readBytes: contentBytes,
|
|
41
|
-
grepBytes
|
|
49
|
+
readBytes: Math.max(MIN_BLOCK_BYTES, Math.floor(contentBytes / READ_SHARE)),
|
|
50
|
+
grepBytes,
|
|
42
51
|
blockBytes,
|
|
43
52
|
fieldBytes,
|
|
44
|
-
grepPreviewUnits: Math.floor(
|
|
53
|
+
grepPreviewUnits: Math.max(MIN_GREP_PREVIEW_UNITS, Math.floor(grepBytes / GREP_PREVIEW_SHARE)),
|
|
45
54
|
});
|
|
46
55
|
}
|
|
47
56
|
|
package/src/pi/config.test.ts
CHANGED
|
@@ -37,7 +37,7 @@ test("defaults come from the settings schema", () => {
|
|
|
37
37
|
hashLen: 4,
|
|
38
38
|
shiftRadius: 15,
|
|
39
39
|
read: { defaultLimit: DEFAULT_MAX_LINES, maxKiB: undefined },
|
|
40
|
-
grep: {
|
|
40
|
+
grep: { defaultLimit: 100, defaultContext: 0, regexTimeoutMs: 5_000 },
|
|
41
41
|
replace: { regexTimeoutMs: 5_000 },
|
|
42
42
|
});
|
|
43
43
|
});
|
|
@@ -52,6 +52,7 @@ test("search warning aggregation retains the final cause and labels truncation",
|
|
|
52
52
|
const { facts, payload } = await grepOutput({
|
|
53
53
|
budget: DEFAULT_OUTPUT_BUDGETS,
|
|
54
54
|
cwd: process.cwd(),
|
|
55
|
+
missing: [],
|
|
55
56
|
anchors: createAnchorFormatter(4),
|
|
56
57
|
context: 0,
|
|
57
58
|
search: {
|
package/src/pi/edit-tool.ts
CHANGED
|
@@ -108,7 +108,7 @@ function buildEditSchema(hashLen: number) {
|
|
|
108
108
|
},
|
|
109
109
|
{
|
|
110
110
|
additionalProperties: false,
|
|
111
|
-
description: "One
|
|
111
|
+
description: "One step. Omit, or set to null, each field its action does not take.",
|
|
112
112
|
},
|
|
113
113
|
);
|
|
114
114
|
return Type.Object(
|
|
@@ -117,7 +117,7 @@ function buildEditSchema(hashLen: number) {
|
|
|
117
117
|
steps: Type.Array(editOpSchema, {
|
|
118
118
|
minItems: 1,
|
|
119
119
|
maxItems: MAX_EDIT_OPS,
|
|
120
|
-
description: `
|
|
120
|
+
description: `Steps applied to one snapshot; ranges must not overlap. Each gap between lines takes at most one insertion; insert_after N and insert_before N+1 target the same gap, so put all new lines for a gap in one step. An insertion at the start of a replaced or deleted range goes before it. Anchors are LINE#HASH with exactly ${hashLen} hash characters. Copy each anchor from read, grep, or edit failure diagnostics; never write a hash you have not seen there. Shell output such as sed, head, or cat has no anchors, so read or grep those lines first.`,
|
|
121
121
|
}),
|
|
122
122
|
},
|
|
123
123
|
{ additionalProperties: false },
|
|
@@ -283,7 +283,7 @@ export function makeEditOverride(env: MutationToolEnvironment) {
|
|
|
283
283
|
"Edit whole lines using LINE#HASH anchors checked against the current file. Use replace instead when the same change repeats in several places, or when only a fragment of a long line changes.",
|
|
284
284
|
promptSnippet: "Edit file lines using verified anchors",
|
|
285
285
|
promptGuidelines: [
|
|
286
|
-
"Batch all steps for one file into a single edit call.",
|
|
286
|
+
"Batch all steps for one file into a single edit call, and send changes to different files in the same response; they do not interfere.",
|
|
287
287
|
"Before citing a line after write, edit, or replace, get its anchor from a new read or grep. Only after edit, lines above the earliest changed line keep their anchors.",
|
|
288
288
|
],
|
|
289
289
|
check: (args, report) =>
|
package/src/pi/execute.test.ts
CHANGED
|
@@ -603,6 +603,10 @@ test("failed commands preserve mutation results and stay out of all main card re
|
|
|
603
603
|
invalidate() {},
|
|
604
604
|
lastComponent: undefined,
|
|
605
605
|
executionStarted: true,
|
|
606
|
+
durationMs: undefined,
|
|
607
|
+
outputPad: 1,
|
|
608
|
+
keyText: () => "",
|
|
609
|
+
keyHint: (_key, description) => description,
|
|
606
610
|
argsComplete: true,
|
|
607
611
|
isPartial: false,
|
|
608
612
|
expanded: true,
|
|
@@ -113,7 +113,10 @@ test("more than eight ambiguous candidates → context uses the same candidate p
|
|
|
113
113
|
});
|
|
114
114
|
|
|
115
115
|
test("neighborhood exceeds byte budget → whole rows and explicit omission counts", () => {
|
|
116
|
-
const
|
|
116
|
+
const empty = [{ lines: "1-1", rows: ["1#XXXX│"] }];
|
|
117
|
+
const exact = "x".repeat(
|
|
118
|
+
DEFAULT_OUTPUT_BUDGETS.blockBytes - Buffer.byteLength(JSON.stringify(empty)),
|
|
119
|
+
);
|
|
117
120
|
const cases = [
|
|
118
121
|
{ lines: [exact, "target", "last"], shown: [1], omitted: 2 },
|
|
119
122
|
{ lines: ["界".repeat(6000), "target", "last"], shown: [2, 3], omitted: 1 },
|
|
@@ -140,7 +143,7 @@ test("neighborhood exceeds byte budget → whole rows and explicit omission coun
|
|
|
140
143
|
);
|
|
141
144
|
assert.equal(result.omittedNeighborhoodRows, omitted);
|
|
142
145
|
assert.ok(
|
|
143
|
-
Buffer.byteLength(
|
|
146
|
+
Buffer.byteLength(JSON.stringify(result.candidateNeighborhoods)) <=
|
|
144
147
|
DEFAULT_OUTPUT_BUDGETS.blockBytes,
|
|
145
148
|
);
|
|
146
149
|
}
|
|
@@ -320,7 +323,7 @@ test("overlapping edits → ordered conflict and shared recovery", () => {
|
|
|
320
323
|
assert.deepEqual(report.conflict, ["steps[0]", "steps[2]"]);
|
|
321
324
|
assert.equal(report.message, error.message);
|
|
322
325
|
assert.equal(report.publication, "NOT_PUBLISHED");
|
|
323
|
-
assert.match(report.next ?? "", /one
|
|
326
|
+
assert.match(report.next ?? "", /one step per range or position/);
|
|
324
327
|
return true;
|
|
325
328
|
},
|
|
326
329
|
);
|
|
@@ -347,3 +350,21 @@ test("unresolved row out of range or oversized → omission facts contain no rec
|
|
|
347
350
|
);
|
|
348
351
|
}
|
|
349
352
|
});
|
|
353
|
+
|
|
354
|
+
test("escaped neighborhood rows → count their JSON bytes before reporting complete rows", () => {
|
|
355
|
+
const budget = outputBudgetsFor(1);
|
|
356
|
+
const report = rejectedEdit(
|
|
357
|
+
`current\n${"\\".repeat(Math.floor(budget.blockBytes * 0.75))}\nold\nold\n`,
|
|
358
|
+
[{ op: "delete", anchor: oldAnchor }],
|
|
359
|
+
4,
|
|
360
|
+
budget,
|
|
361
|
+
);
|
|
362
|
+
assert.ok(report.candidateNeighborhoods);
|
|
363
|
+
assert.ok(Buffer.byteLength(JSON.stringify(report.candidateNeighborhoods)) <= budget.blockBytes);
|
|
364
|
+
const shown = report.candidateNeighborhoods.flatMap((group) => group.rows);
|
|
365
|
+
assert.deepEqual(
|
|
366
|
+
shown.map((row) => Number(row.split("#")[0])),
|
|
367
|
+
[1, 3, 4],
|
|
368
|
+
);
|
|
369
|
+
assert.equal(report.omittedNeighborhoodRows, 1);
|
|
370
|
+
});
|