Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/pi-arc/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ This package is a Pi-native port of the Claude Code Arc plugin at https://github
- `/arc-subagents-sync` is deprecated for normal activation and remains a repair/backcompat command.
- **Session context injection**:
- On session start, the extension runs `arc prime` and injects its output into the system prompt as `<arc-context>`.
- It registers Pi's exact session ID, cwd, and available session file with Arc. Extension commands bind to the current Pi session per invocation, including after a session switch.
- Shell claim and manual prime commands pass guarded `PI_SESSION_ID` through `--session-id`, so a missing native identity stops before Arc runs.
- Extension-owned prime passes the current session-manager ID explicitly. Other extension commands receive that ID through invocation-scoped `ARC_SESSION_ID`. Explicit shell flags take precedence over inherited environment values.
- Before compaction, the extension refreshes `arc prime`.
- **Bundled `@juicesharp/rpiv-todo` integration** (auto-installed + auto-loaded):
- `todo` tool for managing in-session checklist items.
Expand Down
2 changes: 1 addition & 1 deletion packages/pi-arc/agents/issue-manager.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ Types: task, bug, feature, epic, chore

### Updating Issues
```bash
arc update <id> --take # Claim work (sets session ID + in_progress)
arc update <id> --take --session-id "${PI_SESSION_ID:?PI_SESSION_ID is required}" # Claim work (sets session ID + in_progress)
arc update <id> --status=blocked # Mark as blocked
arc update <id> --priority=1 # Change priority
arc update <id> --title="New title" # Update title
Expand Down
93 changes: 11 additions & 82 deletions packages/pi-arc/extensions/arc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,7 @@ import {
type ArcSubagentScope,
} from "./arc/subagents.ts";

type ArcCommandResult = {
code: number | null;
stdout: string;
stderr: string;
};
import { registerArcSession, runArcCommand, type ArcCommandResult } from "./arc/session.ts";

const WORKFLOW_SKILLS: Array<{ command: string; skill: string; description: string }> = [
{
Expand Down Expand Up @@ -722,92 +718,31 @@ async function formatSkippedArcSubagentDetails(result: ArcSubagentMaterializatio
return details;
}

function runArcWithStdin(
args: string[],
stdin: unknown,
cwd: string,
signal?: AbortSignal,
timeoutMs = 15_000,
): Promise<ArcCommandResult> {
return new Promise((resolve) => {
const child = spawn("arc", args, {
cwd,
stdio: ["pipe", "pipe", "pipe"],
});

let stdout = "";
let stderr = "";
let settled = false;

const finish = (result: ArcCommandResult) => {
if (settled) return;
settled = true;
clearTimeout(timeout);
if (signal) signal.removeEventListener("abort", abort);
resolve(result);
};

const abort = () => {
child.kill("SIGTERM");
};

const timeout = setTimeout(() => {
stderr += `Timed out after ${timeoutMs}ms`;
child.kill("SIGTERM");
}, timeoutMs);

if (signal) {
if (signal.aborted) abort();
else signal.addEventListener("abort", abort, { once: true });
}

child.stdout.on("data", (chunk) => {
stdout += chunk.toString();
});
child.stderr.on("data", (chunk) => {
stderr += chunk.toString();
});
child.stdin.on("error", (error) => {
stderr += error.message;
});
child.on("error", (error) => {
finish({ code: 127, stdout, stderr: stderr + error.message });
});
child.on("close", (code) => {
finish({ code, stdout, stderr });
});

child.stdin.end(`${JSON.stringify(stdin)}\n`);
});
}

export default function arcExtension(pi: ExtensionAPI) {
let primeCache = "";
let primeError = "";
let lastPrimeAt = 0;

async function runArc(args: string[], ctx: ExtensionContext, timeout = 15_000): Promise<ArcCommandResult> {
const result = await pi.exec("arc", args, { timeout, signal: ctx.signal });
return {
code: result.code,
stdout: result.stdout ?? "",
stderr: result.stderr ?? "",
};
return runArcCommand(args, ctx, { timeoutMs: timeout });
}

async function refreshPrime(ctx: ExtensionContext): Promise<boolean> {
try {
const result = await runArc(["prime"], ctx, 20_000);
const sessionID = ctx.sessionManager.getSessionId();
const result = await runArcCommand(["prime", "--session-id", sessionID], ctx, { timeoutMs: 20_000, sessionID });
lastPrimeAt = Date.now();
if (result.code === 0) {
primeCache = result.stdout.trim();
primeError = "";
return true;
}
primeCache = "";
primeError = outputOf(result);
return false;
} catch (error) {
lastPrimeAt = Date.now();
primeCache = "";
primeError = error instanceof Error ? error.message : String(error);
return false;
}
Expand Down Expand Up @@ -934,17 +869,11 @@ export default function arcExtension(pi: ExtensionAPI) {
ctx.ui.notify(ok ? "arc context loaded" : "arc context unavailable", ok ? "info" : "warning");
}

const payload = {
harness: "pi",
event: "session_start",
cwd: ctx.cwd,
sessionFile: ctx.sessionManager.getSessionFile(),
timestamp: new Date().toISOString(),
};

// Best-effort compatibility with arc AI session tracking. Older arc versions may not
// support this payload outside Claude; failures are intentionally non-fatal.
await runArcWithStdin(["ai", "session", "start", "--stdin"], payload, ctx.cwd, ctx.signal).catch(() => undefined);
// Session registration is best effort; claim commands verify it before assigning work.
const registration = await registerArcSession(ctx);
if (registration.code !== 0 && ctx.hasUI) {
ctx.ui.notify(`Arc session registration failed: ${outputOf(registration)}`, "warning");
}
});

pi.on("session_before_compact", async (_event, ctx) => {
Expand Down
93 changes: 93 additions & 0 deletions packages/pi-arc/extensions/arc/session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { spawn } from "node:child_process";

// Resolve identity for each command: sessions can change during a Pi process.
// Never mutate process.env, which is also inherited by independently spawned agents.
type ArcSessionContext = {
cwd: string;
signal?: AbortSignal;
sessionManager: {
getSessionId(): string;
getSessionFile(): string | undefined;
};
};

export type ArcCommandResult = {
code: number | null;
stdout: string;
stderr: string;
};

export function registerArcSession(ctx: ArcSessionContext): Promise<ArcCommandResult> {
const sessionID = ctx.sessionManager.getSessionId();
return runArcCommand(["ai", "session", "start", "--stdin"], ctx, {
stdin: {
session_id: sessionID,
cwd: ctx.cwd,
transcript_path: ctx.sessionManager.getSessionFile() ?? "",
},
sessionID,
});
}

export function runArcCommand(
args: string[],
ctx: ArcSessionContext,
options: { stdin?: unknown; timeoutMs?: number; sessionID?: string } = {},
): Promise<ArcCommandResult> {
const { signal } = ctx;
const { stdin, timeoutMs = 15_000, sessionID = ctx.sessionManager.getSessionId() } = options;
if (!sessionID) {
return Promise.resolve({ code: 2, stdout: "", stderr: "Pi session ID is required" });
}
return new Promise((resolve) => {
const child = spawn("arc", args, {
cwd: ctx.cwd,
env: { ...process.env, ARC_SESSION_ID: sessionID },
stdio: ["pipe", "pipe", "pipe"],
});

let stdout = "";
let stderr = "";
let settled = false;

const finish = (result: ArcCommandResult) => {
if (settled) return;
settled = true;
clearTimeout(timeout);
if (signal) signal.removeEventListener("abort", abort);
resolve(result);
};

const abort = () => {
child.kill("SIGTERM");
};

const timeout = setTimeout(() => {
stderr += `Timed out after ${timeoutMs}ms`;
child.kill("SIGTERM");
}, timeoutMs);

if (signal) {
if (signal.aborted) abort();
else signal.addEventListener("abort", abort, { once: true });
}

child.stdout.on("data", (chunk) => {
stdout += chunk.toString();
});
child.stderr.on("data", (chunk) => {
stderr += chunk.toString();
});
child.stdin.on("error", (error) => {
stderr += error.message;
});
child.on("error", (error) => {
finish({ code: 127, stdout, stderr: stderr + error.message });
});
child.on("close", (code) => {
finish({ code, stdout, stderr });
});

child.stdin.end(stdin === undefined ? undefined : `${JSON.stringify(stdin)}\n`);
});
}
2 changes: 1 addition & 1 deletion packages/pi-arc/prompts/arc-prime.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
description: Output AI-optimized workflow context
---

Run `arc prime` to output workflow context for AI assistants.
Run `arc prime --session-id "${PI_SESSION_ID:?PI_SESSION_ID is required}"` to output workflow context for AI assistants.

This is automatically run by the Pi arc extension on session start and before compaction. You typically don't need to run it manually.
2 changes: 1 addition & 1 deletion packages/pi-arc/prompts/arc-ready.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ Present the results to the user showing:
- Priority
- Issue type

If there are ready tasks, ask the user which one they'd like to work on. If they choose one, run `arc update <id> --take` to claim it (sets session ID + in_progress).
If there are ready tasks, ask the user which one they'd like to work on. If they choose one, run `arc update <id> --take --session-id "${PI_SESSION_ID:?PI_SESSION_ID is required}"` to claim it (sets session ID + in_progress).

If there are no ready tasks, suggest checking `arc blocked` or creating a new issue with `arc create`.
4 changes: 2 additions & 2 deletions packages/pi-arc/prompts/arc-team.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,5 @@ arc team context <epic-id> --json # JSON for a specific epic
**JSON output** includes full issue details with plans and dependencies for each role group.

**Related commands:**
- `arc prime --role=lead` — Lead-oriented context output
- `arc prime --role=frontend` — Role-filtered context (or use `ARC_TEAMMATE_ROLE` env var)
- `arc prime --role=lead --session-id "${PI_SESSION_ID:?PI_SESSION_ID is required}"` — Lead-oriented context output
- `arc prime --role=frontend --session-id "${PI_SESSION_ID:?PI_SESSION_ID is required}"` — Role-filtered context (or use `ARC_TEAMMATE_ROLE` env var)
2 changes: 1 addition & 1 deletion packages/pi-arc/prompts/arc-update.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Available updates:

Examples:
```bash
arc update <id> --take # Claim work (sets session ID + in_progress)
arc update <id> --take --session-id "${PI_SESSION_ID:?PI_SESSION_ID is required}" # Claim work (sets session ID + in_progress)
arc update <id> --priority 1 # Raise priority
```

Expand Down
10 changes: 8 additions & 2 deletions packages/pi-arc/scripts/migrate-arc-plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ def validate_source(src: Path) -> None:
text = re.sub(r"/arc:([a-zA-Z0-9_-]+)", r"/arc-\1", text)
text = text.replace("Claude Code", "Pi")
text = text.replace("Claude", "Pi")
text = text.replace("ARC_SESSION_ID", "PI_SESSION_ID")
text = text.replace("SessionStart and PreCompact hooks", "the Pi arc extension on session start and before compaction")
text = re.sub(r"When to use arc vs TodoWrite", "When to use arc vs the bundled `todo` checklist workflow", text, flags=re.IGNORECASE)
text = re.sub(r"todowrite vs arc", "todo checklist vs arc", text, flags=re.IGNORECASE)
Expand Down Expand Up @@ -126,6 +127,7 @@ def transform_text(text: str) -> str:
# Harness naming and Claude-specific tool names.
text = text.replace("Claude Code", "Pi")
text = text.replace("Claude", "Pi")
text = text.replace("ARC_SESSION_ID", "PI_SESSION_ID")
text = text.replace("SessionStart/PreCompact hooks", "Pi extension session-start and before-compaction handlers")
text = text.replace("SessionStart and PreCompact hooks", "Pi extension session-start and before-compaction handlers")
text = text.replace("via the Task tool", "through the auto-materialized `arc-issue-manager` pi-subagent when available, or the bundled `arc_agent` fallback")
Expand Down Expand Up @@ -226,8 +228,8 @@ def replace_section(rel: str, start_marker: str, end_marker: str, replacement: s
"Show teammate-label planning context with `arc team`.\n\nPi does not support Claude-style team deployment. Use this command only to inspect `teammate:*` issue groupings; implementation remains orchestrated through `/arc-build`.",
),
(
"**Related commands:**\n- `arc prime --role=lead` — Team lead context output\n- `arc prime --role=frontend` — Teammate-specific context (or use `ARC_TEAMMATE_ROLE` env var)",
"**Related commands:**\n- `arc prime --role=lead` — Lead-oriented context output\n- `arc prime --role=frontend` — Role-filtered context (or use `ARC_TEAMMATE_ROLE` env var)",
"**Related commands:**\n- `arc prime --role=lead --session-id \"${PI_SESSION_ID:?PI_SESSION_ID is required}\"` — Team lead context output\n- `arc prime --role=frontend --session-id \"${PI_SESSION_ID:?PI_SESSION_ID is required}\"` — Teammate-specific context (or use `ARC_TEAMMATE_ROLE` env var)",
"**Related commands:**\n- `arc prime --role=lead --session-id \"${PI_SESSION_ID:?PI_SESSION_ID is required}\"` — Lead-oriented context output\n- `arc prime --role=frontend --session-id \"${PI_SESSION_ID:?PI_SESSION_ID is required}\"` — Role-filtered context (or use `ARC_TEAMMATE_ROLE` env var)",
),
])

Expand All @@ -236,6 +238,10 @@ def replace_section(rel: str, start_marker: str, end_marker: str, replacement: s
"- **Agentic team**: Add `teammate:*` labels, invoke `/arc-team-dispatch`. Best for parallel multi-role work.",
"- **Parallel Arc build**: For independent task batches, `build` can use worktree-isolated `pi-subagents` runs when that companion package and Arc agent definitions are available. This is not Claude-style team deployment; the orchestrator still owns verification, patch application, issue closure, and handoff.",
),
(
"Operational claim commands and manual `arc prime` commands must pass `--session-id \"${PI_SESSION_ID:?PI_SESSION_ID is required}\"`. `PI_SESSION_ID` is the canonical identity persisted by the lifecycle hook; do not substitute an agent ID or another runtime's session value. Lifecycle hooks keep their stdin-provided session identity and do not need this shell variable.",
"Operational claim commands and manual `arc prime` commands must pass `--session-id \"${PI_SESSION_ID:?PI_SESSION_ID is required}\"`. `PI_SESSION_ID` is the current shell session-manager identity; do not substitute an agent ID or another runtime's session value. The Pi extension captures its current session-manager identity for registration and its own prime command without mutating the process environment.",
),
])

patch_file("skills/arc-plan/SKILL.md", [
Expand Down
4 changes: 2 additions & 2 deletions packages/pi-arc/skills/arc-build/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ arc list --parent=<epic-id> --json | jq '.[] | select(.status != "closed")'
### 2. Claim Task

```bash
arc update <task-id> --take
arc update <task-id> --take --session-id "${PI_SESSION_ID:?PI_SESSION_ID is required}"
```

### 3. Dispatch Agent
Expand Down Expand Up @@ -473,7 +473,7 @@ After successful verification, return to the normal orchestration loop (step 1)

```bash
arc ready # Find next task
arc update <id> --take # Claim task (sets session ID + in_progress)
arc update <id> --take --session-id "${PI_SESSION_ID:?PI_SESSION_ID is required}" # Claim task (sets session ID + in_progress)
arc show <id> # Get task description for subagent
arc close <id> -r "reason" # Close completed task
```
Expand Down
6 changes: 3 additions & 3 deletions packages/pi-arc/skills/arc-finish/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ Create a checklist using the bundled `todo` tool (or `/todos`) with all steps an
```
19. Output context for next session:
```bash
arc prime
arc prime --session-id "${PI_SESSION_ID:?PI_SESSION_ID is required}"
```

## Context-Aware Behavior
Expand All @@ -140,13 +140,13 @@ Create a checklist using the bundled `todo` tool (or `/todos`) with all steps an
- `git stash clear`, `git remote prune origin` — housekeeping, not gates
- Worktree directory `.gitignore` verification — assumed to be configured at project setup
- Merge/PR/keep/discard choice — arc workflow always commits and pushes
- Performative session summaries — `arc prime` handles handoff context
- Performative session summaries — `arc prime --session-id "${PI_SESSION_ID:?PI_SESSION_ID is required}"` handles handoff context

## Rules

- Never skip Phase 2 (quality gates) when code has changed
- Never commit with `git add -A` — stage specific files
- Never leave unpushed commits
- Never close arc issues without completing the work
- Always run `arc prime` at the end for next-session context
- Always run `arc prime --session-id "${PI_SESSION_ID:?PI_SESSION_ID is required}"` at the end for next-session context
- Format all arc content (descriptions, plans, comments) per `skills/arc/_formatting.md`
8 changes: 6 additions & 2 deletions packages/pi-arc/skills/arc/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,11 @@ Run `arc onboard` at session start to get project context and available issues.

## CLI Reference

Run `arc prime` for full workflow context, or `arc <command> --help` for specific commands.
Run `arc prime --session-id "${PI_SESSION_ID:?PI_SESSION_ID is required}"` for full workflow context, or `arc <command> --help` for specific commands.

## Session Binding

Operational claim commands and manual `arc prime` commands must pass `--session-id "${PI_SESSION_ID:?PI_SESSION_ID is required}"`. `PI_SESSION_ID` is the current shell session-manager identity; do not substitute an agent ID or another runtime's session value. The Pi extension captures its current session-manager identity for registration and its own prime command without mutating the process environment.

**Essential commands:**
- `arc ready` - Find unblocked work
Expand Down Expand Up @@ -201,7 +205,7 @@ EOF
arc onboard # Get context (recovers project if needed)
arc ready # Find available work
arc show <id> # View details
arc update <id> --take # Claim work (sets session ID + in_progress)
arc update <id> --take --session-id "${PI_SESSION_ID:?PI_SESSION_ID is required}" # Claim work (sets session ID + in_progress)
```

### Creating Issues
Expand Down
Loading
Loading