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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 94 additions & 2 deletions lab/server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ The local server designed in `docs/design/Agent-Integration.md` (fork #131, bran
`design/agent-integration`). Slice 0: the version-1 contracts, golden examples and a parser.
Slice 2: the attach-only read server ([below](#slice-2-the-attach-only-read-server)). Slice 3: the
durable control plane ([below](#slice-3-the-durable-control-plane)): leases, request records,
tickets and events in SQLite. Nothing presses a button yet: that is Slice 5.
tickets and events in SQLite. Slice 5 ([below](#slice-5-leased-actions)): `stop_program`, the first
leased action, and `cfr_batch`, allowlisted console lines for debugging. Nothing starts a program yet.

| Path | What |
|---|---|
Expand All @@ -26,6 +27,10 @@ tickets and events in SQLite. Nothing presses a button yet: that is Slice 5.
| `pa_lab/db.py` | The SQLite file: migrations (`PRAGMA user_version`), owner-only file, `BEGIN IMMEDIATE` writes |
| `pa_lab/control.py` | Leases, idempotent requests, tickets, events, `next_events`, reconciliation, compaction |
| `tests/test_{db,control,control_concurrency,control_mcp}.py` | Slice 3's tests: restarts, threads and processes racing, kills mid-write |
| `pa_lab/actions.py` | Leased actions (Slice 5): `stop_program`, the channel request it sends and how its reply is read |
| `tests/test_actions.py` | Slice 5's tests: the ticket, retries, refusals, UI takeover, app restart, a terminal event before the response |
| `pa_lab/cfr.py` | The `cfr_batch` allowlist: allowed commands, bounds, the batch's worst-case time |
| `tests/test_cfr.py`, `tests/test_cfr_batch.py` | Slice 5b's tests: every allowed and refused line form; the batch's refusals, journal, save staleness and races |

Stdlib only (Python 3.8+), so no venv: the MCP transport is small enough to write on
`http.server`. Run the tests from the repo root:
Expand Down Expand Up @@ -137,7 +142,9 @@ python3 -m pa_lab serve --config ~/.config/pa-lab/server.json
"profile": "lab-B"}}}
```

The config is the server's own, closed, and must list exactly `B`; it never reads
The config is the server's own, closed, and must list exactly `B`. `consoles.B.channel_owner`
(optional, one word, default the profile) is the token Slice 5's actions claim the app's channel
with; it never reads
`~/BDSPLab/consoles.json`. A Claude Code client adds it as an HTTP MCP server at
`http://127.0.0.1:8765/mcp` with the header `Authorization: Bearer <token>`.

Expand Down Expand Up @@ -264,3 +271,88 @@ every event after an active cursor (one used in the last 7 days), every event of
and every pending record; finished records go after 7 days. A cursor behind the compacted range
is refused (`invalid_arguments`, field `after_seq`, `evidence.compacted_through`), never served
with a silent gap.

## Slice 5: leased actions

Built so far: `stop_program`, the first tool that changes what the app does, and `cfr_batch`
([below](#cfr_batch)). `preflight_program` and `run_program` need app-side commands first; see the
list in the PR that added this section.

**A leased action is a ticket.** `stop_program(console, request_id, lease_token)` returns its
request record at once: `pending` until the app reports the outcome, which arrives as a
`request_completed` / `request_failed` event (`next_events`) and in `request_status`. The tool
does not wait for the program to stop. `ControlPlane.begin_action` stores the call in one
transaction with the lease check: an exact retry gets the stored record and sends nothing; the
lease must be held by the token (an idle lease is renewed by the call); a program that is not
`running` completes at once with `outcome: not_running`; otherwise the record is `pending` and
remembers the app instance it was sent to (`requests.instance_id`, migration 2).

**The channel request** (Lab.md "Requests", "Owner") is fixed text:

```
owner lab-B
request <request_id>
owner claim lab-B
stop
```

The daemon claims the channel with `channel_owner` before each action rather than once at
attach, so it works across app restarts and beside `lab/scripts/lc.sh`, which uses the same
default token. The app puts `request_id` on `program.last_transition` and keeps it from
`stopping` to `stopped`.

**What resolves the ticket.** The app's report, applied by `observe` on every read of
`console://B/state`, every `request_status`, and every poll of a waiting `next_events`:

| The app shows | Ticket |
|---|---|
| `stopped`, `last_transition` `{stop, lab, <this request_id>}` | completed, `outcome: stopped` |
| `stopping` with that transition | still pending |
| `stopped` by `program` or `error` at or after the call | completed, `outcome: ended` (the run's own end) |
| a UI Start/Stop at or after the call | failed, `console_held_by_user`; the lease becomes `user` |
| another `instance.id` | failed, `app_unavailable`, `evidence.reason: instance_replaced` |
| (the stop line failed and nothing runs) | completed, `outcome: not_running` |
| (the stop line failed otherwise, e.g. `owned by <other>`) | failed, `app_unavailable`, the journal in `evidence` |
| (no journal within 7 s and the request still in the inbox) | withdrawn; `refused`, `timeout`: nothing was sent |
| (no journal within 7 s and the app took the request) | still pending; the rows above resolve it |

A stop by this lease holder ends `agent_running` as before (`lease_changed`, reason `run_ended`).
`begin_run` (Slice 3) is still entered only by tests: `run_program` will call it.

### cfr_batch

`cfr_batch(console, request_id, lease_token, lines)` is for debugging between runs: 1-200 lines of
the app's console commands (Lab.md "Console"), sent under the lease as one channel request after
the same `owner` / `request` / `owner claim` lines as `stop_program`. Raw writes to `Lab/inbox`
are still not exposed: `pa_lab/cfr.py` checks every line before anything is stored or sent.

| Allowed | Bounds |
|---|---|
| `press BTN[+BTN] [hold] [release]` | buttons `A B X Y L R ZL ZR PLUS MINUS LCLICK RCLICK HOME` (no `CAPTURE`); hold, release 0-10000 ms |
| `dpad DIR [hold] [release] [BTN[+BTN]]`, `stick L\|R x y [hold] [release] [BTN[+BTN]]` | x, y -1..1 (3 decimals) |
| `wait ms` | 0-30000 |
| `taps DIR N [all] [hold] [release] [still]`, `walk x y [max] [still] [BTN[+BTN]]` | N 1-20; max 200-10000 |
| `shot LABEL`, `shots LABEL count [interval]` | label `A-Z a-z 0-9 _ -`, 1-64; count 1-10; interval 100-5000 |
| `detect D`, `wait_for D [timeout]`, `expect D [timeout]`, `game_open` | detector names only (no image path); timeout 0-30000 |

Everything else is refused (`invalid_arguments`, `field` = `arguments.lines[i]`): channel
commands, `close_game`, `history`, `snapshot`, `state`, game-registered commands, comments, blank
lines and lines not in canonical form (single spaces). The sum of the lines' worst cases must fit
in 60 s (`field` = `arguments.lines`), so the call, which waits for the journal, is bounded.

The call also refuses (stored, nothing sent) unless the program is `stopped` on a program panel,
the controller `ready` and the video `live`. Then it marks `console://B/save` stale (reason
`cfr_batch`, kept in the database across restarts) before sending: only a program-authored save
newer than the batch makes the fact `known` again.

| The journal shows | Record |
|---|---|
| every line `ok` | completed, `outcome: done`, `journal` |
| a batch line failed (an `expect` timeout, a refused press) | completed, `outcome: line_failed`, `failed_line` (1-based), `error`, `journal` |
| the owner lines failed (`owned by <other>`) | failed, `app_unavailable`; nothing ran |
| (nothing in time, request still in the inbox) | withdrawn; refused, `timeout` |
| (nothing in time, the app took it) | failed, `timeout`; it may have run in part |
| (the app restarted while it was pending) | failed, `app_unavailable`, `evidence.reason: instance_replaced` |

An exact retry sends nothing; a retry of a ticket left `pending` (the daemon stopped while
waiting) collects its journal.
4 changes: 3 additions & 1 deletion lab/server/pa_lab/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,9 @@ def _serve(path: str) -> int:
for reader in readers.values(): # restart reconciliation: apply what the app shows now
reader.console_state()
plane.compact()
server = mcp_server.make_server(cfg.port, token, readers, control_plane=plane)
server = mcp_server.make_server(cfg.port, token, readers, control_plane=plane,
channel_owners={name: entry.channel_owner for name, entry in cfg.consoles.items()
if entry.channel_owner is not None})
logging.getLogger('pa_lab.server').info('serving %s on http://127.0.0.1:%d%s',
', '.join(sorted(readers)), server.server_address[1],
mcp_server.ENDPOINT)
Expand Down
Loading