@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,5 +1,6 @@
1
1
  import { Type, type Static } from "typebox";
2
2
  import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
3
+ import { Text } from "@earendil-works/pi-tui";
3
4
  import {
4
5
  createWriteToolDefinition,
5
6
  type ExtensionToolContext,
@@ -8,18 +9,19 @@ import {
8
9
  } from "@earendil-works/pi-coding-agent";
9
10
  import {
10
11
  ACTION_FUSION_GUIDELINES,
12
+ withThenRunDescription,
11
13
  withThenRunSchema,
12
14
  type ThenRunInput,
13
- type ActionFusionDetails,
14
15
  } from "./action-fusion.ts";
15
- import { commitFile, type CommitResult } from "./file-commit.ts";
16
- import { postProcessMutation } from "./mutation-result.ts";
16
+ import { commitFile } from "./file-commit.ts";
17
17
  import { executeMutation, type ActionFusionExecutor } from "./mutation-runner.ts";
18
- import { MUTATION_TOOL_GUIDELINE } from "./tool-prompts.ts";
19
18
  import { throwIfCancelled } from "./error-text.ts";
20
19
  import { createArgumentPreparer } from "./argument-validation.ts";
21
- import { unwritableTextReason } from "../core/text.ts";
22
- import { renderToolError } from "./render.ts";
20
+ import { defaultOutputBudgets, type OutputBudgetProvider } from "./budgets.ts";
21
+ import { unwritableTextError } from "../core/text.ts";
22
+ import { reportLines, renderToolError, splitReport } from "./render.ts";
23
+ import type { MutationResultDetails } from "./mutation-result.ts";
24
+ import type { ReportDetails } from "./report.ts";
23
25
 
24
26
  const writeSchema = Type.Object(
25
27
  {
@@ -28,49 +30,64 @@ const writeSchema = Type.Object(
28
30
  description: "Complete file content, written exactly as supplied, including line endings.",
29
31
  }),
30
32
  mode: Type.Union([
31
- Type.Literal("create", { description: "Fail if the target already exists" }),
32
- Type.Literal("overwrite", { description: "Fail if the target does not exist" }),
33
+ Type.Literal("create", { description: "Fail if the target already exists." }),
34
+ Type.Literal("overwrite", { description: "Fail if the target does not exist." }),
33
35
  ]),
34
36
  },
35
37
  { additionalProperties: false },
36
38
  );
37
39
 
38
- function createWriteSchema(actionFusion: boolean) {
39
- return withThenRunSchema(writeSchema, "write", actionFusion);
40
- }
41
40
  type WriteParams = Static<typeof writeSchema> & { then_run?: ThenRunInput };
42
- type WriteDetails = CommitResult & { path: string; actionFusion?: ActionFusionDetails };
41
+ /** write shows the built-in card; its report states every fact. */
42
+ type WriteMutationDetails = object;
43
+ type WriteDetails = MutationResultDetails<WriteMutationDetails>;
44
+ /** The write card's call line shows the content; the command card owns then_run. */
45
+ const WRITE_CARD_SHOWN = new Set(["publication", "created", "then_run", "progressError"]);
43
46
  type WriteRenderContext = Parameters<
44
47
  NonNullable<ReturnType<typeof createWriteToolDefinition>["renderCall"]>
45
48
  >[2];
46
49
 
47
- export function makeWriteOverride(cwd: string, fusion?: ActionFusionExecutor) {
48
- const parameters = createWriteSchema(fusion !== undefined);
50
+ export function makeWriteOverride(
51
+ cwd: string,
52
+ fusion?: ActionFusionExecutor,
53
+ budgets: OutputBudgetProvider = defaultOutputBudgets,
54
+ ) {
55
+ const parameters = withThenRunSchema(writeSchema, "write", fusion !== undefined);
49
56
  const builtin = createWriteToolDefinition(cwd);
50
57
  return {
51
58
  name: "write" as const,
52
59
  label: "write",
53
- description:
54
- "Write a whole file exactly as supplied, including its line endings. Choose create for a new file or overwrite for an existing file. Creates missing parent directories.",
60
+ description: withThenRunDescription(
61
+ "Write a whole file exactly as supplied, including its line endings. Do not use write for partial changes to an existing file; use edit or replace. Choose create for a new file or overwrite for an existing file. Creates missing parent directories.",
62
+ fusion !== undefined,
63
+ ),
55
64
  promptSnippet: "Write complete file content to a path",
56
- promptGuidelines: [MUTATION_TOOL_GUIDELINE, ...(fusion ? ACTION_FUSION_GUIDELINES : [])],
65
+ promptGuidelines: [...(fusion ? ACTION_FUSION_GUIDELINES : [])],
57
66
  parameters,
58
- prepareArguments: createArgumentPreparer("write", parameters, (args, report) => {
59
- const content = (args as { content?: unknown } | null)?.content;
60
- const reason = typeof content === "string" ? unwritableTextReason(content) : undefined;
61
- if (reason) report("content", reason);
62
- }),
67
+ prepareArguments: createArgumentPreparer(
68
+ "write",
69
+ parameters,
70
+ (args, report) => {
71
+ const content = (args as { content?: unknown } | null)?.content;
72
+ const unwritable = typeof content === "string" ? unwritableTextError(content) : undefined;
73
+ if (unwritable) report("content", unwritable.message);
74
+ },
75
+ budgets,
76
+ ),
63
77
  renderShell: "default" as const,
64
78
  renderCall(args: WriteParams, theme: Theme, context: WriteRenderContext) {
65
79
  return builtin.renderCall!(args, theme, context);
66
80
  },
67
81
  renderResult(
68
- result: AgentToolResult<WriteDetails>,
82
+ result: AgentToolResult<(Partial<WriteMutationDetails> & Partial<ReportDetails>) | undefined>,
69
83
  options: ToolRenderResultOptions,
70
84
  theme: Theme,
71
85
  context: WriteRenderContext,
72
86
  ) {
73
- if (context.isError) return renderToolError(result, theme, options.expanded);
87
+ if (context.isError) return renderToolError(result, "write", theme, options.expanded);
88
+ const { report } = splitReport(result);
89
+ const facts = report ? reportLines(report, theme, WRITE_CARD_SHOWN) : [];
90
+ if (facts.length) return new Text(facts.join("\n"), 0, 0);
74
91
  return builtin.renderResult!({ ...result, details: undefined }, options, theme, context);
75
92
  },
76
93
  async execute(
@@ -80,30 +97,22 @@ export function makeWriteOverride(cwd: string, fusion?: ActionFusionExecutor) {
80
97
  onUpdate: AgentToolUpdateCallback<WriteDetails> | undefined,
81
98
  ctx: ExtensionToolContext,
82
99
  ) {
83
- return executeMutation<Omit<WriteParams, "then_run">, WriteDetails>(
100
+ return executeMutation<WriteParams, WriteMutationDetails, "write">(
84
101
  {
102
+ tool: "write",
85
103
  cwd,
86
104
  fusion,
87
- async run(mutationParams, { absolutePath, displayPath, signal }) {
88
- throwIfCancelled(signal, `before write; ${displayPath} was not changed.`);
89
- const result = await commitFile(absolutePath, mutationParams.content, {
105
+ budgets,
106
+ async run(mutationParams, { absolutePath, signal }) {
107
+ throwIfCancelled(signal);
108
+ const commit = await commitFile(absolutePath, mutationParams.content, {
90
109
  mode: mutationParams.mode,
91
110
  signal,
92
111
  });
93
112
  return {
94
- commit: result,
95
- result: postProcessMutation("write", result.publication, () => ({
96
- content: [
97
- {
98
- type: "text" as const,
99
- text:
100
- result.publication === "NOT_PUBLISHED"
101
- ? `Wrote ${displayPath} (no net change).`
102
- : `${result.created ? "Created" : "Wrote"} ${displayPath}.`,
103
- },
104
- ],
105
- details: { path: displayPath, ...result },
106
- })),
113
+ commit,
114
+ details: {},
115
+ facts: commit.created ? { created: true } : {},
107
116
  };
108
117
  },
109
118
  },
@@ -1,13 +1,17 @@
1
+ import { rejectsArgument } from "./argument-error.testing.ts";
1
2
  import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
3
  import { tmpdir } from "node:os";
3
4
  import { join } from "node:path";
4
5
  import assert from "node:assert/strict";
5
6
  import { test } from "node:test";
6
7
  import { makeWriteOverride } from "./write-tool.ts";
7
- import { createActionFusionExecutor, THEN_RUN_STALE, THEN_RUN_SUCCEEDED } from "./action-fusion.ts";
8
- import { fileRevision } from "./file-commit.ts";
8
+ import { createActionFusionExecutor } from "./action-fusion.ts";
9
9
  import { callTool } from "./tool-call.testing.ts";
10
- import { staleTargetNotice } from "./mutation-result.ts";
10
+ import { reportOf } from "./report.ts";
11
+ import { REREAD } from "./report-schema.ts";
12
+ import { initTheme } from "@earendil-works/pi-coding-agent";
13
+ import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
14
+ initTheme("dark");
11
15
 
12
16
  const context = (cwd: string) => ({ cwd }) as any;
13
17
 
@@ -20,26 +24,16 @@ async function withTemp<T>(run: (dir: string) => Promise<T>): Promise<T> {
20
24
  }
21
25
  }
22
26
 
23
- test("write schema follows the shared actionFusion switch", () => {
24
- const plain = makeWriteOverride("/tmp");
25
- assert.equal(Object.hasOwn(plain.parameters.properties, "then_run"), false);
26
- assert.equal(Object.hasOwn(plain.parameters.properties, "expectedRevision"), false);
27
- const fusion = createActionFusionExecutor();
28
- const withFusion = makeWriteOverride("/tmp", fusion);
29
- assert.equal(Object.hasOwn(withFusion.parameters.properties, "then_run"), true);
30
- assert.equal(Object.hasOwn(withFusion.parameters.properties, "expectedRevision"), false);
31
- });
32
-
33
- test("write rejects unknown fields rather than ignoring a misspelled create mode", async () =>
27
+ test("write receives an unknown field → rejects without changing the file", async () =>
34
28
  withTemp(async (dir) => {
35
29
  const file = join(dir, "file.txt");
36
30
  await writeFile(file, "original\n");
37
31
  for (const fusion of [undefined, createActionFusionExecutor()]) {
38
32
  const tool = makeWriteOverride(dir, fusion);
39
- const args = { path: "file.txt", content: "new\n", modee: "create" };
33
+ const args = { path: "file.txt", content: "new\n", mode: "overwrite", unexpected: true };
40
34
  await assert.rejects(
41
35
  callTool(tool, args, { ctx: context(dir) }),
42
- /Validation failed for tool "write":\n {2}- modee: schema is false/,
36
+ rejectsArgument("unexpected", /not allowed/),
43
37
  );
44
38
  assert.equal(await readFile(file, "utf8"), "original\n");
45
39
  }
@@ -52,8 +46,8 @@ test("write rejects unwritable content before accessing a missing target", async
52
46
  const valid = { path: file, content: "ready\n", mode: "create" };
53
47
  assert.equal(tool.prepareArguments(valid), valid);
54
48
  for (const [content, expected] of [
55
- ["bad\0", /Invalid argument content: UNSUPPORTED_TEXT: NUL bytes are not editable\./],
56
- ["\ud800", /Invalid argument content: INVALID_UNICODE:/],
49
+ ["bad\0", rejectsArgument("content", /NUL/)],
50
+ ["\ud800", rejectsArgument("content", /encoded losslessly/)],
57
51
  ] as const) {
58
52
  await assert.rejects(
59
53
  callTool(tool, { path: file, content, mode: "create" }, { ctx: context(dir) }),
@@ -72,7 +66,7 @@ test("write omits mode → rejects before changing files or running commands", a
72
66
  let commandRuns = 0;
73
67
  const fusion = createActionFusionExecutor(async () => {
74
68
  commandRuns++;
75
- return { status: "succeeded", output: "checked" };
69
+ return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
76
70
  });
77
71
  for (const executor of [undefined, fusion]) {
78
72
  const tool = makeWriteOverride(dir, executor);
@@ -83,7 +77,7 @@ test("write omits mode → rejects before changing files or running commands", a
83
77
  { path, content: "changed\n", ...(executor ? { then_run: { command: "check" } } : {}) },
84
78
  { ctx: context(dir) },
85
79
  ),
86
- /\n {2}- mode:/,
80
+ rejectsArgument("mode", /required/),
87
81
  );
88
82
  }
89
83
  }
@@ -102,42 +96,36 @@ test("write supports create-only and overwrite-only modes", async () =>
102
96
  { path: "new.txt", content: "new\n", mode: "create" },
103
97
  options,
104
98
  );
99
+ assert.equal(created.content[0].type, "text");
105
100
  assert.doesNotMatch(created.content[0].text, /Revision:|[0-9a-f]{64}/);
106
- assert.equal(created.details.publishedRevision, await fileRevision(target));
107
- assert.equal("revision" in created.details, false);
108
- await assert.rejects(
109
- callTool(write, { path: "new.txt", content: "bad\n", mode: "create" }, options),
110
- /already exists/,
101
+ assert.deepEqual(await readFile(target), Buffer.from("new\n"));
102
+ assert.equal(reportOf(created, "write")?.publication, "PUBLISHED");
103
+ assert.equal(reportOf(created, "write")?.created, true);
104
+ const exists = await callTool(
105
+ write,
106
+ { path: "new.txt", content: "bad\n", mode: "create" },
107
+ options,
111
108
  );
109
+ assert.equal(exists.isError, true);
110
+ const conflict = reportOf(exists, "write");
111
+ assert.equal(conflict?.error, "TARGET_EXISTS");
112
+ assert.equal(conflict?.publication, "NOT_PUBLISHED");
113
+ const next = conflict?.next ?? "";
114
+ assert.match(next, /check the path/i);
115
+ assert.match(next, /read the existing file/i);
116
+ assert.match(next, /overwrite.*only if.*intended/i);
112
117
  assert.equal(await readFile(target, "utf8"), "new\n");
113
- await assert.rejects(
114
- callTool(write, { path: "missing.txt", content: "bad\n", mode: "overwrite" }, options),
115
- /does not exist/,
118
+ const missing = await callTool(
119
+ write,
120
+ { path: "missing.txt", content: "bad\n", mode: "overwrite" },
121
+ options,
116
122
  );
123
+ assert.equal(missing.isError, true);
124
+ assert.equal(reportOf(missing, "write")?.error, "PATH_NOT_FOUND");
117
125
  await callTool(write, { path: "new.txt", content: "updated\n", mode: "overwrite" }, options);
118
126
  assert.equal(await readFile(target, "utf8"), "updated\n");
119
127
  }));
120
128
 
121
- test("write rejects obsolete expectedRevision without overwriting", async () =>
122
- withTemp(async (dir) => {
123
- const target = join(dir, "concurrent.txt");
124
- await writeFile(target, "original\n");
125
- const params = {
126
- path: target,
127
- content: "changed\n",
128
- mode: "overwrite",
129
- expectedRevision: await fileRevision(target),
130
- };
131
- for (const fusion of [undefined, createActionFusionExecutor()]) {
132
- const write = makeWriteOverride(dir, fusion);
133
- await assert.rejects(
134
- callTool(write, params, { ctx: context(dir) }),
135
- /Validation failed for tool "write":\n {2}- expectedRevision: schema is false/,
136
- );
137
- assert.equal(await readFile(target, "utf8"), "original\n");
138
- }
139
- }));
140
-
141
129
  test("write returns only a summary for empty, short, and long content", async () =>
142
130
  withTemp(async (dir) => {
143
131
  const contents = [
@@ -154,7 +142,13 @@ test("write returns only a summary for empty, short, and long content", async ()
154
142
  undefined,
155
143
  context(dir),
156
144
  );
157
- assert.deepEqual(result.content, [{ type: "text", text: `Created ${path}.` }]);
145
+ assert.equal(reportOf(result, "write")?.created, true);
146
+ assert.equal(reportOf(result, "write")?.path, path);
147
+ assert.equal(reportOf(result, "write")?.publication, "PUBLISHED");
148
+ assert.equal(result.content.length, 1);
149
+ const block = result.content[0];
150
+ assert.equal(block.type, "text");
151
+ assert.deepEqual(JSON.parse(block.text), { publication: "PUBLISHED", created: true });
158
152
  assert.equal(await readFile(join(dir, path), "utf8"), content);
159
153
  }
160
154
  }));
@@ -163,7 +157,7 @@ test("write returns its summary and command output after an unchanged then_run",
163
157
  withTemp(async (dir) => {
164
158
  const fusion = createActionFusionExecutor(async () => ({
165
159
  status: "succeeded",
166
- output: "checked",
160
+ result: { content: [{ type: "text", text: "checked" }] },
167
161
  }));
168
162
  const write = makeWriteOverride(dir, fusion) as any;
169
163
  const result = await write.execute(
@@ -178,11 +172,11 @@ test("write returns its summary and command output after an unchanged then_run",
178
172
  undefined,
179
173
  context(dir),
180
174
  );
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");
175
+ assert.equal(reportOf(result, "write")?.created, true);
176
+ assert.deepEqual(reportOf(result, "write")?.then_run, {
177
+ status: "succeeded",
178
+ output: "checked",
179
+ });
186
180
  }));
187
181
 
188
182
  test("write reports changed freshness when then_run changes the target", async () =>
@@ -190,7 +184,7 @@ test("write reports changed freshness when then_run changes the target", async (
190
184
  const target = join(dir, "changed.txt");
191
185
  const fusion = createActionFusionExecutor(async () => {
192
186
  await writeFile(target, "command changed\n");
193
- return { status: "succeeded", output: "checked" };
187
+ return { status: "succeeded", result: { content: [{ type: "text", text: "checked" }] } };
194
188
  });
195
189
  const write = makeWriteOverride(dir, fusion) as any;
196
190
  const result = await callTool(
@@ -205,17 +199,21 @@ test("write reports changed freshness when then_run changes the target", async (
205
199
  );
206
200
  const text = result.content.map((block: any) => block.text).join("\n");
207
201
  assert.doesNotMatch(text, /revision:|[0-9a-f]{64}/i);
208
- assert.deepEqual(result.content, [
209
- { type: "text", text: "Created changed.txt." },
210
- { type: "text", text: staleTargetNotice(THEN_RUN_STALE) },
211
- { type: "text", text: `${THEN_RUN_SUCCEEDED}\nchecked` },
212
- ]);
213
- assert.doesNotMatch(text, /Fresh anchors:|\b1#[0-9A-Z]+\b/);
214
- assert.equal(result.details.actionFusion.freshness, "changed");
215
- assert.deepEqual(
216
- write.renderResult(result, { isPartial: false }, {}, { isError: false }).render(100),
217
- [],
218
- );
202
+ assert.equal(reportOf(result, "write")?.created, true);
203
+ assert.equal(reportOf(result, "write")?.freshness, "changed");
204
+ assert.equal(reportOf(result, "write")?.next, REREAD);
205
+ assert.deepEqual(reportOf(result, "write")?.then_run, {
206
+ status: "succeeded",
207
+ output: "checked",
208
+ });
209
+ assert.doesNotMatch(text, /\b1#[0-9A-Z]+\b/);
210
+ const rendered = write
211
+ .renderResult(result, { isPartial: false }, theme, { isError: false })
212
+ .render(100)
213
+ .join("\n");
214
+ assert.match(rendered, /changed/);
215
+ assert.match(rendered, /Read the file/);
216
+ assert.doesNotMatch(rendered, /Command|checked/);
219
217
  }));
220
218
 
221
219
  test("write reports missing freshness when then_run removes the target", async () =>
@@ -223,7 +221,7 @@ test("write reports missing freshness when then_run removes the target", async (
223
221
  const target = join(dir, "missing.txt");
224
222
  const fusion = createActionFusionExecutor(async () => {
225
223
  await rm(target);
226
- return { status: "succeeded", output: "removed" };
224
+ return { status: "succeeded", result: { content: [{ type: "text", text: "removed" }] } };
227
225
  });
228
226
  const result = await makeWriteOverride(dir, fusion).execute(
229
227
  "missing",
@@ -237,11 +235,8 @@ test("write reports missing freshness when then_run removes the target", async (
237
235
  undefined,
238
236
  context(dir),
239
237
  );
240
- const text = result.content.map((block: any) => block.text).join("\n");
241
- assert.ok(result.details.actionFusion);
242
- assert.equal(result.details.actionFusion.freshness, "missing");
243
- assert.match(text, /Re-read/);
244
- assert.doesNotMatch(text, /Fresh anchors:/);
238
+ assert.equal(reportOf(result, "write")?.freshness, "missing");
239
+ assert.equal(reportOf(result, "write")?.next, REREAD);
245
240
  }));
246
241
 
247
242
  test("write preserves command failure and changed freshness", async () =>
@@ -258,26 +253,7 @@ test("write preserves command failure and changed freshness", async () =>
258
253
  undefined,
259
254
  context(dir),
260
255
  );
261
- const text = result.content.map((block: any) => block.text).join("\n");
262
- assert.ok(result.details.actionFusion);
263
- assert.equal(result.details.actionFusion.freshness, "changed");
264
- assert.equal(result.details.actionFusion.command, "failed");
265
- assert.match(text, /Re-read/);
266
- assert.doesNotMatch(text, /Fresh anchors:/);
267
- }));
268
-
269
- test("write rejects NUL content", async () =>
270
- withTemp(async (dir) => {
271
- const write = makeWriteOverride(dir);
272
- await assert.rejects(
273
- write.execute(
274
- "nul",
275
- { path: "nul.txt", content: "a\0b", mode: "create" },
276
- undefined,
277
- undefined,
278
- context(dir),
279
- ),
280
- /UNSUPPORTED_TEXT/,
281
- );
282
- await assert.rejects(readFile(join(dir, "nul.txt")), /ENOENT/);
256
+ assert.equal(reportOf(result, "write")?.freshness, "changed");
257
+ assert.equal(reportOf(result, "write")?.then_run?.status, "failed");
258
+ assert.equal(reportOf(result, "write")?.next, REREAD);
283
259
  }));
@@ -0,0 +1,24 @@
1
+ /** Use Pi's embedded-runtime module mapping against an isolated extension installation. */
2
+ import assert from "node:assert/strict";
3
+ import { createRequire } from "node:module";
4
+ import type { ExtensionFactory } from "@earendil-works/pi-coding-agent";
5
+ import { createJiti } from "../../node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/jiti-static-loader.js";
6
+ import { VIRTUAL_MODULES } from "../../node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/virtual-modules.js";
7
+
8
+ export async function loadInstalledExtension(entry: string): Promise<ExtensionFactory> {
9
+ const require = createRequire(entry);
10
+ assert.throws(() => require.resolve("@earendil-works/pi-coding-agent"), {
11
+ code: "MODULE_NOT_FOUND",
12
+ });
13
+ // typebox is a host-provided peer: the installed layout must NOT resolve its own
14
+ // copy; jiti's virtualModules supply it instead.
15
+ assert.throws(() => require.resolve("typebox/type"), { code: "MODULE_NOT_FOUND" });
16
+ const jiti = createJiti(import.meta.url, {
17
+ moduleCache: false,
18
+ virtualModules: VIRTUAL_MODULES,
19
+ tryNative: false,
20
+ });
21
+ const factory = await jiti.import<ExtensionFactory>(entry, { default: true });
22
+ assert.equal(typeof factory, "function");
23
+ return factory;
24
+ }
@@ -0,0 +1,77 @@
1
+ /** Isolated installed-package layouts with only npm's locked production dependency tree. */
2
+ import assert from "node:assert/strict";
3
+ import { cp, mkdir, mkdtemp, readdir, rm, stat } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { dirname, join, relative } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import type { TestContext } from "node:test";
8
+ import manifest from "../../package.json" with { type: "json" };
9
+ import lock from "../../package-lock.json" with { type: "json" };
10
+ import { runTestProcess } from "./process.testing.ts";
11
+
12
+ const repository = fileURLToPath(new URL("../../", import.meta.url));
13
+
14
+ export async function installedExtension(t: TestContext, source: "source" | "packed" = "source") {
15
+ const root = await mkdtemp(join(tmpdir(), "hashline-install-"));
16
+ t.after(() => rm(root, { recursive: true, force: true }));
17
+ const packageDir = join(root, "node_modules", manifest.name);
18
+ const agentDir = join(root, "agent");
19
+ await mkdir(packageDir, { recursive: true });
20
+ await mkdir(agentDir);
21
+ for (const [path, metadata] of Object.entries(lock.packages)) {
22
+ if (
23
+ !path ||
24
+ ("dev" in metadata && metadata.dev) ||
25
+ ("devOptional" in metadata && metadata.devOptional)
26
+ )
27
+ continue;
28
+ const dependency = join(repository, path);
29
+ try {
30
+ await stat(dependency);
31
+ } catch (error) {
32
+ if (
33
+ error instanceof Error &&
34
+ "code" in error &&
35
+ error.code === "ENOENT" &&
36
+ "optional" in metadata &&
37
+ metadata.optional
38
+ )
39
+ continue;
40
+ throw error;
41
+ }
42
+ // Copy instead of linking: dependency resolution must not walk back into the checkout.
43
+ await cp(dependency, join(root, path), {
44
+ recursive: true,
45
+ dereference: true,
46
+ filter: (candidate) => candidate !== join(dependency, "node_modules"),
47
+ });
48
+ }
49
+ if (source === "packed") {
50
+ const npmCli =
51
+ process.env.npm_execpath ??
52
+ join(
53
+ dirname(process.execPath),
54
+ process.platform === "win32"
55
+ ? "node_modules/npm/bin/npm-cli.js"
56
+ : "../lib/node_modules/npm/bin/npm-cli.js",
57
+ );
58
+ await runTestProcess(
59
+ process.execPath,
60
+ [npmCli, "pack", "--ignore-scripts", "--pack-destination", root],
61
+ repository,
62
+ agentDir,
63
+ );
64
+ const archives = (await readdir(root)).filter((name) => name.endsWith(".tgz"));
65
+ assert.equal(archives.length, 1, "npm pack must produce one archive");
66
+ await runTestProcess(
67
+ "tar",
68
+ ["-xzf", archives[0], "-C", relative(root, packageDir), "--strip-components=1"],
69
+ root,
70
+ agentDir,
71
+ );
72
+ } else {
73
+ await cp(join(repository, "src"), join(packageDir, "src"), { recursive: true });
74
+ await cp(join(repository, "package.json"), join(packageDir, "package.json"));
75
+ }
76
+ return { root, packageDir, agentDir, entry: join(packageDir, manifest.pi.extensions[0]) };
77
+ }
@@ -0,0 +1,33 @@
1
+ /** Own the environment used by test runners and isolated package probes. */
2
+ import { execFile as execFileCallback } from "node:child_process";
3
+ import { promisify } from "node:util";
4
+
5
+ const execFile = promisify(execFileCallback);
6
+ const PROCESS_TIMEOUT_MS = 60_000;
7
+
8
+ export function testEnvironment(agentDir: string): NodeJS.ProcessEnv {
9
+ const env = Object.fromEntries(
10
+ Object.entries(process.env).filter(([key]) => {
11
+ const name = key.toUpperCase();
12
+ return (
13
+ !["NODE_OPTIONS", "NODE_PATH", "PI_CODING_AGENT_DIR"].includes(name) &&
14
+ !name.startsWith("JITI_")
15
+ );
16
+ }),
17
+ );
18
+ return { ...env, PI_CODING_AGENT_DIR: agentDir };
19
+ }
20
+
21
+ /** Start a bounded child without shell interpretation or inherited Node loaders. */
22
+ export async function runTestProcess(
23
+ command: string,
24
+ args: readonly string[],
25
+ cwd: string,
26
+ agentDir: string,
27
+ ) {
28
+ return execFile(command, args, {
29
+ cwd,
30
+ env: testEnvironment(agentDir),
31
+ timeout: PROCESS_TIMEOUT_MS,
32
+ });
33
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Host V8 regex support. Pi supports Node 22.19.0, whose V8 rejects modifier groups
3
+ * (`(?i:…)`) and duplicate named groups; grep validates patterns with the host engine, so
4
+ * cases that need this syntax run only where the host compiles them.
5
+ */
6
+ export function hostCompiles(pattern: string, flags = ""): boolean {
7
+ try {
8
+ new RegExp(pattern, flags);
9
+ return true;
10
+ } catch {
11
+ return false;
12
+ }
13
+ }
14
+
15
+ /** Skip reason for `test`/`t.test` options when the host cannot compile every pattern. */
16
+ export function unsupportedByHost(patterns: readonly string[], flags = ""): string | false {
17
+ return patterns.every((pattern) => hostCompiles(pattern, flags))
18
+ ? false
19
+ : `host V8 ${process.version} cannot compile this regex syntax`;
20
+ }