# pi-resilient-goal

`pi-resilient-goal` keeps an explicitly declared Pi goal running until the goal
is marked complete. It combines a Pi extension with a separate launcher:

- the extension continues after ordinary stopped turns and after Pi's built-in
  transient retries are exhausted;
- explicit account/subscription usage exhaustion waits for the provider's reset
  time when Pi exposes one, then resumes;
- `pi-resilient` restarts an unexpectedly exited or frozen Pi child with the
  same persisted session file.

An in-process extension cannot restart its own terminated process. Use the
launcher when process-death recovery matters.

## Install

This version targets Pi `0.80.x` (`>=0.80.6 <0.81.0`). Install it as a Pi package
to auto-load the extension in normal Pi sessions:

```bash
pi install npm:pi-resilient-goal
```

Install it globally as well when you want the `pi-resilient` launcher on
`PATH` for process-death and heartbeat recovery:

```bash
npm install -g pi-resilient-goal
pi-resilient --
```

During local package development, replace the npm name in the global install
command with `./tools/pi-resilient-goal`.

When `pi` on `PATH` is a wrapper, you can select the real executable explicitly:

```bash
PI_REAL_BIN=/absolute/path/to/pi pi-resilient -- --model openai-codex/gpt-5.6-sol
```

Everything after `--` is passed to Pi. The launcher injects the package's
extension path as well; Pi deduplicates the same resolved extension path when
the package is already enabled. Resilient goals require a persisted session, so
`--no-session` is rejected.

## Use

Start Pi through the launcher, then declare a goal:

```text
/goal implement and verify the requested feature
```

The agent can also call `create_goal` when you explicitly ask for a persistent
goal. A normal final answer does not stop the loop. The agent must call:

```text
update_goal { "status": "complete" }
```

Useful commands:

- `/goal` shows the current state and next retry/reset time.
- `/goal pause` stops automatic continuation but leaves Pi open.
- `/goal resume` resumes immediately.
- `/goal complete` explicitly completes the goal as a user action.
- `/goal clear` removes the goal.
- `/resilient-stop` pauses the goal and tells the launcher to exit.
- `/quit` or launcher `Ctrl+C` also stops a normal run.

## Failure behavior

Pi's own bounded automatic retries run first. The extension makes its recovery
decision from `agent_settled`, after those retries and any automatic compaction
have finished.

- Reconnect failures, terminated streams, timeouts, 429 throttling, overload,
  and 5xx errors use bounded exponential backoff and continue.
- Unknown errors remain recoverable but probe more slowly.
- Explicit usage exhaustion is separate from an ordinary rate limit. If Pi's
  error contains a reset time, the footer and `/goal` show it. If Pi does not
  expose a reset time, the extension says so and shows the next 15-minute probe;
  it never invents a reset timestamp.
- A manual Escape/abort pauses the goal instead of fighting the user.

The reset wait is stored in the Pi session and mirrored to the launcher runtime
file. If Pi dies while waiting, the launcher does not restart it before that
stored deadline.

## Conservative stall recovery

Default stall recovery does not use quiet stdout as evidence. Providers and
long-running tools can be legitimately silent. The extension writes a heartbeat
every five seconds; the launcher restarts only when the child exits, fails to
publish its first heartbeat within 120 seconds, or later lets that heartbeat
become stale for 30 seconds.

```bash
pi-resilient --startup-timeout-seconds 180 --heartbeat-timeout-seconds 60 --
```

A logically stuck promise can still keep the event loop and heartbeat alive.
That ambiguous case is intentionally not killed by default because replaying an
unknown tool outcome can duplicate side effects.

## Durability and safety

Goal state is appended to Pi's branch-aware session log. Launcher/runtime JSON
uses atomic write-and-rename updates. One supervisor lock is held per session,
and every child generation has a unique id so stale processes cannot be
mistaken for the current child. Locks fail closed. If the launcher itself is
killed without cleanup, confirm no supervisor owns the recorded PID before
manually removing the stale lock path named in the next startup error.

Recovery is **at least once**, not exactly once. A process can die after a file,
command, or external system changed but before Pi persisted the tool result.
Every continuation tells the agent to inspect current state before repeating
work. Tools that can produce external side effects still need their own
idempotency keys, transactions, or read-before-write checks.

The launcher itself must remain alive. This package recovers a terminated Pi
child; surviving logout, reboot, or launcher termination requires an OS service
manager such as launchd or systemd around `pi-resilient`.

## State and diagnostics

Each launcher run writes under:

```text
~/.pi/agent/resilient/runs/<run-id>/
  runtime.json
  supervisor.json
```

Use `--run-dir <path>` for a stable or test-specific location. The state files
contain internal session paths, process ids, timestamps, and error text. They do
not store provider credentials.

## Development

```bash
cd tools/pi-resilient-goal
npm test
npm run check
```
