Skip to content

[Epic] Pi coding agent support - #3847

Merged
integry merged 27 commits into
mainfrom
3831-epic-pi-coding-jml
Nov 28, 2026
Merged

integry merged 27 commits into
mainfrom
3831-epic-pi-coding-jml

Conversation

@propr-dev

@propr-dev propr-dev Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Pi coding agent support

This Epic PR aggregates all changes for the plan: Pi coding agent support

Issues in this Epic

Auto-close

When this PR is merged, the following issues will be automatically closed:

Fixes #3831
Fixes #3832
Fixes #3833
Fixes #3834
Fixes #3835
Fixes #3836


Created automatically by ProPR

… a disposable runtime and safe credential handling (#3839)

* chore: install Pi CLI in agent image with disposable runtime

Pi 1.6.1 is now in the agent image, with its own entrypoint and the credential write-back helper. I couldn't build the image here because there's no Docker in this container, so the image build and the new smoke checks haven't run. Their first real run will be CI.

Tested:
- I installed Pi 1.6.1 from npm and ran the Dockerfile's `pi --version` / `pi --help` flag check against it; it passes and catches a missing flag.
- Through a local logging proxy, Pi sent its provider traffic via `HTTPS_PROXY` and contacted only the provider host (`api.anthropic.com`, `openrouter.ai`). It made no `pi.dev` calls in `-p` mode.
- The new test file `test/piCredentials.test.ts` (23 cases) passes. It covers the credential helper and runs the entrypoint as a non-root user with a stand-in `pi`.
- The related suites pass, and typecheck (core, API, root) and core lint are clean.
- One test fails, and it was already failing: `thirdPartyNotices` "committed notice carries the date…". The `Generated:` date in `THIRD_PARTY_LICENSES.md` doesn't match the last `package-lock.json` commit; I didn't change either.

Decision for you: the issue asks for `pi: '1.6.1'` in `AGENT_DEFAULT_VERSIONS`, but `pi` only becomes an agent type in #3832. Adding it to `AgentType` now would ripple through the UI and about 40 typed lookup tables. Instead I added an `AgentCliType` (the agent types plus `pi`) and used it only for the image version tables, labels, build args, egress lists and the entrypoint map. When #3832 adds `pi` as an agent type the extra entry deduplicates itself and nothing else needs undoing. The catch: if you'd rather `pi` became a full agent type in this change, that pulls a chunk of #3832 forward.

What's in place:
- Image: a `pi-cli` stage installs `@earendil-works/pi-coding-agent@${PI_CLI_VERSION}` (default 1.6.1), checks `pi --version` and that `pi --help` lists the eight required flags, and puts `pi` on PATH. The final image gets a `dev.propr.agent.pi.version` label. `scripts/build-images.sh` has the matching `PI_CLI_VERSION`. Both content-hash lists and the app image's build context include the new files. Npm version lookup works for the scoped package.
- Entrypoint (`scripts/pi-entrypoint.sh`), dispatched from `agent-entrypoint.sh`:
  - Each run starts with a fresh `/tmp/propr-pi-home/agent` as `PI_CODING_AGENT_DIR`, with sessions under it.
  - It copies only `auth.json`, `settings.json`, `models.json`, `AGENTS.md`, `SYSTEM.md` and `APPEND_SYSTEM.md` from `PROPR_PI_SOURCE_DIR`. Host `sessions/`, `extensions/` and `mcp.json` are never copied; ProPR can supply its own `mcp.json` through `PROPR_PI_MCP_CONFIG`.
  - It sets `PI_SKIP_VERSION_CHECK=1` and `PI_TELEMETRY=0`. It also sets `PI_OFFLINE=1`, which the issue didn't ask for. It stops Pi's startup model-catalog fetch from `pi.dev`, and the value can be overridden.
  - Every Pi or helper call (seed, version probe, the task, sync) goes through `su-exec node`. The task's exit status is passed through.
  - Provider API-key env vars pass through unchanged.
- Credentials (`scripts/pi-credentials.py`): `seed` saves an owner-only snapshot of the imported `auth.json` before Pi touches it. `sync` writes refreshed OAuth entries back one provider at a time, only if the host entry still equals the snapshot. It never rewrites API-key entries, never adds or removes providers, and writes nothing if no OAuth entry changed. The write is atomic: temp file opened with `O_CREAT|O_EXCL, 0o600`, original mode kept. It also takes Pi's own `auth.json.lock` (same format as Pi's locking library), so it can't interleave with a host Pi refresh; stale locks are taken over.
- Egress: Pi's allowlist covers Anthropic, OpenAI and ChatGPT sign-in, OpenRouter, Gemini and GitHub Copilot, including their token-refresh hosts. `pi.dev` and `radius.pi.dev` are excluded, and Pi is marked as proxy-compatible.
- Smoke tests: `scripts/smoke-test-images.sh` runs `pi --version` through the entrypoint and compares it with the image label. It also starts the entrypoint as `--user 0:0` with a mounted source dir and fails if anything under `/tmp/propr-pi-home` isn't owned by `node`. The preview-image smoke test covers Pi the same way.
- Other: third-party notices list the new package as MIT, and `agent-runtime.md` has a short Pi section. I updated the existing test fixtures that list image labels, and added a Pi case to the provider-egress test.

There's nothing visible to capture, so I made no preview.

ProPR-Agent: claude/claude-opus-5-5

* chore: guard Pi host dir and symlinked auth.json from runtime sync

I fixed both findings, F1 and F2. `test/piCredentials.test.ts` now passes in full (26 of 26). I also ran the new tests against the old scripts: the two regressions below fail there, so they do catch the original bugs.

**F1: a runtime home could delete the host Pi dir** (`scripts/pi-entrypoint.sh`)
- Before anything is deleted or chowned, the entrypoint now resolves both `PROPR_PI_RUNTIME_HOME` and `PROPR_PI_SOURCE_DIR` to real paths, following symlinks and `..`.
- It then refuses with exit 64 if either path is inside the other. Before, it only caught a runtime home inside the source dir, not one that contains it.
- It also refuses a runtime home that resolves to `/`. The old check only caught the literal value `/`, so something like `/tmp/..` would have got through.
- New tests: a runtime home that contains the source dir, given as the parent dir (the `/home/node/.pi` case), as `agent/..`, and as a symlink to the parent. Each one exits 64 and leaves the host `auth.json` and `sessions/` untouched. A runtime home equal to the source dir is also refused.

**F2: write-back replaced a symlinked `auth.json`** (`scripts/pi-credentials.py`)
- `sync` now resolves the host `auth.json` path once. It uses that real file for the lock, the read, the file mode and the atomic replace. The temp file is created next to the real file, the target gets the new credentials, and the symlink stays in place.
- This matches Pi's own lock, which is also taken on the real file.
- New test: with `auth.json` as a symlink to a mode-0640 file elsewhere, after a refresh the link still exists and points to the same file. That file holds the refreshed entry, keeps mode 0640, and has no temp or lock files left next to it.

The other place this could matter is `seed`, which writes the snapshot. It deletes the snapshot path first, so it never writes through a link and needed no change.

PR: #3839
Comment by: @propr-ultrafix (ID: 0)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* fix: forward stop signals to Pi and sync credentials on exit

I fixed F3: stopping a Pi container mid-task now passes the signal on to Pi, waits for Pi to exit, and still writes refreshed OAuth credentials back to the host. All 28 tests in `test/piCredentials.test.ts` pass, including the two new ones. Against the old entrypoint, both new tests fail. I couldn't run the root code path (starting as root and dropping to `node` via `su-exec`) here, because there's no root or Docker in this container; CI's image smoke test is its first real run.

**What changed in `scripts/pi-entrypoint.sh`:**
- **Signal forwarding:** Pi now runs as a background child instead of in the foreground. Handlers for `SIGTERM`, `SIGINT` and `SIGHUP` pass the signal to Pi. The shell keeps waiting until Pi has actually exited, then runs the credential sync once.
- **Exit status:** the container exits with Pi's status, which is 143 after `docker stop` if Pi doesn't handle the signal. If Pi exits cleanly after being told to stop, the entrypoint reports `128 + signal` rather than 0. A signal that arrives during the sync waits until the sync finishes.
- **Three problems I hit and fixed while testing:**
  - The background job was a bash subshell running a helper function, so signals reached the subshell and left Pi orphaned. A new `exec_as_node` helper makes the task's PID Pi itself.
  - Bash without job control makes background commands ignore `SIGINT` and `SIGQUIT`. The task now starts with `env --default-signal=INT,QUIT` to undo that; Debian bookworm's coreutils 9.1 supports the flag.
  - Bash also points a background command's stdin at `/dev/null`, so the prompt on stdin is now passed through explicitly.

**Tests and docs:**
- New tests for `SIGTERM` and `SIGINT`. A stand-in Pi refreshes the Anthropic token and keeps running; the test then signals the entrypoint the way tini would. They check:
  - the exit status is 143 or 130.
  - Pi was stopped, not left running.
  - the host `auth.json` holds the refreshed entry and nothing else changed.
- The existing run test now also checks that the prompt on stdin reaches Pi.
- I updated the existing check that every Pi call drops to `node` so it covers `exec_as_node`.
- The Pi section of `agent-runtime.md` now has one sentence on the shutdown behaviour.

**Separate finding (not changed):** in an interactive `docker run -it`, Ctrl-C reaches Pi from the terminal and again from the entrypoint, so Pi gets `SIGINT` twice. ProPR runs Pi with `-p` and no terminal, so this only matters for manual interactive use.

I didn't change tini to signal the whole process group (`tini -g`). That would affect every agent image, which is beyond this finding.

PR: #3839
Comment by: @propr-ultrafix (ID: 0)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

---------

Co-authored-by: propr-dev[bot] <1316198+propr-dev[bot]@users.noreply.github.com>
@propr-dev

propr-dev Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Epic progress: Pi coding agent support

6 of 6 issues merged ✅

Merged child PRs: #3839, #3849, #3856, #3857, #3858, #3859

✅ This epic PR has been merged into main.


This comment is updated automatically by ProPR as child PRs open, change and merge.

@propr-dev propr-dev Bot added the AI label Nov 27, 2026
Comment thread test/piCredentials.test.ts Fixed
@propr-dev

propr-dev Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

✅ Applied the requested follow-up changes in commit 279c440

Summary of Changes

I removed the bash -c call that CodeQL flagged at test/piCredentials.test.ts:274, so no shell ever sees the temp-dir paths or file names now.

The change: the test "waits for a held Pi auth.json lock" used to start two processes through a shell: a "holder" script standing in for a host Pi, and the credentials sync. Now Node runs the holder script directly with spawnSync('python3', ['-I', '-B', script, …paths]). The holder starts the sync itself with subprocess.Popen and a plain argument list. It then sleeps 0.5s, writes its refresh to the host auth.json, releases the lock, and exits with the sync's exit code. The timing is the same as before. The test still checks that the sync exits 0, that the holder's refresh wins, and that the lock is gone afterwards.

Checks: all 28 tests in test/piCredentials.test.ts pass. ESLint has no rules configured for this file, so the lint run checked nothing. I didn't run a negative check (breaking the lock wait to confirm the test fails), but the assertions are unchanged.

This is a test-only change with nothing visual, so there are no previews.

Review digest

Risk-tiered paths

  • High risk: none
  • Normal risk: none
  • Low risk (1 file)
    • test/piCredentials.test.ts (+9/−5)

Diff size: 1 file changed, +9/−5 lines


🤖 Implementation Details

  • Model: Claude Opus 5.5 (medium)
  • Requested By: @github-advanced-security[bot]
  • Time: 3m 53s
  • Tokens: 217,079 (214,897 in / 2,182 out)
  • Cost: $0.30

Undo Changes • View Task Execution


💡 ProPR Slash Commands
Command Description Example
/merge Merge target branch into this PR and resolve conflicts /merge
/review Request an AI code review /review or /review claude-sonnet
/fix Address review blockers, or blockers and suggestions with /fix all /fix, /fix all, or /fix F3 S5
/switch Change the AI model for this PR /switch claude-opus
/use Override the model for a single follow-up run /use claude-sonnet
/ultrafix Loop review→fix cycles until score goal is met /ultrafix or /ultrafix goal=8 max=10

🤖 Generated by ProPR
Processing comment ID: 4721690976✓

I removed the `bash -c` call that CodeQL flagged at `test/piCredentials.test.ts:274`, so no shell ever sees the temp-dir paths or file names now.

**The change:** the test "waits for a held Pi auth.json lock" used to start two processes through a shell: a "holder" script standing in for a host Pi, and the credentials sync. Now Node runs the holder script directly with `spawnSync('python3', ['-I', '-B', script, …paths])`. The holder starts the sync itself with `subprocess.Popen` and a plain argument list. It then sleeps 0.5s, writes its refresh to the host `auth.json`, releases the lock, and exits with the sync's exit code. The timing is the same as before. The test still checks that the sync exits 0, that the holder's refresh wins, and that the lock is gone afterwards.

**Checks:** all 28 tests in `test/piCredentials.test.ts` pass. ESLint has no rules configured for this file, so the lint run checked nothing. I didn't run a negative check (breaking the lock wait to confirm the test fails), but the assertions are unchanged.

This is a test-only change with nothing visual, so there are no previews.

PR: #3847
Comment by: @github-advanced-security[bot] (ID: 4721690976)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5
@propr-dev propr-dev Bot changed the title ◔ 1/6 [Epic] Pi coding agent support ⚠️ 1/6 [Epic] Pi coding agent support Nov 27, 2026
…or tasks, with full persisted execution events (#3849)

* feat: add Pi agent type with JSON-mode runs and persisted events

I've registered `pi` as a full agent type, and implementation tasks and PR follow-ups now run through Pi in JSON mode with the whole trace saved as execution events. The new tests pass (23 of 23). So do the existing suites I picked that touch agent types, models, reasoning levels, metrics, the watchdog and the CLI, plus the propr-ui Settings/config tests. Typecheck passes for every package and lint passes for core and root `src/`. I did not run a real containerised Pi task: there's no Docker here, so the full in-image run hasn't happened yet.

Agent type. `pi` is now in the shared and core type lists, `createAgentFromConfig`, the default config path (`~/.pi/agent`, overridable with `PI_CONFIG_PATH`/`HOST_PI_DIR`), the in-container path, the health-check models, the PR template's agent name, and the CLI and UI types. Now that `pi` is a real agent type, I removed the temporary image-only `pi` entry that #3839 added; `AgentCliType` is now just an alias for the agent type.

Invocation. Each run is `pi -p --mode json --model <provider/id> [--thinking <level>] --session-dir /tmp/propr-pi-home/agent/sessions --no-approve`, with the prompt on stdin.
- Reasoning levels: `low` through `max` pass straight through. `ultra` and `ultracode` run at `max`. Unset or `auto` leaves the model's own default.
- Docker: the container starts as root only so the existing entrypoint can set up the per-run Pi home, then Pi runs as `node`.
- Pi config dir: mounted only if it exists on the host, because Docker would otherwise create it there owned by root. It is mounted read-write so the entrypoint can write refreshed sign-in tokens back.
- Secrets: the GitHub token and provider API keys go in through the Docker client's environment, so they never appear in the command line.
- Analysis runs: read-only workspace and no saved session. They get no tools, or only `read,grep,find,ls` when the caller allows read-only inspection.

Model IDs. These use the form `pi-<provider>/<model>`, with an optional `:<thinking>` suffix. The defaults are Opus 5.5, Sonnet 5.5, GPT-6.2 Astra, Gemini 4 Argon and Devstral 2 via OpenRouter. PR titles, aliases (e.g. `llm-pi-devstral2`) and pricing resolve to the underlying model. The startup config migration no longer drops Pi models that aren't in the catalog, and doesn't re-add default models an operator has removed.

Parser. It reads the session id, summary, success rule, per-response token sums and provider cost exactly as the issue specifies. Each tool call gets exactly one result event: Pi reports a result in both `tool_execution_end` and a `toolResult` message, and `turn_end` repeats it, so duplicates are skipped. The failed `cat missing.txt` call is recorded with `is_error: true`.

Things that behave differently from what you might assume:
- Pi exits 0 even when the provider rejects the request. I checked this against a real Pi 1.6.1 run with a bad OpenRouter key: it ended with `stopReason: "error"` and exit code 0. The success rule catches this, and there's a test built from that output.
- Provider cost needed a shared change. To use Pi's reported cost instead of ProPR pricing, I added a `providerCostUsd` field. It's passed through the result converters into `recordLLMMetrics`, which uses it before pricing. It is only set when every response says `totalFromProvider`, so other agents are unaffected.
- Managed diagnostics skip Pi, because its sessions live in a per-run directory and the host dir holds nothing to inventory.
- Context scouting stays off for Pi. It isn't added to the agents allowed to do repository scouting.

Watchdog. Pi's `toolCall` blocks, `tool_execution_start`/`_end`, `toolResult` messages and `turn_end` results are now tracked as tool calls. A long-running tool is held to the longer tool threshold instead of being treated as a stall.

Tests and docs. The fixture is at `test/fixtures/pi/pi-1.6.1-json-tool-task.jsonl` and the tests are in `test/piAgent.test.ts`. I updated two existing tests for the new type: a missing `pi` entry in `agentDefaultConfigPaths` and an expected error message in `apiOpenCodeRoutes`. `docs/docs/features/agents-and-models.md` now has a Pi row and a short Pi section.

Not done:
- Launcher and CLI setup plumbing for `HOST_PI_DIR` (orchestrator, `initStack`, `checkCommands`).
- A Pi parser for the live output view in the API.
- Pi-specific fields in the agent settings dialog. Pi does now appear in the agent type selector automatically.

No preview was made: the only visible change is that new "Pi" option in the type selector.

ProPR-Agent: claude/claude-opus-5-5

* test: add pi to expected agent types in OpenCode CLI help test

I fixed the one failing test in shard 3. Everything else in the shard passed.

**Cause:** `test/cliAgentOpenCode.test.ts:29` checks the help text for the `agent add` command against a hard-coded list of agent types. This branch adds `pi`, so the help now reads `Agent type (claude, codex, antigravity, opencode, vibe, pi)`. The old pattern ended at `vibe)` and no longer matched.

**Fix:** I added `pi` to the expected list in that pattern. The file now passes locally (3 of 3).

I also searched the other tests for the same hard-coded list. `packages/cli/src/commands/setupCommand.test.ts` has a similar one, but it's for skill targets, not agent types. This branch doesn't add `pi` to that list, so I left it alone.

No preview, since this only changes a test.

PR: #3849
Comment by: @propr-dev[bot] (ID: 7224133308)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* fix: keep Pi run results when post-run steps fail

I fixed F1. When a Pi run has finished and something after it fails, the failed result now keeps what the run produced instead of discarding it. The new regression tests pass, and they fail against the previous `PiAgent.ts`.

**Problem.** Pi built the finished response inside the `try`, so the `catch` couldn't see it. A rejecting `onSessionId` callback, or a failing log write, produced a failed result with no tokens, cost, session or conversation. In the callback case the run's log row was never written either.

**Changes:**
- **`packages/core/src/agents/impl/PiAgent.ts`:**
  - **What a failure keeps:** `executeTask` now holds the finished response outside the `try`. On any later failure it builds the result with the shared `failedExecutionResult` helper. That keeps the session id, conversation, token usage, cost, provider cost, provider model, reasoning level and execution id, and Pi also keeps the run's usage metrics.
  - **Failures before Pi produced output:** these keep the prompt and carry no run data, as before.
  - **Log row:** if the run finished but its log row was never written, it is now written once, marked failed, with Pi's provider cost. If that write fails too, a warning is logged and the failed result is still returned.
- **`packages/core/src/agents/impl/utils/failedAgentExecution.ts`:** `failedExecutionResult` now also keeps `providerCostUsd`. Claude and Codex already route through this helper; they don't set that field today, so nothing changes for them.

**Sibling check.** Claude and Codex already keep the finished response this way and write the missing log row. Pi's `analyze` path doesn't have the bug: it has no awaited step between building the result and returning it.

**Tests.** The new file `test/piAgentPostExecutionFailure.test.ts` runs the real `executeTask` against the recorded Pi 1.6.1 trace, with only the Docker call replaced. It covers:
- A rejecting session callback: the result keeps the run, and the log row is written exactly once.
- A failing log write: the result still keeps the run.
- Docker throwing before any output: the prompt is kept, there is no run data, and no row is written.
- The shared helper keeping `providerCostUsd`.

All 4 pass, and 2 of them fail against the old `PiAgent.ts`. `test/piAgent.test.ts` and `test/llmMetricsFailedExecutions.test.ts` still pass (30 of 30). The core typecheck passes, and zero-warning lint passes on the two changed source files. Lint has no config that covers the new test file, so it wasn't linted.

One thing to know: when the log write itself is what fails, the failure path tries it once more. The Codex agent does the same.

No preview was made, because nothing visible changed.

PR: #3849
Comment by: @propr-ultrafix (ID: 0)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

---------

Co-authored-by: propr-dev[bot] <1316198+propr-dev[bot]@users.noreply.github.com>
@propr-dev propr-dev Bot changed the title ⚠️ 1/6 [Epic] Pi coding agent support ◔ 2/6 [Epic] Pi coding agent support Nov 27, 2026
…ommit subjects, planner, indexing and the repository scout (#3858)

Pi now handles every analysis path (reviews, summaries, commit subjects, planner, indexing and the review context scout), and Pi task runs get the extension library and the `propr` MCP server. I installed Pi 1.6.1 locally and ran the real CLI against a stub model server, because the issue's scout flag set doesn't work as written.

The scout flags needed one change. The issue's flags (`--no-builtin-tools --no-extensions …`) leave the scout with no tools at all. `--no-extensions` also unloads Pi's own built-in MCP support. The working set is:
- `--no-builtin-tools`, plus `--tools` listing only the three `mcp__propr_repository__*` tools.
- `--no-extensions --extension builtin:mcp`, `--no-skills`, `--no-prompt-templates`, `--no-approve`.
- A generated `mcp.json` with only the `propr_repository` server, set to `"exposure": "direct"`. Pi's default exposure only lets the model reach MCP tools through its `codemode` script tool, which the flags above leave unloaded.

With exactly the args ProPR builds, the model saw only the three scout tools: `bash` and `read` came back "Tool … not found", and a scout read returned the file. A `.pi/mcp.json`, an extension and a skill planted in the project and agent dirs did not load; with the flags removed, they did. The scout mounts the repository read-only at the scout server's root, with no git mounts and no GitHub token, like the other agents. `buildPiRepositoryScoutConfig` and `buildPiRepositoryScoutArgs` sit next to the OpenCode and Vibe builders in `repositoryScoutMcpServer.ts`.

Other analyses run tool-less (`--no-tools`) on a read-only workspace, the same as Claude. The scout is the only analysis that asks for tools, so I replaced the old `read,grep,find,ls` mode with the scout mode. Analysis results go through the existing JSON parser and success rules (final text, usage, provider cost).

Task runs:
- `PiAgent.executeTask` now goes through `executeWithExtensions` and passes `extensionAgentLaunch`, as Claude and Codex do.
- The tool policy becomes a generated `mcp.json`, passed to the container as `PROPR_PI_MCP_CONFIG`. It holds `Bearer ${PROPR_EXTENSION_MCP_0_TOKEN}` placeholders, never token values; the values arrive via `-e NAME`.
- Each staged skill bundle is passed as `--skill /opt/propr/extensions/<id>`, with `--no-skills` for exclusive runs. I added an internal `skillPaths` field to the tool policy for this.
- Runs join the policy's Docker network.

Live checks with real Pi all passed: bearer-auth HTTP server, stdio server through the bridge (secret inherited from the environment), and skill loading.

Gates: #3841 hasn't landed, so I added `pi` to `EXTENSION_RUNTIMES` and `AGENT_TYPES_SUPPORTING_PROPR_MCP`. The five hard-coded `['claude', 'codex']` copies now call a shared `isExtensionRuntime`. Error messages and UI text now read "Claude, Codex or Pi". I regenerated the OpenAPI spec and client types.

Readable tool events:
- MCP tools are named `<server>/<tool>` in persisted events.
- Calls made inside a `codemode` script now get their own tool events. Before, they produced results with no matching call.
- The live view now recognises Pi output, and the task watcher uses the Redis stream for Pi.

`src/jobs/reviewContextScout.ts` now accepts Pi. Indexing and the planner already choose agents generically, so they needed no change.

Tests: I added `test/piScoutAndExtensions.test.ts` (14 tests, including the bridge smoke test), `test/piAgentAnalysis.test.ts` (7) and `packages/api/test/liveDetailsPiParser.test.ts` (3). Two real Pi 1.6.1 recordings are now fixtures, with only the temp paths rewritten. The existing Pi, extension, scout, agent-run-trigger, task-submission and live-details suites and the UI editor test pass. Typecheck and lint are clean for root, core, api and propr-ui. `packages/api/test/mcpObservableSurface.test.ts` fails, but it fails the same way on a clean copy of HEAD.

Not tested: a containerised Pi run, because there is no Docker here. The flags and config were verified with the Pi CLI run directly on the host.

I updated the Pi section in `agents-and-models.md` and the runtime mentions in `agent-extensions.md`. No preview: the only visible change is the word "Pi" added to three help texts.

ProPR-Agent: claude/claude-opus-5-5

Co-authored-by: propr-dev[bot] <1316198+propr-dev[bot]@users.noreply.github.com>
@propr-dev propr-dev Bot changed the title ◔ 2/6 [Epic] Pi coding agent support ◑ 3/6 [Epic] Pi coding agent support Nov 27, 2026
…d login, health check, diagnostics and docs (#3857)

* docs: add Pi to settings UI, CLI, managed login and health check

Pi can now be configured and run everywhere the other agents are: the settings UI, managed login, the CLI and setup, health check, diagnostics, MCP settings and docs. Typecheck and lint are clean for every package I touched, and the affected test suites pass. There's no Docker here, so I haven't done a real containerised login or health check. Instead I installed Pi 1.6.1 locally and ran `pi auth check` and `pi auth login` against it to confirm the output, exit codes and prompts the code relies on.

Managed login
- How it runs: the login container runs `pi auth login <provider> --no-browser`, or `--api-key` to save a key. I tested sign-in on Anthropic (paste a code), OpenRouter (paste the redirect URL) and the ChatGPT subscription (device code); `--api-key` saved a key to `auth.json`.
- Where credentials go: `pi-entrypoint.sh` has a login mode that points Pi straight at the mounted dir (`~/.propr/agent-credentials/<id>/.pi/agent`). It skips the per-run copy because the write-back after a run only saves refreshed tokens, never a new login.
- Choosing the provider: in the UI, a small dialog asks for the provider and login method before the container starts. Through the API the provider is optional and defaults to the provider of the agent's default model.

Health check
- Pi agents are checked with `pi auth check --provider <p> --json --no-refresh` instead of running a prompt. The provider comes from the health-check model.
- It runs with no network, the credential dir mounted read-only, and API keys passed through the environment rather than the command line.
- `ready` shows as ready. `not_ready` and `invalid` show as sign-in required, with Pi's reason. An unknown provider is reported as a configuration problem rather than a login prompt.

Settings UI
- Credentials: Pi offers three choices: log in to a new managed account, use an existing config dir (`~/.pi/agent`), or use API keys. The API-key choice shows one key field per provider used by the selected models.
- Models and logo: a provider + model control adds any `pi-<provider>/<model>`. Pi gets a π logo. The CLI version controls already worked for Pi.

CLI and setup
- `propr agent login <pi-agent>` accepts `--provider` and `--api-key`.
- Pi is now known to `propr check` and `propr init`, the agent skill (installed to `~/.pi/agent/skills/propr`), both launcher copies (`HOST_PI_DIR` → `PI_CONFIG_PATH`), `docker-compose.yml`, the local-setup engine and the desktop setup schema.

Diagnostics and MCP
- Redaction: the keys and tokens in Pi's `auth.json` are now redacted.
- Managed diagnostics: Pi is now included. The previous Pi change had skipped it, so Pi run logs were silently refused; they are captured now.
- MCP: the settings catalog lists `PI_CONFIG_PATH`, `PI_TIMEOUT_MS` and `HOST_PI_DIR`. Creating an agent through the MCP tools now uses each type's own default config path; before, it fell back to `~/.vibe` for every type without managed login.

Docs: `agent-runtime.md` has a Pi section covering the image, entrypoint, credential mount, disposable agent dir, refresh write-back rules, managed login and health check. The setup guides, configuration reference, `.env.example` and CHANGELOG are updated. `settings-locations.md` is generated from the settings catalog, so I regenerated it rather than editing it.

Tests: new tests cover the login descriptor and routes, the entrypoint's login mode, health-check parsing (using recorded Pi 1.6.1 output), redaction, CLI validation and login, the launcher, and the UI dialogs (463 settings UI tests pass). `test/agentRegistryManagedAgentPin.test.ts` only passes when run with `--experimental-test-module-mocks`.

Gaps:
- `propr check` still sends a short prompt to validate Pi rather than using `pi auth check`.
- A stack with only a provider API key and no `HOST_PI_DIR` isn't detected as having Pi, so you need `--agents pi`.
- The setup wizard's login step always signs in to `anthropic`; use `propr agent login --provider` for anything else.
- `SKILL.md` itself is unchanged; the skill installer knows about Pi.

Four UI previews are attached: the Pi agent dialog with API keys, the same dialog with managed login, the provider picker, and an agent card showing a `not_ready` health result.

ProPR-Agent: claude/claude-opus-5-5

* docs: split agent login code to stay under max-lines limit

I fixed the Validate Changes failure. Only the API lint step had failed: two files on this branch went over the 400-line `max-lines` limit, and the API lint fails on any warning. Every other stage in the run passed.

**`packages/api/services/agentLoginSessionManager.ts` (431 → 437 total lines, 400 limit)** — I moved two groups of code into `services/agentLoginDocker.ts`, without changing what they do:
- The Pi login logic: picking the provider, building the login command, and returning a clear error for bad input. It's now one exported function, `resolveAgentLoginDescriptor`, and `start()` calls it.
- The default Docker run and spawn helpers, plus the `DockerCommandResult` type. The manager still re-exports that type, so existing imports keep working.

**`packages/api/test/agentLoginRoutes.test.ts` (498 lines)** — I split it up:
- The Pi route and descriptor tests now live in a new file, `test/agentLoginPi.test.ts`.
- The shared test fixtures are in a new `test/agentLoginTestHelpers.ts`, which both test files import.

**Checks I ran:**
- `eslint . --max-warnings 0` in `packages/api` now passes, and the API typecheck is clean.
- All 20 tests in `agentLoginRoutes.test.ts` and `agentLoginPi.test.ts` pass.
- `test/agentDefaultConfigPaths.test.ts` passes (29 tests).

I didn't add previews, since nothing visible changed.

PR: #3857
Comment by: @propr-dev[bot] (ID: 7226481658)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* docs: return empty configEnv from Pi auth check docker args

I fixed the build error that broke the Restricted network container smoke check; I haven't run the check itself.

**Cause:** The merge from the epic branch (`bdab602a4`) made `configEnv` a required field on `PiDockerInvocation`. The Pi health check builder added on this PR, `buildPiAuthCheckDockerArgs`, still returned only `{ args, secretEnv }`. That made the core package fail to build in the workflow's `npm run test:prepare` step, which is the exit code 2 in the log.

**Fix:**
- `packages/core/src/agents/impl/utils/piAuthCheck.ts`: the health check now returns `configEnv: {}`. It has no non-secret config to pass, so nothing changes at runtime.
- `test/piAuthCheck.test.ts`: added `configEnv: {}` to the test's hand-written invocation so it matches the type.

**Verification:**
- `tsc --noEmit` on `packages/core` is clean.
- `npm run test:prepare`, the step that failed in CI, now builds every package.
- `test/piAuthCheck.test.ts` passes (6 of 6). It needs `PROPR_DEMO_MODE=1`; without it the file reports one failure and stops.

The later steps of that check build the agent image and run tests in a real container. There's no Docker here, so I couldn't run them; the next CI run on this PR will cover them.

No previews, since nothing visible changed.

PR: #3857
Comment by: @propr-dev[bot] (ID: 7227137481)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* docs: resolve agent default config path only on create

I fixed the Shard 3/4 failure. The cause was a bug in this PR, not a flaky test.

**Cause:** the one failing test was `packages/api/test/mcpReviewerConcurrency.test.ts`. In `packages/api/mcp/toolsConfiguration.ts`, this PR changed the fallback config path for new agents from `'~/.vibe'` to the agent type's own default. But that path is worked out for create, update and remove alike, and only create passes a `type`. So every `update_agent_configuration` and `remove_agent_configuration` call now threw `TypeError: Cannot read properties of undefined (reading 'configPath')`. The MCP layer turned that into an `OUTCOME_UNKNOWN` 500, which is the `'unknown'` the test got instead of `'completed'`. I reproduced this locally and got the stack trace by temporarily logging the error, then removed the logging.

**Fix:** the new agent's path is now only worked out when an agent is created, which is the only case that needs it. Creating an agent still uses each type's default path, as the PR intended.

**Verification:**
- `mcpReviewerConcurrency.test.ts` failed locally the same way as CI before the fix and passes after it.
- `mcpToolInputBudget`, `settingsCatalog` and `mcpIntegration` pass (14/14).
- Lint with zero warnings and the `packages/api` typecheck are both clean.

I didn't rerun the whole shard. This change has nothing visual, so there are no previews.

PR: #3857
Comment by: @propr-dev[bot] (ID: 7227524858)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* docs: show readable model and provider in Pi model hint

I've fixed F1: the hint under "Add a Pi model" no longer shows the raw model ID. Instead of `Runs as pi --model openrouter/qwen/qwen3-coder` it now reads **"Adds Qwen3 Coder via OpenRouter."** The Pi settings tests pass (6 of 6), and typecheck and lint are clean for the UI.

- **New helper:** `describePiModel` in `propr-ui/src/pages/SettingsPage/piAgentFieldsUtils.ts` turns a `pi-<provider>/<model>` ID into that text. The model name comes from the shared `getModelDisplayName` helper, which uses the catalog name or makes a readable name from an unknown ID. The provider name comes from the Pi provider list, and an unknown provider is made readable the same way.
- **The hint itself** (`PiAgentFields.tsx`): before anything valid is typed, it says "Enter the model id as Pi names it for this provider." The duplicate warning is unchanged. Raw IDs are still used for the input value, the saved model list and the API payload.
- **Tests** (`PiAgentConfig.test.tsx`): a unit test covers a catalog model (`Claude Sonnet 5.5 via Anthropic`), a model and a provider that aren't in any list, and an OpenRouter model. The add-agent dialog test now checks that the new hint appears and that no raw ID shows as text.
- **Other places checked:** none of the other PR-changed UI files (`AgentConfigModal`, `PiLoginOptionsDialog`, `AgentLoginModal`, `AgentCredentialSetup`) show a model ID in visible text.

**Not changed, outside F1:**
- The model-ID box still has the placeholder `e.g. qwen/qwen3-coder`. I left it because it's an example of what to type into the box.
- The login modal shows the raw provider ID, e.g. `anthropic · Credentials are saved to…`. That's a provider rather than a model, so it isn't covered by this finding.

I've attached a screenshot of the add-agent dialog showing the new hint.

PR: #3857
Comment by: @integry (ID: 7227576335)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

---------

Co-authored-by: propr-dev[bot] <1316198+propr-dev[bot]@users.noreply.github.com>
@propr-dev propr-dev Bot changed the title ◑ 3/6 [Epic] Pi coding agent support ◑ 4/6 [Epic] Pi coding agent support Nov 27, 2026
@propr-dev propr-dev Bot changed the title ◑ 4/6 [Epic] Pi coding agent support ⚠️ 4/6 [Epic] Pi coding agent support Nov 27, 2026
)

* feat: add Pi live view and stored output parsing

I've added live view and stored-output parsing for Pi runs. Each tool call now shows up with its result, assistant text and thinking stream as they arrive, and token usage adds up across responses. The new and nearby test suites pass, and API typecheck and lint pass. I haven't seen it work against a real running Pi task in the UI.

Parser (`packages/api/services/redisOutputParserPi.ts`, new)
- Routing: `parseLine` sends Pi records to the new parser before the Codex, OpenCode and Antigravity checks. That ordering matters: a Pi assistant `message_end` would otherwise pass for an OpenCode message. Records only count as Pi's if they have Pi's shape (e.g. a `session` needs a numeric `version` and an `id`; `tool_execution_*` needs a `toolCallId`), so other agents' records are left alone.
- Streaming text: deltas are buffered per `contentIndex` and shown as the pending message while they stream. `text_end`/`thinking_end` replaces the buffer with the final content, and thinking is marked as reasoning. `message_end` fills in any block that never got an end event; a block that already ended isn't repeated. A finished block keeps the ID it had while streaming, so the live view doesn't jump.
- Tools:
  - Tool calls are emitted from the assistant `message_end` blocks, which carry the arguments, or from `tool_execution_start`, whichever comes first.
  - Pi reports each result three times (`tool_execution_end`, the `toolResult` message, `turn_end`). Only one result per call is emitted, with its error flag.
  - If a result arrives for a call that was never announced, a tool_use line is added first so they still pair up.
- Also:
  - User prompts are not shown.
  - Usage comes from assistant `message_end` only.
  - An assistant stop with `error` or `aborted` shows Pi's error message.

Wiring
- Fix outside the issue's list: Pi's `agent_end.messages` contains messages keyed by role, which the whole-document Vibe transcript scan could claim, swallowing the Pi stream. Both `parseRedisOutput` and the live projector (`liveOutputStream.ts`) now skip that scan when the output contains Pi lines. A test covers it and fails without the guard.
- Stored output: `liveDetailsStoredOutputFormat.ts` now detects a `'pi'` format, and the live-details routes parse it through the same parser via a new `parsePiOutputToConversationResult`. Without this, the live projector held Pi output back as unidentified preamble.
- Task watcher: `taskWatcher.ts` now uses the Redis watcher for `pi` tasks.
- Line splitting: output is split on LF only, as Pi's docs require.

Tests
- `test/redisOutputParser.test.ts`, the fixture regression test: the fixture gives four tool calls, and the three results pair with their calls (the `cat missing.txt` bash call is the one error). It also checks the final assistant text, and usage of 3,785 input and 229 output tokens.
- Other new tests there:
  - delta buffering and the pending message.
  - the Vibe guard.
  - other agents' record shapes not being read as Pi.
  - stored-format detection, including a startup banner and CRLF line endings.
- `packages/api/test/liveOutputPi.test.ts`: reading the stream one record at a time gives the same events and IDs as one full read.
- Existing suites still green: redisOutputParser (Codex, OpenCode, Vibe 3, Antigravity), liveDetails (Antigravity, Codex DB fallback, OpenCode, completed persisted), liveOutput (stream, identity, retention), agentStreamProjection, the two taskWatcher suites, and the Codex app-server and Antigravity native goal suites.

The trimmed fixture has one call with no result (`7Rc4Yw8fp`) and one result whose call isn't in it (`6UNoPXH4u`). The test checks that every result has a call before it, not that every call has a result.

No preview images: the Pi live view reads from Redis, and there's no Redis server here to run the UI against a Pi stream. The preview manifest suggests adding one to the agent image.

ProPR-Agent: claude/claude-opus-5-5

* chore: key Pi tool result live IDs by tool-call ID

I fixed F1: a Pi tool result now gets the same live ID whether it comes from `tool_execution_end` or from a copy Pi repeats later. That holds for a long-running watcher and for a fresh read after Redis trimmed the earlier record, so the UI no longer shows the same result twice.

**The fix** (`packages/api/services/redisOutputParserPi.ts`, `emitToolResult`)
- The result's ID used to come from the byte offset of whichever record emitted it. It now comes from the tool-call ID, so all three of Pi's copies (`tool_execution_end`, the `toolResult` message, `turn_end`) give the same ID.
- Skipped repeat copies no longer reserve a numbered slot in their record. A slot only matters for events numbered by position, and results no longer are, so watcher and fresh read can't disagree about it.
- Nothing changes for other agents: `withIds` and the ID scheme in `liveOutputStream.ts` are untouched.

**Other Pi events.** I checked the rest of the Pi parser for the same problem and found none:
- Tool calls already take their ID from the call ID.
- Text, thinking and error-stop events are each emitted from only one kind of record, so trimming can't change which copy a reader sees first.

**Regression test** (`packages/api/test/liveOutputPi.test.ts`)
- A call is followed by its `tool_execution_end`, `toolResult` message and `turn_end`. The test compares a record-by-record watcher, a full read, and a fresh read that starts at the `toolResult` message after earlier output was trimmed.
- It checks that each read has exactly one result, that the result's ID is the same in all three, and that every event in the trimmed read matches one the watcher emitted.
- With the fix removed, the test fails on the ID assertion.

One difference remains: in the fresh read, the result's timestamp is the `toolResult` message's own, about a second later than the watcher's, because `tool_execution_end` carries none. The call event that read adds before its result has the tool name but not the arguments. Both are under the same IDs, so they don't cause duplicates, and the test allows for them.

**Verification:**
- The Pi, live-output and live-details suites plus `test/redisOutputParser.test.ts`: 126 tests, 109 passed, 0 failed, 17 skipped.
- API typecheck and lint on the changed files both pass.

There's no preview, since nothing on screen changes beyond the duplicate no longer appearing.

PR: #3856
Comment by: @propr-ultrafix (ID: 0)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* chore: key Pi text and thinking IDs by message timestamp and index

I fixed F2. Pi assistant text and thinking now keep the same live ID whether a reader watched the stream without interruption or started fresh after Redis retention trimmed earlier records. The UI should no longer show the same narration twice.

**The fix** (`packages/api/services/redisOutputParserPi.ts`)
- **New key:** each text or thinking block is keyed by its message's timestamp and its `contentIndex`, instead of the byte offset of whichever record emitted it. I checked Pi's source (pi-ai / pi-agent-core 0.73.1): the provider stamps an assistant message once when it starts streaming, and `message_end` carries that same message object. So `message_start` and `message_end` always give the same key, and so does the block's own `text_end` or `thinking_end` in between.
- **Pending message:** while a block streams it uses that same key, so the finished block still keeps the ID it had while streaming.
- **Reader that missed `message_start`:** it can't know the key, so it no longer emits a block at `text_end`/`thinking_end`, or when the next block starts. It keeps showing the block as the pending message and emits it at `message_end`, under the same key and timestamp the watcher used.
- **Slots:** blocks with a key no longer reserve a numbered slot in the `message_end` record. This keeps the later "Pi stopped (error)" event's ID the same across readers.
- **Fallback:** if an assistant message has no timestamp, the old record-offset behaviour applies unchanged.

**Tests**
- **New test in `packages/api/test/liveOutputPi.test.ts`:** a message with a thinking block, a text block and an error stop is read four ways, besides the record-by-record watcher. A full read, and fresh reads starting at a thinking delta, at `thinking_end`, at `text_end` and at `message_end`. Each read must match the watcher's events exactly, IDs and timestamps included. The test also checks that each completed block keeps its streaming ID. It fails on the previous parser.
- **Changed existing test** in `test/redisOutputParser.test.ts`: it gave `message_start` and `message_end` different timestamps, which Pi never does. I made them match, and updated the expected pending key to the new block key.

**Verification**
- The live-output and live-details suites: 105 tests, 88 passed, 0 failed, 17 skipped.
- `test/redisOutputParser.test.ts`: 22 passed.
- API typecheck and lint both pass.

There's no preview, since nothing on screen changes beyond the duplicate no longer appearing.

PR: #3856
Comment by: @propr-ultrafix (ID: 0)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* chore: remove duplicate parsePiOutputToConversationResult export

I fixed the Validate Changes failure: the Core source build and the API build both pass again.

**Cause:** When the epic branch was merged into this PR, `packages/api/routes/liveDetailsOutputParsers.ts` ended up with two exported functions named `parsePiOutputToConversationResult`. The epic's version uses core's `parsePiConversationLog`; this PR's version used the Redis live-view parser. TypeScript rejects the duplicate, so both builds failed.

**Fix:** I kept the epic's version and deleted this PR's duplicate, plus its `parseRedisOutput` import, which nothing else in the file used. The epic's version names MCP tools `<server>/<tool>` and lists the calls a `codemode` script makes as their own tool events, and its tests in `packages/api/test/liveDetailsPiParser.test.ts` check for exactly that. The live-details route still sends `'pi'` stored output to this function.

**What changes for this PR:** Saved Pi output is no longer read by the same parser as the live view. Reading the stream one record at a time still gives the same events as one full read, but that test only covers the live-view parser.

**Checks run:**
- The repo build and the `packages/api` typecheck pass after rebuilding shared and core.
- These test suites pass: `liveDetailsPiParser`, `liveOutputPi`, `test/redisOutputParser` and the `liveDetails*` suites.
- ESLint passes on the edited file with zero warnings.

This is a backend build fix with nothing visible to a user, so there are no preview images.

PR: #3856
Comment by: @propr-dev[bot] (ID: 7227181093)
Comment by: @github-actions[bot] (ID: 7227181488)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* chore: hold unkeyed Pi blocks until message_end to avoid duplicates

I fixed F3: a Pi text or thinking block no longer shows up twice in the live view when a watcher starts reading after retention has trimmed that message's `message_start`.

**The fix** (`packages/api/services/redisOutputParserPi.ts`, `processMessageUpdate`): while the parser doesn't know which message a block belongs to, it keeps buffering the deltas but no longer shows them as the pending message. Before, the block was shown under the offset of the delta record, and `message_end` then emitted it under `pi:block:<timestamp>:<index>`. `appendUniqueEvents` treated that as a new event, so the UI showed both. Now the first time the block appears is at `message_end`, under its block key, the same as a full read. When the message identity is known, the block still streams under its block key and keeps that ID when it completes.

**Same defect elsewhere:** the only place the Pi parser shows a pending block is `processMessageUpdate`. The fix also covers a `message_start` that has no timestamp, which hit the same duplicate before. With pending blocks now always keyed, the branch that dropped an unkeyed earlier block on a block switch couldn't run any more, so I removed it. I also reworded one doc comment on `emitBlock` to match.

**Regression test** (`packages/api/test/liveOutputPi.test.ts`): a watcher's first read starts at a delta (or at `thinking_end`, or mid-text-delta) and stops before `message_end`. The test checks that nothing is published and nothing is pending. It then feeds `message_end` as a separate read and checks that the completed blocks come out under the same IDs a full read gives, with no ID repeated. Against the HEAD parser it fails at "the read from record 3 publishes no unidentified block"; with the fix it passes.

**Trade-off:** when a watcher joins a message part-way through, that message's text stays hidden until it finishes, instead of streaming in from the first retained delta. Messages the watcher sees from their start stream exactly as before.

**Verification:**
- `liveOutputPi` passes, 4 of 4.
- `test/redisOutputParser.test.ts` passes, 22 of 22.
- `liveDetailsPiParser`, `liveOutputIdentity`, `liveOutputRetention`, `liveOutputStream` and `agentStreamProjection` all pass.
- API `tsc --noEmit` and eslint with `--max-warnings 0` on the changed files are clean.
- `liveOutputTimestamps` ran 0 tests because it needs a real Redis server.

I didn't capture a preview: the change is visible in the live view, but there's no Redis server here to run the UI against a trimmed Pi stream. The manifest suggests adding `redis-server` to the agent image.

PR: #3856
Comment by: @propr-ultrafix (ID: 0)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* chore: derive Pi live event IDs from record data, not read start

Every Pi live event ID now comes only from data in the record itself, and one test checks every start line of each stream. The new and existing Pi tests pass, along with the nearby live-output and live-details suites, API lint (`--max-warnings 0`) and API typecheck.

**The fix** (`packages/api/services/redisOutputParserPi.ts`)
- **Tool calls and results:** both are keyed by `toolCallId`. The parser no longer uses per-record slot numbers, so how many earlier copies a read saw can't shift an ID.
- **Text and thinking blocks:** keyed by message identity plus `contentIndex`. The identity is `message.timestamp`, falling back to `responseId` only when there's no timestamp. I put the timestamp first because the captured fixtures reuse `responseId: "c1"` for every message, so `responseId` alone would collide.
- **Deltas before the identity is known:** they stay buffered and unpublished until `message_end`, which publishes each block once under its final ID. When the identity is known, `text_end`/`thinking_end` publish the block under the ID it streamed under, and `message_end` doesn't add a second copy.
- **Two more start-dependent paths, now removed:**
  - If a new block or a new message started before the previous block ended, the parser used to publish that block's partial text. Its content then depended on how many deltas a read had seen. Now the block stays buffered until `message_end` supplies the final text, and a message that never ends is not published.
  - The "Pi stopped (error)" note is now keyed by its message identity instead of its position in the record.

**The test** (`packages/api/test/liveOutputPi.test.ts`) runs on three streams:
- the captured `pi-1.6.1-json-tool-task.jsonl`.
- a new fixture, `test/fixtures/pi/pi-1.6.1-json-streamed-blocks.jsonl`, with several thinking and text deltas, a tool call, and an error stop. I built it by hand from the shapes in the 1.6.1 captures; it is not a real capture.
- an irregular stream: a block starting before the previous one ended, a message that never ends, and one without a timestamp.

For every start line `i`, it checks your three conditions. It also feeds lines `0..k` to a line-by-line watcher, merges the result with a read from every `j ≤ k`, and checks that nothing appears under two IDs. The F1/F2/F3 regressions are still there.

Three caveats:
- **"A tool result's ID equals its call's ID":** I read this as both IDs derived from the same `toolCallId` (`…:tool_use:external:<id>` and `…:pi:tool_result:<id>:0`). Making them literally the same string would break your "no ID appears twice" rule, since a call and its result are separate events. The test checks that both extract to the result's `toolUseId`.
- **The old parser passes on both real fixtures.** After F1–F3 it was already consistent on those streams; only the irregular stream makes it fail, at line 2. The new parser passes all three.
- **Unstamped messages:** in the irregular stream, a message with no timestamp shows the time of the last stamped record, which depends on where the read started. Its ID and text are stable, so the test skips the time check for that stream only. Pi stamps every message, so this doesn't come up with real output.

Not run: 17 tests in the neighbouring suites were skipped because they need a running Redis server, which this container doesn't have; they only cover other agents' streams. I made no preview images, because this change has no visible effect in the UI.

PR: #3856
Comment by: @integry (ID: 7227626300)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

---------

Co-authored-by: propr-dev[bot] <1316198+propr-dev[bot]@users.noreply.github.com>
@propr-dev propr-dev Bot changed the title ⚠️ 4/6 [Epic] Pi coding agent support ◕ 5/6 [Epic] Pi coding agent support Nov 27, 2026
Goals can now run on Pi. A goal keeps a single Pi session across all its runs, and every later run reopens that session file, so the conversation carries through checkpoints, pauses, corrections and model changes.

How it works
- Capability: `goalCapabilities` reports Pi as goal-capable with `launch: 'goal-prompt'`, `resume: 'whole-session'`, `runningInput: 'safe-boundary-resume'`. The probe runs `pi --help` offline with nothing mounted and requires the session flags (`-p`, `--mode`, `--session`, `--session-id`, `--session-dir`, `--no-session`). `PiAgent.goalCapable` is now `true`.
- Where sessions live: each goal gets its own directory at `/tmp/git-processor/pi-goal-sessions/<goal-id>` (override with `PI_GOAL_SESSIONS_PATH`), outside Pi's disposable home. It's created at 0700 and mounted into the run.
- Owner-only: `scripts/pi-entrypoint.sh` chowns the mounted directory to `node` and sets it and its files to owner-only before Pi starts and again after it exits, including after a stop. Without this, Pi's session files come out world-readable (0644).
- New goal: the first run uses `--session-id <uuid>`, an ID ProPR assigns. The ID is saved as soon as the stream shows Pi has written the prompt to the session file. A run stopped before that saves nothing, so the next attempt starts fresh instead of resuming an empty session. To read that moment from the stream I added a small `sessionIdFromLine` option to the shared docker executor.
- Resume: later runs use `--session <exact file>`. If you point Pi 1.6.1 at a file that doesn't exist, it quietly starts an empty session there. So the worker checks the file exists first and fails the goal with a clear error if it's gone.
- Boundaries: checkpoints, model changes, pause and input go through the existing whole-session path in `processGoalJob.ts`. Goal input is sent to Pi unchanged, and direct goals protect the `.git` metadata.
- Environment: Pi now passes the per-run environment (goal mode, launch strategy, admission parent and its key) into the container by variable name. Before this, Pi dropped it; this applies to task runs too.
- Cleanup: deleting a goal removes its session directory. A finished goal keeps it so it can be continued.
- RPC mode (`--mode rpc` live steering) is not implemented; I documented it as a follow-up in `docs/docs/features/goals.md`.

The docs are also updated in `agents-and-models.md` and `architecture/agent-runtime.md`.

Testing
- New `test/piGoalSession.test.ts` (16 tests) covers the capability probe against the real Pi 1.6.1 help output, session store permissions, `--session-id` vs `--session` args, and the missing-file failure. It also covers a run that resumes and keeps the earlier conversation, and a resume after a checkpoint that delivers the checkpoint feedback into the same session.
- Two entrypoint tests in `test/piCredentials.test.ts` cover the owner-only permissions and refusing unsafe or missing directories.
- Separately, I ran the real Pi 1.6.1 binary through the real entrypoint against a mock model server. It created the session under the assigned ID and resumed it with the conversation intact ("seen 2 user messages"), with files at 0600 and directories at 0700.
- Typecheck passes for core, root and api, and lint is clean on the changed files. The existing Pi, goal, docker-executor and `processGoalJob` suites pass.
- The API goal route tests are only partly checked. `goalRoutes.test.ts` passes alone (it contains delete-route cases). Run together with `goalContinueRoute` and `goalCliRoutes`, it hit a 600s timeout with almost no output; that looks like the known hang at exit in `packages/api` tests, but I didn't confirm it.

There are no visual previews because nothing in the UI changes.

ProPR-Agent: claude/claude-opus-5-5

Co-authored-by: propr-dev[bot] <1316198+propr-dev[bot]@users.noreply.github.com>
@propr-dev

propr-dev Bot commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

✅ Epic ready for final merge: Pi coding agent support

6 of 6 issues merged

All 6 issues have been merged into this epic branch. This epic PR is ready for final review and merge.


Posted automatically by ProPR

@integry
integry marked this pull request as ready for review November 27, 2026 22:12
@propr-dev

propr-dev Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

🔀 Resolved merge conflicts from main into 3831-epic-pi-coding-jml in commit 9f5bb36

Conflicting Files

  • Dockerfile.agent
  • docs/docs/features/agents-and-models.md
  • packages/api/services/agentHealthCheck.ts
  • packages/api/services/redisOutputParser.ts
  • packages/api/test/agentHealthCheck.test.ts
  • packages/cli/src/commands/agentCommands.ts
  • packages/core/src/agents/types.ts
  • packages/core/src/agents/version/types.ts
  • propr-ui/src/pages/SettingsPage/AgentCredentialSetup.tsx
  • scripts/generate-notices.sh
  • scripts/smoke-test-images.sh
  • test/redisOutputParser.test.ts

Resolution Summary

All 12 conflicted files are resolved and no conflict markers remain anywhere in the repo. Main had moved OpenCode to the new @opencode/cli 2.x package installed under /opt/opencode, and added Antigravity keyring and file-token handling. The PR adds the Pi agent. Almost every conflict was the two sides adding things in the same spot, so I kept both: main's version wherever it replaced old code, plus the PR's Pi additions.

Image and scripts

  • Dockerfile.agent (3 conflicts): The PR still used the old opencode-ai install path, and main replaced it. I took main's OpenCode layout (copy /opt/opencode, symlink its bin/opencode) and kept the PR's Pi lines: the pi-cli stage copy and link_npm_bin @earendil-works/pi-coding-agent pi. Both credential helpers are copied: main's opencode-credentials.py and the PR's pi-credentials.py. The stale link_npm_bin opencode-ai opencode line is gone, since that package path no longer exists in the image.
  • scripts/generate-notices.sh: The comment listing the image-only CLIs now names @opencode/cli (main) and still includes the PR's Pi package.
  • scripts/smoke-test-images.sh: Both sides added separate smoke checks at the same place. I kept the PR's Pi checks first, then main's OpenCode root-ownership check and the docker stop token write-back checks for OpenCode and Antigravity.

Core and API

  • packages/core/src/agents/version/types.ts: Main bumped OpenCode to @opencode/cli 2.4.2, and the PR added pi 1.6.1. I used main's OpenCode entries and added Pi. Main's fallback that installs opencode-ai for pinned 1.x versions still works.
  • packages/core/src/agents/types.ts: Both sides added an optional method to the Agent interface. It now has main's credentialProblem() and the PR's checkCredentials(model), plus the PR's AgentCredentialCheckResult type.
  • packages/api/services/agentHealthCheck.ts: The dependency type now includes both methods. In the health check, main's credentialProblem() runs first: it is a cheap local file check and catches an unreadable Antigravity keyring login. Then comes the PR's checkCredentials (Pi's pi auth check --no-refresh), and the analysis prompt stays as the fallback. Neither of the two new checks spends tokens.
  • packages/api/services/redisOutputParser.ts: Only the imports conflicted, so I kept both the Pi and the Antigravity stream parser imports. The existing order already tries Antigravity's stream format before Pi records.

CLI, UI and docs

  • packages/cli/src/commands/agentCommands.ts: The agent login help text keeps both notes, Pi's one-provider-per-login and main's Antigravity file-token note.
  • propr-ui/.../AgentCredentialSetup.tsx: Both imports are kept, the PR's credentialSetupOptions and main's InlineCodeText; the component uses both.
  • docs/docs/features/agents-and-models.md: Main's Antigravity paragraph goes right after the "Use existing config" text it explains, followed by the PR's ### Pi section.

Tests

  • packages/api/test/agentHealthCheck.test.ts and test/redisOutputParser.test.ts: Both sides added new test cases at the same point. I kept all of them and restored the closing brace that the two blocks shared.

Verification

  • Typecheck is clean for shared, core, api and cli, after building core and local-setup. propr-ui shows only "cannot find @propr/cli/desktop-discovery" errors, because the CLI package isn't built in this container; that is unrelated to the merge.
  • agentHealthCheck.test.ts passes 11/11, including the Pi and Antigravity cases.
  • test/redisOutputParser.test.ts passes 28/28, including the Pi and Antigravity cases.
  • The version-pin suites pass: agentVersionManagement, agentBundleContentFiles and agentRegistryManagedAgentPin. The last one needs --experimental-test-module-mocks and passes 9/9 with it.
  • bash -n passes on both edited shell scripts. The Docker image and smoke test were not built or run, because there is no Docker in this container.

🤖 Resolution Details

  • Model: Claude Opus 5.5
  • Time: 6m 41s

View Task Execution


System-triggered merge conflict resolution

@propr-dev propr-dev Bot changed the title ◕ 5/6 [Epic] Pi coding agent support ◕ 6/6 [Epic] Pi coding agent support Nov 27, 2026
Automatically resolved merge conflicts after merging target branch into PR branch.
Resolved conflicts in:
- Dockerfile.agent
- docs/docs/features/agents-and-models.md
- packages/api/services/agentHealthCheck.ts
- packages/api/services/redisOutputParser.ts
- packages/api/test/agentHealthCheck.test.ts
- packages/cli/src/commands/agentCommands.ts
- packages/core/src/agents/types.ts
- packages/core/src/agents/version/types.ts
- propr-ui/src/pages/SettingsPage/AgentCredentialSetup.tsx
- scripts/generate-notices.sh
- scripts/smoke-test-images.sh
- test/redisOutputParser.test.ts

PR: #3847
Model: Claude Opus 5.5

integry commented Nov 27, 2026

Copy link
Copy Markdown
Owner

/ultrafix goal=8 max=10

@propr-dev propr-dev Bot added the ultrafix label Nov 27, 2026
@propr-dev

propr-dev Bot commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

🔄 Ultrafix loop started (goal: 8/10, max cycles: 10)

First action: /review

💡 Tip: Remove the ultrafix label from this PR to stop further ultrafix cycles.

@propr-dev

propr-dev Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

⚠️ Ultrafix stopped before reaching its goal. Requested goal: 8/10. Last score: unknown. Stopped in cycle 1 of 10. CI did not settle: blocking checks were still not passing after 2 hours. Blocking checks: Finalize unsigned validation checksums, Validate unsigned darwin-x64 package. Fix or re-run those checks, then re-arm the loop with /ultrafix.

@propr-dev

propr-dev Bot commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

CI failed: Validate Changes

Please investigate and fix this CI failure.

Failure evidence

.github:8
Process completed with exit code 1.

.github:415
Process completed with exit code 1.

@github-actions

Copy link
Copy Markdown

Checks Failed

Validation failed during setup, tests, CLI packaging, linting, or build checks.

View Logs
Build check diagnostics for run 46075980582, attempt 1
Checkout outcome: success

--- GitHub Actions workflow lint ---
docker.io/rhysd/actionlint@sha256:b1934ee5f1c509618f2508e6eb47ee0d3520686341fec936f3b79331f9315667: Pulling from rhysd/actionlint
589002ba0eae: Pulling fs layer
c09af8888d6a: Pulling fs layer
4ccd7d76ca98: Pulling fs layer
b6b4b7b0e257: Pulling fs layer
b6b4b7b0e257: Waiting
589002ba0eae: Verifying Checksum
589002ba0eae: Download complete
c09af8888d6a: Verifying Checksum
c09af8888d6a: Download complete
4ccd7d76ca98: Verifying Checksum
589002ba0eae: Pull complete
c09af8888d6a: Pull complete
4ccd7d76ca98: Pull complete
b6b4b7b0e257: Verifying Checksum
b6b4b7b0e257: Download complete
b6b4b7b0e257: Pull complete
Digest: sha256:b1934ee5f1c509618f2508e6eb47ee0d3520686341fec936f3b79331f9315667
Status: Downloaded newer image for rhysd/actionlint@sha256:b1934ee5f1c509618f2508e6eb47ee0d3520686341fec936f3b79331f9315667
docker.io/rhysd/actionlint@sha256:b1934ee5f1c509618f2508e6eb47ee0d3520686341fec936f3b79331f9315667

--- Release shell script lint ---

--- Toolchain ---
v22.23.5
10.9.9

--- Dependency installation ---
npm warn deprecated [email protected]: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
npm warn deprecated [email protected]: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]
npm warn deprecated [email protected]: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

added 1112 packages, and audited 1121 packages in 50s

318 packages are looking for funding
  run `npm fund` for details

8 moderate severity vulnerabilities

To address issues that do not require attention, run:
  npm audit fix

To address all issues (including breaking changes), run:
  npm audit fix --force

Run `npm audit` for details.

--- CLI release package ---
Verifying propr-cli release package...

> [email protected] cli:pack
> node packages/cli/scripts/build-publish.mjs


> @propr/[email protected] build
> tsc


> @propr/[email protected] build
> tsc


> @propr/[email protected] build
> tsc && node scripts/copy-assets.mjs

copy-assets: copied 9 file(s) into the CLI package.

Staged [email protected] at /home/runner/work/propr/propr/dist-publish/propr-cli
npm notice
npm notice 📦  [email protected]
npm notice Tarball Contents
npm notice 32.0kB README.md
npm notice 36.6kB dist/agentSkill.js
npm notice 477B dist/api/admission.js
npm notice 754B dist/api/agentRuntime.js
npm notice 7.2kB dist/api/agents.js
npm notice 2.6kB dist/api/agentTank.js
npm notice 4.4kB dist/api/automations.js
npm notice 13.3kB dist/api/client.js
npm notice 5.9kB dist/api/errors.js
npm notice 1.6kB dist/api/followupHandoffs.js
npm notice 16.9kB dist/api/goals.js
npm notice 6.0kB dist/api/implement.js
npm notice 2.9kB dist/api/index.js
npm notice 1.9kB dist/api/logs.js
npm notice 7.7kB dist/api/plans.js
npm notice 586B dist/api/pullRequests.js
npm notice 4.2kB dist/api/relay.js
npm notice 12.5kB dist/api/repos.js
npm notice 2.5kB dist/api/repositoryEvents.js
npm notice 16.2kB dist/api/settings.js
npm notice 2.0kB dist/api/stats.js
npm notice 1.6kB dist/api/syntheticPools.js
npm notice 1.8kB dist/api/system.js
npm notice 5.9kB dist/api/tasks.js
npm notice 2.9kB dist/api/todos.js
npm notice 86B dist/api/types.js
npm notice 313B dist/api/visualPreviewAuth.js
npm notice 33.5kB dist/assets/env.example.txt
npm notice 5.9kB dist/auth/githubLogin.js
npm notice 5.0kB dist/auth/verifyToken.js
npm notice 9.0kB dist/commands/admissionCommands.js
npm notice 20.8kB dist/commands/agentCommands.js
npm notice 4.2kB dist/commands/agentPoolCommands.js
npm notice 4.4kB dist/commands/agentSkillCommands.js
npm notice 34.2kB dist/commands/agentValidation.js
npm notice 31.2kB dist/commands/automationCommands.js
npm notice 74.1kB dist/commands/checkCommands.js
npm notice 8.9kB dist/commands/configCommands.js
npm notice 14.6kB dist/commands/connectCommand.js
npm notice 12.2kB dist/commands/eventCommands.js
npm notice 5.5kB dist/commands/githubAppApi.js
npm notice 27.7kB dist/commands/githubAppCommands.js
npm notice 60.9kB dist/commands/goalCommands.js
npm notice 9.4kB dist/commands/handoffCommands.js
npm notice 2.4kB dist/commands/imageCommands.js
npm notice 8.6kB dist/commands/implementCommands.js
npm notice 2.0kB dist/commands/index.js
npm notice 8.5kB dist/commands/initCommands.js
npm notice 14.5kB dist/commands/initStack.js
npm notice 6.1kB dist/commands/logCommands.js
npm notice 26.5kB dist/commands/planCommands.js
npm notice 3.1kB dist/commands/prCommands.js
npm notice 8.4kB dist/commands/relayCommands.js
npm notice 41.4kB dist/commands/repoCommands.js
npm notice 2.7kB dist/commands/repoValidate.js
npm notice 7.5kB dist/commands/runtimeCommands.js
npm notice 19.8kB dist/commands/settingCommands.js
npm notice 4.8kB dist/commands/setup/agentHostActions.js
npm notice 123B dist/commands/setup/agents.js
npm notice 4.7kB dist/commands/setup/engine.js
npm notice 51B dist/commands/setup/github.js
npm notice 37.3kB dist/commands/setup/hostActions.js
npm notice 3.2kB dist/commands/setup/imagePlatform.js
npm notice 27.3kB dist/commands/setup/sequential.js
npm notice 51B dist/commands/setup/state.js
npm notice 51B dist/commands/setup/types.js
npm notice 10.7kB dist/commands/setupCommand.js
npm notice 4.4kB dist/commands/stackCommands.js
npm notice 1.4kB dist/commands/startCommand.js
npm notice 4.8kB dist/commands/statsCommands.js
npm notice 4.9kB dist/commands/statsCostCommand.js
npm notice 14.8kB dist/commands/systemCommands.js
npm notice 3.5kB dist/commands/tankCommands.js
npm notice 47.6kB dist/commands/taskCommands.js
npm notice 29.7kB dist/commands/todoCommands.js
npm notice 31.0kB dist/commands/tunnelCommand.js
npm notice 2.7kB dist/commands/uiDocsCommands.js
npm notice 8.3kB dist/completion.js
npm notice 27.3kB dist/config/ConfigManager.js
npm notice 276B dist/config/index.js
npm notice 989B dist/config/rootKey.js
npm notice 345B dist/config/types.js
npm notice 46.0kB dist/connectIdentity.js
npm notice 25.0kB dist/connectRootAuthority.js
npm notice 32.5kB dist/connectWindowsAuthority.js
npm notice 2.2kB dist/desktopDiscovery.js
npm notice 13.3kB dist/desktopLocalSetup.js
npm notice 17.4kB dist/index.js
npm notice 4.5kB dist/native/darwin-authority-broker.c
npm notice 8.9kB dist/native/directory-operations.c
npm notice 50.1kB dist/native/prebuilds/darwin-arm64/connect-authority-broker
npm notice 54.2kB dist/native/prebuilds/darwin-arm64/directory-operations.node
npm notice 17.1kB dist/native/prebuilds/darwin-x64/connect-authority-broker
npm notice 24.3kB dist/native/prebuilds/darwin-x64/directory-operations.node
npm notice 28.9kB dist/native/prebuilds/linux-arm64/directory-operations.node
npm notice 17.4kB dist/native/prebuilds/linux-x64/directory-operations.node
npm notice 1.2kB dist/native/README.md
npm notice 3.1kB dist/orchestrator/format.js
npm notice 13.4kB dist/orchestrator/index.js
npm notice 302B dist/orchestrator/manifest.json
npm notice 131.9kB dist/orchestrator/orchestrator.mjs
npm notice 408B dist/orchestrator/types.js
npm notice 6.2kB dist/rootHelp.js
npm notice 237B dist/skill/propr/agents/openai.yaml
npm notice 8.9kB dist/skill/propr/SKILL.md
npm notice 4.5kB dist/tui/AgentTableApp.js
npm notice 4.5kB dist/tui/app.js
npm notice 11.6kB dist/tui/CheckApp.js
npm notice 5.1kB dist/tui/render.js
npm notice 32.5kB dist/tui/SetupApp.js
npm notice 18.4kB dist/tui/SetupApp.test.js
npm notice 8.2kB dist/tui/StartApp.js
npm notice 3.8kB dist/utils/apiErrorPresentation.js
npm notice 12.0kB dist/utils/directoryDescriptor.js
npm notice 739B dist/utils/dockerPort.js
npm notice 5.0kB dist/utils/envFile.js
npm notice 520B dist/utils/index.js
npm notice 5.7kB dist/utils/io.js
npm notice 717B dist/utils/localSetupPlatform.js
npm notice 1.5kB dist/utils/nativeArtifact.js
npm notice 544B dist/utils/parseState.js
npm notice 417B dist/utils/positiveInteger.js
npm notice 4.5kB dist/utils/privateFilesystem.js
npm notice 4.2kB dist/utils/resolveProject.js
npm notice 7.2kB dist/vendor/local-setup/agents.js
npm notice 65.6kB dist/vendor/local-setup/engine.js
npm notice 5.0kB dist/vendor/local-setup/envFile.js
npm notice 11.4kB dist/vendor/local-setup/github.js
npm notice 188B dist/vendor/local-setup/index.js
npm notice 27.5kB dist/vendor/local-setup/publicInstanceIdentity.js
npm notice 14.6kB dist/vendor/local-setup/state.js
npm notice 2.8kB dist/vendor/local-setup/types.js
npm notice 13.2kB dist/vendor/shared/acceptanceCriteria.js
npm notice 1.0kB dist/vendor/shared/accountStatusTimestamp.js
npm notice 7.7kB dist/vendor/shared/activityEvents.js
npm notice 2.8kB dist/vendor/shared/agentConfigRedaction.js
npm notice 4.4kB dist/vendor/shared/agentDefinitions.js
npm notice 2.3kB dist/vendor/shared/agentFailureLine.js
npm notice 5.6kB dist/vendor/shared/agentLogin.js
npm notice 3.1kB dist/vendor/shared/agentTank.js
npm notice 1.2kB dist/vendor/shared/agentTankHistory.js
npm notice 2.8kB dist/vendor/shared/analyticsTimeframe.js
npm notice 4.4kB dist/vendor/shared/antigravityCompatibility.js
npm notice 3.5kB dist/vendor/shared/antigravityKeyringLogin.js
npm notice 5.1kB dist/vendor/shared/apiOrigin.js
npm notice 3.5kB dist/vendor/shared/assignment.js
npm notice 17.2kB dist/vendor/shared/automationDefinitions.js
npm notice 9.2kB dist/vendor/shared/automationReportPreview.js
npm notice 2.4kB dist/vendor/shared/automationRunProductivity.js
npm notice 6.4kB dist/vendor/shared/automationTemplateContract.js
npm notice 18.5kB dist/vendor/shared/automationTemplates.catalog.json
npm notice 1.3kB dist/vendor/shared/automationTemplates.js
npm notice 3.4kB dist/vendor/shared/changedFileKinds.js
npm notice 1.4kB dist/vendor/shared/claudeCompatibility.js
npm notice 12.1kB dist/vendor/shared/commitSubject.js
npm notice 8.5kB dist/vendor/shared/connectDiscovery.js
npm notice 9.6kB dist/vendor/shared/cronSchedule.js
npm notice 254B dist/vendor/shared/demoMode.js
npm notice 4.3kB dist/vendor/shared/desktopPairing.js
npm notice 481B dist/vendor/shared/desktopTokenRevocation.js
npm notice 8.9kB dist/vendor/shared/events.js
npm notice 13.3kB dist/vendor/shared/extensionLibrary.js
npm notice 703B dist/vendor/shared/extensionOAuth.js
npm notice 4.0kB dist/vendor/shared/extensionPackages.js
npm notice 2.9kB dist/vendor/shared/extensionProfiles.js
npm notice 2.7kB dist/vendor/shared/fleetData.js
npm notice 2.5kB dist/vendor/shared/githubAppManifest.js
npm notice 1.6kB dist/vendor/shared/githubAuthMode.js
npm notice 2.0kB dist/vendor/shared/githubEventIntakeMode.js
npm notice 12.8kB dist/vendor/shared/goalBlockers.js
npm notice 6.0kB dist/vendor/shared/goalCheckpoints.js
npm notice 4.0kB dist/vendor/shared/goalCreation.js
npm notice 5.2kB dist/vendor/shared/goalWait.js
npm notice 15.1kB dist/vendor/shared/index.js
npm notice 214B dist/vendor/shared/instanceAuthorization.js
npm notice 54B dist/vendor/shared/instanceCatalog.js
npm notice 584B dist/vendor/shared/instanceStorage.js
npm notice 4.0kB dist/vendor/shared/intakeModePrerequisites.js
npm notice 2.9kB dist/vendor/shared/labelUtils.js
npm notice 22.9kB dist/vendor/shared/modelDefinitions.js
npm notice 3.5kB dist/vendor/shared/notificationLinks.js
npm notice 51.3kB dist/vendor/shared/notifications.js
npm notice 2.9kB dist/vendor/shared/openCodeCompatibility.js
npm notice 1.4kB dist/vendor/shared/piProviders.js
npm notice 16.9kB dist/vendor/shared/planItemGraph.js
npm notice 7.5kB dist/vendor/shared/previewStorage/v1.js
npm notice 866B dist/vendor/shared/projectSlug.js
npm notice 3.8kB dist/vendor/shared/proprCompatibility.js
npm notice 884B dist/vendor/shared/proprRuntimePaths.js
npm notice 13.0kB dist/vendor/shared/proprServiceUrls.js
npm notice 17.0kB dist/vendor/shared/prTemplate.js
npm notice 6.9kB dist/vendor/shared/prTitleStatusSlot.js
npm notice 2.2kB dist/vendor/shared/publishedVisualPreviews.js
npm notice 3.0kB dist/vendor/shared/reasoningLevels.js
npm notice 1.8kB dist/vendor/shared/repositoryEvents.js
npm notice 6.7kB dist/vendor/shared/repositoryEventWait.js
npm notice 1.2kB dist/vendor/shared/repositoryIcon.js
npm notice 1.4kB dist/vendor/shared/repositoryIconUrl.js
npm notice 3.9kB dist/vendor/shared/repositoryPresentation.js
npm notice 10.4kB dist/vendor/shared/reviewContextBudget.js
npm notice 5.8kB dist/vendor/shared/reviewFeedbackIds.js
npm notice 2.7kB dist/vendor/shared/reviewPrompt.js
npm notice 907B dist/vendor/shared/runCostCap.js
npm notice 861B dist/vendor/shared/sessionSecret.js
npm notice 392B dist/vendor/shared/sqliteTimestamp.js
npm notice 603B dist/vendor/shared/statusKeys.js
npm notice 7.5kB dist/vendor/shared/syntheticAgents.js
npm notice 2.2kB dist/vendor/shared/taskIdentifiers.js
npm notice 2.0kB dist/vendor/shared/taskLifecycle.js
npm notice 733B dist/vendor/shared/taskReplacement.js
npm notice 957B dist/vendor/shared/text.js
npm notice 2.6kB dist/vendor/shared/tokenOutlierSettings.js
npm notice 1.9kB dist/vendor/shared/ultrafixCycle.js
npm notice 1.8kB dist/vendor/shared/unfinishedRun.js
npm notice 9.8kB dist/vendor/shared/usageTips.catalog.json
npm notice 5.0kB dist/vendor/shared/usageTips.js
npm notice 335B dist/vendor/shared/usageTypes.js
npm notice 1.1kB dist/vendor/shared/userWhitelist.js
npm notice 758B dist/vendor/shared/validateRelayUrl.js
npm notice 2.2kB dist/vendor/shared/validateRoutingUrl.js
npm notice 7.1kB dist/vendor/shared/visualPreviewCapacity.js
npm notice 9.3kB dist/vendor/shared/voice.js
npm notice 222B dist/vendor/shared/workEvidence.js
npm notice 828B package.json
npm notice Tarball Details
npm notice name: propr-cli
npm notice version: 0.9.3
npm notice filename: propr-cli-0.9.3.tgz
npm notice package size: 557.1 kB
npm notice unpacked size: 2.2 MB
npm notice shasum: fb58076def04d0bdb9e80388a23a0bd027fd3c46
npm notice integrity: sha512-fBLWF07bTouqf[...]upjSQNqsGUfxw==
npm notice total files: 224
npm notice
propr-cli-0.9.3.tgz

Dry run only. Re-run with --publish to publish to npm.
✅ propr-cli release package verified
Starting changed-area validation process...
Reusing this job's @propr/shared build from CLI packaging.
Reusing this job's @propr/local-setup build from CLI packaging.

--- Core Service: Lint & Build ---
✅ Core Lint passed
✅ Core Source Build passed

--- UI: Typecheck, Lint & Build ---
✅ Client Package validation passed
✅ UI Typecheck passed
✅ UI Lint passed
✅ UI Build passed

--- Docs: Typecheck & Build ---
✅ Docs Typecheck passed
✅ Docs Build passed
✅ Docs Static Serving Check passed

--- Core Package: Build & Lint ---
✅ Core Package Build passed
✅ Core Package Lint passed

--- CLI: Lint ---
✅ CLI Lint passed

--- API: Build & Lint ---
✅ API Build passed
❌ API Lint FAILED

> @propr/[email protected] lint
> eslint . --max-warnings 0


/home/runner/work/propr/propr/packages/api/services/agentHealthCheck.ts
  126:56  warning  Async arrow function has a complexity of 22. Maximum allowed is 20  complexity

✖ 1 problem (0 errors, 1 warning)

ESLint found too many warnings (maximum: 0).
npm error Lifecycle script `lint` failed with error:
npm error code 1
npm error path /home/runner/work/propr/propr/packages/api
npm error workspace @propr/[email protected]
npm error location /home/runner/work/propr/propr/packages/api
npm error command failed
npm error command sh -c eslint . --max-warnings 0

--- API Reference: OpenAPI Spec & Client Contract ---
✅ OpenAPI spec is current and valid
✅ @propr/client matches the OpenAPI spec

--- Stage outcomes ---
Workflow lint: success
Release shell lint: success
Pre-setup gate: skipped
Node setup: success
Toolchain: success
Dependency install: success
Release metadata: success
CLI packaging: success
Change detection: success
Changed-area checks: failure
Chromium install: skipped
PWA and mobile browser smoke: skipped

View Workflow

@propr-dev

propr-dev Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor Author

✅ Applied the requested follow-up changes in commit fb16e2c

Processed 2 comments:

  • Comment 1 by @propr-dev[bot] (ID: 7229300577✓)
  • Comment 2 by @github-actions[bot] (ID: 7229301096✓)

Summary of Changes

I fixed the Validate Changes failure. It was the API lint gate: the health-check probe in packages/api/services/agentHealthCheck.ts had a complexity of 22, and the limit is 20. The Pi credential-check branch added in this epic pushed it over.

Fix: I moved the code that turns a credential-check result into a health result into its own helper, credentialCheckResult, and the probe now just calls it. The behaviour is unchanged:

  • A ready result reports ready.
  • provider_not_found reports unknown.
  • Anything else reports auth_required, with the same redacted message.

Verification (local):

  • eslint . --max-warnings 0 in packages/api passes with no warnings.
  • tsc --noEmit in packages/api passes, run after rebuilding core.
  • The agent health-check tests pass: 31 passed, 1 skipped, 0 failed. They only run with PROPR_DEMO_MODE=true; without it they exit early because GitHub auth isn't configured in this container.

There are no visual previews because nothing visible changed.

Review digest

Risk-tiered paths

  • High risk: none
  • Normal risk (1 file)
    • packages/api/services/agentHealthCheck.ts (+11/−8)
  • Low risk: none

Diff size: 1 file changed, +11/−8 lines


🤖 Implementation Details

  • Model: Claude Opus 5.5 (medium)
  • Requested By: @propr-dev[bot], @github-actions[bot]
  • Time: 7m 5s
  • Tokens: 548,089 (545,824 in / 2,265 out)
  • Cost: $0.40

Undo Changes • View Task Execution


💡 ProPR Slash Commands
Command Description Example
/merge Merge target branch into this PR and resolve conflicts /merge
/review Request an AI code review /review or /review claude-sonnet
/fix Address review blockers, or blockers and suggestions with /fix all /fix, /fix all, or /fix F3 S5
/switch Change the AI model for this PR /switch claude-opus
/use Override the model for a single follow-up run /use claude-sonnet
/ultrafix Loop review→fix cycles until score goal is met /ultrafix or /ultrafix goal=8 max=10

🤖 Generated by ProPR
Processing comment IDs: 7229300577✓, 7229301096✓

I fixed the Validate Changes failure. It was the API lint gate: the health-check probe in `packages/api/services/agentHealthCheck.ts` had a complexity of 22, and the limit is 20. The Pi credential-check branch added in this epic pushed it over.

**Fix:** I moved the code that turns a credential-check result into a health result into its own helper, `credentialCheckResult`, and the probe now just calls it. The behaviour is unchanged:
- A `ready` result reports ready.
- `provider_not_found` reports `unknown`.
- Anything else reports `auth_required`, with the same redacted message.

**Verification (local):**
- `eslint . --max-warnings 0` in `packages/api` passes with no warnings.
- `tsc --noEmit` in `packages/api` passes, run after rebuilding core.
- The agent health-check tests pass: 31 passed, 1 skipped, 0 failed. They only run with `PROPR_DEMO_MODE=true`; without it they exit early because GitHub auth isn't configured in this container.

There are no visual previews because nothing visible changed.

PR: #3847
Comment by: @propr-dev[bot] (ID: 7229300577)
Comment by: @github-actions[bot] (ID: 7229301096)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5
@propr-dev

propr-dev Bot commented Nov 28, 2026

Copy link
Copy Markdown
Contributor Author

🔍 AI Code Review — astra

Overall Evaluation

Pi is integrated across the agent image, task execution, repository scouting, settings, health checks, and goal resume. Significant corrections are needed before merge. The most serious issue is a root cleanup operation that can delete host credentials after repository setup has run. Goal execution also changes permissions on repository outputs, and the CLI can direct an operator to repair the wrong credential store.

✅ Scout tool isolation — The scout disables built-in tools, reloads only builtin:mcp, and allowlists the three repository tools. The supplied Pi 1.6.1 fixture shows those three tools in the system message and records a successful repository read.

✅ Live event identity — The live parser keys tool results by call ID and streamed blocks by message identity and content index. The retention tests compare incremental reads with full reads, including when Redis has trimmed the original tool announcement.

The review is partial. The issue descriptions and historical follow-up logs contain truncation notices, and 26 changed files were omitted, including PiAgent.ts, scripts/pi-credentials.py, and their principal tests. Current-head checks show 36 passed, zero failed, and two pending. Shard 2 passed on this head.

Merge blockers

Every finding below was introduced by this PR and must be resolved before merging.

F33: 🔴 Root cleanup can delete host credentials

  • Category: security

  • Required behavior: Repository code running as node must be unable to delete or replace the host credential source. Host mutations must go through the protected OAuth refresh writer.

  • Evidence: scripts/pi-entrypoint.sh, prepare_runtime_home and the failed-baseline cleanup immediately after prepare_goal_sessions

    static trace:

    1. The task wrapper runs the repository setup hook as node before invoking the Pi entrypoint. A process left running by that hook can continue while the entrypoint imports credentials.
    2. prepare_runtime_home transfers the entire runtime home to node. The entrypoint subsequently checks the imported auth.json as root and awaits the baseline reader running as node. During that window, the setup process can replace the agent directory entry in the now-writable runtime home.
    3. If that directory entry points to the protected source directory, the root file check succeeds but the unprivileged baseline reader cannot traverse the source. The failure branch then executes /bin/rm -f -- "$pi_agent_dir/auth.json" as root. Path resolution follows the replaced parent directory, deleting the host auth.json on its writable mount.

    The pinned source descriptor and the helper’s O_NOFOLLOW checks protect the helper’s operations. This deletion is a separate shell operation through a path whose parent has already been handed to node.

  • Minimum fix: Capture the baseline and complete any failed-import cleanup while the disposable home is still root-owned. Transfer ownership only after those operations finish.

F34: 🔴 Goal privacy also restricts repository outputs

  • Category: correctness

  • Required behavior: Goal session files must stay owner-only while implementation outputs remain usable by the worker across checkpoints and follow-ups.

  • Evidence: scripts/pi-entrypoint.sh, goal-mode umask 077 around exec_as_node; scripts/smoke-test-images.sh, worker ownership matrix

    static trace:

    1. Start a goal with the supported 1001:1001 worker and container node user 1000. The entrypoint applies umask 077 to the entire Pi process and its descendants.
    2. A goal tool creates an ordinary source file or a new directory in the writable worktree. Normal creation modes become 0600 and 0700, owned by UID 1000.
    3. The worker cannot read the new file or traverse the new directory when inspecting the worktree after the run. The epilogue adjusts only the session store. The smoke test verifies the session file’s mode and explicitly asserts the process-wide umask, but never creates a repository output and reads it as the worker.
  • Minimum fix: Confine owner-only creation to session storage and preserve normal task permissions in the worktree. Extend the existing cross-UID smoke case to verify both session privacy and worker access to a newly created repository file.

F35: 🔴 Managed credential recovery targets the host store

  • Category: correctness

  • Required behavior: A failed check of a configured Pi agent must direct the operator to repair the credentials that agent actually uses.

  • Evidence: packages/cli/src/commands/piConfiguredAgentCheck.ts, runConfiguredPiAgentCheck; packages/cli/src/commands/agentValidation.ts, planAgentLogin

    static trace:

    1. A Pi agent uses an isolated managed directory and its provider login expires. CLI validation calls the stack health endpoint with that agent’s ID and receives an invalid credential result.
    2. The failure cell instructs the operator to run propr agent login pi --provider <provider>. planAgentLogin resolves that command’s destination from HOST_PI_DIR or the default host Pi directory. The command takes no configured agent ID.
    3. Following the instruction can successfully write a login into the host account while leaving the managed account invalid. Rechecking the original agent produces the same failure. Passing the provider selects the provider entry, but does not select the credential directory.
  • Minimum fix: Direct operators to the existing Settings login for the checked agent ID. Offer the host CLI command only when its resolved destination matches the checked store.

F36: 🔴 Live MCP tool names change on completion

  • Category: correctness

  • Required behavior: Pi’s live and stored execution views must identify the same tool call consistently.

  • Evidence: packages/api/services/redisOutputParserPi.ts, rememberToolCall and emitToolUse; packages/core/src/agents/impl/utils/piOutputParser.ts, toolUseItem; packages/api/test/liveDetailsPiParser.test.ts

    static trace:

    1. The supplied scout fixture announces mcp__propr_repository__read_repository_file. The Redis parser retains the raw name and emits it directly as toolName.
    2. When stored details are loaded, toolUseItem passes the same name through readablePiToolName, producing propr_repository/read_repository_file. The displayed name changes for the same call.
    3. The test titled “the live view names a directly declared MCP tool” calls only parseStoredOutputContent. The test comparing actual live and stored tool names uses the built-in tool fixture, whose names require no conversion.
  • Minimum fix: Reuse the same MCP name conversion in the Redis parser and run the existing live-versus-stored comparison against the scout and codemode fixtures.

F37: 🔴 Pi credential checks duplicate result parsing

  • Category: complexity

  • Required behavior: The CLI and stack health paths require one Pi credential-result contract. The objective calls for exposing that check across entry points, without independently implementing its protocol in each one.

  • Evidence: packages/cli/src/commands/agentValidation.ts, evaluatePiAuthCheck; packages/core/src/agents/impl/utils/piAuthCheck.ts, findResultLine, parsePiAuthCheckOutput, and withPiAuthStoreRefusal

    static trace:

    1. Both paths scan stdout backwards for JSON, recognize the same three statuses, validate provider and reason identifiers, and combine the result with the entrypoint’s refusal marker.
    2. Both already import Pi refusal helpers from @propr/shared. Merging the two parsers leaves two implementations to update whenever Pi’s output or refusal handling changes. Their handling already differs for ANSI-decorated output, which only the CLI strips.
  • Minimum fix: Move the pure result-line and refusal interpretation into the existing shared Pi credential module. Keep Docker execution, terminal presentation, and API error formatting in their current callers.

Suggestions

These are optional follow-ups and are not sent to /fix.

S54: 🟢 Bound live delta buffering

redisOutputParserPi.ts truncates displayed text to 2,000 characters while retaining the entire block and appending each delta to it. Keeping only the displayable prefix and a truncation flag would reduce memory use for long thinking blocks. The existing fixtures demonstrate correct rendering at ordinary sizes, so this is an optional performance improvement.

Score

The image integration, scout controls, and retention coverage are substantial. The host credential deletion path and cross-UID goal regression require correction even though current-head CI reports no failures.

Score: 4/10


🤖 Review Details

  • Model: GPT-6.2 Astra
  • Time: 1m 17s
  • Tokens: 200,904 (198,163 in / 2,741 out)
  • Cost: $1.59
  • Review scope: Partial — 26 files were omitted by the review context budget.

View Task

Files omitted from review diff

26 files were omitted from the review diff. Large, binary, generated, and lockfile changes are deprioritized.

Did not fit the review context budget

  • test/cliAgentValidation.test.ts
  • scripts/pi-credentials.py
  • test/fixtures/pi/pi-1.6.1-json-codemode-mcp.jsonl
  • test/piGoalSession.test.ts
  • packages/core/src/agents/impl/PiAgent.ts
  • test/piAgent.test.ts
  • test/piCredentials.test.ts
  • docs/docs/tutorials/setup-vps.md
  • docs/docs/tutorials/setup-source.md
  • docs/static/openapi/propr-api.yaml
  • docs/docs/tutorials/setup-server.md
  • CHANGELOG.md
  • docs/docs/operations/deployment.md
  • docs/docs/tutorials/setup.md
  • packages/cli/README.md
  • docs/operations/native-provider-log-policy.md
  • docs/docs/tutorials/setup-local.md
  • docs/docs/features/propr-cli.md
  • docs/docs/operations/configuration-reference.md
  • docs/docs/operations/settings-locations.md
  • docs/operations/managed-diagnostics.md
  • docs/docs/features/goals.md
  • docs/docs/features/agent-extensions.md
  • docs/docs/features/agents-and-models.md
  • packages/core/test/fixtures/pi-help-1.6.1.txt
  • docs/docs/architecture/agent-runtime.md

💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix F33 F34 F35 F36 F37 S54

🤖 Review by ProPR

@propr-dev propr-dev Bot changed the title ◕ 6/6 [Epic] Pi coding agent support ✅ 6/6 [Epic] Pi coding agent support Nov 28, 2026
@integry

integry commented Nov 28, 2026

Copy link
Copy Markdown
Owner

/fix F33 F34 F35 F36 F37

All five are confirmed against af58280. F33 and F34 matter most. Narrow fixes with a regression test each.

  • F33 (security): .propr/setup.sh runs as node before the entrypoint (repoSetupWrapper.ts) and can leave a background process running. prepare_runtime_home hands the runtime home to node (chown -hR, ~294) before the baseline read (~345) and the root rm -f "$pi_agent_dir/auth.json" (~351). A swapped agent dir can therefore redirect root's rm into the source.
    • Fix: take the baseline and finish any failed-import cleanup while the disposable home is still root-owned, and hand it to node only afterwards. Audit every other root step that touches a path under a node-writable parent the same way.
    • Test: a node-owned process swaps agent for a symlink to the source; the host auth.json survives.
  • F34 (regression from the F19 fix): don't apply umask 077 to the whole Pi process. Worktree outputs must keep normal modes, so a worker with UID ≠ 1000 can read and commit them.
    • Keep session privacy another way: the per-goal dir must not be traversable by others during the run (owner/group grant only, never the "other" bits). Restrict the session files' modes in the epilogue and again on the next prepare.
    • Extend the cross-UID smoke case: session files private, and a new repository file and directory readable by the worker.
  • F35: for an agent with a managed credential dir, the CLI failure hint points to the Settings login for that agent. Offer propr agent login pi --provider … only when its destination is the checked store.
  • F36: the live parser (redisOutputParserPi.ts) uses the same readablePiToolName conversion as the stored one. Run the live-vs-stored comparison on the scout and codemode fixtures.
  • F37: move the pure result-line parsing and refusal interpretation into the shared Pi credential module, used by both the CLI and core. Keep Docker execution and presentation where they are, and keep the CLI's ANSI stripping in the shared version.

@propr-dev propr-dev Bot changed the title ✅ 6/6 [Epic] Pi coding agent support ◕ 6/6 [Epic] Pi coding agent support Nov 28, 2026
@propr-dev

propr-dev Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor Author

✅ Applied the requested follow-up changes in commit a9fabf4

Addressed 1 AI review comment (IDs: 7245237590)

Addressed findings F33, F34, F35, F36, F37

Summary of Changes

All five findings (F33–F37) are fixed, each with a regression test. The two Docker smoke cases are written but I couldn't run them: this container has no Docker and no user namespaces, so they need the image CI. Every other related suite passes: the Pi entrypoint, credential, auth-check, goal-session, agent and scout suites, the post-task suite, CLI validation, the live/stored parser suites and the smoke-script structure tests. Typecheck is clean for shared, core, cli and api. ESLint is clean for the touched core and api files; the CLI files aren't covered by any ESLint config, so they weren't linted.

F33 (root cleanup could delete host credentials) – scripts/pi-entrypoint.sh

  • The baseline read now runs as root inside prepare_runtime_home, before the handoff to node. So does removing a copy that has no baseline (new record_seeded_auth). Both act on root's own 0700 home in /tmp, which no node process can reach yet.
  • The handoff is now the last step. It chowns the agent dir first and the home itself last, so node can't get inside while chown walks the tree.
  • After the handoff, no root step names a path in the home. The "credentials imported" message now comes from root's recorded state, and the post-task read already ran as node.
  • Audit result: as root the entrypoint now refuses any home other than /tmp/propr-pi-home. Any other location could sit under a node-writable parent. Production always uses the standard path, and login mode doesn't use this home. The goal-store descriptor is a bind-mount point, which can't be renamed, so it was already safe.
  • Tests:
    • A unit test checks the ordering: baseline before handoff, and no root use of the home afterwards.
    • Another checks behaviour: a failed baseline drops only the run copy, and the host file is unchanged.
    • A new smoke case starts a node process that swaps agent for a symlink to the source. It asserts the swap happened and that the host auth.json and the source directory are unchanged.

F34 (umask on the whole Pi process)

  • The goal-mode umask 077 is gone, so the task keeps its normal umask.
  • The goal store is opened to node through group bits only (0770), never the "other" bits. If the store's group isn't one of node's groups, root first sets it to node's group, through the pinned descriptor. Afterwards it restores 0700 and the original group.
  • Session files are still made owner-only in the epilogue and again by the next run's prepare.
  • I updated the docs and the piGoalSession.ts comment to match.
  • Tests:
    • Unit tests check that worktree outputs keep normal modes (644/755) with and without a goal.
    • A killed run's session file is fixed to 600 by the next run's prepare.
    • The grant never uses the other bits.
    • The cross-UID smoke case checks the store's owner, group and mode during the run. The task creates a file and a nested directory in the worktree, and the worker UID then reads and lists them.

F35 (recovery hint pointed at the host store)

  • piCredentialRecoveryHint offers propr agent login pi --provider … only when its destination (HOST_PI_DIR, or ~/.pi/agent by default) is the store that was checked.
  • Otherwise it points to that agent's own login in Settings → Agents, by agent ID.
  • The local image check had the same wrong hint for a managed store, and it now uses this too.
  • The CLI test that asserted the old wrong hint now asserts the Settings hint. New cases check the host-dir agent (CLI hint) and the local check.

F36 (live MCP tool names)

  • The live parser now names tools with the same readablePiToolName as the stored parser, which is now exported from @propr/core.
  • The live-vs-stored comparison now runs on the scout and codemode fixtures too. It decodes the call IDs, which the live view stores URL-encoded (call_1%2F1).

F37 (duplicated result parsing)

  • parsePiAuthCheckResult and interpretPiAuthCheckResult now live in packages/shared/src/piAuthStore.ts, including the ANSI stripping. Both core's health check and the CLI use them.
  • Docker execution, CLI presentation and core's error messages stay where they were.
  • A new test runs colour-decorated output through core. That path had no ANSI stripping before.

No visual previews: none of these changes shows up in the UI.

Review digest

Risk-tiered paths

  • High risk (2 files)
    • packages/core/src/agents/impl/utils/piAuthCheck.ts (+15/−43): auth-looking path
    • packages/shared/src/piAuthStore.ts (+57/−0): auth-looking path
  • Normal risk (8 files)
    • packages/api/services/redisOutputParserPi.ts (+4/−1)
    • packages/cli/src/commands/agentValidation.ts (+24/−30)
    • packages/cli/src/commands/piConfiguredAgentCheck.ts (+16/−2)
    • packages/core/src/agents/impl/utils/piGoalSession.ts (+5/−4)
    • packages/core/src/index.ts (+1/−0)
    • packages/shared/src/index.ts (+4/−0)
    • scripts/pi-entrypoint.sh (+90/−52)
    • scripts/smoke-test-images.sh (+63/−7)
  • Low risk (5 files)
    • docs/docs/architecture/agent-runtime.md (+2/−2)
    • packages/api/test/liveDetailsPiParser.test.ts (+14/−2)
    • test/cliAgentValidation.test.ts (+19/−1)
    • test/piAuthCheck.test.ts (+18/−1)
    • test/piCredentials.test.ts (+105/−33)

Diff size: 15 files changed, +437/−178 lines


🤖 Implementation Details

  • Model: Claude Opus 5.5 (medium)
  • Requested By: @integry
  • Time: 16m 17s
  • Tokens: 10,607,354 (10,547,973 in / 59,381 out)
  • Cost: $4.24

Undo Changes • View Task Execution


💡 ProPR Slash Commands
Command Description Example
/merge Merge target branch into this PR and resolve conflicts /merge
/review Request an AI code review /review or /review claude-sonnet
/fix Address review blockers, or blockers and suggestions with /fix all /fix, /fix all, or /fix F3 S5
/switch Change the AI model for this PR /switch claude-opus
/use Override the model for a single follow-up run /use claude-sonnet
/ultrafix Loop review→fix cycles until score goal is met /ultrafix or /ultrafix goal=8 max=10

🤖 Generated by ProPR
Processing comment ID: 7245535517✓

All five findings (F33–F37) are fixed, each with a regression test. The two Docker smoke cases are written but I couldn't run them: this container has no Docker and no user namespaces, so they need the image CI. Every other related suite passes: the Pi entrypoint, credential, auth-check, goal-session, agent and scout suites, the post-task suite, CLI validation, the live/stored parser suites and the smoke-script structure tests. Typecheck is clean for shared, core, cli and api. ESLint is clean for the touched core and api files; the CLI files aren't covered by any ESLint config, so they weren't linted.

**F33 (root cleanup could delete host credentials)** – `scripts/pi-entrypoint.sh`
- The baseline read now runs as root inside `prepare_runtime_home`, before the handoff to `node`. So does removing a copy that has no baseline (new `record_seeded_auth`). Both act on root's own `0700` home in `/tmp`, which no `node` process can reach yet.
- The handoff is now the last step. It chowns the agent dir first and the home itself last, so `node` can't get inside while `chown` walks the tree.
- After the handoff, no root step names a path in the home. The "credentials imported" message now comes from root's recorded state, and the post-task read already ran as `node`.
- Audit result: as root the entrypoint now refuses any home other than `/tmp/propr-pi-home`. Any other location could sit under a `node`-writable parent. Production always uses the standard path, and login mode doesn't use this home. The goal-store descriptor is a bind-mount point, which can't be renamed, so it was already safe.
- Tests:
  - A unit test checks the ordering: baseline before handoff, and no root use of the home afterwards.
  - Another checks behaviour: a failed baseline drops only the run copy, and the host file is unchanged.
  - A new smoke case starts a `node` process that swaps `agent` for a symlink to the source. It asserts the swap happened and that the host `auth.json` and the source directory are unchanged.

**F34 (umask on the whole Pi process)**
- The goal-mode `umask 077` is gone, so the task keeps its normal umask.
- The goal store is opened to `node` through group bits only (`0770`), never the "other" bits. If the store's group isn't one of `node`'s groups, root first sets it to `node`'s group, through the pinned descriptor. Afterwards it restores `0700` and the original group.
- Session files are still made owner-only in the epilogue and again by the next run's prepare.
- I updated the docs and the `piGoalSession.ts` comment to match.
- Tests:
  - Unit tests check that worktree outputs keep normal modes (`644`/`755`) with and without a goal.
  - A killed run's session file is fixed to `600` by the next run's prepare.
  - The grant never uses the other bits.
  - The cross-UID smoke case checks the store's owner, group and mode during the run. The task creates a file and a nested directory in the worktree, and the worker UID then reads and lists them.

**F35 (recovery hint pointed at the host store)**
- `piCredentialRecoveryHint` offers `propr agent login pi --provider …` only when its destination (`HOST_PI_DIR`, or `~/.pi/agent` by default) is the store that was checked.
- Otherwise it points to that agent's own login in Settings → Agents, by agent ID.
- The local image check had the same wrong hint for a managed store, and it now uses this too.
- The CLI test that asserted the old wrong hint now asserts the Settings hint. New cases check the host-dir agent (CLI hint) and the local check.

**F36 (live MCP tool names)**
- The live parser now names tools with the same `readablePiToolName` as the stored parser, which is now exported from `@propr/core`.
- The live-vs-stored comparison now runs on the scout and codemode fixtures too. It decodes the call IDs, which the live view stores URL-encoded (`call_1%2F1`).

**F37 (duplicated result parsing)**
- `parsePiAuthCheckResult` and `interpretPiAuthCheckResult` now live in `packages/shared/src/piAuthStore.ts`, including the ANSI stripping. Both core's health check and the CLI use them.
- Docker execution, CLI presentation and core's error messages stay where they were.
- A new test runs colour-decorated output through core. That path had no ANSI stripping before.

No visual previews: none of these changes shows up in the UI.

PR: #3847
Comment by: @integry (ID: 7245535517)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5
@integry

integry commented Nov 28, 2026

Copy link
Copy Markdown
Owner

/review fable astra

@propr-dev

propr-dev Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor Author

✅ AI Code Review Complete requested by @integry

Posted 2 reviews:

View Task Details

@propr-dev

propr-dev Bot commented Nov 28, 2026

Copy link
Copy Markdown
Contributor Author

🔍 AI Code Review — fable

Overall Evaluation

This epic adds Pi 1.6.1 as a sixth agent across the image, entrypoint, task and analysis runs, live and stored parsing, settings UI, CLI, health check, diagnostics and goals. I reviewed it by static trace only (no commands were run) and found no verified merge blocker. Seven current-head checks are still pending, including all four test shards and Validate Changes, so merge readiness is conditional on them finishing green.

Three paths could not be confirmed from the supplied code and are worth a quick check before merge:

  • Goal-store cleanup from the API: whether the API container mounts the goal session store (S1).
  • Pi's --session-dir layout: whether real Pi writes session files directly into the directory, as findPiGoalSessionFile assumes. Only a stand-in Pi exercises this in the tests.
  • Pi on a private analysis workspace: whether Pi tolerates a 0700 workspace owned by another UID as its working directory (S3).

✅ Privileged steps are confined around the unprivileged task — scripts/pi-entrypoint.sh finishes every root step that names a path in the disposable home (imports, baseline read, baseline-less copy removal, mcp.json) while the home is still root-owned 0700. After the task it uses a fixed PATH, absolute binaries, cd /, and a write-back that goes only through the pinned source descriptor (fd 9), which is closed for every node process.

✅ Refresh write-back is narrow and fail-safe — scripts/pi-credentials.py merges only typed refresh fields into the current host entry under a per-entry compare-and-swap. It takes Pi's own lock with a bounded wait, refuses symlinked or oversized stores, and reports an unreadable post-run copy as a lost refresh instead of "nothing changed".

✅ Live and stored views are tested for parity on recorded traces — redisOutputParserPi.ts derives event IDs from toolCallId and message identity plus contentIndex. liveOutputPi.test.ts checks every retained-read start line of the fixtures against the uninterrupted projection, and liveDetailsPiParser.test.ts checks stored/live parity, including the 6UNoPXH4u edit call and a stream cut after text_end.

Merge blockers

No merge blockers.

Suggestions

These are optional follow-ups and are not sent to /fix.

S55: 🟢 Confirm goal-store cleanup from the API

goalRoutes.ts calls removePiGoalSessions in the API process, which removes /tmp/git-processor/pi-goal-sessions/<goal-id> with force: true. If the API container does not mount that path (I could not see its full volume list), the call succeeds silently and the worker-side store is never deleted. A check or test that the API and worker share the path, or moving the removal to the worker, would close this. It is optional here because I could not establish that the mount is missing.

S56: 🟢 Restricted-network allowlist covers fewer providers than the UI offers

PI_PROVIDERS offers Mistral, DeepSeek, xAI, Groq, Z.ai and OpenCode Zen in the settings UI and login dialog. AGENT_EGRESS_BASE_HOSTS.pi lists only Anthropic, OpenAI, OpenRouter, Gemini and Copilot hosts. With restricted networking, a Pi agent on one of the other providers fails until the operator adds the host. Either extend the base list or add a note in the agent dialog and docs. It is optional because operators can already extend the allowlist.

S57: 🟢 Analysis workspace readability for node

PiAgent.createAnalysisWorkspace uses fs.mkdtempSync, which creates a 0700 directory owned by the worker. When the worker is not UID 1000, Pi runs as node with a working directory it cannot search. Tool-less analysis probably tolerates this (context-file discovery just finds nothing), but I could not verify Pi's behaviour. A chmod 0755 on the empty directory would remove the doubt.

S58: 🟢 Session snapshot reports the un-normalized provider

resolveLoginOptions in agentLoginDocker.ts trims the provider but does not lowercase it, while buildAgentLoginCommand lowercases it for the command. A direct API caller sending OpenRouter gets a session whose provider field differs from the provider actually logged in to. Lowercasing in resolveLoginOptions would keep them equal. It is cosmetic because the UI and CLI already send lowercase.

S59: 🟢 Unrelated behaviour change in shared credential read

readCredentialContent in credentialRedaction.ts now throws for every provider when a credential file's size, mtime or ctime changes during the read. This fails closed and is reasonable, but it is not Pi-specific. A CLI token refresh during a diagnostics pass now refuses that pass for Claude, Codex and the others too. A note in the managed-diagnostics doc would help.

S60: 🟢 Documentation and comment drift

None of these affects behaviour:

  • CHANGELOG.md describes only the settings and operations part of the epic, not the agent, analysis, live view or goals.
  • PI_GOAL_SESSIONS_PATH and PI_ANALYSIS_ROOT are not in the configuration reference or .env.example.
  • agent-runtime.md says the source cannot overlap "another writable bind mount", but the code now refuses any task-readable mount.
  • A comment in test/piGoalSession.test.ts still mentions 0707.
  • piAuthStore.ts and pi-credentials.py point at agentLogin.ts for the refusal marker, which lives in piAuthStore.ts.
  • modelAliases.ts has a doc comment for piUnderlyingModel stranded above stripPiModelVariant.

S61: 🟢 Dev Compose creates ~/.pi/agent for everyone

docker-compose.yml now bind-mounts ${HOME}/.pi/agent into three services. For existing source installs that never use Pi, Docker creates the directory root-owned on the next start, which later breaks a host pi install. This matches the existing pattern for the other agents and the tutorials say to mkdir first. Moving the mount to an optional override file, as OpenCode does, would avoid the surprise.

S62: 🟢 Check the new EXTENSION_RUNTIMES import is used

The diff to packages/shared/src/automationDefinitions.ts shows only the import line changing. If the constant is not referenced elsewhere in the file, it is a dead import. I could not see the rest of the file.

Score

No verified code blocker in a large, security-sensitive change that carries regression tests for each prior fix round. The score assumes the seven pending checks complete green and is limited by this being a static review with the three unconfirmed paths named above.

Score: 8/10


🤖 Review Details

  • Model: Claude Fable 5.2
  • Time: 3m 19s
  • Tokens: 514,120 (494,945 in / 19,175 out)
  • Cost: $5.72

View Task


💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix S55 S56 S57 S58 S59 S60 S61 S62

🤖 Review by ProPR

@propr-dev

propr-dev Bot commented Nov 28, 2026

Copy link
Copy Markdown
Contributor Author

🔍 AI Code Review — astra

Overall Evaluation

PR #3847 integrates Pi 1.6.1 into the agent image, task execution, analysis, live output, settings, and goals. Changes are needed before merge. The supplied code shows cases where a saved agent checks the wrong provider, stored output loses tool evidence visible during the run, and goal resume accepts a session path that Pi cannot reopen.

✅ Image and version checks agree — The Dockerfile verifies the pinned version and required CLI flags. The build script includes Pi’s version and runtime scripts in the bundle identity.

✅ Scout tools are explicitly restricted — The scout disables built-in tools, loads builtin:mcp explicitly, and allowlists the repository tools. The supplied Pi fixture shows those three tools in the model’s tool list.

The review is partial. The issue descriptions and historical logs contain truncation notices, and 17 diff files were omitted, including PiAgent.ts, the credential helper, the entrypoint, and their tests. Credential write-back and checkpoint recovery could therefore only be assessed through their visible callers and fixtures. No commands were run. The supplied current-head status reports 30 passed, seven pending, ten neutral or skipped, and zero failed.

Merge blockers

Every finding below was introduced by this PR and must be resolved before merging.

F38: 🔴 API-key setup can save an unusable default

  • Category: correctness

  • Required behavior: A Pi agent created using provider API keys must have a default model that can use the selected credentials.

  • Evidence: propr-ui/src/pages/SettingsPage/AgentConfigModal.tsx:137, propr-ui/src/pages/SettingsPage/agentCredentialSetupUtils.ts:55, packages/api/services/agentHealthCheck.ts:16

    1. Select Pi in the new-agent dialog. The form selects the first catalog model, pi-anthropic/claude-opus-5-5, as the default.
    2. Choose Use API keys and enter only OPENROUTER_API_KEY. The form accepts any nonempty key with a matching variable-name suffix and saves the agent with an initially empty managed store. Adding an OpenRouter model also preserves the existing Anthropic default.
    3. The health check probes Anthropic. With only the entered OpenRouter key, the newly saved agent reports missing credentials and its default task cannot authenticate.

    static trace: propr-ui/src/pages/SettingsPage/PiAgentConfig.test.tsx exercises this exact save with only an OpenRouter key. It asserts that the key and added model survive, but never checks which provider the saved default uses.

  • Minimum fix: In new-agent API-key mode, require a key applicable to the default model or select a default model for the entered key. Extend the existing OpenRouter-only form test to assert that the saved default is usable.

F39: 🔴 Stored output drops retained tool results

  • Category: correctness

  • Required behavior: The stored Pi trace must preserve tool calls, results, and failure status when the retained output contains that evidence.

  • Evidence: packages/core/src/agents/impl/utils/piOutputParser.ts, PiOutputAccumulator.add, and packages/api/services/redisOutputParserPi.ts, processTurnEnd

    1. A retained Pi stream starts at turn_end after the earlier tool_execution_end and message_end copies have been trimmed. The remaining toolResults entry still identifies the call and carries its content and isError.
    2. The live parser reads toolResults and emits a paired call and result. Stored-format detection also recognizes the same record as Pi, but the core accumulator has no turn_end case.
    3. Opening the retained output through the stored-details route loses the result. If that was the only record, the parser returns no conversation at all.

    static trace: packages/api/test/liveOutputPi.test.ts covers retained copies for the live parser. The stored/live parity tests use complete tool fixtures or truncate after a text block, so they miss this divergence.

  • Minimum fix: Feed turn_end.toolResults through the stored accumulator’s existing call/result deduplication. Test a retained turn_end containing a failed tool result against both projection paths.

F40: 🔴 Goal resume follows session-file symlinks

  • Category: correctness

  • Required behavior: Goal resume must reopen the exact persisted conversation and fail if that conversation is unavailable.

  • Evidence: packages/core/src/agents/impl/utils/piGoalSession.ts, findPiGoalSessionFile and piGoalSessionCliArgs

    1. A goal’s writable session directory contains a matching <timestamp>_<id>.jsonl symlink whose target is a regular file on the worker outside the mounted directory.
    2. findPiGoalSessionFile follows the link with statSync and accepts it. The launcher gives Pi the link’s basename under the container mount.
    3. The target is absent in the container. The host-side existence check has therefore approved a missing conversation, precisely the condition preparePiGoalSession documents as causing Pi to start an empty session. A dangling matching link can also make statSync throw before a valid candidate is selected.

    static trace: The identifier check validates the goal and session IDs. It does not establish that the selected directory entry is itself a regular file.

  • Minimum fix: Select regular directory entries without following symlinks, for example with readdirSync(..., { withFileTypes: true }). Cover both a symlink-only store and a store containing a valid file alongside a dangling link.

F41: 🔴 Provider login defaults to an unsupported method

  • Category: correctness

  • Required behavior: Managed login must choose a method the resolved provider supports when the caller omits the method.

  • Evidence: packages/api/services/agentLoginDocker.ts, resolveLoginOptions, and packages/shared/src/agentLogin.ts, buildAgentLoginCommand

    1. Start login through the API for a Pi agent whose default model uses Google, without supplying login options.
    2. The API correctly derives google, but leaves apiKey unset. The command builder consequently emits pi auth login google --no-browser.
    3. The PR’s own provider catalog identifies Google as key-only, so this starts an account-login flow that cannot authenticate the configured provider. The browser dialog prevents that selection, but direct API callers and propr agent login pi --provider google bypass the dialog.

    static trace: packages/api/test/agentLoginPi.test.ts explicitly expects apiKey: false for the Google default. Its fake Docker child never attempts authentication. packages/cli/src/commands/agentValidation.ts, planAgentLogin, uses the same command builder.

  • Minimum fix: Resolve the default method for known key-only providers in shared login logic and use that resolved method in the API session snapshot and CLI command. Update the Google case to assert --api-key.

Suggestions

These are optional follow-ups and are not sent to /fix.

S63: 🟢 Share Pi record detection

liveDetailsStoredOutputFormat.ts maintains a second Pi event-name list alongside isPiRecord. The two already disagree on whether a bare message_end qualifies. Reusing the shape-aware predicate would simplify maintenance and make malformed-record handling consistent. This cleanup is independent of restoring valid retained results in F2.

S64: 🟢 Clarify host and managed login

The new Pi paragraph in docs/docs/tutorials/setup-local.md groups propr agent login <pi-agent> with ways to skip the host directory. The CLI takes the type pi and writes to HOST_PI_DIR or ~/.pi/agent. Showing propr agent login pi under host credentials and the Settings flow under managed credentials would make it easier for operators to locate the saved login.

Score

The image integration and scout restrictions have concrete coverage. Four localized defects remain in credential selection, login, stored traces, and session resume, including two cases where the new tests accept an unusable configuration.

Score: 6/10


🤖 Review Details

  • Model: GPT-6.2 Astra
  • Time: 1m 14s
  • Tokens: 199,651 (197,153 in / 2,498 out)
  • Cost: $1.57
  • Review scope: Partial — 17 files were omitted by the review context budget.

View Task

Files omitted from review diff

17 files were omitted from the review diff. Large, binary, generated, and lockfile changes are deprioritized.

Did not fit the review context budget

  • scripts/pi-credentials.py
  • test/cliAgentValidation.test.ts
  • scripts/pi-entrypoint.sh
  • test/fixtures/pi/pi-1.6.1-json-codemode-mcp.jsonl
  • test/piGoalSession.test.ts
  • packages/core/src/agents/impl/PiAgent.ts
  • test/piAgent.test.ts
  • test/piCredentials.test.ts
  • docs/docs/features/propr-cli.md
  • docs/docs/operations/configuration-reference.md
  • docs/docs/operations/settings-locations.md
  • docs/operations/managed-diagnostics.md
  • docs/docs/features/goals.md
  • docs/docs/features/agent-extensions.md
  • docs/docs/features/agents-and-models.md
  • packages/core/test/fixtures/pi-help-1.6.1.txt
  • docs/docs/architecture/agent-runtime.md

💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix F38 F39 F40 F41 S63 S64

🤖 Review by ProPR

@propr-dev propr-dev Bot changed the title ◕ 6/6 [Epic] Pi coding agent support ✅ 6/6 [Epic] Pi coding agent support Nov 28, 2026
@integry

integry commented Nov 28, 2026

Copy link
Copy Markdown
Owner

/fix F38 F39 F40 F41

All four are confirmed against a9fabf4. Small, narrow fixes, with a regression test each.

  • F40: findPiGoalSessionFile picks only regular files, without following symlinks (readdirSync(..., { withFileTypes: true }) / lstat), and a dangling link doesn't throw. Test a symlink-only store, and a valid file next to a dangling link.
  • F39: feed turn_end.toolResults through the stored accumulator's existing call/result deduplication. Test a retained stream starting at turn_end with a failed tool result, through both the live and stored paths.
  • F38: in new-agent API-key mode, the saved default model must match a provider whose key was entered. Pick the first model for the entered key's provider, or require a matching key. Extend the OpenRouter-only form test to check the saved default.
  • F41: resolve the default login method for known key-only providers (e.g. google) in the shared login logic, and use it in the API login session and propr agent login pi --provider, so they send --api-key. Update the Google case.

@propr-dev propr-dev Bot changed the title ✅ 6/6 [Epic] Pi coding agent support ◕ 6/6 [Epic] Pi coding agent support Nov 28, 2026
@propr-dev

propr-dev Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor Author

✅ Applied the requested follow-up changes in commit 9900bc8

Addressed 1 AI review comment (IDs: 7245932510)

Addressed findings F38, F39, F40, F41

Summary of Changes

I fixed all four findings, each with a regression test. 197 tests pass across the affected Pi, login, CLI, live-view and stored-output files, plus all 413 UI tests in the Settings page folder. Typecheck and zero-warning lint are clean on the changed files.

F40: goal resume follows symlinks. findPiGoalSessionFile now lists the directory with readdirSync(..., { withFileTypes: true }) and keeps only entries that are themselves regular files. Symlinks are never followed, so a dangling link can't throw. Two new tests in test/piGoalSession.test.ts:

  • A store holding only a symlink to a real file outside it: nothing is found, and the resume fails with the "missing" error.
  • A valid file next to a dangling link that sorts after it: the valid file is resumed. The old code would have thrown here.

F39: stored output drops retained tool results. The stored parser (PiOutputAccumulator) now handles turn_end. Each toolResults entry goes through the same addToolResult deduplication as the other copies: it announces the call if needed, keeps isError, and uses the result's own timestamp. Two new parity tests in packages/api/test/liveDetailsPiParser.test.ts:

  • A stream that starts at turn_end with a failed result: the live and stored views both show the call and the failed result, with its content.
  • A full sequence ending in turn_end: still exactly one result.

I also moved the session case into its own method, because the new case pushed add over the lint complexity limit.

F41: login defaults to an unsupported method.

  • Shared logic: a new isPiKeyOnlyProvider (a known provider without account login) and a new resolveAgentLoginOptions in packages/shared. When a known key-only provider is chosen, the method defaults to --api-key, and buildAgentLoginCommand uses this.
  • API: resolveLoginOptions returns the resolved options, so the session reports the method the command actually uses.
  • CLI: propr agent login pi --provider google gets --api-key from the same builder, and its help text says so.

Tests: the API Google case now expects apiKey: true and checks the docker command ends in google --api-key. The builder and planAgentLogin tests cover google, plus a provider outside the catalog that keeps --no-browser.

One behaviour to know: a key-only provider always uses --api-key, even if a caller explicitly asks for account login. The route, UI and CLI only ever send apiKey: true or nothing, so in practice this only applies when the method is omitted.

F38: API-key setup saves an unusable default. A new Pi agent in API-key mode now saves a default model that the entered keys can use:

  • It keeps the chosen default if that provider's key was entered; otherwise it picks the first selected model whose provider has a key.
  • If no selected model fits the entered keys, the form refuses to save with an error message.
  • A provider outside the catalog counts as covered by any entered *_API_KEY/*_TOKEN, since ProPR doesn't know which variable Pi reads for it.

The OpenRouter-only form test now asserts the saved default is pi-openrouter/mistralai/devstral-2512. That assertion fails on the old code, which saved the Anthropic default. New tests cover the refusal and the default-selection helper.

I checked the sibling setup paths in the CLI and local setup, and none of them choose a default model for API-key setup, so nothing else needed this fix. I didn't capture previews: the visible change is only a new error message in the form's existing error area.

Review digest

Risk-tiered paths

  • High risk (3 files)
    • packages/api/services/agentLoginDocker.ts (+6/−2): auth-looking path
    • packages/shared/src/agentLogin.ts (+21/−3): auth-looking path
    • propr-ui/src/pages/SettingsPage/agentCredentialSetupUtils.ts (+20/−0): auth-looking path
  • Normal risk (7 files)
    • packages/cli/src/commands/agentCommands.ts (+3/−2)
    • packages/core/src/agents/impl/utils/piGoalSession.ts (+10/−3)
    • packages/core/src/agents/impl/utils/piOutputParser.ts (+26/−2)
    • packages/shared/src/index.ts (+2/−0)
    • packages/shared/src/piProviders.ts (+9/−0)
    • propr-ui/src/pages/SettingsPage/AgentConfigModal.tsx (+2/−1)
    • propr-ui/src/pages/SettingsPage/piAgentFieldsUtils.ts (+30/−1)
  • Low risk (5 files)
    • packages/api/test/agentLoginPi.test.ts (+9/−3)
    • packages/api/test/liveDetailsPiParser.test.ts (+30/−0)
    • propr-ui/src/pages/SettingsPage/PiAgentConfig.test.tsx (+34/−1)
    • test/cliAgentValidation.test.ts (+3/−0)
    • test/piGoalSession.test.ts (+25/−0)

Diff size: 15 files changed, +230/−18 lines


🤖 Implementation Details

  • Model: Claude Opus 5.5 (medium)
  • Requested By: @integry
  • Time: 11m 5s
  • Tokens: 6,005,920 (5,979,700 in / 26,220 out)
  • Cost: $2.32
  • Subscription usage: Weekly +1%, Fable +1%

Undo Changes • View Task Execution


💡 ProPR Slash Commands
Command Description Example
/merge Merge target branch into this PR and resolve conflicts /merge
/review Request an AI code review /review or /review claude-sonnet
/fix Address review blockers, or blockers and suggestions with /fix all /fix, /fix all, or /fix F3 S5
/switch Change the AI model for this PR /switch claude-opus
/use Override the model for a single follow-up run /use claude-sonnet
/ultrafix Loop review→fix cycles until score goal is met /ultrafix or /ultrafix goal=8 max=10

🤖 Generated by ProPR
Processing comment ID: 7246105267✓

I fixed all four findings, each with a regression test. 197 tests pass across the affected Pi, login, CLI, live-view and stored-output files, plus all 413 UI tests in the Settings page folder. Typecheck and zero-warning lint are clean on the changed files.

**F40: goal resume follows symlinks.** `findPiGoalSessionFile` now lists the directory with `readdirSync(..., { withFileTypes: true })` and keeps only entries that are themselves regular files. Symlinks are never followed, so a dangling link can't throw. Two new tests in `test/piGoalSession.test.ts`:
- A store holding only a symlink to a real file outside it: nothing is found, and the resume fails with the "missing" error.
- A valid file next to a dangling link that sorts after it: the valid file is resumed. The old code would have thrown here.

**F39: stored output drops retained tool results.** The stored parser (`PiOutputAccumulator`) now handles `turn_end`. Each `toolResults` entry goes through the same `addToolResult` deduplication as the other copies: it announces the call if needed, keeps `isError`, and uses the result's own timestamp. Two new parity tests in `packages/api/test/liveDetailsPiParser.test.ts`:
- A stream that starts at `turn_end` with a failed result: the live and stored views both show the call and the failed result, with its content.
- A full sequence ending in `turn_end`: still exactly one result.

I also moved the session case into its own method, because the new case pushed `add` over the lint complexity limit.

**F41: login defaults to an unsupported method.**
- **Shared logic:** a new `isPiKeyOnlyProvider` (a known provider without account login) and a new `resolveAgentLoginOptions` in `packages/shared`. When a known key-only provider is chosen, the method defaults to `--api-key`, and `buildAgentLoginCommand` uses this.
- **API:** `resolveLoginOptions` returns the resolved options, so the session reports the method the command actually uses.
- **CLI:** `propr agent login pi --provider google` gets `--api-key` from the same builder, and its help text says so.

Tests: the API Google case now expects `apiKey: true` and checks the docker command ends in `google --api-key`. The builder and `planAgentLogin` tests cover `google`, plus a provider outside the catalog that keeps `--no-browser`.

One behaviour to know: a key-only provider always uses `--api-key`, even if a caller explicitly asks for account login. The route, UI and CLI only ever send `apiKey: true` or nothing, so in practice this only applies when the method is omitted.

**F38: API-key setup saves an unusable default.** A new Pi agent in API-key mode now saves a default model that the entered keys can use:
- It keeps the chosen default if that provider's key was entered; otherwise it picks the first selected model whose provider has a key.
- If no selected model fits the entered keys, the form refuses to save with an error message.
- A provider outside the catalog counts as covered by any entered `*_API_KEY`/`*_TOKEN`, since ProPR doesn't know which variable Pi reads for it.

The OpenRouter-only form test now asserts the saved default is `pi-openrouter/mistralai/devstral-2512`. That assertion fails on the old code, which saved the Anthropic default. New tests cover the refusal and the default-selection helper.

I checked the sibling setup paths in the CLI and local setup, and none of them choose a default model for API-key setup, so nothing else needed this fix. I didn't capture previews: the visible change is only a new error message in the form's existing error area.

PR: #3847
Comment by: @integry (ID: 7246105267)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5
@integry

integry commented Nov 28, 2026

Copy link
Copy Markdown
Owner

/review fable astra

@propr-dev

propr-dev Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor Author

✅ AI Code Review Complete requested by @integry

Posted 2 reviews:

View Task Details

@propr-dev

propr-dev Bot commented Nov 28, 2026

Copy link
Copy Markdown
Contributor Author

🔍 AI Code Review — fable

Overall Evaluation

This epic adds Pi as a sixth coding agent: image stage and entrypoint, credential import and write-back, PiAgent task/analysis/goal execution, live and stored parsers, settings UI, CLI, managed login, health check, diagnostics and docs. I traced the changed paths statically against the diff and found no failure I could drive from a reachable trigger to an incorrect outcome, so I have no blockers. Nothing was executed, and readiness is conditional on the 10 pending head checks, including Validate Changes and the four test shards.

Three limits on this pass:

  • Several helpers the diff relies on are not in the supplied context (baseArgs, supportedCapability, MODEL_ALIASES construction, check_version in the preview smoke script, executeDockerCommand's handling of extraEnvVars). I took their behaviour from the accompanying tests.
  • The objective text for Pi: install the CLI in the agent image with a disposable runtime and safe credential handling #3831–Pi: goal support with session resume #3836 is truncated, so I could not check the cut-off acceptance criteria.
  • The zero-warning lint gate was not run. PiAgent.executeTaskWithoutExtensions and PiAgent.analyze look close to the complexity limit of 20 that earlier rounds tripped, so the pending Validate Changes result is the one to watch.

✅ Root steps finish before the disposable home is handed to node — prepare_runtime_home in scripts/pi-entrypoint.sh creates /tmp/propr-pi-home as root 0700, runs every import, the baseline read and the no-baseline removal there, and only then chowns it. Post-task steps use a fixed PATH, absolute binaries and cd /, and the source and goal-store descriptors are closed for every node process.

✅ Write-back is a per-entry compare-and-swap limited to refresh fields — refreshed_entries / write_refreshes in scripts/pi-credentials.py merge only typed token fields into a host entry that still equals the seed. The lock wait is bounded, the result must stay importable, and an unreadable post-run copy is reported rather than treated as "nothing changed".

✅ Live event IDs do not depend on where a read starts — redisOutputParserPi.ts keys tool events by toolCallId and blocks by message identity plus contentIndex. liveOutputPi.test.ts checks this for every start line of three streams, and liveDetailsPiParser.test.ts checks live/stored parity.

Merge blockers

No merge blockers.

Suggestions

These are optional follow-ups and are not sent to /fix.

S65: 🟢 Check Pi shortAlias collisions

PI_MODELS in packages/shared/src/modelDefinitions.ts reuses bare short aliases such as opus55 and sonnet55, and ALL_MODELS now appends Pi last. A comment in modelAliases.ts says agents can be configured with bare aliases like opus55. If MODEL_ALIASES maps bare short aliases with last-wins, opus55 would now resolve to pi-anthropic/claude-opus-5-5. I could not see how that map is built, so this is a check, not a demonstrated bug. Asserting resolveModelAlias('opus55') still returns the Claude id would settle it.

S66: 🟢 Tighten bare Pi event types in format detection

isPiRecord accepts turn_start, turn_end, agent_start and similar on the type name alone. isPiJsonLine runs before the Vibe transcript scan in parseRedisOutput and LiveOutputProjector, and before every other format in detectStoredOutputFormat. Any other runtime that emits a line starting {"type":"turn_start" would be classified as Pi. The added negative tests cover only a handful of shapes. Requiring the Pi session header, or a Pi-specific payload for those bare types, would make the routing robust.

S67: 🟢 Unused EXTENSION_RUNTIMES import

packages/shared/src/automationDefinitions.ts changes only its import line to add EXTENSION_RUNTIMES, and nothing else in the file changes. It looks like a stray import and would fail the build if noUnusedLocals is on for that package.

S68: 🟢 Docs overstate propr agent login for Pi

docs/docs/features/agents-and-models.md and setup-local.md say propr agent login <pi-agent> --provider … "does the same" as the managed Web login. The CLI takes an agent type and writes to HOST_PI_DIR or ~/.pi/agent, which piCredentialRecoveryHint itself accounts for. The docs should say the CLI login targets the host Pi dir.

S69: 🟢 Goal session cleanup runs in the API process

goalRoutes.ts calls removePiGoalSessions from the API, while the worker creates the store under /tmp/git-processor/pi-goal-sessions. If the API container does not mount that path, or runs as another user, deletion silently does nothing (force: true) and session files stay on the host. I could not confirm the API's mounts from the supplied context.

S70: 🟢 Offered providers exceed the egress allowlist

PI_PROVIDERS offers Mistral, DeepSeek, xAI, Groq, Z.ai and OpenCode Zen in the UI. AGENT_EGRESS_BASE_HOSTS.pi covers only Anthropic, OpenAI, OpenRouter, Gemini and Copilot. With restricted networking on, a model from the other providers fails until an administrator adds the host. A hint in the model picker or the docs would help.

S71: 🟢 Dev Compose now always mounts ~/.pi/agent

docker-compose.yml binds ${HOME}/.pi/agent in all three backend services. For existing users who never ran mkdir -p ~/.pi/agent, Docker creates ~/.pi root-owned, which later breaks a host pi install. This matches the existing .vibe pattern; an upgrade note would be enough.

S72: 🟢 Record real-CLI evidence for --no-skills with --skill

piToolPolicyArgs passes --no-skills together with explicit --skill <path> flags. Pi's help says explicit paths still work for --no-extensions but says nothing equivalent for --no-skills. The existing fixtures do not cover a staged skill bundle under an exclusive policy; a recorded Pi 1.6.1 run would close the gap.

Score

No verified blocker after tracing the credential, entrypoint, parser, goal and UI paths, and the changed behaviour is heavily tested. Merge readiness is conditional on the pending head checks completing green, the lint gate in particular.

Score: 8/10


🤖 Review Details

  • Model: Claude Fable 5.2
  • Time: 4m 40s
  • Tokens: 530,053 (502,537 in / 27,516 out)
  • Cost: $6.13

View Task


💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix S65 S66 S67 S68 S69 S70 S71 S72

🤖 Review by ProPR

@propr-dev

propr-dev Bot commented Nov 28, 2026

Copy link
Copy Markdown
Contributor Author

🔍 AI Code Review — astra

Overall Evaluation

PR #3847 integrates Pi 1.6.1 across the agent image, task execution, analysis, goal sessions, settings, and live output. It needs changes before merge. A retained Pi trace can lose an entire assistant response, and a successful goal deletion can leave its conversation on disk.

✅ Pinned runtime — The Docker build checks Pi’s exact version and all eight required help flags. Both bundle-content lists include the entrypoint and credential helper.

✅ Credential checks match task configuration — The stack health check selects the default model’s provider, forwards configured keys by environment-variable name, and runs with a read-only credential mount, --network none, and --no-refresh.

This was a static review. The supplied diff omits 24 files, including PiAgent.ts, the entrypoint, the credential helper, and their principal tests. The issue descriptions and historical logs are also truncated, which limits verification of credential write-back and checkpoint resume. The supplied current-head status reports 26 passed, 10 pending, 10 neutral or skipped, and zero failed.

Merge blockers

Every finding below was introduced by this PR and must be resolved before merging.

F42: 🔴 Recover assistant responses from retained records

  • Category: correctness

  • Required behavior: Live and stored Pi views must preserve assistant text, thinking, tool calls, and usage when the retained output still contains the response.

  • Evidence: packages/api/services/redisOutputParserPi.ts, processTurnEnd and processPiRecord, and packages/core/src/agents/impl/utils/piOutputParser.ts, PiOutputAccumulator.add

    static trace:

    1. Start a retained read at the final turn_end in test/fixtures/pi/pi-1.6.1-json-scout-mcp.jsonl. That record contains the complete assistant answer FINAL ANSWER and its usage. The following agent_end.messages contains another copy.
    2. Both parsers inspect only toolResults on turn_end. This turn has none. Both also skip the messages on agent_end.
    3. The live projection emits no answer or usage. The stored parser produces an empty conversation log even though the answer is present twice in the retained bytes.

    The retention tests in packages/api/test/liveOutputPi.test.ts check that emitted events have valid, stable IDs. An empty projection satisfies that check.

  • Minimum fix: Recover missing assistant messages from turn_end.message and, when it is the surviving copy, agent_end.messages. Deduplicate against already processed messages so full reads count usage once. Assert the answer and usage for reads beginning at each of those records.

F43: 🔴 Keep failed goal cleanup retryable

  • Category: correctness

  • Required behavior: Issue Pi: goal support with session resume #3836 requires persisted Pi session files to be cleaned up with their goal.

  • Evidence: packages/api/routes/goalRoutes.ts:1087 and packages/core/src/agents/impl/utils/piGoalSession.ts, removePiGoalSessions

    static trace:

    1. Delete a Pi goal whose session directory the API process cannot remove. The session-store helper explicitly handles EACCES and EPERM, including the case where the store belongs to another worker UID.
    2. After deleting the goal row, the route awaits session removal, catches the failure, and writes a warning.
    3. The route returns HTTP 204. The conversation remains on disk, and the deleted goal can no longer be used to retry cleanup through the same request.

    The helper provides an actionable filesystem error, but the route discards it as a completion condition and records no retry obligation.

  • Minimum fix: Keep cleanup retryable across a failed removal. Either retain a deletable goal until cleanup succeeds or durably record pending cleanup when deleting the row. Test a denied removal followed by a successful retry.

F44: 🔴 Preserve tool-result timestamps in live replay

  • Category: correctness

  • Required behavior: A retained tool result with its own timestamp should identify the same execution time in live and stored details.

  • Evidence: packages/api/services/redisOutputParserPi.ts, processTurnEnd, and packages/core/src/agents/impl/utils/piOutputParser.ts, addTurnToolResults

    static trace:

    1. Read a retained stream beginning at turn_end with a timed tool result, as in packages/api/test/liveDetailsPiParser.test.ts.
    2. The stored parser calls timestampOf(message, this.lastTimestamp) and preserves the result’s timestamp. The live parser passes the outer fallback timestamp to every result in the turn, ignoring each result’s timestamp.
    3. The same call ID consequently acquires a different time in live replay and stored details. Multiple results with distinct completion times can all display the same time.

    The parity test compares IDs and error flags, then checks the timestamp only on the stored result.

  • Minimum fix: Use each result’s own valid timestamp in processTurnEnd, falling back to the outer time only when needed. Extend the existing parity test to assert the live timestamp as well.

F45: 🔴 Use one Pi record discriminator

  • Category: complexity

  • Required behavior: Stored-output detection adds a duplicate of the Pi record classifier required for live routing, with conflicting acceptance rules.

  • Evidence: packages/api/routes/liveDetailsStoredOutputFormat.ts, PI_STORED_OUTPUT_TYPES and isPiStoredOutputLine, and packages/api/services/redisOutputParserPi.ts, isPiRecord

    static trace:

    1. Give both detection paths {"type":"tool_execution_end"}. The shared live predicate rejects it because it has no toolCallId, as explicitly asserted in test/redisOutputParser.test.ts.
    2. Stored detection first tries isPiJsonLine, which rejects it for the same reason. Its subsequent getImmediateStoredOutputFormat path then accepts the identical record solely because its type is in a second set.
    3. Stored details select the Pi parser on a record that the Pi parser cannot project. The same disagreement exists for a bare message_end.

    The second classifier adds no necessary parsing capability. The already-parsed object can go directly to isPiRecord.

  • Minimum fix: Replace isPiStoredOutputLine and its duplicate type set with isPiRecord(parsed). Assert that incomplete records alone do not select Pi in stored detection.

Suggestions

These are optional follow-ups and are not sent to /fix.

S73: 🟢 Explain restricted-network provider coverage

The settings picker offers providers including Mistral, DeepSeek, and Groq, while the Pi base egress list covers a smaller set. A brief hint beside provider selection could tell restricted-network operators when a deployment allowlist entry is needed. This is optional because the curated default models already use providers covered by the base list.

Score

The image and health-check integration are well supported by the visible code. Lost replay data and non-retryable session cleanup affect requested behavior directly and warrant correction before merge.

Score: 6/10


🤖 Review Details

  • Model: GPT-6.2 Astra
  • Time: 1m 1s
  • Tokens: 200,115 (197,928 in / 2,187 out)
  • Cost: $1.57
  • Review scope: Partial — 24 files were omitted by the review context budget.

View Task

Files omitted from review diff

24 files were omitted from the review diff. Large, binary, generated, and lockfile changes are deprioritized.

Did not fit the review context budget

  • scripts/pi-credentials.py
  • scripts/pi-entrypoint.sh
  • test/cliAgentValidation.test.ts
  • test/fixtures/pi/pi-1.6.1-json-codemode-mcp.jsonl
  • packages/core/src/agents/impl/PiAgent.ts
  • test/piGoalSession.test.ts
  • test/piAgent.test.ts
  • test/piCredentials.test.ts
  • docs/docs/tutorials/setup-server.md
  • CHANGELOG.md
  • docs/docs/operations/deployment.md
  • docs/docs/tutorials/setup.md
  • packages/cli/README.md
  • docs/operations/native-provider-log-policy.md
  • docs/docs/tutorials/setup-local.md
  • docs/docs/features/propr-cli.md
  • docs/docs/operations/configuration-reference.md
  • docs/docs/operations/settings-locations.md
  • docs/operations/managed-diagnostics.md
  • docs/docs/features/goals.md
  • docs/docs/features/agent-extensions.md
  • docs/docs/features/agents-and-models.md
  • packages/core/test/fixtures/pi-help-1.6.1.txt
  • docs/docs/architecture/agent-runtime.md

💡 Next step: Comment /fix to address every F# merge blocker, /fix all for every pending blocker and suggestion, or name records explicitly, as in /fix F3 S5.
F# and S# IDs increment across review comments and remain permanent, so selectors such as /fix F3 F5 stay unambiguous across cycles. S# suggestions stay optional: they are implemented only when you name them or request /fix all, and they never relax a merge blocker.

Copy and edit to choose records from this review:

/fix F42 F43 F44 F45 S73

🤖 Review by ProPR

@propr-dev propr-dev Bot changed the title ◕ 6/6 [Epic] Pi coding agent support ✅ 6/6 [Epic] Pi coding agent support Nov 28, 2026
@integry
integry merged commit 2f816a7 into main Nov 28, 2026
51 checks passed
@propr-dev propr-dev Bot changed the title ✅ 6/6 [Epic] Pi coding agent support [Epic] Pi coding agent support Nov 28, 2026
@propr-dev

propr-dev Bot commented Nov 28, 2026

Copy link
Copy Markdown
Contributor Author

✅ Epic merged: Pi coding agent support

Epic PR #3847 has been merged into main.

6 of 6 issues merged into main through this epic PR.

All planned epic work is now merged.

Posted automatically by ProPR

@integry
integry deleted the 3831-epic-pi-coding-jml branch November 28, 2026 22:21
propr-dev Bot pushed a commit that referenced this pull request Nov 28, 2026
I fixed the Shard 1/4 failure. The only failing file was `test/agentRunSpecStartsAsRoot.test.ts`, which now passes locally (10/10). I didn't run the rest of the shard or the other shards.

**Cause:** the merge from main (#3847) brought in the new Pi agent type. This test requires every agent type to supply an `AgentRunSpec` (the structured run description from this epic), and Pi doesn't build one on this branch. It still assembles a raw `docker run` argument list and only runs on local Docker. So two tests failed: "every agent type has a task spec case", and the `pi` iteration, which had no spec builder to call.

**Fix (test only, no source changes):** in `test/agentRunSpecStartsAsRoot.test.ts`:
- Pi is now listed as one of the agent types that still build raw Docker arguments. The coverage check counts those types plus the ones with specs, so a new agent type added without a case still fails it.
- A new Pi test checks:
  - its task arguments start as root (`--user 0:0`, before the image).
  - they don't drop the CHOWN capability.
  - they include the setup wrapper (`--entrypoint /bin/bash`).
- The same test checks that Fly Machines and Sprites refuse Pi. Those are the runtimes where the clone root check matters, so this stays enforced: if either one ever accepts Pi before Pi builds a proper spec, the test fails.

Moving Pi onto `AgentRunSpec` properly would be a bigger change than this request, so I left it out. That's why Pi is tested on its raw arguments for now. Nothing visible changed, so there are no previews.

PR: #3774
Comment by: @propr-dev[bot] (ID: 7247150384)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5
propr-dev Bot pushed a commit that referenced this pull request Nov 28, 2026
I fixed the shard 4 failure, and the test now passes locally (10/10 subtests).

**Cause:** in run 46198702192 the only failing file was `test/agentRunSpecStartsAsRoot.test.ts`. That test was added in #3853 and has to cover every agent type. The `pi` agent type, added in #3847, landed on this branch through the epic merges, and nobody added a `pi` case to the test. So two subtests failed:
- "every agent type has a task spec case" failed because the list had no `pi`.
- "pi: the task spec starts as root…" crashed because the `pi` case didn't exist.

**Fix (test only, in `test/agentRunSpecStartsAsRoot.test.ts`):** Pi doesn't build a run spec at all. It starts its own `docker run --user 0:0`, so it can't run on Fly Machines or Sprites and the remote-runtime "starts as root" check doesn't apply to it. I split Pi out as a Docker-only agent type:
- The existing run-spec checks now cover every type except `pi`.
- Pi gets its own case that builds its real task Docker arguments and checks that they start as root.
- The coverage check still requires every agent type to appear in one list or the other, so a new agent type fails until someone adds a case for it.

The earlier comment about `test/spritesLeaseProvisioning.test.ts` timing out at 180s came from an older run. In this run it didn't fail, and it passes locally in about 4s. I made no change for it; if it shows up again, it's most likely runner contention rather than code.

This is a test-only change with nothing to see on screen, so there are no previews.

PR: #3865
Comment by: @propr-dev[bot] (ID: 7247259883)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5
integry pushed a commit that referenced this pull request Nov 29, 2026
… paste credentials + interactive login on the remote runtime (#3865)

* feat: add pasted agent credentials and remote-runtime login

I've implemented all three parts of #3863, but none of the live acceptance runs on a Fly-launched instance have happened, so there are no run links for the PR yet. The new tests pass: 311 server-side tests across the touched suites and 12 UI tests. Typecheck, lint (zero warnings) and the OpenAPI check are clean.

1. Pasted credentials (works on every runtime, including Docker)
- The agent dialog has a third setup option, Paste a key or token. Editing a saved agent shows the same section.
- Claude: an Anthropic API key or a `claude setup-token` token. Either goes into `settings.json` under `env` as `ANTHROPIC_API_KEY` or `CLAUDE_CODE_OAUTH_TOKEN`. Saving one removes the other, and other settings are kept.
- Codex: an OpenAI API key, written to `auth.json` the way `codex login --with-api-key` does it, or a pasted `auth.json`.
- OpenCode: a pasted `auth.json`, stored in its data directory.
- Each option links to where the key or token comes from.
- Values are write-only. The dialog and the new `GET/PUT/DELETE /api/agents/:id/credentials` endpoints only report "set" plus the last 4 characters. Remove deletes a value.
- Files are written atomically with mode 0600, under the same store lock the runs use.
- I added redaction patterns for these key formats and for secrets inside the JSON files, with a case in `test/redactSecrets.test.ts`.
- Vibe keeps its existing Mistral key field, which the API already redacts. I didn't touch the stores #3853 changes.

2. Interactive login on the remote runtime
- This applies when the agent runs on Sprites or Fly Machines and there's no local Docker. "No Docker" means neither `DOCKER_HOST` nor `/var/run/docker.sock` is present.
- Sprites: the login takes a Sprite from the normal pool, so it counts against `PROPR_SPRITES_MAX`. It runs the login CLI with a TTY, and the Sprite is always deleted afterwards, never returned to the pool.
- Fly Machines: the login starts a short-lived `propr-login-*` Machine from `PROPR_FLY_IMAGE`, holding a `PROPR_FLY_MACHINES_MAX` slot. Fly's API has no interactive console, so output and keystrokes go through its exec API, polled about once a second. If ProPR crashes, the Machine ends the CLI and destroys itself.
- On success, the login files the provider manifest declares are copied into the agent's credential store, then the Sprite or Machine is destroyed.
- If no slot frees up within 30 seconds, or Fly's organization machine limit is hit, the login fails with a message naming the cap.
- Provisioning a new Sprite takes a few minutes. The dialog streams progress meanwhile.

3. Health check by runtime
- For agents on Sprites or Fly Machines, the check no longer touches a local Docker image or starts a test run. It checks three things: the runtime token is accepted, the CLI version (Sprites) or agent image (Fly) resolves, and the agent has a stored credential.
- Failures now show Agent runtime unavailable or an auth error, never "Agent image preparation failed".
- Docker instances behave as before.

Things to know
- The API process needs `PROPR_SPRITES_TOKEN` or the `PROPR_FLY_*` variables. They're already shared on a `propr deploy fly` instance, since the API and worker run in the same container.
- Interactive login on Sprites covers the agents Sprites runs today (Claude, Codex, Antigravity). OpenCode becomes available there once #3853 adds it.
- To stay under the file-length limit, I moved the terminal-output sanitizer, the Docker helpers and the login routes into separate files. The OpenAPI spec was regenerated.

Docs: `setup-fly.md` has a new "Agent credentials" section. `agents-and-models.md` describes pasting credentials and interactive login without Docker.

Still needed before merge: the live runs on a Fly-launched instance — (a) an `AI` issue to a PR with a pasted key on both Sprites and Fly Machines, (b) the interactive Claude login on Sprites followed by a run, and (c) a healthy agent card. Previews of the dialog and agent cards were taken against a mocked API.

ProPR-Agent: claude/claude-opus-5-5

* chore: move Docker process helpers out of agentLoginDocker

I fixed the Shard 2/4 failure; it was caused by this PR's code, not by flakiness. The failing test file now passes.

**Cause:** `test/agentRoutesOpenCodeDiscovery.test.ts` replaces `child_process` with a mock that only provides `execFile`. This PR gave `agentRoutes` a new import chain: `agentCredentialStore` → `agentLoginDocker.ts`. When I moved the Docker helpers into `agentLoginDocker.ts`, that file started importing `spawn` from `node:child_process`. Under the mock, `spawn` doesn't exist, so the test file failed to load:

```
SyntaxError: The requested module 'node:child_process' does not provide an export named 'spawn'
```

**Fix:** I changed the source rather than adding `spawn` to the test's mock.
- `defaultRunDocker`, `defaultSpawnDocker` and `DockerCommandResult` now live in a new file, `packages/api/services/agentLoginDockerProcess.ts`.
- `agentLoginDocker.ts` no longer imports `child_process`. It keeps only the path and image resolution, which is all the credential store needs.
- `agentLoginSessionManager.ts` imports the Docker helpers from the new file. Its exports are unchanged.

**Checks run:**
- `agentRoutesOpenCodeDiscovery`, `remoteAgentLogin` and `agentRemoteCredentials`: all pass.
- The six other suites that touch agent login: all pass, including `agentLoginRoutes`, `routeAuthorization` and `agentDefaultConfigPaths`.
- `tsc` for `packages/api` and zero-warning ESLint on the three changed files: clean.

I didn't rerun the full shard locally. There's no visual change, so I didn't make previews.

PR: #3865
Comment by: @propr-dev[bot] (ID: 7230494503)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* chore: harden agent credential writes and runtime readiness checks

I fixed all four findings (F1–F4) and added a regression test for each. I put the HEAD versions of the API services back temporarily, and the new F1, F2 and F3 tests failed against them. With the fixes, the touched suites pass: 17 core tests and 61 API tests. Typecheck and lint pass with zero warnings.

**F1: credential edits now read and merge inside the lock**
- `writeCredentialStoreFiles` (`credentialStoreWriter.ts`) now also accepts a function that computes the files to write. It runs while holding the store lock, and the symlink and size checks run there too.
- `rewrite` in `agentCredentialStore.ts` now reads `settings.json` and merges into it inside that function, so a PUT and a DELETE that overlap each build on the other's result.
- `storeReturnedLoginFiles` writes whole login files and doesn't merge, so it didn't have this bug.
- **Tests:** a core test runs two overlapping merges. An API test makes a real PUT (swap the API key for an OAuth token) and DELETE (remove the API key) wait on a busy lock at the same time. The result keeps the new token, removes the key, and keeps an unrelated `model` setting.

**F2: a cancelled login can no longer save credentials**
- The writer takes an optional cancellation signal. It checks it before waiting for the lock, and again inside the lock just before writing.
- That signal is the one cancel and timeout already abort. It now reaches the writer through the session manager, `collectRemoteLoginFiles` and `storeReturnedLoginFiles`. Collection also checks it between file reads.
- For OpenCode, which writes to two stores, the check runs under each store's lock.
- After collection, `runRemoteLoginSession` checks whether the session has already ended. If so, it reports neither "Saved…" nor "Could not save…" and leaves the cancelled or timed-out status as it is.
- **Tests:**
  - A login is cancelled while its collection waits on a busy lock: nothing is written, the status stays cancelled, and the runtime is closed once.
  - Collection with an already-aborted signal stores nothing.
  - A write aborted while waiting for the lock publishes nothing.

**F3: Antigravity's stored login is now checked**
- `remoteCredentialProblem` no longer depends on whether a provider supports pasted credentials. It checks the provider's login files from the credential manifest, plus pasted credentials where those are supported.
- An Antigravity agent without `antigravity-cli/antigravity-oauth-token` now reports `auth_required`, with a login-only message, since it has no paste option.
- **Test:** the missing-login case, then the ready case once the file is stored.

**F4: Fly readiness now resolves the image**
- New `fly/imageResolution.ts`. Images on `registry.fly.io` are resolved with the Fly token (through the existing `FlyRegistry`), down to the linux/amd64 manifest.
- Images on other registries are resolved anonymously, the same way Fly would pull them without credentials. The Fly token is never sent outside `registry.fly.io`.
- `flyReadiness` calls this after the Machines list succeeds. A failure returns not-ready, which shows on the card as `runtime_unavailable`. A 404 says the image doesn't resolve, and a 401 or 403 says access was refused.
- **Tests:**
  - Image resolution is required before Ready.
  - A 404 or 403 makes the agent not ready.
  - Image references parse correctly.
  - A fake registry checks the Fly-token path and the anonymous path, including that the Fly token never reaches another registry.

**Not fixed: unavoidable timing gaps.**
- A cancel that arrives after the in-lock check has passed can't stop a write that is already happening.
- For OpenCode's two stores, a cancel between the two writes can leave the first store written.

These come down to the filesystem having no atomic cross-store write, not stale state.

There's no visual change, so I didn't capture previews.

PR: #3865
Comment by: @integry (ID: 7232932164)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* fix: protect settings.json on read failure; clear key on login

I fixed F5 and F6. All 19 tests in `packages/api/test/agentRemoteCredentials.test.ts` pass, including 3 new ones, and so do the 17 in `test/remoteAgentLogin.test.ts`. Core and API typecheck clean and lint shows zero warnings. All 3 new tests fail when run against the previous `agentCredentialStore.ts`.

**F5: a failed read no longer wipes existing settings**
- Saving or removing a pasted credential now uses a strict reader (`strictRead` in `packages/api/services/agentCredentialStore.ts`), still under the store lock. A missing file still counts as empty. Any other read failure, such as an oversized `settings.json`, now stops the request with a 400: "The existing settings.json could not be read, so it was left unchanged". Before, the failure was treated as an empty file and the settings were overwritten.
- The tolerant reader is now used only for status reporting (`readAgentCredentialStatus` and `remoteCredentialProblem`).
- New test: with an oversized `settings.json`, both a save and a remove are refused, the file is byte-for-byte unchanged, and the status still reads.

**F6: interactive login now replaces a pasted key or token**
- A new core helper, `withoutPastedClaudeAuthentication` in `pastedCredentials.ts` (exported from `@propr/core`), takes `ANTHROPIC_API_KEY` and `CLAUDE_CODE_OAUTH_TOKEN` out of `settings.json` and keeps everything else.
- When `storeReturnedLoginFiles` saves a Claude login, it rewrites `settings.json` in the same locked write as `.credentials.json`. The new login and the removal of the old key land together, and the existing cancellation check before publishing still covers both.
- If `settings.json` can't be read, nothing is saved and the login reports "Could not save the login". Otherwise the old key could still override the new login.
- New tests:
  - Switching from a pasted key to an interactive login removes the key and keeps the other settings (`model`, other env vars). The status then shows no pasted credential, only the stored login.
  - When `settings.json` can't be read, the login stores no `.credentials.json` and leaves `settings.json` unchanged.

Codex and OpenCode don't have this problem, because their login file (`auth.json`) is the same file the pasted credential lives in, so a login replaces it.

**Not fixed: the same F6 conflict exists for Docker logins.** On a Docker instance, the CLI writes `.credentials.json` straight into the bound config directory, and the session is marked successful when the container exits. Nothing removes a previously pasted key from `settings.json`, so it can still override the new login. That code path wasn't part of the requested fix. Fixing it would mean adding a locked settings cleanup to the Docker success handler in `agentLoginSessionManager.ts`.

I made no previews because nothing in the UI changes.

PR: #3865
Comment by: @propr-ultrafix (ID: 0)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* test: wait for logger startup before faking timers in sprites test

Shard 4 failed because one test file, `test/spritesLeaseProvisioning.test.ts`, hung after it had already passed. It ran all four of its subtests in under a second, then never exited, and the runner killed it at the 180s limit. This PR's code didn't cause it: the file is unchanged on this branch, and the hang is a known flake in how the test sets up its fake clock.

**Cause:** the test swaps in a fake `setTimeout` clock. The logger's background thread sometimes finishes starting while that fake clock is active. A timer it sets during startup lands on the fake clock and is thrown away when the test cleans up. The thread then stays open and keeps the process alive. It's timing-dependent, so it happens more often on a busy CI host.

**Fix:** the test now waits for the logger to finish starting before it turns on the fake clock. This is a copy of the fix in the still-open PR #3868, which hit the same flake. Because the change is byte-for-byte the same, the two branches will merge cleanly whichever lands first. Only `test/spritesLeaseProvisioning.test.ts` changed, with 9 lines added and 1 changed.

**Verification:** the file passed 10 out of 10 times through `scripts/run-test-suite.mjs`, with all 10 running in parallel to add load. I can't fully confirm the fix locally, because before the change the file also passed when run alone, so the real test is the next CI run.

There's no visual change, so I didn't make any previews.

PR: #3865
Comment by: @propr-dev[bot] (ID: 7235221214)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* chore: keep other Codex credential on remove; wait for Fly capacity

I fixed F7 and F8 and added regression tests for both. I couldn't do F9: it needs live runs on a Fly-launched instance, which this container can't reach. Both touched test suites pass (20/20 each), and typecheck and zero-warning lint are clean for the changed core files.

### F7 — Removing one Codex kind no longer deletes the other
In `packages/core/src/agents/credentials/pastedCredentials.ts`, both Codex kinds still go through `removePastedCredential`. That runs on the current `auth.json`, read under the store lock. It now checks which kind the file actually holds:
- **Kind not in the file** (a newer save replaced it): nothing changes, so a stale Remove keeps the replacement.
- **Only that kind in the file:** the file is deleted, as before.
- **File holds both** (key and ChatGPT tokens): only the removed one goes.

This also protects a ChatGPT `auth.json` written by an interactive Codex login, which lands in the same file. Claude kinds already removed only their own variable, and OpenCode has a single kind, so neither had this bug.

**Tests:** a unit test in `test/remoteAgentLogin.test.ts` covers both directions, a missing file and the file holding both. An API-level test in `packages/api/test/agentRemoteCredentials.test.ts` saves a key, replaces it with a ChatGPT `auth.json`, removes the old key, and checks the login survives and the agent still counts as having credentials.

### F8 — Fly login now waits for real capacity
In `packages/core/src/agents/runtime/fly/flyLogin.ts`, the one-shot check that failed immediately is replaced by a wait:
- It rechecks Fly's live Machine count every 2 seconds.
- It shares one 30-second deadline with the in-process slot wait, so the total wait still can't exceed 30 seconds.
- The terminal shows "All N Fly Machines are in use; waiting up to 30s…".
- When the deadline passes, the error names `PROPR_FLY_MACHINES_MAX` and the wait time.
- If the user cancels during the wait, the login is cancelled rather than reported as a capacity error.

The Sprites login already retries against its pool inventory until the same 30-second limit, so it needed no change.

**Tests:** the old "full capacity" test expected an immediate failure; it now checks that the login waits the full period and rechecks. Two new tests cover a Machine freed by another process during the wait (the login then starts) and cancelling during the wait.

There is still a short window between a capacity check showing a free Machine and the create call, where another process can take it. That race between separate processes and Fly's API can't be closed. When Fly refuses the create at its organisation limit, the login still fails with the existing capacity message.

### F9 — Live acceptance runs: still to do
These runs still have to happen before merge, on a Fly-launched instance running this branch:
- An `AI` issue taken to a PR with a pasted key, on both Sprites and Fly Machines.
- An interactive Claude login on Sprites, followed by a run.
- An agent card showing healthy.

No run links or healthy-card evidence exist yet, and the existing tests run against mocked Fly and Sprites APIs, so they don't stand in for these runs.

No visual previews were captured, since neither fix changes what's on screen.

PR: #3865
Comment by: @propr-ultrafix (ID: 0)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* chore: merge Slot type export to fit spritesProvisioning line limit

I fixed the Validate Changes failure. The only problem was the Core Package Lint file-length limit: the merge from #3853 left `packages/core/src/agents/runtime/sprites/spritesProvisioning.ts` at 401 code lines, one over the 400 maximum.

**Fix:** I moved the separate `export type { Slot };` line into the existing export, which is now `export { startupStep, SpritePoolCapacityError, type Slot };`. No behaviour changes.

**Checks:** `npm run lint` in `packages/core` now passes with no warnings, and `tsc --noEmit` for core is clean.

**Separate failure on this commit:** the full test suite comment also reports `test/spritesLeaseProvisioning.test.ts` hitting the 180s timeout in shard 4. You didn't ask me to fix that and I made no change for it. When I ran that file on its own here, all 4 tests passed in about 2s, so it doesn't fail on its own in this container. If it shows up again in CI, it should be looked at separately.

PR: #3865
Comment by: @propr-dev[bot] (ID: 7236051545)
Comment by: @github-actions[bot] (ID: 7236051747)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* chore: accept OpenCode and Vibe in Sprites and Fly health checks

I fixed F10: the Sprites health check now accepts OpenCode and Vibe agents. It no longer reports "Agent runtime unavailable" for providers Sprites actually runs.

**What was wrong:** the health check kept its own list of the providers Sprites runs (Claude, Codex, Antigravity). `SpritesRuntime` uses a longer list that also has Vibe and OpenCode. Because the check rejected those two before looking at the token or the CLI version, a valid setup could never pass.

**The fix:**
- **One shared list:** the Sprites provider list now lives in one exported constant, `SPRITES_AGENT_TYPES` in `packages/core/src/agents/runtime/sprites/spritesCliVersions.ts`. Runs, interactive logins and the health check all use it, so they can't drift apart again. OpenCode and Vibe now go through the same pinned CLI version check as the others.
- **Same bug on Fly Machines:** while checking related code I found the Fly Machines health check had the same problem. It hardcoded Claude and Codex, but the Fly runtime also runs Vibe and OpenCode. It now uses the same rule the Fly runtime uses (`isRemoteAgentType`), so Vibe and OpenCode agents there no longer show as unavailable either.

**New tests** in `test/remoteAgentLogin.test.ts`:
- **OpenCode and Vibe on Sprites:** each is ready on its pinned CLI version and reports that version. A missing token or a non-pinned CLI version is still refused.
- **Matching the runtimes:** for every provider, Sprites and Fly Machines readiness must agree with what each runtime itself accepts. Antigravity is still refused on Fly.

**Verification:**
- The new tests failed on the old code and pass now (22 of 22 in the file).
- `test/spritesRuntime.test.ts` and `test/spritesPool.test.ts` still pass (77 of 77).
- The core typecheck and zero-warning lint on the changed files are clean.

There's no visible UI change, so I didn't make previews.

**Found but not changed (outside F10):** the interactive login on Fly Machines still only accepts Claude and Codex (`flyMachinesRuntime.ts:62`). That limit matches the PR description, so I left it alone.

PR: #3865
Comment by: @propr-ultrafix (ID: 0)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* chore: recognize Vibe and OpenCode credentials in remote health check

F11 is fixed. The remote health check now recognizes the credentials Vibe and OpenCode runs actually use, so an agent set up that way shows **Ready** instead of `auth_required`. The new and updated tests pass, typecheck and lint (zero warnings) are clean, and none of this was run on a live Sprites or Fly instance.

**What the check now counts as a credential**

- **Vibe:**
  - A `.env` file in its config directory with a non-empty `MISTRAL_API_KEY`. This is read through the provider manifest, the same way the broker extracts it for a run.
  - `MISTRAL_API_KEY` in the agent's env vars, in ProPR's own environment, or in the Mistral key setting. If settings can't be read, they add no key, as at run time.
  - The config directory is found the way a Vibe run finds it: `VIBE_CONFIG_PATH` first, then the saved path. Paths the login resolver refuses, such as a custom `~/…` path, no longer cause a false failure.
- **OpenCode:**
  - A provider with a non-empty `options.apiKey` in `opencode.json`, `opencode.jsonc` (comments and trailing commas allowed) or `config.json`.
  - A provider key variable (`*_API_KEY` or `*_TOKEN`) among the agent env vars that ProPR passes to the run. GitHub tokens are not counted.

**One addition beyond the two named sources:** an OpenCode agent that offers one of the built-in free models now passes the check with no credential at all. The docs say these models need no login, and the Docker health check already reports such an agent as ready. Without this, the remote check would still have reported it as `auth_required`.

**Code changes**

- The file checks are in a new core module, `packages/core/src/agents/credentials/configuredCredentials.ts`.
- `remoteCredentialProblem` in `packages/api/services/agentCredentialStore.ts` is now async, because it may read settings. `agentHealthCheck.ts` awaits it.
- The health-check sentence in `docs/docs/features/agents-and-models.md` now lists these sources.

**Tests:** I added `packages/api/test/agentRemoteCredentialSources.test.ts` with 8 cases. They cover each source above, blank keys still failing, `VIBE_CONFIG_PATH`, the refused `~/…` path, and a full health check returning **Ready** for Vibe with only `.env` and OpenCode with only its config-file key. All 8 fail when run against the previous code. These tests, the existing credential and health-check suites, the OpenCode discovery route test and the redaction test all pass: 132 tests in total.

There are no visual changes, so I made no previews.

PR: #3865
Comment by: @propr-ultrafix (ID: 0)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* chore: keep operator credential changes from active runs on write-back

I fixed both findings, and each new regression test fails without its fix and passes with it.

**F12: active runs can restore removed credentials**
- Every write through the store writer (paste, Remove, and the files from an interactive login) now records which paths it changed, under the store lock and before the files are published. The record is a small file in the store, `.propr-operator-mutations.json` (new `packages/core/src/agents/credentials/operatorMutations.ts`). It is published the same way as the credentials, so a writer whose lock was taken over can't roll it back.
- The broker reads that record before it copies the store for a run. At write-back, under the lock, a path changed since the run was staged gets the new outcome `kept-operator-change`. The run's copy then can't overwrite a replacement, even with a later refresh time, and can't recreate a removed file.
- What stays the same:
  - A run whose copy still matches the current file writes back as before (`written`).
  - Between runs racing each other, the most recent refresh still wins.
  - A change to a different file in the store doesn't block the run.
- If the record can't be read, every path counts as changed, so the check fails closed. The next change replaces the bad record.
- The Docker, Sprites and Fly runs all go through this broker, so all three are covered.
- Tests:
  - `test/agentCredentialBroker.test.ts` covers: Codex remove, Codex account replacement with a later refresh time, OpenCode remove, runs staged after a change, the unchanged-copy case, and an unreadable record.
  - `packages/api/test/agentCredentialOperatorMutations.test.ts` runs the real paste and Remove functions against a run staged earlier.

**F13: Fly rejects supported OpenCode logins**
- `FlyMachinesRuntime.startLogin` now uses `flyLoginSupported`: an agent type Fly Machines runs that also has an interactive login. That gives Claude, Codex and OpenCode, and replaces the hard-coded `['claude', 'codex']` list.
- Antigravity is still refused before any Machine is created.
- Tests:
  - `test/remoteAgentLogin.test.ts` checks that the Machine runs `opencode auth login` and creates both the config and data directories.
  - The new API test runs a full login session through a real `FlyMachinesRuntime` with a fake Machines API. It checks that the session succeeds, the Machine is destroyed, and OpenCode's `auth.json` ends up in the agent's data store.

**Docs:** one sentence in `agents-and-models.md` saying Remove, replace and a new login also hold for runs already in progress.

**Checks run:**
- The root credential, Fly, Sprites, redaction and remote-login suites pass.
- The API agent login, credential and health-check suites pass: 78 pass, 0 fail, after rebuilding shared and core.
- Core and API typecheck are clean, and lint shows zero warnings on the changed files.

**Not covered (separate, existing behaviour):** runs that mount the store directly rather than through the broker write to the real file themselves, so this check can't stop them. That happens with `PROPR_AGENT_CREDENTIAL_BROKER=legacy`, or by default when the worker can't write the store. I left that alone.

The change has nothing visible in the UI, so I made no previews.

PR: #3865
Comment by: @propr-ultrafix (ID: 0)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* chore: fence stale runs and clear pasted Claude key on Docker login

I fixed both findings. Each new regression test fails on the old code and passes now. Lint (zero warnings), the core and API typechecks, the 187 tests in the credential and login suites, and 87 Sprites/Fly runtime tests all pass.

**F14: run staged during an operator change overwrites the replacement**
- **Change:** the mutation record is now published in two steps, both under the store lock. The new tokens go out with the paths marked "pending" before any file is published. The mark is cleared once the writer stops publishing, whether it succeeded or failed. A run that stages while a path is pending always counts as staged before that change. So if its copy no longer matches the store, its refreshed token is kept out rather than winning on recency. Runs stay lock-free and synchronous, so a read-only store still stages. The changes are in `operatorMutations.ts`, `credentialStoreWriter.ts` and a comment in `broker.ts`.
- **Crash case:** if a writer dies mid-publication, its mark stays. Runs on that path then lose the recency rule until its next operator change completes. That keeps the operator's change, at the cost of the old run-vs-run behaviour for that path.
- **Tests:** two new cases in `test/agentCredentialBroker.test.ts`:
  - A run is staged in the exact window from the finding: new record, old `auth.json`. The replacement is kept, and a run staged afterwards writes back normally.
  - A mark left by a dead writer keeps fencing until the path's next change clears it, and then recency between runs works again.
- **Old code:** run with only a test hook added, it returns `written-newer`, meaning the old account overwrote the replacement.

**F15: pasted Claude key survives a Docker login**
- **Change:** when a Docker login container exits 0 for Claude, the session runs the same locked `settings.json` cleanup as the remote login before reporting success. Other settings are kept.
  - A failed login leaves the pasted key in place.
  - So does a login cancelled or timed out while the cleanup waits for the lock.
  - If the cleanup fails, the login is reported as failed ("Could not save the login: …").
  - Other agent types still finish immediately, as before.
- **Tests:** three cases in `packages/api/test/agentCredentialOperatorMutations.test.ts`: success, failure, and cancel while waiting for the lock. On the old code, the pasted key survived the successful login.
- **Line limit:** `agentLoginSessionManager.ts` was already at 397 of the 400-line limit. I moved two Docker helpers (image pull and orphan sweep) unchanged into `agentLoginDocker.ts`.
- **Docs:** I added one sentence to `agents-and-models.md`: a successful Claude login removes a pasted key or token on every runtime, and a failed or cancelled login leaves it.

One race can't be avoided: a cancel that arrives just after the cleanup published reports "cancelled" even though the key was removed. The remote login has the same race.

**Two related problems I found but didn't fix (outside F14/F15):**
1. **A Docker login isn't recorded as an operator change.** The container writes the login files straight into the store, and no mutation token is recorded for them. A run staged before a Docker login can still overwrite the new login with its newer refresh. After this fix only `settings.json` gets a token. Remote logins go through the writer and are covered.
2. **Removal isn't fenced by the lock.** When the writer deletes a file, it calls `fs.rmSync` directly instead of going through the lock's publication directory. A writer whose lock was taken over as stale can therefore still delete a file afterwards, including the next writer's replacement. File contents and the mutation record are fenced; removals are not.

The changes are server-side only, so there are no visual previews.

PR: #3865
Comment by: @propr-ultrafix (ID: 0)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* chore: redact OpenCode secrets and lease credential removals

I fixed both findings, F16 and F17, and added a regression test for each. Each new test fails against the branch's previous code and passes now.

**F16: OpenCode secrets are now redacted** (`packages/core/src/utils/secretRedaction.ts`)
- I added two patterns that redact the values of `key`, `refresh`, `access` and `token` inside an OpenCode `auth.json` entry. `token` holds the second secret in OpenCode's `wellknown` entries, so I included it as part of the same defect.
- They only fire inside an object that also has a `"type"` field, whether `type` comes before or after the secret. Pasted documents keep the operator's field order, so both have to work. Limiting them this way stops a plain `"key"` or `"access"` field elsewhere in a log from being redacted.
- **Test** (`test/redactSecrets.test.ts`): uses opaque values for `oauth`, `api` and `wellknown` entries, both compact and in the stored two-space layout. It also checks that an unrelated `key`/`access` document passes through unchanged.

**F17: a removal can no longer delete a successor's credential** (`packages/core/src/agents/credentials/credentialStoreWriter.ts`)
- Removal now goes through the lease, the same way replacements do. The writer creates a directory inside its publication directory, moves the file into it, then deletes it there.
- After a stale takeover, that publication directory has been moved away, so the move fails with `CredentialStoreLeaseRevokedError` and the successor's file stays. A file that is already missing still counts as removed.
- Removals are refused for directories, the same as the old direct delete.
- **Test** (`test/agentCredentialStoreLockMultiprocess.test.ts`, new fixture `test/fixtures/credentialStoreWriterContender.ts`): a removal process records its pending mutation and is then suspended. A second process takes over the stale lock and publishes a replacement, then the first resumes. The test checks that:
  - the replacement survives.
  - the removal fails as taken over.
  - the pending mark is cleared.
  - no publication or removal directory is left behind.

  Against the old code, the successor's `auth.json` was deleted.
- **Other deletions checked:** this was the only deletion of a canonical store file in the PR. The broker's write-back never deletes, and the other deletions in the credential staging code only remove per-run copies.
- **Remaining race:** a removal that completes before the takeover revokes its lease simply happens before the successor's write, which is the correct order. There's no avoidable gap left.

**Verification:** I ran the credential lock, broker, remote-login, redaction and tool-policy suites, plus the API `agentRemoteCredentials` suite after rebuilding the core package. All tests passed. Core typecheck and lint on the changed files are clean with zero warnings. No visual previews: nothing here changes what users see.

**Found separately, not changed:**
- If the lease is revoked between preparing a replacement file and renaming it into place, the writer's replacement path throws a raw `ENOENT` rather than `CredentialStoreLeaseRevokedError`. Nothing in the store changes; only the error type is inconsistent with the broker, which converts it.
- When a log entry is redacted as an object rather than as text, only the string values are checked, so no rule that relies on field names applies, including the existing Claude/Codex one. This predates the PR.

PR: #3865
Comment by: @propr-ultrafix (ID: 0)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* fix: fix lint limits in agent config modal and login session manager

I fixed both lint failures that broke Validate Changes. `eslint . --max-warnings 0` now passes in both `propr-ui` and `packages/api`.

**UI: complexity 22, limit 20 (`AgentConfigModal.tsx`)**
- I moved two conditions out of the component into helpers in `agentCredentialSetupUtils.ts`:
  - `showsPastedCredentials(type, isEditing, credentialSetup)` decides when the "Paste a key or token" section shows. The form section and the submit path now both use it.
  - `storedCredentialAgentId(agent, type)` returns the saved agent's id only while its type hasn't changed.
- Defining the helpers inside the modal file pushed it to 403 lines, over the 400-line limit, which is why they're in the utils file.

**API: 404 lines, limit 400 (`agentLoginSessionManager.ts`)**
- In `write()`, the remote and local branches each repeated the same input check, timestamp update and timeout reset. I merged them into one path that writes to the remote runtime or to the container's stdin.
- Behaviour is unchanged: the same errors are thrown in the same order for both kinds of login.

**Checks**
- The UI typecheck is clean.
- The 44 SettingsPage UI test files pass (425 tests).
- The 4 API test files that exercise the login session manager all pass: `agentLoginRoutes`, `agentLoginPi`, `agentRemoteCredentials` and `agentCredentialOperatorMutations`. I ran them through the repo's test runner after rebuilding `shared` and `core`.

This is a code-only change with nothing visible, so there are no previews.

PR: #3865
Comment by: @propr-dev[bot] (ID: 7246900062)
Comment by: @github-actions[bot] (ID: 7246900152)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* test: cover Pi as Docker-only agent in starts-as-root test

I fixed the shard 4 failure, and the test now passes locally (10/10 subtests).

**Cause:** in run 46198702192 the only failing file was `test/agentRunSpecStartsAsRoot.test.ts`. That test was added in #3853 and has to cover every agent type. The `pi` agent type, added in #3847, landed on this branch through the epic merges, and nobody added a `pi` case to the test. So two subtests failed:
- "every agent type has a task spec case" failed because the list had no `pi`.
- "pi: the task spec starts as root…" crashed because the `pi` case didn't exist.

**Fix (test only, in `test/agentRunSpecStartsAsRoot.test.ts`):** Pi doesn't build a run spec at all. It starts its own `docker run --user 0:0`, so it can't run on Fly Machines or Sprites and the remote-runtime "starts as root" check doesn't apply to it. I split Pi out as a Docker-only agent type:
- The existing run-spec checks now cover every type except `pi`.
- Pi gets its own case that builds its real task Docker arguments and checks that they start as root.
- The coverage check still requires every agent type to appear in one list or the other, so a new agent type fails until someone adds a case for it.

The earlier comment about `test/spritesLeaseProvisioning.test.ts` timing out at 180s came from an older run. In this run it didn't fail, and it passes locally in about 4s. I made no change for it; if it shows up again, it's most likely runner contention rather than code.

This is a test-only change with nothing to see on screen, so there are no previews.

PR: #3865
Comment by: @propr-dev[bot] (ID: 7247259883)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* chore: reject OpenCode auth.json pastes without a credential

F18 is fixed: an OpenCode `auth.json` with no actual credential in it is now refused, the working file stays in place, and the agent is no longer reported as having credentials or shown as Ready.

**What changed** (`packages/core/src/agents/credentials/pastedCredentials.ts`)
- **Validation before replacing the file:** each provider entry must be one of the three types `opencode auth login` writes, and must hold a non-empty credential:
  - `api` needs `key`.
  - `oauth` needs `refresh` or `access`.
  - `wellknown` needs `key` or `token`.
  - Any other type is refused, and so is an entry whose credential fields are missing or only spaces. If one entry is bad, the whole document is refused. The error goes back to the operator as a 400, so `rewrite` never replaces the existing `auth.json`.
- **Status reporting:** the status check now uses the same per-entry test. A file with provider entries but no usable credential reports "not set", where before it reported "set". Because the health check reads that status, `remoteCredentialProblem` now returns "No credentials are stored…" instead of Ready.

**Sibling paths checked**
- The Codex `auth.json` check already required a key or login tokens.
- The OpenCode login-file check skips the pasted `auth.json`, so the status fix covers it.
- An OpenCode `auth.json` collected after an interactive remote login is still stored without this check. It now reports "not set" if it has no credential. One test fixture for that path stored `{"a":{"type":"api"}}`, so I added a key to it.

**Regressions added**
- `packages/api/test/agentRemoteCredentials.test.ts`: saves a working OpenCode login, then tries six credential-free or unsupported pastes. Each is refused, and the file is byte-for-byte unchanged afterwards, still with no credential problem. A credential-free file written straight into the store reports "not set" and fails the health check.
- `test/remoteAgentLogin.test.ts`: checks the refusal messages for each type, and that valid `api`, `oauth` and `wellknown` documents are kept as-is.

**Verification:** 61 tests pass across the touched credential suites, plus the related broker, operator-mutation and credential-source suites. The broker suite has to go through `scripts/run-test-suite.mjs` because it needs module mocks. The `tsc` typecheck is clean for core and api, and lint shows zero warnings on the changed files.

I made no visual previews because nothing on screen changed.

PR: #3865
Comment by: @propr-ultrafix (ID: 0)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* chore: recheck agent health after removing a stored credential

F19 is fixed: removing a stored credential in the agent dialog now reruns that agent's health check. A card that showed **Ready** updates to the new result instead of keeping the old cached one.

**What changed**
- `AgentPastedCredentials.tsx`: a new optional `onStoredCredentialRemoved(agentId)` callback is called after `clearAgentCredential` succeeds. If the delete fails, the error shows as before and no recheck is requested.
- `AgentConfigModal.tsx`: passes that callback through. I put the props destructuring on fewer lines because the file had gone over the 400-line lint limit.
- `AgentsListSection.tsx`: connects the callback to the existing `recheck`, the same path used after saving a pasted credential and after closing the login dialog.

**Regression test** in `AgentsListSection.test.tsx`: a Codex agent whose only credential is a stored OpenAI key starts as **Ready**. The test opens Edit, clicks **Remove** and closes the dialog with Cancel. It then checks for a fresh health request with the force flag, the "No credential stored" alert, and that **Ready** is gone. With the connection removed, the test fails.

**Other places checked**
- `AgentPastedCredentials` is the only place in the UI that deletes a credential.
- `AgentsListSection` is the only place that renders `AgentConfigModal`.
- Saving a credential and closing the login dialog already rechecked health.

Removing a credential and then saving the agent rechecks once on removal. If the save changes the agent's configuration, the existing revision logic can start one more check.

**Verification:** all 426 tests in `propr-ui/src/pages/SettingsPage/` pass. `tsc --noEmit` and ESLint with zero warnings allowed are clean for that directory.

I didn't make a visual preview: the card just shows the existing health-error state, with no new UI.

PR: #3865
Comment by: @propr-ultrafix (ID: 0)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* refactor: extract Mistral API key field from AgentConfigModal

I fixed the UI lint failure that broke Validate Changes. `AgentConfigModal.tsx` was at 410 code lines, over the 400-line limit.

I moved the Vibe agent's Mistral API key field, including its show/hide toggle and the "Get your API key from Mistral AI" link, into its own component, `propr-ui/src/pages/SettingsPage/MistralApiKeyField.tsx`. The markup is the same as before. The modal now just renders that component when the agent type is `vibe`, and the file is well under the limit.

The full `propr-ui` lint (`eslint . --max-warnings 0`) and the typecheck now pass. The three agent dialog test files also pass (26 tests). I didn't take previews, since nothing on screen changes.

PR: #3865
Comment by: @github-actions[bot] (ID: 7248908297)
Comment by: @propr-dev[bot] (ID: 7248908799)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* chore: request full Claude sign-in link in agent login terminal

The URL was not being mangled by ProPR. The Claude CLI itself prints that short link, and the login now asks it for the full one. The live end-to-end Sprites login (item 3) is still not done: I have no access to a Fly instance from here, so it needs to be repeated on a Docker-less instance.

**Cause.** I recorded `claude auth login` (Claude Code 2.1.330) in a 120×40 PTY with the same environment the remote logins use. The CLI prints `https://claude.ai/oauth/authorize?z-…` with 45 characters after the `?`, both in the visible text and in the OSC 8 link target. Piped with no TTY it prints the same thing, and there are no redraws. Since 2.1 the CLI compacts the sign-in link on purpose: the 45 characters are 2 scope characters plus the 43-character `code_challenge`, and `client_id`, `redirect_uri` and `state` are dropped. An environment variable in the CLI, `CLAUDE_CODE_FULL_SIGN_IN_LINK`, turns this off. I couldn't check whether claude.ai accepts the compact link, because curl gets a Cloudflare 403.

**Fixes**
- **Full link:** the Claude login now sets `CLAUDE_CODE_FULL_SIGN_IN_LINK=1`. In the recording, the CLI then prints the full `https://claude.com/cai/oauth/authorize?code=true&client_id=…&redirect_uri=…&code_challenge=…&state=…` on one line. The setting reaches Sprites, Fly Machines and local Docker (Docker passes it with `-e`, and the entrypoint keeps it). Local Docker logins were getting the compact link too, since that container is also started with `-t`.
- **Wider terminal:** the login terminal is now 1000 columns on both remote runtimes. Sprites spawns with `cols: 1000`. On Fly, `script` can't take a size from its input pipe, so it runs `stty cols 1000 rows 40` before starting the CLI. I didn't use `TERM=dumb` or `NO_COLOR`: neither was needed, and they could change how the CLIs' paste prompts behave.
- **OSC 8 links in `sanitizeTerminalChunk`:** it now keeps the target of an OSC 8 hyperlink. If the visible label doesn't match the target (ignoring line breaks and spaces), the target is written out as plain text after it. Other control strings stay hidden. Targets that aren't a single scheme-and-text URI are dropped, and anything over 8 KB isn't tracked.
- **"Not signed in" badge:** an `auth_required` error whose message says no credentials are stored (or "not logged in / not signed in") now shows **Not signed in**. An expired login still shows **Authentication expired**.

**Tests.** The new `packages/api/test/agentLoginTerminal.test.ts` uses the recorded transcripts, saved in `packages/api/test/fixtures/agentLoginTranscripts/`. It feeds them in at several chunk sizes so escape sequences fall across chunk boundaries.
- The Claude transcript keeps the full URL with `client_id`, `redirect_uri`, `code_challenge` and `state`, and no control characters are left.
- The real recording has no redraws, so one test builds them from it: the label is wrapped at 120 columns, cleared and rewritten with cursor moves, and partly overwritten. The full URL still comes through from the link target. That test and the label-differs-from-target test fail with the old sanitizer.
- The Codex device-login transcript keeps `https://auth.openai.com/codex/device` and the one-time code.
- The compact-link transcript is kept as a test, showing the short URL comes from the CLI and not the sanitizer.
- The existing Sprites and Fly login tests now also check the 1000-column terminal.

The touched server suites (70 tests), the agent default-path tests and the UI card tests (19, including a new "Not signed in" case) all pass. Typecheck and zero-warning lint are clean.

I captured a preview of the badge with a mocked API: one card that was never signed in next to one whose login expired.

PR: #3865
Comment by: @integry (ID: 7258599907)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

* chore: agent credentials on Docker-less instances: paste credentials +…

I fixed F20: when a login CLI wraps a hyperlink's label across rows, the browser now gets the complete sign-in URL as one unbroken piece of text.

**The fix** (`packages/api/services/agentLoginTerminal.ts`): the old check stripped all whitespace from the label and compared it to the link's target. A label wrapped across rows passed that check, so the full URL was never written out and the dialog only made the first row clickable. A new helper, `labelShowsTarget`, now skips writing the URL out only when the label contains it unbroken and followed by whitespace or the end of the label. That boundary check matches how `AgentLoginModal` finds URLs, so a label like `https://…/a.` also gets the clean URL written after it.

**Tests** (`packages/api/test/agentLoginTerminal.test.ts`), two new cases:
- **Wrapped label:** uses the recorded Claude authorize URL with its label split into 120-column rows and nothing else changed. Fed in chunks of 1, 2, 7, 119, 120, 121 and 4096 characters, the output shows the wrapped label and then the full URL in one piece, with every OAuth parameter checked.
- **URL plus trailing text:** a label where the URL runs into trailing punctuation gets the URL written out again. A label that shows the URL followed by a space does not.

All 8 sanitizer tests pass. Both new tests fail when run against the previous version of the file. ESLint reports zero warnings on both files, and `tsc` reports no errors in them.

The existing check that an unwrapped label isn't repeated still passes. No other code changed in this PR does the same comparison: the sanitizer has a single caller, and the only other OSC 8 matches are the test transcripts. I didn't make a visual preview because the change only affects the text sent to the login dialog.

PR: #3865
Comment by: @propr-ultrafix (ID: 0)
Model: Claude Opus 5.5

ProPR-Agent: claude/claude-opus-5-5

---------

Co-authored-by: propr-dev[bot] <1316198+propr-dev[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

2 participants