@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
@@ -10,7 +10,7 @@ import { ObjectOptions, Type, type Static, type TObject, type TSchema } from "ty
10
10
  import { errorMessage } from "../core/errors.ts";
11
11
  import { diagnoseArguments } from "./argument-diagnostics.ts";
12
12
  import { formatArgumentError } from "./argument-error.ts";
13
- import { defaultOutputBudgets, type OutputBudgetProvider } from "./budgets.ts";
13
+ import type { OutputBudgetProvider } from "./budgets.ts";
14
14
  import type { ArgumentIssue, ReportTool } from "./report-schema.ts";
15
15
 
16
16
  /** Report one semantic issue: what is wrong (a fact), and how to correct it when the fact alone does not say. */
@@ -25,8 +25,8 @@ export function argumentItems(value: unknown): readonly unknown[] {
25
25
  export function createArgumentPreparer<T extends TObject>(
26
26
  name: ReportTool,
27
27
  parameters: T,
28
- check?: CheckArguments,
29
- budgets: OutputBudgetProvider = defaultOutputBudgets,
28
+ check: CheckArguments | undefined,
29
+ budgets: OutputBudgetProvider,
30
30
  ): (args: unknown) => Static<T> {
31
31
  const validate = (schema: TSchema, args: unknown): unknown =>
32
32
  validateToolArguments(
@@ -69,7 +69,6 @@ export function createArgumentPreparer<T extends TObject>(
69
69
  if (!observation) {
70
70
  throw new Error(
71
71
  formatArgumentError(
72
- name,
73
72
  [{ field: "$", reason: errorMessage(schemaFailure) }],
74
73
  false,
75
74
  budgets(),
@@ -90,7 +89,7 @@ export function createArgumentPreparer<T extends TObject>(
90
89
  ? result.issues
91
90
  : [{ field: "$", reason: errorMessage(schemaFailure) }];
92
91
  if (schemaFailure !== undefined || result.issues.length > 0) {
93
- throw new Error(formatArgumentError(name, reported, result.limited, budgets()), {
92
+ throw new Error(formatArgumentError(reported, result.limited, budgets()), {
94
93
  cause: schemaFailure,
95
94
  });
96
95
  }
package/src/pi/budgets.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  /**
2
2
  * Model-facing byte budgets. README "Output budgets" documents this policy.
3
3
  * The context window is a capacity hint, not a tokenizer or remaining-context counter.
4
- * This module also loads in the replacement worker; keep it free of Pi runtime imports.
5
4
  */
6
5
 
7
6
  const BYTES_PER_CONTEXT_TOKEN = 1;
@@ -48,10 +47,9 @@ export function outputBudgetsFor(contextWindow: number | undefined): OutputBudge
48
47
  /** Standalone tool factories have no session model until a provider is supplied. */
49
48
  export const defaultOutputBudgets: OutputBudgetProvider = () => DEFAULT_OUTPUT_BUDGETS;
50
49
 
51
- /** Size wording for notices, e.g. `16 KiB`. */
52
- export function formatKiB(bytes: number): string {
53
- return `${bytes / 1024} KiB`;
54
- }
50
+ const MIB = 1024 * 1024;
55
51
 
56
- /** Smallest read or grep text result tagged for forget; smaller ones save too little to be worth forgetting. */
57
- export const FORGET_MIN_BYTES = 2 * 1024;
52
+ /** Size wording for every model-facing limit: whole MiB as `256 MiB`, otherwise `16 KiB`. */
53
+ export function formatByteSize(bytes: number): string {
54
+ return bytes % MIB === 0 ? `${bytes / MIB} MiB` : `${bytes / 1024} KiB`;
55
+ }
@@ -32,7 +32,6 @@ test("defaults come from the settings schema", () => {
32
32
  assert.deepEqual(DEFAULT_CONFIG, {
33
33
  enabled: true,
34
34
  actionFusion: true,
35
- forget: false,
36
35
  hashLen: 4,
37
36
  shiftRadius: 15,
38
37
  read: { defaultLimit: 500, maxKiB: undefined },
@@ -56,7 +55,7 @@ test("actionFusion defaults on and honors explicit disabling", () =>
56
55
  }
57
56
  }));
58
57
 
59
- test("config rejects fractional values and tolerates malformed settings shapes", () =>
58
+ test("invalid or unknown settings → preserve valid leaves and default malformed values", () =>
60
59
  withSettings(async (write, root) => {
61
60
  for (const value of [3.5, -1, "4", null]) {
62
61
  await write({ hashlineEdit: { hashLen: value, shiftRadius: value } });
@@ -73,9 +72,8 @@ test("config rejects fractional values and tolerates malformed settings shapes",
73
72
  await write(rootValue);
74
73
  assert.deepEqual(loadConfig(root), DEFAULT_CONFIG);
75
74
  }
76
- await write({ hashlineEdit: { hashLen: 8, shiftRadius: 0 } });
77
- assert.equal(loadConfig(root).hashLen, 8);
78
- assert.equal(loadConfig(root).shiftRadius, 0);
75
+ await write({ hashlineEdit: { hashLen: 8, shiftRadius: 0, unexpected: true } });
76
+ assert.deepEqual(loadConfig(root), { ...DEFAULT_CONFIG, hashLen: 8, shiftRadius: 0 });
79
77
  }));
80
78
 
81
79
  test("tool groups resolve each setting independently", () =>
@@ -131,6 +129,18 @@ test("project settings replace global groups while absent project settings use g
131
129
  assert.deepEqual(loadConfig(root), DEFAULT_CONFIG);
132
130
  }));
133
131
 
132
+ test("project hashlineEdit is null → replaces global settings with defaults", () =>
133
+ withSettings(async (write, root, agentDir) => {
134
+ const globalConfig = { ...DEFAULT_CONFIG, enabled: false, hashLen: 8 };
135
+ await writeFile(
136
+ join(agentDir, "settings.json"),
137
+ JSON.stringify({ hashlineEdit: globalConfig }),
138
+ );
139
+ assert.deepEqual(loadConfig(root), globalConfig);
140
+ await write({ hashlineEdit: null });
141
+ assert.deepEqual(loadConfig(root), DEFAULT_CONFIG);
142
+ }));
143
+
134
144
  test("invalid tool groups default independently without discarding valid sibling groups", () =>
135
145
  withSettings(async (write, root) => {
136
146
  const configured = {
package/src/pi/config.ts CHANGED
@@ -32,7 +32,7 @@ const regexTimeoutSetting = integerSetting(
32
32
  );
33
33
 
34
34
  /** Settings schema: the single source of setting types, bounds, and defaults. */
35
- export const configSchema = Type.Object({
35
+ const configSchema = Type.Object({
36
36
  enabled: Type.Boolean({
37
37
  default: true,
38
38
  description:
@@ -42,10 +42,6 @@ export const configSchema = Type.Object({
42
42
  default: true,
43
43
  description: "Expose optional then_run commands after edit/replace/write.",
44
44
  }),
45
- forget: Type.Boolean({
46
- default: false,
47
- description: "Register forget and tag eligible read/grep results for context removal.",
48
- }),
49
45
  hashLen: integerSetting(
50
46
  integerRange(HASH_LEN_MIN, HASH_LEN_MAX),
51
47
  4,
@@ -131,5 +127,9 @@ function readSettings(filePath: string): Record<string, unknown> {
131
127
  export function loadConfig(cwd?: string): HashlineEditConfig {
132
128
  const globalSettings = readSettings(path.join(getAgentDir(), "settings.json"));
133
129
  const projectSettings = cwd ? readSettings(path.join(cwd, ".pi", "settings.json")) : {};
134
- return resolveSetting(configSchema, projectSettings.hashlineEdit ?? globalSettings.hashlineEdit);
130
+ // Any project value replaces the global one, even null or an invalid value, which yields defaults.
131
+ const settings = Object.hasOwn(projectSettings, "hashlineEdit")
132
+ ? projectSettings
133
+ : globalSettings;
134
+ return resolveSetting(configSchema, settings.hashlineEdit);
135
135
  }
@@ -46,10 +46,9 @@ test("diagnostics within the budget are unchanged", () => {
46
46
 
47
47
  test("search warning aggregation retains the final cause and labels truncation", () => {
48
48
  const { facts, payload } = assembleGrepOutput({
49
+ budget: DEFAULT_OUTPUT_BUDGETS,
49
50
  formatted: {
50
- blocks: ["confirmed match"],
51
- linesTruncated: false,
52
- invalidUtf8: [],
51
+ blocks: [{ lines: ["confirmed match"] }],
53
52
  matches: 1,
54
53
  files: 1,
55
54
  },
@@ -3,7 +3,7 @@
3
3
  * model-facing search warnings. Retain the opening context and final cause;
4
4
  * mark omitted text instead of silently dropping diagnostics.
5
5
  */
6
- import { formatKiB } from "./budgets.ts";
6
+ import { formatByteSize } from "./budgets.ts";
7
7
 
8
8
  /** Cut only at UTF-8 boundaries; diagnostics may contain a single oversized line. */
9
9
  function byteSlice(text: string, maxBytes: number, tail: boolean): string {
@@ -25,7 +25,7 @@ export class DiagnosticBuffer {
25
25
 
26
26
  constructor(maxBytes: number) {
27
27
  this.maxBytes = maxBytes;
28
- this.notice = `\n[Diagnostics truncated (${formatKiB(maxBytes)} limit); middle omitted.]\n`;
28
+ this.notice = `\n[Diagnostics truncated (${formatByteSize(maxBytes)} limit); middle omitted.]\n`;
29
29
  const contentBytes = maxBytes - Buffer.byteLength(this.notice);
30
30
  this.headBytes = Math.floor(contentBytes / 2);
31
31
  this.tailBytes = contentBytes - this.headBytes;
@@ -22,7 +22,7 @@ import {
22
22
  type ToolRenderResultOptions,
23
23
  } from "@earendil-works/pi-coding-agent";
24
24
  import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
25
- import { Type, type Static } from "typebox";
25
+ import { Type, type Static, type TLiteral } from "typebox";
26
26
  import {
27
27
  ACTION_FUSION_GUIDELINES,
28
28
  withThenRunDescription,
@@ -36,6 +36,7 @@ import type { HashlineEditConfig } from "./config.ts";
36
36
  import { anchorPattern, createAnchorFormatter, parseAnchorToken } from "./anchor-format.ts";
37
37
  import {
38
38
  formatDiffCounts,
39
+ formatHeaderPath,
39
40
  renderMutationCall,
40
41
  renderMutationResult,
41
42
  type DiffCounts,
@@ -65,90 +66,103 @@ function parseAnchor(value: string | undefined) {
65
66
  return value === undefined ? undefined : parseAnchorToken(value)!;
66
67
  }
67
68
 
68
- /** Edit parameters; anchors must carry exactly `hashLen` hash characters. */
69
+ /** Operation item fields besides `action`. */
70
+ type EditItemField = (typeof EDIT_ANCHOR_FIELDS)[number] | "body";
71
+
72
+ /** What one op does and which item fields it takes; it takes no others. */
73
+ interface EditOpSpec {
74
+ readonly meaning: string;
75
+ readonly required: readonly EditItemField[];
76
+ readonly optional?: readonly EditItemField[];
77
+ /** Destinations, of which exactly one is required. */
78
+ readonly destination?: readonly EditItemField[];
79
+ }
80
+
81
+ const TRANSFER_DESTINATION = ["before", "after"] as const;
82
+
83
+ /** Every op and its fields; the schema states them, and argument checks enforce them. */
84
+ const EDIT_OPS = {
85
+ replace: {
86
+ meaning: "Replace the cited line(s) with body.",
87
+ required: ["anchor", "body"],
88
+ optional: ["end"],
89
+ },
90
+ delete: { meaning: "Delete the cited line(s).", required: ["anchor"], optional: ["end"] },
91
+ insert_after: {
92
+ meaning: "Insert body after the anchor line, which is kept; do not repeat it in body.",
93
+ required: ["anchor", "body"],
94
+ },
95
+ insert_before: {
96
+ meaning: "Insert body before the anchor line, which is kept; do not repeat it in body.",
97
+ required: ["anchor", "body"],
98
+ },
99
+ copy: {
100
+ meaning:
101
+ "Copy the cited line(s), text and indentation unchanged, before or after another original line; use a body edit when either changes.",
102
+ required: ["anchor"],
103
+ optional: ["end"],
104
+ destination: TRANSFER_DESTINATION,
105
+ },
106
+ move: {
107
+ meaning:
108
+ "Move the cited line(s), text and indentation unchanged, before or after another original line, removing the source; use a body edit when either changes.",
109
+ required: ["anchor"],
110
+ optional: ["end"],
111
+ destination: TRANSFER_DESTINATION,
112
+ },
113
+ append: { meaning: "Add body at the end of the file.", required: ["body"] },
114
+ prepend: { meaning: "Add body at the start of the file.", required: ["body"] },
115
+ } as const satisfies Record<string, EditOpSpec>;
116
+ type EditOpName = keyof typeof EDIT_OPS;
117
+ const EDIT_OP_NAMES = Object.keys(EDIT_OPS) as EditOpName[];
118
+
119
+ /** Operations in one call; constrained sampling ends a runaway batch at this bound. */
120
+ const MAX_EDIT_OPS = 64;
121
+
122
+ /** An op's meaning followed by the fields it takes. */
123
+ function describeEditOp({ meaning, required, optional = [], destination }: EditOpSpec): string {
124
+ const takes = [
125
+ ...required,
126
+ ...(destination ? [`exactly one of ${destination.join(" or ")}`] : []),
127
+ ].join(" and ");
128
+ return `${meaning} Takes ${takes}${optional.length ? `; ${optional.join(", ")} is optional` : ""}.`;
129
+ }
130
+
131
+ /**
132
+ * Edit parameters; anchors must carry exactly `hashLen` hash characters. Each
133
+ * operation is one flat object, so providers can constrain sampling to the
134
+ * schema; argument checks enforce which fields each op takes.
135
+ */
69
136
  function buildEditSchema(hashLen: number) {
70
137
  const pattern = anchorPattern(hashLen);
71
- const requiredAnchor = Type.String({
72
- pattern,
73
- description: "LINE#HASH of the target line.",
74
- });
75
- const optionalEnd = Type.Optional(
76
- Type.String({
77
- pattern,
78
- description: "Inclusive last LINE#HASH of the range; omit for one line.",
79
- }),
80
- );
81
- const bodyLines = Type.Array(Type.String({ pattern: "^[^\\r\\n]*$" }), {
82
- minItems: 1,
83
- description: 'New lines, one per element, without CR/LF. At least one; [""] is one blank line.',
84
- });
85
- const transferFields = {
86
- op: Type.Union([Type.Literal("copy"), Type.Literal("move")], {
87
- description:
88
- "Use copy or move to transfer whole lines whose text and indentation stay unchanged; move also removes the source. Use a body edit when text or indentation must change. Give exactly one destination: before or after.",
89
- }),
90
- anchor: requiredAnchor,
91
- end: optionalEnd,
92
- };
93
- const editOpSchema = Type.Union([
94
- Type.Object(
95
- {
96
- op: Type.Literal("replace", { description: "Replace the cited line(s) with `body`." }),
97
- anchor: requiredAnchor,
98
- end: optionalEnd,
99
- body: bodyLines,
100
- },
101
- { additionalProperties: false },
102
- ),
103
- Type.Object(
104
- {
105
- op: Type.Literal("delete", { description: "Delete the cited line(s)." }),
106
- anchor: requiredAnchor,
107
- end: optionalEnd,
108
- },
109
- { additionalProperties: false },
110
- ),
111
- Type.Object(
112
- {
113
- op: Type.Union([Type.Literal("insert_after"), Type.Literal("insert_before")], {
138
+ const anchorField = (description: string) => Type.Optional(Type.String({ pattern, description }));
139
+ const editOpSchema = Type.Object(
140
+ {
141
+ // Constrained sampling and some gateways emit keys alphabetically; `action`
142
+ // sorts first, so the operation is chosen before the fields it governs.
143
+ // TypeBox infers a union's static type only from a tuple.
144
+ action: Type.Union(
145
+ EDIT_OP_NAMES.map((op) =>
146
+ Type.Literal(op, { description: describeEditOp(EDIT_OPS[op]) }),
147
+ ) as [TLiteral<EditOpName>, ...TLiteral<EditOpName>[]],
148
+ ),
149
+ anchor: anchorField("LINE#HASH of the target line."),
150
+ end: anchorField("Inclusive last LINE#HASH of the range; omit for one line."),
151
+ body: Type.Optional(
152
+ Type.Array(Type.String({ pattern: "^[^\\r\\n]*$" }), {
153
+ minItems: 1,
114
154
  description:
115
- "Insert body beside the anchor line, which is kept; do not repeat it in body.",
116
- }),
117
- anchor: requiredAnchor,
118
- body: bodyLines,
119
- },
120
- { additionalProperties: false },
121
- ),
122
- Type.Object(
123
- {
124
- ...transferFields,
125
- before: Type.String({
126
- pattern,
127
- description: "Insert captured lines before this original line.",
155
+ 'New lines, one per element, without CR/LF. At least one; [""] is one blank line.',
128
156
  }),
129
- },
130
- { additionalProperties: false },
131
- ),
132
- Type.Object(
133
- {
134
- ...transferFields,
135
- after: Type.String({
136
- pattern,
137
- description: "Insert captured lines after this original line.",
138
- }),
139
- },
140
- { additionalProperties: false },
141
- ),
142
- Type.Object(
143
- {
144
- op: Type.Union([Type.Literal("append"), Type.Literal("prepend")], {
145
- description: "Add body at the end or start of the file.",
146
- }),
147
- body: bodyLines,
148
- },
149
- { additionalProperties: false },
150
- ),
151
- ]);
157
+ ),
158
+ before: anchorField("Insert captured lines before this original line."),
159
+ after: anchorField("Insert captured lines after this original line."),
160
+ },
161
+ {
162
+ additionalProperties: false,
163
+ description: "One operation. Omit, or set to null, each field its action does not take.",
164
+ },
165
+ );
152
166
  return Type.Object(
153
167
  {
154
168
  path: Type.String({
@@ -157,7 +171,8 @@ function buildEditSchema(hashLen: number) {
157
171
  }),
158
172
  edits: Type.Array(editOpSchema, {
159
173
  minItems: 1,
160
- description: `Operations on one snapshot. Anchors are LINE#HASH with exactly ${hashLen} hash characters. Copy each anchor from read, grep, or edit failure diagnostics; never write a hash you have not seen there. Shell output such as sed, head, or cat has no anchors, so read or grep those lines first.`,
174
+ maxItems: MAX_EDIT_OPS,
175
+ description: `Operations on one snapshot; ranges must not overlap. Each gap between lines takes at most one insertion, copy/move destinations included; insert_after N and insert_before N+1 target the same gap, so put all new lines for a gap in one body. An insertion at the start of a replaced or deleted range goes before it. Anchors are LINE#HASH with exactly ${hashLen} hash characters. Copy each anchor from read, grep, or edit failure diagnostics; never write a hash you have not seen there. Shell output such as sed, head, or cat has no anchors, so read or grep those lines first.`,
161
176
  }),
162
177
  },
163
178
  { additionalProperties: false },
@@ -165,56 +180,89 @@ function buildEditSchema(hashLen: number) {
165
180
  }
166
181
  type EditSchema = ReturnType<typeof buildEditSchema>;
167
182
 
168
- function createEditSchema(actionFusion: boolean, hashLen: number) {
169
- return withThenRunSchema(buildEditSchema(hashLen), "edit", actionFusion);
170
- }
171
183
  type EditParams = Static<EditSchema> & { then_run?: ThenRunInput };
172
184
 
173
185
  type EditOpInput = Static<EditSchema>["edits"][number];
186
+ type EditOpSchema = EditSchema["properties"]["edits"]["items"];
174
187
 
175
188
  /** How to correct edit argument issues; each reason states only what is wrong. */
176
189
  const EDIT_ISSUE_FIX = {
177
- emptyReplace: 'Use {"op":"delete"} to remove lines, or supply the replacement lines.',
190
+ emptyReplace: 'Use {"action":"delete"} to remove lines, or supply the replacement lines.',
178
191
  emptyBody: 'Remove this edit or supply at least one line ([""] for a blank line).',
179
192
  unsafeLine: 'Copy a complete "LINE#HASH" token from the latest tool result.',
180
193
  hashLength: "Read or grep the file for current anchors.",
181
194
  } as const;
182
195
 
183
- /** Report semantic argument issues; malformed shapes remain Pi's schema responsibility. */
184
- function checkEditArguments(args: unknown, hashLen: number, report: ReportArgumentIssue): void {
185
- const raw = (args as { edits?: unknown } | null)?.edits;
186
- const edits = argumentItems(raw);
187
- edits.forEach((op, index) => {
188
- const body = (op as Record<string, unknown> | null)?.body;
189
- if (Array.isArray(body)) {
196
+ /**
197
+ * Report semantic argument issues: the fields each op takes, and field values
198
+ * the schema cannot judge. Malformed shapes remain Pi's schema responsibility;
199
+ * Pi has already removed null optional fields.
200
+ */
201
+ function checkEditArguments(
202
+ args: unknown,
203
+ hashLen: number,
204
+ item: EditOpSchema,
205
+ report: ReportArgumentIssue,
206
+ ): void {
207
+ argumentItems((args as { edits?: unknown } | null)?.edits).forEach((value, index) => {
208
+ if (value === null || typeof value !== "object") return;
209
+ const edit = value as Record<string, unknown>;
210
+ // The schema reports an unknown action; which fields it takes is then unknown.
211
+ if (typeof edit.action !== "string" || !Object.hasOwn(EDIT_OPS, edit.action)) return;
212
+ const name = edit.action as EditOpName;
213
+ const spec: EditOpSpec = EDIT_OPS[name];
214
+ const path = `edits[${index}]`;
215
+ const accepted = new Set([
216
+ ...spec.required,
217
+ ...(spec.optional ?? []),
218
+ ...(spec.destination ?? []),
219
+ ]);
220
+ for (const [field, declaration] of Object.entries(item.properties)) {
221
+ if (field === "action") continue;
222
+ const given = edit[field] !== undefined;
223
+ if (given && !accepted.has(field as EditItemField))
224
+ report(`${path}.${field}`, "is not allowed", `"${name}": ${describeEditOp(spec)}`);
225
+ else if (!given && spec.required.includes(field as EditItemField))
226
+ report(
227
+ `${path}.${field}`,
228
+ `is required for "${name}"`,
229
+ Reflect.get(declaration, "description"),
230
+ );
231
+ }
232
+ if (
233
+ spec.destination &&
234
+ spec.destination.filter((field) => edit[field] !== undefined).length !== 1
235
+ )
236
+ report(path, `expected exactly one of: ${spec.destination.join(", ")}`);
237
+
238
+ const body = edit.body;
239
+ if (accepted.has("body") && Array.isArray(body)) {
190
240
  if (body.length === 0) {
191
241
  report(
192
- `edits[${index}].body`,
242
+ `${path}.body`,
193
243
  "is empty",
194
- (op as Record<string, unknown>).op === "replace"
195
- ? EDIT_ISSUE_FIX.emptyReplace
196
- : EDIT_ISSUE_FIX.emptyBody,
244
+ name === "replace" ? EDIT_ISSUE_FIX.emptyReplace : EDIT_ISSUE_FIX.emptyBody,
197
245
  );
198
246
  }
199
247
  body.forEach((line, lineIndex) => {
200
248
  const unwritable = typeof line === "string" ? unwritableTextError(line) : undefined;
201
- if (unwritable) report(`edits[${index}].body[${lineIndex}]`, unwritable.message);
249
+ if (unwritable) report(`${path}.body[${lineIndex}]`, unwritable.message);
202
250
  });
203
251
  }
204
252
  for (const field of EDIT_ANCHOR_FIELDS) {
205
- const value = (op as Record<string, unknown> | null)?.[field];
206
- if (typeof value !== "string") continue;
207
- const token = parseAnchorToken(value);
253
+ const anchor = edit[field];
254
+ if (!accepted.has(field) || typeof anchor !== "string") continue;
255
+ const token = parseAnchorToken(anchor);
208
256
  if (token && !Number.isSafeInteger(token.line)) {
209
257
  report(
210
- `edits[${index}].${field}`,
258
+ `${path}.${field}`,
211
259
  "line number exceeds the safe integer range",
212
260
  EDIT_ISSUE_FIX.unsafeLine,
213
261
  );
214
262
  }
215
263
  if (token && token.hash.length !== hashLen) {
216
264
  report(
217
- `edits[${index}].${field}`,
265
+ `${path}.${field}`,
218
266
  `has ${token.hash.length} hash characters; hashLen is ${hashLen}`,
219
267
  EDIT_ISSUE_FIX.hashLength,
220
268
  );
@@ -223,32 +271,35 @@ function checkEditArguments(args: unknown, hashLen: number, report: ReportArgume
223
271
  });
224
272
  }
225
273
 
226
- /** Translate validated public operations into core edits, parsing numeric anchor positions. */
274
+ /**
275
+ * Translate validated public operations into core edits, parsing numeric anchor
276
+ * positions. Argument checks guarantee each op carries exactly the fields it takes.
277
+ */
227
278
  function toCoreEdits(ops: readonly EditOpInput[]): Edit[] {
228
279
  return ops.map((op) => {
229
- switch (op.op) {
280
+ switch (op.action) {
230
281
  case "replace":
231
282
  return {
232
283
  op: "replace",
233
- start: parseAnchor(op.anchor),
284
+ anchor: parseAnchor(op.anchor!),
234
285
  end: parseAnchor(op.end),
235
- body: op.body,
286
+ body: op.body!,
236
287
  };
237
288
  case "delete":
238
- return { op: "delete", start: parseAnchor(op.anchor), end: parseAnchor(op.end) };
289
+ return { op: "delete", anchor: parseAnchor(op.anchor!), end: parseAnchor(op.end) };
239
290
  case "copy":
240
291
  case "move": {
241
- const source = { op: op.op, start: parseAnchor(op.anchor), end: parseAnchor(op.end) };
242
- return "before" in op
292
+ const source = { op: op.action, anchor: parseAnchor(op.anchor!), end: parseAnchor(op.end) };
293
+ return op.before !== undefined
243
294
  ? { ...source, before: parseAnchor(op.before) }
244
- : { ...source, after: parseAnchor(op.after) };
295
+ : { ...source, after: parseAnchor(op.after!) };
245
296
  }
246
297
  case "insert_after":
247
298
  case "insert_before":
248
- return { op: op.op, anchor: parseAnchor(op.anchor), body: op.body };
299
+ return { op: op.action, anchor: parseAnchor(op.anchor!), body: op.body! };
249
300
  case "append":
250
301
  case "prepend":
251
- return { op: op.op, body: op.body };
302
+ return { op: op.action, body: op.body! };
252
303
  }
253
304
  });
254
305
  }
@@ -256,11 +307,11 @@ function toCoreEdits(ops: readonly EditOpInput[]): Edit[] {
256
307
  /** Call header with total/per-kind operation counts and the result's diff counts. */
257
308
  function editHeader(args: EditParams, theme: Theme, counts?: DiffCounts): string {
258
309
  let t = theme.fg("toolTitle", theme.bold("edit "));
259
- t += theme.fg("accent", args.path);
310
+ t += formatHeaderPath(args.path, theme);
260
311
  const edits = Array.isArray(args.edits) ? args.edits : [];
261
312
  const n = edits.length;
262
313
  if (n) {
263
- const opCounts: Record<EditOpInput["op"] | "unknown", number> = {
314
+ const opCounts: Record<EditOpName | "unknown", number> = {
264
315
  replace: 0,
265
316
  delete: 0,
266
317
  copy: 0,
@@ -273,7 +324,7 @@ function editHeader(args: EditParams, theme: Theme, counts?: DiffCounts): string
273
324
  };
274
325
  // Renderers receive partial arguments; fixed buckets keep one-pass counting O(1) in space.
275
326
  for (const edit of edits) {
276
- const kind = edit?.op;
327
+ const kind = edit?.action;
277
328
  if (typeof kind === "string" && Object.hasOwn(opCounts, kind)) opCounts[kind]++;
278
329
  else opCounts.unknown++;
279
330
  }
@@ -295,26 +346,29 @@ export function makeEditOverride(
295
346
  ) {
296
347
  // Schema, verification, and recovery use the registered configuration.
297
348
  const { hashLen, shiftRadius } = config;
298
- const parameters = createEditSchema(fusion !== undefined, hashLen);
349
+ const schema = buildEditSchema(hashLen);
350
+ const parameters = withThenRunSchema(schema, "edit", fusion !== undefined);
299
351
 
300
352
  return {
301
353
  name: "edit" as const,
302
354
  label: "edit",
303
355
  description: withThenRunDescription(
304
- "Edit file lines by LINE#HASH anchors checked against the current file. Each operation replaces whole lines. Use replace instead when the same change repeats in several places, or when only a fragment of a long line changes. On anchor failure, shows current context and recovery candidates; nothing is retried automatically.",
356
+ "Edit whole lines using LINE#HASH anchors checked against the current file. Use replace instead when the same change repeats in several places, or when only a fragment of a long line changes.",
305
357
  fusion !== undefined,
306
358
  ),
307
359
  promptSnippet: "Edit file lines using verified anchors",
308
360
  promptGuidelines: [
309
361
  "Batch all edits to one file into a single edit call.",
310
- "Do not re-read a file just to refresh anchors: anchors stay valid while their line number and content are unchanged. Re-read or grep only the lines an edit changed or shifted.",
362
+ "After edit or replace, get fresh anchors with read or grep before citing any line it changed. If it added or removed lines, also refresh anchors below the earliest affected line; anchors above it remain valid. If the affected positions are unknown, read or grep the lines you intend to cite.",
311
363
  ...(fusion ? ACTION_FUSION_GUIDELINES : []),
312
364
  ],
313
365
  parameters,
366
+ // Providers that support it bound the batch by the schema while sampling.
367
+ constrainedSampling: { type: "json_schema", strict: "prefer" } as const,
314
368
  prepareArguments: createArgumentPreparer(
315
369
  "edit",
316
370
  parameters,
317
- (args, report) => checkEditArguments(args, hashLen, report),
371
+ (args, report) => checkEditArguments(args, hashLen, schema.properties.edits.items, report),
318
372
  budgets,
319
373
  ),
320
374
  renderShell: "default" as const,
@@ -329,7 +383,7 @@ export function makeEditOverride(
329
383
  theme: Theme,
330
384
  context: EditRenderContext,
331
385
  ) {
332
- return renderMutationResult(result, options, theme, context, "Editing…", editHeader);
386
+ return renderMutationResult(result, options, theme, context, "Editing…", editHeader, "edit");
333
387
  },
334
388
 
335
389
  async execute(