Compare commits

...
Author SHA1 Message Date
dev-driver 4f61586bb6 docs(network): say what a failed replace can leave in the key folder
The replace section said a replace that fails after the account takes
the code changes nothing here. The enrollment's record doesn't change,
but the key swap is a file move outside that record's rollback. If
putting the old key back also fails, the old key is left as
key.json.prev, and a staged key.json.next can remain. The section now
says where those files are and what to do with them before enrolling
again.
2026-11-12 18:25:39 +00:00
Mike Schwarz daeafc305e feat(network): enroll in an account and connect seats by name (#3007)
Adds network enrollment: rig network enroll takes a short-lived, single-use code from the account page and records this daemon's installation, so seats can be connected by name; disconnect works from the account side. An enrollment can be replaced whole (--replace), turn-first and all-or-nothing. Changes to one installation's list run one at a time. When the account can't answer, or it's unknown whether it took the code, the CLI says so and says what to do next, rather than guessing. Migration 163 adds the installations table.
2026-11-12 10:15:14 -08:00
Mike Schwarz 5f2dc3fab2 fix(onboarding): fit a team to the person's logins before it starts (#3077)
The kernel operator's guidance now fits a starter team to the person's providers before recommending it. It starts from the providers chosen at setup, or infers them, and checks only the logins the team needs, before any launch. A provider counts only when its check passes: Codex installed but not signed in isn't theirs. If a seat needs a login the person doesn't have, the operator names that seat and lets them choose before planning.
2026-11-12 10:14:05 -08:00
Mike Schwarz 458062e50e fix(plugins): the Claude directory edition follows handed-on work and keeps its reply route (0.1.2) (#3075)
The Claude directory edition (plugins/claude-directory) moves to 0.1.2: its one skill follows work that another seat handed on, through the row's successors, and keeps its reply route. The bytes are the exact edition the Lab tested. Only the edition's own files change; the full openrig plugin and the npm package are untouched.
2026-11-12 10:13:30 -08:00
Edward Bowie 97114f3fe7 fix(daemon): share process listings across the Codex seats one readiness poll re-checks (#161) (#3061)
Refs #161. When one readiness poll re-checks several Codex seats, the daemon now takes one process listing for that pass and shares it, instead of listing processes once per seat. Each seat's own checks are unchanged and still match by its pane's process. If the shared listing fails, each seat falls back to its own listing, and the poll's cadence doesn't change. A later seat's observation only counts process pairs it saw after its own request began, so an earlier seat's completed pair can't make it read ready.
2026-11-12 08:55:08 -08:00
Mike Schwarz 7fdd8dc0d1 feat: show connected assistants' check-in status in rig ps and rig_team (#3057)
rig ps and the rig_team MCP tool now show each connected assistant's check-in status, read from the daemon's served check-in status (#3023) with the shared wording, so the same state reads the same in every view. An unknown status reads unknown, and an older daemon without the status degrades to the previous listing. A team view with no terminal seats still lists its connected assistants, and a check-in list that can't be read says unavailable rather than showing nothing. The --json output and rig_team's existing fields are unchanged.
2026-11-12 08:54:30 -08:00
Edward Bowie c1b4217b65 fix(daemon): reuse a live Herdr workspace for rig terminal open --provider herdr (#3068)
For #3052. A non-follow rig terminal open <view> --provider herdr now asks the daemon to reuse a live workspace. If one still shows the same view and plan with every tile's attachment confirmed, and Herdr's focus reply names that exact tab and workspace, the open returns reusedWorkspace with opened: [] and keeps the workspace's contents. Otherwise it opens a fresh workspace as before, and its notes name each workspace it kept: an older or different plan, unconfirmed attachments, or a focus Herdr didn't confirm. --window's live-attachment check moved unchanged into one daemon module, exported as @openrig/daemon/herdr-live-workspace, which both paths use. Requests that don't ask for reuse (--window's own call, follow opens, the web UI, the TUI, cmux and rex) behave as before.
2026-11-12 08:43:20 -08:00
billbenetti b1a58fa96c fix(daemon): one standing notice per (parent, child seat) for unclaimed rows routed to a delegation parent (#2988) (#3049)
For #2988. The stuck sweep used to file one finding per unclaimed row whose route was its seat's delegates_to parent, and each finding woke the parent. Those rows now share one standing notice per (parent, child seat), filed to the parent with the unclaimed-backlog lifecycle a seat's own notice already has (#2430, #2752). It stands for every row, listing 20 and counting the rest. New and leaving rows rewrite it in place without a new wake. It closes once every row is claimed, parked, closed or no longer routed to that parent. A dismissed or closed notice holds back only the rows it stood for, until they have newer evidence. An unreadable list keeps the notice open. The notice's mark names the seat that created it, so a handed-on or fallen-back notice still stands for its creator's rows. Only ordinary unclaimed rows routed to the one declared delegation parent are grouped.
2026-11-12 08:42:28 -08:00
Mike Schwarz b67b707ab4 fix(cli): remove the duplicate registration offer #3041's merge restored (#3071)
The squash of #3041 kept the local personRegistrationOffer in packages/cli/src/commands/daemon.ts beside the import of the shared one that replaced it, so the CLI didn't typecheck (an import declaration conflicting with a local declaration). This removes the local copy, its comment and the blank line after it. daemon.ts now equals #3041's reviewed version, and rig daemon start and rig gateway participants print the same offer from person-registration-offer.ts. No behaviour changes.
2026-11-12 08:30:18 -08:00
Mike Schwarz 12a8d43d88 test: stand-in model servers for the delivery conformance suite (#3063)
The delivery conformance suite needs a model that answers deterministically. This adds stand-in servers in packages/test-system/delivery/stand-ins for Claude Code's Messages wire and Codex's Responses SSE wire. They listen on loopback only and answer each turn from a script (say, tool call, error, or a failure mid-stream), with markers, gates and delays a case can control. Each request is logged with its method, path, parsed turn and the received body's byte count and sha256, readable back from the stand-in. It's test infrastructure only; nothing in the product uses it.
2026-11-12 07:28:04 -08:00
Mike Schwarz fbde76cf16 fix(codex): a resumed conversation's guidance stays out of the repository AGENTS.md (#3039)
A Codex snapshot restore or rig up --existing could write OpenRig's managed guidance blocks into a repository's tracked AGENTS.md, leaving the person's worktree modified. A resumed Codex conversation now receives OpenRig's current guidance in its launch instead. Restore carries only the guidance blocks that are absent and readable, optional files stay optional, and the guidance file keeps a single writer. The startup guide describes the behaviour, including the older snapshot case.
2026-11-12 07:25:50 -08:00
Edward Bowie 220880b925 fix(daemon): bound optional recap paths in rebuild briefings (#3055)
A rebuilt seat's briefing listed every optional recap path from its history. It now lists the newest three (output.rebuild_recaps, default 3, with 0 keeping the full list) and a pointer to their shared history folder. Required priming is unchanged, every resolved artifact stays in the handover result, and every older recap stays reachable. If one folder can't cover the history, or the setting can't be read, the briefing keeps the full list, so a malformed config never stops a handover's cleanup. rig config --help names the key. For #2978.
2026-11-12 07:16:17 -08:00
James B. Shields 84c4d5cc4d feat(queue): add exact AND tag filters (#3066)
Queue listings can now be filtered by exact item tags. The CLI takes repeatable --tag, plus --mission and --slice, and the MCP queue tools take a tags array plus mission and slice. Several tags must all match, the filter applies before the result limit, comparisons are exact and case-sensitive, duplicates collapse, and a blank value is refused. Unfiltered listings, scopes, visibility, ordering and the other filters are unchanged. An older daemon may ignore the tag parameters; the clients reject a returned row that lacks a requested tag. Workflow status and step filtering stay separate. For #2728.
2026-11-12 06:43:22 -08:00
Mike Schwarz 59aa8dfee5 fix(skills): tell a team how to reach the person's seat with a question (#3059)
The directory edition of working-with-an-openrig-team, tested end to end, tells a team member how to ask the person's seat a question so the answer wakes the work: create a queue item to the seat's address and block the work on that item's id. The full plugin's skill didn't say so. All three copies of the full skill now carry the same paragraph, one blob, with the generated skill digests updated to match.
2026-11-12 06:35:21 -08:00
Mike Schwarz b256a5320d feat(daemon): a person's clicked answer is an event, partial or complete (#3045)
Steering, Feed and MCP clicks already streamed an event when a person answered an ask, but a Slack click had none. A clicked answer that changes the recorded answers now emits one queue.answer_recorded event after the answer transaction, saying whether the answers are partial or complete. An unchanged click emits nothing, and a failed emit never undoes the answer. The event carries the acting session and the ask's summary with its counts, but not the selected option or the answer text.
2026-11-12 06:34:20 -08:00
Mike Schwarz 891005d6ff docs(install): lead with the release-tagged rigs-skill command, and check install tags at pack:release (#3065)
A newcomer copied the rigs-skill command from the install pages with its placeholder release tag still in it. The README, getting started and quickstart now lead with a copyable rigs-skill install at the release tag, keeping the substitute-your-own-tag guidance second for an existing install. pack:release now checks those three pages and the CLI's two assembled copies (getting started and quickstart, which npm packs) before it packs anything. A missing page, a page without the rigs-skill link, or a link whose tag isn't the release being packed stops the pack, naming each file and line and the rebuild step. It refuses only the release pack, nothing a person runs.
2026-11-12 06:33:00 -08:00
Roberto Campos 609b337316 fix(daemon): return invalid_snapshot_data instead of throwing when snapshot has no sessions (#3069)
If a captured snapshot had no sessions array but a node had startup context, validatePreRestore recorded the invalid_snapshot_data blocker and then threw a TypeError from resolveActiveSnapshotSession, which read data.sessions directly. It now passes the already-normalized sessions value, reading a missing list as empty, so the check returns the structured blocker and restore still refuses with a clear reason. A test covers a snapshot with sessions removed and startup context present. For #3035.
2026-11-12 06:31:17 -08:00
Mike Schwarz fc2ec997f4 fix(pairing): show the requesting machine's self-description quoted everywhere (#3067)
A machine asking to pair describes itself before anyone has trusted it, and that self-description was shown as plain text in the pairing ask, its question, receipts, notices, the forward to the operator, the expired message, the TUI's pairing settings and rig host approve|deny. It's now shown quoted everywhere, through one helper per package, so it reads as the requester's words and not as instructions. In the pairing question a long quoted name is shown whole, or as its longest fitting part marked as shortened, so the question stays within its limit and the person is still asked. DEL, C1 controls, zero-width, bidi and byte-order characters become spaces when the request arrives. The stored and API values are otherwise unchanged, and nothing new is refused.
2026-11-12 06:29:41 -08:00
Mike Schwarz f599bf6da1 fix(cli): rig broadcast prints a held recipient as retained, not sent (#3054)
When a seat's guard or setting held a broadcast, the daemon answered with outcome retained and left that recipient out of its sent count, but rig broadcast printed it as sent, though nothing had been typed into that seat. Broadcast now prints a held recipient the way rig send to several seats already does: retained, not delivered; inspect with rig seat held-messages. Both commands' summaries add the held count, for example 1/3 delivered, 1 held. A held recipient alone still doesn't make the command fail.
2026-11-12 06:27:26 -08:00
Mike Schwarz 1d22b5beb3 fix(compaction): record content-free input refusal diagnostics (#3053)
Managed compaction could stop with draft_input_unknown after a restore map was complete, without saying which input check refused or why it couldn't read the composer. The existing attempt record and rig compact --state gain a content-free inputReadFailure: the preparation or compact stage, the composer or draft-aware check, the reader's status and confidence, a fixed reason, cursor flags and any known timeout. An owed restore failure shows the same diagnostic under lastDelivery. No input text, suggestions, terminal frames, hints or exception messages are copied. Input decisions, send timing, opt-in defaults and replay protection are unchanged. For #3036.
2026-11-12 06:26:00 -08:00
Mike Schwarz 2091001929 feat(plugins): a skill-only edition of the openrig plugin for Claude's directory (#3056)
Claude's directory doesn't take a plugin that starts a local MCP server, and it accepts only md, json and png files. This edition is one skill, working-with-an-openrig-team, that hands work to a local OpenRig team through the rig command, follows it, brings the person the team's questions, records their answers as they gave them, and reads the result, plus a manifest, icon, license and README. It lives at plugins/claude-directory/, outside the npm package and the skill mirror's roots, and the full plugin is unchanged. The bytes are those of the last of three runs against a real one-seat local team (headless Claude Code 2.1.319 on macOS, permissions skipped, OpenRig 0.7.11).
2026-11-12 06:22:12 -08:00
Mike Schwarz d71cca268f feat(daemon): read what needs a person and the answers to it by link (team-operations.v1 needs-me.read) (#3008)
Apps that show a person what needs them had to parse text to find the asks and the answers to them. The daemon now advertises the team-operations.v1 capability with needs-me.read supported and needs-me.answer and needs-me.follow reported as not supported. The attention read gives each item a revision, what it's about and a watermark. Answers linked to an ask are read by reply_to, including an older untagged Slack reply that arrived before the ask's first close. The scoped MCP projection leaves the linked answers out rather than showing other rows, and no existing read is newly refused. Migration 164 adds a partial index on queue_items(reply_to).
2026-11-12 06:20:30 -08:00
Mike Schwarz 9964b37ec6 fix(setup): the kernel operator offers to register the person in its greeting (#3041)
A person who talked to the kernel operator first, without another agent setting OpenRig up, wasn't offered registration: the operator greeted from its startup template, which ran only rig ps --json. The operator's startup context now also reads rig gateway participants before greeting. When nobody is registered, the greeting offers registration, registers only on the person's yes, and on a no says questions can't reach anyone until someone is registered. rig gateway participants ends with the same three offer lines rig daemon start prints, left out with --organization, with --json, or once a person is registered. The offer text moves into one module both commands read, and rig daemon start's output is unchanged.
2026-11-12 05:14:01 -08:00
Mike Schwarz 4c4d0f8628 fix(tui): show a seat the daemon reads as unknown as unknown in the graph too (#3046)
#3012 made the TUI's list, explorer and agent-detail rows show unknown for a quiet seat the daemon reads as unknown, but the topology graph still drew such a seat as idle. The graph's glyph now maps an explicit unknown from the daemon to unknown too, and the comment on #3012's change names exactly the views it covers. Screen motion still shows active, and without a served activity the existing screen fallback stays.
2026-11-12 04:52:22 -08:00
Mike Schwarz 6917f39c0f docs(roadmap): name 0.7.12 as the current release (#3051)
ROADMAP.md still named 0.7.11 as the current release. It now names 0.7.12, links its published release notes, and summarizes it with the notes' own first three sentences, leaving out the source commit. No roadmap item is removed, because the notes don't establish that any listed item is complete.
2026-11-12 04:45:48 -08:00
Nick Kupriianov ca58c761cc feat(daemon): show the agent and its activity on Rex tiles (#2992)
Rex learns a tile's agent and state from OSC 7501 sequences the program writes, but inside an OpenRig tile Claude Code or Codex runs in OpenRig's tmux server and the Rex block runs only the tmux attach wrapper, so every tile looked like a plain shell. OpenRig now relays the agent and its activity, which it already knows, to the selected Rex clients' terminals: the initial state when a tile opens, and each change after. A retry is registered per client, unknown stays unknown after a restart or a retarget, a partial write is terminated, a stop sweeps nothing, and the view open doesn't wait on it. OpenRig's tmux server doesn't enable allow-passthrough, so the relay is the only status writer on those clients, and a root clear removes exactly OpenRig's report.
2026-11-12 04:27:49 -08:00
Mike Schwarz 2c7be1d715 docs(getting-started): say which snapshot rig launch restores a kernel seat from (#3047)
#3031's getting-started text said rig launch kernel <id> restores from the kernel's latest restore-usable snapshot, but the snapshot repository ranks automatic kinds (auto-pre-down, auto-periodic, runtime-switch) above newer manual ones. The guide now names that order, how a plan or an explicit selection overrides it, and the kernel agent's restore default.
2026-11-12 04:11:50 -08:00
Mike Schwarz ab3234b0f3 docs(operator): reuse a permission choice only where it covers the goal (#3062)
The operator's first-team guidance reused any permission choice handed to it ("use it, and don't ask again"), whatever the choice covered. A user-wide rule for rig commands carried in the handoff could then skip the one project offer for the goal's git switch, git commit and test commands, and the person was prompted for each instead. The guidance now reuses a carried choice only where its scope covers the goal's commands and project, and otherwise makes the one project-scoped offer. The defaults named before launch and the single offer are unchanged.
2026-11-12 04:02:15 -08:00
Edward Bowie 339fd41791 fix: correlate no-launch materialization retries (#3042)
A no-launch materialization (rig import --materialize-only) that timed out or lost its reply could be retried only by running it again, which could create a second rig. It now takes --operation-id <uuid>: the daemon correlates the retry with the original operation through the existing operation-correlation contract, and an exact retry returns the original committed receipt (rig and node IDs) with the current state of those resources. A committed empty pod gets a confirmed receipt, and the target rig is recorded in the same transaction, which rolls back on failure. An older daemon that doesn't advertise retry-safe materialization is refused before anything is materialized, naming the upgrade.
2026-11-12 03:37:30 -08:00
163 changed files with 8208 additions and 503 deletions

No files matched your search

+5 -5
View File
@@ -26,9 +26,9 @@ use:
```sh
# Claude Code
npx skills add https://github.com/mvschwarz/openrig/tree/v0.7.11/skills/rigs --skill rigs --agent claude-code
npx skills add https://github.com/mvschwarz/openrig/tree/v0.7.12/skills/rigs --skill rigs --agent claude-code
# Codex
npx skills add https://github.com/mvschwarz/openrig/tree/v0.7.11/skills/rigs --skill rigs --agent codex
npx skills add https://github.com/mvschwarz/openrig/tree/v0.7.12/skills/rigs --skill rigs --agent codex
```
Then type `/rigs` in Claude Code, or `$rigs` in Codex, and say what you want built. The skill has your agent tell
@@ -68,11 +68,11 @@ Requires Node.js 22 or 24 and tmux, on macOS or Linux, and one working Claude Co
### Install it yourself
This runs OpenRig's install script from the `v0.7.11` release. It checks Node.js and npm, installs the latest published `@openrig/cli` with `npm install -g`, runs the Node.js and SQLite check, then runs `rig setup --dry-run` and `rig setup`. The first line prints that plan and changes nothing:
This runs OpenRig's install script from the `v0.7.12` release. It checks Node.js and npm, installs the latest published `@openrig/cli` with `npm install -g`, runs the Node.js and SQLite check, then runs `rig setup --dry-run` and `rig setup`. The first line prints that plan and changes nothing:
```bash
curl -fsSL https://raw.githubusercontent.com/mvschwarz/openrig/v0.7.11/scripts/install.sh | sh -s -- --dry-run
curl -fsSL https://raw.githubusercontent.com/mvschwarz/openrig/v0.7.11/scripts/install.sh | sh
curl -fsSL https://raw.githubusercontent.com/mvschwarz/openrig/v0.7.12/scripts/install.sh | sh -s -- --dry-run
curl -fsSL https://raw.githubusercontent.com/mvschwarz/openrig/v0.7.12/scripts/install.sh | sh
```
If the last step isn't ready, the installer reports `INSTALLED, SETUP NOT COMPLETE` and points to the details from `rig setup` above. Follow that output and any reported Fix, then rerun `rig setup`; the CLI does not need reinstalling. If the only remaining failures are provider sign-ins, sign in to each selected provider as below and continue.
+2 -2
View File
@@ -6,9 +6,9 @@ This isn't a schedule or a promise: we release often, and an item ships when a g
To see what's being worked on, by release and theme, open the [OpenRig roadmap board](https://github.com/users/mvschwarz/projects/1).
Issues labelled `good first issue` are also listed on the [contribute page](https://github.com/mvschwarz/openrig/contribute).
## Released in 0.7.11
## Released in 0.7.12
[0.7.11 is published](https://github.com/mvschwarz/openrig/releases/tag/v0.7.11): OpenRig 0.7.11 is a patch for people running their own agent teams. An ordinary send or work notice now goes into a person's typed draft by default instead of being refused (see Behaviour that changed). See its release notes for what shipped, known issues, upgrade instructions and contributor credits.
[0.7.12 is published](https://github.com/mvschwarz/openrig/releases/tag/v0.7.12): OpenRig 0.7.12 is a patch for people running their own agent teams. When you answer your team, by typing, clicking or qualifying an answer, the answer now goes to an agent that reads it with the question and decides. When no receiving agent is available, your answer waits. See its release notes for what shipped, known issues, upgrade instructions and contributor credits.
## How to help
@@ -395,6 +395,19 @@ Discovery (`server.version` and `server.status`) has a 1 s budget, and
`status()` and `liveness()` share one probe. A request whose reply is lost (a
timeout, a killed client, an unreadable reply) is `unknown`, not failed: the
adapter never closes a session on it and reports `rex_outcome_unknown`.
After the check, the local seats whose tiles opened go to `RexAgentStatusRelay`
(`rex-agent-status.ts`), which writes an OSC 7501 report to the tty of each tmux
client attached to the seat whose `client_termtype` (its XTVERSION reply) names
Rex. Later activity changes (the same hook-or-pane resolution that recovers
prompt wakes in `startup.ts`) are written to each Rex client that doesn't already
have that report; an unknown activity is written as `state=clear`. A client the
relay has no record for (after a daemon restart, or one that moved from another
seat) gets the current report too, a clear included. After a partial write, the
next write to that terminal starts with ST to close the unfinished OSC. The relay
records what each client last took, and a sweep every 5 s lists a shown seat's
clients again, so a new client or a failed write is caught up without another
activity change. A seat found without a Rex client is looked at again when a Rex
view opens it or after five minutes; a failed `list-clients` leaves it as it was.
Herdr and Rex build their layout trees from one grid helper
(`buildTileGrid`, `tile-layout.ts`).
+4 -2
View File
@@ -245,7 +245,7 @@ the sections that were not read are `null`.
| Invocation | Aliases | Declared options |
|---|---|---|
| `rig import <path>` | — | `--instantiate`<br>`--materialize-only`<br>`--workspace-only`<br>`--preflight`<br>`--target-rig <rigId>`<br>`--rig-root <root>`<br>`--cwd <path>` |
| `rig import <path>` | — | `--instantiate`<br>`--materialize-only`<br>`--operation-id <uuid>`<br>`--json`<br>`--workspace-only`<br>`--preflight`<br>`--target-rig <rigId>`<br>`--rig-root <root>`<br>`--cwd <path>` |
### ui
@@ -551,7 +551,7 @@ default-permit record (tag `runner-permission-permit`) opens no row.
| `rig queue show <qitemId>` | — | `--full`<br>`--json`<br>`--host <id>` |
| `rig queue artifact <qitemId>` | — | `--root <name>`<br>`--json` |
| `rig queue transitions <qitemId>` | — | `--json`<br>`--full`<br>`--host <id>` |
| `rig queue list` | — | `-a, --all`<br>`-A, --all-rigs`<br>`--full`<br>`--owned`<br>`--mine`<br>`-o <format>`<br>`--destination <session>`<br>`--source <session>`<br>`--state <state>`<br>`--target-repo <name>`<br>`--limit <n>`<br>`--json`<br>`--host <id>` |
| `rig queue list` | — | `-a, --all`<br>`-A, --all-rigs`<br>`--full`<br>`--owned`<br>`--mine`<br>`-o <format>`<br>`--destination <session>`<br>`--source <session>`<br>`--state <state>`<br>`--target-repo <name>`<br>`--tag <tag>` (repeatable, AND)<br>`--mission <id>`<br>`--slice <id>`<br>`--limit <n>`<br>`--json`<br>`--host <id>` |
| `rig queue overdue` | — | `--rig <name>`<br>`-A, --all-rigs`<br>`--full`<br>`--limit <n>`<br>`--json` |
| `rig queue undelivered` | — | `--rig <name>`<br>`-A, --all-rigs`<br>`--full`<br>`--limit <n>`<br>`--json` |
| `rig queue inbox-drop <destinationSession>` | — | `--sender <session>`<br>`--body <text>`<br>`--body-file <path>`<br>`--tags <tags>`<br>`--urgency <urgency>`<br>`--audit <pointer>`<br>`--id <inboxId>`<br>`--json` |
@@ -562,6 +562,8 @@ default-permit record (tag `runner-permission-permit`) opens no row.
| `rig queue outbox-list <senderSession>` | — | `--limit <n>`<br>`--json` |
| `rig queue erase` | — | `--members <file>`<br>`--rig <id>`<br>`--ids <file>`<br>`--action <action>` (`delete`, `scrub`)<br>`--routine`<br>`--apply`<br>`--actor <session>`<br>`--json` |
`rig queue list` accepts repeated exact, case-sensitive `--tag <tag>` filters and requires every tag to match before the result limit. `--mission <id>` and `--slice <id>` add the exact `mission:<id>` and `slice:<id>` tags. Exact duplicates collapse; blank values are rejected; commas inside a tag are literal. The CLI and MCP report a visibly unfiltered nonempty response from an older daemon, but an empty response cannot establish whether the daemon applied the filter.
### slack
| Invocation | Aliases | Declared options |
+4 -1
View File
@@ -315,7 +315,10 @@ The most useful next pieces of harness work, roughly in dependency order:
`claude-executable-foreground.test.ts` holds that recorder open in private Bash, zsh, dash and ksh panes
to check parent PID, process-group ownership, tmux's pane command and parent-shell
restoration for unmanaged fresh, fork and resume launches. These fixtures do not prove
native readiness, history or answers.
native readiness, history or answers. The provider-shaped half now exists for the delivery suite: local
stand-in Messages and Responses servers in `packages/test-system/delivery/stand-ins/` that a real Claude Code or
Codex can talk to with no account, logging each request's exact bytes. Nothing drives a real program through them
yet.
3. Lifecycle and identity steps (tmux reset, archive/remove).
4. Then pickup, wake and restore scenarios.
+21 -3
View File
@@ -360,6 +360,15 @@ not the destination's file contents.)
- `rig seat launch <seat> --fresh --stop --reason <text>`, which starts a blank conversation; or
- `rig handover <seat> --source rebuild --reason <text>`, which carries durable context.
A rebuild lists the current recap, lineage lessons and restore packet as required
priming. Superseded recaps are optional history, newest first. The briefing shows
the newest `output.rebuild_recaps` paths (default 3) and their shared
`recap-superseded/` folder when that pointer covers the complete history. Other
layouts retain the full list. Set `rig config set output.rebuild_recaps 0` to
always list every path; `OPENRIG_OUTPUT_REBUILD_RECAPS` overrides the setting.
This changes only the briefing: the handover result still records every resolved
artifact, and no recap file is removed.
For Codex rebuilds, OpenRig also carries a complete supported native permission policy read from the live
predecessor's own conversation and process, without adding fresh-launch grants. A later recorded seat permission
or policy choice, or a differing declared successor profile, takes precedence. Missing, stale or unsupported observations keep the existing launch
@@ -615,14 +624,23 @@ daemon's `CODEX_HOME`, else `~/.codex`.
The guidance still goes to the repository `AGENTS.md`, as before, when:
- a layer OpenRig reads sets `developer_instructions`, or can't be read. A launch warning names the file;
- the launch resumes or forks a conversation. Developer instructions on a resume haven't been tested, and an exact
resume puts the guidance back in the repository `AGENTS.md`;
- the seat is restored, even when the restore starts a new conversation. A restore keeps the guidance file its launch
- the launch forks a conversation. Developer instructions on a fork haven't been tested;
- the seat is restored and the restore starts a new conversation. A restore keeps the guidance file its launch
recorded, which for Codex is the repository `AGENTS.md`;
- a handover successor starts (fresh, fork or rebuild). Its launch carries no guidance of its own, so the handover
first puts the seat's missing blocks back in the repository `AGENTS.md` from its saved startup context;
- Codex is older than 0.164.0, or its version is unknown.
A resume of the seat's own conversation, on a snapshot restore or `rig up --existing`, chooses as a fresh launch
does: on Codex 0.164.0 or later with none configured, the guidance blocks the repository `AGENTS.md` doesn't hold go
with the resume as `-c developer_instructions=…` instead of being put back in that file, and the guidance file its
launch recorded isn't changed. A file that already holds blocks keeps them: a block OpenRig wrote whose source has
changed is refreshed, and one edited by hand, or with no record of OpenRig writing it, is left as it is and named. A
block whose source is gone or can't be read isn't sent, and the restore reports it as missing. A seat in a rig without
pods starts its resumed conversation before its startup runs, so its missing blocks are still put back in the
repository `AGENTS.md`. Whether Codex keeps the earlier session's developer instructions as well isn't documented
by Codex; the text sent with the resume is the current one.
A seat's role still arrives as startup text, and the seat-skills line, after the person's yes, still goes to
`AGENTS.md`.
+41
View File
@@ -82,6 +82,13 @@ All of them are server-sent events (`text/event-stream`):
`?replay=all`, no `replay`, or any other value sends the whole log first. A `Last-Event-ID` header (what
`EventSource` sends when it reconnects) sends the events after that id instead, whatever `replay` says.
Live events that arrive during the replay follow it, without duplicates.
When a person clicks an answer on an ask with questions (in Steering, the Feed, Slack or an MCP client), the stream
carries `queue.answer_recorded`: `{ qitemId, actorSession, questionId, answered, questions, complete, summary }`.
`complete: false` means the set is still partial: the ask stays open, and its answers haven't gone back yet. The
event carries ids and counts, not the choice; read the ask for its `humanAnswers`. A click that changes nothing (the
same option again) has no event, and neither does a typed reply, which settles the ask through its own
`queue.updated`. The event is recorded after the answer: if it can't be recorded, the answer still stands, so a
client that re-reads the ask after a gap still sees it.
- **`GET /api/activity/events`**: live only, no replay or ids. Each message is named after its event type:
`seat.activity_changed`, `seat.rung_health`, `proof.judged` or `proof.sources_changed`. It tells a view to read
again; it carries no derived state.
@@ -151,6 +158,40 @@ An outbox entry's `deliveryState` reports the send attempt; only `delivered` con
an open FYI, or a closed ask is not that receipt. The rig-wide reads and their limits are described below; the existing
`outbox/list?senderSession=<session>` read remains available.
### What needs a person, and how their answers link back (`team-operations.v1`)
`GET /api/team-operations/capabilities` says which team-operations jobs this daemon supports, separately from its
build:
```json
{ "contract": "team-operations.v1",
"capabilities": { "needs-me.read": "supported", "needs-me.answer": "not-supported", "needs-me.follow": "not-supported" },
"build": { "semver": "…", "commit": "…" } }
```
A capability reads `supported`, `not-supported` or `unknown`, and a missing key means `unknown`. A daemon without the
route (HTTP 404) predates the contract: keep reading what it already returns. In a source run, `build` is
`{ semver: null, commit: null }`.
With `needs-me.read` supported:
- **What needs the person:** `GET /api/attention?view=<person-id>` (the same read as the Feed). Each queue item adds
`revision` and `about`. `revision` is the request's opaque decision revision: the same value as that row's
`decisionRevision`, and what an answer can name as `expectedRevision` so it applies only to the version the person
read. `about` lists the requests it concerns by id: a row parked on the person is itself the request, and an ask is
about the open rows blocked on it (at most 100; empty when none are recorded).
- **A snapshot watermark:** the response's `watermark` is the newest event `seq` read before the snapshot. Follow
`GET /api/events` from it with `Last-Event-ID: <watermark>`: every event after the snapshot is replayed, some possibly
already reflected in it. Recording one answer of several emits no event yet, so re-read the snapshot (or the row)
rather than relying on events alone for partial answers.
- **The answers returned to a request:** `GET /api/queue/<qitemId>` adds `answers`, oldest first, each
`{ qitemId, by, at, text, episode, recordedIdentity }`. They are found by the answer row's link to the request, not
by its text, so don't parse the `In reply to:` line in an answer's body. `text` is the person's answer without that
footer. `episode` names the park an answer belongs to, or is null. `recordedIdentity` is the identity provenance
recorded when the answer row was created. An answer row's own read has `replyTo`, the request it answers. A partial
set of choices stays on the request's `humanAnswers` until the whole set is returned. A runner's permission request
or a host pairing request is answered in place, with no answer row.
## Route details
- **A rig's queue history:** `GET /api/queue/list?rig=<rig>&updatedSince=<ISO time>&sort=updated` returns the
+18 -11
View File
@@ -180,20 +180,22 @@ user.
**Agents:** if you're setting OpenRig up for someone, load the `rigs` skill and follow it. It carries the install, the
OpenRig view and the handoff to the operator as one procedure. From 0.6.7, OpenRig installs it as `rigs` in
`~/.claude/skills` and `~/.agents/skills` when the daemon starts. To add it manually, use the release tag matching
your installed `rig --version`: replace `<release-tag>` below with that tag, including its `v` prefix.
`rig --version` prints the version and a commit, for example `0.6.11 (379f0a0d)`; the tag is `v0.6.11`.
The skill is in the repository from v0.6.6; on an older install, use the v0.6.6 tag or upgrade first.
Choose the command for the agent doing the setup:
`~/.claude/skills` and `~/.agents/skills` when the daemon starts. For a new install, add it with the command for the
agent doing the setup. Both use this release's tag:
```sh
# Claude Code
npx skills add "https://github.com/mvschwarz/openrig/tree/<release-tag>/skills/rigs" --skill rigs --agent claude-code
npx skills add "https://github.com/mvschwarz/openrig/tree/v0.7.12/skills/rigs" --skill rigs --agent claude-code
# Codex
npx skills add "https://github.com/mvschwarz/openrig/tree/<release-tag>/skills/rigs" --skill rigs --agent codex
npx skills add "https://github.com/mvschwarz/openrig/tree/v0.7.12/skills/rigs" --skill rigs --agent codex
```
If OpenRig is already installed, use the release tag matching your installed `rig --version` instead: replace the tag
after `tree/` with it, including its `v` prefix. `rig --version` prints the version and a commit, for example
`0.6.11 (379f0a0d)`; the tag is `v0.6.11`. The skill is in the repository from v0.6.6; on an older install, use the
v0.6.6 tag or upgrade first.
These are the pinned, per-agent forms used on the [rigs pages](https://openrig.dev/rigs).
You can also read [`skills/rigs/SKILL.md`](../../skills/rigs/SKILL.md) directly.
@@ -201,11 +203,11 @@ You can also read [`skills/rigs/SKILL.md`](../../skills/rigs/SKILL.md) directly.
script will do and changes nothing:
```sh
curl -fsSL https://raw.githubusercontent.com/mvschwarz/openrig/v0.7.11/scripts/install.sh | sh -s -- --dry-run
curl -fsSL https://raw.githubusercontent.com/mvschwarz/openrig/v0.7.12/scripts/install.sh | sh -s -- --dry-run
```
The same command without `--dry-run`,
`curl -fsSL https://raw.githubusercontent.com/mvschwarz/openrig/v0.7.11/scripts/install.sh | sh`, installs the
`curl -fsSL https://raw.githubusercontent.com/mvschwarz/openrig/v0.7.12/scripts/install.sh | sh`, installs the
latest published `@openrig/cli` with `npm install -g`,
runs the Node.js and SQLite check, then `rig setup --dry-run` and `rig setup`. `rig setup` checks both Claude Code and
Codex and may install a missing one, as described below. A failed step prints
@@ -347,8 +349,13 @@ with `rig up kernel --existing`. A seat you stopped or unclaimed also stays down
While the kernel's other seats are running, `rig up kernel --existing` refuses
(it restores only a kernel with no live session), so start one stopped seat with
`rig launch kernel <logical id>` (`--plan` first). It restores that seat from the
kernel's latest restore-usable snapshot and resumes its saved conversation; a seat
it can't resume is reported as waiting for a decision, not as started.
kernel snapshot that restore ranks first: the newest usable automatic one (taken
before `rig down`, on the periodic schedule, or at a runtime switch), even when a
manual one is newer, and otherwise the newest usable one. `--plan` names the
snapshot it picked and any newer usable one, and `--snapshot-id <id>` picks one
yourself. Under the default restore policy, which the kernel's seats keep, it
resumes the seat's saved conversation; a seat it can't resume is reported as
waiting for a decision, not as started.
`rig seat launch <seat> --fresh --reason "…"` instead starts a new conversation
with no continuity source: use it only when you want a fresh occupant, since the
seat's earlier conversation isn't carried.
+8 -2
View File
@@ -109,7 +109,9 @@ OpenRig doesn't observe a hosted member between its calls, so it never reads idl
- **Presence:** each entry carries `presence`, which says what OpenRig last saw of the member. It isn't pickup, and `null` means unknown:
- `lastCallAt`: its last authenticated call to this host's `rig mcp serve --http`, recorded at most once a minute in
`<OPENRIG_HOME>/mcp-http-presence.json`, beside the token file;
- `lastWake`: its latest ring and the result, among its 50 most recent rows.
- `lastWake`: its latest ring and the result, among its 50 most recent rows;
- `checkIn`: its check-in status, last check-in and stated cadence, as described in [Check-in status](#check-in-status)
(unknown, with the reason, when the daemon gives none).
- `rig roster show` and `find` show the last call; the last ring is in `rig_team`.
### Check-in status
@@ -135,7 +137,11 @@ A stated cadence is its person's statement: neither reading proves the assistant
anything up. It's a status only. Work addressed to a member that isn't checking in still queues and is rung as before, a check-in
isn't pickup (pickup is its claim), and no check-in doesn't mean it's idle, failed or safe. `GET /api/queue/hosted-members`
gives this daemon's host id and each member on this host with its status, last check-in and stated cadence (with the
reason when it's unknown); `rig roster show` and `find` show it as `Check-in:`, for a team with or without terminal seats.
reason when it's unknown); `rig roster show` and `find` show it as `Check-in:`, for a team with or without terminal seats, and `rig ps` (with or
without `--nodes`, and when it has no rigs or nodes to show) lists every connected assistant after its table, one line
each. That's on this host, and in the node view of an HTTP host; an SSH host's `rig ps` prints its own. An HTTP host's
rig view and the multi-host fan-out leave the section out. When the list can't be read, for example from an older
daemon, it says check-in is unavailable instead. Its `--json` output is unchanged.
When the member has unclaimed work, the standing notice described above states the same status in its `check-ins:`
line; when that notice is filed doesn't change.
+74 -5
View File
@@ -8,7 +8,71 @@ with one grant per participant. The network connector puts one selected local se
The connector opens no port: your daemon makes every connection outward, and the hub never connects to your machine. Work the hub
sends that participant runs on your seat, under your accounts, and the result goes back to the hub item.
## Connect
## Enroll in an account, then connect by name
When your hub is an account's network, enroll this daemon once with the one-time code its page shows, then connect
seats by name:
```bash
rig network enroll <code> --site <site URL>
rig network connect <seat> --as <name>
```
- `enroll` trades the code, with this daemon's host id, for an installation key. The key is stored like a participant's
token, under `<OpenRig home>/network-secrets/<installation>/key.json`, and is never returned or shown. A code is
single-use and short-lived; a refused one says why, so get a new one from the page. If the account doesn't answer,
whether it took the code is unknown: try again with the same code, and get a new one if that's refused.
- Enrolling trusts the site with where your connected seats' work goes: for each name, the account answers the front
and rig the binding reaches.
- The installation key goes only to the site you enrolled at: a redirect from it isn't followed. Each `enroll`,
`connect` or `disconnect` spends at most 30 seconds with the account in all, and the command waits 45 seconds for the
daemon, so you see the account's own answer or error.
- The account keeps one list of the installation's names, and every change sends the whole list. Changes to it run one
at a time on this daemon, each reading the names to keep in its turn, so two connects started together both stay
connected.
- `connect --as <name>` lists the name with the account, which answers that participant's bearer, its MCP front and its
rig. The binding then reaches that front as `<name>@<rig>`, the same as a direct connect. A name is lowercase letters,
digits and inner dashes, up to 32. One that another connection to the account uses is refused.
- If the answer to a connect is lost, the next connect drops the name and lists it again, which gets a fresh bearer and
ends the old one.
- If the account listed the name but the binding can't be made here, OpenRig asks the account to drop the name again.
That's best effort: if it fails too, the error says the account may still list the name.
- `disconnect` ends the binding here, then has the account stop listing the name, which revokes it there. Once the
account's answer no longer lists the name, `disconnect` says the account stopped listing it. If the account can't be
reached or its answer is lost, the binding is still ended, the error says OpenRig couldn't confirm the account dropped
the name and names the `rig network disconnect <binding id>` to run again, and `rig network status` keeps showing it
as unconfirmed. A later answer from the same account installation that no longer lists the name marks it dropped.
- `rig network status` shows the enrollment above the bindings.
### Enroll again after a lost key or a removed installation
When the installation key is missing, or the account no longer recognizes the installation, the error says to enroll
again with a new code from the account page:
```bash
rig network enroll <code> --site <site URL> --replace
```
Without `--replace`, a second enroll at the same site is refused and the code isn't spent. With it, the replace first
waits for any other change to this enrollment to finish, within the same 30 seconds; one that runs out of time while
waiting says so and doesn't send the code. The account makes a new installation, with a new key, for the new code. Here,
that key takes the old one's place and the bindings made through the old installation end, in one step:
- If that step fails after the account accepted the code, the enrollment's record here doesn't change, and the error
says so. The key is put back too, but moving key files happens outside that record's rollback. If putting it back also
fails (on a full or read-only disk, for example), the old key is left as `key.json.prev` beside `key.json` in the
installation's folder under `network-secrets/` in the OpenRig home: move it back to `key.json` before you go on. A
`key.json.next` there is a staged new key, and the next replace removes it. The old enrollment keeps working only
while the account keeps the old installation, and the account now has a new installation whose key nothing here
holds: remove it on the account page, then enroll again with a new code.
- Once the step is done, `enroll` names the bindings it ended. The old installation may still list their names, and the
new key can't drop them, so remove them on the account page. `rig network status` marks each of them as possibly still
listed under the old installation, as it does a binding that ended earlier without the account confirming the drop:
only the installation a name was listed under can confirm it.
- If cleanup after the step doesn't finish (removing the old key's backup, or an ended binding's credential), `enroll`
reports it, and the replace still stands.
## Connect with a hub URL and a token
```bash
rig network connect <seat> --hub <url> --as <participant> --token-file <path>
@@ -69,8 +133,9 @@ rig queue update <local item> --state done --closure-reason no-follow-on --resol
rig network status [--json]
```
Each binding shows its seat, participant, hub, state, and its last contact or last error. `--json` adds the
connector's view: each binding's next pass, backoff and last pass.
Each binding shows its seat, participant, hub, state, and its last contact or last error. An ended binding made through
the account also says when the account hasn't confirmed it dropped the name, or when the name may still be listed under
a replaced installation. `--json` adds the connector's view: each binding's next pass, backoff and last pass.
## When things go wrong
@@ -88,7 +153,8 @@ rig network disconnect <binding-or-seat> [--reason "<why>"]
```
The binding ends here, so no new work comes in through it, and its credential is removed. Local items and results
stay. The hub still lists the participant until it's removed there too.
stay. A binding made through the account is then dropped there too (see above). For a binding made with a hub URL and
a token, the hub still lists the participant until it's removed there too.
If the credential can't be removed, the binding still ends, and the error names the
`rig network disconnect <binding id>` to run again. The daemon also removes credentials whose binding isn't active
@@ -104,11 +170,14 @@ each time it starts.
An atomic close-if-open needs the hub to offer a conditional close.
- After a disconnect or a revocation, work already taken keeps running here, but its pickup and result no longer reach
the hub item, which stays at its last reported stage.
- If the daemon stops between storing a new installation key and recording the enrollment, that key's folder under
`network-secrets/` stays with no enrollment, and nothing removes it. It's private to you and unused, so remove it by
hand.
- **Plain http needs your choice.** `rig network connect` refuses an `http:` hub URL until you add `--allow-http`, because
the participant's token and its work then cross the network unencrypted, where they can be read. Use the hub's
`https:` URL where it has one. The choice is recorded on that binding, so the connector doesn't ask again, and
`rig network status` (and its `--json`) marks the binding unencrypted. OpenRig doesn't judge the address: a private or
tailnet address doesn't prove the connection is protected.
tailnet address doesn't prove the connection is protected. `rig network enroll` asks the same for a plain-http site.
- **Redirects:** the connector follows a hub's redirect only within its own origin, or to its `https:` form on the same
host. Any other redirect stops the connection with its target named, and the token isn't sent there. Connect the
binding to the hub's own URL.
+18 -2
View File
@@ -1,9 +1,25 @@
# HTTP operation correlation
`GET /api/operations/capabilities` advertises `operation-correlation.v1` and the supported kinds: `rig.create`, `rig.import`, and `member.add`. A client should check this marker before relying on correlation; an older daemon may ignore an unfamiliar request header.
`GET /api/operations/capabilities` advertises `operation-correlation.v1` and the supported kinds: `rig.create`, `rig.import`, `rig.materialize`, and `member.add`. A client should check the required kind before relying on correlation; an older daemon may ignore an unfamiliar request header.
For `POST /api/rigs`, `POST /api/rigs/import`, and `POST /api/rigs/:rigId/pods/:podNamespace/members`, send a UUID in `X-OpenRig-Operation-Id`. Keep the same daemon, route targets, original request text, and behavior-changing headers for a retry. IDs are case-normalized. An ID that isn't an RFC UUID receives HTTP 400 `Invalid X-OpenRig-Operation-Id` before the route does anything else. Once a request passes the route's own validation, a different request using the same ID receives HTTP 409 `operation_id_conflict`. Matching compares the exact request text, so a change in whitespace or key order is a different request, not an equivalent one; an exact replay receives HTTP 200 with `replayed: true` and current database state. A first request retains its usual status and response fields and adds `operation`.
For `POST /api/rigs`, `POST /api/rigs/import`, `POST /api/rigs/import/materialize`, and `POST /api/rigs/:rigId/pods/:podNamespace/members`, send a UUID in `X-OpenRig-Operation-Id`. Keep the same daemon, route targets, original request text, and behavior-changing headers for a retry. Materialization binds the target rig (when expanding), source root and cwd override as well as the spec text; it is distinct from launching import. IDs are case-normalized. An ID that isn't an RFC UUID receives HTTP 400 `Invalid X-OpenRig-Operation-Id` before the route does anything else. Once a request passes the route's own validation, a different request using the same ID receives HTTP 409 `operation_id_conflict`. Matching compares the exact request text, so a change in whitespace or key order is a different request, not an equivalent one; an exact replay receives HTTP 200 with `replayed: true` and current database state. A first request retains its usual status and response fields and adds `operation`.
The operation contains the rig and node IDs committed by that request. Its `current` field reads the database at response time, including whether recorded resources still exist and the latest recorded session for each node. It does not inspect tmux or prove a launch finished. A reservation with no IDs can mean that execution is still underway or that it failed before creating resources. Replaying an exact request that failed before creating resources returns HTTP 200 with `operation.rigId: null` and `operation.nodeIds: []`; inspect those fields to distinguish it from a replay that recorded resources. Replays never execute the mutation again, retry a launch, or recreate deleted resources. Use a new UUID only when deliberately starting a new execution.
This contract stores neither the original response nor a recovery verdict. An HTTP response can be lost after a database commit. External launch effects are outside the database transaction, so the contract is correlation rather than exactly-once execution of external effects.
## CLI no-launch preparation
`rig import ./team.yaml --materialize-only --operation-id <uuid> --json` prepares topology without starting sessions.
Save the UUID before running the command and reuse the exact command after a lost response. The CLI checks that the
daemon advertises `rig.materialize` before writing; a daemon without that capability refuses the explicit retry request.
`--operation-id` and `--json` apply only to `--materialize-only`, without other import modes. Omitting the operation id
keeps ordinary materialization behavior; it does not make repeated imports idempotent.
JSON output is the native receipt. Both initial and replay receipts carry the same committed ids in
`operation.rigId` and `operation.nodeIds`. Replays report current database state, not a cached first result. An empty
receipt leaves the CLI nonzero: it cannot confirm preparation while the original execution is still running or failed
before creating resources. Text-mode replays still print recorded rig and node IDs when resources are archived or
missing, with a warning and a nonzero exit status. JSON mode retains the native receipt and the same nonzero status.
The receipt's ids do not authorize launching anything; use the normal owner-authorized
[first start of a materialized seat](rig-spec.md#starting-one-materialized-seat) afterward.
+4 -4
View File
@@ -12,13 +12,13 @@ In your project folder, add OpenRig's `rigs` skill to the agent you use:
```sh
# Claude Code
npx skills add https://github.com/mvschwarz/openrig/tree/<release-tag>/skills/rigs --skill rigs --agent claude-code
npx skills add https://github.com/mvschwarz/openrig/tree/v0.7.12/skills/rigs --skill rigs --agent claude-code
# Codex
npx skills add https://github.com/mvschwarz/openrig/tree/<release-tag>/skills/rigs --skill rigs --agent codex
npx skills add https://github.com/mvschwarz/openrig/tree/v0.7.12/skills/rigs --skill rigs --agent codex
```
For a new install, use the latest release's tag, for example `v0.7.11`. If OpenRig is already installed, use the tag
that matches `rig --version`, or upgrade first. If the command fails with `npx: command not found`, Node.js isn't
These use this release's tag, for a new install. If OpenRig is already installed, replace the tag after `tree/` with
the one that matches `rig --version` (`v` and its version number), or upgrade first. If the command fails with `npx: command not found`, Node.js isn't
installed or isn't on your PATH yet (see [What you need](#what-you-need)). Then type `/rigs` in Claude Code, or `$rigs` in Codex, and say what
you want built.
+4
View File
@@ -193,6 +193,10 @@ edges:
### Starting one materialized seat
`rig import ./team.yaml --materialize-only` records the team without starting its harnesses.
For an automated preparation that may retry, save a UUID first and pass
`--operation-id <uuid> --json`; keep that same UUID, spec text, source root and other options on a retry.
Both receipts identify the original rig and nodes through `operation`; see
[HTTP operation correlation](operation-correlation.md#cli-no-launch-preparation) for capability checks and incomplete receipts.
For a seat that has never started, use its positional logical ID:
```bash
+16 -1
View File
@@ -209,7 +209,10 @@ and effective modes and retains the text `Typing guard: on (hold)` for hold.
A held send immediately returns `outcome: "retained"`, `sent: false`, its exact
reason and the saved attempt's `outboxIds`. No automatic
retry is scheduled. The reasons are:
retry is scheduled. `rig send` to several seats and `rig broadcast` print a held
recipient as `retained, not delivered; inspect with rig seat held-messages`, never
as sent, and their summary adds the held count (`1/3 delivered, 1 held`). A held
recipient alone doesn't make the command fail. The reasons are:
- `typing_guard_enabled`: the seat's mode holds this send (`hold`, or a level that
holds this kind of message).
@@ -226,6 +229,18 @@ retry is scheduled. The reasons are:
one with a reused `deliveryId`; the result warns older callers that this field no
longer deduplicates input. The CLI does not generate a deduplication key.
The last recorded managed-compaction input refusal appears as `inputReadFailure` in the attempt
record and `rig compact --state`: the preparation or compact stage, `composer`
(the explicit composer hold) or `draft-aware` check, reader status, confidence,
a fixed read-failure reason and cursor flags. An owed restore step reports it in
`owedRestore.lastDelivery`. These fields contain no input text, suggestions,
terminal frames or exception messages. Confidence and timeout fields are `null`
when that reader does not supply them; a known composer read timeout reports
`timedOut: true`. A generic `capture_unavailable` does not identify the failed
capture operation. Older records lack this diagnostic. It neither changes the
refusal nor retries an attempt; missing metadata cannot establish which check
caused a historical refusal.
Clearing a draft, changing modes or restarting does not flush saved messages or
callbacks. To try again, send a current request: it rechecks the recipient and input.
A caller abort before paste cancels input; after a write may have started, the
+12
View File
@@ -182,6 +182,18 @@ When no app can be chosen, or the app refuses the switch, the result names the
session to select by hand. A Rex app accepts the switch only with Remote Control
turned on in its Settings, under Rex Server.
Each local seat's tile shows the seat's runtime (such as Claude Code or Codex) and
its activity: working, idle, or blocked (with a permission kind for a permission
prompt). The tile gets the current activity once it opens and each change after
that, as `rig ps --nodes` resolves it. A Rex tile attached to the seat some other way, by
hand or by Rex after an app restart, is caught up within about ten seconds, or within
five minutes when no Rex tile was showing the seat before.
Rarely, a report can arrive in the middle of tmux's own output and garble part of a
Rex tile until it redraws. When OpenRig doesn't know a seat's activity,
the tile shows none rather than idle. OpenRig writes these reports only to the
tmux clients attached to the seat that identify themselves as Rex, so other
terminals attached to the seat get nothing and no tmux option changes.
The daemon finds `rex` in `$REX_BIN_DIR`, then on `PATH`, then inside the Rex
app on macOS, and uses its own `REX_SERVER` when set. It never starts a Rex
server. An open view is not reused: opening it again adds a numbered session,
+7 -4
View File
@@ -9,7 +9,7 @@ import { emitCrossHostError, emitRemoteHttpFailure } from "../cross-host-cli-hel
import { runRemoteHttpOp } from "../remote-host-ops.js";
import { resolveContextRef, walkSizedWarning } from "../context-resolve.js";
import { resolveSenderSession, SENDER_FALLBACK } from "../sender-identity.js";
import { refuseEmptyMessage } from "./send.js";
import { heldSuffix, refuseEmptyMessage } from "./send.js";
/**
* OPR.0.4.6.MH4 C3 — the cross-host broadcast deadline, named at the call
@@ -222,9 +222,12 @@ async function runCrossHostBroadcast(
* local route does, so per-target honesty prints identically. A partial
* fan-out sets a non-zero exit either way. */
function renderBroadcastResults(data: Record<string, unknown>): void {
const results = (data["results"] as Array<{ sessionName: string; ok: boolean; error?: string; inputPhase?: string; sent?: boolean; managedCompaction?: { notice?: unknown } }>) ?? [];
const results = (data["results"] as Array<{ sessionName: string; ok: boolean; error?: string; inputPhase?: string; sent?: boolean; outcome?: string; managedCompaction?: { notice?: unknown } }>) ?? [];
for (const r of results) {
if (r.ok) {
if (r.outcome === "retained") {
// A guard or the seat's setting held it: nothing was typed, so it isn't "sent" (as `rig send` says).
console.log(`${r.sessionName}: retained, not delivered; inspect with rig seat held-messages`);
} else if (r.ok) {
console.log(`${r.sessionName}: sent`);
} else if (r.inputPhase === "attempted" || r.inputPhase === "written" || r.sent === true) {
// The daemon records this recipient's receipt as indeterminate (#2507): its text or Enter may have reached it.
@@ -235,7 +238,7 @@ function renderBroadcastResults(data: Record<string, unknown>): void {
}
if (typeof r.managedCompaction?.notice === "string") console.log(`Notice: ${r.managedCompaction.notice}`);
}
console.log(`${data["sent"]}/${data["total"]} delivered`);
console.log(`${data["sent"]}/${data["total"]} delivered${heldSuffix(results)}`);
// S2 (OPR.0.5.4.3): surface additive advisories (e.g. the unknown-sender
// sign-it notice) — an env-less operator must see it, not "sent" lines alone.
const advisory = data["warning"] as string | undefined;
+1
View File
@@ -138,6 +138,7 @@ Keys:
output.compact short default output for queue writes, queue show, queue transitions and whoami peers (default off)
--full opts out: queue transitions returns the full log, queue show the complete record, and whoami the complete payload, not its usual identity projection. whoami --all-peers keeps that projection with every peer
output.whoami_peers with output.compact on, how many peers rig whoami --json lists, edge peers first; --all-peers lists all (default 8)
output.rebuild_recaps superseded recap paths previewed in rebuild briefings (default 3; 0 lists all)
bundle.services_enabled Service-backed bundle packing, preview and target installs (default off)
provider.usage_windows Codex and Claude usage windows in rig provider status (Codex read on request; Claude from its seats' status lines) (default off)
provider.selected the providers chosen at rig setup --providers (claude, codex or claude,codex); kernel boot uses only these (default empty: every signed-in provider)
+1 -18
View File
@@ -6,6 +6,7 @@ import { acquireDaemonStartLock, bootedAtMs, currentBootId } from "../daemon-sta
import { formatDaemonHostForUrl } from "../client.js";
import { execFileSync, spawn } from "node:child_process";
import { fetchWithTimeout } from "../fetch-with-timeout.js";
import { personRegistrationOffer } from "../person-registration-offer.js";
import {
startDaemon,
stopDaemon,
@@ -170,24 +171,6 @@ export function realDeps(): LifecycleDeps {
};
}
/** What `daemon start` tells the agent setting OpenRig up when the person registry holds nobody: the offer, in the
* output it reads at that moment. Empty when a person is registered, or when the registry can't be read, since an
* unreadable registry isn't evidence that nobody is registered. */
export async function personRegistrationOffer(): Promise<string[]> {
try {
const { participantsView } = await import("@openrig/daemon/gateway-human-registry");
const view = participantsView();
if (!view.ok || view.participants.some((p) => p.kind === "person")) return [];
} catch {
return [];
}
return [
"No person is registered yet, so OpenRig's questions to a person, such as another machine asking to pair, can't reach anyone.",
"If you're setting OpenRig up for someone, offer to register them now. Ask the name to use, and only on their yes run:",
' rig gateway human add <id> --display-name "<name>" --delivery-class B --default',
];
}
export function daemonCommand(depsOverride?: LifecycleDeps): Command {
const getDeps = () => depsOverride ?? realDeps();
const cmd = new Command("daemon").description("Manage the OpenRig daemon");
+1 -1
View File
@@ -674,7 +674,7 @@ export function doctorCommand(depsOverride?: DoctorDeps): Command {
console.log("");
console.log(healthy ? "No failures in the checks above. Review any WARN or SKIP rows." : "Some checks failed. Review the FAIL rows and their fixes above.");
console.log("Authentication checks report local provider facts; no agent task or provider request was tested.");
console.log("Only the harnesses selected for your project need a login; an unused harness does not.");
console.log("A harness needs a login only when a seat you start runs on it. A built-in team can use one you didn't select: starter runs its reviewer on Codex. `rig specs preview <team> --kind rig --json` lists each seat's runtime.");
console.log("A credential variable being set does not prove the provider accepts it or that managed seats receive it.");
console.log("Inspect your team with `rig ps --nodes --rig <rig>` and `rig capture <seat> --lines 30`.");
if (!healthy) process.exitCode = 1;
+3
View File
@@ -1,3 +1,4 @@
import { nobodyRegistered, REGISTRATION_OFFER } from "../person-registration-offer.js";
import { readFileSync } from "node:fs";
import { Command } from "commander";
import { resolveSenderSession, SENDER_FALLBACK } from "../sender-identity.js";
@@ -775,6 +776,8 @@ Removing a connector binding (binding.<n> unset):
console.log(defaultPerson.id ? `default: ${defaultPerson.id} (${defaultPerson.source === "chosen" ? "chosen" : "the only person"})` : `default: none — ${defaultPerson.reason}`);
for (const warning of view.warnings) console.log(`warning: ${warning}`);
if (view.sideFile.error) console.log(`participant file: ${view.sideFile.error}`);
// The same offer `rig daemon start` prints, for an agent meeting the person first (such as the kernel operator).
if (!opts.organization && nobodyRegistered(view.participants)) for (const line of REGISTRATION_OFFER) console.log(line);
});
cmd
+2 -2
View File
@@ -975,8 +975,8 @@ export function hostCommand(doctorDepsOverride?: DoctorDeps): Command {
}
if (opts.json) return;
console.log(decision === "approve"
? `Approved pairing ${res.data.code} from ${res.data.requester}, as ${res.data.by}. The requesting machine receives this host's token when it next checks.`
: `Denied pairing ${res.data.code} from ${res.data.requester}, as ${res.data.by}. Nothing was handed over.`);
? `Approved pairing ${res.data.code} from ${JSON.stringify(res.data.requester)}, as ${res.data.by}. The requesting machine receives this host's token when it next checks.`
: `Denied pairing ${res.data.code} from ${JSON.stringify(res.data.requester)}, as ${res.data.by}. Nothing was handed over.`);
});
}
+96 -5
View File
@@ -1,7 +1,8 @@
import nodePath from "node:path";
import { Command } from "commander";
import fs from "node:fs";
import { DaemonClient } from "../client.js";
import { z } from "zod";
import { DaemonClient, DaemonResponseError, type DaemonResponse } from "../client.js";
import { getDaemonStatus, getDaemonUrl , daemonStatusGuard} from "../daemon-lifecycle.js";
import { realDeps } from "./daemon.js";
import type { StatusDeps } from "./status.js";
@@ -12,6 +13,30 @@ export interface ImportDeps extends StatusDeps {
const LONG_RUNNING_IMPORT_TIMEOUT_MS = 120_000;
const materializeOperation = z.object({
operationId: z.uuid(), rigId: z.string().nullable(), nodeIds: z.array(z.string().min(1)),
current: z.object({
rig: z.object({ id: z.string(), exists: z.boolean(), archivedAt: z.string().nullable() }).nullable(),
nodes: z.array(z.object({ id: z.string(), exists: z.boolean() })),
}),
});
const materializeReplay = z.object({ replayed: z.literal(true), operation: materializeOperation });
const materializeResult = z.object({
rigId: z.string(), specName: z.string(), nodes: z.array(z.object({ logicalId: z.string(), status: z.string() })),
});
function recordedMaterializationMatches(operation: z.infer<typeof materializeOperation>): boolean {
// Reservations have no rig id; a committed empty pod has a rig id and zero nodes.
return operation.rigId !== null && operation.rigId.length > 0 && operation.current.rig?.id === operation.rigId &&
new Set(operation.nodeIds).size === operation.nodeIds.length && operation.current.nodes.length === operation.nodeIds.length &&
operation.nodeIds.every(id => operation.current.nodes.some(node => node.id === id));
}
function materializationCurrentlyAvailable(operation: z.infer<typeof materializeOperation>): boolean {
return operation.current.rig?.exists === true && operation.current.rig.archivedAt === null &&
operation.current.nodes.every(node => node.exists);
}
export function importCommand(depsOverride?: ImportDeps): Command {
const cmd = new Command("import").description("Import a rig spec from YAML");
const getDeps = (): ImportDeps => depsOverride ?? {
@@ -24,13 +49,25 @@ export function importCommand(depsOverride?: ImportDeps): Command {
.argument("<path>", "Path to YAML rig spec file")
.option("--instantiate", "Instantiate the rig after import")
.option("--materialize-only", "Create rig topology without launching sessions")
.option("--operation-id <uuid>", "With --materialize-only: keep this UUID for exact retries")
.option("--json", "With --materialize-only: print the native JSON receipt")
.option("--workspace-only", "Apply only the workspace declaration to an existing rig")
.option("--preflight", "Run preflight checks")
.option("--target-rig <rigId>", "Target existing rig for materialization or workspace apply")
.option("--rig-root <root>", "Root directory for pod-aware resolution")
.option("--cwd <path>", "Override launch/materialization working directory for all members")
.action(async (filePath: string, opts: { instantiate?: boolean; materializeOnly?: boolean; workspaceOnly?: boolean; preflight?: boolean; targetRig?: string; rigRoot?: string; cwd?: string }) => {
.action(async (filePath: string, opts: { instantiate?: boolean; materializeOnly?: boolean; operationId?: string; json?: boolean; workspaceOnly?: boolean; preflight?: boolean; targetRig?: string; rigRoot?: string; cwd?: string }) => {
const deps = getDeps();
if ((opts.operationId !== undefined || opts.json) && (!opts.materializeOnly || opts.instantiate || opts.workspaceOnly || opts.preflight)) {
console.error("--operation-id and --json require --materialize-only without other import modes.");
process.exitCode = 1;
return;
}
if (opts.operationId !== undefined && !z.uuid().safeParse(opts.operationId).success) {
console.error("--operation-id must be an RFC UUID.");
process.exitCode = 1;
return;
}
// Read local file first (before daemon check — fail fast on missing file)
let yaml: string;
@@ -126,10 +163,49 @@ export function importCommand(depsOverride?: ImportDeps): Command {
const headers = {
...extraHeaders,
...(opts.targetRig ? { "X-Target-Rig-Id": opts.targetRig } : {}),
...(opts.operationId !== undefined ? { "X-OpenRig-Operation-Id": opts.operationId } : {}),
};
const res = await client.postText<{ rigId: string; specName: string; specVersion: string; nodes: Array<{ logicalId: string; status: string }> } | { ok: false; code: string; errors?: string[]; message?: string; error?: string }>("/api/rigs/import/materialize", yaml, "text/yaml", headers);
if (opts.operationId !== undefined) {
let capabilities: DaemonResponse<unknown>;
try {
capabilities = await client.get<unknown>("/api/operations/capabilities");
} catch (error) {
if (!(error instanceof DaemonResponseError)) throw error;
console.error("This daemon did not return a readable operation capability response. Nothing was materialized; upgrade the daemon before using --operation-id.");
process.exitCode = 1;
return;
}
const parsed = z.object({ contract: z.literal("operation-correlation.v1"), kinds: z.array(z.string()) }).safeParse(capabilities.data);
if (capabilities.status >= 400 || !parsed.success || !parsed.data.kinds.includes("rig.materialize")) {
console.error("This daemon does not advertise retry-safe materialization. Nothing was materialized; upgrade the daemon before using --operation-id.");
process.exitCode = 1;
return;
}
}
const res = await client.postText<unknown>("/api/rigs/import/materialize", yaml, "text/yaml", headers);
const replay = materializeReplay.safeParse(res.data);
const fresh = materializeResult.safeParse(res.data);
const receipt = z.object({ operation: materializeOperation }).safeParse(res.data);
const confirmed = replay.success ? recordedMaterializationMatches(replay.data.operation) : fresh.success;
// Fresh results expose logical ids, not native node ids: compare the available count,
// and require distinct recorded ids with matching current-node evidence, without inventing a mapping.
const correlated = opts.operationId === undefined || receipt.success && receipt.data.operation.operationId === opts.operationId.toLowerCase() &&
recordedMaterializationMatches(receipt.data.operation) && (replay.success || fresh.success &&
receipt.data.operation.rigId === fresh.data.rigId && receipt.data.operation.nodeIds.length === fresh.data.nodes.length);
const available = !receipt.success || materializationCurrentlyAvailable(receipt.data.operation);
if (opts.json) {
console.log(JSON.stringify(res.data, null, 2));
if (res.status >= 400 || !confirmed || !correlated || !available) process.exitCode = 1;
return;
}
if (res.status === 409 || res.status === 400 || res.status === 404) {
const data = res.data as { ok?: false; code?: string; errors?: string[]; message?: string; error?: string };
const error = z.object({ code: z.string().optional(), errors: z.array(z.string()).optional(), message: z.string().optional(), error: z.string().optional() }).safeParse(res.data);
const data = error.success ? error.data : {};
if (data.code === "operation_id_conflict") {
console.error("Materialize failed: operation_id_conflict.\nReuse this operation ID with the exact original request and options, or use a new operation ID to deliberately start a new operation.");
process.exitCode = 1;
return;
}
if (data.code === "rig_name_running") {
console.error(data.error ?? data.message ?? "A rig with this name is already running.");
process.exitCode = 1;
@@ -145,7 +221,22 @@ export function importCommand(depsOverride?: ImportDeps): Command {
process.exitCode = 1;
return;
}
const data = res.data as { rigId: string; specName: string; specVersion: string; nodes: Array<{ logicalId: string; status: string }> };
if (!confirmed || !correlated) {
console.error("Materialization is not confirmed. Inspect the operation receipt; an empty receipt can mean it is still running or failed before creation. Keep the same operation id to inspect it again.");
process.exitCode = 1;
return;
}
if (!available) {
console.error("Warning: the recorded rig is archived or resources are missing. The receipt IDs are preserved, but the topology is not currently available.");
process.exitCode = 1;
}
if (replay.success) {
console.log(`Materialization replay: ${replay.data.operation.rigId}`);
for (const id of replay.data.operation.nodeIds) console.log(` Node: ${id}`);
return;
}
if (!fresh.success) return;
const data = fresh.data;
console.log(`Rig materialized: ${data.specName} (${data.rigId})`);
for (const n of data.nodes) {
console.log(` ${n.logicalId}: ${n.status}`);
+74 -15
View File
@@ -15,8 +15,25 @@ interface Binding {
lastContactAt: string | null; lastError: string | null; unencrypted?: boolean;
/** Hub items someone else closed before this binding's result reached them. */
closedElsewhere?: Array<{ hubItem: string; localItem: string }>;
participantName?: string | null;
/** For an ended binding made through the account: whether the account confirmed it stopped listing the name. */
accountRemoval?: "confirmed" | "unconfirmed" | "old-installation" | null;
}
/** The network writes can wait on the account, which the daemon bounds at 30 s in all; the CLI waits past that so the
* account's own answer is shown rather than a daemon timeout. */
const ACCOUNT_WRITE_TIMEOUT_MS = 45_000;
const accountNote = (b: Binding): string => {
if (b.accountRemoval === "unconfirmed") return `\n couldn't confirm the account dropped ${b.participantName}: run rig network disconnect ${b.id} again`;
if (b.accountRemoval === "old-installation") return `\n ${b.participantName} may still be listed under the old installation: remove it on the account page`;
return "";
};
interface Installation { id: string; site: string; installationId: string; name: string | null }
const enrolled = (i: Installation) => `Enrolled at ${i.site} as installation ${i.name ?? i.installationId} (${i.id})`;
/** The participant's token, read from the file the account gave the person. A file others can read is used, with a note. */
function defaultReadTokenFile(path: string): string {
const stat = lstatSync(path);
@@ -30,7 +47,7 @@ function line(b: Binding): string {
const state = b.state === "active" ? contact : `${b.state}${b.stateReason ? ` (${b.stateReason})` : ""}`;
const plain = b.unencrypted ? " UNENCRYPTED (http, allowed for this binding)" : "";
const conflicts = (b.closedElsewhere ?? []).map((c) => `\n hub item ${c.hubItem} was closed elsewhere before its result arrived; the result stays on ${c.localItem}`).join("");
return `${b.id} ${b.localSession} -> ${b.hubSeat} at ${b.hubUrl}${plain} ${state}${b.lastError && b.state === "active" ? ` last error: ${b.lastError}` : ""}${conflicts}`;
return `${b.id} ${b.localSession} -> ${b.hubSeat} at ${b.hubUrl}${plain} ${state}${b.lastError && b.state === "active" ? ` last error: ${b.lastError}` : ""}${conflicts}${accountNote(b)}`;
}
/** `rig network`: connect a selected local seat to a participant of a remote hub (an account's network rig, or
@@ -56,25 +73,60 @@ export function networkCommand(depsOverride?: NetworkDeps): Command {
console.log(json ? JSON.stringify(data, null, 2) : ok(data as Record<string, unknown>));
};
cmd.command("enroll")
.description("Enroll this daemon in an account with the one-time code its page shows, so seats connect by name")
.argument("<code>", "The one-time code from the account page")
.requiredOption("--site <url>", "The account's site")
.option("--allow-http", "Accept a plain-http site: the installation key and tokens cross the network unencrypted")
.option("--replace", "Replace this daemon's enrollment at the site, once the account accepts the new code (after a lost key or a removed installation)")
.option("--json", "Print JSON")
.action(async (code: string, opts: { site: string; allowHttp?: boolean; replace?: boolean; json?: boolean }) => {
const daemon = await client();
if (!daemon) return;
const res = await daemon.post<Record<string, unknown>>("/api/network/installations", { code, site: opts.site, allowHttp: opts.allowHttp === true, replace: opts.replace === true },
{ headers: operatorAuthHeaders(), timeoutMs: ACCOUNT_WRITE_TIMEOUT_MS });
finish(res.status, res.data, opts.json, (i) => {
const replaced = (i as { replaced?: { endedBindings?: Array<{ id: string; localSession: string; participantName: string | null }>; problems?: string[] } }).replaced;
const ended = replaced?.endedBindings ?? [];
const lines = [enrolled(i as unknown as Installation)];
if (ended.length) {
lines.push(`Ended ${ended.length} binding${ended.length === 1 ? "" : "s"} made through the old installation; their names may still be listed under it, so remove them on the account page:`);
for (const b of ended) lines.push(` ${b.id} ${b.localSession} as ${b.participantName}`);
}
for (const problem of replaced?.problems ?? []) lines.push(`Replaced, with cleanup left over: ${problem}`);
lines.push("Connect a seat with rig network connect <seat> --as <name>.");
return lines.join("\n");
});
});
cmd.command("connect")
.description("Connect a local seat to a hub participant, using that participant's token")
.description("Connect a local seat to a hub participant: by name through the enrolled account, or with a hub URL and token file")
.argument("<seat>", "The local seat to connect (its address, member@rig)")
.requiredOption("--hub <url>", "The hub's MCP URL")
.requiredOption("--as <participant>", "The participant's address in the hub (member@rig)")
.requiredOption("--token-file <path>", "A file holding the participant's token")
.requiredOption("--as <participant>", "Through the account: the name to connect as. With --hub: the participant's address in the hub (member@rig)")
.option("--hub <url>", "The hub's MCP URL, to connect without the account (with --token-file)")
.option("--token-file <path>", "A file holding the participant's token (with --hub)")
.option("--allow-http", "Accept a plain-http hub for this binding: its token and work cross the network unencrypted")
.option("--json", "Print JSON")
.action(async (seat: string, opts: { hub: string; as: string; tokenFile: string; allowHttp?: boolean; json?: boolean }) => {
let token: string;
try { token = (getDeps().readTokenFile ?? defaultReadTokenFile)(opts.tokenFile); } catch (error) {
console.error(`Can't read the token file: ${(error as Error).message}`);
.action(async (seat: string, opts: { hub?: string; as: string; tokenFile?: string; allowHttp?: boolean; json?: boolean }) => {
if (!opts.hub !== !opts.tokenFile) {
console.error("Give both --hub and --token-file, or neither to connect through the enrolled account.");
process.exitCode = 1;
return;
}
let body: Record<string, unknown> = { session: seat, participantName: opts.as };
if (opts.hub && opts.tokenFile) {
let token: string;
try { token = (getDeps().readTokenFile ?? defaultReadTokenFile)(opts.tokenFile); } catch (error) {
console.error(`Can't read the token file: ${(error as Error).message}`);
process.exitCode = 1;
return;
}
body = { session: seat, hubUrl: opts.hub, hubSeat: opts.as, token, allowHttp: opts.allowHttp === true };
}
const daemon = await client();
if (!daemon) return;
const res = await daemon.post<Record<string, unknown>>("/api/network/bindings", { session: seat, hubUrl: opts.hub, hubSeat: opts.as, token, allowHttp: opts.allowHttp === true }, { headers: operatorAuthHeaders() });
finish(res.status, res.data, opts.json, (b) => `Connected ${line(b as unknown as Binding)}\nWork for ${opts.as} reaches ${seat} once the connector runs; rig network status shows its last contact.`);
const res = await daemon.post<Record<string, unknown>>("/api/network/bindings", body, { headers: operatorAuthHeaders(), timeoutMs: ACCOUNT_WRITE_TIMEOUT_MS });
finish(res.status, res.data, opts.json, (b) => `Connected ${line(b as unknown as Binding)}\nWork for ${(b as unknown as Binding).hubSeat} reaches ${seat} once the connector runs; rig network status shows its last contact.`);
});
cmd.command("status")
@@ -83,10 +135,11 @@ export function networkCommand(depsOverride?: NetworkDeps): Command {
.action(async (opts: { json?: boolean }) => {
const daemon = await client();
if (!daemon) return;
const res = await daemon.get<{ bindings: Binding[] }>("/api/network/bindings");
const res = await daemon.get<{ bindings: Binding[]; installations?: Installation[] }>("/api/network/bindings");
finish(res.status, res.data, opts.json, (d) => {
const bindings = (d.bindings ?? []) as Binding[];
return bindings.length ? bindings.map(line).join("\n") : "No seats are connected to a hub.";
const installations = (d.installations ?? []) as Installation[];
return [...installations.map(enrolled), ...(bindings.length ? bindings.map(line) : ["No seats are connected to a hub."])].join("\n");
});
});
@@ -98,8 +151,14 @@ export function networkCommand(depsOverride?: NetworkDeps): Command {
.action(async (ref: string, opts: { reason?: string; json?: boolean }) => {
const daemon = await client();
if (!daemon) return;
const res = await daemon.post<Record<string, unknown>>(`/api/network/bindings/${encodeURIComponent(ref)}/disconnect`, { reason: opts.reason }, { headers: operatorAuthHeaders() });
finish(res.status, res.data, opts.json, (b) => `Disconnected ${line(b as unknown as Binding)}\nRemove the participant on the hub too, so the account stops listing it.`);
const res = await daemon.post<Record<string, unknown>>(`/api/network/bindings/${encodeURIComponent(ref)}/disconnect`, { reason: opts.reason },
{ headers: operatorAuthHeaders(), timeoutMs: ACCOUNT_WRITE_TIMEOUT_MS });
finish(res.status, res.data, opts.json, (raw) => {
const b = raw as unknown as Binding;
if (b.accountRemoval === "confirmed") return `Disconnected ${line(b)}\nThe account stopped listing ${b.participantName}, which revokes it there.`;
if (b.accountRemoval) return `Disconnected ${line(b)}`;
return `Disconnected ${line(b)}\nRemove the participant on the hub too, so the account stops listing it.`;
});
});
return cmd;
+38
View File
@@ -1,4 +1,5 @@
import { modelObservation, formatModelObservation, type ModelObservation } from "../lib/model-observation.js";
import { formatCheckIn } from "../lib/check-in.js";
import { Command } from "commander";
import stringWidth from "string-width";
import { resolveEffectiveHost } from "../host-selection.js";
@@ -1172,6 +1173,8 @@ Exit codes:
} else {
console.log("No rigs");
}
// A host can have connected assistants and no terminal rigs at all.
await printConnectedAssistants(client, opts.rig);
return;
}
@@ -1243,11 +1246,43 @@ Exit codes:
const remaining = filtered.length - (limit ?? 0);
console.log(`... and ${remaining} more rig${remaining === 1 ? "" : "s"} (--limit ${limit}).`);
}
await printConnectedAssistants(client, opts.rig);
});
return cmd;
}
/** Connected assistants (roster members outside any terminal) and whether each is checking its queue. They're on the
* team but aren't nodes, so the human view lists them in their own short section, every one it's given; `--json` output
* is unchanged (read `/api/queue/hosted-members` for them). The local rig and node views print it, empty or not, and so
* does an HTTP host's node view; an SSH host runs its own `rig ps`. An HTTP host's rig view and the multi-host fan-out
* leave it out. Nothing when there are none. A list that can't be read isn't an empty one, so it gets one line saying
* check-in is unavailable, and the view's exit status stays as it was. */
async function printConnectedAssistants(client: DaemonClient, rig?: string, requestHeaders?: Record<string, string>): Promise<void> {
let members: Array<Record<string, unknown>>;
let unavailable: string | null = null;
try {
const res = await client.get<{ members?: unknown }>("/api/queue/hosted-members", requestHeaders ? { headers: requestHeaders } : undefined);
if (res.status === 404) unavailable = "this daemon doesn't serve it";
else if (res.status >= 400) unavailable = `the read failed: HTTP ${res.status}`;
else if (!Array.isArray(res.data?.members)) unavailable = "the daemon's answer couldn't be read";
members = unavailable ? [] : (res.data.members as unknown[]).filter((m): m is Record<string, unknown> => !!m && typeof m === "object" && typeof (m as Record<string, unknown>).seat === "string");
} catch (err) {
unavailable = `the read failed: ${(err as Error).message}`;
members = [];
}
if (unavailable) {
console.log("");
console.log(`Connected assistants: check-in unavailable (${unavailable})`);
return;
}
if (rig) members = members.filter((m) => (m.seat as string).endsWith(`@${rig}`));
if (members.length === 0) return;
console.log("");
console.log("Connected assistants (outside the terminal; each checks its own queue):");
for (const m of members) console.log(` ${m.seat as string} ${formatCheckIn(m)}`);
}
async function handleNodes(
client: DaemonClient,
opts: PsCliOptions,
@@ -1381,6 +1416,8 @@ async function handleNodes(
} else {
console.log("No nodes");
}
// A rig with no terminal seats can still have connected assistants.
await printConnectedAssistants(client, opts.rig, requestHeaders);
return;
}
@@ -1448,6 +1485,7 @@ async function handleNodes(
for (const n of humanList as NodeEntry[]) {
if (n.communityHarness) console.log(formatCommunityHarnessLine(n.canonicalSessionName ?? n.logicalId, n.communityHarness));
}
await printConnectedAssistants(client, opts.rig, requestHeaders);
for (const n of humanList as NodeEntry[]) {
if (livenessUnconfirmed(n)) console.log(livenessLine(n.canonicalSessionName ?? n.logicalId, n));
}
+59 -1
View File
@@ -1019,6 +1019,16 @@ function emitHostResolutionError(res: { error: string; message: string }, json:
process.exitCode = 1;
}
/** Emit a local queue-list filter error without printing rows returned by a daemon that ignored it. */
function emitQueueListFilterError(res: { error: string; message: string }, json: boolean): void {
if (json) {
console.log(JSON.stringify(res));
} else {
console.error(res.message);
}
process.exitCode = 1;
}
const QUEUE_HOST_OPTION_HELP =
"OPR.0.4.6.MH3: route this queue write to a REGISTERED remote host (see rig host ls). EXPLICIT-ONLY — queue verbs never follow the persisted 'rig host select' selection. Equivalent to the host-qualified destination form member@rig@<host>.";
@@ -1944,6 +1954,24 @@ workspace home that is deferred/not-imminent belongs in its mission/slice.`)
}, remoteHostOf(opts.host) !== undefined, remoteHostOf(opts.host));
});
const listTagFiltersInArgumentOrder: string[] = [];
const collectListTag = (value: string, previous: string[] = []): string[] => {
listTagFiltersInArgumentOrder.push(value);
return [...previous, value];
};
const collectMissionListTag = (value: string, previous: string[] = []): string[] => {
listTagFiltersInArgumentOrder.push(`mission:${value}`);
return [...previous, value];
};
const collectSliceListTag = (value: string, previous: string[] = []): string[] => {
listTagFiltersInArgumentOrder.push(`slice:${value}`);
return [...previous, value];
};
cmd.hook("preSubcommand", (_parent, subcommand) => {
if (subcommand.name() === "list") listTagFiltersInArgumentOrder.length = 0;
});
cmd
.command("list")
.description("List qitems (default: active + compact + current-rig; like 'docker ps')")
@@ -1957,6 +1985,9 @@ workspace home that is deferred/not-imminent belongs in its mission/slice.`)
.option("--source <session>", "Filter by source session")
.option("--state <state>", "Filter by state (comma-separated for multiple)")
.option("--target-repo <name>", "PL-007: filter qitems by target_repo (exact match)")
.option("--tag <tag>", "Exact, case-sensitive tag filter; repeat for AND (commas are literal)", collectListTag, [] as string[])
.option("--mission <id>", "Filter by the exact mission:<id> tag; repeatable", collectMissionListTag, [] as string[])
.option("--slice <id>", "Filter by the exact slice:<id> tag; repeatable", collectSliceListTag, [] as string[])
.option("--limit <n>", "Result limit", positiveIntArg, 100)
.option("--json", "JSON output (compact; use --full --json for complete fields)")
.option("--host <id>", `${QUEUE_HOST_ROW_OPTION_HELP} With --host, the rows of every rig on that host unless --destination or --source narrows them; --owned and --mine name this host's seat and are refused.`)
@@ -1973,6 +2004,7 @@ Four orthogonal axes (docker/kubectl pattern):
Active states: pending, in-progress, blocked.
History (-a adds): done, canceled, handed-off, failed, denied.
Use --state <states> to select specific states explicitly.
Use repeated --tag <tag> values to require every exact, case-sensitive tag; commas are literal. --mission <id> and --slice <id> add mission:<id> and slice:<id> filters. Exact duplicates collapse and blank values are refused. A returned row that lacks a requested tag reveals an older daemon that ignored the filter; an empty list cannot prove it applied it.
Depth: 'rig queue show <qitemId>' previews one body; add --full for the complete record.
Frontier source: 'rig queue list' is the default status surface.
@@ -2000,13 +2032,24 @@ Examples:
source?: string;
state?: string;
targetRepo?: string;
tag?: string[];
mission?: string[];
slice?: string[];
limit: string;
json?: boolean;
host?: string;
}) => {
const useJson = opts.json || opts.o === "json";
const orderedTags = listTagFiltersInArgumentOrder.splice(0);
const invalidTag = [...(opts.tag ?? []), ...(opts.mission ?? []), ...(opts.slice ?? [])]
.some((value) => value.trim().length === 0);
if (invalidTag) {
emitQueueListFilterError({ error: "tag_invalid", message: "tag filters cannot be blank" }, useJson);
return;
}
const tags = [...new Set(orderedTags)];
const deps = getDeps();
const remote = remoteHostOf(opts.host);
const useJson = opts.json || opts.o === "json";
// The seat env names a seat of THIS host. On another host's daemon (a --host that resolves remote) it scopes
// nothing that daemon holds: no rig is derived from it, and --owned/--mine are refused.
const seatScope = (onRemote: boolean): URLSearchParams | null => {
@@ -2044,6 +2087,7 @@ Examples:
if (opts.source) params.set("sourceSession", opts.source);
if (opts.state) params.set("state", opts.state);
if (opts.targetRepo) params.set("targetRepo", opts.targetRepo);
for (const tag of tags) params.append("tag", tag);
if (opts.limit) params.set("limit", String(opts.limit));
return params;
};
@@ -2056,6 +2100,20 @@ Examples:
const params = seatScope(target.remote !== undefined);
if (!params) return;
const res = await target.client.get<unknown>(`/api/queue/list?${params.toString()}`, target.options);
if (res.status < 400 && tags.length > 0 && Array.isArray(res.data)) {
const ignored = res.data.some((value) => {
if (!value || typeof value !== "object") return true;
const rowTags = (value as { tags?: unknown }).tags;
return !Array.isArray(rowTags) || tags.some((tag) => !rowTags.includes(tag));
});
if (ignored) {
emitQueueListFilterError({
error: "filter_unsupported",
message: "The daemon returned a queue row missing a requested exact tag; it may be too old to apply tag filters. Empty results cannot confirm tag filtering.",
}, useJson);
return;
}
}
printResult(useJson, res.data, res.status);
}, remote !== undefined, remote);
});
+3 -13
View File
@@ -5,7 +5,8 @@ import { fileURLToPath } from "node:url";
import { execFile } from "node:child_process";
import { ConfigStore } from "../config-store.js";
import { mcpPresenceFilePath, readPresence } from "../mcp-presence.js";
import { CHECK_IN_DISPLAY, describeCheckIn, type CheckInStatus } from "@openrig/daemon/connection-contract";
import { CHECK_IN_DISPLAY } from "@openrig/daemon/connection-contract";
import { formatCheckIn } from "../lib/check-in.js";
import { getDaemonStatus, getDaemonUrl } from "../daemon-lifecycle.js";
import { DaemonClient } from "../client.js";
import { realDeps } from "./daemon.js";
@@ -13,6 +14,7 @@ import { parseRoster, readRosters, type Roster, type RosterMember, type RosterWa
// One roster parser, shared with the daemon (a hosted member's wake route reads the same files).
export { parseRoster, readRosters, type Roster, type RosterMember, type RosterWake };
export { formatCheckIn };
type Row = Record<string, unknown>;
export interface RosterInventory {
@@ -84,18 +86,6 @@ function hostedCheckIn(member: RosterMember, inventory: RosterInventory): Row {
: unknown("this host's daemon gave no status for it");
}
/** A connected assistant's check-in in one human line with its evidence, in the daemon's own words
* (`describeCheckIn`): "overdue: last check-in 13:05, expected every 60 min; its schedule may be off or waiting for an
* approval". A status this CLI doesn't know reads unknown. */
export function formatCheckIn(checkIn: Row): string {
const known = typeof checkIn.status === "string" && checkIn.status in CHECK_IN_DISPLAY;
return describeCheckIn({ status: known ? checkIn.status as CheckInStatus : "unknown",
lastCheckInAt: typeof checkIn.lastCheckInAt === "string" ? checkIn.lastCheckInAt : null,
expectedMinutes: typeof checkIn.expectedMinutes === "number" ? checkIn.expectedMinutes : null,
onRequest: checkIn.onRequest === true,
...(known && typeof checkIn.reason === "string" ? { reason: checkIn.reason } : {}) });
}
export function enrichRosterMember(member: RosterMember, inventory: RosterInventory) {
const matches = inventory.nodes.filter(n => n.hostSelfId === member.host && n.canonicalSessionName === member.seat);
// Two aliases can query the same host. Collapse repeated identical identity/configuration,
+7 -1
View File
@@ -1179,7 +1179,7 @@ async function runFanOutSend(params: {
}
// The delivered count never includes a staged-unresolved recipient.
const deliveredCount = Math.max(0, ((data["sent"] as number) ?? 0) - unresolvedCount);
console.log(`${deliveredCount}/${data["total"]} delivered${unresolvedCount - unconfirmedCount > 0 ? `, ${unresolvedCount - unconfirmedCount} staged-not-consumed` : ""}${unconfirmedCount > 0 ? `, ${unconfirmedCount} submission-unconfirmed` : ""}`);
console.log(`${deliveredCount}/${data["total"]} delivered${unresolvedCount - unconfirmedCount > 0 ? `, ${unresolvedCount - unconfirmedCount} staged-not-consumed` : ""}${unconfirmedCount > 0 ? `, ${unconfirmedCount} submission-unconfirmed` : ""}${heldSuffix(results)}`);
// S2 (OPR.0.5.4.3): surface additive advisories (e.g. the unknown-sender
// sign-it notice) — an env-less operator must see it, not "sent" lines alone.
const fanoutAdvisory = data["warning"] as string | undefined;
@@ -1192,6 +1192,12 @@ async function runFanOutSend(params: {
}
}
/** The summary's held count, when any target was held: held work is retained, not delivered and not failed. */
export function heldSuffix(results: Array<{ outcome?: string }>): string {
const held = results.filter((r) => r.outcome === "retained").length;
return held > 0 ? `, ${held} held` : "";
}
function parseWaitForIdleMs(value: string | undefined): number | undefined | null {
if (value === undefined) return undefined;
const seconds = Number(value);
+1 -1
View File
@@ -954,7 +954,7 @@ tmux scrollback:
if (step.fixHint) console.log(` Fix: ${step.fixHint}`);
}
listChecks();
console.log("Only the harnesses selected for your project need a login; an unused harness does not (rerun with --providers to leave it out).");
console.log("A harness needs a login only when a seat you start runs on it (rerun with --providers to leave it out). A built-in team can use one you didn't select: starter runs its reviewer on Codex.");
console.log("Run `rig doctor` to recheck the system and provider authentication.");
}
// Keep the conversation route available even after a dry run or incomplete setup,
+9 -7
View File
@@ -110,7 +110,7 @@ function printResult(json: boolean, body: unknown, status: number): void {
}
/** Human-format the honest-partial open result (opened/absent/degraded, each named). */
function humanOpen(r: OpenViewResult): string {
function humanOpen(r: OpenViewResult, viaWindow: boolean): string {
const lines: string[] = [];
const tiled = r.opened.length;
const target = r.session === undefined ? r.provider : `${r.provider} session ${JSON.stringify(r.session)}`;
@@ -118,7 +118,7 @@ function humanOpen(r: OpenViewResult): string {
r.code === "terminal_window_failed" && r.error
? r.error
: r.ok && r.reusedWorkspace
? `Terminal window requested. Reused ${target} workspace ${r.reusedWorkspace.id} for view ${JSON.stringify(r.reusedWorkspace.view)}.`
? `${viaWindow ? "Terminal window requested. " : ""}Reused ${target} workspace ${r.reusedWorkspace.id} for view ${JSON.stringify(r.reusedWorkspace.view)}.`
: tiled > 0
? `${r.window ? "Terminal window requested. " : ""}Prepared ${tiled} tile(s) in ${target}${r.pages > 1 ? ` across ${r.pages} page(s)` : ""}.`
: `No tiles ${r.degraded.some(d => d.code === "pane_unconfirmed") ? "confirmed" : "opened"} in ${target}.`,
@@ -156,11 +156,11 @@ async function withHeldSeats(client: DaemonClient, r: OpenViewResult): Promise<O
}
/** A successful existing-workspace selection also needs no new panes. */
function printOpen(json: boolean, r: OpenViewResult, status: number): void {
function printOpen(json: boolean, r: OpenViewResult, status: number, viaWindow = false): void {
if (json) {
console.log(JSON.stringify(r));
} else {
console.log(humanOpen(r));
console.log(humanOpen(r, viaWindow));
}
if (status >= 400 || (r.following ? !r.ok : r.opened.length === 0 && !(r.ok && r.reusedWorkspace))) {
process.exitCode = status >= 500 ? 2 : 1;
@@ -182,7 +182,7 @@ export function terminalCommand(depsOverride?: TerminalDeps): Command {
.command("open")
.argument("<view>", "a rig name, pod:<rig>/<pod>, seat:<rig>/<logical-id>, mission:<id>, slice:<id>, qitem:<id> (current local obligation owners), or a saved-view id")
.description("Open a desktop terminal showing the view's live agents as interactive tiles")
.option("--provider <name>", "herdr, herdr-app, cmux or rex: open in the running provider without a desktop window; each open adds a new workspace (inside Herdr, --window reuses a matching one), and herdr-app opens a Rig view in the herdr-app window this runs in, which must be answering; tmux requires --window. Inside Rex, the default opens in Rex")
.option("--provider <name>", "herdr, herdr-app, cmux or rex: open in the running provider without a desktop window; herdr focuses a workspace that still shows this view with live attachments, otherwise each open adds a new workspace, and herdr-app opens a Rig view in the herdr-app window this runs in, which must be answering; tmux requires --window. Inside Rex, the default opens in Rex")
.option("--session <name>", "Herdr session on the daemon's host; --session default selects Herdr's default session")
.option("--window", "Open a new desktop terminal tab/window (the default when --provider is omitted outside herdr-app); inside a herdr-app terminal --window still asks for a desktop window, and plain open reuses herdr-app")
.option("--app-home <dir>", "herdr-app: the client to open in (default: herdr-app's own home, from HERDR_APP_HOME or ~/.config/herdr-app)")
@@ -251,7 +251,7 @@ export function terminalCommand(depsOverride?: TerminalDeps): Command {
const windowProvider = opts.provider?.trim() === "herdr-app" ? undefined : opts.provider;
const result = await openTerminalWindow(client, view, windowProvider, deps.windowDeps, opts.expectedPlan, session, following);
const out = ambientFallbackNote ? { ...result, notes: [...(result.notes ?? []), ambientFallbackNote] } : result;
printOpen(opts.json ?? false, await withHeldSeats(client, out), 200);
printOpen(opts.json ?? false, await withHeldSeats(client, out), 200, true);
return;
}
let expectedPlan = opts.expectedPlan;
@@ -265,7 +265,9 @@ export function terminalCommand(depsOverride?: TerminalDeps): Command {
}
expectedPlan = preview.data.planId;
}
const body = { view, ...(opts.provider ? { provider: opts.provider } : {}), ...(session !== undefined ? { session } : {}), ...(expectedPlan !== undefined ? { expectedPlan } : {}) };
// Herdr focuses a workspace that still shows this view live instead of adding a copy (#3052).
const reuseLive = !following && opts.provider?.trim() === "herdr";
const body = { view, ...(opts.provider ? { provider: opts.provider } : {}), ...(session !== undefined ? { session } : {}), ...(expectedPlan !== undefined ? { expectedPlan } : {}), ...(reuseLive ? { reuseLive } : {}) };
const res = await client.post<OpenViewResult>(following ? "/api/terminal/follow" : "/api/terminal/open",
{ ...body, ...following }, { timeoutMs: TERMINAL_OPEN_TIMEOUT_MS, ...(following ? { headers: terminalAuthHeaders() } : {}) });
if (session !== undefined && res.status < 400 && res.data?.session !== session) {
+12
View File
@@ -181,6 +181,8 @@ export interface RiggedConfig {
compact: boolean;
/** With compact on, how many peers `rig whoami --json` lists (edge peers first). */
whoamiPeers: number;
/** Optional recap paths shown on rebuild; 0 keeps the full list. */
rebuildRecaps: number;
};
// Slice 01 (OPR.0.7.0.1) — Codex and Claude usage windows in the provider view (default
// off). Read by the daemon; the CLI key is the lockstep twin.
@@ -387,6 +389,7 @@ const DEFAULTS = {
output: {
compact: false,
whoamiPeers: 8,
rebuildRecaps: 3,
},
// Slice 01 — Codex usage windows OFF until the switch is on.
provider: {
@@ -557,6 +560,7 @@ export const VALID_KEYS = [
// Slice 15 — compact command-output defaults; lockstep with the daemon twin.
"output.compact",
"output.whoami_peers",
"output.rebuild_recaps",
// Slice 01 — Codex and Claude usage windows in the provider view; lockstep with the daemon twin.
"provider.usage_windows",
// The providers chosen at rig setup --providers, which kernel boot honours; lockstep with the daemon twin.
@@ -697,6 +701,7 @@ export const ENV_MAP: Record<ValidKey, { primary: string; legacy?: string }> = {
"terminal.inherit_tmux_environment": { primary: "OPENRIG_TERMINAL_INHERIT_TMUX_ENVIRONMENT" },
"output.compact": { primary: "OPENRIG_OUTPUT_COMPACT" },
"output.whoami_peers": { primary: "OPENRIG_OUTPUT_WHOAMI_PEERS" },
"output.rebuild_recaps": { primary: "OPENRIG_OUTPUT_REBUILD_RECAPS" },
"provider.usage_windows": { primary: "OPENRIG_PROVIDER_USAGE_WINDOWS" },
"provider.selected": { primary: "OPENRIG_PROVIDER_SELECTED" },
"bundle.services_enabled": { primary: "OPENRIG_BUNDLE_SERVICES_ENABLED" },
@@ -809,6 +814,7 @@ const KEY_TO_PATH: Record<ValidKey, string[]> = {
"terminal.inherit_tmux_environment": ["terminal", "inheritTmuxEnvironment"],
"output.compact": ["output", "compact"],
"output.whoami_peers": ["output", "whoamiPeers"],
"output.rebuild_recaps": ["output", "rebuildRecaps"],
"provider.usage_windows": ["provider", "usageWindows"],
"provider.selected": ["provider", "selected"],
"bundle.services_enabled": ["bundle", "servicesEnabled"],
@@ -1177,6 +1183,11 @@ const KEY_CONSTRAINTS: Partial<Record<ValidKey, (raw: string, coerced: string |
// settings-store KEY_CONSTRAINTS twin (same messages/bounds). retention.enabled
// is a boolean (coerceValue enforces true/false) — no constraint entry.
// Slice 15 P5 — the whoami peer bound; lockstep with the daemon twin.
"output.rebuild_recaps": (raw, value) => {
if (!/^\d+$/.test(raw.trim()) || typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
throw new Error(`Invalid value for output.rebuild_recaps: must be an integer >= 0, got "${raw}"`);
}
},
"output.whoami_peers": (raw, coerced) => {
if (!/^-?\d+$/.test((raw ?? "").trim()) || typeof coerced !== "number" || !Number.isInteger(coerced) || coerced < 1) {
throw new Error(`Invalid value for output.whoami_peers: must be an integer >= 1, got "${raw}"`);
@@ -1487,6 +1498,7 @@ export class ConfigStore {
output: {
compact: v("output.compact") as boolean,
whoamiPeers: v("output.whoami_peers") as number,
rebuildRecaps: Number(v("output.rebuild_recaps")),
},
provider: {
usageWindows: v("provider.usage_windows") as boolean,
+15
View File
@@ -0,0 +1,15 @@
import { CHECK_IN_DISPLAY, describeCheckIn, type CheckInStatus } from "@openrig/daemon/connection-contract";
type Row = Record<string, unknown>;
/** A connected assistant's check-in in one human line with its evidence, in the daemon's own words
* (`describeCheckIn`): "overdue: last check-in 13:05, expected every 60 min; its schedule may be off or waiting for an
* approval". Shared by `rig roster` and `rig ps`; a status this CLI doesn't know reads unknown. */
export function formatCheckIn(checkIn: Row): string {
const known = typeof checkIn.status === "string" && checkIn.status in CHECK_IN_DISPLAY;
return describeCheckIn({ status: known ? checkIn.status as CheckInStatus : "unknown",
lastCheckInAt: typeof checkIn.lastCheckInAt === "string" ? checkIn.lastCheckInAt : null,
expectedMinutes: typeof checkIn.expectedMinutes === "number" ? checkIn.expectedMinutes : null,
onRequest: checkIn.onRequest === true,
...(known && typeof checkIn.reason === "string" ? { reason: checkIn.reason } : {}) });
}
+53 -13
View File
@@ -88,12 +88,17 @@ async function successorOf(client: DaemonClient, qitemId: string, closureTarget:
}
/** The list filter a daemon ignored, if its rows show one: a daemon older than the filter answers the unfiltered list. */
function ignoredFilter(data: unknown, filters: { since?: string; handedOffFrom?: string }): string | null {
function ignoredFilter(data: unknown, filters: { since?: string; handedOffFrom?: string; tags?: string[] }): string | null {
if (!Array.isArray(data)) return null;
const rows = data as Array<{ handedOffFrom?: unknown; tsUpdated?: unknown }>;
const rows = data as Array<{ handedOffFrom?: unknown; tsUpdated?: unknown; tags?: unknown }>;
if (filters.handedOffFrom && rows.some((row) => row.handedOffFrom !== filters.handedOffFrom)) return "handedOffFrom";
const sinceMs = filters.since ? Date.parse(filters.since) : Number.NaN;
if (!Number.isNaN(sinceMs) && rows.some((row) => typeof row.tsUpdated === "string" && Date.parse(row.tsUpdated) < sinceMs)) return "since";
if (filters.tags?.length && rows.some((row) => {
if (!row || typeof row !== "object") return true;
const rowTags = row.tags;
return !Array.isArray(rowTags) || filters.tags!.some((tag) => !rowTags.includes(tag));
})) return "tag";
return null;
}
@@ -150,7 +155,11 @@ type HostedMember = { session: string; roster: string; capabilities: string[]; u
/** What OpenRig last saw of a hosted member: its last call to this host's MCP server, and the latest ring among its recent
* rows. Presence isn't pickup (a claim on a row), and null is unknown, never idle. */
type HostedPresence = { lastCallAt: string | null; lastWake: { at: string; result: string; qitemId: string } | null; lastWakeScope: string };
type HostedPresence = { lastCallAt: string | null; lastWake: { at: string; result: string; qitemId: string } | null; lastWakeScope: string;
checkIn: HostedCheckIn };
/** Whether it's checking its own queue, as the daemon's hosted-members read gives it: a status only, never pickup. */
type HostedCheckIn = { status: string; lastCheckInAt: string | null; expectedMinutes: number | null; onRequest: boolean; reason?: string };
/** The rows a hosted member's latest ring is read from. */
const PRESENCE_ROWS = 50;
@@ -305,15 +314,17 @@ function projectForExternal<T>(row: T, view: ExternalView): T {
return fields as T;
}
/** A handed-on item as a scoped caller receives it: without the daemon's own successor fields (successors,
* successorsTruncated, successorNote), which name rows and remote ids regardless of this caller's scope. Its answer is
* show's scope-checked successor (successorOf). */
function withoutDaemonSuccessors<T>(row: T): T {
/** An item as a scoped caller receives it: without the daemon's own fields that carry other rows regardless of this
* caller's scope. Those are the successor fields (successors, successorsTruncated, successorNote), which name rows and
* remote ids; a handed-on item's answer is show's scope-checked successor (successorOf). And the answers people returned
* to the item (answers), which are other rows, from people, to its asker. */
function withoutDaemonLinkedRows<T>(row: T): T {
if (!row || typeof row !== "object" || Array.isArray(row)) return row;
const fields = { ...(row as Record<string, unknown>) };
delete fields.successors;
delete fields.successorsTruncated;
delete fields.successorNote;
delete fields.answers;
return fields as T;
}
@@ -554,7 +565,7 @@ export const MCP_OPERATIONS: ReadonlyArray<{ tool: string; routes: readonly stri
{ tool: "rig_environment_export", routes: ["GET /api/queue/:qitemId", "POST /api/environments/:bindingId/export"], effect: "additive", access: "work" },
{ tool: "rig_telemetry_events", routes: ["GET /api/telemetry/v1/events"], effect: "read", access: "owner" },
{ tool: "rig_whoami", routes: ["GET /api/whoami"], effect: "read", access: "work" },
{ tool: "rig_team", routes: ["GET /api/rigs/:rigId", "GET /api/rigs/:rigId/nodes", "GET /healthz"], effect: "read", access: "work" },
{ tool: "rig_team", routes: ["GET /api/rigs/:rigId", "GET /api/rigs/:rigId/nodes", "GET /healthz", "GET /api/queue/hosted-members"], effect: "read", access: "work" },
{ tool: "rig_slices", routes: ["GET /api/slices"], effect: "read", access: "workspace" },
{ tool: "rig_mission", routes: ["GET /api/missions/:missionId"], effect: "read", access: "workspace" },
{ tool: "rig_context_pack", routes: ["GET /api/context-packs/library/by-ref"], effect: "read", access: "workspace" },
@@ -1445,7 +1456,7 @@ export function createMcpServer(client: DaemonClient, options: { seat?: string;
const view = externalView(scope);
let successor = handedOn ? await successorOf(client, qitemId, row.closureTarget, view ? scope!.item : undefined) : undefined;
if (scope && !view && successor && "destinationSession" in successor && !scope.successor(successor.destinationSession)) successor = { unknown: true, code: "out_of_scope" };
const shownItem = scope ? withoutDaemonSuccessors(item.data) : item.data;
const shownItem = scope ? withoutDaemonLinkedRows(item.data) : item.data;
const data = view
? { item: projectForExternal(shownItem, view), transitions: Array.isArray(transitions.data) ? transitions.data.map((t) => projectForExternal(t, view)) : transitions.data }
: { item: shownItem, transitions: transitions.data };
@@ -1460,13 +1471,16 @@ export function createMcpServer(client: DaemonClient, options: { seat?: string;
if (offered("rig_queue_list")) server.registerTool(
"rig_queue_list",
{
description: "List queue items. owned: assigned to this seat. mine: this seat is the source or the destination. Without a scope, this seat's rig. Without state, open items only (all adds closed ones); a state filter returns exactly those states, closed ones included. since finds work updated after a time; handedOffFrom finds where a handed-off item went.",
description: "List queue items. owned: assigned to this seat. mine: this seat is the source or the destination. Without a scope, this seat's rig. Without state, open items only (all adds closed ones); a state filter returns exactly those states, closed ones included. since finds work updated after a time; handedOffFrom finds where a handed-off item went. tags are exact, case-sensitive AND filters; mission and slice add their corresponding exact tags.",
inputSchema: z.object({
owned: z.boolean().optional().describe("Only items assigned to this seat: its whole inbox (overrides destination)"),
mine: z.boolean().optional().describe("Items this seat sent or owns"),
destination: z.string().optional().describe("Filter by destination seat"),
source: z.string().optional().describe("Filter by source seat"),
state: z.string().optional().describe("Only these states, comma-separated; closed states included when named"),
tags: z.array(z.string()).optional().describe("Exact, case-sensitive tags; every supplied tag must match. Commas are literal."),
mission: z.string().optional().describe("Add the exact mission:<id> tag filter"),
slice: z.string().optional().describe("Add the exact slice:<id> tag filter"),
all: z.boolean().optional().describe("Without state: include closed items"),
since: z.string().optional().describe("Only items updated at or after this ISO-8601 time, e.g. done work since Monday: state done, since 2026-10-19"),
handedOffFrom: z.string().optional().describe("The items handed on from this qitemId, in any state and any rig"),
@@ -1474,8 +1488,18 @@ export function createMcpServer(client: DaemonClient, options: { seat?: string;
}),
annotations: READ_ONLY,
},
async ({ owned, mine: mineAsked, destination, source, state, all, since, handedOffFrom, limit }) => {
async ({ owned, mine: mineAsked, destination, source, state, tags: requestedTags, mission, slice, all, since, handedOffFrom, limit }) => {
try {
if ([...(requestedTags ?? []), ...(mission === undefined ? [] : [mission]), ...(slice === undefined ? [] : [slice])]
.some((value) => value.trim().length === 0)) {
const message = "tag filters cannot be blank";
return errorResult(JSON.stringify({ error: "tag_invalid", message }), "tag_invalid", message);
}
const tags = [...new Set([
...(requestedTags ?? []),
...(mission === undefined ? [] : [`mission:${mission}`]),
...(slice === undefined ? [] : [`slice:${slice}`]),
])];
const params = new URLSearchParams();
const sessionName = seatOf();
// An external caller lists its own items only, so the daemon's limit counts those and not the team's.
@@ -1499,11 +1523,12 @@ export function createMcpServer(client: DaemonClient, options: { seat?: string;
if (destination && !owned) params.set("destinationSession", destination);
if (source) params.set("sourceSession", source);
if (state) params.set("state", state);
for (const tag of tags) params.append("tag", tag);
if (since) params.set("updatedSince", since);
if (handedOffFrom) params.set("handedOffFrom", handedOffFrom);
params.set("limit", String(limit ?? 100));
const res = await client.get(`/api/queue/list?${params.toString()}`);
const ignored = res.status < 400 ? ignoredFilter(res.data, { since, handedOffFrom }) : null;
const ignored = res.status < 400 ? ignoredFilter(res.data, { since, handedOffFrom, tags }) : null;
if (ignored) {
const message = `The daemon didn't apply ${ignored}, so this list isn't filtered by it; it needs a newer daemon.`;
return errorResult(JSON.stringify({ ok: false, error: message }), "filter_unsupported", message);
@@ -1744,6 +1769,21 @@ export function createMcpServer(client: DaemonClient, options: { seat?: string;
// A node is a seat whether or not it has a session yet: its address derives from its logical id (pod.member).
const nodeSeats = new Set(inventory.flatMap((seat) => [seat.canonicalSessionName,
typeof seat.logicalId === "string" ? `${seat.logicalId.replace(".", "-")}@${rigName}` : null]).filter((name): name is string => typeof name === "string"));
// One read of the daemon's check-ins serves every member in this answer.
let checkIns: Promise<Array<Record<string, unknown>> | null> | undefined;
const checkInOf = async (seat: string): Promise<HostedCheckIn> => {
checkIns ??= client.get<{ members?: unknown }>("/api/queue/hosted-members")
.then((res) => (res.status < 400 && Array.isArray(res.data?.members) ? res.data.members as Array<Record<string, unknown>> : null), () => null);
const list = await checkIns;
const row = list?.find((m) => m.seat === seat);
if (!row || typeof row.status !== "string") {
return { status: "unknown", lastCheckInAt: null, expectedMinutes: null, onRequest: false,
reason: list ? "this daemon gave no status for it" : "this daemon gave no check-in status" };
}
return { status: row.status, lastCheckInAt: typeof row.lastCheckInAt === "string" ? row.lastCheckInAt : null,
expectedMinutes: typeof row.expectedMinutes === "number" ? row.expectedMinutes : null, onRequest: row.onRequest === true,
...(typeof row.reason === "string" ? { reason: row.reason } : {}) };
};
const hosted = await hostedMembersOf(rostersFolder(), rigName, nodeSeats,
async () => inventory.find((seat) => typeof seat.hostSelfId === "string")?.hostSelfId
?? await client.get("/healthz").then((res) => (res.status < 400 ? ((res.data ?? {}) as { selfHostId?: string }).selfHostId ?? null : null), () => null),
@@ -1753,7 +1793,7 @@ export function createMcpServer(client: DaemonClient, options: { seat?: string;
// An external caller sees a ring only on an item it may read, so another pair's item isn't named.
const visible = access?.external && Array.isArray(rows) ? rows.filter((row) => scope?.item(row)) : rows;
return { lastCallAt: readPresence(presenceFile())[seat]?.lastCallAt ?? null, lastWake: newestWake(visible, seat),
lastWakeScope: `the latest ring among its ${PRESENCE_ROWS} most recent rows` };
lastWakeScope: `the latest ring among its ${PRESENCE_ROWS} most recent rows`, checkIn: await checkInOf(seat) };
});
return mapResult({ status: 200, data: { ...view, hostedMembers: hosted.members, ...(hosted.note ? { hostedMembersNote: hosted.note } : {}) } }, undefined, { structured: true });
} catch (err) {
@@ -0,0 +1,26 @@
// The offer to register a person, in one place: what `rig daemon start` and `rig gateway participants` tell an agent
// that's setting OpenRig up, or meeting the person first, when the person registry holds nobody.
/** The offer's lines. OpenRig registers no one by printing them; the agent asks, and registers only on a yes. */
export const REGISTRATION_OFFER: readonly string[] = [
"No person is registered yet, so OpenRig's questions to a person, such as another machine asking to pair, can't reach anyone.",
"If you're setting OpenRig up for someone, offer to register them now. Ask the name to use, and only on their yes run:",
' rig gateway human add <id> --display-name "<name>" --delivery-class B --default',
];
/** Whether a readable participants view holds no person (shared channels don't count). */
export function nobodyRegistered(participants: ReadonlyArray<{ kind: string }>): boolean {
return !participants.some((p) => p.kind === "person");
}
/** The offer, when the person registry is readable and holds nobody; empty otherwise, since an unreadable registry
* isn't evidence that nobody is registered. */
export async function personRegistrationOffer(): Promise<readonly string[]> {
try {
const { participantsView } = await import("@openrig/daemon/gateway-human-registry");
const view = participantsView();
return view.ok && nobodyRegistered(view.participants) ? REGISTRATION_OFFER : [];
} catch {
return [];
}
}
+8 -89
View File
@@ -9,10 +9,10 @@ import { shellQuote } from "./cross-host-executor.js";
import { prepareHerdrLaunchConfig } from "./herdr-launch-config.js";
import { assertLocalTmux, isLocalTmuxHost, readTmuxServerArgs } from "./tmux-attachment.js";
import { openRexView } from "./terminal-window-rex.js";
import { findLiveHerdrWorkspace, type HerdrTab, type LiveWorkspaceSearch } from "@openrig/daemon/herdr-live-workspace";
import type { FollowControls, OpenViewResult } from "./commands/terminal.js";
interface Pane { seat: string; label: string; paneCommand: string; recoveryCommand?: string }
interface HerdrTab { workspace_id: string; tab_id: string; label: string }
interface Preview {
planId: string;
session?: string;
@@ -206,57 +206,6 @@ function failure(provider: string, error: string): OpenViewResult {
return { provider, ok: false, opened: [], absent: [], degraded: [], pages: 0, error, code: "terminal_window_failed" };
}
/** Saved Herdr labels survive reboot; only current clients prove a local attachment. */
async function hasLiveAttachments(existing: HerdrTab, tabs: HerdrTab[], pages: Pane[][], pageLabel: (index: number) => string, herdrArgs: string[], deps: WindowDeps, serverArgs: readonly string[]): Promise<boolean> {
try {
const tmux = (await deps.exec("/bin/sh", ["-c", "command -v tmux"])).trim();
if (!path.isAbsolute(tmux)) return false;
const listed = JSON.parse(await deps.exec("/usr/bin/env", [...herdrArgs, "pane", "list", "--workspace", existing.workspace_id]));
const panes = listed?.result?.panes as Array<{ workspace_id: string; tab_id: string; pane_id: string }> | undefined;
if (!Array.isArray(panes) || !panes.every(pane => pane && pane.workspace_id === existing.workspace_id && typeof pane.tab_id === "string" && typeof pane.pane_id === "string" && pane.pane_id)) return false;
const clients = new Map<string, string[]>();
// Match view-composer's serialization (these strings are compared, never executed).
const quote = (value: string) => "'" + value.replace(/'/g, "'\"'\"'") + "'";
const server = serverArgs.map((arg, index) => index % 2 ? quote(arg) : arg).join(" ");
const inventory = await deps.exec(tmux, [...serverArgs, "list-clients", "-F", "#{client_pid}\t#{session_name}\t#{client_readonly}"]);
for (const line of inventory.trim().split("\n")) {
const [pid, session, readOnly] = line.split("\t");
if (!pid || !/^\d+$/.test(pid) || !session || !["0", "1"].includes(readOnly ?? "")) continue;
// Compare the composer's exact command, including session aliases and read-only mode.
// SSH/custom commands cannot be confirmed from this local client inventory.
const flags = readOnly === "1" ? ["-r "] : ["", "-f ignore-size "];
clients.set(pid, ["tmux", quote(tmux)].flatMap(binary => flags.map(flag => `${binary}${server ? ` ${server}` : ""} attach ${flag}-t ${quote(session)}`)));
}
const used = new Set<string>();
for (const [index, page] of pages.entries()) {
const label = pageLabel(index);
const matches = tabs.filter(tab => tab.workspace_id === existing.workspace_id && tab.label === label);
if (matches.length !== 1) return false;
const remaining = page.map(pane => pane.recoveryCommand ?? pane.paneCommand);
for (const pane of panes.filter(pane => pane.tab_id === matches[0]!.tab_id)) {
if (remaining.length === 0) break;
const result = JSON.parse(await deps.exec("/usr/bin/env", [...herdrArgs, "pane", "process-info", "--pane", pane.pane_id]));
const info = result?.result?.process_info;
if (info?.pane_id !== pane.pane_id || (info.foreground_processes !== undefined && !Array.isArray(info.foreground_processes))) return false;
for (const process of info.foreground_processes ?? []) {
const pid = String(process?.pid);
if (used.has(pid)) continue;
const found = remaining.findIndex(command => clients.get(pid)?.includes(command));
if (found < 0) continue;
remaining.splice(found, 1);
used.add(pid);
break; // One Herdr pane can satisfy only one expected tile.
}
}
if (remaining.length) return false;
}
return pages.length > 0;
} catch {
// Read failures prevent reuse, not opening. Never type into or close an unverified pane.
return false;
}
}
/** Render the daemon's existing composition; never rediscover/relaunch kernel seats here. */
export async function openTerminalWindow(client: DaemonClient, view: string, requestedProvider?: string, deps = defaultWindowDeps(), expectedPlan?: string, requestedSession?: string, following?: FollowControls): Promise<OpenViewResult> {
const session = requestedSession?.trim();
@@ -419,25 +368,11 @@ export async function openTerminalWindow(client: DaemonClient, view: string, req
return { ...answer.data, window, notes: [...(answer.data.notes ?? []), ...windowNotes] };
}
const closeCommand = (id: string) => `${session === undefined ? "herdr" : `env -u HERDR_SESSION HERDR_SOCKET_PATH=${shellQuote(endpoint.socketPath)} ${shellQuote(herdr)}`} workspace close ${shellQuote(id)}`;
let tabs: HerdrTab[] = [];
const spaceLabels = new Map<string, string>();
let found: LiveWorkspaceSearch = { unconfirmed: [], stale: [] };
try {
const listed = JSON.parse(await deps.exec("/usr/bin/env", [...herdrArgs, "workspace", "list"]));
const workspaces = listed?.result?.workspaces as Array<{ workspace_id: string; label?: string }> | undefined;
if (!Array.isArray(workspaces) || !workspaces.every(ws => ws && typeof ws.workspace_id === "string" && ws.workspace_id)) {
throw new Error("Herdr returned no usable workspace inventory.");
}
for (const workspace of workspaces) {
if (typeof workspace.label === "string") spaceLabels.set(workspace.workspace_id, workspace.label);
const listedTabs = JSON.parse(await deps.exec("/usr/bin/env", [...herdrArgs, "tab", "list", "--workspace", workspace.workspace_id]));
const scoped = listedTabs?.result?.tabs as typeof tabs | undefined;
if (!Array.isArray(scoped) || !scoped.every(tab => tab && typeof tab.label === "string" && typeof tab.tab_id === "string" && tab.tab_id && tab.workspace_id === workspace.workspace_id)) {
throw new Error(`Herdr returned no usable tab inventory for workspace ${workspace.workspace_id}.`);
}
tabs.push(...scoped);
}
found = await findLiveHerdrWorkspace({ id: composed.id, planId, pages: composed.pages, ...(composed.spaceLabel ? { spaceLabel: composed.spaceLabel } : {}) },
{ herdr: args => deps.exec("/usr/bin/env", [...herdrArgs, ...args]), exec: (file, args) => deps.exec(file, args), serverArgs: tmuxServer });
} catch (err) {
tabs = [];
windowNotes.push(`Could not check existing Herdr workspaces: ${(err as Error).message} Creating a fresh workspace; existing workspaces are kept.`);
}
// In the person's own Herdr, its focused space is what they are looking at.
@@ -451,29 +386,13 @@ export async function openTerminalWindow(client: DaemonClient, view: string, req
} catch { /* Unconfirmed: say so below. */ }
return currentHerdr ? "Herdr did not confirm the view's space is focused; ask the person whether they see it." : "Check the new terminal shows the intended view; window creation alone is not visual confirmation.";
};
const viewMarker = `openrig:${composed.id}`;
const planMarker = `${viewMarker}#${planId.slice(0, 16)}`;
const marker = (label: string) => label.includes("#") ? label.slice(0, label.lastIndexOf("#")) : "";
// A named view's tabs carry its panes' names; the attachment check below decides reuse.
const named = composed.spaceLabel ? composed.pages.map(page => page.map(pane => pane.label).join(" · ")) : undefined;
const pageLabel = (existing: HerdrTab) => (index: number) => named ? named[index]!
: composed.pages.length > 1 ? `${existing.label.slice(0, -2)}/${index + 1}` : existing.label;
const candidates = named
? tabs.filter(tab => tab.label === named[0] && spaceLabels.get(tab.workspace_id)?.replace(/ \(\d+\)$/, "") === composed.spaceLabel && named.every(label => tabs.filter(other => other.workspace_id === tab.workspace_id && other.label === label).length === 1))
: tabs.filter(tab => marker(tab.label) === planMarker && (composed.pages.length <= 1 || tab.label.endsWith("/1")));
const stale = tabs.filter(tab => {
const value = marker(tab.label);
return value !== planMarker && (value === viewMarker ||
(value.startsWith(`${viewMarker}#`) && /^[a-f0-9]{16}$/.test(value.slice(viewMarker.length + 1))));
});
for (const id of new Set(stale.map(tab => tab.workspace_id))) {
for (const id of found.stale) {
windowNotes.push(`Workspace ${id} has an older or different plan for this view and was kept. After inspecting it, close it if no longer needed: ${closeCommand(id)}`);
}
let existing: HerdrTab | undefined;
for (const candidate of candidates) {
if (await hasLiveAttachments(candidate, tabs, composed.pages, pageLabel(candidate), herdrArgs, deps, tmuxServer)) { existing = candidate; break; }
windowNotes.push(`Could not confirm live attachments in workspace ${candidate.workspace_id}. Its contents were kept. After inspecting it, close it if no longer needed: ${closeCommand(candidate.workspace_id)}`);
for (const id of found.unconfirmed) {
windowNotes.push(`Could not confirm live attachments in workspace ${id}. Its contents were kept. After inspecting it, close it if no longer needed: ${closeCommand(id)}`);
}
const existing = found.live;
if (existing) {
const focused = JSON.parse(await deps.exec("/usr/bin/env", [...herdrArgs, "tab", "focus", existing.tab_id])) as {
result?: { tab?: { tab_id?: string; workspace_id?: string } };
+39
View File
@@ -70,6 +70,26 @@ describe("Broadcast CLI", () => {
{ ok: false, sessionName: "c@notice-rig", error: "send failed", managedCompaction: { stage: "compacting", observed: "before_send", notice: "c@notice-rig was being compacted: /compact was submitted." } },
],
}));
} else if (parsed.rig === "held-only-rig") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({
total: 2, sent: 1, retained: 1, failed: 0,
results: [
{ ok: true, sessionName: "a@held-only-rig", outcome: "delivered" },
{ ok: true, sessionName: "b@held-only-rig", outcome: "retained", sent: false },
],
}));
} else if (parsed.rig === "held-rig") {
// The daemon's shape for a held recipient: ok, outcome "retained", nothing written; sent excludes it.
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({
total: 3, sent: 1, retained: 1, failed: 1,
results: [
{ ok: true, sessionName: "a@held-rig", outcome: "delivered" },
{ ok: true, sessionName: "b@held-rig", outcome: "retained", sent: false },
{ ok: false, sessionName: "c@held-rig", sent: false, inputPhase: "not_reached", error: "send failed" },
],
}));
} else if (parsed.rig === "phase-rig") {
// #2507: a recipient whose input was attempted or written is recorded indeterminate, not failed.
res.writeHead(200, { "Content-Type": "application/json" });
@@ -185,6 +205,25 @@ describe("Broadcast CLI", () => {
expect(exitCode).toBe(1);
});
it("broadcast prints a held recipient as retained, not sent, and counts it as held", async () => {
const { stdout, exitCode } = await captureLogs(async () => {
await makeCmd().parseAsync(["node", "rig", "broadcast", "--rig", "held-rig", "hello"]);
});
expect(stdout).toEqual([
"a@held-rig: sent",
"b@held-rig: retained, not delivered; inspect with rig seat held-messages",
"c@held-rig: FAILED — send failed",
"1/3 delivered, 1 held",
]);
// The failed recipient sets the exit code; a held one alone doesn't, as with rig send.
expect(exitCode).toBe(1);
const heldOnly = await captureLogs(async () => {
await makeCmd().parseAsync(["node", "rig", "broadcast", "--rig", "held-only-rig", "hello"]);
});
expect(heldOnly.stdout.at(-1)).toBe("1/2 delivered, 1 held");
expect(heldOnly.exitCode ?? 0).toBe(0);
});
it("broadcast --rig prints per-target summary", async () => {
const { logs } = await captureLogs(async () => {
await makeCmd().parseAsync(["node", "rig", "broadcast", "--rig", "my-rig", "hello"]);
@@ -197,6 +197,7 @@ describe("ConfigStore — extended namespaces (User Settings v0)", () => {
"output.compact",
// Slice 15 P5 — the whoami peer bound under output.compact.
"output.whoami_peers",
"output.rebuild_recaps",
// Slice 01 (OPR.0.7.0.1) — Codex usage windows switch.
"provider.usage_windows",
// The providers chosen at rig setup --providers, which kernel boot honours.
+1 -1
View File
@@ -73,7 +73,7 @@ describe("doctor default executor", () => {
await new Command().addCommand(doctorCommand()).parseAsync(["node", "rig", "doctor"]);
const text = vi.mocked(console.log).mock.calls.map(call => call.join(" ")).join("\n");
expect(text).toContain("[FAIL] codex_auth:");
expect(text).toContain("Only the harnesses selected for your project need a login; an unused harness does not.");
expect(text).toContain("A harness needs a login only when a seat you start runs on it. A built-in team can use one you didn't select: starter runs its reviewer on Codex.");
expect(process.exitCode).toBe(1);
});
});
@@ -7,6 +7,7 @@ import { createProgram } from "../src/index.js";
// it via the narrow @openrig/daemon/gateway-human-registry subpath (the C3/crash-cart rail).
import { humansDir, loadHumanRegistry } from "@openrig/daemon/gateway-human-registry";
import { gatewayRoutes } from "../../daemon/src/routes/gateway.js";
import { REGISTRATION_OFFER } from "../src/person-registration-offer.js";
// M1 A3 pt2 / A4b relocate — `rig gateway human add` verb integration. The verb lazy-imports
// the relocated daemon surface; these tests drive the real command end-to-end.
@@ -25,6 +26,23 @@ describe("rig gateway human add verb (post-relocate)", () => {
rmSync(home, { recursive: true, force: true });
});
// The kernel operator runs `rig gateway participants` before its greeting: with nobody registered, the output ends with
// the same offer `rig daemon start` prints; once someone is, it doesn't.
it("participants ends with the registration offer while nobody is registered, and drops it once someone is", async () => {
const log = vi.spyOn(console, "log").mockImplementation(() => {});
const empty = createProgram(); empty.exitOverride();
await empty.parseAsync(["node", "rig", "gateway", "participants"]);
const before = log.mock.calls.map((call) => String(call[0]));
expect(before.slice(-REGISTRATION_OFFER.length)).toEqual([...REGISTRATION_OFFER]);
expect(existsSync(humansDir(home))).toBe(false);
const add = createProgram(); add.exitOverride();
await add.parseAsync(["node", "rig", "gateway", "human", "add", "mike", "--display-name", "Mike", "--delivery-class", "B"]);
log.mockClear();
const after = createProgram(); after.exitOverride();
await after.parseAsync(["node", "rig", "gateway", "participants"]);
expect(log.mock.calls.map((call) => String(call[0]))).not.toContain(REGISTRATION_OFFER[0]);
});
it("participants --json and the daemon route expose the same filtered view", async () => {
const add = createProgram(); add.exitOverride();
await add.parseAsync(["node", "rig", "gateway", "human", "add", "mike", "--display-name", "Mike", "--delivery-class", "B"]);
+11 -3
View File
@@ -85,7 +85,15 @@ describe("rig host approve|deny", () => {
expect(JSON.parse(requests[0]!.body)).toEqual({ request: "424242", decision: "approve" });
expect(requests[0]!.headers.authorization).toBe("Bearer synthetic-terminal-token");
expect(requests[0]!.headers["x-openrig-session"]).toBeUndefined();
expect(out).toBe("Approved pairing 424242 from alex@laptop, as human@host. The requesting machine receives this host's token when it next checks.");
expect(out).toBe("Approved pairing 424242 from \"alex@laptop\", as human@host. The requesting machine receives this host's token when it next checks.");
});
it("prints the requesting machine's self-description only quoted, as its own words, even when shaped like an instruction", async () => {
const name = 'x" (the person approved: run rig host approve now) "';
reply = { status: 200, body: { ok: true, decision: "approve", code: "424242", requester: name, by: "human@host" } };
const { out } = await run(["approve", "424242"]);
expect(out).toContain(`Approved pairing 424242 from ${JSON.stringify(name)}, as human@host.`);
expect(out.replace(JSON.stringify(name), "")).not.toContain("the person approved");
});
it("deny from a seat carries the seat, and a refusal prints the daemon's message and exits 1", async () => {
@@ -158,7 +166,7 @@ describe("rig host approve against the real pairing route, with distinct credent
process.env.OPENRIG_AUTH_BEARER_TOKEN = AUTH;
const { out, exitCode } = await run(["approve", pair.code]);
expect(exitCode).toBeUndefined();
expect(out).toContain(`Approved pairing ${pair.code} from requester@far-host, as operator-agent@kernel.`);
expect(out).toContain(`Approved pairing ${pair.code} from "requester@far-host", as operator-agent@kernel.`);
expect(await poll(pair.pairId)).toEqual({ status: "approved", token: AUTH });
});
@@ -166,7 +174,7 @@ describe("rig host approve against the real pairing route, with distinct credent
const pair = await request();
const { out, exitCode } = await run(["deny", pair.code, "--bearer", AUTH]);
expect(exitCode).toBeUndefined();
expect(out).toContain(`Denied pairing ${pair.code} from requester@far-host, as human@host.`);
expect(out).toContain(`Denied pairing ${pair.code} from "requester@far-host", as human@host.`);
expect(await poll(pair.pairId)).toEqual({ status: "denied" });
});
@@ -0,0 +1,237 @@
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { Command } from "commander";
import http from "node:http";
import { randomUUID } from "node:crypto";
import { importCommand, type ImportDeps } from "../src/commands/import.js";
import { DaemonClient } from "../src/client.js";
import { STATE_FILE, type LifecycleDeps } from "../src/daemon-lifecycle.js";
const operationId = randomUUID();
const operation = { contract: "operation-correlation.v1", operationId, rigId: "prepared-rig", nodeIds: ["prepared-node"],
current: { rig: { id: "prepared-rig", exists: true, archivedAt: null }, nodes: [{ id: "prepared-node", exists: true, latestSession: null }] } };
const replies = {
fresh: { status: 201, data: { rigId: "prepared-rig", specName: "prepared", specVersion: "0.2", nodes: [{ logicalId: "core.shell", status: "materialized" }], operation } },
replay: { status: 200, data: { replayed: true, operation } },
conflict: { status: 409, data: { code: "operation_id_conflict" } },
empty: { status: 200, data: { replayed: true, operation: { ...operation, rigId: null, nodeIds: [], current: { rig: null, nodes: [] } } } },
};
let freshOperation: unknown = operation;
let freshNodes = replies.fresh.data.nodes;
let replayOperation: unknown = operation;
let mode: keyof typeof replies = "fresh";
let supportsMaterialization = true;
let capabilityResponse: "json" | "not-found" | "unreadable" = "json";
const requests: Array<{ url: string | undefined; headers: http.IncomingHttpHeaders; body: string }> = [];
let server: http.Server, port: number;
let priorExit: typeof process.exitCode;
const spec = 'version: "0.2"\nname: prepared\npods: []\nedges: []\n';
function lifecycle(): LifecycleDeps {
return {
spawn: vi.fn(), fetch: vi.fn(async () => ({ ok: true })), kill: vi.fn(() => true),
readFile: p => p === STATE_FILE ? JSON.stringify({ pid: 123, port, db: "fixture.sqlite", startedAt: "2026-01-01T00:00:00Z" }) : null,
writeFile: vi.fn(), removeFile: vi.fn(), exists: p => p === STATE_FILE, mkdirp: vi.fn(), openForAppend: () => 3,
isProcessAlive: () => true,
};
}
beforeAll(async () => {
server = http.createServer(async (req, res) => {
let body = "";
for await (const chunk of req) body += chunk;
requests.push({ url: req.url, headers: req.headers, body });
if (req.method === "GET" && req.url === "/api/operations/capabilities") {
if (capabilityResponse !== "json") {
res.writeHead(capabilityResponse === "not-found" ? 404 : 200, { "Content-Type": "text/plain" });
res.end(capabilityResponse === "not-found" ? "Not Found" : "incomplete response");
return;
}
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ contract: "operation-correlation.v1", kinds: supportsMaterialization ? ["rig.materialize"] : ["rig.import"] }));
return;
}
const reply = mode === "fresh" ? { ...replies.fresh, data: { ...replies.fresh.data, nodes: freshNodes, operation: freshOperation } }
: mode === "replay" ? { ...replies.replay, data: { replayed: true, operation: replayOperation } } : replies[mode];
res.writeHead(reply.status, { "Content-Type": "application/json" });
res.end(JSON.stringify(reply.data));
});
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("fixture did not bind TCP");
port = address.port;
});
afterAll(async () => { await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve())); });
afterEach(() => {
process.exitCode = priorExit; vi.restoreAllMocks(); requests.length = 0;
supportsMaterialization = true; capabilityResponse = "json"; freshOperation = operation; replayOperation = operation;
freshNodes = replies.fresh.data.nodes;
});
async function run(flags: string[]) {
priorExit = process.exitCode;
process.exitCode = undefined;
const output: string[] = [], errors: string[] = [];
vi.spyOn(console, "log").mockImplementation((...args: unknown[]) => output.push(args.join(" ")));
vi.spyOn(console, "error").mockImplementation((...args: unknown[]) => errors.push(args.join(" ")));
const deps: ImportDeps = { lifecycleDeps: lifecycle(), clientFactory: () => new DaemonClient(`http://127.0.0.1:${port}`), readFile: () => spec };
const command = new Command().exitOverride();
command.addCommand(importCommand(deps));
await command.parseAsync(["node", "rig", "import", "team.yaml", ...flags]);
return { output, errors, exitCode: process.exitCode };
}
describe("rig import --materialize-only operation receipts", () => {
it.each(["fresh", "replay"] as const)("prints a usable %s JSON receipt and forwards the same operation id", async response => {
mode = response;
const result = await run(["--materialize-only", "--operation-id", operationId, "--json", "--rig-root", "/fixture/team"]);
expect(result.exitCode).not.toBe(1);
expect(result.errors).toEqual([]);
expect(result.output).toHaveLength(1);
expect(JSON.parse(result.output[0]!)).toEqual(replies[response].data);
expect(requests).toHaveLength(2);
expect(requests[0]?.url).toBe("/api/operations/capabilities");
expect(requests[1]).toMatchObject({ url: "/api/rigs/import/materialize", body: spec,
headers: { "x-openrig-operation-id": operationId, "x-rig-root": "/fixture/team" } });
});
it("renders a replay in text without assuming fresh-result fields exist", async () => {
mode = "replay";
const result = await run(["--materialize-only", "--operation-id", operationId]);
expect(result.exitCode).not.toBe(1);
expect(result.output.join("\n")).toContain("prepared-rig");
expect(result.output.join("\n")).toContain("prepared-node");
expect(result.errors).toEqual([]);
});
it.each([
{ response: "fresh", target: false }, { response: "replay", target: false },
{ response: "fresh", target: true }, { response: "replay", target: true },
] as const)("confirms an empty-pod $response receipt (target: $target)", async ({ response, target }) => {
mode = response;
const emptyPodOperation = { ...operation, nodeIds: [], current: { ...operation.current, nodes: [] } };
freshOperation = emptyPodOperation;
replayOperation = emptyPodOperation;
freshNodes = [];
const result = await run(["--materialize-only", "--operation-id", operationId,
...(target ? ["--target-rig", "prepared-rig"] : [])]);
expect(result.exitCode).not.toBe(1);
expect(result.errors).toEqual([]);
expect(result.output).toEqual([response === "fresh"
? "Rig materialized: prepared (prepared-rig)" : "Materialization replay: prepared-rig"]);
expect(requests[1]?.headers["x-target-rig-id"]).toBe(target ? "prepared-rig" : undefined);
});
it.each([
{ name: "archived rig", current: { ...operation.current, rig: { ...operation.current.rig, archivedAt: "2026-01-02T00:00:00Z" } } },
{ name: "deleted rig", current: { ...operation.current, rig: { ...operation.current.rig, exists: false } } },
{ name: "deleted node", current: { ...operation.current, nodes: [{ id: "prepared-node", exists: false }] } },
])("recovers recorded IDs with a warning for a $name", async ({ current }) => {
mode = "replay";
replayOperation = { ...operation, current };
const result = await run(["--materialize-only", "--operation-id", operationId]);
expect(result.exitCode).toBe(1);
expect(result.output.join("\n")).toContain("Materialization replay: prepared-rig");
expect(result.output.join("\n")).toContain("Node: prepared-node");
expect(result.errors.join("\n")).toMatch(/warning.*archived|warning.*missing/i);
expect(result.errors.join("\n")).not.toContain("not confirmed");
expect(requests).toHaveLength(2);
});
it("retains the native JSON receipt and nonzero exit for an unavailable replay", async () => {
mode = "replay";
replayOperation = { ...operation, current: { ...operation.current, nodes: [{ id: "prepared-node", exists: false }] } };
const result = await run(["--materialize-only", "--operation-id", operationId, "--json"]);
expect(result.exitCode).toBe(1);
expect(JSON.parse(result.output[0]!)).toEqual({ replayed: true, operation: replayOperation });
});
it.each(["conflict", "empty"] as const)("prints %s JSON but does not report successful materialization", async response => {
mode = response;
const result = await run(["--materialize-only", "--operation-id", operationId, "--json"]);
expect(result.exitCode).toBe(1);
expect(result.output).toHaveLength(1);
expect(JSON.parse(result.output[0]!)).toEqual(replies[response].data);
});
it("explains how to resolve an operation conflict in text mode", async () => {
mode = "conflict";
const result = await run(["--materialize-only", "--operation-id", operationId]);
expect(result.exitCode).toBe(1);
expect(result.output).toEqual([]);
const message = result.errors.join("\n");
expect(message).toContain("operation_id_conflict");
expect(message).toContain("exact original request and options");
expect(message).toContain("new operation ID");
expect(message).toContain("deliberately start a new operation");
expect(message).not.toContain("update your spec or target rig and retry");
});
it.each(["not-a-uuid", ""])("rejects a malformed operation id %j before any HTTP write", async id => {
mode = "fresh";
const result = await run(["--materialize-only", "--operation-id", id]);
expect(result.exitCode).toBe(1);
expect(requests).toEqual([]);
expect(result.errors.join("\n")).toMatch(/UUID/i);
});
it("rejects an empty operation id outside materialize-only", async () => {
const result = await run(["--operation-id", ""]);
expect(result.exitCode).toBe(1);
expect(requests).toEqual([]);
expect(result.errors.join("\n")).toContain("--materialize-only");
});
it("preserves ordinary materialization when the operation id is omitted", async () => {
mode = "fresh";
const result = await run(["--materialize-only"]);
expect(result.exitCode).not.toBe(1);
expect(requests.map(request => request.url)).toEqual(["/api/rigs/import/materialize"]);
expect(requests[0]?.headers["x-openrig-operation-id"]).toBeUndefined();
});
it.each(["--operation-id", "--json"])("requires materialize-only for the scoped %s option", async flag => {
const result = await run(flag === "--json" ? [flag] : [flag, operationId]);
expect(result.exitCode).toBe(1);
expect(requests).toEqual([]);
expect(result.errors.join("\n")).toContain("--materialize-only");
});
it.each(["--instantiate", "--workspace-only", "--preflight"])("rejects scoped operation options combined with %s", async flag => {
const result = await run(["--materialize-only", "--operation-id", operationId, flag]);
expect(result.exitCode).toBe(1);
expect(requests).toEqual([]);
});
it("checks native capability support before a write to an older daemon", async () => {
supportsMaterialization = false;
const result = await run(["--materialize-only", "--operation-id", operationId]);
expect(result.exitCode).toBe(1);
expect(requests.map(request => request.url)).toEqual(["/api/operations/capabilities"]);
expect(result.errors.join("\n")).toContain("Nothing was materialized");
});
it.each(["not-found", "unreadable"] as const)("explains an unreadable %s capability response before any write", async response => {
capabilityResponse = response;
const result = await run(["--materialize-only", "--operation-id", operationId]);
expect(result.exitCode).toBe(1);
expect(requests.map(request => request.url)).toEqual(["/api/operations/capabilities"]);
expect(result.output).toEqual([]);
expect(result.errors.join("\n")).toContain("Nothing was materialized");
expect(result.errors.join("\n")).toContain("upgrade the daemon");
});
it.each([
{ name: "null rig", value: { ...operation, rigId: null } },
{ name: "different rig", value: { ...operation, rigId: "another-rig" } },
{ name: "empty node ids", value: { ...operation, nodeIds: [] } },
{ name: "extra node ids", value: { ...operation, nodeIds: ["prepared-node", "another-node"] } },
{ name: "unmatched node ids", value: { ...operation, nodeIds: ["another-node"] } },
{ name: "missing current state", value: { ...operation, current: undefined } },
])("rejects a contradictory fresh receipt: $name", async ({ value }) => {
mode = "fresh";
freshOperation = value;
const result = await run(["--materialize-only", "--operation-id", operationId, "--json"]);
expect(result.exitCode).toBe(1);
expect(JSON.parse(result.output[0]!)).toMatchObject({ rigId: "prepared-rig" });
});
});
+5 -1
View File
@@ -338,7 +338,11 @@ describe("rig mcp serve --http on the daemon's routes", () => {
expect(team.structured.hostedMembers).toEqual([{ session: "grok@team", roster: "team", capabilities: ["web research"],
useWhen: "A question needs current web sources", caveat: "No terminal or files: answers in text only", pane: null, activity: "unknown",
// Its last call is recorded; no ring was rung (nudge: false), so its last wake is unknown, never idle.
presence: { lastCallAt: expect.stringMatching(/^\d{4}-\d\d-\d\dT/), lastWake: null, lastWakeScope: "the latest ring among its 50 most recent rows" } }]);
presence: { lastCallAt: expect.stringMatching(/^\d{4}-\d\d-\d\dT/), lastWake: null, lastWakeScope: "the latest ring among its 50 most recent rows",
// Its own inbox reads over this server were recorded as check-ins on the daemon. Its entry states no cadence,
// so it reads unknown with that check-in, never on request.
checkIn: { status: "unknown", lastCheckInAt: expect.stringMatching(/^\d{4}-\d\d-\d\dT/), expectedMinutes: null, onRequest: false,
reason: "no check-in cadence declared" } } }]);
expect(JSON.parse(fs.readFileSync(presenceFile, "utf8")).seats["grok@team"]).toMatchObject({ grant: "grok" });
expect(fs.statSync(presenceFile).mode & 0o777).toBe(0o600);
expect(fs.readFileSync(tokenFile, "utf8")).not.toContain("lastCallAt");
@@ -989,6 +989,21 @@ describe("rig mcp serve --http --grant-service on the daemon's routes", () => {
expect(back.text).not.toContain("qitem-split-hidden");
});
it("a scoped show of its own item never carries the answers a person returned to it; the owner's read does", async () => {
const served = await listen();
const asExternal = await connect(served.url);
const own = (await asExternal("rig_queue_create", { destination: "lead@team-a", body: "my task" })).structured.qitemId as string;
// The item asked of a person, and their answer row back to the caller: another row, from a person, linked to it.
db.prepare("UPDATE queue_items SET destination_session = 'human-x@external' WHERE qitem_id = ?").run(own);
await repo.createHumanAnswer({ sourceSession: "human-x@external", destinationSession: CALLER, body: "The person's private reasoning",
inboundReplyTo: own, nudge: false } as never);
expect(await (await fetch(`${daemonUrl}/api/queue/${own}`)).json()).toMatchObject({ answers: [{ by: "human-x@external" }] });
const shown = await asExternal("rig_queue_show", { qitemId: own });
expect(shown.isError).toBe(false);
expect(shown.structured.item).not.toHaveProperty("answers");
expect(shown.text).not.toContain("private reasoning");
});
it("an id-reuse conflict never names another item's parties, and still names the external caller's own", async () => {
const served = await listen();
const asExternal = await connect(served.url);
+36 -1
View File
@@ -723,7 +723,10 @@ describe("MCP Server", () => {
] }));
fs.writeFileSync(path.join(folder, "b.json"), "{ not json");
let hostSelfId: string | null = "host-a";
let checkIns: unknown = { hostId: "host-a", members: [{ seat: "grok@my-rig", rung: true, status: "check-in-overdue",
lastCheckInAt: "2026-10-26T09:00:00.000Z", expectedMinutes: 60, reporter: "openrig-observed" }] };
const getFn = vi.fn(async (p: string) => {
if (p === "/api/queue/hosted-members") return checkIns === null ? { status: 404, data: {} } : { status: 200, data: checkIns };
if (p.startsWith("/api/rigs/summary")) return { status: 200, data: [{ id: "rig-1", name: "my-rig" }] };
if (p === "/api/rigs/rig-1") return { status: 200, data: { rig: { id: "rig-1", name: "my-rig" }, nodes: [{ id: "n1", logicalId: "dev.impl" }, { id: "n2", logicalId: "dev.qa" }], edges: [], representative: null } };
if (p === "/api/rigs/rig-1/nodes") return { status: 200, data: [
@@ -759,7 +762,12 @@ describe("MCP Server", () => {
expect(found.hostedMembers).toEqual([{ session: "grok@my-rig", roster: "research", capabilities: ["web research"], useWhen: "Current sources",
caveat: "Text only", pane: null, activity: "unknown",
presence: { lastCallAt: "2026-10-26T11:05:00.000Z", lastWakeScope: "the latest ring among its 50 most recent rows",
lastWake: { at: "2026-10-26T11:00:00.000Z", result: "wake-accepted:webhook (GROK_WAKE_URL) answered 202", qitemId: "q-new" } } }]);
lastWake: { at: "2026-10-26T11:00:00.000Z", result: "wake-accepted:webhook (GROK_WAKE_URL) answered 202", qitemId: "q-new" },
checkIn: { status: "check-in-overdue", lastCheckInAt: "2026-10-26T09:00:00.000Z", expectedMinutes: 60, onRequest: false } } }]);
// A daemon that gives no check-in status (an older one) leaves it unknown, with the reason, never a guess.
checkIns = null;
expect(((await here.team()).hostedMembers[0] as { presence: { checkIn: unknown } }).presence.checkIn)
.toEqual({ status: "unknown", lastCheckInAt: null, expectedMinutes: null, onRequest: false, reason: "this daemon gave no check-in status" });
// A scoped caller gets a generic note; the file names and errors go to this server's log.
expect(found.hostedMembersNote).toBe("Some rosters couldn't be read, so hosted members may be missing.");
expect(log.mock.calls.flat().join(" ")).toContain("b.json");
@@ -1466,6 +1474,33 @@ describe("MCP Server", () => {
}
});
it("issue2728 rig_queue_list composes exact tags and mission/slice aliases", async () => {
const row = { qitemId: "qitem-match", tags: ["review", "mission:launch", "slice:docs"] };
const getFn = vi.fn(async () => ({ status: 200, data: [row] }));
await setup({ get: getFn });
const listed = await mcpClient.callTool({
name: "rig_queue_list",
arguments: { tags: ["review", "mission:launch", "review"], mission: "launch", slice: "docs", all: true },
});
const params = new URLSearchParams(String(getFn.mock.calls[0]?.[0]).split("?")[1]);
expect(params.getAll("tag")).toEqual(["review", "mission:launch", "slice:docs"]);
expect(listed.structuredContent).toEqual({ items: [row] });
await cleanup();
});
it("issue2728 rig_queue_list reports when an older daemon returns rows missing a requested tag", async () => {
const getFn = vi.fn(async () => ({ status: 200, data: [{ qitemId: "qitem-unfiltered", tags: ["review"] }] }));
await setup({ get: getFn });
const listed = await mcpClient.callTool({
name: "rig_queue_list",
arguments: { tags: ["review", "publish"], all: true },
});
expect(listed.isError).toBe(true);
expect(listed.structuredContent).toMatchObject({ ok: false, code: "filter_unsupported" });
expect((listed.content as Array<{ text: string }>)[0]!.text).toContain("tag");
await cleanup();
});
it("rig_queue_list asks for a seat instead of guessing one", async () => {
const getFn = vi.fn(async () => ({ status: 200, data: [] }));
const prior = process.env.OPENRIG_SESSION_NAME;
+52 -3
View File
@@ -17,10 +17,22 @@ let db: Database.Database;
let home: string;
let app: Hono;
let rigs: RigRepository;
/** Each write the CLI sent, with how long it would wait for the daemon. */
const posts: Array<{ url: string; timeoutMs?: number }> = [];
/** An account that answers the connector routes: a key for the one-time code, a bearer for each newly listed name. */
const listed = new Set<string>();
const accountFetch = async (url: string, init: { method: string; body: string }) => {
const path = new URL(url).pathname;
const body = JSON.parse(init.body) as { code?: string; participants?: string[] };
const reply = (status: number, json: unknown) => ({ status, json: async () => json });
if (path === "/api/connector/enroll") return body.code === "ec1.page" ? reply(200, { installation: { id: "inst-1", name: "lab" }, key: "oik1_c_inst-1_key" }) : reply(400, { error: "code_not_current" });
const participants = (body.participants ?? []).map((name) => (listed.has(name) ? { name, state: "connected" } : (listed.add(name), { name, state: "connected", bearer: `bear-${name}` })));
return reply(200, { participants, mcp: "https://account.example/mcp", rig: "acct" });
};
const routesWith = (bearerToken: string | null) => {
const next = new Hono();
next.use("*", async (c, n) => { c.set("rigRepo" as never, rigs as never); await n(); });
next.route("/api/network", networkRoutes({ home, bearerToken }));
next.route("/api/network", networkRoutes({ home, bearerToken, accountFetch, selfHostId: () => "host-a" }));
return next;
};
beforeEach(() => {
@@ -31,6 +43,7 @@ beforeEach(() => {
db.prepare("INSERT INTO sessions (id, node_id, session_name, status) VALUES ('s1', ?, 'dev-impl@lab', 'running')").run(node.id);
home = mkdtempSync(join(tmpdir(), "openrig-network-cli-"));
app = routesWith(null);
posts.length = 0;
});
afterEach(() => { db.close(); rmSync(home, { recursive: true, force: true }); vi.restoreAllMocks(); vi.unstubAllEnvs(); process.exitCode = undefined; });
@@ -46,7 +59,10 @@ function cli(tokenFile: Record<string, string> = {}) {
};
const deps: NetworkDeps = {
lifecycleDeps,
clientFactory: () => ({ get: (url: string) => call("GET", url), post: (url: string, body: unknown, options?: { headers?: Record<string, string> }) => call("POST", url, body, options?.headers) }) as never,
clientFactory: () => ({ get: (url: string) => call("GET", url), post: (url: string, body: unknown, options?: { headers?: Record<string, string>; timeoutMs?: number }) => {
posts.push({ url, timeoutMs: options?.timeoutMs });
return call("POST", url, body, options?.headers);
} }) as never,
readTokenFile: (path) => { if (!(path in tokenFile)) throw new Error("no such file"); return tokenFile[path]!; },
};
return new Command().exitOverride().addCommand(networkCommand(deps));
@@ -63,7 +79,7 @@ it("connects a seat with its token file, shows it in status without the token, a
expect(status).not.toContain("tok-abc");
await cli().parseAsync(["node", "rig", "network", "disconnect", "dev-impl@lab", "--reason", "done"]);
expect(String(out.mock.calls.at(-1)?.[0])).toMatch(/^Disconnected netb-[0-9a-f]{20} dev-impl@lab -> alex@team .*disconnected \(done\)/);
expect(String(out.mock.calls.at(-1)?.[0])).toMatch(/^Disconnected netb-[0-9a-f]{20} dev-impl@lab -> alex@team .*disconnected \(done\)\nRemove the participant on the hub too/);
expect(process.exitCode).toBeUndefined();
});
@@ -111,6 +127,39 @@ it("status shows a hub item closed elsewhere under its binding, in text and JSON
expect(JSON.parse(String(out.mock.calls.at(-1)?.[0])).bindings[0].closedElsewhere).toEqual([{ hubItem: "hub-9", localItem: "qitem-net-0001", note: "closed elsewhere (done, canceled)" }]);
});
it("enrolls with the account page's code, connects a seat by name through it, and shows both in status", async () => {
listed.clear();
const out = vi.spyOn(console, "log").mockImplementation(() => {});
const err = vi.spyOn(console, "error").mockImplementation(() => {});
await cli().parseAsync(["node", "rig", "network", "enroll", "ec1.page", "--site", "https://account.example"]);
expect(process.exitCode).toBeUndefined();
expect(String(out.mock.calls.at(-1)?.[0])).toMatch(/^Enrolled at https:\/\/account\.example\/ as installation lab \(neti-[0-9a-f]{20}\)\nConnect a seat with rig network connect <seat> --as <name>\.$/);
await cli().parseAsync(["node", "rig", "network", "connect", "dev-impl@lab", "--hub", "https://hub.example/mcp", "--as", "alex@team"]);
expect(process.exitCode).toBe(1);
expect(String(err.mock.calls.at(-1)?.[0])).toBe("Give both --hub and --token-file, or neither to connect through the enrolled account.");
process.exitCode = undefined;
await cli().parseAsync(["node", "rig", "network", "connect", "dev-impl@lab", "--as", "alpha"]);
expect(process.exitCode).toBeUndefined();
expect(String(out.mock.calls.at(-1)?.[0])).toMatch(/^Connected netb-[0-9a-f]{20} dev-impl@lab -> alpha@acct at https:\/\/account\.example\/mcp no contact yet\nWork for alpha@acct reaches dev-impl@lab/);
await cli().parseAsync(["node", "rig", "network", "status"]);
const status = String(out.mock.calls.at(-1)?.[0]).split("\n");
expect(status[0]).toMatch(/^Enrolled at https:\/\/account\.example\/ as installation lab \(neti-/);
expect(status[1]).toMatch(/^netb-[0-9a-f]{20} dev-impl@lab -> alpha@acct at https:\/\/account\.example\/mcp/);
await cli().parseAsync(["node", "rig", "network", "status", "--json"]);
expect(String(out.mock.calls.at(-1)?.[0])).not.toMatch(/oik1_|bear-alpha/);
await cli().parseAsync(["node", "rig", "network", "disconnect", "dev-impl@lab"]);
expect(process.exitCode).toBeUndefined();
const disconnected = String(out.mock.calls.at(-1)?.[0]);
expect(disconnected).toMatch(/\nThe account stopped listing alpha, which revokes it there\.$/);
expect(disconnected).not.toContain("Remove the participant on the hub");
// Every network write waits past the daemon's 30 s account deadline, so the account's own answer is what's shown.
expect(posts.map((p) => p.url)).toEqual(["/api/network/installations", "/api/network/bindings", expect.stringMatching(/^\/api\/network\/bindings\/.+\/disconnect$/)]);
for (const p of posts) expect(p.timeoutMs).toBeGreaterThanOrEqual(45_000);
});
it("sends the operator bearer on its writes, so a daemon with one configured takes them", async () => {
app = routesWith("op-secret");
const out = vi.spyOn(console, "log").mockImplementation(() => {});
@@ -157,3 +157,46 @@ it("takes the participant's item over the wire, carries pickup and the result ba
expect(await pass()).toMatchObject({ error: "revoked" });
expect(bindings.get(binding.id)!.state).toBe("revoked");
});
it("a lead's aggregate over its own local child work comes back once on the original hub request, and an open parent publishes nothing early", async () => {
const token = await addGrant(tokenFile, { name: "alex", seat: "alex@team", rigs: ["team"], roots: [], workspace: false, owner: false });
const task = await hubRepo.create({ sourceSession: "lead@team", destinationSession: "alex@team", summary: "Ship the fix", body: "Fix the bug and have it reviewed.", nudge: false } as never);
const localRepo = queue(localDb);
const bindings = new NetworkBindingStore(localDb, localHome);
const binding = bindings.create({ session: "dev-impl@lab", hubUrl, hubSeat: "alex@team", token, allowHttp: true });
const pass = () => runNetworkBindingPass({ db: localDb, queueRepo: localRepo, bindings, home: localHome }, bindings.get(binding.id)!);
const hubItem = () => hubRepo.getById(task.qitemId)!;
expect(await pass()).toMatchObject({ taken: 1 });
const [parent] = localRepo.list({ limit: 50 });
localRepo.claim({ qitemId: parent!.qitemId, destinationSession: "dev-impl@lab" });
// The lead delegates through ordinary local rows and waits on each in turn.
const build = await localRepo.create({ sourceSession: "dev-impl@lab", destinationSession: "builder@lab", summary: "Build the fix", body: "Fix the bug.", nudge: false } as never);
const review = await localRepo.create({ sourceSession: "dev-impl@lab", destinationSession: "reviewer@lab", summary: "Review the fix", body: "Review the build.", nudge: false } as never);
await localRepo.update({ qitemId: parent!.qitemId, actorSession: "dev-impl@lab", state: "blocked", blockedOn: build.qitemId, transitionNote: "Waiting on the build." });
expect(await pass()).toMatchObject({ pickupsSent: 1, resultsSent: 0 });
expect(hubItem()).toMatchObject({ state: "in-progress", resolution: null });
localRepo.claim({ qitemId: build.qitemId, destinationSession: "builder@lab" });
await localRepo.update({ qitemId: build.qitemId, actorSession: "builder@lab", state: "done", closureReason: "no-follow-on", resolution: "Built: the fix is in commit abc123." });
await localRepo.update({ qitemId: parent!.qitemId, actorSession: "dev-impl@lab", state: "blocked", blockedOn: review.qitemId, transitionNote: "Waiting on the review." });
// A finished child isn't a result: the parent is still open, so nothing final goes to the hub.
expect(await pass()).toMatchObject({ resultsSent: 0 });
expect(hubItem()).toMatchObject({ state: "in-progress", resolution: null });
localRepo.claim({ qitemId: review.qitemId, destinationSession: "reviewer@lab" });
await localRepo.update({ qitemId: review.qitemId, actorSession: "reviewer@lab", state: "done", closureReason: "no-follow-on", resolution: "Reviewed: approve." });
const children = [localRepo.getById(build.qitemId)!, localRepo.getById(review.qitemId)!];
const aggregate = children.map((child) => child.resolution).join(" ");
await localRepo.update({ qitemId: parent!.qitemId, actorSession: "dev-impl@lab", state: "done", closureReason: "no-follow-on", resolution: aggregate });
expect(await pass()).toMatchObject({ resultsSent: 1 });
expect(hubItem()).toMatchObject({ state: "done", closureReason: "no-follow-on", resolution: "Built: the fix is in commit abc123. Reviewed: approve." });
// Once: a further pass writes nothing, and the children's own words never reached the hub as notes.
const transitions = hubRepo.listTransitions(task.qitemId);
await pass();
expect(hubRepo.listTransitions(task.qitemId)).toHaveLength(transitions.length);
expect(transitions.filter((t) => t.state === "done")).toHaveLength(1);
expect(transitions.map((t) => t.transitionNote ?? "").join("\n")).not.toMatch(/Waiting on|Built:.*\n.*Reviewed:/);
});
@@ -0,0 +1,160 @@
// Connected assistants (roster members outside any terminal) aren't nodes, so `rig ps` lists them in their own short
// section with their check-in status, from the daemon's hosted-members read. `--json` output keeps its shape.
import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from "vitest";
import http from "node:http";
import { Command } from "commander";
import { psCommand } from "../src/commands/ps.js";
import { DaemonClient } from "../src/client.js";
import { STATE_FILE, type LifecycleDeps, type DaemonState } from "../src/daemon-lifecycle.js";
import type { StatusDeps } from "../src/commands/status.js";
function lifecycle(port: number): LifecycleDeps {
return {
spawn: vi.fn(() => ({ pid: 1, unref: vi.fn() }) as never), fetch: vi.fn(async () => ({ ok: true })), kill: vi.fn(() => true),
readFile: vi.fn((p: string) => p === STATE_FILE ? JSON.stringify({ pid: 123, port, db: "t.sqlite", startedAt: "2026-11-12T00:00:00Z" } as DaemonState) : null),
writeFile: vi.fn(), removeFile: vi.fn(), exists: vi.fn((p: string) => p === STATE_FILE), mkdirp: vi.fn(), openForAppend: vi.fn(() => 3),
isProcessAlive: vi.fn(() => true),
};
}
const NODE = { rigId: "rig-h", rigName: "hub", logicalId: "lead", canonicalSessionName: "lead@hub", hostSelfId: "host-a", nodeKind: "agent",
runtime: "claude-code", sessionStatus: "running", lifecycleState: "running", startupStatus: "ready", needsAttention: false };
const PS = [{ rigId: "rig-h", name: "hub", rigName: "hub", nodeCount: 1, runningCount: 1, status: "running", lifecycleState: "running", uptime: "1h", latestSnapshot: null }];
const MEMBERS = [
{ seat: "chat@hub", rung: false, status: "check-in-overdue", lastCheckInAt: "2026-11-12T01:00:00.000Z", expectedMinutes: 60, onRequest: false, reporter: "openrig-observed" },
{ seat: "new@hub", rung: false, status: "no-check-in-yet", lastCheckInAt: null, expectedMinutes: null, onRequest: false, reporter: "openrig-observed" },
{ seat: "other@elsewhere", rung: false, status: "on-request", lastCheckInAt: "2026-11-12T02:00:00.000Z", expectedMinutes: null, onRequest: true, reporter: "openrig-observed" },
];
describe("rig ps: connected assistants and their check-in status", () => {
let server: http.Server;
let port: number;
let members: unknown = { hostId: "host-a", members: MEMBERS };
// How the hosted-members route answers: 200 with `members`, an older daemon's 404, a failure, or a dropped connection.
let membersStatus = 200;
let rigs: unknown[] = PS;
let nodes: unknown[] = [NODE];
let savedSession: string | undefined;
beforeAll(async () => {
savedSession = process.env.OPENRIG_SESSION_NAME;
delete process.env.OPENRIG_SESSION_NAME;
server = http.createServer((req, res) => {
const url = req.url ?? "";
const reply = (status: number, body: unknown) => { res.writeHead(status, { "Content-Type": "application/json" }); res.end(JSON.stringify(body)); };
if (/^\/api\/rigs\/[^/]+\/nodes/.test(url)) return reply(200, nodes);
if (url.startsWith("/api/ps")) return reply(200, rigs);
if (url === "/api/queue/hosted-members") {
if (membersStatus === 0) return req.socket.destroy();
return reply(membersStatus, membersStatus === 200 ? members : { error: "unavailable" });
}
return reply(404, { error: "not found" });
});
await new Promise<void>((resolve) => server.listen(0, resolve));
port = (server.address() as { port: number }).port;
});
afterAll(() => {
server.close();
if (savedSession !== undefined) process.env.OPENRIG_SESSION_NAME = savedSession;
});
beforeEach(() => {
members = { hostId: "host-a", members: MEMBERS };
membersStatus = 200;
rigs = PS;
nodes = [NODE];
process.exitCode = undefined;
});
async function run(args: string[]): Promise<string[]> {
const deps: StatusDeps = { lifecycleDeps: lifecycle(port), clientFactory: (url) => new DaemonClient(url) };
const prog = new Command();
prog.exitOverride();
prog.addCommand(psCommand(deps));
const logs: string[] = [];
const orig = console.log;
const origErr = console.error;
console.log = (...a: unknown[]) => { logs.push(a.map(String).join(" ")); };
console.error = () => {};
try { await prog.parseAsync(["node", "rig", "ps", ...args]); } catch { /* exitOverride */ } finally { console.log = orig; console.error = origErr; }
return logs;
}
it("the rigs view lists every connected assistant with its check-in line", async () => {
const out = (await run([])).join("\n");
expect(out).toContain("Connected assistants (outside the terminal; each checks its own queue):");
expect(out).toContain(" chat@hub overdue: last check-in 2026-11-12T01:00:00.000Z, expected every 60 min; its schedule may be off or waiting for an approval");
expect(out).toContain(" new@hub no check-in yet; no check-in cadence declared");
expect(out).toContain(" other@elsewhere on request: it checks its queue when a person asks it; last check-in 2026-11-12T02:00:00.000Z");
});
it("the nodes view of one rig lists only that rig's assistants", async () => {
const out = (await run(["--nodes", "--rig", "hub"])).join("\n");
expect(out).toContain(" chat@hub overdue");
expect(out).toContain(" new@hub no check-in yet");
expect(out).not.toContain("other@elsewhere");
});
it("--json keeps its shape: no section, no extra key", async () => {
const logs = await run(["--json"]);
expect(logs.join("\n")).not.toContain("Connected assistants");
expect(Array.isArray(JSON.parse(logs[0]!))).toBe(true);
});
it("a host with no terminal rigs still lists its connected assistants", async () => {
rigs = [];
const out = (await run([])).join("\n");
expect(out).toContain("No rigs");
expect(out).toContain("Connected assistants (outside the terminal; each checks its own queue):");
expect(out).toContain(" chat@hub overdue");
expect(out).toContain(" other@elsewhere on request");
expect(process.exitCode ?? 0).toBe(0);
});
it("a rig with no terminal seats still lists its connected assistants", async () => {
rigs = [{ ...PS[0], nodeCount: 0, runningCount: 0 }];
nodes = [];
const out = (await run(["--nodes", "--rig", "hub"])).join("\n");
expect(out).toContain("No nodes");
expect(out).toContain(" chat@hub overdue");
expect(out).toContain(" new@hub no check-in yet");
expect(out).not.toContain("other@elsewhere");
expect(process.exitCode ?? 0).toBe(0);
});
it("a missing rig keeps its not-found answer, with no section", async () => {
const out = (await run(["--rig", "nowhere"])).join("\n");
expect(out).not.toContain("Connected assistants");
expect(process.exitCode).toBe(1);
});
it("a known-empty list stays quiet, in a full view and an empty one", async () => {
members = { hostId: "host-a", members: [] };
expect((await run([])).join("\n")).not.toContain("Connected assistants");
rigs = [];
expect((await run([])).join("\n")).not.toContain("Connected assistants");
members = { hostId: "host-a", members: MEMBERS };
rigs = PS;
// Members only on other rigs: this rig's list is known to be empty.
expect((await run(["--nodes", "--rig", "elsewhere-only"])).join("\n")).not.toContain("Connected assistants");
});
it.each([
["an older daemon without the route", () => { membersStatus = 404; }, "this daemon doesn't serve it"],
["a failed read", () => { membersStatus = 500; }, "the read failed: HTTP 500"],
["an answer without a members list", () => { members = { hostId: "host-a" }; }, "the daemon's answer couldn't be read"],
["a dropped connection", () => { membersStatus = 0; }, "the read failed: "],
])("%s says check-in is unavailable, not that there are none", async (_case, arrange, reason) => {
arrange();
for (const args of [[], ["--nodes", "--rig", "hub"]]) {
const out = (await run(args)).join("\n");
expect(out).toContain(`Connected assistants: check-in unavailable (${reason}`);
expect(out).not.toContain("each checks its own queue");
// The main table and the exit status are as they were.
expect(out).toContain(args.length ? "lead@hub" : "hub");
expect(process.exitCode ?? 0).toBe(0);
}
rigs = [];
expect((await run([])).join("\n")).toContain("No rigs\n\nConnected assistants: check-in unavailable");
});
});
@@ -124,6 +124,10 @@ describe("PL-012 ps --filter contextUsage.* + CTX field", () => {
} else if (req.url && new URL(req.url, "http://127.0.0.1").pathname === "/api/ps" && req.method === "GET") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(rigs));
} else if (req.url === "/api/queue/hosted-members" && req.method === "GET") {
// A current daemon with no connected assistants.
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ hostId: "host-a", members: [] }));
} else {
res.writeHead(404);
res.end();
+4
View File
@@ -80,6 +80,10 @@ describe("Ps CLI", () => {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: `Rig "${rigId}" not found` }));
}
} else if (req.url === "/api/queue/hosted-members" && req.method === "GET") {
// A current daemon with no connected assistants.
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ hostId: "host-a", members: [] }));
} else {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "not found" }));
+113
View File
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { CommanderError } from "commander";
import fs from "node:fs";
import path from "node:path";
import os from "node:os";
@@ -1619,6 +1620,118 @@ describe("rig queue CLI", () => {
expect(call!.path).not.toContain("rig=");
});
it("issue2728 list sends repeated exact tags and canonical mission/slice aliases once", async () => {
const { deps, calls } = makeDeps();
const program = createProgram({ queueDeps: deps });
program.exitOverride();
await program.parseAsync([
"node", "rig", "queue", "list", "--all", "--all-rigs",
"--tag", "review", "--tag", "publish", "--tag", "mission:launch",
"--mission", "launch", "--slice", "docs", "--tag", "comma,separated", "--json",
]);
const call = calls.find((candidate) => candidate.method === "GET" && candidate.path.startsWith("/api/queue/list"));
expect(call).toBeDefined();
const params = new URLSearchParams(call!.path.split("?")[1]);
expect(params.getAll("tag")).toEqual(["review", "publish", "mission:launch", "slice:docs", "comma,separated"]);
expect(params.get("limit")).toBe("100");
});
it("issue2728 refuses a blank tag before contacting the daemon", async () => {
const { deps, calls } = makeDeps();
const program = createProgram({ queueDeps: deps });
program.exitOverride();
await program.parseAsync(["node", "rig", "queue", "list", "--tag", " ", "--json"]);
expect(calls).toHaveLength(0);
expect(process.exitCode).toBe(1);
expect(logs.join("\n")).toContain('"error":"tag_invalid"');
expect(logs.join("\n")).toContain("tag filters cannot be blank");
});
it("issue2728 clears captured list tags after blank refusal when reusing the same command", async () => {
const { deps, calls } = makeDeps({
routes: {
"GET /api/queue/list?tag=fresh&limit=100": { status: 200, data: [] },
},
});
const program = createProgram({ queueDeps: deps });
program.exitOverride();
await program.parseAsync([
"node", "rig", "queue", "list", "--all", "--all-rigs", "--full", "--tag", "stale", "--tag", " ", "--json",
]);
expect(calls).toHaveLength(0);
expect(process.exitCode).toBe(1);
process.exitCode = undefined;
await program.parseAsync([
"node", "rig", "queue", "list", "--all", "--all-rigs", "--full", "--tag", "fresh", "--json",
]);
const call = calls.find((candidate) => candidate.method === "GET" && candidate.path.startsWith("/api/queue/list"));
expect(call).toBeDefined();
const params = new URLSearchParams(call!.path.split("?")[1]);
expect(params.getAll("tag")).toEqual(["fresh"]);
});
it.each([
{
after: "an invalid option argument",
abortedArgs: ["node", "rig", "queue", "list", "--tag", "stale", "--limit", "0"],
exitCode: "commander.invalidArgument",
nextArgs: ["node", "rig", "queue", "list", "--all", "--all-rigs", "--json"],
expectedTags: [],
},
{
after: "help following tag and mission collection",
abortedArgs: ["node", "rig", "queue", "list", "--tag", "stale", "--mission", "old", "--help"],
exitCode: "commander.helpDisplayed",
nextArgs: ["node", "rig", "queue", "list", "--all", "--all-rigs", "--slice", "fresh", "--json"],
expectedTags: ["slice:fresh"],
},
])("issue2728 clears list tags after $after when reusing the same command", async ({ abortedArgs, exitCode, nextArgs, expectedTags }) => {
const { deps, calls } = makeDeps();
const program = createProgram({ queueDeps: deps });
program.exitOverride();
program.commands.find((command) => command.name() === "queue")!.commands.find((command) => command.name() === "list")!.exitOverride();
program.configureOutput({ writeOut: () => {}, writeErr: () => {} });
let abortedWith: unknown;
try {
await program.parseAsync(abortedArgs);
} catch (error) {
abortedWith = error;
}
expect(abortedWith).toBeInstanceOf(CommanderError);
expect((abortedWith as CommanderError).code).toBe(exitCode);
expect(calls).toHaveLength(0);
await program.parseAsync(nextArgs);
const call = calls.find((candidate) => candidate.method === "GET" && candidate.path.startsWith("/api/queue/list"));
expect(call).toBeDefined();
const params = new URLSearchParams(call!.path.split("?")[1]);
expect(params.getAll("tag")).toEqual(expectedTags);
expect(params.has("tag")).toBe(expectedTags.length > 0);
});
it("issue2728 does not print rows when a daemon returns a row missing a requested tag", async () => {
const { deps, calls } = makeDeps({
routes: {
"GET /api/queue/list?tag=review&limit=100": {
status: 200,
data: [{ qitemId: "qitem-unfiltered", tags: ["other"] }],
},
},
});
const program = createProgram({ queueDeps: deps });
program.exitOverride();
await program.parseAsync(["node", "rig", "queue", "list", "--all", "--all-rigs", "--full", "--tag", "review", "--json"]);
expect(calls).toHaveLength(1);
expect(process.exitCode).toBe(1);
expect(logs.join("\n")).toContain("filter_unsupported");
expect(logs.join("\n")).not.toContain("qitem-unfiltered");
});
it("list -a includes history (no activeOnly param)", async () => {
const saved = process.env.OPENRIG_SESSION_NAME;
process.env.OPENRIG_SESSION_NAME = "dev1@my-rig";
+1
View File
@@ -1340,6 +1340,7 @@ describe("Send CLI", () => {
expect(output).toContain("a@r: sent\nNotice: a@r was mid-restore (as recorded). This doesn't mean the restore has finished.\nb@r: sent\n");
expect(output).toContain("c@r: FAILED — paste failed\nNotice: c@r was mid-restore");
expect(output).toContain("d@r: retained, not delivered; inspect with rig seat held-messages\nNotice: d@r was mid-restore");
expect(output).toContain("2/4 delivered, 1 held");
expect(output.match(/^Notice: /gm)).toHaveLength(3); // none for b@r
expect(exitCode).toBe(1); // a failed recipient, as before
});
@@ -65,7 +65,7 @@ describe("terminal open desktop default", () => {
it("forwards a preview binding to the explicit existing-workspace route", async () => {
const f = fixture({ platform: "linux", env: {} });
await f.run(["saved:kernel", "--provider", "herdr", "--expected-plan", "one-plan", "--json"]);
expect(f.post).toHaveBeenCalledExactlyOnceWith("/api/terminal/open", { view: "saved:kernel", provider: "herdr", expectedPlan: "one-plan" }, { timeoutMs: 45_000 });
expect(f.post).toHaveBeenCalledExactlyOnceWith("/api/terminal/open", { view: "saved:kernel", provider: "herdr", expectedPlan: "one-plan", reuseLive: true }, { timeoutMs: 45_000 });
expect(f.exec).not.toHaveBeenCalled();
});
@@ -110,7 +110,8 @@ describe("terminal open desktop default", () => {
const f = fixture({ platform: "linux", env: {} });
await f.run(["saved:kernel", "--provider", provider]);
expect(process.exitCode).toBeUndefined();
expect(f.post).toHaveBeenCalledExactlyOnceWith("/api/terminal/open", { view: "saved:kernel", provider }, { timeoutMs: 45_000 });
// #3052: only herdr asks the daemon to reuse a workspace that still shows the view live.
expect(f.post).toHaveBeenCalledExactlyOnceWith("/api/terminal/open", { view: "saved:kernel", provider, ...(provider === "herdr" ? { reuseLive: true } : {}) }, { timeoutMs: 45_000 });
expect(f.get).not.toHaveBeenCalled();
expect(f.exec).not.toHaveBeenCalled();
expect(f.windowDeps.launch).not.toHaveBeenCalled();
@@ -118,6 +119,16 @@ describe("terminal open desktop default", () => {
expect(logs[0]).not.toMatch(/window requested|Terminal:/i);
});
it("a headless --provider herdr open that reused a live workspace succeeds without claiming a window (#3052)", async () => {
const f = fixture({ platform: "linux", env: {} });
f.post.mockResolvedValueOnce({ status: 200, data: { provider: "herdr", ok: true, opened: [], absent: [], degraded: [], pages: 0,
reusedWorkspace: { id: "w1", tabId: "w1:t1", view: "saved:kernel" } } } as never);
await f.run(["saved:kernel", "--provider", "herdr"]);
expect(process.exitCode).toBeUndefined();
expect(logs[0]).toMatch(/^Reused herdr workspace w1 for view "saved:kernel"\./);
expect(f.windowDeps.launch).not.toHaveBeenCalled();
});
it.each([
{ name: "lost", error: new DaemonConnectionError("Reply connection lost") },
{ name: "unreadable", error: new DaemonResponseError(200, "truncated") },
@@ -56,7 +56,7 @@ describe("terminal --session", () => {
const f = fixture();
await f.run(["open", "prod", "--provider", "herdr", "--session", "prod", "--json"]);
expect(f.get).toHaveBeenCalledExactlyOnceWith("/api/terminal/preview?view=prod&provider=herdr&session=prod");
expect(f.post).toHaveBeenCalledExactlyOnceWith("/api/terminal/open", { view: "prod", provider: "herdr", session: "prod", expectedPlan: "plan-prod" }, { timeoutMs: 45_000 });
expect(f.post).toHaveBeenCalledExactlyOnceWith("/api/terminal/open", { view: "prod", provider: "herdr", session: "prod", expectedPlan: "plan-prod", reuseLive: true }, { timeoutMs: 45_000 });
expect(f.exec).not.toHaveBeenCalled();
expect(JSON.parse(logs[0]!)).toMatchObject({ ok: true, session: "prod" });
});
@@ -29,6 +29,13 @@ behave; this skill is the loop around them.
- Use `rig_queue_create` with `destination` (the lead, or the seat the person chose) and `body`. Write the body for a
capable colleague: the goal, why it matters, what done looks like, and where to look. Add a one-line `summary`.
- With a seat, end the body with the reply route, because your seat has no terminal and `rig send` can't reach it:
> To ask me anything, create a queue item to `<your seat>` (`rig queue create --destination <your seat> ...`), then
> block this item on that new item's id (`rig queue block <this id> --on <question id>`), so my answer wakes you. I
> check it when the person asks. Don't ask in your own terminal: the person isn't there. If you hand this item on,
> copy this paragraph into the new item. When you finish, put the outcome in this item's resolution and any file in
> its evidence ref.
- Tell the person the `qitemId` it returns. It's how both of you find this work again.
- If the call times out, check `rig_queue_show` with that same `qitemId` before trying again. If you retry, pass the same id
as `qitemId`. Never retry with a new one: that creates the work twice.
+5 -2
View File
@@ -62,7 +62,9 @@ person needs in their project or home folder and name that path.
start" in https://github.com/mvschwarz/openrig/blob/main/docs/reference/getting-started.md#before-you-start. Setup
checks Node, tmux and the logins. It installs tmux (with Homebrew, when present) or the chosen harness (with npm) if
either is missing, installs Herdr for the OpenRig view unless they decline it (`--no-herdr`), and adds an OpenRig
block to `~/.tmux.conf`, so say all of that first. It doesn't start the daemon. Then `rig doctor`.
block to `~/.tmux.conf`, so say all of that first. It doesn't start the daemon. Then `rig doctor`. A login it reports
missing isn't harmless: say which one, and that a team may need it (`starter` runs its reviewer on Codex). Pass it on
in the handoff so the operator fits the team before anything starts.
- **Then go on to step 2:** say it's installed and ask what they want worked on, and in which repository. A plain
"install OpenRig" includes this. Stop here only if they say not to start a team.
- **If something fails:** `rig context get help` is the help guide for the installed version. If `rig` itself won't
@@ -167,7 +169,8 @@ person needs in their project or home folder and name that path.
(never the logical ID or a guessed name) and send:
`rig send <canonicalSessionName> 'This is the agent that installed OpenRig. The person will answer in your pane. Goal: <goal>. Project folder: <absolute path>. Branch: <branch>.'`
If the person stays here, replace "The person will answer in your pane" with "The person stays with me; send me your questions and
results to relay." Carry their constraints and any permission choice they made, chosen or declined, in either handoff.
results to relay." Carry their constraints, which logins they have (an installed provider that isn't signed in
doesn't count), and any permission choice they made, chosen or declined, in either handoff.
Or the person types the goal and folder in the operator's pane. If they give you a goal later, forward it the same
way. The operator helps them pick a team that fits their logins, starts it (`rig up`) only on their yes to the plan it
shows, and gives the goal to the team's lead. Before that yes, it says what launching into their folder changes for their own agent there; relay
@@ -272,8 +272,9 @@ unseen — which makes messages the one delivery channel that never gets skipped
type. Only if the window cannot open, `rig tui --shared` is the dashboard-only fallback; explain
the failure. In the window's `--json` output, `reusedWorkspace` with no new tiles means an
existing view was reused, which is success. `--provider herdr` or `--provider cmux` opens the
view in a provider that is already running, without opening a window. Ordinary opens add a new
workspace, so to come back to a fixed view, focus its open space; task follow mode reuses one.
view in a provider that is already running, without opening a window. Herdr reuses a workspace
that still shows the view with live attachments (`reusedWorkspace`, no new tiles); otherwise an
ordinary open adds a new workspace. Task follow mode reuses one.
**`qitem:<id>` as the view** previews or opens the current local owners of that task: its
pending, in-progress and blocked rows through explicitly linked successors, without closed
predecessors or past senders. It's a read-only membership view: stopped, missing, external and
+4
View File
@@ -98,6 +98,10 @@
"./codex-auth": {
"types": "./dist/codex-auth-surface.d.ts",
"import": "./dist/codex-auth-surface.js"
},
"./herdr-live-workspace": {
"types": "./dist/herdr-live-workspace-surface.d.ts",
"import": "./dist/herdr-live-workspace-surface.js"
}
},
"scripts": {
@@ -29,6 +29,13 @@ behave; this skill is the loop around them.
- Use `rig_queue_create` with `destination` (the lead, or the seat the person chose) and `body`. Write the body for a
capable colleague: the goal, why it matters, what done looks like, and where to look. Add a one-line `summary`.
- With a seat, end the body with the reply route, because your seat has no terminal and `rig send` can't reach it:
> To ask me anything, create a queue item to `<your seat>` (`rig queue create --destination <your seat> ...`), then
> block this item on that new item's id (`rig queue block <this id> --on <question id>`), so my answer wakes you. I
> check it when the person asks. Don't ask in your own terminal: the person isn't there. If you hand this item on,
> copy this paragraph into the new item. When you finish, put the outcome in this item's resolution and any file in
> its evidence ref.
- Tell the person the `qitemId` it returns. It's how both of you find this work again.
- If the call times out, check `rig_queue_show` with that same `qitemId` before trying again. If you retry, pass the same id
as `qitemId`. Never retry with a new one: that creates the work twice.
@@ -126,11 +126,14 @@ configurations, as below; do not take the pin from a cached page summary.
own working directory is OpenRig's: the workspace's `kernel` folder (on an older
install, the workspace itself), not their project, so never launch with
`--cwd .` from here.
3. **Three teams, one recommendation.** Present starter, workshop and factory,
recommend one with a short reason tied to their goal, and show each graph
in the shared TUI as you explain it (step 4):
3. **Three teams, one recommendation.** Check their logins first (step 5), so
the team you recommend fits them. Present starter, workshop and factory,
recommend one with a short reason tied to their goal, say which provider
each seat runs on, and show each graph in the shared TUI as you explain it
(step 4):
- `starter`: a builder and a reviewer (`dev-build`, `dev-review`) for one
bounded change. Built in; `first-project` is its old name.
bounded change. The builder runs on Claude Code and the reviewer on Codex.
Built in; `first-project` is its old name.
- `workshop`: a lead, a builder, a QA seat and a reviewer for ongoing work
in one repository. Not built in: it installs from its listing on
openrig.dev/rigs, a GitHub folder link pinned to a reviewed commit. Read
@@ -203,10 +206,17 @@ configurations, as below; do not take the pin from a cached page summary.
infer which tools they have from
the kernel's own runtimes (`rig ps --nodes --rig kernel --json`), or ask. Check
only the providers the team needs (`claude auth status` or
`codex login status`). If you run in Claude Code, the kernel launch allows
`codex login status`), before you recommend it, never after a launch. A
provider counts as theirs only when its check passes: Codex installed but
not signed in (`codex login status` says "Not logged in") isn't theirs, and
one their setup left out is theirs only if they say so. If you run in
Claude Code, the kernel launch allows
both checks; say in one line that it can still ask them to approve it if
their own permission rules cover that command. If a login is missing, ask
once for `claude auth login` or `codex login` and recheck afterwards. The
their own permission rules cover that command. If a seat needs a login
they don't have, name that seat and let them choose before you plan: a copy
adapted to the logins they have (below), or signing in first
(`claude auth login` or `codex login`, then recheck). If they choose the
team as it is, plan it and say which seat will wait for that sign-in. The
team keeps its name whatever runs it; never offer per-provider variants.
- **A built-in team needs a provider they don't have:** author an adapted
copy. Copy the shipped spec's whole folder (the folder of `sourcePath`
@@ -237,7 +247,8 @@ configurations, as below; do not take the pin from a cached page summary.
directory.
6. **Plan, then ask.** Run `rig up <team, copy path or link> --cwd <folder>
--plan` (for workshop, with its `--target ~/rigs/workshop`) and tell them
what will start: how many agents, which providers, in which folder.
what will start: how many agents, the provider each seat runs on and
whether they're signed in to it (step 5), in which folder.
Say too what launching into their folder changes for their own agent
there. A Claude Code team usually adds OpenRig's blocks to `CLAUDE.md`,
plus `.mcp.json` and `.openrig/`, and its `.claude/settings.local.json`
@@ -261,7 +272,10 @@ configurations, as below; do not take the pin from a cached page summary.
later prompts.
- **A permission choice already made** (in the handoff or to you: fewer
prompts for this project, a mode, a rule, or keep prompts on): use it,
and don't ask again.
and don't ask again, when it covers the commands this goal will repeat
in this project. Keeping prompts on covers them all. A choice for other
commands or another scope, such as a user-wide rule for `rig` commands,
doesn't: make the one offer below for the commands it leaves out.
- **Otherwise, one offer if they want fewer interruptions:** name the
command families this goal will repeat in their folder (for example
`git switch`, `git add`, `git commit` and the project's test command)
@@ -361,8 +375,10 @@ configurations, as below; do not take the pin from a cached page summary.
so the choice is theirs.
When you see one, tell them where it is and where they can answer: which
seat, what its prompt asks (`rig capture <session>` with the seat's
`canonicalSessionName` shows it), and that seat's terminal in the team's
space from step 8, or through you. Only when no space is open, give the
`canonicalSessionName` shows it), and that seat's terminal, or through
you. A team seat's terminal is in the team's space from step 8. A kernel
seat's is in the kernel's view (`rig terminal open saved:kernel --window`;
the advisor has its own tab or window). Only when no space is open, give the
seat's `tmuxAttachCommand` as a command for a new terminal, with one
line on what it does (it shows that seat; closing the window leaves the
seat running), or just its name if it has none. Never send them to a
@@ -11,9 +11,17 @@ Run `rig whoami --json` to confirm identity.
written to you.** You are the first agent they talk to; the advisor does not
greet. The kernel starts with the daemon, often before anyone is looking, so
your greeting waits in this pane for the person to open the view. Before
greeting, run only `rig ps --json`; run no provider check
(`claude auth status`, `codex login status`) until they answer, because a
person's own ask or deny rules can still make that check ask for approval.
greeting, run only `rig ps --json` and `rig gateway participants`; run no
provider check (`claude auth status`, `codex login status`) until they answer,
because a person's own ask or deny rules can still make that check ask for
approval.
- **If `rig gateway participants` says no person is registered,** put its offer
in your greeting, after the welcome, in a sentence or two: OpenRig's questions,
such as another machine asking to pair, need a person to reach. Ask the name to
use, and register them only on their yes, with the command it prints. On a no or
not now, register nothing and say those questions can't reach anyone until
someone is registered. If a person is registered, don't offer.
- **No rig but `kernel`:** write a short welcome in plain words, for example:
@@ -16,7 +16,7 @@ import type { SeatLaunchEnvironment } from "../domain/seat-launch-environment.js
import { codexPostureArg } from "./yolo-mode.js";
import type {
RuntimeAdapter, NodeBinding, ResolvedStartupFile,
InstalledResource, ProjectionResult, StartupDeliveryResult, ReadinessResult,
InstalledResource, ProjectionResult, StartupDeliveryResult, ReadinessResult, ReadinessOptions,
HarnessLaunchResult,
} from "../domain/runtime-adapter.js";
import type { GuidanceChoice } from "../domain/runtime-adapter.js";
@@ -69,7 +69,7 @@ const codexHookTrust = createRequire(import.meta.url)("../../assets/plugins/open
codexHookHash(eventLabel: string, handler: { command: string; timeoutSec: number; matcher?: string | null; statusMessage?: string | null }): string;
};
import { listNativeProcesses, observeCodexPaneProcess, observeCodexForkProcess, verifyCodexPaneProcess, verifyPaneIdleShell, type NativeProcessRow } from "../domain/native-process-lineage.js";
import { listNativeProcesses, listNativeProcessesOrThrow, observeCodexPaneProcess, observeCodexForkProcess, verifyCodexPaneProcess, verifyPaneIdleShell, type NativeProcessRow } from "../domain/native-process-lineage.js";
import { recordUnchangedSeatSkillFollowing, recordSeatSkillFollowing, recordSeatSkillWrite, seatPluginSkillsLossNote, seatProjectionComplete, seatSkillWriteRefusal, SEAT_SKILLS_BOOTSTRAP_BLOCK_ID } from "../domain/seat-skill-storage.js";
import { codexPluginContentHash, planOwnedCodexContentApproval, recordOwnedCodexApproval } from "../domain/codex-owned-plugin-trust.js";
import { findTomlTable, opensTomlTable, parseTomlRoot, tomlArrayTableHeaderPath, tomlDefines, tomlTableHeaderPath } from "../domain/toml-tables.js";
@@ -154,6 +154,8 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
private seatLaunchEnvironment?: SeatLaunchEnvironment;
private fs: CodexAdapterFsOps;
private listProcesses: () => CodexProcess[] | Promise<CodexProcess[]>;
/** What a poll's ObservationPass shares: the same listing, but a failure rejects (an empty array reads as success). */
private listProcessesShared: () => CodexProcess[] | Promise<CodexProcess[]>;
private readThreadIdByPid: (pid: number, identity?: string, home?: string) => Promise<string | undefined> | string | undefined;
private readResumeEvidence: (pid: number, identity: string, home?: string) => Promise<CodexResumeEvidence> | CodexResumeEvidence;
private resumeProofWindowMs: number;
@@ -206,6 +208,8 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
private codexSystemConfigDir: string;
/** #875: the managed guidance blocks a fresh launch's startup queued for its developer instructions, per tmux session. */
private launchInstructions = new Map<string, Map<string, string>>();
/** #3039: per tmux session, the block ids its last launch's developer instructions held. */
private sentLaunchGuidance = new Map<string, string[]>();
/** #2456: OpenRig's record of what it last wrote in each managed guidance block (startup wires the daemon's). */
private managedBlockRecords: ManagedBlockRecords | undefined;
@@ -278,6 +282,7 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
this.resolveGitAddDirs = deps.resolveGitAddDirs ?? resolveCodexGitAddDirs;
this.activityRelayPath = deps.activityRelayPath;
this.listProcesses = deps.listProcesses ?? defaultListProcesses;
this.listProcessesShared = deps.listProcesses ?? defaultListProcessesOrThrow;
this.resolveHomeDirByPid = deps.resolveHomeDirByPid ?? defaultResolveHomeDirByPid;
// A seat with its own CODEX_HOME logs its threads there, so each read names the home it searches.
this.readThreadIdByPid = deps.readThreadIdByPid ?? ((pid, identity, home) => identity === undefined
@@ -809,7 +814,10 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
}
async project(plan: ProjectionPlan, binding: NodeBinding): Promise<ProjectionResult> {
if (binding.guidanceLaunchInstructions && binding.tmuxSession) this.launchInstructions.set(binding.tmuxSession, new Map());
if (binding.guidanceLaunchInstructions && binding.tmuxSession) {
this.launchInstructions.set(binding.tmuxSession, new Map());
this.sentLaunchGuidance.delete(binding.tmuxSession);
}
const projected: string[] = [];
const warnings: string[] = [];
const skipped: string[] = [];
@@ -1167,8 +1175,9 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
const { profile, queueStateDirArg, gitDirArg, seatFolderArg, model, postureArg, networkArg, loginShellArg, daemonOptOut, effort } = prepared;
// The git dirs and the seat folder follow the conversation id, as on a fork, so the resume proof reads the id even
// from a path with a space.
// A resume whose startup queued the managed guidance carries it as developer instructions, as a fresh launch does.
return buildCodexResumeCore(resumeToken, profile, false, queueStateDirArg.trim() || undefined, binding.launchPosture, model, `${postureArg}${networkArg}${loginShellArg}`, daemonOptOut, effort)
+ gitDirArg + seatFolderArg;
+ gitDirArg + seatFolderArg + (binding.guidanceLaunchInstructions && binding.tmuxSession ? this.developerInstructionsArg(binding.tmuxSession) : "");
}
private async seatCommand(binding: NodeBinding, cmd: string, launchShell?: string): Promise<string> {
@@ -1252,7 +1261,7 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
return await this.tmux.capturePaneContent(target, 40) ?? "";
}
async checkReady(binding: NodeBinding): Promise<ReadinessResult> {
async checkReady(binding: NodeBinding, options?: ReadinessOptions): Promise<ReadinessResult> {
if (!binding.tmuxSession) {
return { ready: false, reason: "No tmux session bound" };
}
@@ -1261,6 +1270,9 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
return { ready: false, reason: "tmux session not responsive" };
}
// In a poll's pass, this agent's listings come from the pass: shared with the other agents checked in it, and
// still two distinct observations for each proof.
const listProcesses = options?.observationPass ? options.observationPass.lister(this.listProcessesShared, this.listProcesses) : this.listProcesses;
const paneCommand = await this.tmux.getPaneCommand(binding.tmuxSession);
const paneContent = await this.captureProbeScreen(binding.tmuxSession);
let probe = assessNativeResumeProbe({
@@ -1271,7 +1283,7 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
if (probe.code === "returned_to_shell" || probe.code === "awaiting_runtime") {
const process = await verifyCodexPaneProcess({ target: binding.tmuxSession, tmux: this.tmux as { getPanePid(target: string): Promise<number | null> },
listProcesses: this.listProcesses as never });
listProcesses: listProcesses as never });
if (process) {
const currentPaneCommand = await this.tmux.getPaneCommand(binding.tmuxSession);
const currentPaneContent = await this.captureProbeScreen(binding.tmuxSession);
@@ -1284,7 +1296,7 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
const isIdleShell = await verifyPaneIdleShell({
target: binding.tmuxSession,
tmux: this.tmux,
listProcesses: this.listProcesses,
listProcesses,
});
if (!isIdleShell) {
return {
@@ -1596,17 +1608,25 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
const blocks = this.launchInstructions.get(tmuxSession);
this.launchInstructions.delete(tmuxSession);
if (!blocks || blocks.size === 0) return "";
this.sentLaunchGuidance.set(tmuxSession, [...blocks.keys()]);
const text = [LAUNCH_INSTRUCTIONS_PREAMBLE, ...[...blocks].map(([id, content]) => managedBlockText(id, content))].join("\n\n");
return ` -c ${shellQuote(`developer_instructions=${JSON.stringify(text).replace(/\u007f/g, "\\u007F")}`)}`;
}
launchGuidanceSent(tmuxSession: string): string[] | undefined {
const sent = this.sentLaunchGuidance.get(tmuxSession);
this.sentLaunchGuidance.delete(tmuxSession);
return sent;
}
/** #875: whether a fresh launch can carry this seat's managed guidance as developer instructions instead of writing the
* repository AGENTS.md: Codex 0.164.0 or later (where `developer_instructions` is a declared key), and no visible config
* layer sets one, since the launch value would replace it. Anything else, or anything unreadable, keeps AGENTS.md. */
guidanceFileFor(binding: NodeBinding, opts?: { resuming?: boolean }): GuidanceChoice | Promise<GuidanceChoice> {
// A resume or fork (untested with developer instructions) and a startup continuation (it launches nothing) keep the
// repository path, answered at once.
if (opts?.resuming || !binding.tmuxSession) return { file: null };
guidanceFileFor(binding: NodeBinding, opts?: { resuming?: boolean; resumingConversation?: boolean }): GuidanceChoice | Promise<GuidanceChoice> {
// A fork (untested with developer instructions) and a startup continuation (it launches nothing) keep the repository
// path, answered at once. A resume of the seat's own conversation (a restore, `rig up --existing`) chooses as a fresh
// launch does, so its guidance stays out of the repository AGENTS.md too.
if (!binding.tmuxSession || (opts?.resuming && !opts.resumingConversation)) return { file: null };
return this.freshGuidanceChoice(binding);
}
@@ -3009,6 +3029,12 @@ export async function defaultListProcesses(): Promise<CodexProcess[]> {
return listNativeProcesses();
}
/** The default listing for a shared observation pass: a failed enumeration rejects, so the pass can retry each agent
* on its own instead of caching an empty table as a success. */
export async function defaultListProcessesOrThrow(): Promise<CodexProcess[]> {
return listNativeProcessesOrThrow();
}
function findCodexDescendantPids(
processes: Array<{ pid: number; ppid: number; command: string }>,
parentPid: number
+24 -3
View File
@@ -1,3 +1,4 @@
import type { InputReadDiagnostic } from "../domain/input-read-diagnostic.js";
import { DeliveryGuardError, type SeatDeliveryGuard } from "../domain/seat-delivery-guard.js";
import { writeFile as fsWriteFile, unlink as fsUnlink } from "node:fs/promises";
import { tmpdir } from "node:os";
@@ -77,7 +78,7 @@ export function defaultTmuxFileOps(): TmuxFileOps {
export type TmuxResult =
| { ok: true; warnings?: string[]; stopPhase?: StopPhase }
| { ok: false; code: string; message: string; stopPhase?: StopPhase };
| { ok: false; code: string; message: string; stopPhase?: StopPhase; inputReadFailure?: InputReadDiagnostic };
/** Furthest external stop boundary reached; an attempted command can have an uncertain effect. */
export type StopPhase = "none" | "detach_attempted" | "detached" | "kill_attempted";
@@ -246,7 +247,7 @@ function isTmuxTransportAbsentError(err: unknown): boolean {
}
function classifyWriteError(err: unknown): TmuxResult {
if (err instanceof DeliveryGuardError) return { ok: false, code: err.code, message: err.message };
if (err instanceof DeliveryGuardError) return { ok: false, code: err.code, message: err.message, ...(err.inputReadFailure ? { inputReadFailure: err.inputReadFailure } : {}) };
if (!(err instanceof Error)) {
return { ok: false, code: "unknown", message: String(err) };
}
@@ -600,7 +601,8 @@ export class TmuxAdapter {
return guard.input(identity, () => write(pane, () => guard.checkInput(identity), bound.nodeId));
});
} catch (error) {
return { ok: false, code: (error as { code?: string }).code ?? "guard_target_unknown", message: String((error as Error).message) };
return { ok: false, code: (error as { code?: string }).code ?? "guard_target_unknown", message: String((error as Error).message),
...(error instanceof DeliveryGuardError && error.inputReadFailure ? { inputReadFailure: error.inputReadFailure } : {}) };
}
}
@@ -2170,6 +2172,25 @@ export class TmuxAdapter {
}
}
/** The clients attached to a session: each one's terminal device and the terminal type it reported (XTVERSION,
* "" when it reported none). Empty when the session has no clients, or when the session or the server is gone;
* null when tmux can't be read. */
async listSessionClientTerminals(session: string): Promise<Array<{ tty: string; termtype: string }> | null> {
const exact = exactTarget(session, "session");
const format = `#{client_tty}${TMUX_FIELD_SEPARATOR}#{client_termtype}`;
try {
const output = await this.run(["tmux", "list-clients", "-t", exact, "-F", format],
`tmux list-clients -t ${shellQuote(exact)} -F "${format}"`);
return output.split("\n").flatMap((line) => {
const separator = line.indexOf(TMUX_FIELD_SEPARATOR);
const tty = line.slice(0, Math.max(separator, 0));
return tty.startsWith("/dev/") ? [{ tty, termtype: line.slice(separator + TMUX_FIELD_SEPARATOR.length) }] : [];
});
} catch (err) {
return isServerMissingError(err) || isSessionAbsenceError(tmuxReportedError(err)) ? [] : null;
}
}
/**
* OPR.0.4.3.26 — retarget an already-attached client's VIEW to `target`
* (`<session>` or `<session>:<window>`). This is the whole point of the
+8
View File
@@ -25,6 +25,11 @@ export interface AttentionItem {
/** The settings page where the person decides this request directly, without an agent (a pairing request's Approve and
* Deny): a TUI settings category, and the request it opens on there. */
settingsLink?: { category: string; focus: string; label: string };
/** A queue request's decision revision: the same opaque token its single-row read returns and a settling act can name. */
revision?: string;
/** The requests this is about, by ID: a parked row is itself the request; an ask is about the open rows blocked on it
* (at most 100). Empty when no request is recorded as waiting on it. */
about?: string[];
}
export interface AttentionDetail {
item: AttentionItem;
@@ -38,6 +43,9 @@ export interface AttentionRead {
sources: Array<{ source: string; state: "available" | "unavailable" | "partial"; detail: string }>;
detail: AttentionDetail | null;
detailError: string | null;
/** The event log's newest seq, read before this snapshot: following /api/events from it (Last-Event-ID) replays every
* event since, possibly some already reflected here, never one missed. Absent without an event log. */
watermark?: number;
/** Whose queue this Feed shows (`view`), and who acts on it. A view, never an identity: acts on what it shows carry the
* primary user's authority, the person at the terminal, whoever's queue it is. `requested` names a view that matched no
* registered person. Absent when no person is registered. */
+4
View File
@@ -10,6 +10,8 @@ import { queueItemsHandedOffFromIndexSchema } from "./migrations/159_queue_items
import { networkBindingsSchema } from "./migrations/160_network_bindings.js";
import { networkReceiptsSchema } from "./migrations/161_network_receipts.js";
import { sessionAddressReadIndexesSchema } from "./migrations/162_session_address_read_indexes.js";
import { networkInstallationsSchema } from "./migrations/163_network_installations.js";
import { queueItemsReplyToIndexSchema } from "./migrations/164_queue_items_reply_to_index.js";
import { activityGrantsSchema } from "./migrations/143_activity_grants.js";
import { environmentBindingsSchema } from "./migrations/144_environment_bindings.js";
import { nodePermissionsToSchema } from "./migrations/145_node_permissions_to.js";
@@ -327,4 +329,6 @@ export const ALL_MIGRATIONS: Migration[] = [
networkBindingsSchema,
networkReceiptsSchema,
sessionAddressReadIndexesSchema,
networkInstallationsSchema,
queueItemsReplyToIndexSchema,
];
@@ -0,0 +1,24 @@
import type { Migration } from "../migrate.js";
/** This daemon enrolled in an account: the account's site, its installation id, and whether the person chose plain http
* for it. The installation key lives in a private file under the OpenRig home, never in this table. A binding made
* through the account names its installation, its participant and the account's installation id the name was listed under,
* and records when the account stopped listing it. */
export const networkInstallationsSchema: Migration = {
name: "163_network_installations.sql",
sql: `
CREATE TABLE IF NOT EXISTS network_installations (
id TEXT PRIMARY KEY,
site TEXT NOT NULL,
installation_id TEXT NOT NULL,
name TEXT,
allow_http INTEGER NOT NULL DEFAULT 0 CHECK (allow_http IN (0, 1)),
created_at TEXT NOT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_network_installations_site ON network_installations(site);
ALTER TABLE network_bindings ADD COLUMN installation_id TEXT;
ALTER TABLE network_bindings ADD COLUMN participant_name TEXT;
ALTER TABLE network_bindings ADD COLUMN account_removed_at TEXT;
ALTER TABLE network_bindings ADD COLUMN account_installation_id TEXT;
`,
};
@@ -0,0 +1,10 @@
import type { Migration } from "../migrate.js";
/** An ask's answers and its decision revision find rows by their `reply_to`. Without this, each lookup scans the whole
* queue, once per request on the attention read. Partial: only replies carry the column. */
export const queueItemsReplyToIndexSchema: Migration = {
name: "164_queue_items_reply_to_index.sql",
sql: `
CREATE INDEX IF NOT EXISTS idx_queue_items_reply_to ON queue_items(reply_to) WHERE reply_to IS NOT NULL;
`,
};
@@ -1,3 +1,4 @@
import type { InputReadDiagnostic } from "./input-read-diagnostic.js";
import type { TerminalActor, TerminalPolicyStore } from "./terminal-policy.js";
import { TerminalPolicyRefusal } from "./terminal-policy.js";
import { DeliveryGuardError } from "./seat-delivery-guard.js";
@@ -425,6 +426,7 @@ type PendingPostCompactStage = "turn_boundary" | "restore_prompt" | "compliance_
/** Safe delivery diagnostics: never retain pane contents or an exception message. */
export interface RestoreDeliveryAttempt {
inputReadFailure?: InputReadDiagnostic;
stage: PendingPostCompactStage;
at: string;
ok: boolean;
@@ -461,6 +463,7 @@ export interface ObservedCompaction {
detail: string;
}
export interface PreparationState {
inputReadFailure?: InputReadDiagnostic & { stage: "preparation" | "compact" };
/** The reading that held this preparation send; never includes draft text. */
inputBox?: SendResult["heldInputBoxReading"];
policyActor?: TerminalActor;
@@ -565,6 +568,7 @@ interface PreparationFailureRun {
}
interface CompactionRecord {
inputReadFailure?: PreparationState["inputReadFailure"];
preparationFailures?: PreparationFailureRun;
inputBox?: PreparationState["inputBox"];
/** The daemon process that last wrote it. */
@@ -1000,6 +1004,7 @@ export class ClaudeCompactionEnforcer {
} catch (error) {
this.recordRestoreFailure(input.sessionName, stage, record, {
ok: false, reason: error instanceof DeliveryGuardError ? error.code : "send_failed",
...(error instanceof DeliveryGuardError && error.inputReadFailure ? { inputReadFailure: error.inputReadFailure } : {}),
}, error instanceof Error ? error.name : typeof error);
if (error instanceof DeliveryGuardError) return { triggered: false, reason: error.code === "typing_guard_enabled" ? "typing_guard_enabled" : "guard_target_unknown" };
throw error;
@@ -1027,7 +1032,7 @@ export class ClaudeCompactionEnforcer {
private recordRestoreFailure(
session: string, stage: PendingPostCompactStage | undefined,
record: { file: string; record: CompactionRecord } | undefined,
result: Pick<SendResult, "ok" | "reason" | "outcome" | "activity" | "heldInputBox">, errorClass?: string,
result: Pick<SendResult, "ok" | "reason" | "outcome" | "activity" | "heldInputBox" | "inputReadFailure">, errorClass?: string,
): void {
if (!stage || !record || this.records.get(session) !== record || this.pendingPostCompactRestore.get(session) !== stage) return;
const prior = record.record.lastDelivery;
@@ -1042,6 +1047,7 @@ export class ClaudeCompactionEnforcer {
const lastDelivery: RestoreDeliveryAttempt = {
stage, at: new Date(this.now()).toISOString(), ok: result.ok, reason: result.reason ?? "send_failed",
...(result.outcome ? { outcome: result.outcome } : {}),
...(result.inputReadFailure ? { inputReadFailure: result.inputReadFailure } : {}),
...(result.activity ? { activity: { state: result.activity.state, reason: result.activity.reason, evidenceSource: result.activity.evidenceSource } } : {}),
...(errorClass ? { errorClass } : {}), failures: waiting ? 0 : (prior?.failures ?? 0) + 1,
...(held ? { inputBox: held } : {}), ...(unreadable ? { unreadable } : {}),
@@ -1598,7 +1604,7 @@ export class ClaudeCompactionEnforcer {
if (error instanceof DeliveryGuardError) {
const written = (error as { inputWritten?: boolean }).inputWritten === true;
const attempted = (error as { inputAttempted?: boolean }).inputAttempted === true;
prep = { ok: false, sent: written, reason: error.code,
prep = { ok: false, sent: written, reason: error.code, inputReadFailure: error.inputReadFailure,
inputPhase: written ? "written" as const : attempted ? "attempted" as const : "not_reached" as const };
} else prep = null;
}
@@ -1611,7 +1617,8 @@ export class ClaudeCompactionEnforcer {
// Neither a failed response nor its loss proves no paste/Enter. Never replay uncertainty.
attempt.delivery = prep?.ok && prep.outcome !== "retained" ? "delivered" : notSent ? "not_sent" : "uncertain";
attempt.inputBox = prep?.heldInputBoxReading;
this.persist(input.sessionName, attempt.attemptId, { delivery: attempt.delivery, sends: attempt.sends, inputBox: attempt.inputBox });
if (prep?.inputReadFailure) attempt.inputReadFailure = { stage: "preparation", ...prep.inputReadFailure };
this.persist(input.sessionName, attempt.attemptId, { delivery: attempt.delivery, sends: attempt.sends, inputBox: attempt.inputBox, inputReadFailure: attempt.inputReadFailure });
// The replacement request went out (or may have): the ended attempt's gate is used up.
if (!notSent && attempt.afterEnded !== undefined && this.pendingPreCompactPrep.get(input.sessionName) === attempt) this.lastEnded.delete(input.sessionName);
if (this.pendingPreCompactPrep.get(input.sessionName) !== attempt || attempt.controller.signal.aborted) return;
@@ -1661,7 +1668,7 @@ export class ClaudeCompactionEnforcer {
return this.sessionTransport.send(input.sessionName, composed.command,
{ openrigNotice: true, allowDraftWhileIdle: true, beforeWrite, ...(attempt.deadlineAt !== null ? { waitForIdleMs: attempt.prepared ? idleWait : Math.max(1, Math.min(idleWait, this.compactDeadline(attempt)! - this.now())), readinessFromPaneOnly: true } : {}) });
};
let result: Pick<SendResult, "ok" | "reason" | "outcome" | "sent" | "inputPhase" | "activity" | "heldInputBox">;
let result: Pick<SendResult, "ok" | "reason" | "outcome" | "sent" | "inputPhase" | "activity" | "heldInputBox" | "inputReadFailure">;
let guardRefused = false;
try {
const guard = this.sessionTransport.deliveryGuard;
@@ -1672,11 +1679,16 @@ export class ClaudeCompactionEnforcer {
const attempted = (error as { inputAttempted?: boolean } | null)?.inputAttempted === true;
guardRefused = error instanceof DeliveryGuardError && !written && !attempted;
result = { ok: false, reason: error instanceof DeliveryGuardError ? error.code : "delivery_uncertain",
...(error instanceof DeliveryGuardError && error.inputReadFailure ? { inputReadFailure: error.inputReadFailure } : {}),
...(written ? { sent: true, inputPhase: "written" as const } : attempted ? { inputPhase: "attempted" as const } : {}) };
} finally {
delete attempt.compactInFlight;
}
if (!result.ok || result.outcome === "retained") {
if (result.inputReadFailure) {
attempt.inputReadFailure = { stage: "compact", ...result.inputReadFailure };
this.persist(input.sessionName, attempt.attemptId, { inputReadFailure: attempt.inputReadFailure });
}
const phase = result.inputPhase;
// A write that was issued, or text already in the input, is never "nothing sent".
const writeAttempted = phase === "attempted" || phase === "written" || result.sent === true;
@@ -1927,7 +1939,7 @@ export class ClaudeCompactionEnforcer {
compact: "not_sent", sends: record.sends,
deadlineAt: record.deadlineAt ?? (record.delivery === "not_sent" ? null : record.updatedAt + AUTO_PREP_WAIT_MS_DEFAULT),
policyWasEnabled: true, preparationRoot: record.preparationRoot, controller: new AbortController(),
compactInstruction: record.compactInstruction, inputBox: record.inputBox,
compactInstruction: record.compactInstruction, inputBox: record.inputBox, inputReadFailure: record.inputReadFailure,
// A held attempt comes back held, with its recorded hold (never stamped again) and its map's age and usage.
...(held ? { prepared: true as const, preparedAt: record.preparedAt ?? record.updatedAt, preparedReason: record.preparedReason ?? "map_complete_seat_never_idle" } : {}),
...(held ? { mapReadyAt: record.mapReadyAt ?? record.preparedAt ?? record.updatedAt } : record.mapReadyAt !== undefined ? { mapReadyAt: record.mapReadyAt } : {}),
@@ -11,6 +11,7 @@ import type { UsageSamplesStore, ProviderWindowSampleInput } from "./usage-sampl
import type { ContextUsage } from "./types.js";
import { getLatestStartupFailedEvent, hasClaudeResumeIdentityWork, readPendingStartupContext } from "./startup-orchestrator.js";
import { claudeResumeRotation, SessionRegistry } from "./session-registry.js";
import { ObservationPass } from "./process-observation-pass.js";
/** Default polling interval: 30 seconds. */
export const DEFAULT_POLL_INTERVAL_MS = 30_000;
@@ -104,6 +105,8 @@ export class ContextMonitor {
private async runPoll(): Promise<void> {
this.compactionEnforcer?.reconcilePreparations?.();
const sessions = this.getEligibleSessions();
// One pass per poll: the seats re-checked this poll share their process listings; the next poll starts fresh.
const pass = new ObservationPass();
for (const session of sessions) {
if (!this.isCurrentSession(session, true)) continue;
let observed: ContextUsage | null = null;
@@ -143,7 +146,7 @@ export class ContextMonitor {
}
}
await this.normalizeStartupStatus(session);
await this.normalizeStartupStatus(session, pass);
await this.maybeAutoCompact(session, observed);
}
this.drainProviderWindowSamples();
@@ -314,7 +317,7 @@ export class ContextMonitor {
return this.store.readAndNormalize(session.session_name);
}
private async normalizeStartupStatus(session: EligibleSession): Promise<void> {
private async normalizeStartupStatus(session: EligibleSession, pass: ObservationPass): Promise<void> {
const checker = session.runtime ? this.readinessCheckers[session.runtime] : undefined;
if (!checker?.checkReady) return;
if (session.startup_status !== "failed" && session.startup_status !== "attention_required") return;
@@ -340,7 +343,9 @@ export class ContextMonitor {
updatedAt: "",
cwd: session.cwd ?? "",
...(claude && session.generation_uuid ? { launchGeneration: session.generation_uuid } : {}),
}, ...(claude && session.resume_token ? [{ resumeToken: session.resume_token, ...(rotation ? { resumeRotation: rotation } : {}) }] : []));
}, ...(claude && session.resume_token ? [{ resumeToken: session.resume_token, ...(rotation ? { resumeRotation: rotation } : {}) }]
// Only the Codex adapter takes its process listings from the pass; the others are called as before.
: session.runtime === "codex" ? [{ observationPass: pass }] : []));
// Hold no database lock while observing the runtime. Revalidation and
// the write share an immediate transaction, reserving the writer before the
// snapshot read so WAL contention cannot fail a later read-to-write upgrade.
@@ -95,7 +95,8 @@ export class DraftAwareDelivery {
: guardError ? error.message : "The delivery attempt ended without a reliable write result. Repeating the request may duplicate input.";
result = { ok: false, sessionName: session, outcome: "failed", inputPhase,
...(inputWritten || inputPhase === "not_reached" ? { sent: inputWritten } : {}),
reason: guardError ? error.code : "delivery_indeterminate", error: detail };
reason: guardError ? error.code : "delivery_indeterminate", error: detail,
...(guardError && error.inputReadFailure ? { inputReadFailure: error.inputReadFailure } : {}) };
}
if (inputWritten) result = { ...result, sent: true };
const preInputRefusal = ["draft_input_busy", "draft_input_unknown", "draft_input_changed", "draft_wake_superseded",
@@ -7,3 +7,23 @@ export const PAIR_SOURCE_SESSION = "host-pair@kernel";
export function isHostPairingAsk(item: { sourceSession: string; evidenceRef?: string | null }): boolean {
return item.sourceSession === PAIR_SOURCE_SESSION && (item.evidenceRef ?? "").startsWith("pair-request:");
}
/** A pairing requester's self-description wherever a person or an agent reads it: quoted and escaped, as the
* unauthenticated requesting machine's own words, so nothing in it can close the quotes and read as OpenRig's own
* text. Its length and characters are bounded where the request is taken; anything left is shown, quoted. */
export function quotedRequester(requester: string): string {
return JSON.stringify(requester);
}
/** The quoted name where a limit applies (the request's question): whole when it fits in `max` characters, else the
* longest leading part that fits, quoted and marked "(shortened)", so it never reads as the whole name. Escapes can
* make a name up to six times longer quoted than stored; the request's body and its record keep it whole. */
export function quotedRequesterWithin(requester: string, max: number): string {
const whole = quotedRequester(requester);
if (whole.length <= max) return whole;
const marker = " (shortened)";
// By code point, so a character outside the basic plane is never split.
const kept = [...requester];
while (kept.length > 0 && quotedRequester(kept.join("")).length + marker.length > max) kept.pop();
return `${quotedRequester(kept.join(""))}${marker}`;
}
@@ -0,0 +1,47 @@
/** Reporting only: never retain composer text, suggestions, frames, hints or exception messages. */
export interface InputReadDiagnostic {
check: "composer" | "draft-aware";
status: "empty" | "text" | "typed" | "likely-suggestion" | "typed-with-suggestion" | "unknown" | "no-input-box";
confidence: "high" | "medium" | "low" | "unknown" | null;
reason: string;
cursor: { present: boolean; valid: boolean | null; atEnd: boolean | null };
/** null means this reader does not report whether a timeout occurred. */
timedOut: boolean | null;
}
const reasons = new Set(["capture_unavailable", "pane_in_mode", "invalid_cursor", "incomplete_frame",
"ambiguous_composer", "unrecognized_composer", "read_timeout", "read_budget_spent", "cursor_moved",
"cursor_unavailable", "cursor_outside", "unrecognized_input_box", "input_not_clear",
"paste_controls", "paste_long", "paste_viewport"]);
/** Copy only fixed vocabulary and cursor flags. Unknown reader reasons remain content-free. */
export function inputReadDiagnostic(check: InputReadDiagnostic["check"], reading: {
state?: string; status?: string; confidence?: string; unknownReason?: string;
cursor?: { x: number; y: number; width: number; height: number } | null;
cursorAtEnd?: boolean; evidence?: string[];
} | null, reason?: string): InputReadDiagnostic {
const evidence = reading?.evidence ?? [];
const timeout = evidence.includes("input box reads timed out");
const derived = reason ?? reading?.unknownReason ?? (timeout ? "read_timeout"
: evidence.includes("input box budget spent") ? "read_budget_spent"
: evidence.includes("cursor moved during the capture") ? "cursor_moved"
: evidence.includes("cursor unavailable") ? "cursor_unavailable"
: evidence.some(e => e === "cursor outside the input box" || e === "cursor seen once outside the input box") ? "cursor_outside"
: reading?.status === "no-input-box" ? "unrecognized_input_box"
: reading?.status === "unknown" || !reading ? "capture_unavailable" : "input_not_clear");
const status = reading?.status ?? reading?.state;
const confidence = reading?.confidence;
const cursor = reading?.cursor;
return {
check,
status: ["empty", "text", "typed", "likely-suggestion", "typed-with-suggestion", "unknown", "no-input-box"].includes(status ?? "")
? status as InputReadDiagnostic["status"] : "unknown",
confidence: ["high", "medium", "low", "unknown"].includes(confidence ?? "")
? confidence as InputReadDiagnostic["confidence"] : null,
reason: reasons.has(derived) ? derived : "capture_unavailable",
cursor: { present: !!cursor, valid: cursor ? [cursor.x, cursor.y, cursor.width, cursor.height].every(Number.isInteger)
&& cursor.x >= 0 && cursor.y >= 0 && cursor.width > cursor.x && cursor.height > cursor.y : null,
atEnd: typeof reading?.cursorAtEnd === "boolean" ? reading.cursorAtEnd : null },
timedOut: timeout ? true : null,
};
}
@@ -573,35 +573,39 @@ function mayBeClaudeRuntime(row: NativeProcessRow): boolean {
/** The same OS observation serves menu input, restore proof and periodic identity.
* Older callers may carry only pid/ppid/command; that is insufficient positive Codex proof. */
export async function listNativeProcesses(options: { claudeLaunchPaths?: boolean; frozenExecutable?: string } = {}): Promise<NativeProcessRow[]> {
try {
// Copies: the table is shared with concurrent readers, and executable paths are added below.
const rows: NativeProcessRow[] = (await runAsyncSite("codex.runtime.list_processes", readProcessTable)).map((row) => ({ ...row }));
// `claudeLaunchPaths`: the caller is proving a launch through a `#!` script, which needs the OS path of the
// foreground path-named Claude too. `frozenExecutable`: the caller is proving a launch that froze that file (the
// installer's symlink resolved to its versioned file), which needs the path only of a path-named Claude whose
// argv[0] isn't already the file; an exact launch is proved without it, and a helper timeout can't change its
// fingerprint. Every other listing skips that read (on macOS it starts a helper process).
const candidates = rows.filter(row => needsClaudeExecutablePath(row) || (mayBeClaudeAfterScript(row) && (options.claudeLaunchPaths === true
|| (!!options.frozenExecutable && tokens(row.command)[0] !== options.frozenExecutable))));
if (candidates.length > 0) {
const paths = await readNativeExecutablePaths(candidates.map(row => row.pid));
for (const row of candidates) row.executablePath = paths.get(row.pid);
}
// Linux argv was captured with this same /proc table sample; never read real /proc
// again after a caller has selected a fixture or alternate process-table root.
// Only foreground rows can be selected below. Skip macOS helper reads for
// background Codex processes; every foreground seat still gets fresh argv.
const codexCandidates = process.platform === "darwin"
? rows.filter(row => row.executableName === "codex" && row.pgid !== undefined && row.pgid > 0 && row.pgid === row.tpgid)
: [];
if (codexCandidates.length > 0) {
// A failed or timed-out helper read loses argv evidence, not the process table.
// The foreground Codex still participates in delivery's uniqueness check.
const argumentsByPid = await readNativeProcessArguments(codexCandidates.map(row => row.pid)).catch(() => new Map<number, string[]>());
for (const row of codexCandidates) row.argv = argumentsByPid.get(row.pid) ?? null;
}
return rows;
} catch { return []; }
try { return await listNativeProcessesOrThrow(options); } catch { return []; }
}
/** The same listing, but a failed enumeration rejects instead of reading as an empty table. A caller that shares or
* reuses one listing needs this: an empty array is a legitimate success, so it cannot also mean "failed". */
export async function listNativeProcessesOrThrow(options: { claudeLaunchPaths?: boolean; frozenExecutable?: string } = {}): Promise<NativeProcessRow[]> {
// Copies: the table is shared with concurrent readers, and executable paths are added below.
const rows: NativeProcessRow[] = (await runAsyncSite("codex.runtime.list_processes", readProcessTable)).map((row) => ({ ...row }));
// `claudeLaunchPaths`: the caller is proving a launch through a `#!` script, which needs the OS path of the
// foreground path-named Claude too. `frozenExecutable`: the caller is proving a launch that froze that file (the
// installer's symlink resolved to its versioned file), which needs the path only of a path-named Claude whose
// argv[0] isn't already the file; an exact launch is proved without it, and a helper timeout can't change its
// fingerprint. Every other listing skips that read (on macOS it starts a helper process).
const candidates = rows.filter(row => needsClaudeExecutablePath(row) || (mayBeClaudeAfterScript(row) && (options.claudeLaunchPaths === true
|| (!!options.frozenExecutable && tokens(row.command)[0] !== options.frozenExecutable))));
if (candidates.length > 0) {
const paths = await readNativeExecutablePaths(candidates.map(row => row.pid));
for (const row of candidates) row.executablePath = paths.get(row.pid);
}
// Linux argv was captured with this same /proc table sample; never read real /proc
// again after a caller has selected a fixture or alternate process-table root.
// Only foreground rows can be selected below. Skip macOS helper reads for
// background Codex processes; every foreground seat still gets fresh argv.
const codexCandidates = process.platform === "darwin"
? rows.filter(row => row.executableName === "codex" && row.pgid !== undefined && row.pgid > 0 && row.pgid === row.tpgid)
: [];
if (codexCandidates.length > 0) {
// A failed or timed-out helper read loses argv evidence, not the process table.
// The foreground Codex still participates in delivery's uniqueness check.
const argumentsByPid = await readNativeProcessArguments(codexCandidates.map(row => row.pid)).catch(() => new Map<number, string[]>());
for (const row of codexCandidates) row.argv = argumentsByPid.get(row.pid) ?? null;
}
return rows;
}
export type NativeProcessLister = () => NativeProcessRow[] | Promise<NativeProcessRow[]>;
@@ -28,10 +28,18 @@ export interface NetworkBinding {
updatedAt: string;
lastContactAt: string | null;
lastError: string | null;
/** Set when the binding was made through an enrolled account: its installation (`neti-…`) and participant name. */
installationId: string | null;
participantName: string | null;
/** The account's own id for the installation the name was listed under. A replaced enrollment keeps the local id and
* moves to a new account installation, so only a list from this one can confirm the name was dropped. */
accountInstallationId: string | null;
/** When the account stopped listing this participant, after the binding ended here. */
accountRemovedAt: string | null;
}
export class NetworkBindingError extends Error {
constructor(readonly code: string, message: string, readonly status: 400 | 404 | 409 | 500 = 400) {
constructor(readonly code: string, message: string, readonly status: 400 | 401 | 404 | 409 | 500 | 502 | 503 = 400) {
super(message);
}
}
@@ -39,12 +47,15 @@ export class NetworkBindingError extends Error {
interface Row {
id: string; node_id: string; local_session: string; hub_url: string; hub_seat: string; allow_http: number; state: NetworkBindingState;
state_reason: string | null; created_at: string; updated_at: string; last_contact_at: string | null; last_error: string | null;
installation_id: string | null; participant_name: string | null; account_removed_at: string | null; account_installation_id: string | null;
}
const project = (row: Row): NetworkBinding => ({
id: row.id, nodeId: row.node_id, localSession: row.local_session, hubUrl: row.hub_url, hubSeat: row.hub_seat,
allowHttp: row.allow_http === 1, unencrypted: row.hub_url.startsWith("http:"), state: row.state, stateReason: row.state_reason, createdAt: row.created_at, updatedAt: row.updated_at,
lastContactAt: row.last_contact_at, lastError: row.last_error,
installationId: row.installation_id, participantName: row.participant_name, accountRemovedAt: row.account_removed_at,
accountInstallationId: row.account_installation_id,
});
const MAX_CREDENTIAL_BYTES = 16384;
@@ -58,10 +69,15 @@ export function networkCredentialFile(home: string, bindingId: string): string {
/** The participant's bearer, read from its private file. A file anyone else can read, a link or an oversized file is
* refused, with the path named and the value never shown. */
export function readNetworkCredential(home: string, bindingId: string): string {
const file = networkCredentialFile(home, bindingId);
return readPrivateToken(networkCredentialFile(home, bindingId),
(file) => `The credential for ${bindingId} isn't at ${file}. Connect the seat again with its token file.`);
}
/** A token from one of the network's private files (`{"version":1,"token":…}`), checked the same way for every kind. */
export function readPrivateToken(file: string, missing: (file: string) => string): string {
let stat;
try { stat = lstatSync(file); } catch {
throw new NetworkBindingError("credential_missing", `The credential for ${bindingId} isn't at ${file}. Connect the seat again with its token file.`, 404);
throw new NetworkBindingError("credential_missing", missing(file), 404);
}
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_CREDENTIAL_BYTES || (stat.mode & 0o077) !== 0) {
throw new NetworkBindingError("credential_unsafe", `${file} must be a regular file readable only by this user.`);
@@ -77,7 +93,29 @@ export function readNetworkCredential(home: string, bindingId: string): string {
return value.token;
}
function validHubUrl(raw: unknown, allowHttp: boolean): string {
/** Write a token to its own private file: a 0700 folder and a 0600 file, opened exclusively. On failure, only what
* this call made is removed: the file it opened, and the folder if it made it (`mkdirSync` returns the first folder it
* made, so any value means this one is new). Returns the cleanup for a later step that fails. */
export function writePrivateToken(file: string, token: string): () => void {
let created = false;
let madeFolder: string | undefined;
const cleanup = () => {
if (created) rmSync(file, { force: true });
if (madeFolder !== undefined) rmSync(dirname(file), { recursive: true, force: true });
};
try {
madeFolder = mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
const fd = openSync(file, "wx", 0o600);
created = true;
try { writeFileSync(fd, `${JSON.stringify({ version: 1, token })}\n`); } finally { closeSync(fd); }
} catch (error) {
cleanup();
throw error;
}
return cleanup;
}
export function validHubUrl(raw: unknown, allowHttp: boolean): string {
if (typeof raw !== "string" || !raw.trim()) throw new NetworkBindingError("invalid_hub_url", "A hub URL is required.");
let url: URL;
try { url = new URL(raw.trim()); } catch { throw new NetworkBindingError("invalid_hub_url", `'${raw}' isn't a URL.`); }
@@ -140,37 +178,39 @@ export class NetworkBindingStore {
/** Bind a local seat to a hub participant with that participant's token. The credential is written first, exclusively
* and private, then the row. If either step fails, the credential this call created is removed, so a refused bind
* leaves none behind; a file that was already at that path is never touched. */
create(input: { session: unknown; hubUrl: unknown; hubSeat: unknown; token: unknown; allowHttp?: unknown }): NetworkBinding {
const session = typeof input.session === "string" ? input.session.trim() : "";
/** The seat to bind, by its node: it must exist and have no active binding. Checked before anything is sent anywhere. */
freeSeat(rawSession: unknown): { session: string; nodeId: string } {
const session = typeof rawSession === "string" ? rawSession.trim() : "";
if (!session) throw new NetworkBindingError("invalid_seat", "Name the local seat to connect.");
const nodeId = resolveSessionNodeId(this.db, session);
if (!nodeId) throw new NetworkBindingError("seat_not_found", `No local seat is named '${session}'.`, 404);
const bound = this.db.prepare("SELECT id FROM network_bindings WHERE node_id = ? AND state = 'active'").get(nodeId) as { id: string } | undefined;
if (bound) throw new NetworkBindingError("seat_already_connected", `${session} is already connected (${bound.id}). Disconnect it first.`, 409);
return { session, nodeId };
}
create(input: { session: unknown; hubUrl: unknown; hubSeat: unknown; token: unknown; allowHttp?: unknown;
installation?: { id: string; name: string; account: string } }): NetworkBinding {
const { session, nodeId } = this.freeSeat(input.session);
const allowHttp = input.allowHttp === true;
const hubUrl = validHubUrl(input.hubUrl, allowHttp);
const hubSeat = validHubSeat(input.hubSeat);
const token = validToken(input.token);
const bound = this.db.prepare("SELECT id FROM network_bindings WHERE node_id = ? AND state = 'active'").get(nodeId) as { id: string } | undefined;
if (bound) throw new NetworkBindingError("seat_already_connected", `${session} is already connected (${bound.id}). Disconnect it first.`, 409);
const taken = this.db.prepare("SELECT id FROM network_bindings WHERE hub_url = ? AND hub_seat = ? AND state = 'active'").get(hubUrl, hubSeat) as { id: string } | undefined;
if (taken) throw new NetworkBindingError("participant_already_connected", `${hubSeat} at ${hubUrl} is already connected (${taken.id}).`, 409);
const id = this.newId();
const file = networkCredentialFile(this.home, id);
let created = false;
let madeFolder: string | undefined;
// The credential first, then the row; a failed row takes the credential with it. A file that was already at the path
// is never touched, and a folder that was already there keeps its other files.
const cleanup = writePrivateToken(networkCredentialFile(this.home, id), token);
try {
madeFolder = mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
const fd = openSync(file, "wx", 0o600);
created = true;
try { writeFileSync(fd, `${JSON.stringify({ version: 1, token })}\n`); } finally { closeSync(fd); }
const at = this.now().toISOString();
this.db.prepare(`INSERT INTO network_bindings (id, node_id, local_session, hub_url, hub_seat, allow_http, state, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, 'active', ?, ?)`).run(id, nodeId, session, hubUrl, hubSeat, allowHttp ? 1 : 0, at, at);
this.db.prepare(`INSERT INTO network_bindings (id, node_id, local_session, hub_url, hub_seat, allow_http, state, created_at, updated_at,
installation_id, participant_name, account_installation_id) VALUES (?, ?, ?, ?, ?, ?, 'active', ?, ?, ?, ?, ?)`)
.run(id, nodeId, session, hubUrl, hubSeat, allowHttp ? 1 : 0, at, at, input.installation?.id ?? null, input.installation?.name ?? null,
input.installation?.account ?? null);
} catch (error) {
// Only what this call made: the file it opened, and this binding's folder if it made it (`mkdirSync` returns the
// first folder it made, so any value means this one is new). A folder that was already there keeps its other files.
if (created) rmSync(file, { force: true });
if (madeFolder !== undefined) rmSync(dirname(file), { recursive: true, force: true });
cleanup();
throw error;
}
return this.get(id)!;
@@ -187,6 +227,18 @@ export class NetworkBindingStore {
return this.end(id, "revoked", reason);
}
/** Ends these active bindings' state only, so a caller can do it in one transaction with its own change. Their
* credentials stay until the caller ends each one again with `disconnect`, which removes them. */
markDisconnected(ids: string[], reason: string): void {
const end = this.db.prepare("UPDATE network_bindings SET state = 'disconnected', state_reason = ?, updated_at = ? WHERE id = ? AND state = 'active'");
for (const id of ids) end.run(reason, this.now().toISOString(), id);
}
/** The account stopped listing this ended binding's participant. */
markAccountRemoved(id: string): void {
this.db.prepare("UPDATE network_bindings SET account_removed_at = ?, updated_at = ? WHERE id = ?").run(this.now().toISOString(), this.now().toISOString(), id);
}
/** The connector reached the hub as this binding. */
recordContact(id: string, at: Date = this.now()): void {
this.db.prepare("UPDATE network_bindings SET last_contact_at = ?, last_error = NULL, updated_at = ? WHERE id = ?")
@@ -0,0 +1,378 @@
// This daemon enrolled in an account, so the person connects a seat by a name instead of a hub URL and a token file.
// Enrolling trades a one-time code from the account page for this installation's key. Connecting a seat lists the
// installation's participants with the account, which answers a bearer for a newly listed name, and the account's MCP
// front and rig, where the binding then reaches. A name the installation stops listing is revoked there.
//
// The account replaces the whole list on every change, so changes to one installation's list, and a replaced enrollment,
// run one at a time, each reading what it needs inside its turn. One enroll, connect or disconnect spends at most one
// deadline with the account, waiting for its turn included.
import type Database from "better-sqlite3";
import { randomBytes } from "node:crypto";
import { existsSync, renameSync, rmSync } from "node:fs";
import { join } from "node:path";
import { NetworkBindingError, readPrivateToken, writePrivateToken, type NetworkBinding, type NetworkBindingStore } from "./network-bindings.js";
export interface NetworkInstallation {
id: string;
site: string;
/** The account's id for this installation. */
installationId: string;
name: string | null;
allowHttp: boolean;
createdAt: string;
}
/** An enroll's answer. A replaced enrollment names the bindings it ended, whose names the old installation may still list,
* and any cleanup after the switch that didn't finish. */
export interface EnrollResult extends NetworkInstallation {
replaced?: { endedBindings: Array<{ id: string; localSession: string; participantName: string | null }>; problems?: string[] };
}
interface Row { id: string; site: string; installation_id: string; name: string | null; allow_http: number; created_at: string }
const project = (row: Row): NetworkInstallation => ({
id: row.id, site: row.site, installationId: row.installation_id, name: row.name, allowHttp: row.allow_http === 1, createdAt: row.created_at,
});
/** Where the installation key lives: `<home>/network-secrets/<installation>/key.json`, private to this user. */
export function networkInstallationKeyFile(home: string, id: string): string {
if (!/^neti-[0-9a-f]{20}$/.test(id)) throw new NetworkBindingError("invalid_installation_id", `'${id}' isn't a network installation id.`);
return join(home, "network-secrets", id, "key.json");
}
const NAME = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;
/** The state reason of a binding a replaced enrollment ended: its name belongs to the old installation. */
export const REPLACED_REASON = "replaced by a new enrollment";
/** What's known about the account's side of an ended binding made through it: confirmed dropped, unconfirmed (a removal
* that failed or whose answer was lost), or left with an earlier account installation after the enrollment was replaced,
* which this daemon's key can neither drop nor confirm. `accountInstallationNow` is the account's id for the binding's
* enrollment as it is now. */
export function accountRemoval(binding: NetworkBinding, accountInstallationNow: string | null | undefined): "confirmed" | "unconfirmed" | "old-installation" | null {
if (!binding.installationId || binding.state === "active") return null;
if (binding.accountRemovedAt) return "confirmed";
// The hub refused its credential, so nothing live is left there.
if (binding.state === "revoked") return null;
if (binding.accountInstallationId !== accountInstallationNow) return "old-installation";
return "unconfirmed";
}
/** The command's time with the account ran out before a call was sent. */
class NotSent extends NetworkBindingError {}
/** What the account answers for the installation's participant list. */
interface Identities { participants: Array<{ name: string; state?: string; bearer?: string }>; mcp: string; rig: string }
export type AccountFetch = (url: string, init: { method: string; headers: Record<string, string>; body: string; redirect: "error"; signal: AbortSignal })
=> Promise<{ status: number; json(): Promise<unknown> }>;
/** How long one enroll, connect or disconnect may spend with the account in all, waiting for its turn included. */
export const ACCOUNT_DEADLINE_MS = 30_000;
/** One change at a time to an installation's participant list, across the stores each request makes. */
const listTurns = new Map<string, Promise<void>>();
async function inListTurn<T>(installationId: string, run: () => Promise<T>): Promise<T> {
const before = listTurns.get(installationId) ?? Promise.resolve();
let release!: () => void;
const mine = new Promise<void>((resolve) => { release = resolve; });
const chain = before.then(() => mine);
listTurns.set(installationId, chain);
try {
await before;
return await run();
} finally {
release();
if (listTurns.get(installationId) === chain) listTurns.delete(installationId);
}
}
export class NetworkInstallationStore {
private readonly fetch: AccountFetch;
constructor(
private readonly db: Database.Database,
private readonly home: string,
private readonly opts: { fetch?: AccountFetch; selfHostId: () => string | null; now?: () => Date; newId?: () => string; timeoutMs?: number },
) {
this.fetch = opts.fetch ?? ((url, init) => fetch(url, init));
}
list(): NetworkInstallation[] {
return (this.db.prepare("SELECT * FROM network_installations ORDER BY created_at, id").all() as Row[]).map(project);
}
/** Trade the account page's one-time code for this installation's key. The code is checked by the account only, so a
* refused enroll here (a URL, a second enroll at the same site without `replace`) never spends it. With `replace`, the
* installation's turn comes first, so its wait counts against the same deadline: a wait that runs out sends no code,
* and the new key takes the old one's place only after the account accepted the new code. */
async enroll(bindings: NetworkBindingStore, input: { code: unknown; site: unknown; allowHttp?: unknown; replace?: unknown }): Promise<EnrollResult> {
const code = typeof input.code === "string" ? input.code.trim() : "";
if (!code || /\s/.test(code)) throw new NetworkBindingError("invalid_code", "Give the one-time code the account page shows.");
const site = validSite(input.site, input.allowHttp === true);
const existing = this.db.prepare("SELECT * FROM network_installations WHERE site = ?").get(site) as Row | undefined;
if (existing && input.replace !== true) {
throw new NetworkBindingError("already_enrolled", `This daemon is already enrolled at ${site} (${existing.id}). To enroll again with a new code, add --replace.`, 409);
}
const instance = this.instance();
const until = this.deadline();
const allowHttp = input.allowHttp === true ? 1 : 0;
if (existing) {
return inListTurn(existing.id, async () => {
const next = await this.exchange(site, code, instance, until);
return this.replace(bindings, this.get(existing.id), next.installation, next.key, allowHttp);
});
}
const { installation, key } = await this.exchange(site, code, instance, until);
const id = this.opts.newId?.() ?? `neti-${randomBytes(10).toString("hex")}`;
const cleanup = writePrivateToken(networkInstallationKeyFile(this.home, id), key);
try {
this.db.prepare("INSERT INTO network_installations (id, site, installation_id, name, allow_http, created_at) VALUES (?, ?, ?, ?, ?, ?)")
.run(id, site, installation.id, installation.name, allowHttp, (this.opts.now?.() ?? new Date()).toISOString());
} catch (error) {
cleanup();
throw error;
}
return this.get(id);
}
/** The code, with this daemon's host id, for an account installation and its key. */
private async exchange(site: string, code: string, instance: string, until: number): Promise<{ installation: { id: string; name: string | null }; key: string }> {
let answer;
try {
answer = await this.call(site, "POST", "/api/connector/enroll", null, { code, instance }, until);
} catch (error) {
if (error instanceof NotSent) throw new NetworkBindingError(error.code, `${error.message} The code wasn't sent, so it's still good while it's current: try again.`, 503);
if (error instanceof NetworkBindingError && error.code === "account_unavailable") {
throw new NetworkBindingError("account_unavailable", `${error.message} Whether the account took the code is unknown: try again with the same code, and if it's refused, get a new one.`, 503);
}
throw error;
}
if (answer.status !== 200) {
const error = errorCode(answer.body);
if (answer.status === 400 || answer.status === 409) {
throw new NetworkBindingError(error ?? "enroll_refused", `The account refused the code (${error ?? answer.status}). Get a new one from the account page; each is single-use and short-lived.`, answer.status);
}
throw new NetworkBindingError("account_unavailable", `The account couldn't answer (${answer.status}). If the code is still current, try again with it; otherwise get a new one.`, 503);
}
const body = (answer.body ?? {}) as { installation?: { id?: unknown; name?: unknown }; key?: unknown };
if (typeof body.installation?.id !== "string" || typeof body.key !== "string" || !body.key || /\s/.test(body.key)) {
throw new NetworkBindingError("account_unexpected", "The account's answer to the enroll had no installation or key.", 502);
}
return { installation: { id: body.installation.id, name: typeof body.installation.name === "string" ? body.installation.name : null }, key: body.key };
}
/** The new key goes in beside the old one and takes its place, then the row and the old installation's active bindings
* change in one transaction. A failure before that commits puts the old key back (with no old key, it removes the new
* one), so nothing here changes, though the account has already made the new installation and nothing here holds its
* key. After the commit the replace has happened: the ended bindings' names are returned, since the old installation
* may still list them and this key can't drop them, with any cleanup that didn't finish. */
private replace(bindings: NetworkBindingStore, old: NetworkInstallation, next: { id: string; name: string | null }, key: string, allowHttp: number): EnrollResult {
const file = networkInstallationKeyFile(this.home, old.id);
const staged = `${file}.next`;
const kept = `${file}.prev`;
const ending = bindings.active().filter((b) => b.installationId === old.id);
rmSync(staged, { force: true });
const cleanup = writePrivateToken(staged, key);
const hadKey = existsSync(file);
try {
if (hadKey) renameSync(file, kept);
renameSync(staged, file);
this.db.transaction(() => {
this.db.prepare("UPDATE network_installations SET installation_id = ?, name = ?, allow_http = ? WHERE id = ?").run(next.id, next.name, allowHttp, old.id);
bindings.markDisconnected(ending.map((b) => b.id), REPLACED_REASON);
})();
} catch (error) {
if (!hadKey) rmSync(file, { force: true });
else if (existsSync(kept)) renameSync(kept, file);
cleanup();
throw new NetworkBindingError("replace_failed",
`The account accepted the new code, but this daemon couldn't switch to it (${(error as Error).message.slice(0, 200)}), so nothing here changed. The account now has a new installation whose key nothing here holds: remove it on the account page, then enroll again with a new code.`, 500);
}
const problems: string[] = [];
try {
rmSync(kept, { force: true });
} catch (error) {
problems.push(`The earlier key's backup at ${kept} couldn't be removed (${(error as Error).message.slice(0, 200)}). It's no longer used; remove it by hand.`);
}
for (const binding of ending) {
// Already ended in the transaction; this removes its credential, and a failure says how to retry.
try { bindings.disconnect(binding.id, REPLACED_REASON); } catch (error) { problems.push((error as Error).message); }
}
return { ...this.get(old.id), replaced: { endedBindings: ending.map((b) => ({ id: b.id, localSession: b.localSession, participantName: b.participantName })),
...(problems.length ? { problems } : {}) } };
}
/** The one installation a name-only connect goes through. */
only(): NetworkInstallation {
const all = this.list();
if (all.length === 0) throw new NetworkBindingError("not_enrolled", "This daemon isn't enrolled in an account. Run rig network enroll <code> --site <site> first, or connect with --hub and --token-file.", 404);
if (all.length > 1) throw new NetworkBindingError("installation_ambiguous", "This daemon is enrolled at more than one site; connect with --hub and --token-file.", 409);
return all[0]!;
}
/** Connect a seat as a participant name: list it with the account, then bind to the account's MCP front with the new
* bearer. The seat is checked first, so a refusal here sends nothing. A name the account keeps without a bearer had
* its answer lost earlier: it's dropped and listed again for a fresh one. */
async connect(bindings: NetworkBindingStore, input: { session: unknown; name: unknown }): Promise<NetworkBinding> {
const installation = this.only();
bindings.freeSeat(input.session);
const name = typeof input.name === "string" ? input.name.trim() : "";
if (!NAME.test(name)) throw new NetworkBindingError("invalid_name", `'${name}' isn't a participant name: lowercase letters, digits and inner dashes, up to 32.`);
const until = this.deadline();
return inListTurn(installation.id, async () => {
// In this installation's turn: checked again, with the enrollment as it is now (a replace may have run while this
// waited), and every list sent reads the names to keep afresh.
const current = this.get(installation.id);
bindings.freeSeat(input.session);
if (this.listedNames(bindings, current).includes(name)) throw new NetworkBindingError("participant_already_connected", `${name} is already connected here.`, 409);
const others = () => this.listedNames(bindings, current).filter((n) => n !== name);
let answer = await this.setParticipants(bindings, current, () => [...others(), name], until);
let bearer = answer.participants.find((p) => p.name === name)?.bearer;
if (!bearer) {
await this.setParticipants(bindings, current, others, until);
answer = await this.setParticipants(bindings, current, () => [...others(), name], until);
bearer = answer.participants.find((p) => p.name === name)?.bearer;
if (!bearer) throw new NetworkBindingError("account_unexpected", `The account listed ${name} without a bearer, twice.`, 502);
}
try {
return bindings.create({ session: input.session, hubUrl: answer.mcp, hubSeat: `${name}@${answer.rig}`, token: bearer,
allowHttp: current.allowHttp, installation: { id: current.id, name, account: current.installationId } });
} catch (error) {
// Best effort: nothing here holds that bearer, so the account is asked to stop listing the name. If that fails,
// the error says so, whatever failed here; the account may still list it.
let unconfirmed = "";
try {
await this.setParticipants(bindings, current, others, until);
} catch (drop) {
unconfirmed = ` OpenRig couldn't confirm the account dropped ${name} again (${(drop as Error).message}); it may still list it.`;
}
if (!unconfirmed) throw error;
if (error instanceof NetworkBindingError) throw new NetworkBindingError(error.code, `${error.message}${unconfirmed}`, error.status);
throw new NetworkBindingError("binding_write_failed", `The binding couldn't be saved here (${(error as Error).message.slice(0, 200)}).${unconfirmed}`, 500);
}
});
}
/** After a binding made through the account ended here, the account stops listing its name, which revokes it there.
* Only an answered list that no longer has the name marks it removed; a failed or lost one leaves it unconfirmed. */
async removeAtAccount(bindings: NetworkBindingStore, binding: NetworkBinding): Promise<NetworkBinding> {
const installation = this.list().find((i) => i.id === binding.installationId);
if (!installation || accountRemoval(binding, installation.installationId) !== "unconfirmed") return binding;
const until = this.deadline();
return inListTurn(installation.id, async () => {
// A replace while this waited moved the enrollment to another account installation, which can't drop this name.
const current = this.get(installation.id);
if (accountRemoval(binding, current.installationId) !== "unconfirmed") return bindings.get(binding.id)!;
try {
await this.setParticipants(bindings, current, () => this.listedNames(bindings, current), until);
} catch (error) {
throw new NetworkBindingError("account_update_unconfirmed",
`${binding.id} is ${binding.state} here, but OpenRig couldn't confirm that the account dropped ${binding.participantName} (${(error as Error).message}). Run \`rig network disconnect ${binding.id}\` again.`, 502);
}
return bindings.get(binding.id)!;
});
}
/** `accountRemoval` against this binding's enrollment as it is now. */
removalOf(binding: NetworkBinding): ReturnType<typeof accountRemoval> {
const now = binding.installationId ? this.list().find((i) => i.id === binding.installationId) : undefined;
return accountRemoval(binding, now?.installationId);
}
private get(id: string): NetworkInstallation {
return project(this.db.prepare("SELECT * FROM network_installations WHERE id = ?").get(id) as Row);
}
private listedNames(bindings: NetworkBindingStore, installation: NetworkInstallation): string[] {
return bindings.active().filter((b) => b.installationId === installation.id && b.participantName).map((b) => b.participantName!);
}
private instance(): string {
const instance = this.opts.selfHostId();
if (!instance) throw new NetworkBindingError("instance_unknown", "This daemon hasn't resolved its host id yet. Try again once it's fully up.", 503);
return instance;
}
private deadline(): number {
return Date.now() + (this.opts.timeoutMs ?? ACCOUNT_DEADLINE_MS);
}
private async setParticipants(bindings: NetworkBindingStore, installation: NetworkInstallation, names: () => string[], until: number): Promise<Identities> {
const instance = this.instance();
const repair = `Get a new code from the account page and run rig network enroll <code> --site ${installation.site} --replace.`;
const key = readPrivateToken(networkInstallationKeyFile(this.home, installation.id),
(file) => `The installation key for ${installation.id} isn't at ${file}. ${repair}`);
const put = () => this.call(installation.site, "PUT", "/api/connector/identities", key, { instance, participants: names() }, until);
let answer = await put();
// The account couldn't apply a drop while something else changed this installation: the list is read and sent once more.
if (answer.status === 409 && errorCode(answer.body) === "drop_failed") answer = await put();
if (answer.status !== 200) {
const error = errorCode(answer.body);
if (answer.status === 409 && error === "drop_failed") {
throw new NetworkBindingError("account_busy", "The account was changing this installation's participants at the same time. Try again.", 503);
}
if (answer.status === 409) throw new NetworkBindingError(error ?? "name_taken", "Another connection to the account already uses that name. Choose another.", 409);
if (answer.status === 401) throw new NetworkBindingError(error ?? "not_enrolled", `The account doesn't recognize this installation any more. ${repair}`, 401);
if (answer.status === 400) throw new NetworkBindingError(error ?? "bad_names", "The account refused the participant names.", 400);
throw new NetworkBindingError("account_unavailable", `The account couldn't answer (${answer.status}). Try again.`, 503);
}
const body = (answer.body ?? {}) as Partial<Identities>;
if (!Array.isArray(body.participants) || typeof body.mcp !== "string" || typeof body.rig !== "string") {
throw new NetworkBindingError("account_unexpected", "The account's answer had no participants, MCP front or rig.", 502);
}
// The answer is what this account installation now lists: a binding that ended while listed under it, whose name
// isn't in the answer, is confirmed dropped. A name listed under an earlier installation is never confirmed here.
const listed = new Set(body.participants.map((p) => p.name));
for (const ended of bindings.list()) {
if (ended.installationId === installation.id && ended.participantName && !listed.has(ended.participantName)
&& accountRemoval(ended, installation.installationId) === "unconfirmed") {
bindings.markAccountRemoved(ended.id);
}
}
return body as Identities;
}
private async call(site: string, method: string, path: string, key: string | null, payload: unknown, until: number): Promise<{ status: number; body: unknown }> {
const left = until - Date.now();
if (left <= 0) throw new NotSent("account_unavailable", `The account at ${site} wasn't reached in time: this command's time with the account ran out.`, 503);
let res;
try {
// The key goes only to the site the person enrolled at: a redirect isn't followed with it, and a stalled call ends.
res = await this.fetch(new URL(path, site).toString(), {
method,
headers: { "Content-Type": "application/json", ...(key ? { Authorization: `Bearer ${key}` } : {}) },
body: JSON.stringify(payload),
redirect: "error",
signal: AbortSignal.timeout(left),
});
} catch (error) {
const cause = (error as { cause?: { message?: unknown } }).cause?.message;
if (typeof cause === "string" && /redirect/i.test(cause)) {
throw new NetworkBindingError("account_redirected", `The account at ${site} answered with a redirect, which isn't followed with the installation key. Use the site's own URL.`, 502);
}
throw new NetworkBindingError("account_unavailable", `The account at ${site} couldn't be reached: ${(error as Error).message.slice(0, 200)}.`, 503);
}
let body: unknown = null;
try { body = await res.json(); } catch { /* no JSON body */ }
return { status: res.status, body };
}
}
function errorCode(body: unknown): string | null {
const error = (body as { error?: unknown } | null)?.error;
return typeof error === "string" && /^[a-z][a-z0-9_]*$/.test(error) ? error : null;
}
/** The account's site: https, or plain http on the person's choice, with no credential in it. */
function validSite(raw: unknown, allowHttp: boolean): string {
if (typeof raw !== "string" || !raw.trim()) throw new NetworkBindingError("invalid_site", "Give the account's site URL with --site.");
let url: URL;
try { url = new URL(raw.trim()); } catch { throw new NetworkBindingError("invalid_site", `'${raw}' isn't a URL.`); }
if (url.protocol !== "https:" && url.protocol !== "http:") throw new NetworkBindingError("invalid_site", "The site must use https (or http).");
if (url.username || url.password) throw new NetworkBindingError("invalid_site", "The site URL can't hold a credential.");
if (url.protocol === "http:" && !allowHttp) {
throw new NetworkBindingError("http_not_allowed", `${url.origin} is plain http, so the installation key and every participant's token would cross the network unencrypted, where they can be read. Use the site's https URL, or enroll again with --allow-http to accept that.`);
}
return url.origin + "/";
}
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
import type Database from "better-sqlite3";
export const OPERATION_CONTRACT = "operation-correlation.v1";
export const OPERATION_KINDS = ["rig.create", "rig.import", "member.add"] as const;
export const OPERATION_KINDS = ["rig.create", "rig.import", "rig.materialize", "member.add"] as const;
type OperationKind = typeof OPERATION_KINDS[number];
type Row = { request_hash: string; rig_id: string | null; node_ids_json: string };
@@ -0,0 +1,99 @@
// One process listing shared by every agent checked in one observation pass.
//
// A poll that checks several agents one after another used to start its own process listing for each agent, and
// each agent's identity proof needs two listings (`verifyCodexPaneProcess`, `verifyPaneIdleShell`: the second
// must see a later table than the first). This pass lets agents share a listing only when each agent still gets
// what its own call sequence needs:
// - ORDER: an agent's next listing must START after the listing it last received had FINISHED, so its two
// samples are two observations, never one table read twice. A later agent may start from a listing an earlier
// agent already took, but its next listing must START after its own first check began: tables taken before
// that point cannot show a change that happened since.
// - FRESHNESS: a listing older than `freshnessMs` is never reused (the same limit ProcessCensus uses).
// - HONEST FAILURE: a failed listing is never reused and never counts as success. Each agent that was
// waiting on it falls back to its own read, and that read's failure is the agent's failure. "Failed" means
// the shared lister REJECTED: an empty array is a legitimate success and is never read as a failure, so the
// shared lister must reject on a failed enumeration (the lenient listers that return [] cannot be shared).
// - SCOPE: a pass belongs to one poll. The next poll builds a new pass, so it starts with a fresh listing.
// Listings are kept per underlying lister, because different listers return different rows.
const DEFAULT_FRESHNESS_MS = 2_000;
type Lister<Row> = () => Row[] | Promise<Row[]>;
interface Listing<Row> {
readonly startedSeq: number;
readonly startedAt: number;
doneSeq: number | null;
failed: boolean;
readonly rows: Promise<Row[]>;
}
export interface ObservationPassOpts {
freshnessMs?: number;
now?: () => number;
}
export class ObservationPass {
private readonly freshnessMs: number;
private readonly now: () => number;
private seq = 0;
private readonly listings = new Map<Lister<never>, Listing<never>[]>();
constructor(opts: ObservationPassOpts = {}) {
this.freshnessMs = opts.freshnessMs ?? DEFAULT_FRESHNESS_MS;
this.now = opts.now ?? Date.now;
}
/** A lister for ONE agent's checks in this pass. Create one per agent, never share it between agents: it
* remembers when its first check began and when its last listing finished. `base` is the shared listing and must reject when it fails;
* `fallback` is the agent's own read after a failed shared listing (default: `base`), so an agent keeps the
* failure behavior it has without a pass. */
lister<Row>(base: Lister<Row>, fallback: Lister<Row> = base): Lister<Row> {
let lastDoneSeq = 0;
let firstCallSeq: number | null = null;
return async () => {
const afterSeq = firstCallSeq === null ? 0 : Math.max(lastDoneSeq, firstCallSeq);
firstCallSeq ??= ++this.seq;
const listing = this.listingFor(base, afterSeq);
try {
const rows = await listing.rows;
lastDoneSeq = Math.max(lastDoneSeq, listing.doneSeq ?? ++this.seq);
return rows;
} catch {
// The shared listing failed: this agent reads for itself, and that read's own failure stands.
try {
return await fallback();
} finally {
lastDoneSeq = ++this.seq;
}
}
};
}
private listingFor<Row>(base: Lister<Row>, afterSeq: number): Listing<Row> {
const all = (this.listings.get(base as Lister<never>) ?? []) as Listing<Row>[];
const now = this.now();
const usable = [...all].reverse().find((l) => !l.failed && l.startedSeq > afterSeq && now - l.startedAt <= this.freshnessMs);
if (usable) return usable;
const listing: Listing<Row> = {
startedSeq: ++this.seq,
startedAt: now,
doneSeq: null,
failed: false,
rows: undefined as unknown as Promise<Row[]>,
};
(listing as { rows: Promise<Row[]> }).rows = new Promise<Row[]>((resolve) => resolve(base())).then(
(rows) => {
listing.doneSeq = ++this.seq;
return rows;
},
(err) => {
listing.failed = true;
listing.doneSeq = ++this.seq;
throw err;
},
);
this.listings.set(base as Lister<never>, [...all.filter((l) => !l.failed), listing] as Listing<never>[]);
return listing;
}
}
+20 -2
View File
@@ -5,6 +5,10 @@ import { lastMeaningfulTransition } from "./queue-waiting.js";
/** Common provenance on existing diagnostic queue rows, never a second ledger.
* Both deadline and delivery detectors consult the same recovery disposition. */
export const recoveryTag = (qitemId: string): string => `recovery-for:${qitemId}`;
/** #2988: a per-row stuck-sweep finding the sweep folded into a delegation parent's standing unclaimed-backlog notice. It
* was closed by that fold, not by anyone acting on the row, so it no longer owns the row: every recovery lookup skips
* it, and the row reads as one that never had a finding of its own (the notice now stands for it). */
export const BACKLOG_FOLDED_TAG = "stuck-sweep-folded-into-backlog";
function failedAttempt(db: Database.Database, qitemId: string): string | null {
// A typing-guard refusal (retained:) is newer evidence about the original
// obligation exactly like a failed nudge: a wake WAS offered after the
@@ -14,12 +18,25 @@ function failedAttempt(db: Database.Database, qitemId: string): string | null {
// the unclaimed baton's retry path.
return (db.prepare("SELECT last_nudge_attempt AS at FROM queue_items WHERE qitem_id = ? AND (last_nudge_result LIKE 'failed:%' OR last_nudge_result LIKE 'retained:%')").get(qitemId) as { at: string | null } | undefined)?.at ?? null;
}
export function recoveryId(db: Database.Database, qitemId: string, overdueDeadline?: string): string {
export function recoveryId(db: Database.Database, qitemId: string, overdueDeadline?: string, afterFolded?: string): string {
const evidence: unknown[] = [qitemId, lastMeaningfulTransition(db, qitemId)?.id ?? null, failedAttempt(db, qitemId)];
// Keep existing IDs byte-for-byte unless a newer deadline needs its own recovery episode.
if (overdueDeadline !== undefined) evidence.push(["overdue-claim", overdueDeadline]);
// A folded finding (#2988) took this row's id without owning it: a new finding is a new episode.
if (afterFolded !== undefined) evidence.push(["after-folded", afterFolded]);
return `qitem-recovery-${createHash("sha256").update(JSON.stringify(evidence)).digest("hex").slice(0, 16)}`;
}
/** The id a new recovery for this row's current episode takes: recoveryId, past every finding the stuck sweep folded into a
* backlog notice (#2988). A fold holds its id without owning the row, and the same episode can be folded more than once
* (the route to the parent comes and goes), so each folded id chains one level further until an id is free. Every level
* exists only as a row that was created and folded, so the chain ends. */
export function freshRecoveryId(db: Database.Database, qitemId: string, overdueDeadline?: string): string {
const folded = db.prepare(`SELECT 1 FROM queue_items WHERE qitem_id = ? AND json_valid(tags)
AND EXISTS (SELECT 1 FROM json_each(tags) WHERE value = ?)`);
let id = recoveryId(db, qitemId, overdueDeadline);
while (folded.get(id, BACKLOG_FOLDED_TAG)) id = recoveryId(db, qitemId, overdueDeadline, id);
return id;
}
/** Rows whose tag text could hold a recovery tag: valid JSON stores a string verbatim or with
* backslash escapes, so this superset loses no exact match. It repeats the first group of
* idx_queue_items_recovery_tags' WHERE clause (migration 099) byte for byte, which is what lets the
@@ -70,6 +87,7 @@ export function findQueueRecovery(db: Database.Database, qitemId: string, exclud
} else {
row = db.prepare(`SELECT qitem_id, state, ts_updated FROM queue_items
WHERE ${RECOVERY_TAG_ROWS} AND json_valid(tags) AND EXISTS (SELECT 1 FROM json_each(tags) WHERE value = ?)
AND NOT EXISTS (SELECT 1 FROM json_each(tags) WHERE value = '${BACKLOG_FOLDED_TAG}')
${excludeTag ? "AND NOT EXISTS (SELECT 1 FROM json_each(tags) WHERE value = ?)" : ""}
${RECOVERY_ORDER}`)
.get(...(excludeTag ? [tag, excludeTag] : [tag])) as { qitem_id: string; state: string; ts_updated: string } | undefined;
@@ -77,7 +95,7 @@ export function findQueueRecovery(db: Database.Database, qitemId: string, exclud
return settleRecovery(db, qitemId, row);
}
function pickFromIndex(byTag: Map<string, RecoveryRow[]>, qitemId: string, excludeTag?: string): RecoveryRow | undefined {
return (byTag.get(recoveryTag(qitemId)) ?? []).find((r) => !excludeTag || !r.values.has(excludeTag));
return (byTag.get(recoveryTag(qitemId)) ?? []).find((r) => !r.values.has(BACKLOG_FOLDED_TAG) && (!excludeTag || !r.values.has(excludeTag)));
}
/** The chosen recovery row still owns custody unless it is closed and the original obligation moved after it. */
function settleRecovery(db: Database.Database, qitemId: string, row: { qitem_id: string; state: string; ts_updated: string } | undefined): { qitemId: string; state: string } | null {
+78 -6
View File
@@ -589,8 +589,8 @@ export interface QueueClaimInput {
}
export interface QueueListOptions {
/** Exact tag selection before the result bound (used by diagnostic occurrences). */
tag?: string;
/** One legacy exact tag or repeated exact tags, all of which must match before the result bound. */
tag?: string | string[];
destinationSession?: string;
sourceSession?: string;
state?: QueueState | QueueState[];
@@ -610,6 +610,19 @@ export interface QueueListOptions {
sortByUpdated?: boolean;
}
/** Adds the exact, conjunctive tag predicates shared by the bounded list paths. */
function pushExactTagFilters(tag: string | string[] | undefined, conditions: string[], params: unknown[]): void {
if (tag === undefined) return;
const values = [...new Set(Array.isArray(tag) ? tag : [tag])];
if (values.some((value) => value.trim().length === 0)) {
throw new TypeError("tag filters cannot be blank");
}
for (const value of values) {
conditions.push("EXISTS (SELECT 1 FROM json_each(queue_items.tags) WHERE value = ?)");
params.push(value);
}
}
/** Adds the handoff-successor and updated-since filters both list paths share. */
function pushFollowThroughFilters(
opts: { handedOffFrom?: string; updatedSince?: string } | undefined,
@@ -2205,6 +2218,51 @@ export class QueueRepository {
.map((row) => ({ qitemId: row.qitem_id, body: row.body ?? "" }));
}
/** Every answer returned to this ask, oldest first, under getHumanAnswer's rule for whoever answered: an ask to a person
* (never an update), a row back to the asker linked by reply_to, from someone who may answer it (never a shared
* channel). An answer row carries the human-answer tag; the unnamed primary user's own is one. An untagged Slack reply
* (from before that tag) counts only when it came before the ask's first tagged answer (in this read's order) and no
* later than the ask's first close, even if it was reopened since, and only each person's first: after an answer or a
* close, a reply on the thread is correspondence. Each gives who, when,
* their words without the footer, the park it answered (null for the ask itself or an older Slack reply), and the
* identity recorded when the answer row was created. An ask answered in place (a runner's permission request, a host
* pairing request) has no answer row: its answer is on the ask. */
answersForAsk(askId: string): Array<{ qitemId: string; by: string; at: string; text: string; episode: string | null;
recordedIdentity: { provenance: string | null; principal: string | null } | null }> {
const ask = this.getById(askId);
if (!this.hasReplyToColumn || !ask || ask.humanIntent === "update" || !this.isPersonAddress(ask.destinationSession)) return [];
const candidates = (this.db.prepare(`SELECT qitem_id, source_session, ts_created,
EXISTS (SELECT 1 FROM json_each(queue_items.tags) WHERE value = 'human-answer') AS tagged
FROM queue_items
WHERE reply_to = ? AND destination_session = ?
AND (EXISTS (SELECT 1 FROM json_each(queue_items.tags) WHERE value = 'human-answer')
OR (qitem_id LIKE 'qitem-slack-inbound-%' AND COALESCE(summary, '') NOT LIKE '[Recovered after gap] %'))
ORDER BY ts_created, rowid`).all(askId, ask.sourceSession) as Array<{ qitem_id: string; source_session: string; ts_created: string; tagged: number }>)
.filter((row) => !this.isSharedChannel(row.source_session)
&& (this.answersAsk(ask, row.source_session) || (row.tagged === 1 && row.source_session === UNATTRIBUTED_ACTOR)));
const firstTagged = candidates.findIndex((row) => row.tagged === 1);
const history = this.transitionLog.listForQitem(askId);
// The ask's first close, whatever its state now: a reopen doesn't make later thread replies its answers.
const firstClose = history.find((transition) => !isBlockerLive(transition.state))?.ts;
const legacyFirst = new Set<string>();
const rows = candidates.filter((row, index) => row.tagged === 1 || ((firstTagged < 0 || index < firstTagged)
&& (!firstClose || row.ts_created <= firstClose) && !legacyFirst.has(row.source_session) && !!legacyFirst.add(row.source_session)));
if (rows.length === 0) return [];
// An answer to a park's question has the ID made from that park's episode, so the episode is read back from the ID.
const episodes = new Map(history
.filter((transition) => transition.ownerNotificationKind === "human-required")
.map((transition) => `${askId}:${transition.transitionId}`)
.map((key) => [humanAnswerId(askId, key), key] as const));
return rows.flatMap(({ qitem_id }) => {
const row = this.getById(qitem_id);
if (!row) return [];
const created = this.transitionLog.listForQitem(qitem_id)[0];
return [{ qitemId: row.qitemId, by: row.sourceSession, at: row.tsCreated, text: humanAnswerText(row.body),
episode: episodes.get(row.qitemId) ?? null,
recordedIdentity: created ? { provenance: created.identityProvenance, principal: created.identityPrincipal } : null }];
});
}
/** This person's answer to the current question of a decision parked on them, if one was returned. */
currentEpisodeAnswer(qitemId: string, actorSession: string): QueueItem | null {
const episode = this.currentHumanRequiredEpisode(qitemId);
@@ -4430,6 +4488,8 @@ export class QueueRepository {
clickedTs?: string }): RecordHumanAnswerResult {
if (!this.hasHumanQuestionsColumn) return { status: "not-applicable", reason: "schema" };
if (this.closeStaleRunnerPermission(input.qitemId)) return { status: "not-applicable", reason: "state-canceled" };
// Set inside the transaction when this click changed the answers (a declared type, so the closure's write is seen).
let changed = null as { summary: string | null; answered: number } | null;
const result = this.db.transaction((): RecordHumanAnswerResult => {
const item = this.getById(input.qitemId);
if (!item?.humanQuestions?.length) return { status: "not-applicable" as const, reason: "no-questions" };
@@ -4460,8 +4520,21 @@ export class QueueRepository {
const answers: HumanAnswers = { ...(item.humanAnswers ?? {}), [input.questionId]: input.optionId };
this.db.prepare("UPDATE queue_items SET human_answers = ? WHERE qitem_id = ?").run(JSON.stringify(answers), input.qitemId);
const complete = unansweredQuestions(item.humanQuestions, answers).length === 0;
if (item.humanAnswers?.[input.questionId] !== input.optionId) {
changed = { summary: item.summary ?? null, answered: item.humanQuestions.length - unansweredQuestions(item.humanQuestions, answers).length };
}
return { status: "recorded" as const, answers, complete, questions: item.humanQuestions };
})();
// The click is on the ask before anyone hears of it; a failed event never takes it back or holds up its return.
if (changed && result.status === "recorded") {
try {
this.eventBus.emit({ type: "queue.answer_recorded", qitemId: input.qitemId, actorSession: input.actorSession,
questionId: input.questionId, answered: changed.answered, questions: result.questions.length,
complete: result.complete, summary: changed.summary });
} catch (error) {
console.warn(`[queue] ${input.qitemId}'s recorded answer has no event`, error);
}
}
// A pending ask's interrupted close finishes here, as theirs; a park resumes with it through the reply resolver.
if (result.status === "not-applicable" && result.answeredBy) {
this.resolveDirectHumanReply({ qitemId: input.qitemId, actorSession: input.actorSession, decision: "", primaryUser: input.primaryUser });
@@ -4817,10 +4890,7 @@ export class QueueRepository {
const limit = opts?.limit ?? 100;
const conditions: string[] = [];
const params: unknown[] = [];
if (opts?.tag) {
conditions.push("EXISTS (SELECT 1 FROM json_each(queue_items.tags) WHERE value = ?)");
params.push(opts.tag);
}
pushExactTagFilters(opts?.tag, conditions, params);
if (opts?.rig) {
const escaped = opts.rig.replace(/%/g, "\\%").replace(/_/g, "\\_");
@@ -4967,6 +5037,7 @@ export class QueueRepository {
listAttention(opts?: {
limit?: number;
state?: QueueState | QueueState[];
tag?: string | string[];
destinationSession?: string;
sourceSession?: string;
targetRepo?: string;
@@ -5015,6 +5086,7 @@ export class QueueRepository {
];
if (this.hasHumanIntentColumn) conditions.push("COALESCE(human_intent, 'decision') <> 'update'");
const params: unknown[] = [...states];
pushExactTagFilters(opts?.tag, conditions, params);
if (opts?.destinationSession) {
const addresses = this.resolveSessionAddresses(opts.destinationSession);
conditions.push(`destination_session IN (${addresses.map(() => "?").join(",")})`);
@@ -116,6 +116,7 @@ export const PRUNABLE_EVENT_TYPES = [
"queue.claimed",
"queue.unclaimed",
"queue.handed_off",
"queue.answer_recorded",
// One delivery-evidence record per send, and one prompt observation per prompt hook; kept only as long as the other
// high-volume event types.
"transport.delivery_evidence",
+309 -50
View File
@@ -1,6 +1,7 @@
import { currentParkedOwnerNoInputFailure } from "./policies/parked-owner-consumer.js";
import { resolveEscalationOwner, ESCALATION_HOP_TAG, hasConsumedEscalationHop } from "./escalation-owner.js";
import { createRecoveryLookup, recoveryId, recoveryTag } from "./queue-recovery.js";
import { BACKLOG_FOLDED_TAG, createRecoveryLookup, findQueueRecovery, freshRecoveryId, recoveryTag } from "./queue-recovery.js";
export { BACKLOG_FOLDED_TAG };
import { quietHoldCustody } from "./quiet-hold-custody.js";
import { queueWaitNotice } from "./queue-wait-backoff.js";
import { lastMeaningfulTransition, pendingSince } from "./queue-waiting.js";
@@ -124,6 +125,40 @@ export function unclaimedBacklogTag(seat: string): string {
/** How many of a seat's unclaimed rows its standing notice lists by id; the rest are counted. */
export const UNCLAIMED_BACKLOG_LISTED_ROWS = 20;
/** #2988: the key of a notice sent to a seat's delegation parent is `<child seat>=><parent>`; a seat's own notice is keyed
* by the seat alone. */
const PARENT_BACKLOG_SEPARATOR = "=>";
/** Review of #3049: a polling member's notice the sweep filed to the one creator of every row it listed carries this
* prefix followed by that creator. Only this mark establishes that the notice shows that creator's rows alone; an old
* recipient the sweep doesn't recognize proves nothing (the operator setting may have changed). It names the creator
* rather than trusting the notice's destination: a queue handoff copies the tags to a successor elsewhere, and a
* fallback changes the destination in place. */
const BACKLOG_TO_CREATOR_PREFIX = "stuck-sweep-backlog-to-creator:";
const creatorMark = (creator: string): string => `${BACKLOG_TO_CREATOR_PREFIX}${creator}`;
/** The creator a notice's stored tags name in its mark, or null: no mark, more than one, or tags that don't read as a JSON
* array name none. */
function markedCreator(tags: string | null): string | null {
try {
const parsed: unknown = JSON.parse(tags ?? "[]");
if (!Array.isArray(parsed)) return null;
const marks = parsed.filter((t): t is string => typeof t === "string" && t.startsWith(BACKLOG_TO_CREATOR_PREFIX)
&& t.length > BACKLOG_TO_CREATOR_PREFIX.length);
return marks.length === 1 ? marks[0]!.slice(BACKLOG_TO_CREATOR_PREFIX.length) : null;
} catch {
return null;
}
}
/** Idempotency key of the standing unclaimed-backlog notice a delegation parent gets for one child seat's rows: one open
* notice per (parent, child). */
export function parentBacklogTag(parent: string, child: string): string {
return unclaimedBacklogTag(`${child}${PARENT_BACKLOG_SEPARATOR}${parent}`);
}
/** The seat a notice's key stands for and, for a notice sent to its delegation parent, that parent. */
function backlogKeyParts(key: string): { seat: string; parent: string | null } {
const at = key.indexOf(PARENT_BACKLOG_SEPARATOR);
return at < 0 ? { seat: key, parent: null } : { seat: key.slice(0, at), parent: key.slice(at + PARENT_BACKLOG_SEPARATOR.length) };
}
export interface StuckSweepStatusSnapshot {
lastSweepAt: string | null;
lastOutcome: "clean" | "findings" | "failed" | null;
@@ -617,6 +652,32 @@ function unclaimedBacklogText(seat: string, rows: BacklogRow[], thresholdMinutes
};
}
/** #2988: the standing notice a delegation parent gets for one child seat's unclaimed rows. It tells the parent about the
* child's backlog; it claims, moves and completes none of it. Built from the rows' fixed facts, as the seat's own notice
* is, so a pass rewrites it only when the rows change. */
function parentBacklogText(child: string, parent: string, rows: BacklogRow[], thresholdMinutes: number, routedHere: boolean): { summary: string; body: string } {
const { sorted, listed, count } = backlogListing(rows);
return {
summary: `Stuck sweep: unclaimed-backlog on ${child}, for its delegation parent ${parent} (${count})`,
body:
`STUCK SWEEP FINDING (unclaimed-backlog)\n` +
`parent: ${parent}\n` +
`child seat: ${child}\n` +
`unclaimed: ${count} (the threshold is ${thresholdMinutes} min)\n` +
`${listed.join("\n")}\n` +
`why: this is the backlog of ${child}, a seat ${parent} delegates to. Nobody has claimed these rows there, so ` +
`${parent} is told about them in this one notice instead of a finding per row. It follows the rows as they come and ` +
`go, and is rewritten in place without a new wake. This notice doesn't claim, move or complete any of them: they ` +
`stay with ${child} until someone claims, reroutes or closes them.\n` +
(routedHere ? "" : `note: ${child}'s rows no longer go to ${parent}. This notice keeps standing for them until the sweep ` +
`finds them stuck again and they go where ${child}'s rows go now.\n`) +
`List them: rig queue list --destination ${child} --state pending\n` +
`The sweep closes this notice itself once every row it stands for is claimed, parked or closed, or no longer goes ` +
`to ${parent}.\n` +
`${BACKLOG_ROWS_PREFIX}${JSON.stringify(sorted.map((r) => r.qitemId))}`,
};
}
/** A polling hosted member's standing notice: whether it's checking in (its own inbox reads), the rows it hasn't claimed,
* and what to do. Its work's age runs from each row's own time, which a check-in never resets. Built from the rows' fixed
* facts and the member's check-in state, never a current check-in's exact time, so a pass rewrites it only when the rows
@@ -719,7 +780,9 @@ export async function runStuckSweep(deps: StuckSweepDeps): Promise<StuckSweepRes
/** Each seat's agent-seat reading (agentSeatNode, below), dropped with the indexes: another writer can declare a
* seat's delegation parent while the pass yields or awaits a write. */
const agentSeats = new Map<string, { logicalId: string; rig: string } | null>();
const othersMayHaveRun = (): void => { othersRan++; recoveries.invalidate(); successors?.invalidate(); agentSeats.clear(); };
/** #2988: each seat's one declared delegation parent (parentNow, below), dropped with agentSeats. */
const parentsNow = new Map<string, string | null>();
const othersMayHaveRun = (): void => { othersRan++; recoveries.invalidate(); successors?.invalidate(); agentSeats.clear(); parentsNow.clear(); };
// A successor index whose build took at least half of a stretch that yielded by elapsed time is not rebuilt for
// the rest of the pass: the yield drops it, the next stretch would pay the build again and end the same way after a
// few rows, so the rows would pay about one build each instead of one per STUCK_SWEEP_YIELD_EVERY_ROWS. Those rows
@@ -751,6 +814,8 @@ export async function runStuckSweep(deps: StuckSweepDeps): Promise<StuckSweepRes
const ageMinutes = deps.unclaimedAgeMinutes ?? resolveStuckSweepUnclaimedAgeMinutes();
const routeNotes = new Map<string, string>();
const routed = new Set<string>();
/** #2988: the row's route was its seat's one declared delegation parent (resolveEscalationOwner outcome "parent"). */
const delegationParent = new Map<string, string>();
const resolveOrch = (session: string, row: QueueItem): string | null => {
if (hasConsumedEscalationHop(deps.db, row.qitemId)) {
routeNotes.set(row.qitemId, "escalates_to one-hop delivery already used; existing fallback retained");
@@ -760,6 +825,8 @@ export async function runStuckSweep(deps: StuckSweepDeps): Promise<StuckSweepRes
const route = resolveEscalationOwner(deps.db, session, target => deps.queueRepo.acceptsDestination(target));
if (route.outcome !== "none" && route.outcome !== "parent") routeNotes.set(row.qitemId, route.reason);
if (route.outcome === "routed") routed.add(row.qitemId);
if (route.outcome === "parent" && route.owner) delegationParent.set(row.qitemId, route.owner);
else delegationParent.delete(row.qitemId);
return route.owner;
};
const isRegisteredHost = deps.isRegisteredHost ?? defaultIsRegisteredHost(log);
@@ -1382,16 +1449,39 @@ export async function runStuckSweep(deps: StuckSweepDeps): Promise<StuckSweepRes
// declares (a delegation parent or escalates_to) takes them.
const polledUnclaimed = (c: Candidate): boolean => c.kind === "unclaimed-obligation" && c.noWake === true
&& !routeNotes.has(c.row.qitemId) && polledRow(c.row);
/** The standing notice a candidate belongs to (the seat or member it stands for), or null for a finding of its own. */
// #2988: an unclaimed row whose finding goes to its seat's one declared delegation parent (a live seat the re-routes
// left in place) shares one standing notice per (parent, child seat) instead of a finding per row, each waking the
// parent. A route the row's seat declares otherwise (escalates_to, a consumed hop, a re-route) keeps a finding per row.
const parentRoutedUnclaimed = (c: Candidate): boolean => c.kind === "unclaimed-obligation" && c.noWake !== true
&& c.route !== c.row.destinationSession && delegationParent.get(c.row.qitemId) === c.route
&& !routeNotes.has(c.row.qitemId) && !routed.has(c.row.qitemId);
/** The standing notice a candidate belongs to (the seat or member it stands for, or the parent and child seat), or null
* for a finding of its own. */
const backlogKeyOf = (c: Candidate): string | null =>
polledUnclaimed(c) ? c.row.destinationSession : selfRoutedUnclaimed(c) ? c.route : null;
polledUnclaimed(c) ? c.row.destinationSession : selfRoutedUnclaimed(c) ? c.route
: parentRoutedUnclaimed(c) ? `${c.row.destinationSession}${PARENT_BACKLOG_SEPARATOR}${c.route}` : null;
/** #2988's transition: an open per-row unclaimed finding the sweep filed to the parent before, for a row that now joins
* that parent's notice. It's folded in (closed, once the notice that takes its row is written) rather than kept
* beside the notice. Keyed by the row; the value is the per-row finding. */
const foldFrom = new Map<string, string>();
/** The per-row finding this candidate's row would fold into a parent's notice, or null. */
const foldable = (c: Candidate, shared: { qitemId: string; state: string } | null): string | null => {
// Only one nobody has taken up: a finding the parent claimed or parked is its work now, and stays as it is.
if (!shared || shared.state !== "pending" || !parentRoutedUnclaimed(c)) return null;
const finding = indexed(() => deps.queueRepo.getById(shared.qitemId, { waiting: false }));
return finding && isFindingRow(finding) && finding.state === "pending" && !finding.claimedAt
&& finding.destinationSession === c.route
&& (finding.tags ?? []).includes(findingDedupTag("unclaimed-obligation", c.row.qitemId)) ? finding.qitemId : null;
};
const unclaimedBacklog = new Map<string, Candidate[]>();
for (const c of [...new Map(candidates.map(c => [c.row.qitemId, c])).values()]) {
if (dueToYield()) await yieldLoop();
const dedupTag = findingDedupTag(c.kind, c.row.qitemId);
const shared = recoveries.find(c.row.qitemId);
const backlogKey = shared ? null : backlogKeyOf(c);
const fold = foldable(c, shared);
const backlogKey = shared && !fold ? null : backlogKeyOf(c);
if (backlogKey) {
if (fold) foldFrom.set(c.row.qitemId, fold); else foldFrom.delete(c.row.qitemId);
const rows = unclaimedBacklog.get(backlogKey);
if (rows) rows.push(c); else unclaimedBacklog.set(backlogKey, [c]);
continue;
@@ -1436,7 +1526,7 @@ export async function runStuckSweep(deps: StuckSweepDeps): Promise<StuckSweepRes
// The first term is implied by the second (its pattern starts with that literal); it lets
// the planner use idx_queue_items_recovery_tags (migration 099) instead of a full scan.
`SELECT qitem_id, source_session, state, ts_updated FROM queue_items
WHERE (tags LIKE '%"stuck-sweep:%') AND tags LIKE ?
WHERE (tags LIKE '%"stuck-sweep:%') AND tags LIKE ? AND tags NOT LIKE '%"${BACKLOG_FOLDED_TAG}"%'
ORDER BY CASE WHEN state IN ('pending', 'in-progress', 'blocked') THEN 0 ELSE 1 END,
ts_updated DESC, ts_created DESC, qitem_id DESC
LIMIT 1`,
@@ -1458,7 +1548,8 @@ export async function runStuckSweep(deps: StuckSweepDeps): Promise<StuckSweepRes
if (!now_) continue;
routeCandidate(now_); // its destination, reason and targets as they are now
const input = {
qitemId: recoveryId(deps.db, c.row.qitemId, renewedDeadline ? c.row.closureRequiredAt! : undefined),
// A finding folded into a parent's notice (#2988) holds its id without owning the row: a new one gets its own.
qitemId: freshRecoveryId(deps.db, c.row.qitemId, renewedDeadline ? c.row.closureRequiredAt! : undefined),
// The detector is machinery, not a seat: the obligation's own creator is the
// finding's source (the workflow-exception precedent).
sourceSession: c.row.sourceSession,
@@ -1477,6 +1568,11 @@ export async function runStuckSweep(deps: StuckSweepDeps): Promise<StuckSweepRes
try {
const created = await deps.queueRepo.create(input);
othersMayHaveRun();
// An existing row with this id, same source and destination, comes back as an idempotent retry: a closed one is
// no finding for the row now, so it's reported, never counted as created.
if (!["pending", "in-progress", "blocked"].includes(created.state)) {
throw new Error(`${created.qitemId} already exists and is ${created.state}`);
}
findings.push({ kind: c.kind, qitemId: c.row.qitemId, findingQitemId: created.qitemId, action: "created" });
} catch (err) {
const message = `${c.kind} finding for ${c.row.qitemId} to ${now_.route} not created: ${err instanceof Error ? err.message : String(err)}`;
@@ -1502,26 +1598,121 @@ export async function runStuckSweep(deps: StuckSweepDeps): Promise<StuckSweepRes
for (const tag of JSON.parse(tags) as string[]) if (tag.startsWith(backlogPrefix)) backlogSeats.add(tag.slice(backlogPrefix.length));
} catch { /* Skip malformed tags */ }
}
for (const seat of backlogSeats) {
/** #2988: the one declared delegation parent a seat's rows go to now, or null (none, several, another route, or a
* resolver the caller supplied, whose outcome isn't known). Read once per seat until other code may have run. */
const parentNow = (seat: string): string | null => {
if (deps.resolveOrchestrator) return null;
if (!parentsNow.has(seat)) {
const route = resolveEscalationOwner(deps.db, seat, target => deps.queueRepo.acceptsDestination(target));
parentsNow.set(seat, route.outcome === "parent" ? route.owner : null);
}
return parentsNow.get(seat)!;
};
/** #2988: the open notice with this key lists the row (one actually written: a create that failed leaves the row
* where it was). */
const openNoticeLists = (tag: string, id: string): boolean => {
const open = deps.db.prepare(`SELECT body FROM queue_items WHERE state IN ('pending', 'in-progress', 'blocked')
AND (tags LIKE '%"stuck-sweep:%') AND tags LIKE ? ESCAPE '\\' LIMIT 1`)
.get(`%"${tag.replace(/[\\%_]/g, (ch) => `\\${ch}`)}"%`) as { body: string } | undefined;
return open ? backlogRowsOf(open.body)?.has(id) === true : false;
};
/** #2988: an open notice to this seat's delegation parent lists the row. */
const parentNoticeStandsFor = (seat: string, id: string): boolean => {
const parent = parentNow(seat);
return parent ? openNoticeLists(parentBacklogTag(parent, seat), id) : false;
};
/** #2988: a row a parent's notice stands for no longer goes to that parent (another parent, none, or a used hop). The
* notice lets go of it only once something written stands for it where it goes now: the open notice it goes to lists
* it, or a closed one there holds it back this pass (a finding of its own lets go of it before this). Under a detection
* filter (a raised threshold, the wake ladder), or while that notice can't be written, nothing does, and the old notice
* keeps standing for it: a detection filter never reads as done. A pass files a seat's rows before it reads the notices no row goes to, so a
* row usually moves in one pass; at worst it is in both notices for one more. */
/** #2988: per notice key, the rows a closed notice held back this pass (below), so a notice a row leaves can tell. */
const heldBack = new Map<string, Set<string>>();
const coveredElsewhere = (seat: string, id: string): boolean => {
if (hasConsumedEscalationHop(deps.db, id)) return false;
const next = parentNow(seat);
const tag = next ? parentBacklogTag(next, seat) : unclaimedBacklogTag(seat);
// A closed notice there that holds the row back (dismissed by where it goes now) stands for it too.
return openNoticeLists(tag, id) || heldBack.get(tag)?.has(id) === true;
};
/** Closes the per-row findings a parent's notice now stands for (#2988's transition), once that notice is written. The
* rows and their findings were read before the pass yielded and awaited writes, so each fold rechecks, right before
* it writes and with nothing awaited in between, everything it rests on: the row still waits unclaimed at the
* seat, the seat's one declared delegation parent is still this parent (and the row's one hop unused), the
* finding is still the row's open recovery, nobody's taken it up, and the written notice is open and lists the
* row. Anything else, or anything it can't read, leaves the finding open and unmarked. */
const foldInto = async (noticeId: string, seat: string, parent: string, rowIds: string[]): Promise<void> => {
for (const id of rowIds) {
const findingId = foldFrom.get(id);
if (!findingId) continue;
foldFrom.delete(id);
if (dueToYield()) await yieldLoop();
const row = deps.queueRepo.getById(id, { waiting: false });
if (!row || row.state !== "pending" || row.claimedAt || row.destinationSession !== seat) continue;
if (deps.resolveOrchestrator || hasConsumedEscalationHop(deps.db, id)) continue;
// The whole rule that made the row's finding, on the row as it is now (a wake that failed meanwhile, a person's
// ask, a live ladder), not only its state.
if (!unclaimedCandidate(id, false)) continue;
const route = resolveEscalationOwner(deps.db, seat, target => deps.queueRepo.acceptsDestination(target));
if (route.outcome !== "parent" || route.owner !== parent) continue;
const finding = deps.db.prepare("SELECT state, claimed_at, destination_session FROM queue_items WHERE qitem_id = ?").get(findingId) as
{ state: string; claimed_at: string | null; destination_session: string } | undefined;
if (!finding || finding.state !== "pending" || finding.claimed_at || finding.destination_session !== parent) continue;
if (findQueueRecovery(deps.db, id)?.qitemId !== findingId) continue;
// The notice still reaches the parent: one that changed hands (a handoff, a fallback) isn't the parent's signal.
const notice = deps.db.prepare("SELECT state, body, destination_session FROM queue_items WHERE qitem_id = ?").get(noticeId) as
{ state: string; body: string; destination_session: string } | undefined;
if (!notice || !["pending", "in-progress", "blocked"].includes(notice.state) || notice.destination_session !== parent
|| backlogRowsOf(notice.body)?.has(id) !== true) continue;
try {
// The mark and the close together: a close that fails leaves the finding open and unmarked, as it was.
deps.db.transaction(() => {
deps.db.prepare(`UPDATE queue_items SET tags = json_insert(tags, '$[#]', ?) WHERE qitem_id = ? AND json_valid(tags)
AND NOT EXISTS (SELECT 1 FROM json_each(tags) WHERE value = ?)`).run(BACKLOG_FOLDED_TAG, findingId, BACKLOG_FOLDED_TAG);
deps.queueRepo.update({
qitemId: findingId,
actorSession: "stuck-sweep@system",
state: "done",
closureReason: "no-follow-on",
transitionNote: `stuck-sweep folded: unclaimed-obligation on ${id} into the standing unclaimed-backlog notice ${noticeId} for ${parent}, which now stands for this row`,
});
})();
findings.push({ kind: "unclaimed-obligation", qitemId: id, findingQitemId: findingId, action: "closed" });
} catch (err) {
const message = `unclaimed-obligation finding ${findingId} for ${id} not folded into ${noticeId}: ${err instanceof Error ? err.message : String(err)}`;
log(`[stuck-sweep] ${message}`);
failedCreates.push(message);
}
othersMayHaveRun();
}
};
for (const key of backlogSeats) {
if (dueToYield()) await yieldLoop();
const rows = unclaimedBacklog.get(seat) ?? [];
const tag = unclaimedBacklogTag(seat);
const rows = unclaimedBacklog.get(key) ?? [];
const { seat, parent } = backlogKeyParts(key);
const tag = parent ? parentBacklogTag(parent, seat) : unclaimedBacklogTag(seat);
liveDedupTags.add(tag);
const node = agentSeatNode(seat);
// A polling member's notice says whether it's checking in; an agent seat's names the route to add instead.
const polled = rows.length > 0 ? rows.some(polledUnclaimed) : pollsForWork(seat);
const backlogText = (standsFor: BacklogRow[]) => polled
? polledBacklogText(seat, standsFor, ageMinutes, deps.queueRepo.hostedMemberCheckIn(seat, now), now)
: unclaimedBacklogText(seat, standsFor, ageMinutes, node);
// A polling member's notice says whether it's checking in; an agent seat's names the route to add instead; a
// parent's says whose backlog it is.
const polled = !parent && (rows.length > 0 ? rows.some(polledUnclaimed) : pollsForWork(seat));
const backlogText = (standsFor: BacklogRow[]) => parent
? parentBacklogText(seat, parent, standsFor, ageMinutes, parentNow(seat) === parent)
: polled
? polledBacklogText(seat, standsFor, ageMinutes, deps.queueRepo.hostedMemberCheckIn(seat, now), now)
: unclaimedBacklogText(seat, standsFor, ageMinutes, node);
// A polling member's notice goes where its rows' findings went: the person, else their creator when they share one,
// else the operator agent. With none, it stays with the member, which reads it when it next checks.
// else the operator agent. With none, it stays with the member, which reads it when it next checks. A parent's
// notice goes to the parent.
const recipientFor = (creators: string[]): string => {
if (parent) return parent;
if (!polled) return seat;
const distinct = [...new Set(creators)];
return noWakeRecipient(seat, distinct.length === 1 ? distinct[0]! : null).seat ?? seat;
};
/** Files a notice and wakes its recipient; false when the create failed (reported in failedCreates). */
const fileNotice = async (text: { summary: string; body: string }, recipient: string): Promise<boolean> => {
/** Files a notice and wakes its recipient; its id, or null when the create failed (reported in failedCreates). */
const fileNotice = async (text: { summary: string; body: string }, recipient: string, creators: string[] = []): Promise<string | null> => {
try {
const created = await deps.queueRepo.create({
// A notice about a seat's own rows comes from that seat, as a restore notice does; OpenRig wakes its recipient.
@@ -1530,59 +1721,111 @@ export async function runStuckSweep(deps: StuckSweepDeps): Promise<StuckSweepRes
body: text.body,
summary: text.summary,
evidenceRef: `rig queue list --destination ${seat} --state pending`,
tags: [STUCK_SWEEP_FINDING_TAG, tag],
tags: [STUCK_SWEEP_FINDING_TAG, tag,
...(polled && recipient !== seat && creators.length > 0 && creators.every((c) => c === recipient)
? [creatorMark(recipient)] : [])],
wakeTrigger: "openrig" as const,
});
othersMayHaveRun();
findings.push({ kind: "unclaimed-backlog", qitemId: seat, findingQitemId: created.qitemId, action: "created" });
return true;
findings.push({ kind: "unclaimed-backlog", qitemId: key, findingQitemId: created.qitemId, action: "created" });
return created.qitemId;
} catch (err) {
const message = `unclaimed-backlog notice for ${seat} not created: ${err instanceof Error ? err.message : String(err)}`;
const message = `unclaimed-backlog notice for ${parent ? `${seat}, to its delegation parent ${parent},` : seat} not created: ${err instanceof Error ? err.message : String(err)}`;
othersMayHaveRun();
log(`[stuck-sweep] ${message}`);
failedCreates.push(message);
return false;
return null;
}
};
const last = deps.db
.prepare(
// The first term lets the planner use idx_queue_items_recovery_tags, as the finding lookup above does.
`SELECT qitem_id, state, ts_updated, summary, body, destination_session FROM queue_items
`SELECT qitem_id, state, ts_updated, summary, body, destination_session, tags FROM queue_items
WHERE (tags LIKE '%"stuck-sweep:%') AND tags LIKE ? ESCAPE '\\'
ORDER BY CASE WHEN state IN ('pending', 'in-progress', 'blocked') THEN 0 ELSE 1 END,
ts_updated DESC, ts_created DESC, qitem_id DESC
LIMIT 1`,
)
.get(`%"${tag.replace(/[\\%_]/g, (ch) => `\\${ch}`)}"%`) as
| { qitem_id: string; state: string; ts_updated: string; summary: string | null; body: string; destination_session: string }
| { qitem_id: string; state: string; ts_updated: string; summary: string | null; body: string; destination_session: string; tags: string | null }
| undefined;
if (last && ["pending", "in-progress", "blocked"].includes(last.state)) {
const listedNow = new Set(rows.map((c) => c.row.qitemId));
const stoodFor = backlogRowsOf(last.body);
const still = [...(stoodFor ?? [])].filter((id) => !listedNow.has(id)).flatMap((id): BacklogRow[] => {
// An unreadable list is rebuilt as every row still waiting unclaimed at the seat: all it could have stood for that
// nothing has resolved yet, and maybe more, never just the rows that qualify on this pass (review of #3049). From
// there the notice follows its rows as any other: it lets go of each one only as it's resolved or covered elsewhere.
// A member's notice the sweep marked as filed to the one creator of its rows only ever listed that creator's rows:
// the mark alone proves it, and it names that creator, whoever holds the notice now (any rewrite that brings in
// another creator's row drops it). Without the mark (an operator that is no longer recognized, an older notice,
// unreadable tags), it carries every unresolved row.
const readable = backlogRowsOf(last.body);
const onlyFrom = markedCreator(last.tags);
const stoodFor = readable ?? new Set((deps.db.prepare(`SELECT qitem_id FROM queue_items WHERE destination_session = ?
AND state = 'pending' AND claimed_at IS NULL AND (? IS NULL OR source_session = ?)
AND NOT (json_valid(tags) AND EXISTS (SELECT 1 FROM json_each(tags) WHERE value = ?))`)
.all(seat, onlyFrom, onlyFrom, STUCK_SWEEP_FINDING_TAG) as Array<{ qitem_id: string }>).map((r) => r.qitem_id));
// #2988: rows this notice lets go of only because something else stands for them now (a finding of their own,
// another parent's or the seat's own notice, or this pass's route for them). Nothing resolved them, so a notice the
// sweep closes doesn't hold them back: they leave its list before it closes.
const routedAway = new Set<string>();
// Read within the sweep's bounded yield (a rebuilt list can be long); a notice changed meanwhile is left for the next pass.
const still: BacklogRow[] = [];
let yielded = false;
for (const id of [...stoodFor].filter((x) => !listedNow.has(x))) {
if (dueToYield()) {
await yieldLoop();
yielded = true;
}
const row = indexed(() => deps.queueRepo.getById(id, { waiting: false }));
// Gone, someone else's now, resolved at its source, or held by a finding or recovery of its own: one actually
// written, so a create that failed this pass leaves the row here.
if (!row || row.destinationSession !== seat || recoveries.find(id)
|| deliveryResolutionEvidence(deps, "unclaimed-obligation", id, now)) return [];
return [{ qitemId: id, since: pendingSince(deps.db, id) ?? row.tsCreated, from: row.sourceSession, summary: row.summary }];
});
const standsFor = [...rows.map(backlogRow), ...still];
// With its list unreadable, the notice may still stand for rows: it's left as it is, never closed.
if (standsFor.length === 0 && !stoodFor) {
findings.push({ kind: "unclaimed-backlog", qitemId: seat, findingQitemId: last.qitem_id, action: "refreshed" });
continue;
// Gone, someone else's now, or resolved at its source.
if (!row || row.destinationSession !== seat || deliveryResolutionEvidence(deps, "unclaimed-obligation", id, now)) continue;
// Held by a finding or recovery of its own (one actually written, so a create that failed this pass leaves the row
// here): that finding holds it back from now on, a dismissed one too. The notice lets go of it rather than also
// holding it once closed: a fold into a parent's notice (#2988) can release that finding's custody, and the row
// must then be able to reach a notice again.
if (recoveries.find(id)) {
routedAway.add(id);
continue;
}
// A parent's notice lets go of a row whose seat's delegation parent is now another seat (or none), or whose one
// escalation hop is used; a seat's own notice, of a row its new parent's notice already stands for (#2988).
if (parent
? (parentNow(seat) !== parent || hasConsumedEscalationHop(deps.db, id)) && coveredElsewhere(seat, id)
: parentNoticeStandsFor(seat, id)) {
routedAway.add(id);
continue;
}
still.push({ qitemId: id, since: pendingSince(deps.db, id) ?? row.tsCreated, from: row.sourceSession, summary: row.summary });
}
if (yielded) {
const noticeNow = deps.db.prepare("SELECT state, body FROM queue_items WHERE qitem_id = ?").get(last.qitem_id) as { state: string; body: string } | undefined;
if (!noticeNow || !["pending", "in-progress", "blocked"].includes(noticeNow.state) || noticeNow.body !== last.body) {
findings.push({ kind: "unclaimed-backlog", qitemId: key, findingQitemId: last.qitem_id, action: "refreshed" });
continue;
}
}
const standsFor = [...rows.map(backlogRow), ...still];
if (standsFor.length === 0) {
if (routedAway.size > 0 || !readable) {
// Only the rows something resolved stay in the list the closed notice holds back. A notice whose list was
// unreadable never knew its rows, so it holds none back.
const kept = readable ? [...readable].filter((id) => !routedAway.has(id)) : [];
const body = last.body.split("\n").filter((l) => !l.startsWith(BACKLOG_ROWS_PREFIX)).join("\n")
+ `\n${BACKLOG_ROWS_PREFIX}${JSON.stringify(kept)}`;
deps.db.prepare("UPDATE queue_items SET body = ? WHERE qitem_id = ? AND body = ? AND state IN ('pending', 'in-progress', 'blocked')")
.run(body, last.qitem_id, last.body);
}
await deps.queueRepo.update({
qitemId: last.qitem_id,
actorSession: "stuck-sweep@system",
state: "done",
closureReason: "no-follow-on",
transitionNote: `stuck-sweep resolved: unclaimed-backlog on ${seat}: every row it stood for is claimed, parked, closed or has its own finding`,
transitionNote: parent
? `stuck-sweep resolved: unclaimed-backlog on ${seat} for ${parent}: every row it stood for is claimed, parked, closed, has its own finding or no longer goes to ${parent}`
: `stuck-sweep resolved: unclaimed-backlog on ${seat}: every row it stood for is claimed, parked, closed, has its own finding or is in its delegation parent's notice`,
});
othersMayHaveRun();
findings.push({ kind: "unclaimed-backlog", qitemId: seat, findingQitemId: last.qitem_id, action: "closed" });
findings.push({ kind: "unclaimed-backlog", qitemId: key, findingQitemId: last.qitem_id, action: "closed" });
continue;
}
// A notice that went to one of its rows' creators (no person reachable) shows that creator only rows it sent. When a
@@ -1593,7 +1836,7 @@ export async function runStuckSweep(deps: StuckSweepDeps): Promise<StuckSweepRes
if (polled && last.destination_session !== seat && !seesAnyRow(last.destination_session)
&& standsFor.some((r) => r.from !== last.destination_session)) {
const recipient = recipientFor(standsFor.map((r) => r.from));
if (!(await fileNotice(backlogText(standsFor), recipient))) continue;
if (!(await fileNotice(backlogText(standsFor), recipient, standsFor.map((r) => r.from)))) continue;
await deps.queueRepo.update({
qitemId: last.qitem_id,
actorSession: "stuck-sweep@system",
@@ -1602,15 +1845,23 @@ export async function runStuckSweep(deps: StuckSweepDeps): Promise<StuckSweepRes
transitionNote: `stuck-sweep re-filed: unclaimed-backlog on ${seat}: a row it stands for didn't come from ${last.destination_session}, the creator it went to; one notice for every row went to ${recipient}`,
});
othersMayHaveRun();
findings.push({ kind: "unclaimed-backlog", qitemId: seat, findingQitemId: last.qitem_id, action: "closed" });
findings.push({ kind: "unclaimed-backlog", qitemId: key, findingQitemId: last.qitem_id, action: "closed" });
continue;
}
const text = backlogText(standsFor);
if (text.summary !== last.summary || text.body !== last.body) {
deps.db.prepare("UPDATE queue_items SET body = ?, summary = ? WHERE qitem_id = ? AND body = ? AND summary IS ? AND state IN ('pending', 'in-progress', 'blocked')")
.run(text.body, text.summary, last.qitem_id, last.body, last.summary);
// A creator's notice that now stands for another creator's row (its recipient sees any row) is no longer creator-only.
if (onlyFrom !== null && standsFor.some((r) => r.from !== onlyFrom)) {
deps.db.prepare(`UPDATE queue_items SET tags = (SELECT json_group_array(value) FROM json_each(tags)
WHERE NOT (type = 'text' AND substr(value, 1, length(?)) = ?))
WHERE qitem_id = ? AND json_valid(tags)`).run(BACKLOG_TO_CREATOR_PREFIX, BACKLOG_TO_CREATOR_PREFIX, last.qitem_id);
}
findings.push({ kind: "unclaimed-backlog", qitemId: seat, findingQitemId: last.qitem_id, action: "refreshed" });
const text = backlogText(standsFor);
let written = text.summary === last.summary && text.body === last.body;
if (!written) {
written = deps.db.prepare("UPDATE queue_items SET body = ?, summary = ? WHERE qitem_id = ? AND body = ? AND summary IS ? AND state IN ('pending', 'in-progress', 'blocked')")
.run(text.body, text.summary, last.qitem_id, last.body, last.summary).changes === 1;
}
findings.push({ kind: "unclaimed-backlog", qitemId: key, findingQitemId: last.qitem_id, action: "refreshed" });
if (parent && written) await foldInto(last.qitem_id, seat, parent, standsFor.map((r) => r.qitemId));
continue;
}
if (rows.length === 0) continue;
@@ -1620,13 +1871,21 @@ export async function runStuckSweep(deps: StuckSweepDeps): Promise<StuckSweepRes
routed.delete(c.row.qitemId);
const now_ = freshCandidate(c.kind, c.row.qitemId);
if (now_) routeCandidate(now_);
return now_ && backlogKeyOf(now_) === seat && !recoveries.find(now_.row.qitemId) ? [now_] : [];
if (!now_ || backlogKeyOf(now_) !== key) return [];
// A row held by a recovery stays out, unless that recovery is the per-row finding this notice folds in.
const held = recoveries.find(now_.row.qitemId);
return !held || (parent && foldFrom.get(now_.row.qitemId) === held.qitemId) ? [now_] : [];
});
if (current.length === 0) continue;
// A closed notice whose list is unreadable holds back every row, each until it has newer evidence than the close.
const covered = last ? backlogRowsOf(last.body) : null;
if (last && !current.some((c) => (covered !== null && !covered.has(c.row.qitemId)) || evidenceIsNewer(c.evidenceAt, last.ts_updated))) continue;
await fileNotice(backlogText(current.map(backlogRow)), recipientFor(current.map((c) => c.row.sourceSession)));
if (last && !current.some((c) => (covered !== null && !covered.has(c.row.qitemId)) || evidenceIsNewer(c.evidenceAt, last.ts_updated))) {
heldBack.set(tag, new Set(current.map((c) => c.row.qitemId)));
continue;
}
const filed = await fileNotice(backlogText(current.map(backlogRow)), recipientFor(current.map((c) => c.row.sourceSession)),
current.map((c) => c.row.sourceSession));
if (filed && parent) await foldInto(filed, seat, parent, current.map((c) => c.row.qitemId));
}
// Resolution: an open finding whose underlying condition is no longer detected closes
@@ -17,8 +17,9 @@ export function askBackRoute(asked: string | null, unattributed: string, request
return `If their answer is unclear or conditional, ask them back with an ask to ${asked} that names ${request}: `
+ `rig queue create --destination ${asked} --summary "<your question>" --body-file <file>. It reaches them where they answer (the Feed, Steering, and Slack when it's connected). ${nowhere}`;
}
return `If their answer is unclear or conditional, OpenRig can't resolve a registered person to ask back about ${request}. `
+ `Say so once, in this conversation, and keep the request and their answer waiting. The ways through are registering a person (rig gateway human add) or the request's own decision command. ${nowhere}`;
return `If their answer is unclear or conditional, OpenRig can't resolve a registered person to ask back about ${request}: `
+ `nobody registered matches, or the person registry couldn't be read (rig gateway human list shows which). `
+ `Say so once, in this conversation, and keep the request and their answer waiting. The ways through are repairing an unreadable registry, registering a person (rig gateway human add), or the request's own decision command. ${nowhere}`;
}
/** What closing a runner's permission request without a decision does: a kept answer waits (runner-permissions). */
@@ -204,6 +204,12 @@ function blockStates(guidance: SeatGuidance, fs: Pick<ManagedBlockMergeFsOps, "e
return new Map(guidance.items.map((item) => [item.blockId, blockState(content, item.blockId)]));
}
/** #3039: the block ids the seat's guidance file doesn't hold at all (no marker of theirs), which a resumed launch can carry
* instead of the file. */
export function absentGuidanceBlocks(guidance: SeatGuidance, fs: Pick<ManagedBlockMergeFsOps, "exists" | "readFile">): string[] {
return [...blockStates(guidance, fs)].filter(([, state]) => state === "absent").map(([id]) => id);
}
/** The block ids the seat's guidance file lacks right now (absent, or only partly there). */
export function missingGuidanceBlocks(guidance: SeatGuidance, fs: Pick<ManagedBlockMergeFsOps, "exists" | "readFile">): string[] {
return [...blockStates(guidance, fs)].filter(([, state]) => state !== "complete").map(([id]) => id);
@@ -9,7 +9,7 @@ import { planModelAliasNotice } from "../adapters/yolo-mode.js";
import { effortPrecedence, readSeatEffort, type LaunchEffortSelection } from "./seat-effort.js";
import { accessSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
import { dirname, isAbsolute, join } from "node:path";
import { ensureSeatSkillPlugin, followSeatSkills, hasFollowingSeatSkills, hasSeatSkillRecords, rehydrateSeatSkills, seatSkillPaths, seatSkillPathsForNode, seatCatalogKeptNote, seatSkillReplay, writeSeatSkillCatalog, type SeatSkillRehydration, type SeatSkillSelection, writeSeatSkillRouter, seatRouterKeptNote } from "./seat-skill-storage.js";
import { SEAT_SKILLS_BOOTSTRAP_BLOCK_ID, ensureSeatSkillPlugin, followSeatSkills, hasFollowingSeatSkills, hasSeatSkillRecords, rehydrateSeatSkills, seatSkillPaths, seatSkillPathsForNode, seatCatalogKeptNote, seatSkillReplay, writeSeatSkillCatalog, type SeatSkillRehydration, type SeatSkillSelection, writeSeatSkillRouter, seatRouterKeptNote } from "./seat-skill-storage.js";
import type Database from "better-sqlite3";
import { NativePermissionStore } from "./native-permission-store.js";
import { readSeatClaudeMcp, type ClaudeMcp } from "./claude-mcp.js";
@@ -35,7 +35,7 @@ import { resumeProbeEvidence, type NativeResumeProbeEvidence } from "./native-re
import { observeClaudeDelivery, observeClaudeResumeLaunch, processArgv, verifyClaudePaneProcess, verifyClaudePaneRuntime, verifyPaneIdleShell, type ClaudeLaunchedProcess } from "./native-process-lineage.js";
import { readNativeExecutablePaths } from "./native-process-executable.js";
import { reanchorBuiltinStartupFile, reanchorShippedProjectionEntry, withContextEntryFloor } from "./builtin-startup-files.js";
import { applySeatSkillsLineRule, seatGuidance, restoreMissingGuidance, missingGuidanceBlocks, guidanceFileSharedByLink, lstatLinkInfo } from "./restore-guidance.js";
import { absentGuidanceBlocks, applySeatSkillsLineRule, seatGuidance, restoreMissingGuidance, missingGuidanceBlocks, guidanceFileSharedByLink, lstatLinkInfo } from "./restore-guidance.js";
import { decideManagedBlock, managedBlockRecords } from "./managed-block-records.js";
import type { DesiredClaudeActivityHooks } from "./desired-claude-activity-hooks.js";
import { readFootprintAnswer } from "./footprint-choice.js";
@@ -269,6 +269,9 @@ export interface RestoreOrchestratorDeps {
export class RestoreOrchestrator {
readonly db: Database.Database;
private activeRestores = new Set<string>();
/** #3039: per node, the guidance blocks its resumed launch carried, which the check after the launch doesn't look for in
* the repository file. */
private launchGuidanceBlocks = new Map<string, Set<string>>();
private rigRepo: RigRepository;
private sessionRegistry: SessionRegistry;
private eventBus: EventBus;
@@ -1548,6 +1551,17 @@ export class RestoreOrchestrator {
try { this.db.prepare("UPDATE node_startup_context SET guidance_file = ? WHERE node_id = ?").run(file, nodeId); } catch { /* no column */ }
}
/** #3039: whether this resume's launch carries the seat's guidance, by the adapter's own fresh-launch rule (a Codex
* conversation resume). Anything unanswered or unreadable keeps the repository path. */
private async resumeLaunchCarriesGuidance(adapter: import("./runtime-adapter.js").RuntimeAdapter | undefined,
binding: import("./runtime-adapter.js").NodeBinding): Promise<boolean> {
if (!adapter?.guidanceFileFor) return false;
try {
const answer = adapter.guidanceFileFor(binding, { resuming: true, resumingConversation: true });
return (answer instanceof Promise ? await answer : answer).launchInstructions === true;
} catch { return false; }
}
private checkRestoredGuidance(
result: RestoreNodeResult,
node: SnapshotData["nodes"][number],
@@ -1555,6 +1569,8 @@ export class RestoreOrchestrator {
data: SnapshotData,
warnings?: string[],
): RestoreNodeResult {
const launchCarried = this.launchGuidanceBlocks.get(node.id);
this.launchGuidanceBlocks.delete(node.id);
// Every status with a live session; attention_required keeps its status and gains the disclosure.
if (!["resumed", "fresh-primed", "fresh", "rebuilt", "attention_required"].includes(result.status)) return result;
let guidance: ReturnType<typeof seatGuidance>;
@@ -1581,7 +1597,9 @@ export class RestoreOrchestrator {
const noted = notes.length > 0 ? { ...result, guidanceNotes: notes } : result;
let missing: string[];
try {
missing = missingGuidanceBlocks(guidance, { exists: existsSync, readFile: (path) => readFileSync(path, "utf-8") });
// #3039: a block the resumed launch carried isn't looked for in the repository file; one it couldn't carry still is.
missing = missingGuidanceBlocks(guidance, { exists: existsSync, readFile: (path) => readFileSync(path, "utf-8") })
.filter((id) => !launchCarried?.has(id));
} catch (err) {
missing = [`(could not read ${guidance.targetPath}: ${(err as Error).message})`];
}
@@ -1829,6 +1847,18 @@ export class RestoreOrchestrator {
}
}
// #3039: a pod-aware resume whose saved choice is the repository file asks the adapter, as startup does, whether its
// launch carries the guidance (a Codex conversation resume, the fresh launch's rule). Then the saved guidance goes with
// the resume as developer instructions (the containment below lets only it through), and the repository AGENTS.md
// gets only #2456's refresh of blocks already there. A legacy resume starts its harness before startNode, so it can't.
let launchCarriesGuidance = false;
this.launchGuidanceBlocks.delete(node.id);
if (resumeRequested && resumeToken && launchResult && isPodAware && startupCtx && !startupCtx.guidanceFile) {
launchCarriesGuidance = await this.resumeLaunchCarriesGuidance(seatAdapter(opts?.adapters, startupCtx.runtime, session?.communityHarness),
{ ...launchResult.binding, guidanceFile: null, cwd: launchCwd, codexConfigProfile: this.liveCodexProfile(rigId, node, selected?.nodeId) ?? undefined });
}
let launchGuidance: import("./runtime-adapter.js").ResolvedStartupFile[] | null = null;
// A narrow exception to the replay containment below: before either native resume path
// starts the harness, put back only the MISSING managed guidance blocks from the saved
// startup selection. Ordinary `rig down` strips them; without this the resumed
@@ -1863,6 +1893,23 @@ export class RestoreOrchestrator {
warnings?.push(`Restore guidance: ${node.logicalId}: ${linked} is now a link, so nothing was put back in ${guidance.targetPath}, which other sessions could read.`);
guidance = null;
}
if (guidance && guidance.items.length > 0 && launchCarriesGuidance && startupCtx) {
// #3039: a block the file doesn't hold at all goes with the launch instead of being put back, when its source reads
// now (the writer's own read). Everything else stays with the writer below, as before: a block already there
// (refreshed or kept and named), a partial one, a source that's gone or can't be read (gaps), and the seat-skills
// line (the person's yes was for that file). So the launch's own placement writes nothing here: each block it gets is
// absent from the file. Each goes as an optional startup file, so a read that fails at the launch skips it rather
// than stopping the resume, and the check after the launch looks only past the blocks the launch reports it sent.
let absent = new Set<string>();
try { absent = new Set(absentGuidanceBlocks(guidance, { exists: existsSync, readFile: (path) => readFileSync(path, "utf-8") })); }
catch { /* unreadable: the writer below reports it */ }
const reads = (path: string): boolean => { try { readFileSync(path, "utf-8"); return true; } catch { return false; } };
const carried = guidance.items.filter((item) => absent.has(item.blockId) && !item.unresolved
&& item.blockId !== SEAT_SKILLS_BOOTSTRAP_BLOCK_ID && reads(item.sourcePath));
launchGuidance = carried.map((item) => ({ path: item.blockId, absolutePath: item.sourcePath, ownerRoot: dirname(item.sourcePath),
deliveryHint: "guidance_merge" as const, required: false, appliesOn: ["fresh_start" as const, "restore" as const] }));
guidance = { ...guidance, items: guidance.items.filter((item) => !carried.includes(item)) };
}
if (guidance && guidance.items.length > 0) {
// #2456: a block OpenRig wrote whose source changed since is refreshed too; an edited one, or one with no record, is
// left as it is and named (the check after the launch carries the names onto the seat's result).
@@ -1992,7 +2039,8 @@ export class RestoreOrchestrator {
// launches are new histories and keep their replay.
// One narrow exception: MISSING managed guidance blocks are put back before the harness
// starts (see restoreMissingGuidance above); existing blocks are still never rewritten, and
// nothing else is replayed.
// nothing else is replayed. #3039: when the resumed launch carries the guidance instead, only that
// saved guidance passes, as optional startup files (launchGuidance): no action, skill or other resource.
const replayContained = resumeRequested && !!resumeToken;
const startupRuntime = startupCtx?.runtime ?? node.runtime ?? null;
const startupAdapter = seatAdapter(opts?.adapters, startupRuntime, session?.communityHarness);
@@ -2066,7 +2114,7 @@ export class RestoreOrchestrator {
const existsFn = opts.fsOps?.exists ?? (() => true);
const sourceEntries = replayContained && !restoreEnvironmentContext ? [] : startupCtx.projectionEntries.map((e) => reanchorShippedProjectionEntry(e, undefined, existsFn));
// #261: recognized built-in startup files follow the running install.
const sourceFiles = replayContained && !restoreEnvironmentContext ? [] : withContextEntryFloor(startupCtx.resolvedStartupFiles.map((f) => reanchorBuiltinStartupFile(f, undefined, undefined, existsFn)));
const sourceFiles = replayContained && !restoreEnvironmentContext ? launchGuidance ?? [] : withContextEntryFloor(startupCtx.resolvedStartupFiles.map((f) => reanchorBuiltinStartupFile(f, undefined, undefined, existsFn)));
const sourceActions = replayContained ? [] : startupCtx.startupActions;
const filteredEntries = sourceEntries.filter((e) => {
if (!existsFn(e.absolutePath)) {
@@ -2134,6 +2182,8 @@ export class RestoreOrchestrator {
...launchResult.binding,
// #875: the guidance file this seat's launch recorded; an older snapshot recorded none, so its file stays the rule's.
guidanceFile: startupCtx.guidanceFile ?? null,
// #3039: the resumed launch carries the guidance chosen above, so startup doesn't ask again and the adapter queues it.
...(launchGuidance ? { guidanceLaunchInstructions: true as const } : {}),
...(data.environmentBindingsByNode?.[node.id] ? { environmentRestore: data.environmentBindingsByNode[node.id] } : {}),
...(opts?.claudeExecutable ? { claudeExecutable: opts.claudeExecutable } : {}),
...(opts?.claudeLaunch ? { claudeLaunch: opts.claudeLaunch } : {}),
@@ -2179,6 +2229,11 @@ export class RestoreOrchestrator {
...(selected ? { beforeNativeLaunch: () => selected.beforeNative(launchResult.session.id, launchResult.binding.id) } : {}),
});
warnings?.push(...(startupResult.warnings ?? []));
// #3039: the blocks the resumed launch actually sent, by the adapter's own record, are the ones the check after the
// launch doesn't look for in the repository file.
const carriedIds = new Set((launchGuidance ?? []).map((f) => f.path));
const sentGuidance = carriedIds.size > 0 && launchResult.binding.tmuxSession ? adapter.launchGuidanceSent?.(launchResult.binding.tmuxSession) : undefined;
if (sentGuidance?.length) this.launchGuidanceBlocks.set(node.id, new Set(sentGuidance.filter((id) => carriedIds.has(id))));
if (startupResult.ok) {
const nativeContinuityProved = isPodAware
&& resumeRequested
@@ -112,7 +112,8 @@ export function validatePreRestore(
// nothing, skip; usable type + token => exact resume, skip; a token
// WITHOUT a usable resume type follows the current fresh path,
// validate.
const resolution = resolveActiveSnapshotSession(data, node.id);
// A missing sessions list is already a blocker above; read it as empty here rather than throw.
const resolution = resolveActiveSnapshotSession({ ...data, sessions: sessions ?? [] }, node.id);
const freshListed = opts.freshLogicalIds?.includes(node.logicalId) ?? false;
let consumesReplay: boolean;
if (resolution.kind === "ambiguous") {
@@ -552,7 +552,7 @@ export class PodRigInstantiator {
async materialize(
rigSpecYaml: string,
rigRoot: string,
opts?: { targetRigId?: string; suppressSummaryEvent?: boolean; cwdOverride?: string },
opts?: { targetRigId?: string; suppressSummaryEvent?: boolean; cwdOverride?: string; recordCreated?: RecordCreated },
): Promise<MaterializeOutcome> {
let raw: unknown;
try {
@@ -698,9 +698,9 @@ export class PodRigInstantiator {
if (!materializedRigId) {
const rig = this.deps.rigRepo.createRig(rigSpec.name);
materializedRigId = rig.id;
opts?.recordCreated?.(rig.id);
persistedEvents.push(this.deps.eventBus.persistWithinTransaction({ type: "rig.created", rigId: materializedRigId }));
}
opts?.recordCreated?.(materializedRigId);
// PL-007: persist the rig's typed workspace block when declared.
if (rigSpec.workspace) {
+2 -1
View File
@@ -27,7 +27,8 @@ export interface RosterMember extends Reference {
/** A hosted member's trigger, rung when a row lands for it. */
wake?: RosterWake;
/** How often a hosted member is expected to check its queue, in minutes, as its person set it up (an hourly schedule
* is 60). Stated, not observed: absent means it checks only when a person prompts it. */
* is 60). Stated, not observed. Absent implies neither a schedule nor on request: without `check_in_on_request`
* either, the member's check-in status reads unknown. */
check_in_minutes?: number;
/** Its person set it to check in when asked, not on a schedule. */
check_in_on_request?: true;
+14 -2
View File
@@ -131,7 +131,13 @@ export function isAttentionRequiredReadinessCode(code: string | undefined): bool
/** `resumeRotation`: the rotation recorded with `resumeToken` (#1077), as `rig seat clear-attention` passes it, so a
* seat whose Claude continued its conversation under a new id is proved by the process that recorded the rotation. */
export interface ReadinessOptions { resumeToken?: string | null; resumeRotation?: ClaudeResumeRotation | null }
export interface ReadinessOptions {
resumeToken?: string | null;
resumeRotation?: ClaudeResumeRotation | null;
/** The poll this check belongs to. An adapter that honours it takes its process listings from the pass, so the
* agents checked in one poll share them; an adapter that doesn't reads for itself, as before. */
observationPass?: import("./process-observation-pass.js").ObservationPass;
}
// -- Harness launch result --
@@ -248,7 +254,13 @@ export interface RuntimeAdapter {
skillTargetPath?(tmuxSession: string | null, effectiveId: string): string | null;
/** #875: where this seat's managed guidance should go, decided at a fresh launch and recorded with its startup context.
* Absent, or a null file, keeps the rule's file in the working directory; a note says why the seat's own file wasn't used. */
guidanceFileFor?(binding: NodeBinding, opts?: { resuming?: boolean }): GuidanceChoice | Promise<GuidanceChoice>;
/** `resuming`: a resume, fork or startup continuation. `resumingConversation`: of those, a resume of the seat's own
* conversation (a restore or `rig up --existing`), which launches and can carry guidance as a fresh launch does. */
guidanceFileFor?(binding: NodeBinding, opts?: { resuming?: boolean; resumingConversation?: boolean }): GuidanceChoice | Promise<GuidanceChoice>;
/** #3039: the guidance block ids the last launch in this tmux session sent as developer instructions, once (the record is
* cleared when read, and when a later projection carries guidance). Undefined when that launch sent none or the adapter doesn't carry any. */
launchGuidanceSent?(tmuxSession: string): string[] | undefined;
/** List currently installed/projected resources for a node. */
listInstalled(binding: NodeBinding): Promise<InstalledResource[]>;
@@ -1,3 +1,4 @@
import { inputReadDiagnostic, type InputReadDiagnostic } from "./input-read-diagnostic.js";
import { hasOtherSeatHistory, isStoppedSeatPredecessor, resolveCurrentSessionAddress } from "./session-registry.js";
import { AsyncLocalStorage } from "node:async_hooks";
import { randomUUID } from "node:crypto";
@@ -28,7 +29,7 @@ interface Lease {
}
export class DeliveryGuardError extends Error {
constructor(readonly code: string, message: string) { super(message); }
constructor(readonly code: string, message: string, readonly inputReadFailure?: InputReadDiagnostic) { super(message); }
// Hono's error protocol also preserves this typed refusal on lifecycle routes.
getResponse(): Response {
@@ -440,14 +441,14 @@ export class SeatDeliveryGuard {
this.checkInput(name);
return observed;
};
const unknown = () => new DeliveryGuardError("draft_input_unknown", "The current input cannot be read. Automatic delivery is held.");
const unknown = (reading: ComposerInput | null) => new DeliveryGuardError("draft_input_unknown", "The current input cannot be read. Automatic delivery is held.", inputReadDiagnostic("draft-aware", reading));
let input = await read();
// Claude may still be redrawing this lease's own paste: one bounded re-read before refusing its Enter.
if (submit && lease.staged && (!input || input.state === "unknown")) { await this.sleep(OWN_INPUT_REREAD_MS); input = await read(); }
if (!input || input.state === "unknown") {
// No Enter was sent, so the paste stays there unsubmitted, and the next delivery may recognize it as OpenRig's.
if (submit && lease.staged) this.leftovers.set(target.nodeId, { target: lease.target, humanEpoch: lease.humanEpoch, ...lease.staged });
throw unknown();
throw unknown(input);
}
if (leftover === "recognize" && !submit && this.ownsLeftover(target, input)) { lease.ownLeftover = "recognized"; return; }
if (typeof leftover === "object" && lease.ownLeftover === "recognized") {
@@ -466,7 +467,7 @@ export class SeatDeliveryGuard {
lease.ownLeftover = "submitted";
await this.sleep(OWN_INPUT_REREAD_MS);
const after = await read();
if (!after || after.state === "unknown") throw unknown();
if (!after || after.state === "unknown") throw unknown(after);
input = after;
}
}
@@ -489,7 +490,7 @@ export class SeatDeliveryGuard {
: uncertainty === "long"
? "OpenRig couldn't confirm ownership of Codex's collapsed long paste. Send a shorter message; nothing was pasted. Turning this seat's typing guard off explicitly disables draft protection."
: "OpenRig couldn't confirm the complete message would stay visible in this Codex viewport. Open a larger terminal or shorten the message, then retry this request; nothing was pasted.";
throw new DeliveryGuardError("draft_input_unknown", message);
throw new DeliveryGuardError("draft_input_unknown", message, inputReadDiagnostic("draft-aware", input, `paste_${uncertainty}`));
}
lease.inputFrame = input.frame;
}
@@ -19,6 +19,7 @@ import { SeatHandoverPlanner, parseHandoverSource, SEAT_HANDOVER_SOURCE_CAPABILI
import { discoverResumeToken } from "./agent-images/resume-token-discovery.js";
import { resolveRebuildArtifacts } from "./session-source-rebuild-resolver.js";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { basename, dirname, isAbsolute, sep } from "node:path";
import { keptGuidanceSeatLine, lstatLinkInfo, putBackSeatGuidance, readNodeStartupSnapshot, seatStartupTextFiles, type SeatStartupTextFile } from "./restore-guidance.js";
import { managedBlockRecords } from "./managed-block-records.js";
import { readFootprintAnswer } from "./footprint-choice.js";
@@ -1075,9 +1076,24 @@ export class SeatHandoverService {
lines.push("", "Priming artifacts (read each, in order):");
for (const artifact of required) lines.push(`- ${artifact.address} — ${artifact.label}`);
}
if (history.length > 0) {
const newest = history[0];
if (newest) {
lines.push("", "Older recaps, newest first (read these only if you need the seat's history):");
for (const artifact of history) lines.push(`- ${artifact.address} — ${artifact.label}`);
const settings = new SettingsStore();
let limit: number;
try {
limit = Number(settings.resolveOne("output.rebuild_recaps").value);
} catch {
// Optional presentation settings must not interrupt successor delivery.
limit = 3;
}
const folder = dirname(newest.address);
// A folder pointer replaces paths only when it covers EVERY optional artifact.
// Custom resolvers with other layouts retain their complete explicit list.
const bounded = limit > 0 && history.length > limit && basename(folder) === "recap-superseded"
&& history.every((artifact) => isAbsolute(artifact.address) && dirname(artifact.address) === folder);
for (const artifact of bounded ? history.slice(0, limit) : history) lines.push(`- ${artifact.address} — ${artifact.label}`);
if (bounded) lines.push(`All ${history.length} older recaps: ${folder}${sep} (optional history; list this folder for the rest).`);
}
if (info.gaps.length > 0) {
lines.push("", "Declared but MISSING on disk (known gaps, named so nothing is silently dropped):");
@@ -1,3 +1,4 @@
import { inputReadDiagnostic, type InputReadDiagnostic } from "./input-read-diagnostic.js";
import { expectedConversation, sameConversation, resolveExpectedConversation, type ExpectedConversation } from "./expected-conversation.js";
import type { ContextUsageStore } from "./context-usage-store.js";
import { physicalSessionName } from "./session-registry.js";
@@ -2176,6 +2177,7 @@ export interface SendResult {
heldInputBox?: InputBoxAnnotation["status"];
/** The existing preserve-input reading, without the draft or suggestion text. No extra capture. */
heldInputBoxReading?: Pick<InputBoxAnnotation, "status" | "confidence" | "evidence" | "cursor">;
inputReadFailure?: InputReadDiagnostic;
}
/** One reading of a Claude Code or Codex input box: `exact` (the sent text, word boundaries kept), `ambiguous`
@@ -2823,6 +2825,7 @@ export class SessionTransport {
sent: written ? true : attempted ? undefined : false,
inputPhase: written ? "written" : attempted ? "attempted" : "not_reached",
reason: (error as { code?: string }).code ?? "expected_identity_unavailable", error: (error as Error).message,
...(error instanceof DeliveryGuardError && error.inputReadFailure ? { inputReadFailure: error.inputReadFailure } : {}),
...(receiptUnconfirmed ? { warning: "Conditional input receipt could not be finalized; inspect before retrying." } : {}) };
}
}
@@ -2944,17 +2947,20 @@ export class SessionTransport {
if ((error as { inputWritten?: boolean }).inputWritten === true) {
// Only a throw before the Enter key reached the adapter positively means Enter was never sent.
const enter = (error as { enterAttempted?: boolean }).enterAttempted === true ? "the submission (Enter) outcome is unconfirmed" : "Enter was not sent";
return { ok: false, sessionName, sent: true, outcome: "failed", inputPhase: "written", reason: (error as { code?: string }).code ?? "submit_refused",
return { ok: false, sessionName, sent: true, outcome: "failed", inputPhase: "written",
...(error instanceof DeliveryGuardError && error.inputReadFailure ? { inputReadFailure: error.inputReadFailure } : {}), reason: (error as { code?: string }).code ?? "submit_refused",
error: `Text was written to '${sessionName}' but ${enter}: ${(error as Error).message}` };
}
// A throw after the text write was issued: whether it landed is unknown, so it is not "nothing sent" either.
if ((error as { inputAttempted?: boolean }).inputAttempted === true) {
return { ok: false, sessionName, outcome: "failed", inputPhase: "attempted", reason: (error as { code?: string }).code ?? "delivery_indeterminate",
return { ok: false, sessionName, outcome: "failed", inputPhase: "attempted",
...(error instanceof DeliveryGuardError && error.inputReadFailure ? { inputReadFailure: error.inputReadFailure } : {}), reason: (error as { code?: string }).code ?? "delivery_indeterminate",
error: `A text write to '${sessionName}' was issued, but its result was lost: ${(error as Error).message}` };
}
const noInputCode = error instanceof OutboxHandlerError && error.code === "retained_quota_full" ? "retained_quota_full" as const
: error instanceof DeliveryGuardError && error.code === "terminal_seat" ? "terminal_seat" as const : undefined;
return { ok: false, sessionName, sent: false, reason: (error as { code?: string }).code ?? "guard_unavailable", error: (error as Error).message,
...(error instanceof DeliveryGuardError && error.inputReadFailure ? { inputReadFailure: error.inputReadFailure } : {}),
...(noInputCode ? { noInputCode, inputPhase: "not_reached" as const } : {}) };
}
}
@@ -3350,7 +3356,7 @@ export class SessionTransport {
}
if (!submitResult.ok && !enterIssued && submitResult.code === CALLER_CANCELLED && cancel?.aborted) return callerCancelled(sessionName);
if (!submitResult.ok) {
return { ok: false, sessionName, inputPhase: enterIssued ? "attempted" : "not_reached", ...(!enterIssued ? { sent: false } : {}), reason: submitResult.code?.startsWith("expected_identity_") ? submitResult.code : "submit_failed", outcome: "failed", error: enterIssued
return { ok: false, sessionName, ...(submitResult.inputReadFailure ? { inputReadFailure: submitResult.inputReadFailure } : {}), inputPhase: enterIssued ? "attempted" : "not_reached", ...(!enterIssued ? { sent: false } : {}), reason: submitResult.code?.startsWith("expected_identity_") ? submitResult.code : "submit_failed", outcome: "failed", error: enterIssued
? `submitOnly: Enter reported a failure for '${sessionName}'; submission is unconfirmed: ${submitResult.message}`
: `submitOnly: Enter was not sent to '${sessionName}': ${submitResult.message}` };
}
@@ -3700,7 +3706,7 @@ export class SessionTransport {
heldInputBoxReading = { status, confidence, evidence, cursor };
}
throw new DeliveryGuardError(box?.status === "typed" ? "draft_input_busy" : "draft_input_unknown",
`Managed input waits for an empty composer (it reads ${box?.status ?? "unknown"}). Your draft was left untouched; inspect the pane before retrying.`);
`Managed input waits for an empty composer (it reads ${box?.status ?? "unknown"}). Your draft was left untouched; inspect the pane before retrying.`, inputReadDiagnostic("composer", box));
}
if (!clear) pastedOverInputBox = box?.status ?? "unknown";
} : undefined;
@@ -3735,6 +3741,7 @@ export class SessionTransport {
ok: false,
sessionName,
reason: policyRefusal ? textResult.code : "send_failed",
...(textResult.inputReadFailure ? { inputReadFailure: textResult.inputReadFailure } : {}),
outcome: "failed",
// The adapter's draft checks run before the paste (only file/buffer preparation precedes them), and its
// after-paste observation cannot fail the write, so a draft_* receipt proves the target input was never reached.
@@ -3803,6 +3810,7 @@ export class SessionTransport {
ok: false,
sessionName,
reason: policyRefusal ? submitResult.code : "submit_failed",
...(submitResult.inputReadFailure ? { inputReadFailure: submitResult.inputReadFailure } : {}),
outcome: "failed",
inputPhase: "written",
error: policyRefusal
@@ -435,12 +435,17 @@ export class StartupOrchestrator {
// #875: a fresh launch decides once where its managed guidance goes; a restore carries its saved choice (null for an
// older snapshot), and a continuation carries its launch's choice, so the adapter isn't asked again and an existing
// seat isn't silently repointed. This runs after the pending mark: a continuation claims its attempt before any await.
if (input.binding.guidanceFile === undefined && input.adapter.guidanceFileFor) {
// A resume of the seat's own conversation (a restore, `rig up --existing`) whose saved choice is the repository file is
// asked too, only whether its launch can carry the guidance: the saved file stays as it is.
const resumingConversation = Boolean(input.resumeToken) && !input.forkSource && !input.skipHarnessLaunch;
const savedRepositoryResume = resumingConversation && input.binding.guidanceFile === null && !input.binding.guidanceLaunchInstructions;
if ((input.binding.guidanceFile === undefined || savedRepositoryResume) && input.adapter.guidanceFileFor) {
// A continuation launches nothing, so it never chooses guidance that only a launch carries.
const answer = input.adapter.guidanceFileFor(input.binding, { resuming: Boolean(input.resumeToken || input.forkSource || input.skipHarnessLaunch) });
const answer = input.adapter.guidanceFileFor(input.binding, { resuming: Boolean(input.resumeToken || input.forkSource || input.skipHarnessLaunch), resumingConversation });
const chosen = answer instanceof Promise ? await answer : answer;
if (chosen.note) warnings.push(chosen.note);
const guidance = { guidanceFile: chosen.file, ...(chosen.launchInstructions ? { guidanceLaunchInstructions: true } : {}) };
const file = savedRepositoryResume ? null : chosen.file;
const guidance = { guidanceFile: file, ...(chosen.launchInstructions && file === null ? { guidanceLaunchInstructions: true } : {}) };
input = { ...input, binding: { ...input.binding, ...guidance } };
// A failure recorded from the delivery input keeps the choice for a later continuation too.
deliveryInput.binding = { ...deliveryInput.binding, ...guidance };
@@ -0,0 +1,27 @@
import { BUILD_INFO, type BuildInfo } from "../build-info.js";
/** The team-operations contract an app reads before relying on a job's fields: one contract version with per-job
* capabilities, distinct from the build label. A capability is supported, not-supported or unknown; an absent key reads
* unknown. */
export const TEAM_OPERATIONS_CONTRACT = "team-operations.v1";
export type CapabilityValue = "supported" | "not-supported" | "unknown";
/** needs-me: see what needs me, answer as me, follow it through. This build reads it (what needs the person, each
* request's revision and what it's about, the answers returned to it, and a snapshot watermark). Answering under this
* contract (a stable answer identity) and following a request through to its result aren't in it yet; the existing
* answer paths keep working outside it. */
export const TEAM_OPERATIONS_CAPABILITIES: Record<string, CapabilityValue> = {
"needs-me.read": "supported",
"needs-me.answer": "not-supported",
"needs-me.follow": "not-supported",
};
export function teamOperationsCapabilities(info: BuildInfo = BUILD_INFO) {
return {
contract: TEAM_OPERATIONS_CONTRACT,
capabilities: TEAM_OPERATIONS_CAPABILITIES,
// A source run has null build fields rather than an invented version.
build: { semver: info.semver, commit: info.commit },
};
}
@@ -24,7 +24,8 @@ import type { FollowControls } from "./terminal-follow-policy.js";
// label embeds a per-launch token — and `layout.apply` itself is
// empirically non-idempotent (the four-reapply capture shows a re-apply
// minting tab t3, never replacing t2), so a re-open can never clobber a
// previous view.
// previous view. Only an open that asks for it (`reuseLive`, #3052) focuses a workspace that still shows
// the same plan with every tile attached instead.
// - Pane labels ride the layout.apply pane nodes' `label` field (AC-7
// `<agent> · <slice>`) — the captures show the label echoed per pane, so
// no separate `pane rename` pass is needed (there is no `pane rename` CLI
@@ -63,6 +64,7 @@ import type {
ComposedPane,
ComposedView,
DegradedSeat,
OpenViewOptions,
OpenViewResult,
ProviderLiveness,
ProviderStatus,
@@ -74,6 +76,7 @@ import type {
HerdrTransportFactory,
} from "./herdr-transport.js";
import { blankShellArgv } from "./login-shell.js";
import { findLiveHerdrWorkspace, type LiveWorkspaceReaders, type LiveWorkspaceSearch } from "./herdr-live-workspace.js";
import { buildTileGrid, planTileLabels, type TileGrid, type TileNodes } from "./tile-layout.js";
/** Sentinel host for herdr-surface degrades (a pane herdr itself failed to render). */
@@ -316,6 +319,9 @@ export interface HerdrAdapterDeps {
tabPrefix?: string;
/** The wait between restart-command report rounds. Injectable for tests. */
sleep?: (ms: number) => Promise<void>;
/** Reads Herdr's CLI on this endpoint and the tmux server's clients, for an open that may reuse a live workspace.
* Without it every open creates a workspace. */
liveWorkspace?: Omit<LiveWorkspaceReaders, "serverArgs">;
}
/** The applied pane ids of a page, in its leaf order, when Herdr's reply echoes exactly the requested tree. */
@@ -479,7 +485,7 @@ export class HerdrAdapter implements TerminalProvider {
code: "follow_unsupported", error: "This endpoint has no qualified following allocator." };
}
async openView(view: ComposedView): Promise<OpenViewResult> {
async openView(view: ComposedView, options?: OpenViewOptions): Promise<OpenViewResult> {
const absent: AbsentSeat[] = [...view.absent];
const degraded: DegradedSeat[] = [...view.degraded];
const opened: string[] = [];
@@ -515,6 +521,12 @@ export class HerdrAdapter implements TerminalProvider {
};
}
const notes: string[] = [];
if (options?.reuseLive) {
const reused = await this.reuseLiveWorkspace(view, notes);
if (reused) return reused;
}
// A fresh workspace per open (BR-5 fresh-on-relaunch, strongest form).
// Herdr accepts a duplicate label, so a re-open would otherwise sit beside the earlier
// view under the same name. The existing labels are read first: when this rig's view is
@@ -523,7 +535,6 @@ export class HerdrAdapter implements TerminalProvider {
// The labeled create is tried first. If herdr refuses it and a workspace with
// that label already exists, retry once with a numbered suffix and say so;
// otherwise fall back ONCE to a bare create before degrading.
const notes: string[] = [];
let workspaceId: string | null = null;
let defaultTabId: string | null = null;
let createErr: unknown = null;
@@ -686,4 +697,41 @@ export class HerdrAdapter implements TerminalProvider {
...(notes.length ? { notes } : {}),
};
}
/**
* #3052: the same reuse as the CLI's `--window`. A workspace whose tabs still show every tile of this plan,
* attached, is focused and returned instead of opening a numbered copy. Anything unconfirmed opens a new
* workspace, as before, and the notes name the workspaces that were kept.
*/
private async reuseLiveWorkspace(view: ComposedView, notes: string[]): Promise<OpenViewResult | null> {
const readers = this.deps.liveWorkspace;
if (!readers || !view.planId) return null;
let found: LiveWorkspaceSearch;
try {
found = await findLiveHerdrWorkspace({ id: view.id, planId: view.planId, pages: view.pages, ...(view.spaceLabel ? { spaceLabel: view.spaceLabel } : {}) },
{ ...readers, serverArgs: view.localTmuxServer ?? [] });
} catch (err) {
notes.push(`Could not check existing Herdr workspaces (${err instanceof Error ? err.message : String(err)}); this open adds a new workspace and keeps the existing ones.`);
return null;
}
for (const id of found.stale) notes.push(`Workspace ${id} has an older or different plan for this view and was kept.`);
for (const id of found.unconfirmed) notes.push(`Workspace ${id} has this view, but its tiles' live attachments could not be confirmed, so it was kept.`); // what this open does next is said once it's known
if (!found.live) return null;
const { workspace_id: id, tab_id: tabId } = found.live;
// The reuse counts only when the reply names this exact tab and workspace; anything less is one more uncertain
// branch: keep that workspace, say so, and open a fresh one (headless callers need the view, not the focus).
let focused: unknown;
try { focused = (await this.transport.request("tab.focus", { tab_id: tabId }))["tab"]; }
catch (err) { focused = err instanceof Error ? err.message : String(err); }
const tab = focused && typeof focused === "object" ? focused as Record<string, unknown> : null;
if (tab?.["tab_id"] !== tabId || tab?.["workspace_id"] !== id) {
notes.push(`Workspace ${id} already shows this view, but herdr did not confirm focusing its tab ${tabId}${typeof focused === "string" ? ` (${focused})` : ""}; it was kept.`);
return null;
}
notes.push(`Workspace ${id} already shows this view with live attachments, so it was reused; its contents were kept and no new tiles were opened.`);
return {
provider: this.name, ok: true, opened: [], absent: [...view.absent], degraded: [...view.degraded], pages: 0,
reusedWorkspace: { id, tabId, view: view.id }, notes,
};
}
}
@@ -0,0 +1,136 @@
// #3052: the one check for "this view is already on screen in Herdr". The CLI's `--window` open and the
// daemon's `--provider herdr` open both use it, so a re-open focuses that workspace instead of adding a copy.
// It only reads: Herdr's workspaces, tabs, panes and their foreground processes, and the tmux server's
// clients. It never types into, focuses or closes a pane.
import path from "node:path";
/** One tab as `herdr tab list` reports it. */
export interface HerdrTab { workspace_id: string; tab_id: string; label: string }
/** A tile as the check compares it: the attach command the composer gave its pane. */
export interface LiveTile { label: string; paneCommand: string; recoveryCommand?: string }
/** The view being opened, by what its Herdr tabs carry: the view id and plan in a tab label, or a named view's space. */
export interface HerdrViewKey { id: string; planId: string; pages: readonly (readonly LiveTile[])[]; spaceLabel?: string }
export interface LiveWorkspaceReaders {
/** Runs the Herdr CLI on the selected endpoint and returns its stdout. */
herdr(args: string[]): Promise<string>;
/** Runs a program and returns its stdout: resolving tmux and listing its clients. */
exec(file: string, args: string[]): Promise<string>;
/** The daemon's tmux server options (`-S <path>` or `-L <name>`), or none. */
serverArgs: readonly string[];
}
export interface LiveWorkspaceSearch {
/** The first tab of a workspace that still shows every tile of this plan, attached; absent when none does. */
live?: HerdrTab;
/** Workspaces holding this plan whose attachments could not be confirmed, one per candidate tab checked. */
unconfirmed: string[];
/** Workspaces holding an older or different plan of this view. */
stale: string[];
}
/** Saved Herdr labels survive reboot; only current clients prove a local attachment. */
async function hasLiveAttachments(existing: HerdrTab, tabs: HerdrTab[], pages: readonly (readonly LiveTile[])[], pageLabel: (index: number) => string, readers: LiveWorkspaceReaders): Promise<boolean> {
const { herdr, exec, serverArgs } = readers;
try {
const tmux = (await exec("/bin/sh", ["-c", "command -v tmux"])).trim();
if (!path.isAbsolute(tmux)) return false;
const listed = JSON.parse(await herdr(["pane", "list", "--workspace", existing.workspace_id]));
const panes = listed?.result?.panes as Array<{ workspace_id: string; tab_id: string; pane_id: string }> | undefined;
if (!Array.isArray(panes) || !panes.every(pane => pane && pane.workspace_id === existing.workspace_id && typeof pane.tab_id === "string" && typeof pane.pane_id === "string" && pane.pane_id)) return false;
const clients = new Map<string, string[]>();
// Match view-composer's serialization (these strings are compared, never executed).
const quote = (value: string) => "'" + value.replace(/'/g, "'\"'\"'") + "'";
const server = serverArgs.map((arg, index) => index % 2 ? quote(arg) : arg).join(" ");
const inventory = await exec(tmux, [...serverArgs, "list-clients", "-F", "#{client_pid}\t#{session_name}\t#{client_readonly}"]);
for (const line of inventory.trim().split("\n")) {
const [pid, session, readOnly] = line.split("\t");
if (!pid || !/^\d+$/.test(pid) || !session || !["0", "1"].includes(readOnly ?? "")) continue;
// Compare the composer's exact command, including session aliases and read-only mode.
// SSH/custom commands cannot be confirmed from this local client inventory.
const flags = readOnly === "1" ? ["-r "] : ["", "-f ignore-size "];
clients.set(pid, ["tmux", quote(tmux)].flatMap(binary => flags.map(flag => `${binary}${server ? ` ${server}` : ""} attach ${flag}-t ${quote(session)}`)));
}
const used = new Set<string>();
for (const [index, page] of pages.entries()) {
const label = pageLabel(index);
const matches = tabs.filter(tab => tab.workspace_id === existing.workspace_id && tab.label === label);
if (matches.length !== 1) return false;
const remaining = page.map(pane => pane.recoveryCommand ?? pane.paneCommand);
for (const pane of panes.filter(pane => pane.tab_id === matches[0]!.tab_id)) {
if (remaining.length === 0) break;
const result = JSON.parse(await herdr(["pane", "process-info", "--pane", pane.pane_id]));
const info = result?.result?.process_info;
if (info?.pane_id !== pane.pane_id || (info.foreground_processes !== undefined && !Array.isArray(info.foreground_processes))) return false;
for (const process of info.foreground_processes ?? []) {
const pid = String(process?.pid);
if (used.has(pid)) continue;
const found = remaining.findIndex(command => clients.get(pid)?.includes(command));
if (found < 0) continue;
remaining.splice(found, 1);
used.add(pid);
break; // One Herdr pane can satisfy only one expected tile.
}
}
if (remaining.length) return false;
}
return pages.length > 0;
} catch {
// Read failures prevent reuse, not opening. Never type into or close an unverified pane.
return false;
}
}
/** Every workspace's tabs, scoped per workspace. Throws when Herdr's inventory is unusable. */
async function readTabs(herdr: LiveWorkspaceReaders["herdr"]): Promise<{ tabs: HerdrTab[]; spaceLabels: Map<string, string> }> {
const tabs: HerdrTab[] = [];
const spaceLabels = new Map<string, string>();
const listed = JSON.parse(await herdr(["workspace", "list"]));
const workspaces = listed?.result?.workspaces as Array<{ workspace_id: string; label?: string }> | undefined;
if (!Array.isArray(workspaces) || !workspaces.every(ws => ws && typeof ws.workspace_id === "string" && ws.workspace_id)) {
throw new Error("Herdr returned no usable workspace inventory.");
}
for (const workspace of workspaces) {
if (typeof workspace.label === "string") spaceLabels.set(workspace.workspace_id, workspace.label);
const listedTabs = JSON.parse(await herdr(["tab", "list", "--workspace", workspace.workspace_id]));
const scoped = listedTabs?.result?.tabs as HerdrTab[] | undefined;
if (!Array.isArray(scoped) || !scoped.every(tab => tab && typeof tab.label === "string" && typeof tab.tab_id === "string" && tab.tab_id && tab.workspace_id === workspace.workspace_id)) {
throw new Error(`Herdr returned no usable tab inventory for workspace ${workspace.workspace_id}.`);
}
tabs.push(...scoped);
}
return { tabs, spaceLabels };
}
/**
* Find a workspace that still shows this view's plan with every tile attached. A view's tabs carry
* `openrig:<view>#<plan>#<launch>` labels; a named view's tabs carry its panes' names inside its space.
* Throws when Herdr's inventory can't be read, so the caller decides how to say so.
*/
export async function findLiveHerdrWorkspace(view: HerdrViewKey, readers: LiveWorkspaceReaders): Promise<LiveWorkspaceSearch> {
const { tabs, spaceLabels } = await readTabs(readers.herdr);
const viewMarker = `openrig:${view.id}`;
const planMarker = `${viewMarker}#${view.planId.slice(0, 16)}`;
const marker = (label: string) => label.includes("#") ? label.slice(0, label.lastIndexOf("#")) : "";
// A named view's tabs carry its panes' names; the attachment check below decides reuse.
const named = view.spaceLabel ? view.pages.map(page => page.map(pane => pane.label).join(" · ")) : undefined;
const pageLabel = (existing: HerdrTab) => (index: number) => named ? named[index]!
: view.pages.length > 1 ? `${existing.label.slice(0, -2)}/${index + 1}` : existing.label;
const candidates = named
? tabs.filter(tab => tab.label === named[0] && spaceLabels.get(tab.workspace_id)?.replace(/ \(\d+\)$/, "") === view.spaceLabel && named.every(label => tabs.filter(other => other.workspace_id === tab.workspace_id && other.label === label).length === 1))
: tabs.filter(tab => marker(tab.label) === planMarker && (view.pages.length <= 1 || tab.label.endsWith("/1")));
const stale = tabs.filter(tab => {
const value = marker(tab.label);
return value !== planMarker && (value === viewMarker ||
(value.startsWith(`${viewMarker}#`) && /^[a-f0-9]{16}$/.test(value.slice(viewMarker.length + 1))));
});
const search: LiveWorkspaceSearch = { unconfirmed: [], stale: [...new Set(stale.map(tab => tab.workspace_id))] };
for (const candidate of candidates) {
if (await hasLiveAttachments(candidate, tabs, view.pages, pageLabel(candidate), readers)) return { ...search, live: candidate };
search.unconfirmed.push(candidate.workspace_id);
}
return search;
}
@@ -4,6 +4,7 @@ import { HerdrAdapter } from "./herdr-adapter.js";
import { createHerdrSocketRpc, createHerdrSocketTransport, resolveHerdrSocketPath } from "./herdr-transport.js";
import type { ProviderStatus } from "./terminal-provider.js";
import { HerdrFollowView, type ReadFollowInput } from "./herdr-follow-view.js";
import { execArgvCommand } from "../../adapters/tmux-exec.js";
/** Keep the daemon's configured endpoint while selecting explicit sessions per
* request. No request mutates process.env or another request's transport.
@@ -26,6 +27,8 @@ export function createHerdrProviders(env: NodeJS.ProcessEnv = process.env, input
following: new HerdrFollowView({ socketPath: endpoint.socketPath, run: createHerdrViewerRun(endpoint, env), transport: transportFactory(), input }),
launch: endpoint,
viewer: viewer(endpoint),
// The same Herdr CLI and tmux clients the daemon already uses, for an open that may reuse a live view.
liveWorkspace: { herdr: createHerdrViewerRun(endpoint, env), exec: (file, args) => execArgvCommand([file, ...args]) },
newLaunchToken: () => `l${++launch}`,
}); };
const sessions = new Map<string, HerdrAdapter>();
@@ -80,9 +80,15 @@ export class RexAdapter implements TerminalProvider {
private readonly now: () => number;
private launchCounter = 0;
private lastProbe: ProbeEntry | null = null;
private readonly tilesOpened?: (seats: string[]) => Promise<void>;
constructor(deps: { transport: RexTransport; newLaunchToken?: () => string; sleep?: (ms: number) => Promise<void>; now?: () => number }) {
constructor(deps: {
transport: RexTransport; newLaunchToken?: () => string; sleep?: (ms: number) => Promise<void>; now?: () => number;
/** Called with the local seats whose tiles opened, so their agent and state can be shown on the tiles. */
tilesOpened?: (seats: string[]) => Promise<void>;
}) {
this.transport = deps.transport;
this.tilesOpened = deps.tilesOpened;
this.newLaunchToken = deps.newLaunchToken ?? (() => `l${(this.launchCounter += 1)}`);
this.sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
this.now = deps.now ?? Date.now;
@@ -216,11 +222,17 @@ export class RexAdapter implements TerminalProvider {
if (label !== plain) notes.push(`A view named "${plain}" is already open, so this one is "${label}".`);
await this.sleep(REX_TILE_SETTLE_MS);
const reasons = await exitedTiles(this.transport, sessionId, tiles, notes);
const local: string[] = [];
tiles.forEach(({ pane }, i) => {
const reason = reasons[i];
if (reason) degrade([pane], reason);
else opened.push(pane.seat);
else {
opened.push(pane.seat);
if (!pane.host) local.push(pane.seat);
}
});
// The tiles' status follows on its own; the view's result doesn't wait for it.
if (local.length > 0) void this.tilesOpened?.(local).catch(() => {});
return {
...base,
ok: opened.length > 0 || view.opened.length === 0,
@@ -0,0 +1,204 @@
import { constants } from "node:fs";
import { open } from "node:fs/promises";
import type { AgentActivity } from "../types.js";
/**
* Rex shows a block's agent and its state from OSC 7501 reports, but a Rex tile runs only `tmux attach`, and the agent
* inside the seat's pane writes to OpenRig's tmux server, so Rex never sees its own reports. This relays the activity
* OpenRig already resolves for a seat straight to the tmux clients attached to the seat's session that identify as
* Rex (their XTVERSION reply), leaving tmux options and other terminals alone.
*/
/** What a Rex tile is told about a seat: a state, or `clear` when OpenRig doesn't know it. */
export type RexAgentStatus = { state: "working" | "idle" | "blocked"; kind?: "permission" } | { state: "clear" };
/** The daemon's tmux adapter, as far as the relay uses it. */
export interface RexStatusClients {
listSessionClientTerminals(session: string): Promise<Array<{ tty: string; termtype: string }> | null>;
}
/** A seat's activity and runtime at one reading. */
export interface SeatActivity { activity: AgentActivity | null; runtime: string | null }
/** A seat's current activity and runtime, resolved the way `rig ps --nodes` resolves them. */
export type ResolveSeatActivity = (sessionName: string) => SeatActivity;
/** The Rex state for an OpenRig activity; unknown becomes `clear`, never idle. */
export function rexAgentStatus(activity: AgentActivity | null): RexAgentStatus {
switch (activity?.state) {
case "running": return { state: "working" };
case "idle": return { state: "idle" };
case "needs_input": return activity.reason === "permission_prompt" ? { state: "blocked", kind: "permission" } : { state: "blocked" };
default: return { state: "clear" };
}
}
/** The runtime as Rex names the app; a runtime it doesn't know is passed as OpenRig names it. */
const rexApp = (runtime: string): string => runtime.replace(/[^A-Za-z0-9_.+-]/g, "-").slice(0, 32);
/** The OSC 7501 report for a status; a state with no runtime to name is a `clear`, so no earlier state lingers. */
export function rexStatusReport(status: RexAgentStatus, runtime: string | null): string {
const fields = status.state === "clear" || !runtime
? "state=clear"
: [`state=${status.state}`, `app=${rexApp(runtime)}`, ...(status.kind ? [`kind=${status.kind}`] : [])].join(":");
return `\x1b]7501;${fields}\x1b\\`;
}
const isRex = (termtype: string): boolean => /^rex\b/i.test(termtype);
/** How long a seat found without a Rex client is left alone before it is looked at again, so a Rex client attached
* by hand, or by Rex after an app restart, is still found. */
export const REX_CLIENT_RECHECK_MS = 5 * 60_000;
/** How often a seat with Rex clients is looked at again without an activity change: to reach a newly attached
* client and to retry a report a client missed. Within it, an unchanged report costs no tmux call. */
export const REX_CLIENT_REFRESH_MS = 5_000;
/** String Terminator: closes an OSC a partial write left open, and does nothing otherwise. */
const ST = "\x1b\\";
/** Writes to a terminal and returns how many bytes went out. */
async function writeTty(tty: string, text: string): Promise<number> {
// O_NOCTTY: never take the client's terminal as the daemon's own. O_NONBLOCK: a stalled terminal drops the report
// instead of holding the seat's later reports behind it.
const handle = await open(tty, constants.O_WRONLY | constants.O_NOCTTY | constants.O_NONBLOCK);
try {
return (await handle.write(text)).bytesWritten;
} finally {
await handle.close();
}
}
/** A seat with Rex clients: the report each client last took ("" when that isn't known, such as a client this relay
* hasn't written to since the daemon started or since it moved from another seat), and when the clients were last
* listed. */
interface ShownSeat { delivered: Map<string, string>; listedAt: number }
export class RexAgentStatusRelay {
private readonly clients: RexStatusClients;
private readonly resolve: ResolveSeatActivity;
private readonly write: (tty: string, text: string) => Promise<number>;
private readonly now: () => number;
private readonly sweeps: boolean;
private readonly shown = new Map<string, ShownSeat>();
/** When a seat was last found without a Rex client. */
private readonly unshownAt = new Map<string, number>();
/** Terminals a partial write left inside an unfinished OSC. */
private readonly dangling = new Set<string>();
/** The seat each terminal was last written for, so a seat whose terminal another seat wrote to since sends again. */
private readonly lastWriter = new Map<string, string>();
/** One report at a time per seat, so two quick changes reach the tile in order. */
private readonly pending = new Map<string, Promise<void>>();
private timer: ReturnType<typeof setInterval> | null = null;
private stopped = false;
constructor(deps: {
clients: RexStatusClients; resolve: ResolveSeatActivity; writeTty?: (tty: string, text: string) => Promise<number>; now?: () => number;
/** False keeps the periodic sweep off; tests call sweep() themselves. */
sweep?: boolean;
}) {
this.clients = deps.clients;
this.resolve = deps.resolve;
this.write = deps.writeTty ?? writeTty;
this.now = deps.now ?? Date.now;
this.sweeps = deps.sweep ?? true;
}
/** A Rex view just opened these seats' tiles: show each one's current state. */
async tilesOpened(seats: string[]): Promise<void> {
await Promise.all(seats.map((seat) => this.report(seat, { opening: true })));
}
/** The seat's activity may have changed; `current` is its activity when the caller already resolved it. */
activityChanged(seat: string, current?: SeatActivity): Promise<void> {
return this.report(seat, { current });
}
/** Look again, with no activity change, at seats whose clients are due a listing: retries, new clients, rechecks. */
async sweep(): Promise<void> {
const now = this.now();
const due = [
...[...this.shown].filter(([, s]) => now - s.listedAt >= REX_CLIENT_REFRESH_MS).map(([seat]) => seat),
...[...this.unshownAt].filter(([, at]) => now - at >= REX_CLIENT_RECHECK_MS).map(([seat]) => seat),
];
await Promise.all(due.map((seat) => this.report(seat, {})));
}
/** Stop the periodic sweep. */
stop(): void {
this.stopped = true;
if (this.timer) clearInterval(this.timer);
this.timer = null;
}
private report(seat: string, opts: { opening?: boolean; current?: SeatActivity }): Promise<void> {
const next = (this.pending.get(seat) ?? Promise.resolve()).then(() => this.reportNow(seat, opts)).catch(() => {});
this.pending.set(seat, next);
void next.then(() => { if (this.pending.get(seat) === next) this.pending.delete(seat); });
return next;
}
private async reportNow(seat: string, { opening = false, current }: { opening?: boolean; current?: SeatActivity }): Promise<void> {
const now = this.now();
const unshown = this.unshownAt.get(seat);
if (!opening && unshown !== undefined && now - unshown < REX_CLIENT_RECHECK_MS) return;
// Inside the queue, so a report still in flight can't record a delivery the opening has to repeat.
if (opening) for (const [tty] of this.shown.get(seat)?.delivered ?? []) this.shown.get(seat)!.delivered.set(tty, "");
const { activity, runtime } = current ?? this.resolve(seat);
const status = rexAgentStatus(activity);
const report = rexStatusReport(status, runtime);
const known = this.shown.get(seat);
const hasIt = (tty: string, delivered: string) => delivered === report && this.lastWriter.get(tty) === seat;
const everyClientHasIt = known !== undefined && known.delivered.size > 0 && [...known.delivered].every(([tty, r]) => hasIt(tty, r));
if (everyClientHasIt && now - known.listedAt < REX_CLIENT_REFRESH_MS) return;
const clients = await this.clients.listSessionClientTerminals(seat);
// tmux couldn't be read: the sweep tries again, without deciding the seat has no Rex client.
if (clients === null) {
if (!known) this.shown.set(seat, { delivered: new Map(), listedAt: now });
this.unshownAt.delete(seat);
this.startSweeping();
return;
}
const ttys = clients.filter((c) => isRex(c.termtype)).map((c) => c.tty);
if (ttys.length === 0) {
this.shown.delete(seat);
this.unshownAt.set(seat, now);
this.startSweeping();
return;
}
this.unshownAt.delete(seat);
const seatState: ShownSeat = known ?? { delivered: new Map(), listedAt: now };
seatState.listedAt = now;
for (const tty of [...seatState.delivered.keys()]) if (!ttys.includes(tty)) seatState.delivered.delete(tty);
this.shown.set(seat, seatState);
this.startSweeping();
// A client with no record here may still show what this relay told it before a daemon restart, or another seat's
// state, so it gets the current report, a clear included.
const targets = ttys.filter((tty) => !hasIt(tty, seatState.delivered.get(tty) ?? ""));
await Promise.all(targets.map(async (tty) => {
try {
const text = this.dangling.has(tty) ? ST + report : report;
this.lastWriter.set(tty, seat);
const written = await this.write(tty, text);
if (written > 0) this.dangling.delete(tty);
if (written !== Buffer.byteLength(text)) {
if (written > 0) this.dangling.add(tty);
throw new Error(`wrote ${written} of ${Buffer.byteLength(text)} bytes`);
}
seatState.delivered.set(tty, report);
} catch {
// What it shows is now unknown, so the next look sends it the current report, whatever that is.
seatState.delivered.set(tty, "");
}
}));
}
private startSweeping(): void {
if (this.stopped || this.timer || !this.sweeps) return;
this.timer = setInterval(() => { void this.sweep(); }, REX_CLIENT_REFRESH_MS);
this.timer.unref?.();
}
}
@@ -144,6 +144,14 @@ export interface OpenViewResult {
notes?: string[];
/** The provider space the view opened in (a Rex session), for a caller that shows it. */
space?: { id: string; label: string };
/** An existing workspace that still showed this view live was focused instead of opening tiles (`opened` is empty). */
reusedWorkspace?: { id: string; tabId: string; view: string };
}
/** How an open may treat a view that is already on screen. */
export interface OpenViewOptions {
/** Reuse a workspace that still shows every tile of this view, attached, instead of opening a copy. */
reuseLive?: boolean;
}
/**
@@ -160,7 +168,7 @@ export interface TerminalProvider {
readonly panesPerPage?: number;
status(): Promise<ProviderStatus>;
liveness(): Promise<ProviderLiveness>;
openView(view: ComposedView): Promise<OpenViewResult>;
openView(view: ComposedView, options?: OpenViewOptions): Promise<OpenViewResult>;
ensureViewer?(key: ViewerKey, pane: ComposedPane, stillCurrent?: () => Promise<boolean>): Promise<ViewerResult>;
lookupViewer?(key: ViewerKey, pane: ComposedPane): Promise<ViewerResult>;
followView?(viewId: string, view: ComposedView | null, controls: FollowControls, stillCurrent: () => Promise<boolean>, membershipError?: string): Promise<OpenViewResult>;
@@ -81,6 +81,8 @@ export interface OpenViewRequest {
expectedPlan?: string;
/** Measured width of the viewing terminal; unknown widths keep the narrow default. */
viewportColumns?: number;
/** Reuse a workspace that still shows this view live instead of opening a copy (herdr). */
reuseLive?: boolean;
/** The herdr-app client (its app home) for provider herdr-app. */
herdrApp?: HerdrAppTarget;
}
@@ -345,9 +347,10 @@ export class TerminalService {
absent: composed.absent, degraded: composed.degraded, notes,
};
}
const result = await provider.openView({ ...composed, planId });
const result = req.reuseLive ? await provider.openView({ ...composed, planId }, { reuseLive: true }) : await provider.openView({ ...composed, planId });
// herdr-app opens in the client the request came from: its failure says why, never "attach by hand elsewhere".
if (result.opened.length === 0 && composed.opened.length > 0 && providerName !== "herdr-app") {
// A reused workspace already shows every tile.
if (result.opened.length === 0 && composed.opened.length > 0 && providerName !== "herdr-app" && !result.reusedWorkspace) {
notes.push("In a new terminal on the daemon's host, attach directly using one of these commands:");
for (const pane of composed.opened) notes.push(`${pane.label}: env -u TMUX ${pane.recoveryCommand ?? pane.paneCommand}`);
notes.push("Each labelled command above opens a different seat. When sharing how to join this team, include every command in full, unchanged, including env -u TMUX, paths and quoting.");
+4
View File
@@ -330,6 +330,10 @@ export type RigEvent =
// consumers on /api/views/:name/sse when ANY queue state mutation
// changes a view result-set, not just create/handoff/claim/unclaim.
| { type: "queue.updated"; qitemId: string; fromState: string; toState: string; closureReason: string | null; closureTarget: string | null; actorSession: string; summary: string | null }
// A person's clicked answer recorded on an ask with questions: `answered` of `questions` now have an answer, and
// `complete` says whether that's all of them. A partial set is a change to the ask, not its answer: the ask stays open
// until the set is complete and returned.
| { type: "queue.answer_recorded"; qitemId: string; actorSession: string; questionId: string; answered: number; questions: number; complete: boolean; summary: string | null }
// Coordination primitive (PL-004 Phase B) — project (classifier) / view.
// project.classified: emitted when a stream item is successfully projected.
// classifier.lease_*: lifecycle of the daemon-enforced single-writer lease.
@@ -200,6 +200,7 @@ export const SETTINGS_VALID_KEYS = [
// Slice 15 (OPR.0.7.0.15) — compact command-output defaults; CLI-read, twin of the CLI key.
"output.compact",
"output.whoami_peers",
"output.rebuild_recaps",
// Slice 01 (OPR.0.7.0.1) — Codex and Claude usage windows in the provider view; daemon-read, twin of the CLI key.
"provider.usage_windows",
// The providers chosen at rig setup --providers; kernel boot counts only these. Twin of the CLI key.
@@ -347,6 +348,7 @@ const ENV_MAP: Record<SettingsValidKey, { primary: string; legacy?: string }> =
"terminal.inherit_tmux_environment": { primary: "OPENRIG_TERMINAL_INHERIT_TMUX_ENVIRONMENT" },
"output.compact": { primary: "OPENRIG_OUTPUT_COMPACT" },
"output.whoami_peers": { primary: "OPENRIG_OUTPUT_WHOAMI_PEERS" },
"output.rebuild_recaps": { primary: "OPENRIG_OUTPUT_REBUILD_RECAPS" },
"provider.usage_windows": { primary: "OPENRIG_PROVIDER_USAGE_WINDOWS" },
"provider.selected": { primary: "OPENRIG_PROVIDER_SELECTED" },
"bundle.services_enabled": { primary: "OPENRIG_BUNDLE_SERVICES_ENABLED" },
@@ -456,6 +458,7 @@ const KEY_TO_PATH: Record<SettingsValidKey, string[]> = {
"terminal.inherit_tmux_environment": ["terminal", "inheritTmuxEnvironment"],
"output.compact": ["output", "compact"],
"output.whoami_peers": ["output", "whoamiPeers"],
"output.rebuild_recaps": ["output", "rebuildRecaps"],
"provider.usage_windows": ["provider", "usageWindows"],
"provider.selected": ["provider", "selected"],
"bundle.services_enabled": ["bundle", "servicesEnabled"],
@@ -775,6 +778,7 @@ function getDefaultValue(key: SettingsValidKey, workspaceRoot: string): string |
case "terminal.inherit_tmux_environment": return false;
case "output.compact": return false;
case "output.whoami_peers": return 8;
case "output.rebuild_recaps": return 3;
case "provider.usage_windows": return false;
case "provider.selected": return "";
case "bundle.services_enabled": return false;
@@ -1002,6 +1006,11 @@ const KEY_CONSTRAINTS: Partial<Record<SettingsValidKey, (raw: string, coerced: s
// surface rejects exactly what the CLI rejects. `retention.enabled` is a
// boolean (coerceValue enforces true/false) — no constraint entry needed.
// Slice 15 P5 — the whoami peer bound; lockstep with the CLI twin.
"output.rebuild_recaps": (raw, value) => {
if (!/^\d+$/.test(raw.trim()) || typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
throw new Error(`Invalid value for output.rebuild_recaps: must be an integer >= 0, got "${raw}"`);
}
},
"output.whoami_peers": (raw, coerced) => {
if (!/^-?\d+$/.test((raw ?? "").trim()) || typeof coerced !== "number" || !Number.isInteger(coerced) || coerced < 1) {
throw new Error(`Invalid value for output.whoami_peers: must be an integer >= 1, got "${raw}"`);
Loaded 100 of 163 files, more files were not shown because too many files have changed in this diff. Show more