@criogaid/pi-hashline-edit 0.3.1 → 0.4.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 (69) hide show
  1. package/README.md +58 -49
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +366 -310
  4. package/src/core/apply.ts +269 -202
  5. package/src/core/hash.test.ts +61 -23
  6. package/src/core/hash.ts +45 -16
  7. package/src/core/lines.test.ts +46 -27
  8. package/src/core/lines.ts +36 -28
  9. package/src/core/ranges.test.ts +73 -19
  10. package/src/core/ranges.ts +15 -15
  11. package/src/core/text.test.ts +3 -3
  12. package/src/core/text.ts +28 -9
  13. package/src/core/types.ts +54 -36
  14. package/src/index.ts +22 -16
  15. package/src/integration/grep-rg.test.ts +834 -219
  16. package/src/integration/large-text.test.ts +62 -0
  17. package/src/integration/replace-package.test.ts +37 -0
  18. package/src/pi/action-fusion.test.ts +535 -206
  19. package/src/pi/action-fusion.ts +469 -244
  20. package/src/pi/anchor-format.test.ts +30 -19
  21. package/src/pi/anchor-format.ts +27 -14
  22. package/src/pi/budgets.ts +20 -0
  23. package/src/pi/config.test.ts +60 -30
  24. package/src/pi/config.ts +45 -32
  25. package/src/pi/directory-sync.test.ts +55 -0
  26. package/src/pi/e2e-scenarios.test.ts +359 -0
  27. package/src/pi/edit-tool.ts +426 -262
  28. package/src/pi/error-text.ts +21 -0
  29. package/src/pi/execute.test.ts +1593 -712
  30. package/src/pi/failure-context.test.ts +105 -83
  31. package/src/pi/failure-context.ts +83 -71
  32. package/src/pi/failure-path.test.ts +171 -64
  33. package/src/pi/file-commit.test.ts +446 -233
  34. package/src/pi/file-commit.ts +347 -203
  35. package/src/pi/fusion-card.test.ts +118 -83
  36. package/src/pi/fusion-card.ts +120 -85
  37. package/src/pi/grep-output.ts +208 -0
  38. package/src/pi/grep-render.ts +58 -0
  39. package/src/pi/grep-scope.ts +152 -0
  40. package/src/pi/grep-search.ts +217 -0
  41. package/src/pi/grep-tool.ts +191 -766
  42. package/src/pi/grep.test.ts +562 -150
  43. package/src/pi/mutation-result.test.ts +37 -0
  44. package/src/pi/mutation-result.ts +107 -59
  45. package/src/pi/mutation-runner.ts +168 -0
  46. package/src/pi/path.ts +20 -12
  47. package/src/pi/pi.test.ts +95 -52
  48. package/src/pi/read-tool.ts +215 -132
  49. package/src/pi/registration.test.ts +274 -113
  50. package/src/pi/render.test.ts +218 -83
  51. package/src/pi/render.ts +152 -95
  52. package/src/pi/replace-apply.ts +109 -0
  53. package/src/pi/replace-tool.ts +280 -240
  54. package/src/pi/replace-worker.mjs +4 -0
  55. package/src/pi/replace-worker.ts +10 -0
  56. package/src/pi/replace.test.ts +773 -389
  57. package/src/pi/result-safety.test.ts +779 -342
  58. package/src/pi/rg-line-filter.test.ts +64 -36
  59. package/src/pi/rg-line-filter.ts +40 -124
  60. package/src/pi/rg-line-ranges.test.ts +57 -31
  61. package/src/pi/rg-line-ranges.ts +44 -82
  62. package/src/pi/rg-text-view.ts +106 -36
  63. package/src/pi/schema.ts +27 -0
  64. package/src/pi/state.ts +7 -7
  65. package/src/pi/text-stream.test.ts +118 -0
  66. package/src/pi/text-stream.ts +136 -0
  67. package/src/pi/tool-call.testing.ts +37 -0
  68. package/src/pi/write-tool.ts +115 -52
  69. package/src/pi/write.test.ts +248 -96
@@ -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,122 @@
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
+ // Write results carry no anchors; stale revisions are reported by then_run.
95
+ reportsAnchors: false,
96
+ async run(mutationParams, { absolutePath, displayPath, signal }) {
97
+ throwIfCancelled(signal, `before write; ${displayPath} was not changed.`);
98
+ const result = await commitFile(absolutePath, mutationParams.content, {
99
+ mode: mutationParams.mode as CommitMode | undefined,
100
+ signal,
101
+ });
102
+ return {
103
+ result: postProcessMutation("write", result.publication, () => ({
104
+ content: [
105
+ {
106
+ type: "text" as const,
107
+ text:
108
+ result.publication === "NOT_PUBLISHED"
109
+ ? `Wrote ${displayPath} (no net change).`
110
+ : `${result.created ? "Created" : "Wrote"} ${displayPath}.`,
111
+ },
112
+ ],
113
+ details: { path: displayPath, ...result },
114
+ })),
115
+ };
116
+ },
117
+ },
118
+ { toolCallId, params, signal, onUpdate, ctx },
119
+ );
120
+ },
121
+ };
59
122
  }
@@ -6,116 +6,268 @@ import { test } from "node:test";
6
6
  import { makeWriteOverride } from "./write-tool.ts";
7
7
  import { createActionFusionExecutor } from "./action-fusion.ts";
8
8
  import { fileRevision } from "./file-commit.ts";
9
+ import { callTool } from "./tool-call.testing.ts";
9
10
 
10
11
  const context = (cwd: string) => ({ cwd }) as any;
11
12
 
12
13
  async function withTemp<T>(run: (dir: string) => Promise<T>): Promise<T> {
13
- const dir = await mkdtemp(join(tmpdir(), "hashline-write-"));
14
- try { return await run(dir); } finally { await rm(dir, { recursive: true, force: true }); }
14
+ const dir = await mkdtemp(join(tmpdir(), "hashline-write-"));
15
+ try {
16
+ return await run(dir);
17
+ } finally {
18
+ await rm(dir, { recursive: true, force: true });
19
+ }
15
20
  }
16
21
 
17
22
  test("write schema follows the shared actionFusion switch", () => {
18
- assert.equal((makeWriteOverride("/tmp") as any).parameters.properties.then_run, undefined);
19
- const fusion = createActionFusionExecutor();
20
- assert.ok((makeWriteOverride("/tmp", fusion) as any).parameters.properties.then_run);
23
+ const plain = makeWriteOverride("/tmp");
24
+ assert.equal(Object.hasOwn(plain.parameters.properties, "then_run"), false);
25
+ assert.equal(Object.hasOwn(plain.parameters.properties, "expectedRevision"), false);
26
+ const fusion = createActionFusionExecutor();
27
+ const withFusion = makeWriteOverride("/tmp", fusion);
28
+ assert.equal(Object.hasOwn(withFusion.parameters.properties, "then_run"), true);
29
+ assert.equal(Object.hasOwn(withFusion.parameters.properties, "expectedRevision"), false);
21
30
  });
22
31
 
23
- test("write preserves native default create/overwrite behavior", async () => withTemp(async (dir) => {
24
- const write = makeWriteOverride(dir) as any;
25
- const target = join(dir, "file.txt");
26
- const created = await write.execute("create", { path: "file.txt", content: "one\n" }, undefined, undefined, context(dir));
27
- assert.doesNotMatch(created.content[0].text, /Revision:|[0-9a-f]{64}/);
28
- assert.equal(created.details.publishedRevision, await fileRevision(target));
29
- assert.equal(created.details.revision, created.details.publishedRevision);
30
- assert.equal(await readFile(target, "utf8"), "one\n");
31
- await write.execute("overwrite", { path: "file.txt", content: "two\n" }, undefined, undefined, context(dir));
32
- assert.equal(await readFile(target, "utf8"), "two\n");
33
- }));
32
+ test("write rejects unknown fields rather than ignoring a misspelled create mode", async () =>
33
+ withTemp(async (dir) => {
34
+ const file = join(dir, "file.txt");
35
+ await writeFile(file, "original\n");
36
+ for (const fusion of [undefined, createActionFusionExecutor()]) {
37
+ const tool = makeWriteOverride(dir, fusion);
38
+ const args = { path: "file.txt", content: "new\n", modee: "create" };
39
+ await assert.rejects(
40
+ callTool(tool, args, { ctx: context(dir) }),
41
+ /Validation failed for tool "write":\n {2}- modee: schema is false/,
42
+ );
43
+ assert.equal(await readFile(file, "utf8"), "original\n");
44
+ }
45
+ }));
34
46
 
35
- test("write supports create-only, overwrite-only, and expectedRevision", async () => withTemp(async (dir) => {
36
- const write = makeWriteOverride(dir) as any;
37
- await write.execute("create", { path: "new.txt", content: "new\n", mode: "create" }, undefined, undefined, context(dir));
38
- await assert.rejects(write.execute("create-again", { path: "new.txt", content: "bad\n", mode: "create" }, undefined, undefined, context(dir)), /already exists/);
39
- await assert.rejects(write.execute("missing-overwrite", { path: "missing.txt", content: "bad\n", mode: "overwrite" }, undefined, undefined, context(dir)), /does not exist/);
40
- const revision = await fileRevision(join(dir, "new.txt"));
41
- await write.execute("revision", { path: "new.txt", content: "updated\n", expectedRevision: revision }, undefined, undefined, context(dir));
42
- await assert.rejects(write.execute("stale", { path: "new.txt", content: "bad\n", expectedRevision: revision }, undefined, undefined, context(dir)), /expectedRevision/);
43
- assert.equal(await readFile(join(dir, "new.txt"), "utf8"), "updated\n");
44
- }));
47
+ test("write rejects unwritable content before accessing a missing target", async () =>
48
+ withTemp(async (dir) => {
49
+ const file = join(dir, "missing.txt");
50
+ const tool = makeWriteOverride(dir);
51
+ const valid = { path: file, content: "ready\n" };
52
+ assert.equal(tool.prepareArguments(valid), valid);
53
+ for (const [content, expected] of [
54
+ ["bad\0", /Invalid argument content: UNSUPPORTED_TEXT: NUL bytes are not editable\./],
55
+ ["\ud800", /Invalid argument content: INVALID_UNICODE:/],
56
+ ] as const) {
57
+ await assert.rejects(
58
+ callTool(tool, { path: file, content }, { ctx: context(dir) }),
59
+ expected,
60
+ );
61
+ await assert.rejects(readFile(file, "utf8"), { code: "ENOENT" });
62
+ }
63
+ }));
45
64
 
46
- test("concurrent writes cannot both consume the same expectedRevision", async () => withTemp(async (dir) => {
47
- const target = join(dir, "concurrent.txt");
48
- await writeFile(target, "original\n");
49
- const expectedRevision = await fileRevision(target);
50
- const write = makeWriteOverride(dir);
51
- const results = await Promise.allSettled(["first\n", "second\n"].map((content) =>
52
- write.execute("concurrent", { path: target, content, expectedRevision }, undefined, undefined, context(dir)),
53
- ));
54
- assert.equal(results.filter((result) => result.status === "fulfilled").length, 1);
55
- const rejected = results.find((result) => result.status === "rejected");
56
- assert.ok(rejected && rejected.status === "rejected");
57
- assert.match(rejected.reason.message, /expectedRevision/);
58
- }));
65
+ test("write preserves native default create/overwrite behavior", async () =>
66
+ withTemp(async (dir) => {
67
+ const write = makeWriteOverride(dir) as any;
68
+ const target = join(dir, "file.txt");
69
+ const created = await write.execute(
70
+ "create",
71
+ { path: "file.txt", content: "one\n" },
72
+ undefined,
73
+ undefined,
74
+ context(dir),
75
+ );
76
+ assert.doesNotMatch(created.content[0].text, /Revision:|[0-9a-f]{64}/);
77
+ assert.equal(created.details.publishedRevision, await fileRevision(target));
78
+ assert.equal("revision" in created.details, false);
79
+ assert.equal(await readFile(target, "utf8"), "one\n");
80
+ await write.execute(
81
+ "overwrite",
82
+ { path: "file.txt", content: "two\n" },
83
+ undefined,
84
+ undefined,
85
+ context(dir),
86
+ );
87
+ assert.equal(await readFile(target, "utf8"), "two\n");
88
+ }));
59
89
 
60
- test("write returns only a summary for empty, short, and long content", async () => withTemp(async (dir) => {
61
- const contents = ["", "before\n", Array.from({ length: 500 }, (_, index) => `line ${index + 1}`).join("\n")];
62
- for (const [index, content] of contents.entries()) {
63
- const path = `file-${index}.txt`;
64
- const result = await makeWriteOverride(dir).execute("write", { path, content }, undefined, undefined, context(dir));
65
- assert.deepEqual(result.content, [{ type: "text", text: `Created ${path}.` }]);
66
- assert.equal(await readFile(join(dir, path), "utf8"), content);
67
- }
68
- }));
90
+ test("write supports create-only and overwrite-only modes", async () =>
91
+ withTemp(async (dir) => {
92
+ const write = makeWriteOverride(dir) as any;
93
+ await write.execute(
94
+ "create",
95
+ { path: "new.txt", content: "new\n", mode: "create" },
96
+ undefined,
97
+ undefined,
98
+ context(dir),
99
+ );
100
+ await assert.rejects(
101
+ write.execute(
102
+ "create-again",
103
+ { path: "new.txt", content: "bad\n", mode: "create" },
104
+ undefined,
105
+ undefined,
106
+ context(dir),
107
+ ),
108
+ /already exists/,
109
+ );
110
+ await assert.rejects(
111
+ write.execute(
112
+ "missing-overwrite",
113
+ { path: "missing.txt", content: "bad\n", mode: "overwrite" },
114
+ undefined,
115
+ undefined,
116
+ context(dir),
117
+ ),
118
+ /does not exist/,
119
+ );
120
+ await write.execute(
121
+ "overwrite",
122
+ { path: "new.txt", content: "updated\n", mode: "overwrite" },
123
+ undefined,
124
+ undefined,
125
+ context(dir),
126
+ );
127
+ assert.equal(await readFile(join(dir, "new.txt"), "utf8"), "updated\n");
128
+ }));
69
129
 
70
- test("write returns its summary and command output after an unchanged then_run", async () => withTemp(async (dir) => {
71
- const fusion = createActionFusionExecutor(async () => "checked");
72
- const write = makeWriteOverride(dir, fusion) as any;
73
- const result = await write.execute("unchanged", { path: "unchanged.txt", content: "mutation\n", then_run: { command: "check" } }, undefined, undefined, context(dir));
74
- assert.deepEqual(result.content, [
75
- { type: "text", text: "Created unchanged.txt." },
76
- { type: "text", text: "[then_run:succeeded]\nchecked" },
77
- ]);
78
- assert.equal(result.details.actionFusion.freshness, "unchanged");
79
- }));
130
+ test("write rejects obsolete expectedRevision without overwriting", async () =>
131
+ withTemp(async (dir) => {
132
+ const target = join(dir, "concurrent.txt");
133
+ await writeFile(target, "original\n");
134
+ const params = {
135
+ path: target,
136
+ content: "changed\n",
137
+ expectedRevision: await fileRevision(target),
138
+ };
139
+ for (const fusion of [undefined, createActionFusionExecutor()]) {
140
+ const write = makeWriteOverride(dir, fusion);
141
+ await assert.rejects(
142
+ callTool(write, params, { ctx: context(dir) }),
143
+ /Validation failed for tool "write":\n {2}- expectedRevision: schema is false/,
144
+ );
145
+ assert.equal(await readFile(target, "utf8"), "original\n");
146
+ }
147
+ }));
80
148
 
81
- test("write reports changed freshness when then_run changes the target", async () => withTemp(async (dir) => {
82
- const target = join(dir, "changed.txt");
83
- const fusion = createActionFusionExecutor(async () => { await writeFile(target, "command changed\n"); return "checked"; });
84
- const write = makeWriteOverride(dir, fusion) as any;
85
- const result = await write.execute("changed", { path: "changed.txt", content: "mutation\n", then_run: { command: "check" } }, undefined, undefined, context(dir));
86
- const text = result.content.map((block: any) => block.text).join("\n");
87
- assert.doesNotMatch(text, /revision:|[0-9a-f]{64}/i);
88
- assert.doesNotMatch(text, /anchors are omitted/);
89
- assert.equal((text.match(/Re-read/g) ?? []).length, 1);
90
- assert.equal((text.match(/\[then_run:stale\]/g) ?? []).length, 1);
91
- assert.doesNotMatch(text, /Fresh anchors:|\b1#[0-9A-Z]+\b/);
92
- assert.equal(result.details.actionFusion.freshness, "changed");
93
- assert.deepEqual(write.renderResult(result, { isPartial: false }, {}, { isError: false }).render(100), []);
94
- }));
149
+ test("write returns only a summary for empty, short, and long content", async () =>
150
+ withTemp(async (dir) => {
151
+ const contents = [
152
+ "",
153
+ "before\n",
154
+ Array.from({ length: 500 }, (_, index) => `line ${index + 1}`).join("\n"),
155
+ ];
156
+ for (const [index, content] of contents.entries()) {
157
+ const path = `file-${index}.txt`;
158
+ const result = await makeWriteOverride(dir).execute(
159
+ "write",
160
+ { path, content },
161
+ undefined,
162
+ undefined,
163
+ context(dir),
164
+ );
165
+ assert.deepEqual(result.content, [{ type: "text", text: `Created ${path}.` }]);
166
+ assert.equal(await readFile(join(dir, path), "utf8"), content);
167
+ }
168
+ }));
95
169
 
96
- test("write reports missing freshness when then_run removes the target", async () => withTemp(async (dir) => {
97
- const target = join(dir, "missing.txt");
98
- const fusion = createActionFusionExecutor(async () => { await rm(target); return "removed"; });
99
- const result = await makeWriteOverride(dir, fusion).execute("missing", { path: "missing.txt", content: "mutation\n", then_run: { command: "remove" } }, undefined, undefined, context(dir));
100
- const text = result.content.map((block: any) => block.text).join("\n");
101
- assert.equal(result.details.actionFusion.freshness, "missing");
102
- assert.match(text, /Re-read/);
103
- assert.doesNotMatch(text, /Fresh anchors:/);
104
- }));
170
+ test("write returns its summary and command output after an unchanged then_run", async () =>
171
+ withTemp(async (dir) => {
172
+ const fusion = createActionFusionExecutor(async () => "checked");
173
+ const write = makeWriteOverride(dir, fusion) as any;
174
+ const result = await write.execute(
175
+ "unchanged",
176
+ { path: "unchanged.txt", content: "mutation\n", then_run: { command: "check" } },
177
+ undefined,
178
+ undefined,
179
+ context(dir),
180
+ );
181
+ assert.deepEqual(result.content, [
182
+ { type: "text", text: "Created unchanged.txt." },
183
+ { type: "text", text: "[then_run:succeeded]\nchecked" },
184
+ ]);
185
+ assert.equal(result.details.actionFusion.freshness, "unchanged");
186
+ }));
105
187
 
106
- test("write preserves command failure and changed freshness", async () => withTemp(async (dir) => {
107
- const target = join(dir, "failed.txt");
108
- const fusion = createActionFusionExecutor(async () => { await writeFile(target, "changed before failure\n"); throw new Error("command failed"); });
109
- const result = await makeWriteOverride(dir, fusion).execute("failed", { path: "failed.txt", content: "mutation\n", then_run: { command: "fail" } }, undefined, undefined, context(dir));
110
- const text = result.content.map((block: any) => block.text).join("\n");
111
- assert.equal(result.details.actionFusion.freshness, "changed");
112
- assert.equal(result.details.actionFusion.command, "failed");
113
- assert.match(text, /Re-read/);
114
- assert.doesNotMatch(text, /Fresh anchors:/);
115
- }));
188
+ test("write reports changed freshness when then_run changes the target", async () =>
189
+ withTemp(async (dir) => {
190
+ const target = join(dir, "changed.txt");
191
+ const fusion = createActionFusionExecutor(async () => {
192
+ await writeFile(target, "command changed\n");
193
+ return "checked";
194
+ });
195
+ const write = makeWriteOverride(dir, fusion) as any;
196
+ const result = await write.execute(
197
+ "changed",
198
+ { path: "changed.txt", content: "mutation\n", then_run: { command: "check" } },
199
+ undefined,
200
+ undefined,
201
+ context(dir),
202
+ );
203
+ const text = result.content.map((block: any) => block.text).join("\n");
204
+ assert.doesNotMatch(text, /revision:|[0-9a-f]{64}/i);
205
+ assert.doesNotMatch(text, /anchors are omitted/);
206
+ assert.equal((text.match(/Re-read/g) ?? []).length, 1);
207
+ assert.equal((text.match(/\[then_run:stale\]/g) ?? []).length, 1);
208
+ assert.doesNotMatch(text, /Fresh anchors:|\b1#[0-9A-Z]+\b/);
209
+ assert.equal(result.details.actionFusion.freshness, "changed");
210
+ assert.deepEqual(
211
+ write.renderResult(result, { isPartial: false }, {}, { isError: false }).render(100),
212
+ [],
213
+ );
214
+ }));
116
215
 
117
- test("write rejects NUL content", async () => withTemp(async (dir) => {
118
- const write = makeWriteOverride(dir);
119
- await assert.rejects(write.execute("nul", { path: "nul.txt", content: "a\0b" }, undefined, undefined, context(dir)), /UNSUPPORTED_TEXT/);
120
- await assert.rejects(readFile(join(dir, "nul.txt")), /ENOENT/);
121
- }));
216
+ test("write reports missing freshness when then_run removes the target", async () =>
217
+ withTemp(async (dir) => {
218
+ const target = join(dir, "missing.txt");
219
+ const fusion = createActionFusionExecutor(async () => {
220
+ await rm(target);
221
+ return "removed";
222
+ });
223
+ const result = await makeWriteOverride(dir, fusion).execute(
224
+ "missing",
225
+ { path: "missing.txt", content: "mutation\n", then_run: { command: "remove" } },
226
+ undefined,
227
+ undefined,
228
+ context(dir),
229
+ );
230
+ const text = result.content.map((block: any) => block.text).join("\n");
231
+ assert.ok(result.details.actionFusion);
232
+ assert.equal(result.details.actionFusion.freshness, "missing");
233
+ assert.match(text, /Re-read/);
234
+ assert.doesNotMatch(text, /Fresh anchors:/);
235
+ }));
236
+
237
+ test("write preserves command failure and changed freshness", async () =>
238
+ withTemp(async (dir) => {
239
+ const target = join(dir, "failed.txt");
240
+ const fusion = createActionFusionExecutor(async () => {
241
+ await writeFile(target, "changed before failure\n");
242
+ throw new Error("command failed");
243
+ });
244
+ const result = await makeWriteOverride(dir, fusion).execute(
245
+ "failed",
246
+ { path: "failed.txt", content: "mutation\n", then_run: { command: "fail" } },
247
+ undefined,
248
+ undefined,
249
+ context(dir),
250
+ );
251
+ const text = result.content.map((block: any) => block.text).join("\n");
252
+ assert.ok(result.details.actionFusion);
253
+ assert.equal(result.details.actionFusion.freshness, "changed");
254
+ assert.equal(result.details.actionFusion.command, "failed");
255
+ assert.match(text, /Re-read/);
256
+ assert.doesNotMatch(text, /Fresh anchors:/);
257
+ }));
258
+
259
+ test("write rejects NUL content", async () =>
260
+ withTemp(async (dir) => {
261
+ const write = makeWriteOverride(dir);
262
+ await assert.rejects(
263
+ write.execute(
264
+ "nul",
265
+ { path: "nul.txt", content: "a\0b" },
266
+ undefined,
267
+ undefined,
268
+ context(dir),
269
+ ),
270
+ /UNSUPPORTED_TEXT/,
271
+ );
272
+ await assert.rejects(readFile(join(dir, "nul.txt")), /ENOENT/);
273
+ }));