Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(runtime): canonicalize mutation recovery path identities
cauliflowera06e14eb34ad
diff --git a/docs/spec/03-runtime/18-line-anchored-edit-contract.md b/docs/spec/03-runtime/18-line-anchored-edit-contract.mdindex 028178922..39b51e807 100644--- a/docs/spec/03-runtime/18-line-anchored-edit-contract.md+++ b/docs/spec/03-runtime/18-line-anchored-edit-contract.md@@ -474,6 +474,17 @@ occurrence, because repeating one of those means the model is guessing.Counting a grace is per code, not per call, so a stale tag followed by unseenlines is two distinct honest failures while the same code twice is not.+The runtime identifies an existing target by its filesystem canonical path,+resolved against the session project (or scratch root for a temporary session)+before the mutation runs. Relative and+absolute spellings, lexical `.`/`..`, directory links, and filesystem-supported+case aliases therefore share the failure count, per-code grace, and successful+mutation reset. Case-distinct files retain separate budgets. If canonicalization+is unavailable (for example, a missing target), the normalized absolute path is+the bookkeeping fallback. This identity never changes the submitted tool path+or replaces Host permission and workspace checks; delegate budgets remain+isolated from the parent and from other delegate runs.+Counts and per-code graces belong to the executing parent turn or delegaterun. Parallel delegates working on the same path do not share failures orsuccessful-write resets. A new parent prompt resets only the parent's recoverydiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 89c75b8a4..7887eebd0 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -16979,6 +16979,19 @@ host-created files. The full app's file-preview viewer is covered separately.with optional `--single` and `--patch`; runtime tests cover parent restart.+## Mutation recovery file aliases++- Retry a failing Edit using relative, absolute, `.`/`..`, directory-link and+ Windows case-alias spellings of the same existing file. The third counted+ failure terminates; changing spelling does not grant another recoverable-code+ grace. Distinct files retain independent budgets.+- Successfully Edit or Write through an alias and retry: the count and grace+ reset. Removing the file through a linked path clears its pre-mutation identity.+- Repeat relative/absolute aliases in a temporary session: its scratch root is+ the relative base. Case-distinct POSIX files remain separate.+- Automated filesystem/runtime boundary coverage: `runtime.test.ts` and+ `mutation-recovery.test.ts`; no UI, production profile or real provider is used.+## Regenerate archival during quit- Regenerate a completed answer and quit as soon as the terminal event arrives.diff --git a/packages/agent-runtime/src/mutation-recovery.test.ts b/packages/agent-runtime/src/mutation-recovery.test.tsnew file mode 100644index 000000000..56086e5a4--- /dev/null+++ b/packages/agent-runtime/src/mutation-recovery.test.ts@@ -0,0 +1,40 @@+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";+import { describe, expect, it } from "vitest";+import { mutationFailureKey } from "./mutation-recovery.js";++describe("mutationFailureKey", () => {+ it("uses a stable lexical identity when the target does not exist", async () => {+ const root = await mkdtemp(join(tmpdir(), "pi-missing-edit-"));+ try {+ const expected = resolve(root, "missing", "example.ts");+ expect(await mutationFailureKey("missing/example.ts", root)).toBe(expected);+ expect(await mutationFailureKey("./missing/sub/../example.ts", root)).toBe(expected);+ expect(await mutationFailureKey(expected, root)).toBe(expected);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });++ it.skipIf(process.platform === "win32")("keeps existing case-distinct files independent", async () => {+ const root = await mkdtemp(join(tmpdir(), "pi-case-edit-"));+ try {+ await writeFile(join(root, "a.ts"), "lower\n");+ await writeFile(join(root, "A.ts"), "upper\n");+ expect(await mutationFailureKey("a.ts", root)).not.toBe(await mutationFailureKey("A.ts", root));+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });++ it.skipIf(process.platform === "win32")("preserves POSIX backslashes in file names", async () => {+ const root = await mkdtemp(join(tmpdir(), "pi-backslash-edit-"));+ try {+ await writeFile(join(root, "a\\b.ts"), "literal\n");+ expect(await mutationFailureKey("a\\b.ts", root)).toBe(join(root, "a\\b.ts"));+ } finally {+ await rm(root, { recursive: true, force: true });+ }+ });+});diff --git a/packages/agent-runtime/src/mutation-recovery.ts b/packages/agent-runtime/src/mutation-recovery.tsindex bfee1c94f..9c51d5cf6 100644--- a/packages/agent-runtime/src/mutation-recovery.ts+++ b/packages/agent-runtime/src/mutation-recovery.ts@@ -1,3 +1,6 @@+import { realpath } from "node:fs/promises";+import { resolve } from "node:path";+export const MAX_MUTATION_RECOVERY_FAILURES = 3;export const BASH_PATCH_FAILURE_KEY = "__bash_patch_command__";/**@@ -37,8 +40,21 @@ export function mutationTerminationAdvice(}return "Re-read the live file, regenerate a narrower Edit, and avoid repeating the same payload.";}-export function mutationFailureKey(path: unknown): string {- return String(path).replaceAll("\\", "/").replace(/^\.\//, "");+/** Bookkeeping identity only; Host still resolves and authorizes the original path. */+export async function mutationFailureKey(path: string, projectPath?: string): Promise<string> {+ const absolute = resolve(projectPath ?? process.cwd(), path);+ try {+ // The runtime and Host run on the same machine, including headless hosts.+ // Keep the filesystem's canonical spelling: lowercasing would merge distinct+ // files on POSIX and on case-sensitive Windows directories.+ return await realpath(absolute);+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ if (!["ENOENT", "ENOTDIR", "EACCES", "EPERM", "EINVAL", "ELOOP"].includes(code ?? "")) throw error;+ // Missing or inaccessible targets have no usable canonical spelling. Keep+ // their lexical identity, and let the Host report the actual tool error.+ return absolute;+ }}export function isPatchCommand(command: unknown): boolean {diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex 1eb99db16..4dc5dc350 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -1,4 +1,4 @@-import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { describe, expect, it, vi } from "vitest";@@ -210,6 +210,13 @@ function createRuntime(});}+function runtimeTool(runtime: DesktopAgentRuntime, name: string): AgentTool {+ const internal = runtime as unknown as { agent: { state: { tools: AgentTool[] } } };+ const tool = internal.agent.state.tools.find((entry) => entry.name === name);+ if (!tool) throw new Error(`Runtime tool not found: ${name}`);+ return tool;+}+/** Minimal pi-ai assistant message; overrides carry the shape under test. */function assistantMessage(overrides: {content: unknown[];@@ -700,6 +707,151 @@ describe("DesktopAgentRuntime configuration matching", () => {await runtime.dispose();});+ it.each(["lexical", "directory-link", ...(process.platform === "win32" ? ["windows-case"] : [])])(+ "shares Edit failure counts across %s file aliases", async (aliasKind) => {+ const root = await mkdtemp(join(tmpdir(), "pi-edit-identity-"));+ await mkdir(join(root, "src"));+ await writeFile(join(root, "src", "example.ts"), "original\n");+ let aliases = ["src/example.ts", "src/./example.ts", join(root, "src", "..", "src", "example.ts")];+ if (aliasKind === "directory-link") {+ await symlink(join(root, "src"), join(root, "linked"), process.platform === "win32" ? "junction" : "dir");+ aliases = ["src/example.ts", "linked/example.ts", join(root, "linked", "example.ts")];+ } else if (aliasKind === "windows-case") {+ aliases = ["src/example.ts", "SRC/EXAMPLE.TS", join(root, "SRC", "example.ts")];+ }+ const host = { call: vi.fn(async (method: string, _params?: unknown) => method === "tools.execute"+ ? { ok: false, isError: true, errorCode: "EDIT_PARSE_FAILED", content: {} }+ : undefined) };+ const runtime = createRuntime({ host, projectPath: root });+ const edit = runtimeTool(runtime, "Edit");+ try {+ for (const [index, path] of aliases.entries()) {+ const result = await edit.execute(`alias-${index}`, { path, tag: "ABCD", ops: "bad ops" });+ expect(result.terminate).toBe(index === 2 ? true : undefined);+ }+ // Bookkeeping must not rewrite arguments or replace Host authority.+ expect(host.call.mock.calls.filter(([method]) => method === "tools.execute").map(([, params]) => (params as { args: { path: string } }).args.path)).toEqual(aliases);+ } finally {+ await runtime.dispose();+ await rm(root, { recursive: true, force: true });+ }+ },+ );++ it("shares recoverable Edit grace across file aliases", async () => {+ const root = await mkdtemp(join(tmpdir(), "pi-edit-grace-"));+ await writeFile(join(root, "example.ts"), "original\n");+ const host = { call: vi.fn(async (method: string) => method === "tools.execute"+ ? { ok: false, isError: true, errorCode: "EDIT_TAG_MISMATCH", content: {} }+ : undefined) };+ const runtime = createRuntime({ host, projectPath: root });+ const edit = runtimeTool(runtime, "Edit");+ try {+ const aliases = ["example.ts", "./example.ts", join(root, "example.ts"), "sub/../example.ts"];+ for (const [index, path] of aliases.entries()) {+ const result = await edit.execute(`grace-${index}`, { path, tag: "ABCD", ops: "PUT 1.=1:\n+fresh" });+ expect(result.terminate).toBe(index === 3 ? true : undefined);+ }+ } finally {+ await runtime.dispose();+ await rm(root, { recursive: true, force: true });+ }+ });++ it.each(["Edit", "Write"])("clears alias failure counts and graces after successful %s", async (toolName) => {+ const root = await mkdtemp(join(tmpdir(), "pi-edit-reset-"));+ await writeFile(join(root, "example.ts"), "original\n");+ let callIndex = 0;+ const host = { call: vi.fn(async (method: string) => {+ if (method !== "tools.execute") return undefined;+ return ++callIndex === 4+ ? { ok: true, content: { tag: "CDEF" } }+ : { ok: false, isError: true, errorCode: "EDIT_TAG_MISMATCH", content: {} };+ }) };+ const runtime = createRuntime({ host, projectPath: root });+ const edit = runtimeTool(runtime, "Edit");+ const succeedingTool = runtimeTool(runtime, toolName);+ try {+ const args = { path: "example.ts", tag: "ABCD", ops: "PUT 1.=1:\n+fresh", content: "fresh" };+ for (let i = 0; i < 3; i++) expect((await edit.execute(`before-${i}`, args)).terminate).toBeUndefined();+ expect((await succeedingTool.execute("success", { ...args, path: join(root, "example.ts") })).isError).toBe(false);+ for (let i = 0; i < 4; i++) {+ const result = await edit.execute(`after-${i}`, args);+ expect(result.terminate).toBe(i === 3 ? true : undefined);+ }+ } finally {+ await runtime.dispose();+ await rm(root, { recursive: true, force: true });+ }+ });++ it("keeps different files' Edit failure budgets independent", async () => {+ const root = await mkdtemp(join(tmpdir(), "pi-edit-independent-"));+ await writeFile(join(root, "a.ts"), "a\n");+ await writeFile(join(root, "b.ts"), "b\n");+ const host = { call: vi.fn(async (method: string) => method === "tools.execute"+ ? { ok: false, isError: true, errorCode: "EDIT_PARSE_FAILED", content: {} }+ : undefined) };+ const runtime = createRuntime({ host, projectPath: root });+ const edit = runtimeTool(runtime, "Edit");+ try {+ for (const [index, path] of ["a.ts", "./a.ts", "b.ts", join(root, "a.ts")].entries()) {+ const result = await edit.execute(`independent-${index}`, { path, tag: "ABCD", ops: "bad ops" });+ expect(result.terminate).toBe(index === 3 ? true : undefined);+ }+ } finally {+ await runtime.dispose();+ await rm(root, { recursive: true, force: true });+ }+ });++ it("uses the scratch root for temporary-session Edit aliases", async () => {+ const root = await mkdtemp(join(tmpdir(), "pi-scratch-edit-"));+ await writeFile(join(root, "example.ts"), "original\n");+ const host = { call: vi.fn(async (method: string) => method === "tools.execute"+ ? { ok: false, isError: true, errorCode: "EDIT_PARSE_FAILED", content: {} }+ : undefined) };+ const runtime = createRuntime({ host, scratchDir: root });+ const edit = runtimeTool(runtime, "Edit");+ try {+ for (const [index, path] of ["example.ts", join(root, "example.ts"), "./example.ts"].entries()) {+ const result = await edit.execute(`scratch-${index}`, { path, tag: "ABCD", ops: "bad ops" });+ expect(result.terminate).toBe(index === 2 ? true : undefined);+ }+ } finally {+ await runtime.dispose();+ await rm(root, { recursive: true, force: true });+ }+ });++ it("clears the pre-mutation identity when a successful Edit removes a linked target", async () => {+ const root = await mkdtemp(join(tmpdir(), "pi-remove-edit-"));+ await mkdir(join(root, "src"));+ await writeFile(join(root, "src", "example.ts"), "original\n");+ await symlink(join(root, "src"), join(root, "linked"), process.platform === "win32" ? "junction" : "dir");+ let callIndex = 0;+ const host = { call: vi.fn(async (method: string) => {+ if (method !== "tools.execute") return undefined;+ if (++callIndex === 3) {+ await rm(join(root, "linked", "example.ts"));+ return { ok: true, content: {} };+ }+ return { ok: false, isError: true, errorCode: "EDIT_PARSE_FAILED", content: {} };+ }) };+ const runtime = createRuntime({ host, projectPath: root });+ const edit = runtimeTool(runtime, "Edit");+ try {+ const args = { path: "src/example.ts", tag: "ABCD", ops: "bad ops" };+ expect((await edit.execute("remove-before-1", args)).terminate).toBeUndefined();+ expect((await edit.execute("remove-before-2", args)).terminate).toBeUndefined();+ expect((await edit.execute("remove-success", { ...args, path: "linked/example.ts", ops: "REM" })).isError).toBe(false);+ expect((await edit.execute("remove-after", args)).terminate).toBeUndefined();+ } finally {+ await runtime.dispose();+ await rm(root, { recursive: true, force: true });+ }+ });+it("terminates repeated failed shell patch recovery", async () => {const host = {call: vi.fn().mockResolvedValue({diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex 4dff3fd77..b136011a0 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -3244,6 +3244,9 @@ Do not invent objections or turn speculative risks into blockers. Stop when thesignal,onUpdate,) => {+ const mutationPath = PATH_MUTATING_TOOLS.has(toolName) && isRecord(params) && typeof params.path === "string"+ ? await mutationFailureKey(params.path, this.projectPath ?? this.scratchDir)+ : undefined;await this.loadPathInstructions(toolName, params);const isBash = toolName === "Bash";const timeoutMs = isBash ? commandTimeoutMs(params) : undefined;@@ -3398,7 +3401,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when thetoolName === "Edit" &&failedToolExecution &&typeof recordParams?.path === "string"- ? mutationFailureKey(recordParams.path)+ ? recordParams.path: undefined;const failedPatchCommand =toolName === "Bash" &&@@ -3406,7 +3409,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when theisPatchCommand(recordParams?.command);const mutationOwner = this.mutationOwners.get(toolCallId);const targetKey = failedEditPath- ? failedEditPath+ ? mutationPath: failedPatchCommand? BASH_PATCH_FAILURE_KEY: undefined;@@ -3449,7 +3452,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when theif (!failureKey && result.ok) {const succeededTarget =PATH_MUTATING_TOOLS.has(toolName) && typeof recordParams?.path === "string"- ? mutationFailureKey(recordParams.path)+ ? mutationPath: toolName === "Bash" && isPatchCommand(recordParams?.command)? BASH_PATCH_FAILURE_KEY: undefined;