# Update from chat

`self_update` installs a committed change from chat. Status and cancellation work on every installation; published versions keep the release updaters above.

| Installation | `self_update(action="prepare")` |
| --- | --- |
| Development instance (`dev` profile, source repository with a `dev` branch) | Lands the commit on `dev`, deploys it to the development instance and checks it there; that is the whole update. [Development checkout](https://fzkuji.github.io/OpenProgram/docs/install/development-checkout.html) |
| Official App (Developer ID signed) | Says it cannot rebuild the published App and points to **Check for updates** in Settings, before creating a request |
| Other packaged App on macOS | Builds and installs into the App, below |
| Packaged App or release install on Windows or Linux | Says this host has no source-update controller, before creating a request |
| Plain developer checkout | Says it activates nothing; restart the worker from the checkout |

Status: every activation level is verified end to end in the default App. Open: real-App acceptance of other tasks across a restart, and of session and tab restoration.

## Recover

| Situation | Run |
| --- | --- |
| The default App is stuck in maintenance | `openprogram self-update status --json` `openprogram self-update status UPDATE_ID --json` `openprogram self-update repair UPDATE_ID` |
| The App or normal CLI cannot start | `"$HOME/.openprogram/self-updates/UPDATE_ID/recover.sh" status` `"$HOME/.openprogram/self-updates/UPDATE_ID/recover.sh" repair` |
| The supervisor stopped partway | `recover.sh resume`, within the original authority and deadlines |
| Stop an update, including diagnosis, repair and tests | `self_update(action="cancel", update_id=…)` in chat |

**What repair does and refuses**

| Aspect | Rule |
| --- | --- |
| Runs | Local terminal, no Agent. Needs an interactive terminal and the exact confirmation shown with the action, revision and plan digest. No `--yes` or force-clear |
| Authority | An approved attempt resumes only within its original ten minutes; a failed or expired one needs fresh confirmation |
| Controller | Saved before the update. Restores the previous App when rollback is possible, or finishes an already started irreversible commit only with the original accepted evidence |
| Refuses | An aborted, unactivated transaction keeps the old App. Missing or changed evidence leaves maintenance on |
| Finishes | Restarts the default worker, checks App identity and the live service, clears maintenance. No verifier Job; the verdict stands. A separate result records the recovered version, which does not prove the failed feature works |
| `recover.sh` | Saved runtime outside the App; `status` is the default. `repair` still needs interactive confirmation and cannot bypass failed evidence or expired authorization. `resume` approves nothing new and recreates no verifier Job |

**Recovery at login**

- Before activation the update publishes `~/Library/LaunchAgents/ai.openprogram.self-update.recovery.UPDATE_ID.plist`. It runs once per later login, independently of the App. There is no resident process or periodic retry, and writing it starts nothing.
- It does not run before login or disk unlock. If App and controller both stop in the current login session, run the saved script.
- New jobs use launchd's `Standard` process class. Saved `Background` entries keep their bindings and policy.
- Progress goes to `bootstrap.log` before runtime validation and controller resumption.
- A completed update validates the saved runtime and removes only its unchanged login file, within the same state lock and without rehashing the whole runtime. The saved runtime, script and evidence stay.
- Missing or damaged trusted recovery files need manual intervention; nothing is rebuilt from an unverified App.

## Undo a change

| Target of `self_update(action="undo", target=…)` | Effect |
| --- | --- |
| Version id | Returns to exactly that version; everything after it stops running. Commits left behind stay under `refs/openprogram/undone/`. A version no longer on disk is rebuilt from its commit. |
| Commit | Reverts that one commit and keeps later ones. If later commits changed the same lines, it stops and names the files. |
| In the development instance | The target is a commit: the revert lands on `dev` and is deployed like any other change. |

From a terminal, even when the running version is broken:

```
openprogram versions list
openprogram versions use VERSION_ID
```

- `use` stops the worker, giving it up to 60 seconds to pause running work, and switches with no checks.
- A version that keeps failing to start returns to the last good one by itself, and your most recent conversation says so.
- Either way, at the next healthy start that version is the code new changes are made from. Conversations, settings and files do not change.

## Files edited inside a running version

Allowed, but without effect. At the next start they are saved under `~/.openprogram/runtime/unapplied/<time>/` with a `changes.patch`, the version is restored, and your most recent conversation says so once. `openprogram versions list` shows them. To use them, `git apply` the patch in a `self_update` worktree and run a normal update.

## What an update restarts

| Changed paths | Rebuilt | Restart |
| --- | --- | --- |
| `apps/web/**` | Web export | None. Open pages reload once nothing typed would be lost. |
| `docs/**`, `scripts/docs_site/**` | Docs site | None |
| `apps/cli/**` | Terminal UI bundle | None. New terminal sessions use it. |
| `openprogram/**`, `setup.py` | Wheel and docs | Worker. The App window stays open and shows that it is updating. |
| `apps/desktop/**` | Desktop archive | App quits and reopens |
| Dependency locks, `package.json` files, `scripts/release/**`, `apps/desktop/scripts/**`, `apps/desktop/build/**`, any other path | Complete App | App quits and reopens |
| `tests/**`, `README.md`, `.github/**` and similar | Nothing ships | None |

Diffed against the commit in `Contents/Resources/openprogram-source-revision`. An App from a `-dirty` checkout or an outside commit always gets the complete build. `prepare` reports the expected `restart` and `rebuild`; the controller decides again at build time and records it in `activation.json`.

## How it runs

**The chat tool**

- `action` is `status` (default), `prepare`, `retry`, `cancel` or `undo`.
- The first result explains the workflow and lists the guides. The first `prepare`, `retry` or `undo` in a conversation is refused once, with that action's instructions (`help("self_update.prepare")`, `help("self_update.retry")`, `help("self_update.undo")`). `help("self_update")` shows the workflow again.
- `prepare`, `retry` and `undo` follow the conversation's permission mode; `status` needs no approval.
- Conversations show ordinary messages and tool results only: no update history, controls, evidence viewer or recovery notice, and no polling of update-history APIs.

**Installation, Jobs and continuation**

| Aspect | Rule |
| --- | --- |
| Install | New bundle beside the installed one, swapped by rename, verified, then committed or rolled back. Rollback restores the previous bundle at the same restart level. |
| No restart needed | Skips maintenance; conversations and Jobs continue. |
| Queued Jobs | Keep their identities and wait through maintenance. |
| Running work | Executions with durable pause stop at their next checkpoint. The App is replaced only after active attempts and resource claims end. A task without a safe pause must finish before the update deadline, or activation is aborted. |
| After commit or rollback | Only executions this update paused resume. Tasks paused by the user or waiting for input stay paused. |
| Changed tool contract | Checkpoint validation still rejects it. An update-owned continuation then keeps the old checkpoint and gets one planning Job from the original task and history, with its tool selection and permission rules. Unresolved side effects or a user cancellation prevent replanning. |
| Original task | New updates save an original-session follow-up with a stable Job identity. After maintenance and any repair sequence it keeps checking the requested behavior as a new background turn, with no approval for another installation. Older records get none. Installation success and task continuation are separate outcomes. |
| Finite results | Persisted in the original session even if the window is closed or no verification Job was created. Reconciliation reuses the same update, attempt and result-type identity, starts no model turn and does not move HEAD. Interrupted writes retry. |
| Session or node gone | Delivery stays pending and goes nowhere else. A persisted result neither reopens the App nor proves installation. |

**Offline packaging and pre-activation checks**

| Aspect | Rule |
| --- | --- |
| Dependency base | Exactly the candidate's `uv.lock` and `scripts/release/product-runtime.json`. Otherwise, or with caches missing, the update stops before activation; neither authorizes downloads or mismatched dependencies. |
| Build tools | The saved runtime's pinned tools and private copies of existing npm, uv, Electron-builder and node-gyp caches. |
| Electron archive | Matches the controller's pinned version, architecture and release SHA-256; the candidate gets it as read-only `electronDist`. |
| Packaged | Complete build: the candidate's Web, docs, wheel and Desktop archive. Partial build: starts from a copy of the installed App. |
| Worker smoke test | One private controller-selected loopback port, never 18100. |
| Browser and icon checks | Run by the revalidated saved controller runtime, outside every candidate-writable path, against assets whose tree hash matches it. The writable build-runtime copy is never executed by the controller. All finish before activation. |
| Recovery protocol | Candidate and installed App both hold matching declarations, generated by packaging and the refresh script from the actual Desktop archive, installer, runtime manifest, backend and compiled Web files. Rechecked after waiting and after resuming. |
| Stops activation | Missing, incompatible or changed declarations, a mismatched transaction ID or invalid frozen owner configuration, before the old App is replaced. An older App without a declaration needs an explicit complete update first. |

**Status and history APIs**

| Endpoint | Returns |
| --- | --- |
| `GET /api/self-updates?session_id=…` | History with completed attempts; bounded `limit` and `cursor` |
| `GET /api/self-updates/{update_id}?session_id=…` | Detail |
| `GET /api/self-updates/{update_id}/evidence?session_id=…&evidence_id=…` | Observations cited by the validated signed result; use the verifier's `evidence_id` or an assertion's `evidence_refs` |

- All need owner authentication; evidence also needs the original session. The chat tool shares the same read-only projection. `self_update()` and `self-update status --json` expose `source_repair_result`.
- `candidate_revision` and `target_app` describe the requested installation. `last_verified_runtime` holds the last matching verification's SHA, PID, timestamp and source, or null; it does not prove the worker is online. `state_revision` is a counter, not a Git revision.
- Queries do not initialize or repair state. Invalid state returns an error, not an empty history; changed or invalid evidence too. Running reports `self_update_error` if its snapshot is unavailable.
- The projection excludes credentials, raw logs and configuration; repair summaries hold status and any new candidate SHA. It does not replace the CLI recovery output. Stored HTTP or HTML text is not proof of a rendered window.

**Reopening the conversation**

- The controller persists the recovery intent before activation and binds the opaque update ID to the installer transaction. If the App was open, activation and rollback reopen it with that ID; a closed App stays closed. Ordinary launches do not consume these requests.
- Desktop resolves only the original session through owner authentication and acknowledges once the transcript loads in the main window. An expired request, deleted session or authentication failure leaves normal startup, with no notice. Changing pages stops relocation. Neither step starts a verification Job or proves success.

[Self-update verification plans](https://fzkuji.github.io/OpenProgram/docs/install/self-update-verification.html) · [Self-update rollback](https://fzkuji.github.io/OpenProgram/docs/install/self-update-rollback.html)
