@criogaid/pi-hashline-edit 0.6.1 β†’ 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +78 -369
  2. package/README.zh-CN.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +80 -0
  4. package/package.json +11 -6
  5. package/src/core/AGENTS.md +20 -0
  6. package/src/core/apply.test.ts +328 -161
  7. package/src/core/apply.ts +129 -95
  8. package/src/core/case-fold.test.ts +44 -0
  9. package/src/core/case-fold.ts +77 -0
  10. package/src/core/character-set.test.ts +103 -0
  11. package/src/core/character-set.ts +184 -0
  12. package/src/core/errors.test.ts +23 -0
  13. package/src/core/errors.ts +70 -4
  14. package/src/core/hash.test.ts +1 -25
  15. package/src/core/hash.ts +0 -5
  16. package/src/core/lines.ts +32 -7
  17. package/src/core/ranges.test.ts +41 -9
  18. package/src/core/ranges.ts +11 -4
  19. package/src/core/regex.ts +51 -0
  20. package/src/core/replace-schema.ts +41 -0
  21. package/src/core/replace.test.ts +90 -0
  22. package/src/core/replace.ts +40 -56
  23. package/src/core/search-analysis.test.ts +208 -0
  24. package/src/core/search-analysis.ts +379 -0
  25. package/src/core/search-matrix.test.ts +64 -0
  26. package/src/core/search-matrix.testing.ts +183 -0
  27. package/src/core/search-schema.ts +18 -0
  28. package/src/core/search.test.ts +145 -0
  29. package/src/core/search.ts +119 -0
  30. package/src/core/text.test.ts +16 -8
  31. package/src/core/text.ts +26 -6
  32. package/src/core/types.ts +20 -17
  33. package/src/index.ts +24 -16
  34. package/src/integration/config-registration.test.ts +42 -28
  35. package/src/integration/fusion-dispatch.test.ts +62 -127
  36. package/src/integration/grep-errors.test.ts +50 -0
  37. package/src/integration/grep-flags.test.ts +273 -0
  38. package/src/integration/grep-js-completeness.test.ts +218 -0
  39. package/src/integration/grep-line-candidates.test.ts +233 -0
  40. package/src/integration/grep-matrix.test.ts +121 -0
  41. package/src/integration/grep-order.test.ts +78 -0
  42. package/src/integration/grep-path-matrix.test.ts +133 -0
  43. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  44. package/src/integration/grep-regex.test.ts +407 -0
  45. package/src/integration/grep-rg.test.ts +294 -436
  46. package/src/integration/grep-scan-budget.test.ts +111 -0
  47. package/src/integration/grep-translation.test.ts +206 -0
  48. package/src/integration/large-text.test.ts +56 -1
  49. package/src/integration/model-budget-lifecycle.test.ts +137 -0
  50. package/src/integration/mutation-file-types.test.ts +12 -26
  51. package/src/integration/mutation-file-types.testing.ts +33 -0
  52. package/src/integration/npm-package.test.ts +17 -0
  53. package/src/integration/npm-package.testing.ts +97 -0
  54. package/src/integration/publication-read-changes.test.ts +376 -0
  55. package/src/integration/read-changes.test.ts +98 -0
  56. package/src/integration/replace-package.test.ts +17 -36
  57. package/src/integration/replace-package.testing.ts +36 -0
  58. package/src/integration/replace-worker-boundary.test.ts +117 -0
  59. package/src/integration/report-replay.test.ts +90 -0
  60. package/src/integration/utf8-errors.test.ts +46 -0
  61. package/src/pi/AGENTS.md +54 -0
  62. package/src/pi/action-fusion.test.ts +256 -251
  63. package/src/pi/action-fusion.ts +121 -332
  64. package/src/pi/anchor-format.test.ts +16 -0
  65. package/src/pi/anchor-format.ts +16 -3
  66. package/src/pi/argument-diagnostics.ts +478 -0
  67. package/src/pi/argument-error.testing.ts +46 -0
  68. package/src/pi/argument-error.ts +76 -0
  69. package/src/pi/argument-format.test.ts +197 -0
  70. package/src/pi/argument-validation.test.ts +780 -49
  71. package/src/pi/argument-validation.ts +55 -58
  72. package/src/pi/budgets.ts +48 -21
  73. package/src/pi/codemode.test.ts +96 -0
  74. package/src/pi/config.test.ts +29 -15
  75. package/src/pi/config.ts +27 -13
  76. package/src/pi/diagnostic-buffer.test.ts +51 -16
  77. package/src/pi/diagnostic-buffer.ts +13 -16
  78. package/src/pi/directory-sync.test.ts +4 -1
  79. package/src/pi/edit-tool.ts +103 -99
  80. package/src/pi/error-text.ts +39 -16
  81. package/src/pi/execute.test.ts +407 -429
  82. package/src/pi/extension-loading.test.ts +7 -27
  83. package/src/pi/extension-loading.testing.ts +2 -14
  84. package/src/pi/failure-context.test.ts +265 -88
  85. package/src/pi/failure-context.ts +165 -181
  86. package/src/pi/failure-path.test.ts +179 -117
  87. package/src/pi/file-commit.test.ts +90 -73
  88. package/src/pi/file-commit.ts +216 -178
  89. package/src/pi/file-read.test.ts +29 -0
  90. package/src/pi/file-read.ts +60 -0
  91. package/src/pi/file-revision.ts +25 -0
  92. package/src/pi/file-snapshot.test.ts +1 -1
  93. package/src/pi/fusion-card-interaction.test.ts +143 -0
  94. package/src/pi/fusion-card.test.ts +233 -51
  95. package/src/pi/fusion-card.ts +246 -142
  96. package/src/pi/grep-candidates.test.ts +127 -0
  97. package/src/pi/grep-candidates.ts +191 -0
  98. package/src/pi/grep-matrix.test.ts +83 -0
  99. package/src/pi/grep-order.test.ts +323 -0
  100. package/src/pi/grep-output.testing.ts +24 -0
  101. package/src/pi/grep-output.ts +187 -151
  102. package/src/pi/grep-render.ts +31 -25
  103. package/src/pi/grep-scope.ts +62 -54
  104. package/src/pi/grep-search.ts +327 -241
  105. package/src/pi/grep-tool.ts +126 -147
  106. package/src/pi/grep-worker.mjs +4 -0
  107. package/src/pi/grep-worker.ts +14 -0
  108. package/src/pi/grep.test.ts +813 -713
  109. package/src/pi/model-budgets.test.ts +43 -0
  110. package/src/pi/model-budgets.ts +44 -0
  111. package/src/pi/mutation-outcome.testing.ts +6 -7
  112. package/src/pi/mutation-result.test.ts +45 -91
  113. package/src/pi/mutation-result.ts +86 -114
  114. package/src/pi/mutation-runner.ts +81 -81
  115. package/src/pi/output-budgets.test.ts +175 -0
  116. package/src/pi/path.ts +10 -1
  117. package/src/pi/pi.test.ts +4 -5
  118. package/src/pi/read-tool.ts +108 -142
  119. package/src/pi/read.test.ts +155 -96
  120. package/src/pi/regex-worker-contract.ts +55 -0
  121. package/src/pi/regex-worker.ts +95 -0
  122. package/src/pi/registration.test.ts +148 -124
  123. package/src/pi/render.test.ts +361 -84
  124. package/src/pi/render.ts +150 -32
  125. package/src/pi/replace-regex.ts +13 -48
  126. package/src/pi/replace-tool.ts +52 -158
  127. package/src/pi/replace-worker-contract.ts +10 -0
  128. package/src/pi/replace-worker.ts +12 -8
  129. package/src/pi/replace.test.ts +191 -340
  130. package/src/pi/report-cause.ts +103 -0
  131. package/src/pi/report-failure.testing.ts +20 -0
  132. package/src/pi/report-schema.ts +524 -0
  133. package/src/pi/report.test.ts +343 -0
  134. package/src/pi/report.ts +285 -0
  135. package/src/pi/result-safety.test.ts +216 -481
  136. package/src/pi/rg-process.test.ts +101 -76
  137. package/src/pi/rg-process.ts +130 -177
  138. package/src/pi/rg-regex.test.ts +67 -0
  139. package/src/pi/rg-regex.ts +715 -0
  140. package/src/pi/text-stream.test.ts +97 -69
  141. package/src/pi/text-stream.ts +97 -76
  142. package/src/pi/tool-call.testing.ts +20 -46
  143. package/src/pi/write-tool.ts +50 -41
  144. package/src/pi/write.test.ts +71 -95
  145. package/src/testing/extension-loader.testing.ts +24 -0
  146. package/src/testing/installation.testing.ts +77 -0
  147. package/src/testing/process.testing.ts +33 -0
  148. package/src/testing/regex-host.testing.ts +20 -0
  149. package/src/testing/regex-translation-corpus.ts +324 -0
  150. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  151. package/src/testing/run-tests.ts +47 -0
  152. package/src/testing/session.testing.ts +127 -0
  153. package/src/integration/forget-grep.test.ts +0 -98
  154. package/src/pi/forget-tool.ts +0 -268
  155. package/src/pi/forget.test.ts +0 -343
  156. package/src/pi/forget.testing.ts +0 -273
  157. package/src/pi/rg-line-ranges.test.ts +0 -66
  158. package/src/pi/rg-line-ranges.ts +0 -75
  159. package/src/pi/rg-match-bytes.ts +0 -95
  160. package/src/pi/rg-text-view.ts +0 -192
  161. package/src/pi/tool-prompts.ts +0 -15
@@ -1,19 +1,20 @@
1
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.
2
+ * Shared tool argument boundary. Pi owns preparation and acceptance; tool checks
3
+ * report semantic issues. Failure-only diagnostics observe Pi's prepared value,
4
+ * then project and aggregate the declared schema in argument-diagnostics.ts.
5
+ * Pi still validates returned arguments in its mandatory tool-call pipeline.
6
+ * Tool schemas have no cross-field constraints.
8
7
  */
9
8
  import { validateToolArguments, type ToolCall } from "@earendil-works/pi-ai";
10
9
  import { ObjectOptions, Type, type Static, type TObject, type TSchema } from "typebox";
11
10
  import { errorMessage } from "../core/errors.ts";
12
- import { MAX_BLOCK_BYTES } from "./budgets.ts";
13
- import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
14
- import { invalidArgument } from "./error-text.ts";
11
+ import { diagnoseArguments } from "./argument-diagnostics.ts";
12
+ import { formatArgumentError } from "./argument-error.ts";
13
+ import type { OutputBudgetProvider } from "./budgets.ts";
14
+ import type { ArgumentIssue, ReportTool } from "./report-schema.ts";
15
15
 
16
- export type ReportArgumentIssue = (field: string, reason: string) => void;
16
+ /** Report one semantic issue: what is wrong (a fact), and how to correct it when the fact alone does not say. */
17
+ export type ReportArgumentIssue = (field: string, reason: string, fix?: string) => void;
17
18
  type CheckArguments = (args: unknown, report: ReportArgumentIssue) => void;
18
19
 
19
20
  /** Inspect arrays and the singleton objects Pi may coerce, without changing input. */
@@ -21,30 +22,12 @@ export function argumentItems(value: unknown): readonly unknown[] {
21
22
  return Array.isArray(value) ? value : value !== null && typeof value === "object" ? [value] : [];
22
23
  }
23
24
 
24
- /**
25
- * Compact the exact argument suffix emitted by Pi 0.99.1's validateToolArguments.
26
- * If Pi changes that format, preserve its full error unchanged, including multiline JSON.
27
- */
28
- function schemaDiagnostic(error: unknown, args: unknown): string {
29
- const message = errorMessage(error);
30
- const label = "Received arguments:";
31
- const suffix = `\n\n${label}\n${JSON.stringify(args, null, 2)}`;
32
- if (!message.endsWith(suffix)) return message;
33
- return `${message.slice(0, -suffix.length)}\n${label} ${JSON.stringify(args)}`;
34
- }
35
-
36
25
  export function createArgumentPreparer<T extends TObject>(
37
- name: string,
26
+ name: ReportTool,
38
27
  parameters: T,
39
- check?: CheckArguments,
28
+ check: CheckArguments | undefined,
29
+ budgets: OutputBudgetProvider,
40
30
  ): (args: unknown) => Static<T> {
41
- const fields = Object.keys(parameters.properties);
42
- const options = { additionalProperties: ObjectOptions(parameters).additionalProperties };
43
- const fieldSchemas = fields.map((field) => ({
44
- field,
45
- schema: Type.Pick(parameters, [field], options),
46
- }));
47
- const unknownFieldsSchema = Type.Omit(parameters, fields, options);
48
31
  const validate = (schema: TSchema, args: unknown): unknown =>
49
32
  validateToolArguments(
50
33
  { name, parameters: schema, description: "" },
@@ -65,37 +48,51 @@ export function createArgumentPreparer<T extends TObject>(
65
48
  } catch (error) {
66
49
  schemaFailure = error;
67
50
  }
68
- const diagnostics = new DiagnosticBuffer(MAX_BLOCK_BYTES);
69
- let hasIssues = schemaFailure !== undefined;
70
- check?.(checked, (field, reason) => {
71
- hasIssues = true;
72
- diagnostics.append(`${invalidArgument(field, reason).message}\n`);
73
- });
74
51
  if (schemaFailure !== undefined) {
75
- if (typeof args === "object" && args !== null && !Array.isArray(args)) {
76
- const entries = Object.entries(args);
77
- const diagnose = (schema: TSchema, value: unknown) => {
78
- try {
79
- validate(schema, value);
80
- } catch (error) {
81
- diagnostics.append(`${schemaDiagnostic(error, value)}\n`);
82
- }
83
- };
84
- for (const { field, schema } of fieldSchemas) {
85
- diagnose(schema, Object.fromEntries(entries.filter(([key]) => key === field)));
86
- }
87
- diagnose(
88
- unknownFieldsSchema,
89
- Object.fromEntries(entries.filter(([key]) => !fields.includes(key))),
52
+ let observation: { readonly value: unknown } | undefined;
53
+ // Pi does not expose failed prepared values. A successful allOf refinement
54
+ // observes its error pass without changing coercion, null handling or acceptance.
55
+ const observer = Type.Object(parameters.properties, {
56
+ ...ObjectOptions(parameters),
57
+ allOf: [
58
+ Type.Refine(Type.Unknown(), (value: unknown) => {
59
+ observation = { value };
60
+ return true;
61
+ }),
62
+ ],
63
+ });
64
+ try {
65
+ validate(observer, args);
66
+ } catch {
67
+ // The original schema already failed; this call only observes preparation.
68
+ }
69
+ if (!observation) {
70
+ throw new Error(
71
+ formatArgumentError(
72
+ [{ field: "$", reason: errorMessage(schemaFailure) }],
73
+ false,
74
+ budgets(),
75
+ ),
76
+ { cause: schemaFailure },
90
77
  );
91
- } else {
92
- diagnostics.append(schemaDiagnostic(schemaFailure, args));
93
78
  }
94
- diagnostics.append(
95
- "\nPi limits schema diagnostics within each field; additional errors may remain.\n",
96
- );
79
+ checked = observation.value;
80
+ }
81
+ const issues: ArgumentIssue[] = [];
82
+ check?.(checked, (field, reason, fix) =>
83
+ issues.push(fix === undefined ? { field, reason } : { field, reason, fix }),
84
+ );
85
+ if (schemaFailure === undefined && issues.length === 0) return args as Static<T>;
86
+ const result = diagnoseArguments(parameters, checked, issues, schemaFailure !== undefined);
87
+ const reported =
88
+ result.issues.length > 0
89
+ ? result.issues
90
+ : [{ field: "$", reason: errorMessage(schemaFailure) }];
91
+ if (schemaFailure !== undefined || result.issues.length > 0) {
92
+ throw new Error(formatArgumentError(reported, result.limited, budgets()), {
93
+ cause: schemaFailure,
94
+ });
97
95
  }
98
- if (hasIssues) throw new Error(diagnostics.toString().trimEnd(), { cause: schemaFailure });
99
96
  // Keep Pi's preparation contract: the framework performs its own coercion next.
100
97
  return args as Static<T>;
101
98
  };
package/src/pi/budgets.ts CHANGED
@@ -1,28 +1,55 @@
1
1
  /**
2
- * Fixed model-facing output budgets.
3
- *
4
- * README "Output budgets" documents each value; change both together. Result
5
- * and notice text derive their size wording from these constants. Budgets that
6
- * users can configure (read line and byte limits, grep line limit) live in the
7
- * settings schema in config.ts; Pi's own total-output limit stays with Pi.
8
- *
9
- * @module pi-hashline-edit/pi
2
+ * Model-facing byte budgets. README "Output budgets" documents this policy.
3
+ * The context window is a capacity hint, not a tokenizer or remaining-context counter.
10
4
  */
11
5
 
12
- /** grep line preview, in UTF-16 units, excluding its partial-line label. */
13
- export const GREP_MAX_LINE_LENGTH = 500;
6
+ const BYTES_PER_CONTEXT_TOKEN = 1;
7
+ const BLOCK_SHARE = 4;
8
+ const FIELD_SHARE = 4;
9
+ const UTF16_PREVIEW_BYTES = 4;
10
+ // Keep JSON envelopes and diagnostic omission markers usable for tiny declared windows.
11
+ const MIN_BLOCK_BYTES = 512;
12
+ const MIN_FIELD_BYTES = 128;
13
+ // Model-derived content budgets never exceed the explicit read cap's ceiling; config.ts
14
+ // reuses this constant for the read.maxKiB range, so automatic sizing may approach but
15
+ // not surpass what a user could configure, keeping one absolute bound per call.
16
+ export const MAX_CONTENT_KIB = 4096;
17
+ const MAX_CONTENT_BYTES = MAX_CONTENT_KIB * 1024;
14
18
 
15
- /** Each diagnostic or anchor block: argument errors, failure details, input-anchor checks, candidate neighborhoods, mutation anchors. */
16
- export const MAX_BLOCK_BYTES = 16 * 1024;
17
- /** One recovery-candidate or cited row inside a failure diagnostic. */
18
- export const MAX_RECOVERY_CANDIDATE_BYTES = 4 * 1024;
19
- /** grep search diagnostics appended to a result. */
20
- export const MAX_SEARCH_DIAGNOSTIC_BYTES = 4 * 1024;
19
+ const fallbackBudgets = {
20
+ readBytes: 256 * 1024,
21
+ grepBytes: 50 * 1024,
22
+ blockBytes: 16 * 1024,
23
+ fieldBytes: 4 * 1024,
24
+ grepPreviewUnits: 500,
25
+ };
26
+ export const DEFAULT_OUTPUT_BUDGETS = Object.freeze(fallbackBudgets);
27
+ export type OutputBudgets = typeof DEFAULT_OUTPUT_BUDGETS;
28
+ export type OutputBudgetProvider = () => OutputBudgets;
21
29
 
22
- /** Size wording for notices, e.g. `16 KiB`. */
23
- export function formatKiB(bytes: number): string {
24
- return `${bytes / 1024} KiB`;
30
+ /** Unknown or invalid capacity uses the bounded defaults; each returned budget is immutable. */
31
+ export function outputBudgetsFor(contextWindow: number | undefined): OutputBudgets {
32
+ if (contextWindow === undefined || !Number.isSafeInteger(contextWindow) || contextWindow <= 0) {
33
+ return DEFAULT_OUTPUT_BUDGETS;
34
+ }
35
+ const contentBytes = Math.min(contextWindow * BYTES_PER_CONTEXT_TOKEN, MAX_CONTENT_BYTES);
36
+ const blockBytes = Math.max(MIN_BLOCK_BYTES, Math.floor(contentBytes / BLOCK_SHARE));
37
+ const fieldBytes = Math.max(MIN_FIELD_BYTES, Math.floor(blockBytes / FIELD_SHARE));
38
+ return Object.freeze({
39
+ readBytes: contentBytes,
40
+ grepBytes: contentBytes,
41
+ blockBytes,
42
+ fieldBytes,
43
+ grepPreviewUnits: Math.floor(fieldBytes / UTF16_PREVIEW_BYTES),
44
+ });
25
45
  }
26
46
 
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;
47
+ /** Standalone tool factories have no session model until a provider is supplied. */
48
+ export const defaultOutputBudgets: OutputBudgetProvider = () => DEFAULT_OUTPUT_BUDGETS;
49
+
50
+ const MIB = 1024 * 1024;
51
+
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
+ }
@@ -0,0 +1,96 @@
1
+ import assert from "node:assert/strict";
2
+ import { readFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { test } from "node:test";
5
+ import { Type } from "typebox";
6
+ import { createCodemodeToolDefinition } from "../../node_modules/@earendil-works/pi-coding-agent/dist/extensions/codemode/tool.js";
7
+ import { openTestSession, responseStream, SESSION_TIMEOUT_MS } from "../testing/session.testing.ts";
8
+ import { createActionFusionExecutor } from "./action-fusion.ts";
9
+ import { makeWriteOverride } from "./write-tool.ts";
10
+
11
+ for (const entry of ["direct", "codemode"] as const) {
12
+ test(`${entry} mutation waits on then_run β†’ the call and model continuation stay pending`, {
13
+ timeout: SESSION_TIMEOUT_MS,
14
+ }, async (t) => {
15
+ const started = Promise.withResolvers<void>();
16
+ const finished = Promise.withResolvers<void>();
17
+ const { cwd, session, model } = await openTestSession(t, {
18
+ tools: ["write", "bash", "codemode"],
19
+ configure(pi, cwd) {
20
+ pi.registerTool(makeWriteOverride(cwd, createActionFusionExecutor()));
21
+ pi.registerTool(createCodemodeToolDefinition());
22
+ pi.registerTool({
23
+ name: "bash",
24
+ label: "bash",
25
+ description: "Hold the requested command until the test releases it",
26
+ parameters: Type.Object({ command: Type.String() }),
27
+ async execute() {
28
+ started.resolve();
29
+ await finished.promise;
30
+ return { content: [{ type: "text", text: "checked" }], details: undefined };
31
+ },
32
+ });
33
+ },
34
+ });
35
+ const ended: string[] = [];
36
+ session.subscribe((event) => {
37
+ if (event.type === "tool_execution_end") ended.push(event.toolName);
38
+ });
39
+ const args = {
40
+ path: "saved.txt",
41
+ mode: "create",
42
+ content: "saved\n",
43
+ then_run: { command: "held command" },
44
+ };
45
+ let requests = 0;
46
+ session.agent.streamFunction = () => {
47
+ const first = requests++ === 0;
48
+ assert.ok(requests <= 2, "Unexpected model continuation");
49
+ return responseStream(model, {
50
+ content: first
51
+ ? [
52
+ {
53
+ type: "toolCall",
54
+ id: "mutation",
55
+ name: entry === "direct" ? "write" : "codemode",
56
+ arguments:
57
+ entry === "direct"
58
+ ? args
59
+ : {
60
+ code: `text(await tools.write(${JSON.stringify(args)})); text("AFTER_WRITE");`,
61
+ },
62
+ },
63
+ ]
64
+ : [{ type: "text", text: "Done." }],
65
+ stopReason: first ? "toolUse" : "stop",
66
+ });
67
+ };
68
+ const pending = session.prompt("Run the mutation and its command.");
69
+ try {
70
+ await started.promise;
71
+ assert.equal(await readFile(join(cwd, "saved.txt"), "utf8"), "saved\n");
72
+ assert.equal(requests, 1, "The model must not continue before then_run ends");
73
+ assert.ok(!ended.includes("write"));
74
+ assert.ok(!ended.includes("codemode"));
75
+ } finally {
76
+ finished.resolve();
77
+ await pending;
78
+ }
79
+ assert.equal(session.agent.state.errorMessage, undefined);
80
+ assert.equal(requests, 2);
81
+ assert.ok(ended.includes("write"));
82
+ const result = session.agent.state.messages.find(
83
+ (message) => message.role === "toolResult" && message.toolCallId === "mutation",
84
+ );
85
+ assert.ok(result?.role === "toolResult");
86
+ assert.equal(result.isError, false);
87
+ if (entry === "codemode") {
88
+ assert.ok(ended.includes("codemode"));
89
+ const output = result.content
90
+ .filter((block) => block.type === "text")
91
+ .map((block) => block.text)
92
+ .join("\n");
93
+ assert.match(output, /"then_run":\s*\{\s*"status":\s*"succeeded"[\s\S]*AFTER_WRITE/);
94
+ }
95
+ });
96
+ }
@@ -32,11 +32,10 @@ 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
- read: { defaultLimit: 500, maxKiB: 256 },
39
- grep: { defaultLimit: 100, defaultContext: 0 },
37
+ read: { defaultLimit: 500, maxKiB: undefined },
38
+ grep: { ...DEFAULT_CONFIG.grep, defaultLimit: 100, defaultContext: 0 },
40
39
  replace: { regexTimeoutMs: 5_000 },
41
40
  });
42
41
  });
@@ -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", () =>
@@ -83,14 +81,18 @@ test("tool groups resolve each setting independently", () =>
83
81
  await write({
84
82
  hashlineEdit: {
85
83
  read: { defaultLimit: 50, maxKiB: 0 },
86
- grep: { defaultContext: 21, defaultLimit: 7 },
84
+ grep: { ...DEFAULT_CONFIG.grep, defaultContext: 21, defaultLimit: 7 },
87
85
  replace: "fast",
88
86
  },
89
87
  });
90
88
  assert.deepEqual(loadConfig(root), {
91
89
  ...DEFAULT_CONFIG,
92
90
  read: { defaultLimit: 50, maxKiB: DEFAULT_CONFIG.read.maxKiB },
93
- grep: { defaultLimit: 7, defaultContext: DEFAULT_CONFIG.grep.defaultContext },
91
+ grep: {
92
+ ...DEFAULT_CONFIG.grep,
93
+ defaultLimit: 7,
94
+ defaultContext: DEFAULT_CONFIG.grep.defaultContext,
95
+ },
94
96
  });
95
97
  await write({ hashlineEdit: { replace: { regexTimeoutMs: 20_000 } } });
96
98
  assert.equal(loadConfig(root).replace.regexTimeoutMs, 20_000);
@@ -105,8 +107,8 @@ test("project settings replace global groups while absent project settings use g
105
107
  hashLen: 8,
106
108
  shiftRadius: 0,
107
109
  read: { defaultLimit: 7, maxKiB: 2 },
108
- grep: { defaultLimit: 3, defaultContext: 2 },
109
- replace: { regexTimeoutMs: 1_000 },
110
+ grep: { ...DEFAULT_CONFIG.grep, defaultLimit: 3, defaultContext: 2 },
111
+ replace: { regexTimeoutMs: 3_000 },
110
112
  };
111
113
  await writeFile(
112
114
  join(agentDir, "settings.json"),
@@ -127,6 +129,18 @@ test("project settings replace global groups while absent project settings use g
127
129
  assert.deepEqual(loadConfig(root), DEFAULT_CONFIG);
128
130
  }));
129
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
+
130
144
  test("invalid tool groups default independently without discarding valid sibling groups", () =>
131
145
  withSettings(async (write, root) => {
132
146
  const configured = {
@@ -135,8 +149,8 @@ test("invalid tool groups default independently without discarding valid sibling
135
149
  hashLen: 6,
136
150
  shiftRadius: 0,
137
151
  read: { defaultLimit: 2, maxKiB: 1 },
138
- grep: { defaultLimit: 3, defaultContext: 2 },
139
- replace: { regexTimeoutMs: 1_000 },
152
+ grep: { ...DEFAULT_CONFIG.grep, defaultLimit: 3, defaultContext: 2 },
153
+ replace: { regexTimeoutMs: 3_000 },
140
154
  };
141
155
  for (const group of ["read", "grep", "replace"] as const) {
142
156
  for (const value of [null, [], 42, "invalid", true]) {
@@ -166,8 +180,8 @@ test("tool settings accept their boundary values and default invalid leaves", ()
166
180
  {
167
181
  group: "replace",
168
182
  key: "regexTimeoutMs",
169
- valid: [1_000, 300_000],
170
- invalid: [999, 300_001, 1000.5, "1000", null],
183
+ valid: [3_000, 300_000],
184
+ invalid: [2_999, 300_001, 3000.5, "3000", null],
171
185
  },
172
186
  ] as const;
173
187
  for (const { group, key, valid, invalid } of cases) {
package/src/pi/config.ts CHANGED
@@ -13,6 +13,7 @@ import { Type, type Static, type TSchema } from "typebox";
13
13
  import { Value } from "typebox/value";
14
14
  import { HASH_LEN_MAX, HASH_LEN_MIN } from "../core/hash.ts";
15
15
  import { GREP_CONTEXT_RANGE, integerRange, POSITIVE_SAFE_INTEGER } from "./schema.ts";
16
+ import { MAX_CONTENT_KIB } from "./budgets.ts";
16
17
 
17
18
  function integerSetting(
18
19
  range: ReturnType<typeof integerRange>,
@@ -22,8 +23,16 @@ function integerSetting(
22
23
  return Type.Number({ ...range, default: value, description });
23
24
  }
24
25
 
26
+ // The floor exceeds measured worker startup+handshake on slower Windows hosts.
27
+ // README's regex timeout settings link to this shared definition.
28
+ const regexTimeoutSetting = integerSetting(
29
+ integerRange(3_000, 300_000),
30
+ 5_000,
31
+ "Time limit for one isolated regex evaluation, in milliseconds.",
32
+ );
33
+
25
34
  /** Settings schema: the single source of setting types, bounds, and defaults. */
26
- export const configSchema = Type.Object({
35
+ const configSchema = Type.Object({
27
36
  enabled: Type.Boolean({
28
37
  default: true,
29
38
  description:
@@ -33,10 +42,6 @@ export const configSchema = Type.Object({
33
42
  default: true,
34
43
  description: "Expose optional then_run commands after edit/replace/write.",
35
44
  }),
36
- forget: Type.Boolean({
37
- default: false,
38
- description: "Register forget and tag eligible read/grep results for context removal.",
39
- }),
40
45
  hashLen: integerSetting(
41
46
  integerRange(HASH_LEN_MIN, HASH_LEN_MAX),
42
47
  4,
@@ -53,7 +58,13 @@ export const configSchema = Type.Object({
53
58
  500,
54
59
  "Lines returned when limit is omitted.",
55
60
  ),
56
- maxKiB: integerSetting(integerRange(1, 4096), 256, "Anchored text returned per call, in KiB."),
61
+ maxKiB: Type.Optional(
62
+ Type.Number({
63
+ ...integerRange(1, MAX_CONTENT_KIB),
64
+ description:
65
+ "Explicit anchored-text byte cap in KiB; omitted uses the selected model capacity.",
66
+ }),
67
+ ),
57
68
  }),
58
69
  grep: Type.Object({
59
70
  defaultLimit: integerSetting(
@@ -66,13 +77,10 @@ export const configSchema = Type.Object({
66
77
  0,
67
78
  "Context lines shown when context is omitted.",
68
79
  ),
80
+ regexTimeoutMs: regexTimeoutSetting,
69
81
  }),
70
82
  replace: Type.Object({
71
- regexTimeoutMs: integerSetting(
72
- integerRange(1_000, 300_000),
73
- 5_000,
74
- "Time limit for one regex batch, in milliseconds.",
75
- ),
83
+ regexTimeoutMs: regexTimeoutSetting,
76
84
  }),
77
85
  });
78
86
 
@@ -95,7 +103,9 @@ function resolveSetting<T extends TSchema>(schema: T, value: unknown): Static<T>
95
103
  ]),
96
104
  ) as Static<T>;
97
105
  }
98
- return (Value.Check(schema, value) ? value : Value.Create(schema)) as Static<T>;
106
+ return (
107
+ Value.Check(schema, value) ? value : Type.IsOptional(schema) ? undefined : Value.Create(schema)
108
+ ) as Static<T>;
99
109
  }
100
110
 
101
111
  export const DEFAULT_CONFIG: HashlineEditConfig = resolveSetting(configSchema, {});
@@ -117,5 +127,9 @@ function readSettings(filePath: string): Record<string, unknown> {
117
127
  export function loadConfig(cwd?: string): HashlineEditConfig {
118
128
  const globalSettings = readSettings(path.join(getAgentDir(), "settings.json"));
119
129
  const projectSettings = cwd ? readSettings(path.join(cwd, ".pi", "settings.json")) : {};
120
- 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);
121
135
  }
@@ -1,16 +1,19 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { test } from "node:test";
3
3
  import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
4
- import { MAX_SEARCH_DIAGNOSTIC_BYTES } from "./budgets.ts";
5
- import { formatSearchWarnings } from "./grep-output.ts";
6
- import { MAX_RG_STDERR_BYTES, runText } from "./rg-process.ts";
4
+ import { DEFAULT_OUTPUT_BUDGETS } from "./budgets.ts";
5
+ import { assembleGrepOutput } from "./grep-output.ts";
6
+ import { MAX_RG_STDERR_BYTES, runRgPaths } from "./rg-process.ts";
7
+ import { mkdtemp, writeFile, rm } from "node:fs/promises";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
7
10
 
8
11
  const diagnostic = (size: number) =>
9
12
  `regex parse error:\n${"intermediate context δΈ­πŸ™‚\n".repeat(size)}error: unclosed group\n`;
10
13
 
11
14
  test("bounded diagnostics retain opening context and the final cause across streamed chunks", () => {
12
- const source = diagnostic(MAX_SEARCH_DIAGNOSTIC_BYTES);
13
- const buffer = new DiagnosticBuffer(MAX_SEARCH_DIAGNOSTIC_BYTES);
15
+ const source = diagnostic(DEFAULT_OUTPUT_BUDGETS.fieldBytes);
16
+ const buffer = new DiagnosticBuffer(DEFAULT_OUTPUT_BUDGETS.fieldBytes);
14
17
  const chunkChars = 113;
15
18
  for (let offset = 0; offset < source.length; offset += chunkChars) {
16
19
  buffer.append(source.slice(offset, offset + chunkChars));
@@ -19,31 +22,63 @@ test("bounded diagnostics retain opening context and the final cause across stre
19
22
  assert.match(result, /^regex parse error:/);
20
23
  assert.match(result, /error: unclosed group\n$/);
21
24
  assert.match(result, /omitted/i);
22
- assert.ok(Buffer.byteLength(result) <= MAX_SEARCH_DIAGNOSTIC_BYTES);
25
+ assert.ok(Buffer.byteLength(result) <= DEFAULT_OUTPUT_BUDGETS.fieldBytes);
26
+ });
27
+
28
+ test("a diagnostic is one oversized line β†’ retain its opening and final cause without splitting UTF-8", () => {
29
+ const source = `opening cause: ${"δΈ­πŸ™‚".repeat(DEFAULT_OUTPUT_BUDGETS.fieldBytes)}; final recovery`;
30
+ const buffer = new DiagnosticBuffer(DEFAULT_OUTPUT_BUDGETS.fieldBytes);
31
+ buffer.append(source);
32
+ const result = buffer.toString();
33
+ assert.match(result, /^opening cause:/);
34
+ assert.match(result, /final recovery$/);
35
+ assert.match(result, /omitted/);
36
+ assert.doesNotMatch(result, /οΏ½/);
37
+ assert.ok(Buffer.byteLength(result) <= DEFAULT_OUTPUT_BUDGETS.fieldBytes);
23
38
  });
24
39
 
25
40
  test("diagnostics within the budget are unchanged", () => {
26
- const buffer = new DiagnosticBuffer(MAX_SEARCH_DIAGNOSTIC_BYTES);
41
+ const buffer = new DiagnosticBuffer(DEFAULT_OUTPUT_BUDGETS.fieldBytes);
27
42
  const source = "path: ζƒι™δΈθΆ³πŸ™‚\nretry with another path\n";
28
43
  for (const point of source) buffer.append(point);
29
44
  assert.equal(buffer.toString(), source);
30
45
  });
31
46
 
32
47
  test("search warning aggregation retains the final cause and labels truncation", () => {
33
- const result = formatSearchWarnings([diagnostic(MAX_SEARCH_DIAGNOSTIC_BYTES)]);
34
- assert.match(result, /Search incomplete/);
35
- assert.match(result, /regex parse error:/);
36
- assert.match(result, /error: unclosed group/);
37
- assert.match(result, /omitted/i);
48
+ const { facts, payload } = assembleGrepOutput({
49
+ budget: DEFAULT_OUTPUT_BUDGETS,
50
+ formatted: {
51
+ blocks: [{ lines: ["confirmed match"] }],
52
+ matches: 1,
53
+ files: 1,
54
+ },
55
+ warnings: [diagnostic(DEFAULT_OUTPUT_BUDGETS.fieldBytes)],
56
+ outputMode: "content",
57
+ matchLimitReached: false,
58
+ effectiveLimit: 100,
59
+ });
60
+ assert.equal(payload, "confirmed match");
61
+ assert.match(facts.diagnostics ?? "", /regex parse error:/);
62
+ assert.match(facts.diagnostics ?? "", /error: unclosed group/);
63
+ assert.match(facts.diagnostics ?? "", /omitted/i);
38
64
  });
39
65
 
40
- test("stderr collection preserves UTF-8 and reports overflow without losing the final cause", async () => {
66
+ test("stderr overflow β†’ UTF-8 opening and final cause survive", async (t) => {
67
+ const directory = await mkdtemp(join(tmpdir(), "hl-rg-stderr-"));
68
+ t.after(() => rm(directory, { recursive: true, force: true }));
69
+ const path = join(directory, "stderr.txt");
41
70
  for (const source of ["ζƒι™δΈθΆ³πŸ™‚\n", diagnostic(MAX_RG_STDERR_BYTES)]) {
42
- const result = await runText(
71
+ await writeFile(path, source);
72
+ const result = await runRgPaths(
43
73
  process.execPath,
44
- ["--input-type=module", "--eval", "process.stdin.pipe(process.stderr)"],
45
- Buffer.from(source),
74
+ [
75
+ "--input-type=module",
76
+ "--eval",
77
+ "import { createReadStream } from 'node:fs'; createReadStream(process.argv[1]).pipe(process.stderr)",
78
+ path,
79
+ ],
46
80
  AbortSignal.timeout(10000),
81
+ () => true,
47
82
  );
48
83
  if (Buffer.byteLength(source) <= MAX_RG_STDERR_BYTES) {
49
84
  assert.equal(result.stderr, source);