@criogaid/pi-hashline-edit 0.7.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.
Files changed (118) hide show
  1. package/README.md +76 -220
  2. package/README.zh-CN.md +166 -0
  3. package/package.json +2 -1
  4. package/src/core/AGENTS.md +1 -1
  5. package/src/core/apply.test.ts +171 -133
  6. package/src/core/apply.ts +34 -31
  7. package/src/core/case-fold.test.ts +11 -7
  8. package/src/core/case-fold.ts +2 -6
  9. package/src/core/character-set.ts +14 -0
  10. package/src/core/hash.test.ts +1 -25
  11. package/src/core/hash.ts +0 -5
  12. package/src/core/lines.ts +25 -7
  13. package/src/core/ranges.test.ts +49 -9
  14. package/src/core/ranges.ts +15 -4
  15. package/src/core/regex.ts +36 -6
  16. package/src/core/replace-schema.ts +18 -11
  17. package/src/core/replace.test.ts +90 -0
  18. package/src/core/replace.ts +6 -5
  19. package/src/core/search-analysis.test.ts +9 -0
  20. package/src/core/search-analysis.ts +35 -31
  21. package/src/core/search.ts +1 -1
  22. package/src/core/types.ts +6 -8
  23. package/src/index.ts +2 -4
  24. package/src/integration/config-registration.test.ts +18 -10
  25. package/src/integration/fusion-dispatch.test.ts +41 -22
  26. package/src/integration/grep-flags.test.ts +6 -13
  27. package/src/integration/grep-js-completeness.test.ts +41 -31
  28. package/src/integration/grep-order.test.ts +78 -0
  29. package/src/integration/grep-path-matrix.test.ts +4 -3
  30. package/src/integration/grep-regex.test.ts +13 -16
  31. package/src/integration/grep-rg.test.ts +132 -92
  32. package/src/integration/grep-scan-budget.test.ts +27 -5
  33. package/src/integration/large-text.test.ts +4 -5
  34. package/src/integration/model-budget-lifecycle.test.ts +26 -8
  35. package/src/integration/mutation-file-types.test.ts +0 -1
  36. package/src/integration/mutation-file-types.testing.ts +2 -2
  37. package/src/integration/npm-package.testing.ts +7 -33
  38. package/src/integration/publication-read-changes.test.ts +60 -28
  39. package/src/integration/replace-package.testing.ts +4 -1
  40. package/src/integration/replace-worker-boundary.test.ts +34 -24
  41. package/src/integration/report-replay.test.ts +3 -3
  42. package/src/integration/utf8-errors.test.ts +3 -3
  43. package/src/pi/AGENTS.md +13 -14
  44. package/src/pi/action-fusion.test.ts +75 -220
  45. package/src/pi/action-fusion.ts +37 -74
  46. package/src/pi/anchor-format.test.ts +16 -0
  47. package/src/pi/anchor-format.ts +7 -3
  48. package/src/pi/argument-diagnostics.ts +35 -186
  49. package/src/pi/argument-error.testing.ts +7 -4
  50. package/src/pi/argument-error.ts +5 -7
  51. package/src/pi/argument-format.test.ts +25 -38
  52. package/src/pi/argument-validation.test.ts +446 -420
  53. package/src/pi/argument-validation.ts +4 -5
  54. package/src/pi/budgets.ts +5 -7
  55. package/src/pi/config.test.ts +15 -5
  56. package/src/pi/config.ts +6 -6
  57. package/src/pi/diagnostic-buffer.test.ts +2 -3
  58. package/src/pi/diagnostic-buffer.ts +2 -2
  59. package/src/pi/edit-tool.ts +175 -121
  60. package/src/pi/execute.test.ts +170 -227
  61. package/src/pi/failure-context.test.ts +61 -16
  62. package/src/pi/failure-context.ts +13 -10
  63. package/src/pi/failure-path.test.ts +115 -50
  64. package/src/pi/file-commit.test.ts +30 -46
  65. package/src/pi/file-commit.ts +11 -40
  66. package/src/pi/file-revision.ts +25 -0
  67. package/src/pi/fusion-card-interaction.test.ts +143 -0
  68. package/src/pi/fusion-card.test.ts +193 -37
  69. package/src/pi/fusion-card.ts +186 -116
  70. package/src/pi/grep-candidates.ts +25 -27
  71. package/src/pi/grep-matrix.test.ts +1 -1
  72. package/src/pi/grep-order.test.ts +323 -0
  73. package/src/pi/grep-output.testing.ts +24 -0
  74. package/src/pi/grep-output.ts +62 -69
  75. package/src/pi/grep-render.ts +4 -1
  76. package/src/pi/grep-scope.ts +1 -1
  77. package/src/pi/grep-search.ts +85 -56
  78. package/src/pi/grep-tool.ts +17 -48
  79. package/src/pi/grep.test.ts +271 -170
  80. package/src/pi/mutation-outcome.testing.ts +2 -3
  81. package/src/pi/mutation-result.test.ts +26 -19
  82. package/src/pi/mutation-result.ts +25 -40
  83. package/src/pi/mutation-runner.ts +9 -17
  84. package/src/pi/output-budgets.test.ts +27 -18
  85. package/src/pi/path.ts +3 -1
  86. package/src/pi/pi.test.ts +7 -6
  87. package/src/pi/read-tool.ts +32 -80
  88. package/src/pi/read.test.ts +145 -92
  89. package/src/pi/regex-worker-contract.ts +5 -23
  90. package/src/pi/regex-worker.ts +4 -10
  91. package/src/pi/registration.test.ts +106 -67
  92. package/src/pi/render.test.ts +239 -109
  93. package/src/pi/render.ts +42 -22
  94. package/src/pi/replace-regex.ts +3 -5
  95. package/src/pi/replace-tool.ts +29 -27
  96. package/src/pi/replace-worker-contract.ts +3 -12
  97. package/src/pi/replace.test.ts +144 -226
  98. package/src/pi/report-cause.ts +23 -19
  99. package/src/pi/report-failure.testing.ts +2 -2
  100. package/src/pi/report-schema.ts +60 -45
  101. package/src/pi/report.test.ts +138 -71
  102. package/src/pi/report.ts +40 -43
  103. package/src/pi/result-safety.test.ts +186 -131
  104. package/src/pi/rg-process.test.ts +36 -10
  105. package/src/pi/rg-process.ts +9 -3
  106. package/src/pi/rg-regex.test.ts +17 -0
  107. package/src/pi/rg-regex.ts +28 -22
  108. package/src/pi/text-stream.test.ts +35 -36
  109. package/src/pi/text-stream.ts +14 -14
  110. package/src/pi/tool-call.testing.ts +17 -7
  111. package/src/pi/write-tool.ts +9 -11
  112. package/src/pi/write.test.ts +43 -75
  113. package/src/testing/regex-translation-corpus.ts +16 -0
  114. package/src/testing/rg-line-listing.fixture.mjs +1 -1
  115. package/src/integration/forget-grep.test.ts +0 -148
  116. package/src/pi/forget-tool.ts +0 -367
  117. package/src/pi/forget.test.ts +0 -630
  118. package/src/pi/forget.testing.ts +0 -201
@@ -26,13 +26,9 @@ import { basename, dirname, resolve } from "node:path";
26
26
  import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
27
27
  import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
28
28
  import { Type, type Static, type TObject, type TProperties } from "typebox";
29
+ import { commitFreshness, observeFreshness, type FreshnessObservation } from "./file-commit.ts";
29
30
  import {
30
- commitFreshness,
31
- FileMutationError,
32
- observeFreshness,
33
- type FreshnessObservation,
34
- } from "./file-commit.ts";
35
- import {
31
+ commandText,
36
32
  finalizeMutation,
37
33
  type CommandFacts,
38
34
  type MutationOutcome,
@@ -41,13 +37,13 @@ import {
41
37
  import { errnoCode, errorMessage } from "../core/errors.ts";
42
38
  import { throwIfCancelled } from "./error-text.ts";
43
39
  import { causeOf, CommandNotRun, type ReportDetails } from "./report.ts";
44
- import { DEFAULT_OUTPUT_BUDGETS, type OutputBudgets } from "./budgets.ts";
40
+ import type { OutputBudgets } from "./budgets.ts";
45
41
  import type {
46
42
  ActionFusionProgress,
43
+ CommandResult,
47
44
  CommandStatus,
48
45
  Freshness,
49
46
  MutationToolName,
50
- PublicationStatus,
51
47
  SuccessReport,
52
48
  } from "./report-schema.ts";
53
49
  export type { ActionFusionProgress } from "./report-schema.ts";
@@ -64,22 +60,12 @@ const COMMAND_DESCRIPTION =
64
60
  : "Bash command to run.";
65
61
 
66
62
  export const ACTION_FUSION_GUIDELINES = [
67
- "Before each file mutation, identify its next command.",
68
- "then_run is a parameter of edit, replace, and write, not a separate tool.",
69
- "Check the command outcome before claiming validation passed.",
63
+ "When a check covers several changes, run it once after all of those changes.",
70
64
  ];
71
65
 
72
- export interface ActionFusionDetails {
73
- readonly publication: PublicationStatus;
74
- readonly command: CommandStatus | "not_requested";
75
- readonly freshness: Freshness;
76
- }
77
-
78
66
  type ProgressReporter = (progress: ActionFusionProgress, ctx: ExtensionToolContext) => void;
79
67
 
80
- /** The tools that accept then_run. */
81
-
82
- export function createThenRunSchema(tool: MutationToolName) {
68
+ function createThenRunSchema(tool: MutationToolName) {
83
69
  return Type.Optional(
84
70
  Type.Object(
85
71
  {
@@ -88,7 +74,7 @@ export function createThenRunSchema(tool: MutationToolName) {
88
74
  Type.Number({
89
75
  exclusiveMinimum: 0,
90
76
  maximum: MAX_BASH_TIMEOUT_SECONDS,
91
- description: "Timeout in seconds (optional, no default timeout)",
77
+ description: "Timeout in seconds; none when omitted.",
92
78
  }),
93
79
  ),
94
80
  },
@@ -117,14 +103,14 @@ export type ThenRunInput = NonNullable<Static<ReturnType<typeof createThenRunSch
117
103
  /** Name then_run in a mutation tool's description when Action Fusion is enabled. */
118
104
  export function withThenRunDescription(description: string, actionFusion: boolean): string {
119
105
  return actionFusion
120
- ? `${description} If a command such as tests, a typecheck, or a build should run right after this change, set then_run instead of calling bash separately, unless the command needs the user's approval, depends on this call's result, must wait for a reload, or checks several changes sent in the same response; run that check once with bash after them.`
106
+ ? `${description} Set the then_run parameter for checks that can run immediately after this change. Use a separate bash call when the command requires approval, needs information from this tool's result, must wait for reload, or checks several changes from one response.`
121
107
  : description;
122
108
  }
123
109
 
124
110
  /** Keep command state independent of its diagnostic text and of file publication. */
125
111
  export interface CommandOutcome {
126
112
  readonly status: Exclude<CommandStatus, "skipped">;
127
- readonly output: string;
113
+ readonly result: CommandResult;
128
114
  /** Preserve the session tool's request to stop after this tool batch. */
129
115
  readonly terminate?: boolean;
130
116
  }
@@ -137,11 +123,6 @@ type CommandRunner = (
137
123
  onUpdate?: AgentToolUpdateCallback<unknown>,
138
124
  ) => Promise<CommandOutcome>;
139
125
 
140
- /** Publication of a mutation failure, for progress reports; the failure report states it to the model. */
141
- function publicationOf(error: unknown): PublicationStatus {
142
- return error instanceof FileMutationError ? error.publication : "NOT_PUBLISHED";
143
- }
144
-
145
126
  async function defaultCommandRunner(
146
127
  _toolCallId: string,
147
128
  input: ThenRunInput,
@@ -152,11 +133,10 @@ async function defaultCommandRunner(
152
133
  // Use the session's callable Bash, including overrides, validation, permission
153
134
  // hooks and tool_result hooks. Tool failures resolve with isError, not rejection.
154
135
  const { result, isError } = await ctx.executeTool("bash", input, { signal, onUpdate });
155
- const output = result.content
156
- .filter((block) => block.type === "text")
157
- .map((block) => block.text)
158
- .join("\n");
159
- const command = { output, terminate: result.terminate };
136
+ const command = {
137
+ terminate: result.terminate,
138
+ result: { content: result.content, details: result.details },
139
+ };
160
140
  if (!isError) return { status: "succeeded", ...command };
161
141
  if (signal?.aborted) return { status: "cancelled", ...command };
162
142
 
@@ -170,6 +150,7 @@ async function defaultCommandRunner(
170
150
  // timeout as text. Only recognize its final diagnostic for the requested
171
151
  // timeout; a failed command's output may itself mention or quote a timeout.
172
152
  const timeoutDiagnostic = `Command timed out after ${input.timeout} seconds`;
153
+ const output = commandText(result.content);
173
154
  const timedOut =
174
155
  !hasExitCode &&
175
156
  input.timeout !== undefined &&
@@ -227,7 +208,7 @@ export function createActionFusionExecutor(
227
208
  displayPath,
228
209
  absolutePath,
229
210
  thenRun,
230
- budget = DEFAULT_OUTPUT_BUDGETS,
211
+ budget,
231
212
  mutate,
232
213
  signal,
233
214
  ctx,
@@ -239,32 +220,24 @@ export function createActionFusionExecutor(
239
220
  displayPath: string;
240
221
  absolutePath: string;
241
222
  thenRun: ThenRunInput | undefined;
242
- budget?: OutputBudgets;
223
+ budget: OutputBudgets;
243
224
  mutate: () => Promise<MutationOutcome<TDetails, NoInfer<TTool>>>;
244
225
  signal: AbortSignal | undefined;
245
226
  ctx: ExtensionToolContext;
246
227
  onUpdate?: AgentToolUpdateCallback<MutationResultDetails<TDetails>>;
247
- }): Promise<
248
- AgentToolResult<TDetails & ReportDetails<SuccessReport> & { actionFusion: ActionFusionDetails }>
249
- > {
228
+ }): Promise<AgentToolResult<TDetails & ReportDetails<SuccessReport>>> {
250
229
  let completedMutation: MutationOutcome<TDetails, TTool> | undefined;
251
230
  let progressFailure: unknown;
231
+ let commandResult: CommandResult | undefined;
252
232
  let commandTiming: { readonly timeoutSeconds: number; readonly deadlineMs: number } | undefined;
253
- const report = (
254
- command: ActionFusionProgress["command"],
255
- publication: PublicationStatus,
256
- freshness: Freshness,
257
- output = "",
258
- ) => {
233
+ const report = (command: ActionFusionProgress["command"], freshness: Freshness) => {
259
234
  if (!thenRun) return;
260
235
  const progress: ActionFusionProgress = {
261
236
  toolCallId,
262
- path: absolutePath,
263
237
  commandText: thenRun.command,
264
238
  command,
265
- publication,
266
239
  freshness,
267
- output,
240
+ ...(commandResult ? { result: commandResult } : {}),
268
241
  mutationCompleted: completedMutation !== undefined,
269
242
  ...(commandTiming
270
243
  ? {
@@ -296,10 +269,10 @@ export function createActionFusionExecutor(
296
269
  };
297
270
  /** A mutation that did not complete keeps its own failure; Fusion adds only the command status. */
298
271
  const notRun = (error: unknown, command: "skipped" | "cancelled") => {
299
- report(command, publicationOf(error), "unknown");
272
+ report(command, "unknown");
300
273
  return new CommandNotRun(error, command, causeOf(progressFailure, budget.fieldBytes));
301
274
  };
302
- report("waiting", "NOT_PUBLISHED", "unknown");
275
+ report("waiting", "unknown");
303
276
  let terminate: boolean | undefined;
304
277
  const result = await withQueue(absolutePath, async () => {
305
278
  try {
@@ -317,11 +290,12 @@ export function createActionFusionExecutor(
317
290
  throw error;
318
291
  }
319
292
 
320
- const { publication, publishedRevision } = outcome.commit;
321
- report("waiting", publication, "unknown");
293
+ const { publishedRevision } = outcome.commit;
294
+ report("waiting", "unknown");
322
295
  const settle = (observation: FreshnessObservation, command?: CommandFacts) => {
323
- if (command) report(command.status, publication, observation.freshness, command.output);
324
- const settled = finalizeMutation(
296
+ if (command) report(command.status, observation.freshness);
297
+ // The report states publication, freshness, and the command status once.
298
+ return finalizeMutation(
325
299
  tool,
326
300
  displayPath,
327
301
  outcome,
@@ -329,12 +303,6 @@ export function createActionFusionExecutor(
329
303
  command && { ...command, progressError: progressFailure },
330
304
  budget,
331
305
  );
332
- const actionFusion: ActionFusionDetails = {
333
- publication,
334
- command: command?.status ?? "not_requested",
335
- freshness: observation.freshness,
336
- };
337
- return { ...settled, details: { ...settled.details, actionFusion } };
338
306
  };
339
307
  if (thenRun === undefined) return settle(commitFreshness(outcome.commit));
340
308
 
@@ -343,8 +311,7 @@ export function createActionFusionExecutor(
343
311
  if (signal?.aborted) return settle(before, { status: "cancelled" });
344
312
  if (before.freshness !== "unchanged") return settle(before, { status: "skipped" });
345
313
 
346
- report("running", publication, "unchanged");
347
- let output = "";
314
+ report("running", "unchanged");
348
315
  let command: CommandOutcome;
349
316
  // The executor owns the heartbeat lifetime; Pi Bash owns timeout and process cleanup.
350
317
  let heartbeat: ReturnType<typeof setInterval> | undefined;
@@ -358,30 +325,26 @@ export function createActionFusionExecutor(
358
325
  deadlineMs: Date.now() + thenRun.timeout * MILLISECONDS_PER_SECOND,
359
326
  };
360
327
  if (onProgress || onUpdate) {
361
- heartbeat = setInterval(
362
- () => report("running", publication, "unknown", output),
363
- MILLISECONDS_PER_SECOND,
364
- );
328
+ heartbeat = setInterval(() => report("running", "unknown"), MILLISECONDS_PER_SECOND);
365
329
  heartbeat.unref();
366
330
  }
367
331
  }
368
- output = partial.content
369
- .filter((block) => block.type === "text")
370
- .map((block) => block.text)
371
- .join("\n");
372
- report("running", publication, "unknown", output);
332
+ commandResult = { content: partial.content, details: partial.details };
333
+ report("running", "unknown");
373
334
  });
374
- output = command.output;
375
335
  } catch (error) {
376
- output = errorMessage(error);
377
- command = { status: signal?.aborted ? "cancelled" : "failed", output };
336
+ command = {
337
+ status: signal?.aborted ? "cancelled" : "failed",
338
+ result: { content: [{ type: "text", text: errorMessage(error) }] },
339
+ };
378
340
  } finally {
379
341
  if (heartbeat) clearInterval(heartbeat);
380
342
  }
343
+ commandResult = command.result;
381
344
  terminate = command.terminate;
382
345
  return settle(await observeFreshness(absolutePath, publishedRevision), {
383
346
  status: command.status,
384
- output,
347
+ result: command.result,
385
348
  });
386
349
  }).catch((error: unknown) => {
387
350
  // Failures before the mutation started (such as resolving the queue key) also skip the command.
@@ -106,3 +106,19 @@ test("display row parsing rejects headers, notices, and invalid line references"
106
106
  assert.equal(parseDisplayRow(row), null, row);
107
107
  }
108
108
  });
109
+
110
+ test("Unicode line separators in display rows → preserves the complete content", async (t) => {
111
+ const formatter = createAnchorFormatter(4);
112
+ for (const separator of ["\u2028", "\u2029"]) {
113
+ const content = `before${separator}after`;
114
+ for (const [name, row, parse] of [
115
+ ["anchored", formatter.row(12, content), parseHashline],
116
+ ["anchored display", formatter.row(12, content), parseDisplayRow],
117
+ ["plain display", plainRow(12, content), parseDisplayRow],
118
+ ] as const) {
119
+ await t.test(`${name} ${JSON.stringify(separator)}`, () => {
120
+ assert.deepEqual(parse(row), { lineNo: "12", content });
121
+ });
122
+ }
123
+ }
124
+ });
@@ -18,11 +18,15 @@ export function anchorPattern(hashLen: number): string {
18
18
  return `^${anchorSource(`{${hashLen}}`)}$`;
19
19
  }
20
20
 
21
- /** Separates a row's line reference from its displayed content. */
21
+ /**
22
+ * Separates a row's line reference from its displayed content. Rows are split on LF only, so
23
+ * row and header patterns use `s`: content may hold U+2028 or U+2029, which `.` skips otherwise.
24
+ */
22
25
  const ROW_SEPARATOR = "│";
23
26
  const ANCHOR_TOKEN = new RegExp(`^${anchorSource("+")}$`);
24
27
  const HASHLINE_ROW = new RegExp(
25
28
  `^${anchorSource(`{${HASH_LEN_MIN},${HASH_LEN_MAX}}`)}${ROW_SEPARATOR}(.*)$`,
29
+ "s",
26
30
  );
27
31
 
28
32
  /** Split a `LINE#HASH` token of any hash length; undefined when the shape is wrong. */
@@ -31,7 +35,7 @@ export function parseAnchorToken(value: string): { line: number; hash: string }
31
35
  return match ? { line: Number(match[1]), hash: match[2]! } : undefined;
32
36
  }
33
37
 
34
- export interface HashlineRow {
38
+ interface HashlineRow {
35
39
  /** Line number as written in the anchor (string form). */
36
40
  lineNo: string;
37
41
  /** Line content with the `LINE#HASH│` prefix removed. */
@@ -44,7 +48,7 @@ export function parseHashline(line: string): HashlineRow | null {
44
48
  return match ? { lineNo: match[1], content: match[3] } : null;
45
49
  }
46
50
 
47
- const PLAIN_ROW = new RegExp(`^([1-9][0-9]*)${ROW_SEPARATOR}(.*)$`);
51
+ const PLAIN_ROW = new RegExp(`^([1-9][0-9]*)${ROW_SEPARATOR}(.*)$`, "s");
48
52
 
49
53
  /** Parse an anchored row or a non-editable `LINE│content` row; null for other text. */
50
54
  export function parseDisplayRow(line: string): HashlineRow | null {
@@ -11,33 +11,24 @@ 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";
18
17
  import type { ArgumentIssue } from "./report-schema.ts";
19
18
 
20
- export interface ArgumentDiagnostics {
19
+ interface ArgumentDiagnostics {
21
20
  readonly issues: readonly ArgumentIssue[];
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),
@@ -1,7 +1,10 @@
1
1
  import assert from "node:assert/strict";
2
2
  import type { ArgumentIssue, Report } from "./report-schema.ts";
3
3
 
4
- type ArgumentRejection = Report & { error: "INVALID_ARGUMENTS"; issues: ArgumentIssue[] };
4
+ type ArgumentRejection = Omit<Report, "tool" | "path"> & {
5
+ error: "INVALID_ARGUMENTS";
6
+ issues: ArgumentIssue[];
7
+ };
5
8
 
6
9
  /** Assert the model-facing JSON contract before inspecting an individual rejection. */
7
10
  export function argumentError(error: unknown): ArgumentRejection {
@@ -9,7 +12,8 @@ export function argumentError(error: unknown): ArgumentRejection {
9
12
  const value: unknown = JSON.parse(error.message);
10
13
  assert.ok(typeof value === "object" && value !== null);
11
14
  assert.equal(Reflect.get(value, "error"), "INVALID_ARGUMENTS");
12
- assert.equal(typeof Reflect.get(value, "tool"), "string");
15
+ assert.equal(Object.hasOwn(value, "tool"), false);
16
+ assert.equal(Object.hasOwn(value, "path"), false);
13
17
  const issues: unknown = Reflect.get(value, "issues");
14
18
  assert.ok(Array.isArray(issues));
15
19
  for (const issue of issues) {
@@ -33,10 +37,9 @@ export function rejectsArgument(field: string, reason: RegExp = /./) {
33
37
  };
34
38
  }
35
39
 
36
- export function rejectsArguments(tool: string) {
40
+ export function rejectsArguments() {
37
41
  return (error: unknown): boolean => {
38
42
  const result = argumentError(error);
39
- assert.equal(result.tool, tool);
40
43
  assert.ok(result.issues.length > 0);
41
44
  return true;
42
45
  };