@criogaid/pi-hashline-edit 0.6.1 → 0.7.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 (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +55 -57
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +7 -27
  76. package/src/pi/extension-loading.testing.ts +2 -14
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. 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 { defaultOutputBudgets, 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
28
  check?: CheckArguments,
29
+ budgets: OutputBudgetProvider = defaultOutputBudgets,
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,52 @@ 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
+ name,
73
+ [{ field: "$", reason: errorMessage(schemaFailure) }],
74
+ false,
75
+ budgets(),
76
+ ),
77
+ { cause: schemaFailure },
90
78
  );
91
- } else {
92
- diagnostics.append(schemaDiagnostic(schemaFailure, args));
93
79
  }
94
- diagnostics.append(
95
- "\nPi limits schema diagnostics within each field; additional errors may remain.\n",
96
- );
80
+ checked = observation.value;
81
+ }
82
+ const issues: ArgumentIssue[] = [];
83
+ check?.(checked, (field, reason, fix) =>
84
+ issues.push(fix === undefined ? { field, reason } : { field, reason, fix }),
85
+ );
86
+ if (schemaFailure === undefined && issues.length === 0) return args as Static<T>;
87
+ const result = diagnoseArguments(parameters, checked, issues, schemaFailure !== undefined);
88
+ const reported =
89
+ result.issues.length > 0
90
+ ? result.issues
91
+ : [{ field: "$", reason: errorMessage(schemaFailure) }];
92
+ if (schemaFailure !== undefined || result.issues.length > 0) {
93
+ throw new Error(formatArgumentError(name, reported, result.limited, budgets()), {
94
+ cause: schemaFailure,
95
+ });
97
96
  }
98
- if (hasIssues) throw new Error(diagnostics.toString().trimEnd(), { cause: schemaFailure });
99
97
  // Keep Pi's preparation contract: the framework performs its own coercion next.
100
98
  return args as Static<T>;
101
99
  };
package/src/pi/budgets.ts CHANGED
@@ -1,23 +1,52 @@
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.
4
+ * This module also loads in the replacement worker; keep it free of Pi runtime imports.
10
5
  */
11
6
 
12
- /** grep line preview, in UTF-16 units, excluding its partial-line label. */
13
- export const GREP_MAX_LINE_LENGTH = 500;
7
+ const BYTES_PER_CONTEXT_TOKEN = 1;
8
+ const BLOCK_SHARE = 4;
9
+ const FIELD_SHARE = 4;
10
+ const UTF16_PREVIEW_BYTES = 4;
11
+ // Keep JSON envelopes and diagnostic omission markers usable for tiny declared windows.
12
+ const MIN_BLOCK_BYTES = 512;
13
+ const MIN_FIELD_BYTES = 128;
14
+ // Model-derived content budgets never exceed the explicit read cap's ceiling; config.ts
15
+ // reuses this constant for the read.maxKiB range, so automatic sizing may approach but
16
+ // not surpass what a user could configure, keeping one absolute bound per call.
17
+ export const MAX_CONTENT_KIB = 4096;
18
+ const MAX_CONTENT_BYTES = MAX_CONTENT_KIB * 1024;
14
19
 
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;
20
+ const fallbackBudgets = {
21
+ readBytes: 256 * 1024,
22
+ grepBytes: 50 * 1024,
23
+ blockBytes: 16 * 1024,
24
+ fieldBytes: 4 * 1024,
25
+ grepPreviewUnits: 500,
26
+ };
27
+ export const DEFAULT_OUTPUT_BUDGETS = Object.freeze(fallbackBudgets);
28
+ export type OutputBudgets = typeof DEFAULT_OUTPUT_BUDGETS;
29
+ export type OutputBudgetProvider = () => OutputBudgets;
30
+
31
+ /** Unknown or invalid capacity uses the bounded defaults; each returned budget is immutable. */
32
+ export function outputBudgetsFor(contextWindow: number | undefined): OutputBudgets {
33
+ if (contextWindow === undefined || !Number.isSafeInteger(contextWindow) || contextWindow <= 0) {
34
+ return DEFAULT_OUTPUT_BUDGETS;
35
+ }
36
+ const contentBytes = Math.min(contextWindow * BYTES_PER_CONTEXT_TOKEN, MAX_CONTENT_BYTES);
37
+ const blockBytes = Math.max(MIN_BLOCK_BYTES, Math.floor(contentBytes / BLOCK_SHARE));
38
+ const fieldBytes = Math.max(MIN_FIELD_BYTES, Math.floor(blockBytes / FIELD_SHARE));
39
+ return Object.freeze({
40
+ readBytes: contentBytes,
41
+ grepBytes: contentBytes,
42
+ blockBytes,
43
+ fieldBytes,
44
+ grepPreviewUnits: Math.floor(fieldBytes / UTF16_PREVIEW_BYTES),
45
+ });
46
+ }
47
+
48
+ /** Standalone tool factories have no session model until a provider is supplied. */
49
+ export const defaultOutputBudgets: OutputBudgetProvider = () => DEFAULT_OUTPUT_BUDGETS;
21
50
 
22
51
  /** Size wording for notices, e.g. `16 KiB`. */
23
52
  export function formatKiB(bytes: number): string {
@@ -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
+ }
@@ -35,8 +35,8 @@ test("defaults come from the settings schema", () => {
35
35
  forget: false,
36
36
  hashLen: 4,
37
37
  shiftRadius: 15,
38
- read: { defaultLimit: 500, maxKiB: 256 },
39
- grep: { defaultLimit: 100, defaultContext: 0 },
38
+ read: { defaultLimit: 500, maxKiB: undefined },
39
+ grep: { ...DEFAULT_CONFIG.grep, defaultLimit: 100, defaultContext: 0 },
40
40
  replace: { regexTimeoutMs: 5_000 },
41
41
  });
42
42
  });
@@ -83,14 +83,18 @@ test("tool groups resolve each setting independently", () =>
83
83
  await write({
84
84
  hashlineEdit: {
85
85
  read: { defaultLimit: 50, maxKiB: 0 },
86
- grep: { defaultContext: 21, defaultLimit: 7 },
86
+ grep: { ...DEFAULT_CONFIG.grep, defaultContext: 21, defaultLimit: 7 },
87
87
  replace: "fast",
88
88
  },
89
89
  });
90
90
  assert.deepEqual(loadConfig(root), {
91
91
  ...DEFAULT_CONFIG,
92
92
  read: { defaultLimit: 50, maxKiB: DEFAULT_CONFIG.read.maxKiB },
93
- grep: { defaultLimit: 7, defaultContext: DEFAULT_CONFIG.grep.defaultContext },
93
+ grep: {
94
+ ...DEFAULT_CONFIG.grep,
95
+ defaultLimit: 7,
96
+ defaultContext: DEFAULT_CONFIG.grep.defaultContext,
97
+ },
94
98
  });
95
99
  await write({ hashlineEdit: { replace: { regexTimeoutMs: 20_000 } } });
96
100
  assert.equal(loadConfig(root).replace.regexTimeoutMs, 20_000);
@@ -105,8 +109,8 @@ test("project settings replace global groups while absent project settings use g
105
109
  hashLen: 8,
106
110
  shiftRadius: 0,
107
111
  read: { defaultLimit: 7, maxKiB: 2 },
108
- grep: { defaultLimit: 3, defaultContext: 2 },
109
- replace: { regexTimeoutMs: 1_000 },
112
+ grep: { ...DEFAULT_CONFIG.grep, defaultLimit: 3, defaultContext: 2 },
113
+ replace: { regexTimeoutMs: 3_000 },
110
114
  };
111
115
  await writeFile(
112
116
  join(agentDir, "settings.json"),
@@ -135,8 +139,8 @@ test("invalid tool groups default independently without discarding valid sibling
135
139
  hashLen: 6,
136
140
  shiftRadius: 0,
137
141
  read: { defaultLimit: 2, maxKiB: 1 },
138
- grep: { defaultLimit: 3, defaultContext: 2 },
139
- replace: { regexTimeoutMs: 1_000 },
142
+ grep: { ...DEFAULT_CONFIG.grep, defaultLimit: 3, defaultContext: 2 },
143
+ replace: { regexTimeoutMs: 3_000 },
140
144
  };
141
145
  for (const group of ["read", "grep", "replace"] as const) {
142
146
  for (const value of [null, [], 42, "invalid", true]) {
@@ -166,8 +170,8 @@ test("tool settings accept their boundary values and default invalid leaves", ()
166
170
  {
167
171
  group: "replace",
168
172
  key: "regexTimeoutMs",
169
- valid: [1_000, 300_000],
170
- invalid: [999, 300_001, 1000.5, "1000", null],
173
+ valid: [3_000, 300_000],
174
+ invalid: [2_999, 300_001, 3000.5, "3000", null],
171
175
  },
172
176
  ] as const;
173
177
  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,6 +23,14 @@ 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
35
  export const configSchema = Type.Object({
27
36
  enabled: Type.Boolean({
@@ -53,7 +62,13 @@ export const configSchema = Type.Object({
53
62
  500,
54
63
  "Lines returned when limit is omitted.",
55
64
  ),
56
- maxKiB: integerSetting(integerRange(1, 4096), 256, "Anchored text returned per call, in KiB."),
65
+ maxKiB: Type.Optional(
66
+ Type.Number({
67
+ ...integerRange(1, MAX_CONTENT_KIB),
68
+ description:
69
+ "Explicit anchored-text byte cap in KiB; omitted uses the selected model capacity.",
70
+ }),
71
+ ),
57
72
  }),
58
73
  grep: Type.Object({
59
74
  defaultLimit: integerSetting(
@@ -66,13 +81,10 @@ export const configSchema = Type.Object({
66
81
  0,
67
82
  "Context lines shown when context is omitted.",
68
83
  ),
84
+ regexTimeoutMs: regexTimeoutSetting,
69
85
  }),
70
86
  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
- ),
87
+ regexTimeoutMs: regexTimeoutSetting,
76
88
  }),
77
89
  });
78
90
 
@@ -95,7 +107,9 @@ function resolveSetting<T extends TSchema>(schema: T, value: unknown): Static<T>
95
107
  ]),
96
108
  ) as Static<T>;
97
109
  }
98
- return (Value.Check(schema, value) ? value : Value.Create(schema)) as Static<T>;
110
+ return (
111
+ Value.Check(schema, value) ? value : Type.IsOptional(schema) ? undefined : Value.Create(schema)
112
+ ) as Static<T>;
99
113
  }
100
114
 
101
115
  export const DEFAULT_CONFIG: HashlineEditConfig = resolveSetting(configSchema, {});
@@ -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,64 @@ 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
+ formatted: {
50
+ blocks: ["confirmed match"],
51
+ linesTruncated: false,
52
+ invalidUtf8: [],
53
+ matches: 1,
54
+ files: 1,
55
+ },
56
+ warnings: [diagnostic(DEFAULT_OUTPUT_BUDGETS.fieldBytes)],
57
+ outputMode: "content",
58
+ matchLimitReached: false,
59
+ effectiveLimit: 100,
60
+ });
61
+ assert.equal(payload, "confirmed match");
62
+ assert.match(facts.diagnostics ?? "", /regex parse error:/);
63
+ assert.match(facts.diagnostics ?? "", /error: unclosed group/);
64
+ assert.match(facts.diagnostics ?? "", /omitted/i);
38
65
  });
39
66
 
40
- test("stderr collection preserves UTF-8 and reports overflow without losing the final cause", async () => {
67
+ test("stderr overflow → UTF-8 opening and final cause survive", async (t) => {
68
+ const directory = await mkdtemp(join(tmpdir(), "hl-rg-stderr-"));
69
+ t.after(() => rm(directory, { recursive: true, force: true }));
70
+ const path = join(directory, "stderr.txt");
41
71
  for (const source of ["权限不足🙂\n", diagnostic(MAX_RG_STDERR_BYTES)]) {
42
- const result = await runText(
72
+ await writeFile(path, source);
73
+ const result = await runRgPaths(
43
74
  process.execPath,
44
- ["--input-type=module", "--eval", "process.stdin.pipe(process.stderr)"],
45
- Buffer.from(source),
75
+ [
76
+ "--input-type=module",
77
+ "--eval",
78
+ "import { createReadStream } from 'node:fs'; createReadStream(process.argv[1]).pipe(process.stderr)",
79
+ path,
80
+ ],
46
81
  AbortSignal.timeout(10000),
82
+ () => true,
47
83
  );
48
84
  if (Buffer.byteLength(source) <= MAX_RG_STDERR_BYTES) {
49
85
  assert.equal(result.stderr, source);
@@ -1,11 +1,18 @@
1
1
  /**
2
- * Bounded diagnostic text shared by ripgrep stderr, batch aggregation, and
2
+ * Bounded diagnostic text shared by ripgrep stderr, report causes, and
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 { truncateHead, truncateTail } from "@earendil-works/pi-coding-agent";
7
6
  import { formatKiB } from "./budgets.ts";
8
7
 
8
+ /** Cut only at UTF-8 boundaries; diagnostics may contain a single oversized line. */
9
+ function byteSlice(text: string, maxBytes: number, tail: boolean): string {
10
+ const bytes = Buffer.from(text);
11
+ let boundary = tail ? Math.max(0, bytes.length - maxBytes) : Math.min(bytes.length, maxBytes);
12
+ while (boundary < bytes.length && (bytes[boundary] & 0xc0) === 0x80) boundary += tail ? 1 : -1;
13
+ return (tail ? bytes.subarray(boundary) : bytes.subarray(0, boundary)).toString("utf8");
14
+ }
15
+
9
16
  export class DiagnosticBuffer {
10
17
  private head = "";
11
18
  private tail = "";
@@ -31,10 +38,7 @@ export class DiagnosticBuffer {
31
38
  this.head = combined;
32
39
  return;
33
40
  }
34
- this.head = truncateHead(combined, {
35
- maxBytes: this.headBytes,
36
- maxLines: Number.MAX_SAFE_INTEGER,
37
- }).content;
41
+ this.head = byteSlice(combined, this.headBytes, false);
38
42
  this.tail = this.truncateTail(combined);
39
43
  this.truncated = true;
40
44
  return;
@@ -47,13 +51,6 @@ export class DiagnosticBuffer {
47
51
  }
48
52
 
49
53
  private truncateTail(text: string): string {
50
- // Pi's truncated previews omit the final newline; streaming must retain it
51
- // so the next chunk cannot merge two diagnostic lines.
52
- const newline = text.endsWith("\n") ? "\n" : "";
53
- const preview = truncateTail(text, {
54
- maxBytes: this.tailBytes - newline.length,
55
- maxLines: Number.MAX_SAFE_INTEGER,
56
- });
57
- return preview.content + (preview.truncated ? newline : "");
54
+ return byteSlice(text, this.tailBytes, true);
58
55
  }
59
56
  }
@@ -37,7 +37,10 @@ test("macOS attempts directory sync, tolerates unsupported operations, and prese
37
37
  (error: unknown) =>
38
38
  error instanceof FileMutationError &&
39
39
  error.publication === "PUBLISHED" &&
40
- /EIO/.test(error.message),
40
+ error.stage === "post_process" &&
41
+ error.cause instanceof Error &&
42
+ "code" in error.cause &&
43
+ error.cause.code === "EIO",
41
44
  );
42
45
  } else {
43
46
  assert.equal((await commit).publication, "PUBLISHED");