@criogaid/pi-hashline-edit 0.6.1 → 0.8.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 (161) hide show
  1. package/README.md +78 -369
  2. package/README.zh-CN.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +80 -0
  4. package/package.json +11 -6
  5. package/src/core/AGENTS.md +20 -0
  6. package/src/core/apply.test.ts +328 -161
  7. package/src/core/apply.ts +129 -95
  8. package/src/core/case-fold.test.ts +44 -0
  9. package/src/core/case-fold.ts +77 -0
  10. package/src/core/character-set.test.ts +103 -0
  11. package/src/core/character-set.ts +184 -0
  12. package/src/core/errors.test.ts +23 -0
  13. package/src/core/errors.ts +70 -4
  14. package/src/core/hash.test.ts +1 -25
  15. package/src/core/hash.ts +0 -5
  16. package/src/core/lines.ts +32 -7
  17. package/src/core/ranges.test.ts +41 -9
  18. package/src/core/ranges.ts +11 -4
  19. package/src/core/regex.ts +51 -0
  20. package/src/core/replace-schema.ts +41 -0
  21. package/src/core/replace.test.ts +90 -0
  22. package/src/core/replace.ts +40 -56
  23. package/src/core/search-analysis.test.ts +208 -0
  24. package/src/core/search-analysis.ts +379 -0
  25. package/src/core/search-matrix.test.ts +64 -0
  26. package/src/core/search-matrix.testing.ts +183 -0
  27. package/src/core/search-schema.ts +18 -0
  28. package/src/core/search.test.ts +145 -0
  29. package/src/core/search.ts +119 -0
  30. package/src/core/text.test.ts +16 -8
  31. package/src/core/text.ts +26 -6
  32. package/src/core/types.ts +20 -17
  33. package/src/index.ts +24 -16
  34. package/src/integration/config-registration.test.ts +42 -28
  35. package/src/integration/fusion-dispatch.test.ts +62 -127
  36. package/src/integration/grep-errors.test.ts +50 -0
  37. package/src/integration/grep-flags.test.ts +273 -0
  38. package/src/integration/grep-js-completeness.test.ts +218 -0
  39. package/src/integration/grep-line-candidates.test.ts +233 -0
  40. package/src/integration/grep-matrix.test.ts +121 -0
  41. package/src/integration/grep-order.test.ts +78 -0
  42. package/src/integration/grep-path-matrix.test.ts +133 -0
  43. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  44. package/src/integration/grep-regex.test.ts +407 -0
  45. package/src/integration/grep-rg.test.ts +294 -436
  46. package/src/integration/grep-scan-budget.test.ts +111 -0
  47. package/src/integration/grep-translation.test.ts +206 -0
  48. package/src/integration/large-text.test.ts +56 -1
  49. package/src/integration/model-budget-lifecycle.test.ts +137 -0
  50. package/src/integration/mutation-file-types.test.ts +12 -26
  51. package/src/integration/mutation-file-types.testing.ts +33 -0
  52. package/src/integration/npm-package.test.ts +17 -0
  53. package/src/integration/npm-package.testing.ts +97 -0
  54. package/src/integration/publication-read-changes.test.ts +376 -0
  55. package/src/integration/read-changes.test.ts +98 -0
  56. package/src/integration/replace-package.test.ts +17 -36
  57. package/src/integration/replace-package.testing.ts +36 -0
  58. package/src/integration/replace-worker-boundary.test.ts +117 -0
  59. package/src/integration/report-replay.test.ts +90 -0
  60. package/src/integration/utf8-errors.test.ts +46 -0
  61. package/src/pi/AGENTS.md +54 -0
  62. package/src/pi/action-fusion.test.ts +256 -251
  63. package/src/pi/action-fusion.ts +121 -332
  64. package/src/pi/anchor-format.test.ts +16 -0
  65. package/src/pi/anchor-format.ts +16 -3
  66. package/src/pi/argument-diagnostics.ts +478 -0
  67. package/src/pi/argument-error.testing.ts +46 -0
  68. package/src/pi/argument-error.ts +76 -0
  69. package/src/pi/argument-format.test.ts +197 -0
  70. package/src/pi/argument-validation.test.ts +780 -49
  71. package/src/pi/argument-validation.ts +55 -58
  72. package/src/pi/budgets.ts +48 -21
  73. package/src/pi/codemode.test.ts +96 -0
  74. package/src/pi/config.test.ts +29 -15
  75. package/src/pi/config.ts +27 -13
  76. package/src/pi/diagnostic-buffer.test.ts +51 -16
  77. package/src/pi/diagnostic-buffer.ts +13 -16
  78. package/src/pi/directory-sync.test.ts +4 -1
  79. package/src/pi/edit-tool.ts +103 -99
  80. package/src/pi/error-text.ts +39 -16
  81. package/src/pi/execute.test.ts +407 -429
  82. package/src/pi/extension-loading.test.ts +7 -27
  83. package/src/pi/extension-loading.testing.ts +2 -14
  84. package/src/pi/failure-context.test.ts +265 -88
  85. package/src/pi/failure-context.ts +165 -181
  86. package/src/pi/failure-path.test.ts +179 -117
  87. package/src/pi/file-commit.test.ts +90 -73
  88. package/src/pi/file-commit.ts +216 -178
  89. package/src/pi/file-read.test.ts +29 -0
  90. package/src/pi/file-read.ts +60 -0
  91. package/src/pi/file-revision.ts +25 -0
  92. package/src/pi/file-snapshot.test.ts +1 -1
  93. package/src/pi/fusion-card-interaction.test.ts +143 -0
  94. package/src/pi/fusion-card.test.ts +233 -51
  95. package/src/pi/fusion-card.ts +246 -142
  96. package/src/pi/grep-candidates.test.ts +127 -0
  97. package/src/pi/grep-candidates.ts +191 -0
  98. package/src/pi/grep-matrix.test.ts +83 -0
  99. package/src/pi/grep-order.test.ts +323 -0
  100. package/src/pi/grep-output.testing.ts +24 -0
  101. package/src/pi/grep-output.ts +187 -151
  102. package/src/pi/grep-render.ts +31 -25
  103. package/src/pi/grep-scope.ts +62 -54
  104. package/src/pi/grep-search.ts +327 -241
  105. package/src/pi/grep-tool.ts +126 -147
  106. package/src/pi/grep-worker.mjs +4 -0
  107. package/src/pi/grep-worker.ts +14 -0
  108. package/src/pi/grep.test.ts +813 -713
  109. package/src/pi/model-budgets.test.ts +43 -0
  110. package/src/pi/model-budgets.ts +44 -0
  111. package/src/pi/mutation-outcome.testing.ts +6 -7
  112. package/src/pi/mutation-result.test.ts +45 -91
  113. package/src/pi/mutation-result.ts +86 -114
  114. package/src/pi/mutation-runner.ts +81 -81
  115. package/src/pi/output-budgets.test.ts +175 -0
  116. package/src/pi/path.ts +10 -1
  117. package/src/pi/pi.test.ts +4 -5
  118. package/src/pi/read-tool.ts +108 -142
  119. package/src/pi/read.test.ts +155 -96
  120. package/src/pi/regex-worker-contract.ts +55 -0
  121. package/src/pi/regex-worker.ts +95 -0
  122. package/src/pi/registration.test.ts +148 -124
  123. package/src/pi/render.test.ts +361 -84
  124. package/src/pi/render.ts +150 -32
  125. package/src/pi/replace-regex.ts +13 -48
  126. package/src/pi/replace-tool.ts +52 -158
  127. package/src/pi/replace-worker-contract.ts +10 -0
  128. package/src/pi/replace-worker.ts +12 -8
  129. package/src/pi/replace.test.ts +191 -340
  130. package/src/pi/report-cause.ts +103 -0
  131. package/src/pi/report-failure.testing.ts +20 -0
  132. package/src/pi/report-schema.ts +524 -0
  133. package/src/pi/report.test.ts +343 -0
  134. package/src/pi/report.ts +285 -0
  135. package/src/pi/result-safety.test.ts +216 -481
  136. package/src/pi/rg-process.test.ts +101 -76
  137. package/src/pi/rg-process.ts +130 -177
  138. package/src/pi/rg-regex.test.ts +67 -0
  139. package/src/pi/rg-regex.ts +715 -0
  140. package/src/pi/text-stream.test.ts +97 -69
  141. package/src/pi/text-stream.ts +97 -76
  142. package/src/pi/tool-call.testing.ts +20 -46
  143. package/src/pi/write-tool.ts +50 -41
  144. package/src/pi/write.test.ts +71 -95
  145. package/src/testing/extension-loader.testing.ts +24 -0
  146. package/src/testing/installation.testing.ts +77 -0
  147. package/src/testing/process.testing.ts +33 -0
  148. package/src/testing/regex-host.testing.ts +20 -0
  149. package/src/testing/regex-translation-corpus.ts +324 -0
  150. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  151. package/src/testing/run-tests.ts +47 -0
  152. package/src/testing/session.testing.ts +127 -0
  153. package/src/integration/forget-grep.test.ts +0 -98
  154. package/src/pi/forget-tool.ts +0 -268
  155. package/src/pi/forget.test.ts +0 -343
  156. package/src/pi/forget.testing.ts +0 -273
  157. package/src/pi/rg-line-ranges.test.ts +0 -66
  158. package/src/pi/rg-line-ranges.ts +0 -75
  159. package/src/pi/rg-match-bytes.ts +0 -95
  160. package/src/pi/rg-text-view.ts +0 -192
  161. package/src/pi/tool-prompts.ts +0 -15
@@ -0,0 +1,478 @@
1
+ /** Failure-only schema projection and structured error aggregation; Pi owns input preparation and acceptance. */
2
+ import {
3
+ ArrayOptions,
4
+ IsArray,
5
+ IsLiteral,
6
+ IsObject,
7
+ IsOptional,
8
+ ObjectOptions,
9
+ IsUnion,
10
+ Type,
11
+ type TLiteralValue,
12
+ type TObject,
13
+ type TSchema,
14
+ type TUnion,
15
+ } from "typebox";
16
+ import type { TLocalizedValidationError } from "typebox/error";
17
+ import { Value } from "typebox/value";
18
+ import type { ArgumentIssue } from "./report-schema.ts";
19
+
20
+ interface ArgumentDiagnostics {
21
+ readonly issues: readonly ArgumentIssue[];
22
+ readonly limited: boolean;
23
+ }
24
+
25
+ /** The declared object a value was projected with, and the tag field that selected it among branches. */
26
+ interface SelectedShape {
27
+ readonly object: TObject;
28
+ readonly tag?: string;
29
+ }
30
+
31
+ /** State shared by one failure projection. */
32
+ interface Projection {
33
+ /** Fields a tool check already explained; their schema constraints are dropped. */
34
+ readonly explained: ReadonlySet<string>;
35
+ /** Fields that belong to the selected shapes. */
36
+ readonly applicable: Set<string>;
37
+ /** Branch constraints that native diagnostics would split across branches. */
38
+ readonly derived: ArgumentIssue[];
39
+ /** Each object path's selected shape; paths left to several branches are absent. */
40
+ readonly selected: Map<string, SelectedShape>;
41
+ }
42
+
43
+ function literalValues(schema: TSchema): readonly TLiteralValue[] | undefined {
44
+ if (IsLiteral(schema)) return [schema.const];
45
+ if (!IsUnion(schema)) return undefined;
46
+ const values = schema.anyOf.map(literalValues);
47
+ const choices = values.filter((value) => value !== undefined);
48
+ return choices.length === values.length ? choices.flat() : undefined;
49
+ }
50
+
51
+ function objectTag(schema: TUnion):
52
+ | {
53
+ readonly field: string;
54
+ readonly branches: readonly TObject[];
55
+ readonly choices: readonly TLiteralValue[];
56
+ }
57
+ | undefined {
58
+ const branches = schema.anyOf.filter(IsObject);
59
+ const first = branches[0];
60
+ if (!first || branches.length !== schema.anyOf.length) return undefined;
61
+ for (const field of Object.keys(first.properties)) {
62
+ if (!branches.every((branch) => branch.required?.includes(field))) continue;
63
+ const values = branches.map((branch) => literalValues(branch.properties[field]));
64
+ const choices = values.filter((value) => value !== undefined);
65
+ if (choices.length === branches.length) return { field, branches, choices: choices.flat() };
66
+ }
67
+ return undefined;
68
+ }
69
+
70
+ /**
71
+ * Fields that alone tell tag-sharing branches apart: each branch requires one
72
+ * field that every other branch forbids, and shares all others unchanged.
73
+ * Shared fields are compared by schema identity, so branches must reuse one
74
+ * instance per field; otherwise the general union projection applies.
75
+ */
76
+ function exclusiveFields(branches: readonly TObject[]): readonly string[] | undefined {
77
+ const fields = branches.map((branch) => {
78
+ const own = Object.keys(branch.properties).filter((field) =>
79
+ branches.some((other) => other.properties[field] !== branch.properties[field]),
80
+ );
81
+ return own.length === 1 &&
82
+ branch.required?.includes(own[0]) &&
83
+ ObjectOptions(branch).additionalProperties === false
84
+ ? own[0]
85
+ : undefined;
86
+ });
87
+ return fields.every((field): field is string => field !== undefined) &&
88
+ new Set(fields).size === fields.length
89
+ ? fields
90
+ : undefined;
91
+ }
92
+
93
+ function projectSchema(
94
+ schema: TSchema,
95
+ value: unknown,
96
+ path: string,
97
+ projection: Projection,
98
+ ): TSchema {
99
+ const projected = projectValueSchema(schema, value, path, projection);
100
+ return IsOptional(schema) && !IsOptional(projected) ? Type.Optional(projected) : projected;
101
+ }
102
+
103
+ function projectValueSchema(
104
+ schema: TSchema,
105
+ value: unknown,
106
+ path: string,
107
+ projection: Projection,
108
+ ): TSchema {
109
+ if (IsUnion(schema)) {
110
+ const choices = literalValues(schema);
111
+ if (choices) {
112
+ projection.applicable.add(path);
113
+ return Type.Unknown({ enum: [...new Set(choices)] });
114
+ }
115
+ const tag = objectTag(schema);
116
+ if (tag) {
117
+ if (typeof value !== "object" || value === null || Array.isArray(value))
118
+ return Type.Unknown({ type: "object" });
119
+ const select = (branch: TObject): TSchema => {
120
+ const projected = projectSchema(branch, value, path, projection);
121
+ projection.selected.set(path, { object: branch, tag: tag.field });
122
+ return projected;
123
+ };
124
+ const matches = tag.branches.filter((branch) =>
125
+ Value.Check(branch.properties[tag.field], Reflect.get(value, tag.field)),
126
+ );
127
+ if (matches.length === 1) return select(matches[0]);
128
+ if (matches.length === 0)
129
+ return Type.Object({ [tag.field]: Type.Unknown({ enum: [...new Set(tag.choices)] }) });
130
+ // Distinct property presence can disambiguate branches sharing a tag even
131
+ // when common fields are missing or field values are invalid. Only choose
132
+ // a branch here; its original constraints still supply the diagnostics.
133
+ const knownFields = new Set(matches.flatMap((branch) => Object.keys(branch.properties)));
134
+ const shapeValue = Object.fromEntries(
135
+ Object.entries(value).filter(([field]) => knownFields.has(field)),
136
+ );
137
+ const shapes = matches.filter((branch) =>
138
+ Value.Check(
139
+ Type.Object(
140
+ Object.fromEntries(
141
+ Object.entries(branch.properties).map(([field, child]) => [
142
+ field,
143
+ IsOptional(child) ||
144
+ matches.every((other) => Object.hasOwn(other.properties, field))
145
+ ? Type.Optional(Type.Unknown())
146
+ : Type.Unknown(),
147
+ ]),
148
+ ),
149
+ ObjectOptions(branch),
150
+ ),
151
+ shapeValue,
152
+ ),
153
+ );
154
+ if (shapes.length === 1) return select(shapes[0]);
155
+ // Branches set apart only by exclusive fields (for example before/after
156
+ // destinations) fail together when none or several are given. Validate their
157
+ // merged shape once and state the choice as one issue, instead of each branch
158
+ // requiring its own field and forbidding the others.
159
+ const alternatives = exclusiveFields(matches);
160
+ if (alternatives) {
161
+ const given = alternatives.filter((field) => Object.hasOwn(value, field));
162
+ if (given.length !== 1)
163
+ projection.derived.push({
164
+ field: path || "$",
165
+ reason: `expected exactly one of: ${alternatives.join(", ")}`,
166
+ });
167
+ const merged = Type.Object(
168
+ Object.fromEntries(
169
+ matches
170
+ .flatMap((branch) => Object.entries(branch.properties))
171
+ .map(([field, child]) => [
172
+ field,
173
+ alternatives.includes(field) ? Type.Optional(child) : child,
174
+ ]),
175
+ ),
176
+ ObjectOptions(matches[0]),
177
+ );
178
+ return select(merged);
179
+ }
180
+ // Otherwise project every applicable branch so semantic checks are retained, then
181
+ // let the native engine select a shape after already-explained constraints are removed.
182
+ const projected = matches.map((branch) => projectSchema(branch, value, path, projection));
183
+ projection.selected.delete(path);
184
+ const accepted = projected.filter((branch) => Value.Check(branch, value));
185
+ return accepted.length === 1 ? accepted[0] : Type.Union(projected);
186
+ }
187
+ const typed = schema.anyOf.filter((branch) => "type" in branch);
188
+ if (typed.length === schema.anyOf.length) {
189
+ const matches = typed.filter(
190
+ (branch) => "type" in branch && Value.Check(Type.Unknown({ type: branch.type }), value),
191
+ );
192
+ if (matches.length === 1) return projectSchema(matches[0], value, path, projection);
193
+ if (matches.length === 0) {
194
+ const types = typed.flatMap((branch) =>
195
+ "type" in branch ? (Array.isArray(branch.type) ? branch.type : [branch.type]) : [],
196
+ );
197
+ return Type.Unknown({ type: [...new Set(types)] });
198
+ }
199
+ }
200
+ return schema;
201
+ }
202
+ if ("type" in schema && !Value.Check(Type.Unknown({ type: schema.type }), value)) return schema;
203
+ projection.applicable.add(path);
204
+ if (projection.explained.has(path)) return Type.Unknown();
205
+ if (IsObject(schema) && typeof value === "object" && value !== null) {
206
+ projection.selected.set(path, { object: schema });
207
+ const properties = Object.fromEntries(
208
+ Object.entries(schema.properties).map(([key, child]) => [
209
+ key,
210
+ projectSchema(child, Reflect.get(value, key), propertyPath(path, key), projection),
211
+ ]),
212
+ );
213
+ return Type.Object(properties, ObjectOptions(schema));
214
+ }
215
+ if (IsArray(schema) && Array.isArray(value)) {
216
+ const items = value.map((item, index) =>
217
+ projectSchema(schema.items, item, `${path}[${index}]`, projection),
218
+ );
219
+ return items.every((item) => item === schema.items)
220
+ ? schema
221
+ : Type.Tuple(items, ArrayOptions(schema));
222
+ }
223
+ return schema;
224
+ }
225
+
226
+ function propertyPath(path: string, key: string): string {
227
+ return /^[A-Za-z_][A-Za-z_0-9]*$/.test(key)
228
+ ? path
229
+ ? `${path}.${key}`
230
+ : key
231
+ : `${path}[${JSON.stringify(key)}]`;
232
+ }
233
+
234
+ const unescapePointer = (part: string) => part.replaceAll("~1", "/").replaceAll("~0", "~");
235
+
236
+ function pointerParts(pointer: string): readonly string[] {
237
+ return pointer.split("/").slice(1).map(unescapePointer);
238
+ }
239
+
240
+ /**
241
+ * The projection path of the value at `pointer`; the root is "". Pi's TypeBox leaves `/` and
242
+ * `~` in property names unescaped, so a name spans the fewest segments that form an own key,
243
+ * read escaped or as is.
244
+ */
245
+ function valuePath(pointer: string, prepared: unknown): string {
246
+ const segments = pointer.split("/").slice(1);
247
+ let value = prepared;
248
+ let path = "";
249
+ for (let index = 0; index < segments.length; index++) {
250
+ let part = unescapePointer(segments[index]);
251
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
252
+ const object = value;
253
+ for (let end = index + 1; end <= segments.length; end++) {
254
+ const raw = segments.slice(index, end).join("/");
255
+ const key = [unescapePointer(raw), raw].find((name) => Object.hasOwn(object, name));
256
+ if (key !== undefined) {
257
+ part = key;
258
+ index = end - 1;
259
+ break;
260
+ }
261
+ }
262
+ }
263
+ path = Array.isArray(value) ? `${path}[${part}]` : propertyPath(path, part);
264
+ value = typeof value === "object" && value !== null ? Reflect.get(value, part) : undefined;
265
+ }
266
+ return path;
267
+ }
268
+
269
+ function fieldPath(pointer: string, prepared: unknown, key?: string): string {
270
+ const path = valuePath(pointer, prepared);
271
+ return (key === undefined ? path : propertyPath(path, key)) || "$";
272
+ }
273
+
274
+ /** One declaration's meaning: its description, labeled with its values when it is a choice. */
275
+ function explainDeclaration(schema: TSchema): string | undefined {
276
+ const description: unknown = Reflect.get(schema, "description");
277
+ const values = literalValues(schema);
278
+ if (values === undefined) return typeof description === "string" ? description : undefined;
279
+ if (typeof description === "string")
280
+ return `${values.map((value) => JSON.stringify(value)).join(" or ")}: ${description}`;
281
+ if (!IsUnion(schema)) return undefined;
282
+ const choices = schema.anyOf.map(explainDeclaration);
283
+ return choices.every((choice) => choice !== undefined) ? choices.join(" ") : undefined;
284
+ }
285
+
286
+ /**
287
+ * What the field at `parts` does, from its declarations in every branch.
288
+ * Choices label each value, so every branch's choices are listed together;
289
+ * other declarations must agree, so one branch's description is never
290
+ * attributed to another. An array item without its own description is
291
+ * explained by its array.
292
+ */
293
+ function fieldExplanation(schema: TSchema, parts: readonly string[]): string | undefined {
294
+ const declarations = new Set<TSchema>();
295
+ const visit = (node: TSchema, depth: number): void => {
296
+ if (depth === parts.length) declarations.add(node);
297
+ else if (IsUnion(node)) for (const branch of node.anyOf) visit(branch, depth);
298
+ else if (IsObject(node)) {
299
+ if (Object.hasOwn(node.properties, parts[depth]))
300
+ visit(node.properties[parts[depth]], depth + 1);
301
+ } else if (IsArray(node))
302
+ visit(
303
+ depth + 1 === parts.length && explainDeclaration(node.items) === undefined
304
+ ? node
305
+ : node.items,
306
+ depth + 1,
307
+ );
308
+ };
309
+ visit(schema, 0);
310
+ if (declarations.size === 0) return undefined;
311
+ const explanations = new Set([...declarations].map(explainDeclaration));
312
+ if (explanations.has(undefined)) return undefined;
313
+ const choices = [...declarations].every(
314
+ (declaration) => literalValues(declaration) !== undefined,
315
+ );
316
+ return choices || explanations.size === 1 ? [...explanations].join(" ") : undefined;
317
+ }
318
+
319
+ /** Why a field is not allowed: the fields the selected shape declares, after the meaning of the tag that chose it. */
320
+ function shapeExplanation({ object, tag }: SelectedShape): string {
321
+ const fields = `Accepted fields: ${Object.keys(object.properties).join(", ")}.`;
322
+ const choice = tag === undefined ? undefined : explainDeclaration(object.properties[tag]);
323
+ return choice === undefined ? fields : `${choice} ${fields}`;
324
+ }
325
+
326
+ /** One issue per field: distinct reasons joined, and distinct fixes joined, each in report order. */
327
+ function combineIssues(issues: readonly ArgumentIssue[]): readonly ArgumentIssue[] {
328
+ const fields = new Map<string, { reasons: Set<string>; fixes: Set<string> }>();
329
+ for (const { field, reason, fix } of issues) {
330
+ const existing = fields.get(field) ?? { reasons: new Set<string>(), fixes: new Set<string>() };
331
+ existing.reasons.add(reason);
332
+ if (fix !== undefined) existing.fixes.add(fix);
333
+ fields.set(field, existing);
334
+ }
335
+ return [...fields].map(([field, { reasons, fixes }]) => ({
336
+ field,
337
+ reason: [...reasons].join("; "),
338
+ ...(fixes.size ? { fix: [...fixes].join(" ") } : {}),
339
+ }));
340
+ }
341
+
342
+ /**
343
+ * One issue per native error. Reasons that do not say how to correct the value
344
+ * carry a fix derived from the declared schema: a missing field and a pattern
345
+ * mismatch explain the field, and a field that is not allowed explains its
346
+ * selected shape.
347
+ */
348
+ function aggregateErrors(
349
+ errors: readonly TLocalizedValidationError[],
350
+ parameters: TObject,
351
+ prepared: unknown,
352
+ selected: ReadonlyMap<string, SelectedShape>,
353
+ ): readonly ArgumentIssue[] {
354
+ const issues: ArgumentIssue[] = [];
355
+ const add = (field: string, reason: string, fix?: string) =>
356
+ issues.push(fix === undefined ? { field, reason } : { field, reason, fix });
357
+ for (const error of errors) {
358
+ if (
359
+ error.keyword === "anyOf" &&
360
+ errors.some(
361
+ (child) =>
362
+ child !== error &&
363
+ child.keyword !== "anyOf" &&
364
+ (child.instancePath === error.instancePath ||
365
+ child.instancePath.startsWith(`${error.instancePath}/`)),
366
+ )
367
+ )
368
+ continue;
369
+ switch (error.keyword) {
370
+ case "required": {
371
+ const parts = pointerParts(error.instancePath);
372
+ for (const key of error.params.requiredProperties)
373
+ add(
374
+ fieldPath(error.instancePath, prepared, key),
375
+ "is required",
376
+ fieldExplanation(parameters, [...parts, key]),
377
+ );
378
+ break;
379
+ }
380
+ case "additionalProperties": {
381
+ const shape = selected.get(valuePath(error.instancePath, prepared));
382
+ const fix = shape && shapeExplanation(shape);
383
+ for (const key of error.params.additionalProperties)
384
+ add(fieldPath(error.instancePath, prepared, key), "is not allowed", fix);
385
+ break;
386
+ }
387
+ case "pattern":
388
+ add(
389
+ fieldPath(error.instancePath, prepared),
390
+ error.message,
391
+ fieldExplanation(parameters, pointerParts(error.instancePath)),
392
+ );
393
+ break;
394
+ case "boolean":
395
+ add(fieldPath(error.instancePath, prepared), "is not allowed");
396
+ break;
397
+ case "enum":
398
+ add(
399
+ fieldPath(error.instancePath, prepared),
400
+ `expected one of: ${error.params.allowedValues.map((value) => JSON.stringify(value)).join(", ")}`,
401
+ );
402
+ break;
403
+ default:
404
+ add(fieldPath(error.instancePath, prepared), error.message);
405
+ }
406
+ }
407
+ return combineIssues(issues);
408
+ }
409
+
410
+ /** Detect native capacity through a terminal error, without importing unbundled TypeBox settings. */
411
+ function boundedErrors(
412
+ schema: TSchema,
413
+ value: unknown,
414
+ ): {
415
+ readonly errors: readonly TLocalizedValidationError[];
416
+ readonly limited: boolean;
417
+ } {
418
+ const terminalPath = "#/allOf/1";
419
+ const errors = Value.Errors(Type.Unknown({ allOf: [schema, Type.Never()] }), value);
420
+ const terminal = (error: TLocalizedValidationError) =>
421
+ error.schemaPath === terminalPath || error.schemaPath.startsWith(`${terminalPath}/`);
422
+ return { errors: errors.filter((error) => !terminal(error)), limited: !errors.some(terminal) };
423
+ }
424
+
425
+ /** Diagnose prepared values without repeating Pi's coercion or optional-null rules. */
426
+ export function diagnoseArguments(
427
+ parameters: TObject,
428
+ prepared: unknown,
429
+ semanticIssues: readonly ArgumentIssue[],
430
+ schemaFailed: boolean,
431
+ ): ArgumentDiagnostics {
432
+ const projection: Projection = {
433
+ explained: new Set(semanticIssues.map((issue) => issue.field)),
434
+ applicable: new Set<string>(),
435
+ derived: [],
436
+ selected: new Map(),
437
+ };
438
+ const projected = projectSchema(parameters, prepared, "", projection);
439
+ const retained = combineIssues(
440
+ semanticIssues.filter((issue) => projection.applicable.has(issue.field)),
441
+ );
442
+ if (!schemaFailed) return { issues: retained, limited: false };
443
+ const batches =
444
+ IsObject(projected) &&
445
+ typeof prepared === "object" &&
446
+ prepared !== null &&
447
+ !Array.isArray(prepared)
448
+ ? Object.keys(parameters.properties)
449
+ .map((field) =>
450
+ boundedErrors(
451
+ Type.Pick(projected, [field], { additionalProperties: false }),
452
+ Object.fromEntries(Object.entries(prepared).filter(([key]) => key === field)),
453
+ ),
454
+ )
455
+ .concat([
456
+ boundedErrors(
457
+ Type.Omit(projected, Object.keys(parameters.properties), {
458
+ additionalProperties: false,
459
+ }),
460
+ Object.fromEntries(
461
+ Object.entries(prepared).filter(
462
+ ([key]) => !Object.hasOwn(parameters.properties, key),
463
+ ),
464
+ ),
465
+ ),
466
+ ])
467
+ : [boundedErrors(projected, prepared)];
468
+ return {
469
+ issues: combineIssues([
470
+ ...retained,
471
+ ...projection.derived,
472
+ ...batches.flatMap((batch) =>
473
+ aggregateErrors(batch.errors, parameters, prepared, projection.selected),
474
+ ),
475
+ ]),
476
+ limited: batches.some((batch) => batch.limited),
477
+ };
478
+ }
@@ -0,0 +1,46 @@
1
+ import assert from "node:assert/strict";
2
+ import type { ArgumentIssue, Report } from "./report-schema.ts";
3
+
4
+ type ArgumentRejection = Omit<Report, "tool" | "path"> & {
5
+ error: "INVALID_ARGUMENTS";
6
+ issues: ArgumentIssue[];
7
+ };
8
+
9
+ /** Assert the model-facing JSON contract before inspecting an individual rejection. */
10
+ export function argumentError(error: unknown): ArgumentRejection {
11
+ assert.ok(error instanceof Error);
12
+ const value: unknown = JSON.parse(error.message);
13
+ assert.ok(typeof value === "object" && value !== null);
14
+ assert.equal(Reflect.get(value, "error"), "INVALID_ARGUMENTS");
15
+ assert.equal(Object.hasOwn(value, "tool"), false);
16
+ assert.equal(Object.hasOwn(value, "path"), false);
17
+ const issues: unknown = Reflect.get(value, "issues");
18
+ assert.ok(Array.isArray(issues));
19
+ for (const issue of issues) {
20
+ assert.ok(typeof issue === "object" && issue !== null);
21
+ assert.equal(typeof Reflect.get(issue, "field"), "string");
22
+ assert.equal(typeof Reflect.get(issue, "reason"), "string");
23
+ }
24
+ // The assertions above establish the output boundary's required fields.
25
+ return value as ArgumentRejection;
26
+ }
27
+
28
+ /** Match a precise field and caller-relevant reason, independent of JSON layout. */
29
+ export function rejectsArgument(field: string, reason: RegExp = /./) {
30
+ return (error: unknown): boolean => {
31
+ const result = argumentError(error);
32
+ assert.ok(
33
+ result.issues.some((issue) => issue.field === field && reason.test(issue.reason)),
34
+ JSON.stringify(result),
35
+ );
36
+ return true;
37
+ };
38
+ }
39
+
40
+ export function rejectsArguments() {
41
+ return (error: unknown): boolean => {
42
+ const result = argumentError(error);
43
+ assert.ok(result.issues.length > 0);
44
+ return true;
45
+ };
46
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Model-facing argument rejection: an `INVALID_ARGUMENTS` report (report.ts)
3
+ * with field issues within one byte budget. Pi raises it before execution,
4
+ * so it travels as the thrown message only. Oversized issues are omitted whole.
5
+ */
6
+ import type { OutputBudgets } from "./budgets.ts";
7
+ import { boundedText, renderReport, type ReportText } from "./report.ts";
8
+ import type { ArgumentIssue, FailureReport } from "./report-schema.ts";
9
+
10
+ type ArgumentRejection = ReportText<Extract<FailureReport, { error: "INVALID_ARGUMENTS" }>>;
11
+
12
+ /**
13
+ * State each distinct fix once, on the first reported issue that needs it:
14
+ * later issues with the same fix state only their reason.
15
+ */
16
+ function fixesOnce(issues: readonly ArgumentIssue[]): ArgumentIssue[] {
17
+ const fixes = new Set<string>();
18
+ return issues.map(({ field, reason, fix }) => {
19
+ const repeated = fix === undefined || fixes.has(fix);
20
+ if (fix !== undefined) fixes.add(fix);
21
+ return repeated ? { field, reason } : { field, reason, fix };
22
+ });
23
+ }
24
+
25
+ /** One rejection as text; issues are deduplicated after any omission so no kept issue loses its fix. */
26
+ function encode(report: ArgumentRejection): string {
27
+ return renderReport({ ...report, issues: fixesOnce(report.issues) });
28
+ }
29
+
30
+ /** Encode actionable field diagnostics without repeating the call's arguments. */
31
+ export function formatArgumentError(
32
+ issues: readonly ArgumentIssue[],
33
+ schemaLimited: boolean,
34
+ budget: OutputBudgets,
35
+ ): string {
36
+ const boundedIssues = issues.map(({ field, reason, fix }) => ({
37
+ field,
38
+ reason: boundedText(reason, budget.fieldBytes),
39
+ ...(fix === undefined ? {} : { fix: boundedText(fix, budget.fieldBytes) }),
40
+ }));
41
+ const base = {
42
+ error: "INVALID_ARGUMENTS" as const,
43
+ ...(schemaLimited ? { schemaLimited: true as const } : {}),
44
+ };
45
+ const fits = (text: string) => Buffer.byteLength(text) <= budget.blockBytes;
46
+ const complete = encode({ ...base, issues: boundedIssues });
47
+ if (fits(complete)) return complete;
48
+
49
+ // An oversized field path must be omitted whole: a shortened path could name another field.
50
+ const eligible = boundedIssues.filter((issue) =>
51
+ fits(
52
+ encode({
53
+ ...base,
54
+ issues: [issue],
55
+ omittedIssues: boundedIssues.length - 1 || undefined,
56
+ }),
57
+ ),
58
+ );
59
+ const frame = (count: number) => {
60
+ const head = Math.ceil(count / 2);
61
+ const tail = count - head;
62
+ return encode({
63
+ ...base,
64
+ issues: [...eligible.slice(0, head), ...(tail ? eligible.slice(-tail) : [])],
65
+ omittedIssues: boundedIssues.length - count || undefined,
66
+ });
67
+ };
68
+ let low = 0;
69
+ let high = eligible.length;
70
+ while (low < high) {
71
+ const middle = Math.ceil((low + high) / 2);
72
+ if (fits(frame(middle))) low = middle;
73
+ else high = middle - 1;
74
+ }
75
+ return frame(low);
76
+ }