# In-conversation self-update

An Agent changes OpenProgram in a private worktree. The change becomes a sealed version, is tried on a copy of the data, and is switched to by the old version from outside the worker. Any failure returns to the version that was running. Official releases follow [Automatic updates](https://fzkuji.github.io/OpenProgram/docs/reference/design/distribution/automatic-updates.html).

1. **Worktree** Edit, commit
2. **Sealed version** Built beside live code
3. **Trial** Copy of the data
4. **Wait for idle** Checkpoint tasks
5. **Pointer** Compare-and-set
6. **New worker** Turns held
7. **Probes** Turn check, release
8. **Probation** 120 s clean
   
   Any failure: pointer back, code only
9. **Commit** Good pairs shift, local moves

## Rules

| Subject | Rule |
| --- | --- |
| Writing | Never gated; only activation is checked |
| Running code | Always a committed version |
| Turns | Refused at no point; during the switch they are held and run afterwards |
| Activation and rollback | Done by the old version's out-of-process controller. A changed updater applies from the next switch. A candidate's worker reports and never transitions an update that names it. |
| Rollback scope | Code only |
| What may change | Anything, with no protected-path list. Three fixed protocols are read by things that do not self-update: the pointer format, the `<state>/self-updates/` files, the shell's main-process contract. |

## Backends

`control/backend.py` picks the first that matches; `self_update` calls only this interface.

| Backend | When | Behaviour |
| --- | --- | --- |
| `checkout` | `developer.json` exists | Explains this is a developer checkout; activates nothing |
| `versions` | `sys.prefix` inside `<root>/versions/` | Full lifecycle on macOS, Windows, Linux |
| `dev_deploy` | The worker runs the `dev` profile and its source repo has a `dev` branch | [Development instance](#development-instance) |
| `legacy_app` | Packaged App with an embedded runtime otherwise; the official, Developer ID signed App is refused and pointed to Check for updates | `_prepare_update` path and App installer transaction, macOS only |
| `checkout` | Otherwise, a source checkout | As above |

## Tool surface

| Action (`versions`) | Effect |
| --- | --- |
| `begin(task)` | Creates `work/<task>` from `local` through `manager.create_worktree(..., destination=...)`, binds it as the turn's working directory, returns its path |
| `prepare(task, goal, assertions, verification_plan?, iteration_policy?)` | Validates and starts the lifecycle, or queues it |
| `retry(update_id)` | Next attempt, at most 3 per chain |
| `status(update_id?)` | Read; includes queued requests |
| `cancel(update_id)` | Through `quiescing`, and for a queued request |
| `versions()` | Retained versions |
| `undo(target)` | [Undo](#undo) |

`status` and `versions` are free. `self_update` adds `unsafe_in=["plan"]`. `dev_deploy` and `legacy_app` keep `prepare(worktree_id, candidate_sha, goal, assertions, ...)`.

- **Validation**: `prepare` requires an existing, linked, clean worktree with commits beyond `local`; errors return to the model. The candidate may be based on any ancestor of `local`; it is rebased, not refused.
- **Authorization**: In default mode the owner's call runs without a card. Ask mode or an ask rule produces the ordinary card. A non-owner is refused by identity.
- **Acceptance**: `goal`, `assertions`, `verification_plan` keep one `acceptance-N` check per assertion. `self_update_observe` is the verifier's only way to observe; in trial it targets the trial port.

## States

| From | To | Condition |
| --- | --- | --- |
| new | `preparing` | Valid, slot free (tool, in worker) |
| `preparing` | `building` | Origin turn durable (`control/handoff.py`) |
| `preparing` | `aborted` | Origin turn ended without committing the call |
| `building` | `trial` | Version sealed |
| `building` | `aborted` | Build error, not enough disk, `shell_compat` outside the shell's range |
| `trial` | `ready` | Every check passed, verifier receipt valid |
| `trial` | `aborted` | Any check failed, or timeout |
| `ready` | `building` | `local` moved; rebased, `rebases <= 3` |
| `ready` | `aborted` | Rebase conflict, or too many rebases |
| `ready` | `quiescing` | `local` equals `base_sha` |
| `quiescing` | `activating` | Tasks idle or checkpointed |
| `quiescing` | `aborted` | Cancelled, or 30 minutes |
| `activating` | `verifying` | Pointer moved, worker reports candidate identity |
| `activating` | `rolled_back` | Worker did not start, pointer returned |
| `verifying` | `succeeded` | Probes passed, turn check done, 120 s probation clean, commit done |
| `verifying` | `rolled_back` | Probe failed, crash, timeout at 390 s |
| `activating`, `verifying` | `needs_manual_recovery` | Pointer returned and the old version also fails its probe |

`rolled_back` is also recorded by the sweep in the restored worker. The controller owns every other transition from `building` on.

**Request, queue, controller**

| Item | Rule |
| --- | --- |
| `UpdateRequest` | Schema 2: `kind` (`change`, `undo_to`, `undo_commit`, `official`), `controller_version`, `task`, `candidate_version`, `rebases`. Schema 1: terminal ones shown as they are; others become `aborted`, “started under the previous update system”. A stored `staging` reads as `building`. |
| Queue | A request finding the slot held is validated and written to `queue.json` in order, with no update directory. The finishing controller or worker start sweep takes the head. |
| Verifier | `store.claim_verifier`, `_validate_event`, `verification_channel.load_grant` and `control/recovery.py` accept `VERIFIER_PHASES = {TRIAL, VERIFYING}`. |
| `self-updates/` | A versioned protocol read by the old controller and the candidate's worker. During `activating` and `verifying` only the controller writes. Readers ignore unknown keys in protocol-tagged files. |
| Controller | `python -I -B -m openprogram.operations.self_update.control.supervisor <update_id>` from `versions/<controller_version>/venv`, pinned until terminal. Restarted on abnormal exit by launchd `KeepAlive={SuccessfulExit=false}`, a Scheduled Task, `systemd-run --user`, or `setsid` as fallback. |
| Liveness | The controller writes its pid and start time to `controller.json` once and writes nothing more; the Worker's watchdog (`control/watchdog.py`) learns from the operating system the moment that process ends and relaunches the controller, giving a launched one 30 s to appear. `maintenance.json` has a deadline, and an expired marker is ignored. An expired `probation_deadline` is a failure at the launcher. |
| Start sweep | `recover_pending_updates` relaunches the controller of any non-terminal update. If `current` no longer names the candidate during `activating` or `verifying`, it records `rolled_back`, leaves maintenance, delivers and starts diagnosis. |

## On-disk layout

`<root>` is `<state>/runtime`, per profile. A flat runtime (`~/.openprogram-dev/runtime`) has no `current`; seeding refuses a non-empty `<root>` without `.seeding`.

```
<root>/
  current, current.prev, current.lock   pointer, previous pointer, writer lock
  developer.json                        developer mode only
  .seeding                              while first-run extraction runs
  switching                             pid and deadline while the worker is held down
  pending-rollback                      rollback the launcher applies
  repo/                                 bare Git repository
  repo-backups/                         git bundles, last 3
  work/<task>/                          linked worktree per task
  versions/<id>/, versions/.staging-<update>/
  bases/<base>/                         Python, packages, Playwright, Node, npm, uv, Git
  toolchain/<lock-sha>/                 node_modules for Web and TUI builds
  pristine-frontend/<sha>.zip           Web and docs bundle, shared by content
  identity/                             macOS helper; Windows and Linux launcher
  bin/                                  stable command launchers
  bootstrap/restore_version.py, versions.py    stdlib only
  boot/<id>.attempts .migrating .desktop-failed .desktop-ready
  shell.json, shell-relaunch            open shell; relaunch request
  trials/<update>/                      temporary data, logs, sandbox profile
  unapplied/<stamp>/                    captured direct edits
  unreplayable/<release>/               saved patches
  trash/                                versions being deleted

versions/<id>/
  venv/          pyvenv.cfg home = bases/<base>/python, system site packages on
  desktop/       real Electron main process
  version.json   id, commit, base, shell_compat, built_by, built_at, components, parent, frontend_sha
  files.tsv      relative path, size, mtime_ns of every sealed file
  pristine.zip   every sealed file except the frontend bundle
```

**Ids, sizes, refs**

| Item | Value |
| --- | --- |
| Version id | `<UTC yyyymmddThhmmssZ>-<12 hex of the commit>`; characters `[A-Za-z0-9._-]`, validated by every reader |
| Base id | `py<major.minor>-<16 hex>` of `uv.lock`, the dependency section of `pyproject.toml`, `product-runtime.json` |
| Sizes | Base about 1.5 GB, once per dependency set. Version about 160 MB, 136 MB of it the bundle: an APFS clone, a full NTFS copy. |
| Identity | `layout.current_runtime()` from `sys.prefix`. On Windows the venv's `pythonw.exe` starts the base interpreter as a child, so the process image path is never used. |
| `refs/heads/local` (HEAD) | The line the current version is built from. Moves only at commit of a switch or when a manual pointer move is reconciled. |
| `refs/heads/release` | Official line |
| `refs/heads/op/wt/<task>` | Each task; the namespace Sandbox makes writable |
| `refs/openprogram/version/<id>` | Pins each retained version's commit |
| `refs/openprogram/undone/<update>` | Previous tip after an undo |
| Durability | `repo/` is the only home of the owner's commits: `core.fsync=committed,loose-object`, a bundle after each successful switch, `runtime/repo-backups` in `operations/backup.py` `INCLUDED`. |

## Pointer

```
schema=1
generation=17
version=<id>
base=<base>
last_good=…              last_good_base=…
previous_good=…          previous_good_base=…
probation=u_7f3a9c       probation_deadline=1794134010
writer=controller
```

ASCII `key=value` lines, readable from C, batch, Python, Node and shell. Names and meanings are frozen. `probation` is empty when no switch is being verified.

1. Take `current.lock` with exclusive create; break it past 10 s.
2. Read `current`; on a `generation` mismatch release and fail.
3. Write `current.<pid>.tmp` with generation + 1, fsync. Copy `current` to `current.prev` the same way; the write ending probation stores the committed pointer there, so a repair cannot bring back an expired probation.
4. POSIX: rename, fsync the directory. Windows: `MoveFileExW` with `MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH`, retried 20 times at 50 ms on access or sharing errors.
5. Release the lock. A lock that cannot be removed does not undo the move; it expires by age.

- **Implementations**: `versions/pointer.py`, JavaScript in the shell, C in the launcher, `bootstrap/versions.py`. No symlinks, no junctions.
- **What a switch replaces**: This one file, after the worker has stopped. `versions/` and `bases/` are never rewritten once sealed, so an interpreter or DLL that a process or a scanner still holds is never in the way of a switch; it only delays retention.
- **Writers**: Controller, launcher guard, shell recovery page, `bootstrap/versions.py`, installer
- **Missing or unparsable**: Rebuilt, never reseeded: from `current.prev`, else `rebuild-pointer` picks the newest version whose commit is reachable from `local`, `writer=bootstrap`.
- **Rollback conflict**: Reread; `version` no longer the candidate means done. Still failing at the deadline: write `pending-rollback`, applied by the launcher.

## Building

Run by the controller in `versions/.staging-<update>/` from the task's worktree, or a temporary detached worktree for a kind without one.

### Prepare

1. Disk: a new base if needed, the version, the trial copy and 2 GB of margin; else abort with both sizes.
2. Classify paths with `delivery/activation.py`.
3. Base: reuse, or `build-base.sh`/`.ps1` into `bases/.staging-<id>`, the recipe `build-product-runtime.sh` also calls. Unchanged pins are cloned. Needs network. A changed Python minor aborts: the launcher is compiled per minor.
4. Venv, then the base renamed into place after `verify-product-runtime.py` passes.

### Assemble

1. `git archive <commit> openprogram pyproject.toml` into site-packages; generated dist-info.
2. Frontend: cloned if no `web`, `docs`, `tui` component changed; else `stage-release-assets` with `--node-modules <toolchain>`. A changed lock runs `npm ci --ignore-scripts`.
3. `desktop/` from `git archive` of `apps/desktop/main*`.
4. `apps/desktop/shell/compat.json` outside the shell's range aborts: “this change needs a new signed shell release”.

### Seal

1. `compileall --invalidation-mode unchecked-hash`.
2. `version.json`, `files.tsv`, `pristine.zip`; fsync everything; rename to `versions/<id>`.

## Trial

| Aspect | Value |
| --- | --- |
| Process | `trial/instance.py`. Signed launcher with `--root trials/<update>/fake-root`, `HOME` and `USERPROFILE` = `trials/<update>/home`, `OPENPROGRAM_WEB_PORT` = free loopback port, `OPENPROGRAM_TRIAL=1` |
| Started | Web server, runtime, tools, job runner, startup recovery on the sanitized copy |
| Not started | Scheduler, cron, always-on ticker, channels, MCP server and clients, release check, service installation, update sweep, idle-session watcher, nightly reorganizer, config hooks, subscription catalog refresher, Programs watcher. Decided in `runner.py:trial_mode()` |
| macOS | `sandbox.sb`: writes only in the trial directory; live state reads denied except `versions/<id>`, `bases/<base>`, `trials/<update>` and ancestor metadata; network only to the trial's worker port and fake model port |
| Linux | bubblewrap with the same rules where available |
| Windows | No OS sandbox: temporary data, a separate port and the sanitized copy are the only isolation. The progress line during the trial and the result both say the test could reach other files on the computer. `PATH` is the base's Python plus the Windows system directories. The check that the launcher follows a moved pointer is skipped. |

| Trial check, in order | Rule |
| --- | --- |
| 1 Baseline | The old version on the copy records doctor rows |
| 2 Cold start | Reaches `/healthz` within 120 s, extended up to 30 minutes while `boot/<id>.migrating` names a process that still runs |
| 3 `system_probe` | Candidate identity, `/healthz`, `/chat`, WebSocket ping, doctor rows under the regression rule |
| 4 Browser probe | With Playwright |
| 5 Full Agent turn | Against `trial/fake_model.py`: one tool call, then a final answer |
| 6 Tests named in the plan | With the version's venv in `work/<task>`. No `pytest-timeout` or `pytest-xdist`; the controller enforces limits |
| 7 Desktop main smoke | The shell's Electron runs candidate `desktop/main.js` headless to the main-ready handshake. Code that throws fails. An App that cannot open a window under the sandbox judges nothing and leaves desktop code to the relaunch handshake |
| 8 Schema guard | `sqlite_master`, `user_version`, `min_reader_schema` and row digests. Dropped tables or columns, changed types, a raised floor or rewritten rows fail without a `Destructive-Migration: <name>` trailer. Conversation logs, function logs, `revisions.jsonl`, `run_index.jsonl` may only grow |
| 9 Updater self-test | The candidate's controller switches and rolls back between dummy versions, the signed launcher reads its pointer, its sweep runs on a synthetic update, and old code reads what it wrote |
| 10 Rollback rehearsal | The old version starts on migrated data and reads a migrated execution and conversation. Skipped only under the trailer, and then the result must say rollback needs the backup |
| 11 Independent verifier | Job source `self_update_verify` in the live worker, read-only tools, frozen plan, signed receipt, 15 minutes. Gets the diff and plan, not the author's reasoning |

- **Regression rule**: Compared with the old version on the same copy. Only a row that was OK and stopped being OK blocks.
- **Cleanup**: Trial directory deleted on pass. On failure logs and evidence stay 7 days; the data copy goes at once.

**Data copied by `trial/data_copy.py`**

| Data | Rule |
| --- | --- |
| SQLite | Online backup API. Over 4 GB, the largest databases are schema plus a sample. Migration time is scaled to full size; beyond 30 minutes stops the update, and an unsampleable database stops it with “migration untested”. |
| Copied | `config.json` without hooks, agents, projects metadata, last 3 conversations, `programs/`, skills, program sources; models without secrets plus one loopback default; a fresh `owner.json` |
| Never copied | `auth/`, `mcp_tokens/`, `mcp_servers.json`, channel state, `chrome-profile/`, `runtime/`, `self-updates/`, `worktrees/`, logs, recordings, the files applications keep (`programs/.runtime/files/`, meetings among them), `*.pid`, `*.port`, `*.lock` |
| Sanitizing | Run state is the run-table rows on each log's `turn.rows` lines. Copied logs are folded with the worker's run tables and closing rows appended: executions `interrupted`, attempts end, waits and commands close, effects, intents, admissions, finalizations and reservations settle, an unsettled restart intent is removed. Queued and running jobs end in `jobs.json`; `execution.auto_resume_window_seconds` = 0. Reading back must find nothing open; a conversation with no session log stops the trial. |

## Activation

| Step | Action |
| --- | --- |
| `quiescing` 1 | Wait up to 10 minutes for no running task; checkpoint what runs with `delivery/restart.py`. Give up at 30 minutes. |
| 2 | Probe the old version; store doctor rows and subsystems as reference. Only `/healthz` or identity failing aborts. |
| `activating` 3 | Write `switching`, `enter_maintenance` with a deadline. Owner messages and scheduled or always-on wakes go to `self-updates/held/` (`control/held_turns.py`): “Switching versions; this runs as soon as that finishes.” The verifier source stays admitted. |
| 4 | Checkpoint anything started since step 1. |
| 5 | Journal `{update, from, to, generation}`; stop the worker without unloading its service definition. |
| 6 | With a destructive trailer: snapshot every `*.db`, `projects/`, `sessions/`, `functions/`, `memory/`, `active/`, `revisions.jsonl`, `run_index.jsonl`, `config.json` to `backups/pre-switch-<update>/`. |
| 7 | Compare-and-set the pointer: candidate, `probation`, deadline now + 600 s. |
| 8 | Start through the launcher; up to 120 s for candidate identity, 30 minutes with migration progress. |
| `verifying` 9 | `system_probe` under the regression rule; subsystems against step 2. |
| 10 | Turn check: a real turn, the owner's default model, one read tool call, the single admitted job. Provider or network error: inconclusive, no rollback. The candidate's own code failing: rollback. |
| 11 | Leave maintenance, remove `switching`; run held turns, resume tasks, tell the owner. A held turn is deleted only after it ran or its reply exists; three failures move it to `held/failed/`. |
| 12 | Probation 120 s: same worker pid, no subsystem regression. If `desktop` changed, relaunch the shell; main-ready and window-loaded within 30 s. |
| 13 | Commit, each step idempotent: pointer with shifted good pairs and empty probation; `git update-ref refs/heads/local <candidate> <base>` and `refs/openprogram/version/<id>`; deliver. Deletion belongs to retention. |

`/api/diagnostics` reports `subsystems`: scheduler, always-on, each channel, job runner, as running, deferred or failed. Every switch is a worker restart; the hot level exists only for user Programs.

## Failures

| Failure | Action | Phase |
| --- | --- | --- |
| Build error, no network, conflict, no disk | Drop staging, keep `work/<task>` | `aborted` |
| Trial check, timeout, verifier rejects | Stop candidate; version kept until retention | `aborted` |
| Tasks past the limit, or cancel | Nothing was closed | `aborted` |
| Old `/healthz` or identity fails before the switch | Nothing changed | `aborted` |
| Controller dies before the pointer moves | Watchdog or service manager; resumes from the phase, restarts the old worker. Maintenance expires otherwise | continues |
| Pointer write fails | Restart old version, leave maintenance | `aborted` |
| Candidate does not start | Pointer back, start old, probe | `rolled_back` |
| 2 abnormal ends on probation | Launcher guard returns the pointer; next worker start records it | `rolled_back` |
| Probe, subsystem regression, turn check, pid change, shell handshake | Pointer back, start old, probe | `rolled_back` |
| Controller dies after the pointer moved | Healthy: candidate's watchdog relaunches it. Unhealthy: launcher guard. | continues, or `rolled_back` |
| `verifying` past 390 s, or `probation_deadline` passed | Pointer back, by controller or launcher | `rolled_back` |
| Reboot during `verifying` | Launcher runs the candidate on probation; controller restarts | either |
| Commit step fails after the pointer update | Each sub-step retries on resume | `succeeded` |
| Old version fails its probe after rollback | Leave maintenance, `recovery.log`, recovery page | `needs_manual_recovery` |
| Days later, version will not come up | Guard, 3 abnormal ends in 10 minutes: pointer to `last_good`, or `previous_good` when `version` is `last_good` | none |
| Fallback will not come up | Recovery page; CLI installs use `openprogram versions` | none |
| Direct-edit capture fails | Launcher starts the fallback | none |

Every failure writes to the origin conversation; each from trial on starts the read-only diagnosis Job. After a destructive migration the result names the backup; `openprogram versions restore-data <backup>` restores it.

## Undo

| Target of `undo` | Path |
| --- | --- |
| Retained version, no later commit kept | `undo_to`. Skips building, runs trial, activates. At commit `local` moves there; old tip at `refs/openprogram/undone/<update>`. |
| One commit with later commits | `undo_commit`. `git revert` in `work/undo-<short>`, normal lifecycle. A conflict aborts and shows the files. |
| Version no longer retained | Built from its commit, reachable through `local` or `undone` |

| Terminal | Effect |
| --- | --- |
| `versions list` | Commit, date, summary; current, last good, previous good |
| `versions use <id>` | Asks a responding worker to checkpoint (60 s, failure ignored), stops it, moves the pointer with `writer=bootstrap`, restarts |
| `versions restore-data <backup>` | Restores a `pre-switch-*` snapshot with the worker stopped |

`bin/openprogram versions` runs `bootstrap/versions.py` on the base's Python before any version starts. A pointer move with `writer` launcher, shell or bootstrap is reconciled at the next healthy start: old tip under `undone`, `local` and `last_good` to the running version.

## Retention

- **Kept**: `current`, `last_good`, `previous_good`; 5 most recent successful versions; each update's `controller_version` and `candidate_version` while non-terminal or queued; the version an open shell loaded (`shell.json`, live pid); versions whose `boot/<id>.attempts` was touched in 10 minutes; the frontend zips kept versions name
- **Deletion**: Rename to `trash/<id>`, then delete. A read-only file, such as a Git object on Windows, is made writable and tried again. Unreferenced bases go the same way.
- **Left behind**: A tree a running process holds, or a file that stays locked. The pass lists them in `Plan.remaining`, logs them, and the next pass tries again.
- **When**: After `succeeded` and at worker start, never while the slot is held. Failed candidates after 7 days, `work/<task>` from aborted updates after 14.

## Launcher and shell

| Launcher step | `runtime-launcher.c`, never self-updated |
| --- | --- |
| 1 | `developer.json`: follow it, nothing else |
| 2 | Read `current`, else `current.prev`, else `rebuild-pointer`. Apply a `pending-rollback` naming `version`. |
| 3 | Expired `probation_deadline`: the fallback below |
| 4 | Fallback is `last_good`, or `previous_good` when `version == last_good`. 3 attempts in 10 minutes (2 on probation): compare-and-set to it, `writer=launcher`, append to `recovery.log`. |
| 5 | `versions/<version>` missing: fallback |
| 6 | Stat `files.tsv`, compare listings of `site-packages/openprogram` and `desktop/`; a difference runs the capture |
| 7 | Append a start to the attempts file |
| 8 | macOS: `dlopen` the base's libpython, `PyConfig` isolated. Windows, Linux: start the venv Python. |

| Part | Rule |
| --- | --- |
| Attempts | The worker truncates them every 10 minutes and on clean shutdown, and a start losing the worker lock takes its entry back, so entries count abnormal ends only |
| Service managers | launchd, Scheduled Task and systemd all call the stable launcher path |
| macOS helper | `identity/OpenProgram.app` keeps one path and signature, so privacy grants stay; it carries `com.apple.security.cs.disable-library-validation` |

| Shell mode | `apps/desktop/shell/loader.js` |
| --- | --- |
| Developer | `developer.json` exists |
| Embedded | `Resources/instance.json` or `Resources/runtime` exists; `<root>` is not read |
| Managed | Seed if needed. Read `current`, add the asar's `node_modules`, await `start({runtimeRoot, versionId, shellVersion})` from `versions/<id>/desktop/main.js` (30 s, resolved when the first window loaded). Failure: `boot/<id>.desktop-failed`, the fallback's `desktop/`, then `recovery.html`. |

- **Recovery page**: When `/healthz` fails for 120 s with no switch or migration, and the version is off probation or has no fallback. Lists the versions Settings shows, numbered from `version-numbers.json`, without never-committed candidates. Picking writes `writer=shell`. Offers re-seeding code, never over a non-empty `repo/`. Needs neither Python nor the worker.
- **Stopping the worker**: Before the page moves `current`. POSIX: `SIGTERM`. Windows: a `worker.stop` request the worker reads, 8 s for an orderly exit, then `taskkill /T /F`. A worker still alive after 20 s changes nothing.
- **`shell_compat`**: A range: the shell declares min and max, each new shell accepts the previous compat. `spawnWorker` and the recovery and undo lists filter by it.
- **During a switch**: `appInstallInProgress()` reads `switching` on every platform: a live pid inside its deadline makes the shell wait instead of spawning or restarting.
- **Always available**: Native menu item “Go back to a previous version” (File menu on Windows and Linux), needing nothing from the worker

## Concurrency and data

| Subject | Rule |
| --- | --- |
| Worktrees and slot | Any number of `work/<task>`. One update holds the slot; others wait in `queue.json`, FIFO. `controller.lock` per update prevents two controllers. |
| Admission | Closes only from activation step 3 to step 11 |
| Schema and config | Changes are additive; old code tolerates unknown tables, columns and keys |
| SQLite reader floor | A store keeps `min_reader_schema` beside `PRAGMA user_version` (`state/store/reader_floor.py`), refused only when newer than the code knows. Run state needs none: older readers skip unknown tables and columns on log lines. |
| Migrating store | Writes its pid and start time to `boot/<id>.migrating` once and removes it when done; readers check that the process still runs (`versions/store.py` `migrating_process`) |
| Destructive migration | Needs the trailer, is backed up at activation step 6, and is stated in the result, the rollback result and `versions list` |

## Direct edits to a running version

At next start a `files.tsv` mismatch runs `bootstrap/restore_version.py <version>`. The owner is told once. Built-in applications are not hot-loaded when `layout.managed()`; developer checkouts keep hot loading.

1. Compare hashes with `pristine.zip` and the frontend zip; only metadata differs: rewrite `files.tsv`, stop.
2. Save changed and added files and a patch under `unapplied/<stamp>/`.
3. Restore from the zips, removing added files except `__pycache__`.

## User Programs

| Item | Rule |
| --- | --- |
| Check | Success records `refs/openprogram/checked` in the package's repository. The loader reads only that ref; none means pending. A clean package with a HEAD migrates once. |
| Import | From `<state>/programs-cache/<name>/<sha>/`, extracted by `git archive`. A dirty copy keeps serving: “Uncommitted changes. The last checked version is still loaded.” |
| Replace | Import the new commit; on failure re-import the previous, `state="error"`. Old version disposal waits up to 30 s for in-flight calls, then retries. |
| Errors | `_debug_registry_error` feeds the `load_error` API; watcher failures log at warning; no Git binary says “Git is not available”. |

## Official updates

Discovery stays in `update-service.js`. Assets: `version-<platform>.tar.zst`, `repo.bundle`, `SHA256SUMS`, signed manifest, plus `base-` and `toolchain-` when changed.

1. `official/replay.py` verifies assets and fetches the bundle into `refs/heads/release`.
2. No user commits: unpack the prebuilt version, go to trial.
3. User commits: in `work/official-<version>`, cherry-pick `old_release..local` oldest first. A conflict saves `unreplayable/<release>/<sha>.patch` and continues.
4. Build, trial, activate with `kind = official`, one record per candidate, by `control/official_update.py`. No independent verifier. The old tip is saved under `undone`.
5. A failed clean replay retries with user commits dropped newest first, at most 5 times, ending at the unmodified release.

A release needing a `shell_compat` outside the shell's range waits for the DMG or EXE shell update.

## Development instance (`dev_deploy`)

A change made in the development instance is a commit on `dev`, and deploying it is the update. The stable instance is the official App, which only its own updater changes, so nothing here waits for it. See [Development instance](https://fzkuji.github.io/OpenProgram/docs/reference/design/distribution/dev-instance.html). The detached controller runs from a private copy (`delivery/controller_bundle.py`) with neither a session nor a profile in its environment.

### Land

1. Wait for the calling turn to be saved.
2. Rebase the candidate onto `dev`.
3. `git merge --ff-only <sha>` in the primary checkout, up to 10 tries. A rebase conflict or overlapping dirty file: `aborted` with the list.

### Deploy

1. `openprogram dev deploy <sha>`, unless the instance already serves it. This restarts the worker that asked.
2. `system_probe` and browser probe on `18200`. Pass: `succeeded`, delivered by the restarted worker. Fail: `aborted`; the commit stays on `dev` and the next commit fixes it.

Undo here is `git revert` on `dev`, submitted like any change. The trial engine and version layout run in tests with temporary `HOME` and ephemeral ports.

## Packaging

| Item | Rule |
| --- | --- |
| Signed | Electron, `app.asar` (loader, recovery page, node-pty), launcher, macOS helper. Without Developer ID, `local_signing.py` gives the helper a stable identity. Files in `versions/` and `bases/` are unsigned and unquarantined. |
| Seed | `Resources/seed/`: `base.tar.zst`, `version.tar.zst`, `repo.bundle`, launcher, helper. `.seeding` is written first and removed last; an interrupted seed restarts. A non-empty `repo/` is never overwritten. |
| Git | Pinned dugite-native on macOS and Windows; `<base>/git/bin` first on `PATH`, on Windows `<base>\git\cmd` |
| Windows | Per-user NSIS installs the shell only. A fresh install runs no PowerShell before it installs. On an upgrade, when `OpenProgram.exe` and `resources\app.asar` are there, `prepare-upgrade.ps1` stops only processes from the shell's root. Every hook's text goes to `powershell.exe -Command`, not `-File`, so a Group Policy that allows only signed scripts does not stop it. On an uninstall `remove-background.ps1` also stops the worker and removes its logon task; `<root>` and the user's data stay. |
| CLI | `install-release.sh`/`.ps1` adopt `<root>` and `current`, migrating `runtime/cli/releases` |
| Mode flag | `layout.managed()` replaces `OPENPROGRAM_IMMUTABLE_RUNTIME`; embedded mode keeps it |

Developer mode: `<root>/developer.json` is `{"checkout", "python"}`. The shell and launcher start from the checkout with no pointer, trial, guard or capture.

## Implementation status

| State | Items |
| --- | --- |
| Built | State machine and schema 2, queue, switch controller and launchers on all platforms, controller exit watch, watchdog, held turns, subsystems, sweep, every `self_update` action, version store, pointer, launcher, retention, trial engine, release fetch and replay through `openprogram upgrade`, thin shell loader, seed, recovery page, handshake, relaunch, CLI seed installers |
| Unverified | Windows: no part of the version store has run there. Its branches are tested through stand-ins and a cross-compiled launcher. `windows-desktop` runs the shell checks on Windows; `windows-core` runs the launcher test only. |
| Not done | No Windows App or Windows update files are published: the one Release run that built them failed there. Linux thin Apps and signed update files are published; a switch on an installed copy is not yet observed. The macOS App embeds its runtime unless `OPENPROGRAM_RELEASE_MAC_THIN` is set. macOS privacy-grant gate needs a human click. |
| Kept for now | `legacy_app`, `delivery/bootstrap.py`, the App path of `control/supervisor.py`, `repair/owner_repair.py`, `owner_terminal.py`, until published Apps are thin. `package_protocol.py` while `native_checks.py` and `ui_checks.py` read it. |

[Self-update for users](https://fzkuji.github.io/OpenProgram/docs/capabilities/self-update.html) · [Stable release updates](https://fzkuji.github.io/OpenProgram/docs/reference/design/distribution/automatic-updates.html)
