@criogaid/pi-hashline-edit 0.3.1 → 0.5.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 (75) hide show
  1. package/README.md +166 -61
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +459 -313
  4. package/src/core/apply.ts +251 -215
  5. package/src/core/errors.ts +9 -0
  6. package/src/core/hash.test.ts +61 -23
  7. package/src/core/hash.ts +49 -20
  8. package/src/core/lines.test.ts +46 -27
  9. package/src/core/lines.ts +36 -28
  10. package/src/core/ranges.test.ts +73 -19
  11. package/src/core/ranges.ts +15 -15
  12. package/src/core/replace.ts +109 -0
  13. package/src/core/text.test.ts +3 -3
  14. package/src/core/text.ts +26 -9
  15. package/src/core/types.ts +56 -41
  16. package/src/index.ts +23 -19
  17. package/src/integration/config-registration.test.ts +206 -0
  18. package/src/integration/grep-rg.test.ts +879 -251
  19. package/src/integration/large-text.test.ts +63 -0
  20. package/src/integration/replace-package.test.ts +41 -0
  21. package/src/pi/action-fusion.test.ts +612 -207
  22. package/src/pi/action-fusion.ts +442 -254
  23. package/src/pi/anchor-format.test.ts +53 -21
  24. package/src/pi/anchor-format.ts +48 -20
  25. package/src/pi/budgets.ts +25 -0
  26. package/src/pi/config.test.ts +178 -35
  27. package/src/pi/config.ts +96 -37
  28. package/src/pi/directory-sync.test.ts +55 -0
  29. package/src/pi/e2e-scenarios.test.ts +360 -0
  30. package/src/pi/edit-tool.ts +307 -279
  31. package/src/pi/error-text.ts +26 -0
  32. package/src/pi/execute.test.ts +1718 -713
  33. package/src/pi/failure-context.test.ts +110 -83
  34. package/src/pi/failure-context.ts +232 -73
  35. package/src/pi/failure-path.test.ts +180 -66
  36. package/src/pi/file-commit.test.ts +446 -233
  37. package/src/pi/file-commit.ts +348 -203
  38. package/src/pi/fusion-card.test.ts +118 -83
  39. package/src/pi/fusion-card.ts +203 -87
  40. package/src/pi/grep-output.ts +225 -0
  41. package/src/pi/grep-render.ts +59 -0
  42. package/src/pi/grep-scope.ts +139 -0
  43. package/src/pi/grep-search.ts +231 -0
  44. package/src/pi/grep-tool.ts +215 -774
  45. package/src/pi/grep.test.ts +825 -376
  46. package/src/pi/mutation-outcome.testing.ts +22 -0
  47. package/src/pi/mutation-result.test.ts +86 -0
  48. package/src/pi/mutation-result.ts +118 -63
  49. package/src/pi/mutation-runner.ts +151 -0
  50. package/src/pi/path.ts +20 -12
  51. package/src/pi/pi.test.ts +100 -52
  52. package/src/pi/read-tool.ts +245 -134
  53. package/src/pi/registration.test.ts +271 -114
  54. package/src/pi/render.test.ts +227 -84
  55. package/src/pi/render.ts +86 -116
  56. package/src/pi/replace-regex.ts +54 -0
  57. package/src/pi/replace-tool.ts +247 -241
  58. package/src/pi/replace-worker.mjs +4 -0
  59. package/src/pi/replace-worker.ts +10 -0
  60. package/src/pi/replace.test.ts +778 -390
  61. package/src/pi/result-safety.test.ts +821 -344
  62. package/src/pi/rg-line-ranges.test.ts +57 -31
  63. package/src/pi/rg-line-ranges.ts +45 -82
  64. package/src/pi/rg-process.test.ts +113 -0
  65. package/src/pi/{rg-line-filter.ts → rg-process.ts} +72 -125
  66. package/src/pi/rg-text-view.ts +102 -48
  67. package/src/pi/schema.ts +19 -0
  68. package/src/pi/text-stream.test.ts +118 -0
  69. package/src/pi/text-stream.ts +136 -0
  70. package/src/pi/tool-call.testing.ts +37 -0
  71. package/src/pi/write-tool.ts +114 -52
  72. package/src/pi/write.test.ts +250 -97
  73. package/src/core/index.ts +0 -14
  74. package/src/pi/rg-line-filter.test.ts +0 -85
  75. package/src/pi/state.ts +0 -26
@@ -0,0 +1,136 @@
1
+ import { createReadStream } from "node:fs";
2
+ import { createUtf8Decoder } from "../core/text.ts";
3
+ import { throwIfCancelled } from "./error-text.ts";
4
+
5
+ /** Scan and validate the whole file with bounded chunks, preserving BOM and raw line endings. */
6
+ export async function scanTextFile(
7
+ path: string,
8
+ onChunk?: (text: string) => void | Promise<void>,
9
+ signal?: AbortSignal,
10
+ onBytes?: (bytes: Buffer) => void,
11
+ ) {
12
+ const decode = createUtf8Decoder();
13
+ let byteLength = 0;
14
+ let lineFeeds = 0;
15
+ let lastByte = -1;
16
+ let hasNul = false;
17
+ let hasCrLf = false;
18
+ let decodingError: unknown;
19
+ const stream = createReadStream(path, { highWaterMark: 64 * 1024, signal });
20
+ try {
21
+ for await (const chunk of stream) {
22
+ const bytes = chunk as Buffer;
23
+ onBytes?.(bytes);
24
+ byteLength += bytes.length;
25
+ hasNul ||= bytes.includes(0);
26
+ hasCrLf ||= (lastByte === 13 && bytes[0] === 10) || bytes.includes("\r\n");
27
+ lastByte = bytes[bytes.length - 1];
28
+ let offset = 0;
29
+ while ((offset = bytes.indexOf(10, offset)) !== -1) {
30
+ lineFeeds++;
31
+ offset++;
32
+ }
33
+ // NUL takes precedence even when an earlier chunk contained malformed UTF-8.
34
+ if (hasNul || decodingError) continue;
35
+ let text: string;
36
+ try {
37
+ text = decode(bytes, true);
38
+ } catch (error) {
39
+ decodingError = error;
40
+ continue;
41
+ }
42
+ await onChunk?.(text);
43
+ }
44
+ } catch (error) {
45
+ // Node's stream abort raises its own AbortError; report the shared cancellation text.
46
+ throwIfCancelled(signal);
47
+ throw error;
48
+ }
49
+ throwIfCancelled(signal);
50
+ if (!hasNul) {
51
+ if (decodingError) throw decodingError;
52
+ const tail = decode();
53
+ if (tail) await onChunk?.(tail);
54
+ }
55
+ return {
56
+ byteLength,
57
+ totalLines: lineFeeds + (lastByte !== -1 && lastByte !== 10 ? 1 : 0),
58
+ finalNewline: lastByte === -1 || lastByte === 10,
59
+ hasNul,
60
+ hasCrLf,
61
+ };
62
+ }
63
+
64
+ interface ScannedLine {
65
+ number: number;
66
+ byteLength: number;
67
+ carriageReturns: number;
68
+ /** Absent when the selected line exceeds maxLineBytes. */
69
+ text: string | undefined;
70
+ }
71
+
72
+ /** Visit selected logical lines, retaining at most maxLineBytes of content per line. */
73
+ export async function scanTextLines(
74
+ path: string,
75
+ select: (number: number) => boolean,
76
+ onLine: (line: ScannedLine) => void,
77
+ options: { signal?: AbortSignal; maxLineBytes?: number; onBytes?: (bytes: Buffer) => void } = {},
78
+ ) {
79
+ const maxBytes = options.maxLineBytes ?? Infinity;
80
+ let number = 1;
81
+ let byteLength = 0;
82
+ let carriageReturns = 0;
83
+ let parts: string[] = [];
84
+ let selected = select(number);
85
+ let lastChar = "";
86
+ const finish = (terminated: boolean) => {
87
+ if (selected) {
88
+ const stripCr = terminated && lastChar === "\r";
89
+ const logicalBytes = byteLength - (stripCr ? 1 : 0);
90
+ let text = logicalBytes <= maxBytes ? parts.join("") : undefined;
91
+ if (stripCr && text !== undefined) text = text.slice(0, -1);
92
+ onLine({
93
+ number,
94
+ byteLength: logicalBytes,
95
+ carriageReturns: carriageReturns - (stripCr ? 1 : 0),
96
+ text,
97
+ });
98
+ carriageReturns = 0;
99
+ byteLength = 0;
100
+ parts = [];
101
+ lastChar = "";
102
+ }
103
+ number++;
104
+ selected = select(number);
105
+ };
106
+ const stats = await scanTextFile(
107
+ path,
108
+ (text) => {
109
+ let start = 0;
110
+ while (start < text.length) {
111
+ const lf = text.indexOf("\n", start);
112
+ if (selected) {
113
+ const end = lf === -1 ? text.length : lf;
114
+ const fragment = text.slice(start, end);
115
+ byteLength += Buffer.byteLength(fragment);
116
+ let cr = 0;
117
+ while ((cr = fragment.indexOf("\r", cr)) !== -1) {
118
+ carriageReturns++;
119
+ cr++;
120
+ }
121
+ if (fragment) lastChar = fragment[fragment.length - 1];
122
+ // Keep one extra byte until the terminator decides whether a final CR is content.
123
+ if (byteLength <= maxBytes + 1) parts.push(fragment);
124
+ else parts = [];
125
+ }
126
+ if (lf === -1) break;
127
+ finish(true);
128
+ start = lf + 1;
129
+ }
130
+ },
131
+ options.signal,
132
+ options.onBytes,
133
+ );
134
+ if (!stats.hasNul && byteLength > 0) finish(false);
135
+ return stats;
136
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Test support: invoke a tool the way Pi does.
3
+ *
4
+ * In production, input reaches `execute` only after Pi runs the tool's
5
+ * `prepareArguments` and validates (and coerces) the result against the tool
6
+ * schema. `execute` trusts that input, so tests that probe invalid or
7
+ * unusual arguments go through the same funnel instead of calling `execute`.
8
+ */
9
+
10
+ import { validateToolArguments } from "@earendil-works/pi-ai";
11
+
12
+ interface CallableTool {
13
+ readonly name: string;
14
+ readonly parameters: unknown;
15
+ prepareArguments?(args: unknown): unknown;
16
+ execute(...args: any[]): Promise<any>;
17
+ }
18
+
19
+ export interface ToolCallOptions {
20
+ toolCallId?: string;
21
+ signal?: AbortSignal;
22
+ onUpdate?: unknown;
23
+ ctx?: unknown;
24
+ }
25
+
26
+ /** prepareArguments → schema validation → execute, failing the way Pi reports invalid calls. */
27
+ export async function callTool(tool: CallableTool, args: unknown, options: ToolCallOptions = {}) {
28
+ const toolCallId = options.toolCallId ?? "test";
29
+ const prepared = tool.prepareArguments ? tool.prepareArguments(args) : args;
30
+ const validated = validateToolArguments(tool as never, {
31
+ type: "toolCall",
32
+ id: toolCallId,
33
+ name: tool.name,
34
+ arguments: prepared as never,
35
+ });
36
+ return tool.execute(toolCallId, validated, options.signal, options.onUpdate, options.ctx);
37
+ }
@@ -1,59 +1,121 @@
1
1
  import { Type, type Static } from "typebox";
2
- import { createWriteToolDefinition, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
3
- import { ACTION_FUSION_GUIDELINES, createActionFusionExecutor, createThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
4
- import { commitFile, type CommitMode } from "./file-commit.ts";
2
+ import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
3
+ import {
4
+ createWriteToolDefinition,
5
+ type ExtensionContext,
6
+ type Theme,
7
+ type ToolRenderResultOptions,
8
+ } from "@earendil-works/pi-coding-agent";
9
+ import {
10
+ ACTION_FUSION_GUIDELINES,
11
+ withThenRunSchema,
12
+ type ThenRunInput,
13
+ type ActionFusionDetails,
14
+ } from "./action-fusion.ts";
15
+ import { commitFile, type CommitMode, type CommitResult } from "./file-commit.ts";
5
16
  import { postProcessMutation } from "./mutation-result.ts";
6
- import { canonicalPath } from "./path.ts";
17
+ import { executeMutation, type ActionFusionExecutor } from "./mutation-runner.ts";
18
+ import { invalidArgument, throwIfCancelled } from "./error-text.ts";
19
+ import { unwritableTextReason } from "../core/text.ts";
20
+
21
+ const writeSchema = Type.Object(
22
+ {
23
+ path: Type.String({ minLength: 1, description: "Path to the file (relative or absolute)" }),
24
+ content: Type.String({
25
+ description: "Complete file content, written exactly as supplied, including line endings.",
26
+ }),
27
+ mode: Type.Optional(
28
+ Type.Union([
29
+ Type.Literal("create", { description: "Fail if the target already exists" }),
30
+ Type.Literal("overwrite", { description: "Fail if the target does not exist" }),
31
+ ]),
32
+ ),
33
+ },
34
+ { additionalProperties: false },
35
+ );
7
36
 
8
37
  function createWriteSchema(actionFusion: boolean) {
9
- return Type.Object({
10
- path: Type.String({ description: "Path to the file to write" }),
11
- content: Type.String({ description: "Complete file content, including the exact desired line endings. Source-code escape sequences remain literal text." }),
12
- mode: Type.Optional(Type.Union([
13
- Type.Literal("create", { description: "Fail if the target already exists" }),
14
- Type.Literal("overwrite", { description: "Fail if the target does not exist" }),
15
- ])),
16
- expectedRevision: Type.Optional(Type.String({ description: "Expected SHA-256 revision of an existing target" })),
17
- ...(actionFusion ? { then_run: createThenRunSchema("Command to run after write succeeds; failure does not roll back the write.") } : {}),
18
- });
38
+ return withThenRunSchema(
39
+ writeSchema,
40
+ "Command to run after write succeeds; failure does not roll back the write.",
41
+ actionFusion,
42
+ );
19
43
  }
44
+ type WriteParams = Static<typeof writeSchema> & { then_run?: ThenRunInput };
45
+ type WriteDetails = CommitResult & { path: string; actionFusion?: ActionFusionDetails };
46
+ type WriteRenderContext = Parameters<
47
+ NonNullable<ReturnType<typeof createWriteToolDefinition>["renderCall"]>
48
+ >[2];
20
49
 
21
- const writeSchema = createWriteSchema(false);
22
- type WriteParams = Omit<Static<typeof writeSchema>, "then_run"> & { then_run?: ThenRunInput };
23
-
24
- export function makeWriteOverride(cwd: string, fusion?: ReturnType<typeof createActionFusionExecutor>): any {
25
- const parameters = createWriteSchema(fusion !== undefined);
26
- const builtin = createWriteToolDefinition(cwd);
27
- return {
28
- name: "write" as const,
29
- label: "write",
30
- description: "Write complete file content exactly as supplied, including LF/CRLF choices. Use for intentional whole-file line-ending conversion. By default, creates missing files and overwrites existing files.",
31
- promptSnippet: "Write complete file content to a path",
32
- promptGuidelines: fusion ? ACTION_FUSION_GUIDELINES : [],
33
- parameters,
34
- renderShell: "default" as const,
35
- renderCall: builtin.renderCall,
36
- renderResult: builtin.renderResult,
37
- async execute(toolCallId: string, params: WriteParams, signal: AbortSignal | undefined, onUpdate: any, ctx: any) {
38
- const { then_run, ...mutationParams } = params;
39
- if (!fusion && then_run !== undefined) throw new Error("then_run is unavailable because hashlineEdit.actionFusion is disabled");
40
- const absolutePath = canonicalPath(cwd, mutationParams.path);
41
- const mutate = () => withFileMutationQueue(absolutePath, async () => {
42
- signal?.throwIfAborted();
43
- const result = await commitFile(absolutePath, mutationParams.content, {
44
- mode: mutationParams.mode as CommitMode | undefined,
45
- expectedRevision: mutationParams.expectedRevision,
46
- signal,
47
- });
48
- return postProcessMutation("write", result.publication, () => ({
49
- content: [{ type: "text" as const, text: result.publication === "NOT_PUBLISHED"
50
- ? `Wrote ${mutationParams.path} (no net change).`
51
- : `${result.created ? "Created" : "Wrote"} ${mutationParams.path}.` }],
52
- details: { path: mutationParams.path, ...result },
53
- }));
54
- });
55
- if (!fusion) return mutate();
56
- return fusion({ toolCallId, absolutePath, thenRun: then_run, mutate, signal, ctx, onUpdate });
57
- },
58
- };
50
+ export function makeWriteOverride(cwd: string, fusion?: ActionFusionExecutor) {
51
+ const parameters = createWriteSchema(fusion !== undefined);
52
+ const builtin = createWriteToolDefinition(cwd);
53
+ return {
54
+ name: "write" as const,
55
+ label: "write",
56
+ description:
57
+ "Write a whole file exactly as supplied, including LF/CRLF, so it also converts line endings. By default, creates missing files and parent directories and overwrites existing files.",
58
+ promptSnippet: "Write complete file content to a path",
59
+ promptGuidelines: [
60
+ "Use write for creating new files or whole-file overwrites; for targeted changes, prefer edit or replace to preserve surrounding content.",
61
+ ...(fusion ? ACTION_FUSION_GUIDELINES : []),
62
+ ],
63
+ parameters,
64
+ /** Reject content that cannot be written as UTF-8 before Pi's schema validation; never rewrites. */
65
+ prepareArguments(args: unknown): WriteParams {
66
+ const content = (args as { content?: unknown } | null)?.content;
67
+ const reason = typeof content === "string" ? unwritableTextReason(content) : undefined;
68
+ if (reason) throw invalidArgument("content", reason);
69
+ return args as WriteParams;
70
+ },
71
+ renderShell: "default" as const,
72
+ renderCall(args: WriteParams, theme: Theme, context: WriteRenderContext) {
73
+ return builtin.renderCall!(args, theme, context);
74
+ },
75
+ renderResult(
76
+ result: AgentToolResult<WriteDetails>,
77
+ options: ToolRenderResultOptions,
78
+ theme: Theme,
79
+ context: WriteRenderContext,
80
+ ) {
81
+ return builtin.renderResult!({ ...result, details: undefined }, options, theme, context);
82
+ },
83
+ async execute(
84
+ toolCallId: string,
85
+ params: WriteParams,
86
+ signal: AbortSignal | undefined,
87
+ onUpdate: AgentToolUpdateCallback<WriteDetails> | undefined,
88
+ ctx: ExtensionContext,
89
+ ) {
90
+ return executeMutation<Omit<WriteParams, "then_run">, WriteDetails>(
91
+ {
92
+ cwd,
93
+ fusion,
94
+ async run(mutationParams, { absolutePath, displayPath, signal }) {
95
+ throwIfCancelled(signal, `before write; ${displayPath} was not changed.`);
96
+ const result = await commitFile(absolutePath, mutationParams.content, {
97
+ mode: mutationParams.mode as CommitMode | undefined,
98
+ signal,
99
+ });
100
+ return {
101
+ commit: result,
102
+ result: postProcessMutation("write", result.publication, () => ({
103
+ content: [
104
+ {
105
+ type: "text" as const,
106
+ text:
107
+ result.publication === "NOT_PUBLISHED"
108
+ ? `Wrote ${displayPath} (no net change).`
109
+ : `${result.created ? "Created" : "Wrote"} ${displayPath}.`,
110
+ },
111
+ ],
112
+ details: { path: displayPath, ...result },
113
+ })),
114
+ };
115
+ },
116
+ },
117
+ { toolCallId, params, signal, onUpdate, ctx },
118
+ );
119
+ },
120
+ };
59
121
  }