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(agent-runtime): match heredoc delimiters exactly and queue pending bodies
liuzixiang229d0a38b49c
diff --git a/packages/agent-runtime/src/mutation-recovery.test.ts b/packages/agent-runtime/src/mutation-recovery.test.tsindex 6fde35ed5..2c71c1056 100644--- a/packages/agent-runtime/src/mutation-recovery.test.ts+++ b/packages/agent-runtime/src/mutation-recovery.test.ts@@ -127,4 +127,30 @@ describe("isPatchCommand", () => {expect(isPatchCommand("patch <<'EOF'\nbody\nEOF")).toBe(true);expect(isPatchCommand("apply_patch <<'EOF'\n*** Begin Patch\nEOF")).toBe(true);});++ it("matches heredoc delimiters exactly, stripping tabs only for <<-", () => {+ // #2016 review round three: `line.trim()` accepted a space-prefixed+ // delimiter, so ` EOF` ended the body early and the lines after it — the+ // real payload — became commands.+ expect(isPatchCommand("cat <<'EOF'\n EOF\nordinary text\npatch notes\nEOF")).toBe(false);+ expect(isPatchCommand("cat <<EOF\n\tEOF\npatch -p1 < x.diff")).toBe(false);+ // `<<-` is the one form whose delimiter may carry leading tabs.+ expect(isPatchCommand("cat <<-EOF\n\tbody\n\tEOF\npatch -p1 < x.diff")).toBe(true);+ expect(isPatchCommand("cat <<-'EOF'\n\tbody\n\tEOF\npatch notes")).toBe(true);+ // `<<-` strips tabs only: a space-prefixed delimiter still does not close.+ expect(isPatchCommand("cat <<-EOF\n body\n EOF\npatch notes\nEOF")).toBe(false);+ });++ it("queues every heredoc on the opening line before reading bodies", () => {+ // #2016 review round three: one stored tag made the parser treat the+ // second redirect as payload on the opening line, so `cat <<A <<B` never+ // consumed B's body and ordinary text after A became commands.+ expect(isPatchCommand("cat <<A <<B\nA\nordinary text\npatch notes\nB")).toBe(false);+ expect(isPatchCommand("cat <<A <<B\nA\nB\npatch notes")).toBe(true);+ // The opening line is not body: a patch after `;` on it still executes.+ expect(isPatchCommand("cat <<EOF; git apply p.diff\nbody\nEOF")).toBe(true);+ expect(isPatchCommand("cat <<A <<B; patch -p1 < x.diff\nA\nB")).toBe(true);+ // Both spellings of the first tag still queue with a later one.+ expect(isPatchCommand("cat <<-'A' <<\"B\"\n\tbody\n\tA\nB\npatch notes")).toBe(true);+ });});diff --git a/packages/agent-runtime/src/mutation-recovery.ts b/packages/agent-runtime/src/mutation-recovery.tsindex d812e8c3c..545ee77b0 100644--- a/packages/agent-runtime/src/mutation-recovery.ts+++ b/packages/agent-runtime/src/mutation-recovery.ts@@ -70,6 +70,14 @@ export async function mutationFailureKey(path: string, projectPath?: string): Pr* is not a patch and `kubectl apply` after `git pull` is not a git patch* (#1985).*+ * Heredoc bookkeeping follows the shell's ordering, not the tag's: every `<<`+ * on the opening line is queued, and the queue is drained in tag order only+ * once that line ends. So `cat <<A <<B` consumes both bodies instead of+ * treating `<<B` as payload, and `cat <<EOF; git apply p.diff` still counts+ * the patch on its opening line. A closing delimiter must be the whole line;+ * `<<-` strips leading tabs from it and nothing else, so a space-prefixed+ * ` EOF` stays payload (#2016 review round three).+ ** This is best-effort segmentation for the recovery guard, not a shell* parser: quotes, backslash escapes, comments and heredocs are modeled,* shell grammar like command substitution is not — an unmodeled construct@@ -78,22 +86,28 @@ export async function mutationFailureKey(path: string, projectPath?: string): Pr* recovery, and widening this into real shell parsing is never worth the* false positives.*/+type HeredocBody = { tag: string; stripTabs: boolean };+function splitCommandSegments(command: string): string[] {const segments: string[] = [];let current = "";let quote: '"' | "'" | null = null;- /** When set, whole lines are heredoc payload until a line holding the tag. */- let heredocTag: string | null = null;+ /** Tags found on the open line whose bodies follow it, in tag order. */+ const queued: HeredocBody[] = [];+ /** When set, whole lines are this heredoc's payload until its delimiter. */+ let body: HeredocBody | null = null;let index = 0;while (index < command.length) {const char = command[index]!;- if (heredocTag !== null) {- // The body and its closing tag line are data; the closing line is not a- // command either. An unmatched tag consumes the rest — a real shell- // would read the same lines as stdin.+ if (body !== null) {+ // Body lines and the closing delimiter line are data, never commands.+ // An unmatched tag consumes the rest: a real shell would read the same+ // lines as stdin, and inventing a patch from them is the failure this+ // guard exists to avoid.const lineEnd = command.indexOf("\n", index);const line = lineEnd === -1 ? command.slice(index) : command.slice(index, lineEnd);- if (line.trim() === heredocTag) heredocTag = null;+ const delimiter = body.stripTabs ? line.replace(/^\t+/, "") : line;+ if (delimiter === body.tag) body = queued.shift() ?? null;index = lineEnd === -1 ? command.length : lineEnd + 1;continue;}@@ -137,7 +151,10 @@ function splitCommandSegments(command: string): string[] {}const tag = parseHeredocTag(command, index + 2);if (tag !== null) {- heredocTag = tag.text;+ // Collect only: the body starts after this whole line ends, so a+ // second redirect on the same line (`cat <<A <<B`) is queued instead+ // of being swallowed as A's payload.+ queued.push({ tag: tag.text, stripTabs: tag.stripTabs });index = tag.end;continue;}@@ -147,6 +164,8 @@ function splitCommandSegments(command: string): string[] {segments.push(current);current = "";index += 1;+ // The opening line is complete: its heredoc bodies follow, in tag order.+ if (char === "\n" && queued.length > 0) body = queued.shift()!;continue;}current += char;@@ -156,10 +175,22 @@ function splitCommandSegments(command: string): string[] {return segments;}-/** Read the tag after `<<` (or `<<-`). Null when there is no tag word. */-function parseHeredocTag(command: string, start: number): { text: string; end: number } | null {+/**+ * Read the tag after `<<` (or `<<-`). Null when there is no tag word.+ *+ * `stripTabs` reports the `<<-` form, whose delimiter line may carry leading+ * tabs; every other form requires the tag to be the whole line.+ */+function parseHeredocTag(+ command: string,+ start: number,+): { text: string; stripTabs: boolean; end: number } | null {let index = start;- if (command[index] === "-") index += 1;+ let stripTabs = false;+ if (command[index] === "-") {+ stripTabs = true;+ index += 1;+ }let text = "";let quote: '"' | "'" | null = null;while (index < command.length) {@@ -183,7 +214,7 @@ function parseHeredocTag(command: string, start: number): { text: string; end: ntext += char;index += 1;}- return text ? { text, end: index } : null;+ return text ? { text, stripTabs, end: index } : null;}/**diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex b3942f183..dc6ce5bbd 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -2047,6 +2047,69 @@ describe("DesktopAgentRuntime configuration matching", () => {await runtime.dispose();});+ it("never reaches the patch budget for heredoc forms that only look closed", async () => {+ // #2016 review round three: a space-prefixed delimiter ended the body+ // early, and a second heredoc on the opening line was swallowed as the+ // first one's payload. In both scripts the `patch` lines are stdin, so+ // repeated ordinary failures must not terminate the turn.+ const host = {+ call: vi.fn().mockResolvedValue({+ ok: false,+ isError: true,+ errorCode: "TOOL_FAILED",+ content: { exitCode: 1, stderr: "no match" },+ }),+ };+ const runtime = createRuntime({ host });+ const agent = (runtime as any).agent;+ const bash = agent.state.tools.find((tool: any) => tool.name === "Bash");+ const payloadOnly = [+ { command: "cat <<'EOF'\n EOF\nordinary text\npatch notes\nEOF" },+ { command: "cat <<A <<B\nA\nordinary text\npatch notes\nB" },+ { command: "cat <<EOF\n\tEOF\npatch -p1 < x.diff" },+ ];+ for (const [index, args] of payloadOnly.entries()) {+ for (let attempt = 1; attempt <= 5; attempt += 1) {+ const id = `looks-closed-${index}-${attempt}`;+ const result = await bash.execute(id, args);+ await expect(agent.afterToolCall({ toolCall: { id } })).resolves.toEqual({+ isError: true,+ });+ expect(result.terminate).toBeUndefined();+ }+ }++ await runtime.dispose();+ });++ it("terminates repeated failures of a patch on the heredoc opening line", async () => {+ // The reverse direction: heredocs start consuming bodies only after the+ // opening line ends, so a `git apply` on that line still counts and its+ // repeated failures must terminate at the budget.+ const host = {+ call: vi.fn().mockResolvedValue({+ ok: false,+ isError: true,+ errorCode: "TOOL_FAILED",+ content: { exitCode: 128, stderr: "error: patch does not apply" },+ }),+ };+ const runtime = createRuntime({ host });+ const agent = (runtime as any).agent;+ const bash = agent.state.tools.find((tool: any) => tool.name === "Bash");+ const args = { command: "cat <<EOF; git apply p.diff\nbody\nEOF" };++ for (const [index, id] of ["opening-patch-1", "opening-patch-2", "opening-patch-3"].entries()) {+ const result = await bash.execute(id, args);+ await expect(agent.afterToolCall({ toolCall: { id } })).resolves.toEqual(+ index === 2 ? { isError: true, terminate: true } : { isError: true },+ );+ expect(result.terminate).toBe(index === 2 ? true : undefined);+ }++ await runtime.dispose();+ });+it("terminates repeated failures of an empty -C git apply at the budget", async () => {// The empty quoted argument occupies git's option-value slot, so this is// a real patch command whose failures must still terminate the turn.