@criogaid/pi-hashline-edit 0.8.0 → 0.9.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.
@@ -11,7 +11,6 @@ import {
11
11
  type TLiteralValue,
12
12
  type TObject,
13
13
  type TSchema,
14
- type TUnion,
15
14
  } from "typebox";
16
15
  import type { TLocalizedValidationError } from "typebox/error";
17
16
  import { Value } from "typebox/value";
@@ -22,22 +21,14 @@ interface ArgumentDiagnostics {
22
21
  readonly limited: boolean;
23
22
  }
24
23
 
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
24
  /** State shared by one failure projection. */
32
25
  interface Projection {
33
- /** Fields a tool check already explained; their schema constraints are dropped. */
26
+ /** Fields a tool check already explained; their schema constraints are dropped, except an object's fields'. */
34
27
  readonly explained: ReadonlySet<string>;
35
- /** Fields that belong to the selected shapes. */
28
+ /** Fields that belong to the projected shapes; a declared field belongs even when absent. */
36
29
  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>;
30
+ /** Each object path's declared shape. */
31
+ readonly objects: Map<string, TObject>;
41
32
  }
42
33
 
43
34
  function literalValues(schema: TSchema): readonly TLiteralValue[] | undefined {
@@ -48,48 +39,6 @@ function literalValues(schema: TSchema): readonly TLiteralValue[] | undefined {
48
39
  return choices.length === values.length ? choices.flat() : undefined;
49
40
  }
50
41
 
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
42
  function projectSchema(
94
43
  schema: TSchema,
95
44
  value: unknown,
@@ -112,78 +61,6 @@ function projectValueSchema(
112
61
  projection.applicable.add(path);
113
62
  return Type.Unknown({ enum: [...new Set(choices)] });
114
63
  }
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
64
  const typed = schema.anyOf.filter((branch) => "type" in branch);
188
65
  if (typed.length === schema.anyOf.length) {
189
66
  const matches = typed.filter(
@@ -201,17 +78,21 @@ function projectValueSchema(
201
78
  }
202
79
  if ("type" in schema && !Value.Check(Type.Unknown({ type: schema.type }), value)) return schema;
203
80
  projection.applicable.add(path);
204
- if (projection.explained.has(path)) return Type.Unknown();
81
+ // An issue on a whole object, such as a choice between its fields, explains
82
+ // none of the object's own constraints; its fields keep their diagnostics.
205
83
  if (IsObject(schema) && typeof value === "object" && value !== null) {
206
- projection.selected.set(path, { object: schema });
84
+ projection.objects.set(path, schema);
207
85
  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
- ]),
86
+ Object.entries(schema.properties).map(([key, child]) => {
87
+ const field = propertyPath(path, key);
88
+ // A tool check may require a field the schema leaves optional.
89
+ if (!Object.hasOwn(value, key)) projection.applicable.add(field);
90
+ return [key, projectSchema(child, Reflect.get(value, key), field, projection)];
91
+ }),
212
92
  );
213
93
  return Type.Object(properties, ObjectOptions(schema));
214
94
  }
95
+ if (projection.explained.has(path)) return Type.Unknown();
215
96
  if (IsArray(schema) && Array.isArray(value)) {
216
97
  const items = value.map((item, index) =>
217
98
  projectSchema(schema.items, item, `${path}[${index}]`, projection),
@@ -284,43 +165,24 @@ function explainDeclaration(schema: TSchema): string | undefined {
284
165
  }
285
166
 
286
167
  /**
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.
168
+ * What the field at `parts` does, from its declaration. An array item without
169
+ * its own description is explained by its array.
292
170
  */
293
171
  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;
172
+ if (parts.length === 0) return explainDeclaration(schema);
173
+ const [part, ...rest] = parts;
174
+ if (IsObject(schema))
175
+ return Object.hasOwn(schema.properties, part)
176
+ ? fieldExplanation(schema.properties[part], rest)
177
+ : undefined;
178
+ if (!IsArray(schema)) return undefined;
179
+ const item = fieldExplanation(schema.items, rest);
180
+ return item ?? (rest.length === 0 ? explainDeclaration(schema) : undefined);
317
181
  }
318
182
 
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}`;
183
+ /** Why a field is not allowed: the fields its object declares. */
184
+ function shapeExplanation(object: TObject): string {
185
+ return `Accepted fields: ${Object.keys(object.properties).join(", ")}.`;
324
186
  }
325
187
 
326
188
  /** One issue per field: distinct reasons joined, and distinct fixes joined, each in report order. */
@@ -342,30 +204,19 @@ function combineIssues(issues: readonly ArgumentIssue[]): readonly ArgumentIssue
342
204
  /**
343
205
  * One issue per native error. Reasons that do not say how to correct the value
344
206
  * 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.
207
+ * mismatch explain the field, and a field that is not allowed lists its
208
+ * object's declared fields.
347
209
  */
348
210
  function aggregateErrors(
349
211
  errors: readonly TLocalizedValidationError[],
350
212
  parameters: TObject,
351
213
  prepared: unknown,
352
- selected: ReadonlyMap<string, SelectedShape>,
214
+ objects: ReadonlyMap<string, TObject>,
353
215
  ): readonly ArgumentIssue[] {
354
216
  const issues: ArgumentIssue[] = [];
355
217
  const add = (field: string, reason: string, fix?: string) =>
356
218
  issues.push(fix === undefined ? { field, reason } : { field, reason, fix });
357
219
  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
220
  switch (error.keyword) {
370
221
  case "required": {
371
222
  const parts = pointerParts(error.instancePath);
@@ -378,7 +229,7 @@ function aggregateErrors(
378
229
  break;
379
230
  }
380
231
  case "additionalProperties": {
381
- const shape = selected.get(valuePath(error.instancePath, prepared));
232
+ const shape = objects.get(valuePath(error.instancePath, prepared));
382
233
  const fix = shape && shapeExplanation(shape);
383
234
  for (const key of error.params.additionalProperties)
384
235
  add(fieldPath(error.instancePath, prepared, key), "is not allowed", fix);
@@ -432,8 +283,7 @@ export function diagnoseArguments(
432
283
  const projection: Projection = {
433
284
  explained: new Set(semanticIssues.map((issue) => issue.field)),
434
285
  applicable: new Set<string>(),
435
- derived: [],
436
- selected: new Map(),
286
+ objects: new Map(),
437
287
  };
438
288
  const projected = projectSchema(parameters, prepared, "", projection);
439
289
  const retained = combineIssues(
@@ -468,9 +318,8 @@ export function diagnoseArguments(
468
318
  return {
469
319
  issues: combineIssues([
470
320
  ...retained,
471
- ...projection.derived,
472
321
  ...batches.flatMap((batch) =>
473
- aggregateErrors(batch.errors, parameters, prepared, projection.selected),
322
+ aggregateErrors(batch.errors, parameters, prepared, projection.objects),
474
323
  ),
475
324
  ]),
476
325
  limited: batches.some((batch) => batch.limited),
@@ -6,7 +6,7 @@ import { makeGrepOverride } from "./grep-tool.ts";
6
6
  import { makeWriteOverride } from "./write-tool.ts";
7
7
  import { makeReplaceTool } from "./replace-tool.ts";
8
8
  import { DEFAULT_CONFIG } from "./config.ts";
9
- import { DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
9
+ import { DEFAULT_OUTPUT_BUDGETS, outputBudgetsFor } from "./budgets.ts";
10
10
  import { callTool } from "./tool-call.testing.ts";
11
11
  import { argumentError } from "./argument-error.testing.ts";
12
12
 
@@ -16,7 +16,7 @@ test("all tools receive invalid arguments → return field diagnostics without a
16
16
  const cases = [
17
17
  {
18
18
  tool: makeEditOverride(cwd, DEFAULT_CONFIG),
19
- args: { path: "unused", edits: [{ op: "append", body: [] }] },
19
+ args: { path: "unused", edits: [{ action: "append", body: [] }] },
20
20
  },
21
21
  { tool: makeReadOverride(cwd, DEFAULT_CONFIG), args: { path: "unused", limit: 0 } },
22
22
  { tool: makeGrepOverride(cwd, DEFAULT_CONFIG), args: { pattern: "", literal: true } },
@@ -53,12 +53,12 @@ test("all tools receive invalid arguments → return field diagnostics without a
53
53
  test("Pi prepares a singleton operation → semantic and schema paths resolve to the prepared array", async () => {
54
54
  const tool = makeEditOverride(cwd, DEFAULT_CONFIG);
55
55
  await assert.rejects(
56
- callTool(tool, { path: "unused", edits: { op: "insert_after", body: [] } }),
56
+ callTool(tool, { path: "unused", edits: { action: "insert_after", body: [] } }),
57
57
  (error: unknown) => {
58
58
  const result = argumentError(error);
59
59
  assert.deepEqual(
60
60
  result.issues.map((issue) => issue.field),
61
- ["edits[0].body", "edits[0].anchor"],
61
+ ["edits[0].anchor", "edits[0].body"],
62
62
  );
63
63
  return true;
64
64
  },
@@ -78,25 +78,23 @@ test("Pi prepares a singleton operation → semantic and schema paths resolve to
78
78
  });
79
79
 
80
80
  test("JSON diagnostics exceed the budget → retain whole opening and closing issues and label omissions", async () => {
81
- const edits = Array.from({ length: DEFAULT_OUTPUT_BUDGETS.blockBytes }, () => ({
82
- op: "append",
81
+ const budget = outputBudgetsFor(4096);
82
+ const tool = makeEditOverride(cwd, DEFAULT_CONFIG, undefined, () => budget);
83
+ const maxItems: unknown = Reflect.get(tool.parameters.properties.edits, "maxItems");
84
+ assert.ok(typeof maxItems === "number");
85
+ const edits = Array.from({ length: maxItems }, () => ({
86
+ action: "append",
83
87
  body: [],
84
88
  }));
85
- await assert.rejects(
86
- callTool(makeEditOverride(cwd, DEFAULT_CONFIG), { path: "", edits }),
87
- (error: unknown) => {
88
- const result = argumentError(error);
89
- assert.ok(
90
- error instanceof Error &&
91
- Buffer.byteLength(error.message) <= DEFAULT_OUTPUT_BUDGETS.blockBytes,
92
- );
93
- assert.equal(result.issues[0].field, "edits[0].body");
94
- assert.equal(result.issues.at(-1)?.field, "path");
95
- assert.ok((result.omittedIssues ?? 0) > 0);
96
- assert.equal(result.issues.length + (result.omittedIssues ?? 0), edits.length + 1);
97
- return true;
98
- },
99
- );
89
+ await assert.rejects(callTool(tool, { path: "", edits }), (error: unknown) => {
90
+ const result = argumentError(error);
91
+ assert.ok(error instanceof Error && Buffer.byteLength(error.message) <= budget.blockBytes);
92
+ assert.equal(result.issues[0].field, "edits[0].body");
93
+ assert.equal(result.issues.at(-1)?.field, "path");
94
+ assert.ok((result.omittedIssues ?? 0) > 0);
95
+ assert.equal(result.issues.length + (result.omittedIssues ?? 0), edits.length + 1);
96
+ return true;
97
+ });
100
98
  });
101
99
 
102
100
  test("a reason contains an oversized anchor → keep its cause and recovery instruction inside valid JSON", async () => {
@@ -104,7 +102,7 @@ test("a reason contains an oversized anchor → keep its cause and recovery inst
104
102
  await assert.rejects(
105
103
  callTool(makeEditOverride(cwd, DEFAULT_CONFIG), {
106
104
  path: "unused",
107
- edits: [{ op: "delete", anchor }],
105
+ edits: [{ action: "delete", anchor }],
108
106
  }),
109
107
  (error: unknown) => {
110
108
  const result = argumentError(error);