@criogaid/pi-hashline-edit 0.5.1 → 0.6.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 (51) hide show
  1. package/README.md +51 -15
  2. package/package.json +6 -6
  3. package/src/core/apply.test.ts +66 -16
  4. package/src/core/apply.ts +36 -19
  5. package/src/core/lines.ts +3 -3
  6. package/src/index.ts +2 -0
  7. package/src/integration/forget-grep.test.ts +98 -0
  8. package/src/integration/fusion-dispatch.test.ts +343 -0
  9. package/src/integration/grep-rg.test.ts +269 -33
  10. package/src/integration/mutation-file-types.test.ts +44 -0
  11. package/src/pi/action-fusion.test.ts +71 -128
  12. package/src/pi/action-fusion.ts +83 -45
  13. package/src/pi/argument-validation.test.ts +136 -0
  14. package/src/pi/argument-validation.ts +103 -0
  15. package/src/pi/budgets.ts +4 -1
  16. package/src/pi/config.test.ts +1 -0
  17. package/src/pi/config.ts +4 -0
  18. package/src/pi/directory-sync.test.ts +1 -1
  19. package/src/pi/edit-tool.ts +55 -36
  20. package/src/pi/execute.test.ts +185 -645
  21. package/src/pi/failure-context.test.ts +4 -3
  22. package/src/pi/failure-path.test.ts +3 -3
  23. package/src/pi/file-commit.test.ts +24 -17
  24. package/src/pi/file-commit.ts +36 -9
  25. package/src/pi/file-snapshot.test.ts +24 -0
  26. package/src/pi/forget-tool.ts +268 -0
  27. package/src/pi/forget.test.ts +343 -0
  28. package/src/pi/forget.testing.ts +273 -0
  29. package/src/pi/grep-output.ts +57 -28
  30. package/src/pi/grep-search.ts +35 -12
  31. package/src/pi/grep-tool.ts +28 -9
  32. package/src/pi/grep.test.ts +173 -152
  33. package/src/pi/mutation-result.test.ts +23 -0
  34. package/src/pi/mutation-runner.ts +8 -4
  35. package/src/pi/path.ts +16 -2
  36. package/src/pi/pi.test.ts +3 -2
  37. package/src/pi/read-tool.ts +58 -26
  38. package/src/pi/read.test.ts +361 -0
  39. package/src/pi/registration.test.ts +115 -2
  40. package/src/pi/render.test.ts +45 -14
  41. package/src/pi/replace-tool.ts +18 -27
  42. package/src/pi/replace.test.ts +8 -107
  43. package/src/pi/result-safety.test.ts +123 -149
  44. package/src/pi/rg-match-bytes.ts +95 -0
  45. package/src/pi/rg-process.test.ts +40 -59
  46. package/src/pi/rg-text-view.ts +52 -5
  47. package/src/pi/tool-call.testing.ts +50 -0
  48. package/src/pi/tool-prompts.ts +15 -0
  49. package/src/pi/write-tool.ts +17 -26
  50. package/src/pi/write.test.ts +70 -61
  51. package/src/pi/e2e-scenarios.test.ts +0 -361
@@ -22,7 +22,7 @@
22
22
  import { realpath } from "node:fs/promises";
23
23
  import { basename, dirname, resolve } from "node:path";
24
24
  import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
25
- import { createBashToolDefinition, type ExtensionContext } from "@earendil-works/pi-coding-agent";
25
+ import type { ExtensionToolContext } from "@earendil-works/pi-coding-agent";
26
26
  import { Type, type Static, type TObject, type TProperties } from "typebox";
27
27
  import { fileRevision, FileMutationError, type PublicationStatus } from "./file-commit.ts";
28
28
  import { commitFreshness, finalizeMutation, type MutationOutcome } from "./mutation-result.ts";
@@ -76,9 +76,12 @@ export interface ActionFusionProgress extends Omit<ActionFusionDetails, "command
76
76
  timing?: { readonly timeoutSeconds: number; readonly remainingSeconds: number };
77
77
  }
78
78
 
79
- type ProgressReporter = (progress: ActionFusionProgress, ctx: ExtensionContext) => void;
79
+ type ProgressReporter = (progress: ActionFusionProgress, ctx: ExtensionToolContext) => void;
80
80
 
81
- export function createThenRunSchema(description: string) {
81
+ /** The tools that accept then_run. */
82
+ export type MutationToolName = "edit" | "replace" | "write";
83
+
84
+ export function createThenRunSchema(tool: MutationToolName) {
82
85
  return Type.Optional(
83
86
  Type.Object(
84
87
  {
@@ -91,32 +94,43 @@ export function createThenRunSchema(description: string) {
91
94
  }),
92
95
  ),
93
96
  },
94
- { description, additionalProperties: false },
97
+ {
98
+ description: `Command to run once after ${tool} succeeds; failure does not roll back the file.`,
99
+ additionalProperties: false,
100
+ },
95
101
  ),
96
102
  );
97
103
  }
98
104
  /** Add the optional then_run field to a mutation schema when Action Fusion is enabled. */
99
105
  export function withThenRunSchema<P extends TProperties>(
100
106
  schema: TObject<P>,
101
- description: string,
107
+ tool: MutationToolName,
102
108
  actionFusion: boolean,
103
109
  ): TObject<P> | TObject<P & { then_run: ReturnType<typeof createThenRunSchema> }> {
104
110
  return actionFusion
105
111
  ? Type.Object(
106
- { ...schema.properties, then_run: createThenRunSchema(description) },
112
+ { ...schema.properties, then_run: createThenRunSchema(tool) },
107
113
  { additionalProperties: false },
108
114
  )
109
115
  : schema;
110
116
  }
111
117
  export type ThenRunInput = NonNullable<Static<ReturnType<typeof createThenRunSchema>>>;
112
118
 
119
+ /** Keep command state independent of its diagnostic text and of file publication. */
120
+ export interface CommandOutcome {
121
+ readonly status: Exclude<CommandStatus, "not_requested" | "skipped">;
122
+ readonly output: string;
123
+ /** Preserve the session tool's request to stop after this tool batch. */
124
+ readonly terminate?: boolean;
125
+ }
126
+
113
127
  type CommandRunner = (
114
128
  toolCallId: string,
115
129
  input: ThenRunInput,
116
130
  signal: AbortSignal | undefined,
117
- ctx: ExtensionContext,
131
+ ctx: ExtensionToolContext,
118
132
  onUpdate?: AgentToolUpdateCallback<unknown>,
119
- ) => Promise<string>;
133
+ ) => Promise<CommandOutcome>;
120
134
 
121
135
  type MutationResult<TDetails> = AgentToolResult<TDetails>;
122
136
  /** Attach the fused outcome to a finalized mutation result, plus optional command text. */
@@ -204,24 +218,39 @@ export class ActionFusionError extends Error {
204
218
  }
205
219
  }
206
220
 
207
- function commandStatus(error: unknown, signal: AbortSignal | undefined): CommandStatus {
208
- if (signal?.aborted) return "cancelled";
209
- return /timeout|timed out/i.test(errorMessage(error)) ? "timeout" : "failed";
210
- }
211
-
212
221
  async function defaultCommandRunner(
213
- toolCallId: string,
222
+ _toolCallId: string,
214
223
  input: ThenRunInput,
215
224
  signal: AbortSignal | undefined,
216
- ctx: ExtensionContext,
225
+ ctx: ExtensionToolContext,
217
226
  onUpdate?: AgentToolUpdateCallback<unknown>,
218
- ): Promise<string> {
219
- const bash = createBashToolDefinition(ctx.cwd);
220
- const result = await bash.execute(`${toolCallId}:then_run`, input, signal, onUpdate, ctx);
221
- return result.content
227
+ ): Promise<CommandOutcome> {
228
+ // Use the session's callable Bash, including overrides, validation, permission
229
+ // hooks and tool_result hooks. Tool failures resolve with isError, not rejection.
230
+ const { result, isError } = await ctx.executeTool("bash", input, { signal, onUpdate });
231
+ const output = result.content
222
232
  .filter((block) => block.type === "text")
223
233
  .map((block) => block.text)
224
234
  .join("\n");
235
+ const command = { output, terminate: result.terminate };
236
+ if (!isError) return { status: "succeeded", ...command };
237
+ if (signal?.aborted) return { status: "cancelled", ...command };
238
+
239
+ const structured = result.structuredContent;
240
+ const hasExitCode =
241
+ structured !== null &&
242
+ typeof structured === "object" &&
243
+ "exit_code" in structured &&
244
+ typeof structured.exit_code === "number";
245
+ // Pi 0.99.1 supplies exit_code for ordinary exits, but serializes a thrown
246
+ // timeout as text. Only recognize its final diagnostic for the requested
247
+ // timeout; a failed command's output may itself mention or quote a timeout.
248
+ const timeoutDiagnostic = `Command timed out after ${input.timeout} seconds`;
249
+ const timedOut =
250
+ !hasExitCode &&
251
+ input.timeout !== undefined &&
252
+ (output === timeoutDiagnostic || output.endsWith(`\n${timeoutDiagnostic}`));
253
+ return { status: timedOut ? "timeout" : "failed", ...command };
225
254
  }
226
255
 
227
256
  async function canonicalQueueKey(path: string): Promise<string> {
@@ -289,10 +318,11 @@ export function createActionFusionExecutor(
289
318
  thenRun: ThenRunInput | undefined;
290
319
  mutate: () => Promise<MutationOutcome<TDetails>>;
291
320
  signal: AbortSignal | undefined;
292
- ctx: ExtensionContext;
321
+ ctx: ExtensionToolContext;
293
322
  onUpdate?: AgentToolUpdateCallback<TDetails>;
294
323
  }): Promise<MutationResult<TDetails>> {
295
324
  let completedMutation: MutationOutcome<TDetails> | undefined;
325
+ let commandTermination: boolean | undefined;
296
326
  let progressFailure: string | undefined;
297
327
  let commandTiming: { readonly timeoutSeconds: number; readonly deadlineMs: number } | undefined;
298
328
  const report = (
@@ -416,44 +446,50 @@ export function createActionFusionExecutor(
416
446
  );
417
447
  }
418
448
 
419
- if (thenRun.timeout !== undefined) {
420
- commandTiming = {
421
- timeoutSeconds: thenRun.timeout,
422
- deadlineMs: Date.now() + thenRun.timeout * MILLISECONDS_PER_SECOND,
423
- };
424
- }
425
449
  report("running", publication, "unchanged");
426
450
  let output = "";
451
+ let command: CommandOutcome;
427
452
  let commandError: unknown;
428
453
  // The executor owns the heartbeat lifetime; Pi Bash owns timeout and process cleanup.
429
- const heartbeat =
430
- commandTiming && (onProgress || onUpdate)
431
- ? setInterval(
432
- () => report("running", publication, "unknown", output),
433
- MILLISECONDS_PER_SECOND,
434
- )
435
- : undefined;
436
- heartbeat?.unref();
454
+ let heartbeat: ReturnType<typeof setInterval> | undefined;
437
455
  try {
438
- output = await commandRunner(toolCallId, thenRun, signal, ctx, (partial) => {
456
+ command = await commandRunner(toolCallId, thenRun, signal, ctx, (partial) => {
457
+ // Pi Bash emits an initial update even for silent commands. Start its
458
+ // countdown here, after session permission hooks have allowed execution.
459
+ if (!commandTiming && thenRun.timeout !== undefined) {
460
+ commandTiming = {
461
+ timeoutSeconds: thenRun.timeout,
462
+ deadlineMs: Date.now() + thenRun.timeout * MILLISECONDS_PER_SECOND,
463
+ };
464
+ if (onProgress || onUpdate) {
465
+ heartbeat = setInterval(
466
+ () => report("running", publication, "unknown", output),
467
+ MILLISECONDS_PER_SECOND,
468
+ );
469
+ heartbeat.unref();
470
+ }
471
+ }
439
472
  output = partial.content
440
473
  .filter((block) => block.type === "text")
441
474
  .map((block) => block.text)
442
475
  .join("\n");
443
476
  report("running", publication, "unknown", output);
444
477
  });
478
+ output = command.output;
445
479
  } catch (error) {
446
480
  commandError = error;
447
- output = "";
481
+ output = errorMessage(error);
482
+ command = { status: signal?.aborted ? "cancelled" : "failed", output };
448
483
  } finally {
449
484
  if (heartbeat) clearInterval(heartbeat);
450
485
  }
486
+ commandTermination = command.terminate;
451
487
  const freshness = await readFreshness(absolutePath, baseline);
452
- if (commandError !== undefined) {
488
+ if (command.status !== "succeeded") {
453
489
  throw new ActionFusionError(
454
490
  "mutation completed; then_run did not complete successfully",
455
- { publication, command: commandStatus(commandError, signal), freshness },
456
- { cause: commandError, commandOutput: errorMessage(commandError) },
491
+ { publication, command: command.status, freshness },
492
+ { cause: commandError ?? output, commandOutput: output },
457
493
  );
458
494
  }
459
495
 
@@ -514,16 +550,18 @@ export function createActionFusionExecutor(
514
550
  throw error;
515
551
  }
516
552
  })
517
- .then((result) =>
518
- progressFailure
553
+ .then((result) => {
554
+ const finalResult =
555
+ commandTermination === undefined ? result : { ...result, terminate: commandTermination };
556
+ return progressFailure
519
557
  ? {
520
- ...result,
558
+ ...finalResult,
521
559
  content: [
522
- ...result.content,
560
+ ...finalResult.content,
523
561
  { type: "text" as const, text: `Progress reporting failed: ${progressFailure}` },
524
562
  ],
525
563
  }
526
- : result,
527
- );
564
+ : finalResult;
565
+ });
528
566
  };
529
567
  }
@@ -0,0 +1,136 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { test } from "node:test";
6
+ import { createActionFusionExecutor } from "./action-fusion.ts";
7
+ import { DEFAULT_CONFIG } from "./config.ts";
8
+ import { makeEditOverride } from "./edit-tool.ts";
9
+ import { makeGrepOverride } from "./grep-tool.ts";
10
+ import { makeReadOverride } from "./read-tool.ts";
11
+ import { makeReplaceTool } from "./replace-tool.ts";
12
+ import { makeWriteOverride } from "./write-tool.ts";
13
+ import { callTool } from "./tool-call.testing.ts";
14
+ import { MAX_BLOCK_BYTES } from "./budgets.ts";
15
+ import { POSITIVE_SAFE_INTEGER } from "./schema.ts";
16
+
17
+ const invalidCommand = { command: "", timeout: 0 };
18
+ const anchorHash = "A".repeat(DEFAULT_CONFIG.hashLen);
19
+ const cases = [
20
+ {
21
+ name: "read",
22
+ make: (cwd: string, _fusion: ReturnType<typeof createActionFusionExecutor>) =>
23
+ makeReadOverride(cwd, DEFAULT_CONFIG),
24
+ args: { offset: -1, limit: 0 },
25
+ diagnostics: [
26
+ new RegExp(`\\n - offset:.*>= ${POSITIVE_SAFE_INTEGER.minimum}`),
27
+ new RegExp(`\\n - limit:.*>= ${POSITIVE_SAFE_INTEGER.minimum}`),
28
+ ],
29
+ },
30
+ {
31
+ name: "grep",
32
+ make: (cwd: string, _fusion: ReturnType<typeof createActionFusionExecutor>) =>
33
+ makeGrepOverride(cwd, DEFAULT_CONFIG),
34
+ args: { pattern: [], literal: true, limit: 0, context: -1 },
35
+ diagnostics: [/\n - pattern:/, /\n - limit:/, /\n - context:/],
36
+ },
37
+ {
38
+ name: "edit",
39
+ make: (cwd: string, fusion: ReturnType<typeof createActionFusionExecutor>) =>
40
+ makeEditOverride(cwd, DEFAULT_CONFIG, fusion),
41
+ args: {
42
+ edits: [
43
+ { op: "replace", anchor: `1#${anchorHash}`, body: [] },
44
+ { op: "append", body: ["bad\0", "bad\ud800"] },
45
+ { op: "delete", anchor: `${Number.MAX_SAFE_INTEGER + 1}#${anchorHash}`, end: "1#A" },
46
+ { op: "append", body: [] },
47
+ ],
48
+ then_run: invalidCommand,
49
+ },
50
+ diagnostics: [
51
+ /Invalid argument edits\[0\]\.body:.*delete/,
52
+ /Invalid argument edits\[1\]\.body\[0\]: UNSUPPORTED_TEXT:/,
53
+ /Invalid argument edits\[1\]\.body\[1\]: INVALID_UNICODE:/,
54
+ /Invalid argument edits\[2\]\.anchor:.*safe integer/,
55
+ /Invalid argument edits\[2\]\.end:.*hash/,
56
+ /Invalid argument edits\[3\]\.body:.*empty/,
57
+ /\n - then_run.command:/,
58
+ /\n - then_run.timeout:/,
59
+ ],
60
+ },
61
+ {
62
+ name: "replace",
63
+ make: (cwd: string, fusion: ReturnType<typeof createActionFusionExecutor>) =>
64
+ makeReplaceTool(cwd, DEFAULT_CONFIG, fusion),
65
+ args: {
66
+ replacements: [
67
+ { find: "(", replace: "bad\0", regex: true },
68
+ { find: "[", replace: "bad\ud800", regex: true },
69
+ ],
70
+ then_run: invalidCommand,
71
+ },
72
+ diagnostics: [
73
+ /Invalid argument replacements\[0\]\.replace: UNSUPPORTED_TEXT:/,
74
+ /Invalid argument replacements\[0\]\.find: invalid regex/,
75
+ /Invalid argument replacements\[1\]\.replace: INVALID_UNICODE:/,
76
+ /Invalid argument replacements\[1\]\.find: invalid regex/,
77
+ /\n - then_run.command:/,
78
+ /\n - then_run.timeout:/,
79
+ ],
80
+ },
81
+ {
82
+ name: "write",
83
+ make: (cwd: string, fusion: ReturnType<typeof createActionFusionExecutor>) =>
84
+ makeWriteOverride(cwd, fusion),
85
+ args: { content: "bad\0", mode: "invalid", then_run: invalidCommand },
86
+ diagnostics: [
87
+ /Invalid argument content: UNSUPPORTED_TEXT:/,
88
+ /\n - mode:/,
89
+ /\n - then_run.command:/,
90
+ /\n - then_run.timeout:/,
91
+ ],
92
+ },
93
+ ] as const;
94
+
95
+ for (const scenario of cases) {
96
+ test(`${scenario.name} receives independent argument errors → reports them together without effects`, async (t) => {
97
+ const cwd = await mkdtemp(join(tmpdir(), "hashline-arguments-"));
98
+ t.after(() => rm(cwd, { recursive: true, force: true }));
99
+ const path = join(cwd, "target.txt");
100
+ const original = "original\n";
101
+ await writeFile(path, original);
102
+ let commandRuns = 0;
103
+ const fusion = createActionFusionExecutor(async () => {
104
+ commandRuns++;
105
+ return { status: "succeeded", output: "ran" };
106
+ });
107
+ const tool = scenario.make(cwd, fusion);
108
+ // These values round-trip through JSON exactly as model tool arguments do.
109
+ const args: unknown = JSON.parse(JSON.stringify({ path, ...scenario.args, unexpected: true }));
110
+ await assert.rejects(callTool(tool, args), (error: Error) => {
111
+ for (const diagnostic of [...scenario.diagnostics, /\n - unexpected:/]) {
112
+ assert.match(error.message, diagnostic);
113
+ }
114
+ assert.doesNotMatch(error.message, /\n - path:/);
115
+ assert.doesNotMatch(error.message, /Received arguments:\n/);
116
+ const echoedArgs = [...error.message.matchAll(/^Received arguments: (.+)$/gm)].map((match) =>
117
+ JSON.parse(match[1]),
118
+ );
119
+ assert.deepEqual(echoedArgs.at(-1), { unexpected: true });
120
+ return true;
121
+ });
122
+ assert.equal(await readFile(path, "utf8"), original);
123
+ assert.equal(commandRuns, 0);
124
+ });
125
+ }
126
+
127
+ test("argument diagnostics exceed the shared budget → rejection labels omitted text", async () => {
128
+ const tool = makeEditOverride(process.cwd(), DEFAULT_CONFIG);
129
+ const edits = Array.from({ length: MAX_BLOCK_BYTES }, () => ({ op: "append", body: [] }));
130
+ await assert.rejects(callTool(tool, { path: "", edits }), (error: Error) => {
131
+ assert.ok(Buffer.byteLength(error.message) <= MAX_BLOCK_BYTES);
132
+ assert.match(error.message, /Invalid argument edits\[0\]\.body:/);
133
+ assert.match(error.message, /Diagnostics truncated/);
134
+ return true;
135
+ });
136
+ });
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Shared argument preparation for every tool. Tool checks only report independent
3
+ * field issues; this boundary combines them with Pi's schema diagnostics and throws
4
+ * once. Pi still validates returned arguments in its mandatory tool-call pipeline.
5
+ * Failure diagnostics validate independent top-level fields separately so an invalid
6
+ * union in one field cannot exhaust Pi's error budget for another. Tool schemas have
7
+ * no cross-field constraints. Arguments and TypeBox's process-wide settings are not changed.
8
+ */
9
+ import { validateToolArguments, type ToolCall } from "@earendil-works/pi-ai";
10
+ import { Type, type Static, type TObject, type TSchema } from "typebox";
11
+ import { ObjectOptions } from "typebox/type";
12
+ import { errorMessage } from "../core/errors.ts";
13
+ import { MAX_BLOCK_BYTES } from "./budgets.ts";
14
+ import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
15
+ import { invalidArgument } from "./error-text.ts";
16
+
17
+ export type ReportArgumentIssue = (field: string, reason: string) => void;
18
+ type CheckArguments = (args: unknown, report: ReportArgumentIssue) => void;
19
+
20
+ /** Inspect arrays and the singleton objects Pi may coerce, without changing input. */
21
+ export function argumentItems(value: unknown): readonly unknown[] {
22
+ return Array.isArray(value) ? value : value !== null && typeof value === "object" ? [value] : [];
23
+ }
24
+
25
+ /**
26
+ * Compact the exact argument suffix emitted by Pi 0.99.1's validateToolArguments.
27
+ * If Pi changes that format, preserve its full error unchanged, including multiline JSON.
28
+ */
29
+ function schemaDiagnostic(error: unknown, args: unknown): string {
30
+ const message = errorMessage(error);
31
+ const label = "Received arguments:";
32
+ const suffix = `\n\n${label}\n${JSON.stringify(args, null, 2)}`;
33
+ if (!message.endsWith(suffix)) return message;
34
+ return `${message.slice(0, -suffix.length)}\n${label} ${JSON.stringify(args)}`;
35
+ }
36
+
37
+ export function createArgumentPreparer<T extends TObject>(
38
+ name: string,
39
+ parameters: T,
40
+ check?: CheckArguments,
41
+ ): (args: unknown) => Static<T> {
42
+ const fields = Object.keys(parameters.properties);
43
+ const options = { additionalProperties: ObjectOptions(parameters).additionalProperties };
44
+ const fieldSchemas = fields.map((field) => ({
45
+ field,
46
+ schema: Type.Pick(parameters, [field], options),
47
+ }));
48
+ const unknownFieldsSchema = Type.Omit(parameters, fields, options);
49
+ const validate = (schema: TSchema, args: unknown): unknown =>
50
+ validateToolArguments(
51
+ { name, parameters: schema, description: "" },
52
+ // Pi owns shape checking and coercion at this external boundary.
53
+ {
54
+ type: "toolCall",
55
+ id: "argument-validation",
56
+ name,
57
+ arguments: args as ToolCall["arguments"],
58
+ },
59
+ );
60
+
61
+ return (args) => {
62
+ let checked: unknown = args;
63
+ let schemaFailure: unknown;
64
+ try {
65
+ checked = validate(parameters, args);
66
+ } catch (error) {
67
+ schemaFailure = error;
68
+ }
69
+ const diagnostics = new DiagnosticBuffer(MAX_BLOCK_BYTES);
70
+ let hasIssues = schemaFailure !== undefined;
71
+ check?.(checked, (field, reason) => {
72
+ hasIssues = true;
73
+ diagnostics.append(`${invalidArgument(field, reason).message}\n`);
74
+ });
75
+ if (schemaFailure !== undefined) {
76
+ if (typeof args === "object" && args !== null && !Array.isArray(args)) {
77
+ const entries = Object.entries(args);
78
+ const diagnose = (schema: TSchema, value: unknown) => {
79
+ try {
80
+ validate(schema, value);
81
+ } catch (error) {
82
+ diagnostics.append(`${schemaDiagnostic(error, value)}\n`);
83
+ }
84
+ };
85
+ for (const { field, schema } of fieldSchemas) {
86
+ diagnose(schema, Object.fromEntries(entries.filter(([key]) => key === field)));
87
+ }
88
+ diagnose(
89
+ unknownFieldsSchema,
90
+ Object.fromEntries(entries.filter(([key]) => !fields.includes(key))),
91
+ );
92
+ } else {
93
+ diagnostics.append(schemaDiagnostic(schemaFailure, args));
94
+ }
95
+ diagnostics.append(
96
+ "\nPi limits schema diagnostics within each field; additional errors may remain.\n",
97
+ );
98
+ }
99
+ if (hasIssues) throw new Error(diagnostics.toString().trimEnd(), { cause: schemaFailure });
100
+ // Keep Pi's preparation contract: the framework performs its own coercion next.
101
+ return args as Static<T>;
102
+ };
103
+ }
package/src/pi/budgets.ts CHANGED
@@ -12,7 +12,7 @@
12
12
  /** grep line preview, in UTF-16 units, excluding its partial-line label. */
13
13
  export const GREP_MAX_LINE_LENGTH = 500;
14
14
 
15
- /** Each diagnostic or anchor block: failure details, input-anchor checks, candidate neighborhoods, mutation anchors. */
15
+ /** Each diagnostic or anchor block: argument errors, failure details, input-anchor checks, candidate neighborhoods, mutation anchors. */
16
16
  export const MAX_BLOCK_BYTES = 16 * 1024;
17
17
  /** One recovery-candidate or cited row inside a failure diagnostic. */
18
18
  export const MAX_RECOVERY_CANDIDATE_BYTES = 4 * 1024;
@@ -23,3 +23,6 @@ export const MAX_SEARCH_DIAGNOSTIC_BYTES = 4 * 1024;
23
23
  export function formatKiB(bytes: number): string {
24
24
  return `${bytes / 1024} KiB`;
25
25
  }
26
+
27
+ /** Smallest read or grep text result tagged for forget; smaller ones save too little to be worth forgetting. */
28
+ export const FORGET_MIN_BYTES = 2 * 1024;
@@ -32,6 +32,7 @@ test("defaults come from the settings schema", () => {
32
32
  assert.deepEqual(DEFAULT_CONFIG, {
33
33
  enabled: true,
34
34
  actionFusion: true,
35
+ forget: false,
35
36
  hashLen: 4,
36
37
  shiftRadius: 15,
37
38
  read: { defaultLimit: 500, maxKiB: 256 },
package/src/pi/config.ts CHANGED
@@ -33,6 +33,10 @@ export const configSchema = Type.Object({
33
33
  default: true,
34
34
  description: "Expose optional then_run commands after edit/replace/write.",
35
35
  }),
36
+ forget: Type.Boolean({
37
+ default: false,
38
+ description: "Register forget and tag eligible read/grep results for context removal.",
39
+ }),
36
40
  hashLen: integerSetting(
37
41
  integerRange(HASH_LEN_MIN, HASH_LEN_MAX),
38
42
  4,
@@ -30,7 +30,7 @@ test("macOS attempts directory sync, tolerates unsupported operations, and prese
30
30
  syncBuiltinESMExports();
31
31
  for (failure of [undefined, "EINVAL", "ENOTSUP", "EIO"]) {
32
32
  const path = join(directory, failure ?? "success");
33
- const commit = commitFile(path, "published\n");
33
+ const commit = commitFile(path, "published\n", { mode: "create" });
34
34
  if (failure === "EIO") {
35
35
  await assert.rejects(
36
36
  commit,