Compare commits

...
Author SHA1 Message Date
dev60-review 80f923a2a0 docs: scope two promises to what they cover
The startup guide's "nothing you wrote is removed" now says it's about
tidying copies, since a launch still replaces an unrecorded block that
differs from its source. rig down's help now says a community harness
only has its pane stopped, so its own processes may keep running.
2026-11-12 22:48:44 +00:00
Mike Schwarz 16509d0091 docs: five help and doc lines say what OpenRig does now (#3091)
Five places in the help and reference docs described behaviour OpenRig has since changed. A runner waiting on a permission request now gets the decision at once, and one that isn't waiting gets it at its next read. A guidance file keeps one copy of each distinct block text, and every different edited copy stays. The network connector's reference and help say once that it's experimental and unsupported, used at your own risk, and a disconnected hub-URL binding is described as the hub still listing it. rig down's help says it stops the agents OpenRig started and leaves a session it didn't start running. ui.timezone's help names the Feed as well as the TUI. Text only: no behaviour changes.
2026-11-12 14:45:54 -08:00
Mike Schwarz 2e3521b345 feat: list connected assistants and their check-in in the TUI tables (#3058)
Connected assistants (roster members outside any terminal) aren't seats, so the TUI's seat tables didn't show them. The instance table and the rig table now end their seat rows with a short section listing each one and its check-in line, the same line rig ps and rig roster print, with the last check-in in the viewer's time zone. The rig table lists only that rig's assistants, and the instance filter applies to them. The read is optional and made only for those two tables. When the list can't be read, the tables say check-in is unavailable, as rig ps does, and a status this TUI doesn't know reads unknown.
2026-11-12 14:15:11 -08:00
Mike Schwarz 2eaa1ea3d9 fix(queue): account erasure takes OpenRig's own wakes and notices to the account (#3089)
Account erasure in members scope can now come back clean for an account that OpenRig itself woke or notified. OpenRig's own sessions (daemon@kernel and system:*, the existing isOpenRigSender rule) belong to no account: a row, a row's copy or an unlinked outbox or inbox entry is judged by its other sessions and needs a member among them. So members scope now also erases rows between a member and OpenRig's own session (such as wake escalations and health findings sent to a member), OpenRig's wake for a row it erases, and unlinked entries between a member and OpenRig's own session. Still kept and reported: anything with a session outside the account, OpenRig's wakes and rows to another account's seats, entries between two of OpenRig's own sessions, and lookalike names (the system: prefix is matched exactly and case-sensitively). Running the same members plan again over data an earlier daemon wrote removes what that daemon left and reports clean. The erasure docs and the CLI help say exactly what is now erased and what is kept.
2026-11-12 13:26:16 -08:00
Mike Schwarz 38c9b158c6 docs(changelog): carry 0.7.13's notes to main, with two remedy lines corrected (#3086)
CHANGELOG.md on main gains the 0.7.13 section, as earlier releases' sections were carried to main, so later notes build on the same text. Two sentences differ from the packaged notes and match the published release notes: a Codex seat can ask for hook approval after the upgrade (relaunching isn't established as clearing it), and if Codex is installed, tell the person about the possible sign-in wait before the team starts (signing in first wasn't tested as a remedy). Everything else is the 0.7.13 section as released.
2026-11-12 12:44:02 -08:00
billbenetti 2ea8ba07fe fix(daemon): never auto-drive Claude's gated-grants trust check, and answer the trust prompt only on "Yes" (#2820) (#3073)
For #2820 (item 2; item 1 shipped in #2899). On a Claude Code seat's restore or fresh launch, OpenRig answers the plain workspace trust prompt only when it reads Claude's current screen (above the input frame, with any draft inside a frame blanked first), sees exactly the "No, exit" and "Yes, I trust this folder" options, and finds the cursor on Yes; it then presses Enter once. Any other option set, more than one cursor, or no cursor reads unknown, and nothing is sent. The gated-grants backstop, the screen that asks about a folder's pre-approved tool permissions, is never driven: a screen carrying its marks, even partly drawn, reads as waiting for the person. A framed draft no longer counts as a current dialog, and a dialog drawn below older output is still recognised.
2026-11-12 12:38:28 -08:00
29 changed files with 1139 additions and 53 deletions

No files matched your search

+246
View File
@@ -8,6 +8,252 @@ deprecations, and behavioral changes. Breaking changes are called out explicitly
---
## [0.7.13]
OpenRig 0.7.13 is a patch for people running their own agent teams. When you answer a runner's permission request, you now get a
note back saying who decides it, and the runner wakes on the decision. The
agent that reads your answers is told what an answer typed at your machine
means and how to ask you back. `rig daemon start` tells the agent setting
OpenRig up to offer to register you when nobody is registered yet, and a Claude
seat whose usage-limit message states a reset time waits for it instead of being
retried. There are fixes across delivery,
handover and recovery, the TUI and speed, many contributed by people using
OpenRig. In our tests, a first Claude user (with Codex absent) and a first Codex
user each went from a fresh install to a built, independently reviewed and
committed change. Two repairs aren't in this release: see Known limits.
### Before you upgrade
- **Back up the database, then restart the daemon:** `rig daemon stop`, copy the
database file (`rig config get db.path` prints its path), then
`rig daemon start`. Your agents keep running through a daemon restart; don't
use `rig down`, which ends them. Three migrations run on the daemon's first start: 160 and 161 (for the experimental hub connector below)
and 162 (indexes for session reads). Going back to 0.7.12 after them isn't
established. ([#2993](https://github.com/mvschwarz/openrig/pull/2993), [#2997](https://github.com/mvschwarz/openrig/pull/2997))
- **openrig-core is 0.1.29, and the `openrig` plugin now carries the CLI's
version, 0.7.13.** A Codex seat can ask for hook approval after the
upgrade; see Codex hook review after an upgrade below. ([#3034](https://github.com/mvschwarz/openrig/pull/3034), [#3064](https://github.com/mvschwarz/openrig/pull/3064))
### Answering your team
- A runner's permission answer gets a note back to you: who decides it and in
what state, or that it's kept and the tool hasn't run. A runner waiting on
the decision gets it within about half a second. Read that note before answering again. If
it says your answer couldn't be passed on, follow its retry instruction or use
the `rig seat decide-permission` command it names.
([#3001](https://github.com/mvschwarz/openrig/pull/3001))
- The answer a receiving agent reads now says what an answer typed at this
machine's terminal or TUI means, to act on a clear answer with the request's
own decision command, and how to ask you back with a new ask when it isn't
clear. When the default receiving agent asks you back, the question reaches
your Feed, and your reply decides. Closing a runner's request without
deciding permits nothing. ([#3030](https://github.com/mvschwarz/openrig/pull/3030))
- `rig daemon start` ends by telling the agent setting OpenRig up to offer to
register you as the team's person, when the person registry can be read and
holds nobody. The rigs skill's start step makes the same offer, and asking to
be reachable registers you as the default person directly. In our
fresh-install tests the setup agent passed the offer on in 5 of 6 installs,
and a no registered nothing. Nobody is registered without your yes, and the
exit code is unchanged.
([#3028](https://github.com/mvschwarz/openrig/pull/3028))
- In the change's own tests, before a first team launches, the kernel operator
says which commands it will ask permission for and reuses a choice you've
already made. Otherwise it makes one offer: allow just the command families
your goal repeats, for this project only, applied on your yes. On a no, the
team's default stays and the offer isn't repeated. It hasn't been shown to
make a first team ask you fewer times. ([#3029](https://github.com/mvschwarz/openrig/pull/3029))
- A connected assistant (a hosted member; experimental and off by default) shows
whether it's checking in, against a cadence its roster entry states
(`check_in_minutes`, or `check_in_on_request: true`): checking in, overdue, no
check-in yet, on request, or unknown. `rig roster show` and `find` print it as
a Check-in line. It's a status only: work for a member that isn't checking in
still queues and rings as before. ([#3023](https://github.com/mvschwarz/openrig/pull/3023))
### Seats, handover and recovery
- A Claude seat stopped by a usage limit whose message states a reset time (for
example "resets Nov 10, 4pm") parks its pending work until then, instead of
being retried every few minutes. ([#2917](https://github.com/mvschwarz/openrig/pull/2917))
- A handover whose successor was launched but not ready says it may be running,
instead of "retry": look at the pane first. A handover also cleans up the
retiring occupant's own claims and jobs. ([#3003](https://github.com/mvschwarz/openrig/pull/3003), [#3024](https://github.com/mvschwarz/openrig/pull/3024))
- After `rig unclaim`, the guidance for an adopted session says to end its
process and its tmux session, and `rig seat stop`'s help matches. A fresh
launch after `rig unclaim` ended the server's last session reopens the server.
([#2996](https://github.com/mvschwarz/openrig/pull/2996), [#3006](https://github.com/mvschwarz/openrig/pull/3006), [#3014](https://github.com/mvschwarz/openrig/pull/3014), [#3009](https://github.com/mvschwarz/openrig/pull/3009))
- A handover whose successor was launched into the seat's own tmux session
can reclaim a claim left by a removed owner, or by an archived owner whose
latest session for that node is superseded, detached or exited; a live owner
still refuses.
When a seat
with no declared route can't be woken, the finding goes to the item's creator,
skipping a creator that is a terminal seat. ([#2869](https://github.com/mvschwarz/openrig/pull/2869), [#2987](https://github.com/mvschwarz/openrig/pull/2987), [#2995](https://github.com/mvschwarz/openrig/pull/2995))
### Fixes
- **Delivery:** Claude's auto-update failure footers, including one clipped form,
no longer hold a send to an idle Claude seat; an unrecognised wake result reads unknown, not
delivered; an ordinary one-time park wake is kept and retried
while its park is current and the failed attempt typed nothing into the seat
(an attempt whose effect is unknown needs checking, and repeating waits and
usage-limit expiry keep their own lifecycle); a `custody-verified:` note whose target is followed by a
period, comma or other closing punctuation now verifies it; the Pi runner pane keeps the operator's
draft out of the stream. ([#2948](https://github.com/mvschwarz/openrig/pull/2948), [#3016](https://github.com/mvschwarz/openrig/pull/3016), [#3011](https://github.com/mvschwarz/openrig/pull/3011), [#3038](https://github.com/mvschwarz/openrig/pull/3038), [#3004](https://github.com/mvschwarz/openrig/pull/3004), [#2842](https://github.com/mvschwarz/openrig/pull/2842))
- **Codex and Claude:** completed Codex 0.167 turns read idle, and unsupported
versions stay unknown; a usage-limit banner with a curly apostrophe is
detected; refocus bounds Codex context and records what it left out; an
unreadable Claude status-line cache gets its own reason. ([#2954](https://github.com/mvschwarz/openrig/pull/2954), [#2879](https://github.com/mvschwarz/openrig/pull/2879), [#2951](https://github.com/mvschwarz/openrig/pull/2951), [#2880](https://github.com/mvschwarz/openrig/pull/2880))
- **TUI and CLI:** instance rows are grouped by rig; for a quiet seat the
daemon explicitly reads as unknown, the list, explorer and agent-detail status
rows show unknown, not idle (screen motion still shows active, a daemon that
serves no activity keeps the screen fallback, and the topology graph is
unchanged); Feed times use the configured time zone; the
CLI doesn't call a daemon stopped when the shell can't see its process (a
sandbox), and says not to start another; ssh options are separated from the
target, and the generated attach command quotes the session name. ([#2857](https://github.com/mvschwarz/openrig/pull/2857), [#3012](https://github.com/mvschwarz/openrig/pull/3012), [#3022](https://github.com/mvschwarz/openrig/pull/3022), [#2913](https://github.com/mvschwarz/openrig/pull/2913), [#2973](https://github.com/mvschwarz/openrig/pull/2973), [#2971](https://github.com/mvschwarz/openrig/pull/2971))
- **Scope and workflows:** qualified slice reads and proof discovery are scoped
by mission; workflow spec reads are recorded across restarts; the spec library skips
synthetic alias entries. ([#2960](https://github.com/mvschwarz/openrig/pull/2960), [#2986](https://github.com/mvschwarz/openrig/pull/2986), [#2999](https://github.com/mvschwarz/openrig/pull/2999))
- **Guidance and plugins:** guidance cleanup in a repository's `AGENTS.md` or
`CLAUDE.md` removes redundant recognized copies of an OpenRig-managed block,
including after an editor rewrapped a marker, and keeps distinct edited
copies. A saved write record lets OpenRig identify and keep your edits; on a
fresh start, a differing block with no write record is refreshed to OpenRig's
text and named, while an exact resume or restore keeps it; a bundled plugin's files,
including a binary icon, are copied byte for byte; the plugins carry https
repository URLs and a PNG icon for Claude's plugin directory, and the Codex
manifests link the privacy policy and terms. ([#3020](https://github.com/mvschwarz/openrig/pull/3020), [#3025](https://github.com/mvschwarz/openrig/pull/3025), [#3021](https://github.com/mvschwarz/openrig/pull/3021), [#3064](https://github.com/mvschwarz/openrig/pull/3064))
- **Speed:** the daemon is much more responsive while it reads a project's
proof, which now yields between missions; current-session reads for the node inventory
use an index; the daemon's recorder and Linux clipboard discovery no longer
wait on the main thread.
([#2970](https://github.com/mvschwarz/openrig/pull/2970), [#2997](https://github.com/mvschwarz/openrig/pull/2997), [#3019](https://github.com/mvschwarz/openrig/pull/3019))
- **Docs:** what `rig seat clear-attention`'s check proves, how managed
compaction notices are routed, when the keyboard moves in herdr-app, a
complete periodic-reminder registration, and starting one stopped kernel seat
with `rig launch`. ([#2964](https://github.com/mvschwarz/openrig/pull/2964), [#2984](https://github.com/mvschwarz/openrig/pull/2984), [#2991](https://github.com/mvschwarz/openrig/pull/2991), [#3002](https://github.com/mvschwarz/openrig/pull/3002), [#3031](https://github.com/mvschwarz/openrig/pull/3031))
### Experimental
- **`rig network`** connects one local seat to a hub you already have.
Experimental, unsupported and at your own risk. The connector uses the MCP
SDK, which the installed package already included in 0.7.12. ([#2993](https://github.com/mvschwarz/openrig/pull/2993))
### Behaviour that changed
- **A runner's answer is confirmed to you.** Through 0.7.12 no note came back,
and the runner waited for its next read. ([#3001](https://github.com/mvschwarz/openrig/pull/3001))
- **A usage-limited Claude seat waits for its stated reset**; don't release it
by hand on a timer. **A failed handover may have left its successor
running**; look at the pane before retrying. ([#2917](https://github.com/mvschwarz/openrig/pull/2917), [#3003](https://github.com/mvschwarz/openrig/pull/3003))
- **Passive SSH host status reads `unknown`.** Routine host listings no longer
open a TCP connection to SSH hosts, because repeated probes closed without a
handshake can make OpenSSH block real logins for a while. Hosts that used to
read reachable now read unknown; `rig host doctor` still checks actively.
([#2979](https://github.com/mvschwarz/openrig/pull/2979))
- **`rig package install` leaves a guidance file alone when a recognized
managed block has no complete marker pair,** lists it under "Left as it is:" and installs the rest, instead
of appending a second copy. Launch and restore name such a file
(`guidance_block_markers_damaged`). ([#3020](https://github.com/mvschwarz/openrig/pull/3020))
### Known limits
- **Not in this release:** a Codex snapshot restore or `rig up --existing` can
write OpenRig's managed guidance into a tracked `AGENTS.md`, leaving the
worktree modified; check `git status` after either operation.
- **Not in this release:** a person who talks to the kernel operator first, with
no other agent setting OpenRig up, isn't offered registration. `rig up`,
`rig start` and `rig context` start the daemon without printing the offer
either. Register with `rig gateway human add`. While nobody is registered, a
later `rig daemon start` offers again, even after a no; nothing is registered
without your yes. ([#3028](https://github.com/mvschwarz/openrig/pull/3028), [#3041](https://github.com/mvschwarz/openrig/pull/3041) isn't in this release)
- **The hub connector isn't inert:** the daemon starts it, sweeps leftover
credential folders and schedules local rounds even with no binding; only the
pass to a hub is absent. Its migrations apply on upgrade. ([#2993](https://github.com/mvschwarz/openrig/pull/2993))
- **The recorder:** a queued begin record can be lost before the durable append,
and a stalled worker has no acknowledgement timeout. ([#3019](https://github.com/mvschwarz/openrig/pull/3019))
- **Speed and memory:** On one performance host, whole `rig queue create`
invocations had a median about 10.4% slower than 0.7.12 (about +29 ms). Send
latency stayed within the comparison's unchanged range. The cause remains
unidentified. The standard idle-memory comparison was inconclusive. A post-hoc
analysis of the same six runs found 7.9–8.6 MiB (4.2–5.3%) higher daemon RSS
across three matched idle windows, using the median of three arm medians per
version. The cause and steady-state behavior remain unestablished.
- **Draft-aware delivery ([#3076](https://github.com/mvschwarz/openrig/issues/3076)):** an automatic OpenRig notice can be left beside a
draft started during delivery. This also concerns notices admitted by
openrig-urgent and urgent-only modes. In the reproduced 0.7.12 Claude Code and
Codex cases, the person's draft remained intact and no Enter was sent, but
OpenRig's text stayed in the input. The guard and paste path are unchanged in
this cut; a native 0.7.13 reproduction has not run.
- **Native model pickers:** with a /model picker open, an ordinary send can act
on the picker instead of delivering the message. In 0.7.12 tests it confirmed
Claude Code's already-selected default and advanced Codex's model selection;
neither message reached the model. Close or deliberately resolve the picker
before ordinary delivery. The native 0.7.13 case has not run.
- **Codex hook review after an upgrade:** in one test whose Codex home already
held earlier hook approvals, `rig up --existing` stopped for hook review in
each Codex pane; approving the hooks resumed all three conversations. A
separate test of the same upgrade on a fresh Codex home, on another host,
restored without review. The cause of the difference is not established.
- **A first team with Codex installed but signed out:** a Claude user's starter
team includes a Codex reviewer that waits for a Codex sign-in, and you aren't
told beforehand. If Codex is installed, tell the person about the possible sign-in wait
before the team starts; signing in first was not tested as a remedy.
- **A first team's permission asks:** a command joined with `&&`, `;` or a pipe
still asks unless every part is allowed, and OpenRig's own lifecycle commands
still ask on Claude seats. ([#3029](https://github.com/mvschwarz/openrig/pull/3029))
- **Usage-limit parking** was tested with the limit message from `claude -p`. If
an interactive seat's limit report doesn't carry the message, the seat is
retried as before. A reset in the past or more than 8 days away is ignored.
([#2917](https://github.com/mvschwarz/openrig/pull/2917))
- **Handover:** two other failures can still say "retry" while a successor may
be running: a context delivery failure, and a Codex launch failure after an
update prompt wasn't dismissed. Look at the pane first. ([#3003](https://github.com/mvschwarz/openrig/pull/3003))
- **Answers:** when a receiving agent asks you back, it can stop at Claude
Code's own permission prompt, which you don't see. A receiving agent you
choose can still decline to act on a clear answer. A pairing requester's
description of itself is quoted for the receiving agent, but still shown
unquoted in the request's summary and the notices about it. The TUI's
one-line notice after you answer can clear within a frame. ([#3030](https://github.com/mvschwarz/openrig/pull/3030), [#3001](https://github.com/mvschwarz/openrig/pull/3001))
- **Proof reads** still pause briefly, and a whole read takes slightly longer.
Yielding isn't a hard bound on latency or a single atomic snapshot of the
proof. ([#2970](https://github.com/mvschwarz/openrig/pull/2970))
- **`rig down`** keeps no stored host or boot identity, doesn't guard against
another program running as you, and a daemon restart between losing the tmux
server and the stop wasn't exercised. ([#2962](https://github.com/mvschwarz/openrig/pull/2962))
- **Codex working counter:** a capture that doesn't name its pane keeps the old
comparison, a restart that keeps both the pane and its process id isn't seen,
and a leftover live frame can count once until it expires. ([#2980](https://github.com/mvschwarz/openrig/pull/2980))
- **Custom blocker IDs** explain the wait, but their progress gives no event
wake; the timer remains. ([#2983](https://github.com/mvschwarz/openrig/pull/2983))
- **Delivery:** delivery evidence records what was known, not that the agent read
the message, and events are best effort. A footer row OpenRig doesn't
recognize can still hold a delivery ([#2925](https://github.com/mvschwarz/openrig/issues/2925)), and a held message's full envelope
can stay held; clearing a draft doesn't deliver it ([#2515](https://github.com/mvschwarz/openrig/pull/2515)).
- **Runner permission answers** were run end to end with a real receiving agent
and the example runner, whose requesting agent was a stand-in; a model-driven
runner waiting on a person's answer hasn't been run. ([#2934](https://github.com/mvschwarz/openrig/pull/2934))
- **A receiving agent you choose** (`agents.operator_session`) that runs in an
explicit or auto permission mode gets no OpenRig allowance for
`rig host approve` or `rig host deny`, so Claude's review can refuse them.
- **An already-running tmux server** keeps its old environment, daemon
credentials included, until it restarts. ([#2850](https://github.com/mvschwarz/openrig/pull/2850))
- **herdr-app views** are one-shot; following isn't claimed. **Pull relay** needs
a connector that implements pull. ([#2744](https://github.com/mvschwarz/openrig/pull/2744), [#2844](https://github.com/mvschwarz/openrig/pull/2844))
- **From 0.7.12:** [its known limits](https://github.com/mvschwarz/openrig/releases/tag/v0.7.12)
still apply, except that [#2970](https://github.com/mvschwarz/openrig/pull/2970) and [#2948](https://github.com/mvschwarz/openrig/pull/2948) are now in this release,
runner answers are confirmed and reach a waiting runner at once ([#3001](https://github.com/mvschwarz/openrig/pull/3001)),
and `rig seat stop` no longer suggests `rig down` for an adopted session
([#3006](https://github.com/mvschwarz/openrig/pull/3006)). They weren't re-checked for this release unless named here.
### Credits
Thanks to @Aummadour, @Kayhusk, @Coder8124, @DeryFerd, @EZotoff, @hgreene624,
@cavalcanticampos, @ziadeh, @dajiaohuang and @billbenetti for merged
contributions. Thanks also for the reports behind these fixes: @jamesloosli
([#2879](https://github.com/mvschwarz/openrig/pull/2879)), @Kayhusk ([#2880](https://github.com/mvschwarz/openrig/pull/2880) and [#2951](https://github.com/mvschwarz/openrig/pull/2951)), @CaptObvious ([#2948](https://github.com/mvschwarz/openrig/pull/2948) and
[#3016](https://github.com/mvschwarz/openrig/pull/3016)), @alperta ([#2917](https://github.com/mvschwarz/openrig/pull/2917)), @ziadeh ([#2960](https://github.com/mvschwarz/openrig/pull/2960)) and @todd-dhango ([#2984](https://github.com/mvschwarz/openrig/pull/2984)).
## [0.7.12]
OpenRig 0.7.12 is a patch for people running their own agent teams, cut from
@@ -82,9 +82,10 @@ optional `evidence` (last-N pane lines, flowed through to
`RestoreNodeResult.attentionEvidence` for `attention_required` outcomes,
`:99–102`). This is the honest-failure shape, not a smoothed optional `error`.
Readiness has its own attention codes (`runtime-adapter.ts:74–87`):
Readiness has its own attention codes (`ATTENTION_REQUIRED_READINESS_CODES` in `runtime-adapter.ts`):
`trust_gate`, `hook_trust_gate`, `update_gate`, `login_required`, `mcp_gate`,
`bypass_consent_gate`, `codex_auth_refusal` and `codex_client_incompatible`.
`bypass_consent_gate`, `claude_resume_selection_prompt`, `claude_gated_grants_gate`,
`codex_auth_refusal` and `codex_client_incompatible`.
When `checkReady` reports one, the readiness wait returns at once and startup
ends `attention_required`.
@@ -476,7 +477,8 @@ command + pane content and returns one of four honest statuses
conversation"; it is *distinct* from `inconclusive` and `failed` (comment
`:4–6`).
Other codes include `bypass_consent_gate`, `mcp_gate`, `login_required` and
Other codes include `bypass_consent_gate`, `claude_gated_grants_gate` (the
"gated grants" trust check, which is never auto-driven), `mcp_gate`, `login_required` and
`returned_to_shell` for Claude, and `codex_client_incompatible`,
`no_saved_session`, `codex_auth_refusal` and `model_selection_gate` for Codex;
an unknown runtime gets `unsupported_runtime`. For Claude, `assessManagedProbe`
+13 -4
View File
@@ -35,8 +35,17 @@ command. `rig ps --nodes` shows it under "Startup details (<seat>)", and
The attention codes that stop startup this way are `trust_gate`,
`hook_trust_gate`, `update_gate`, `login_required`, `mcp_gate`,
`bypass_consent_gate`, `codex_auth_refusal` and `codex_client_incompatible`.
`bypass_consent_gate`, `claude_resume_selection_prompt`,
`claude_gated_grants_gate`, `codex_auth_refusal` and `codex_client_incompatible`.
They are recognized from each harness's English prompt text.
`claude_gated_grants_gate` is Claude Code's workspace trust check that warns "This folder
pre-approves N tool permissions" (from the folder's `.claude/settings.json`): OpenRig never
answers it, not even with `recovery.auto_drive_provider_prompts`, because its default choice
declines those permissions (or exits) and approving them is your call. With that setting on,
the plain workspace trust prompt is answered only when its options are exactly "No, exit" and
"Yes, I trust this folder": Claude Code 2.1.322 opens it on "No, exit", so OpenRig moves the
selection down once and presses Enter only after it reads the focus on "Yes". Any other option
set, a prompt drawn without a cursor or a focus that does not reach "Yes" gets no confirmation.
## Continue a Codex fork whose child ID arrived late
@@ -414,10 +423,10 @@ Each startup file and action specifies when it applies:
- a launch replaces it, as launches always did, and names it (`guidance_block_refreshed_unrecorded`);
- an exact resume or a handover leaves it, and names it as possibly stale (`guidance_block_may_be_stale`).
**A file keeps one copy of each block.**
**A file keeps one copy of each distinct block text, and tidying the copies never removes a text you wrote.**
- **Touched markers:** a marker an editor or formatter rewrapped, with spaces or line breaks inside the comment, still reads as its block, and the next write puts it back in OpenRig's form.
- **Collected copies:** they're reduced to the first. Beside a copy you edited, OpenRig's own unedited copies and exact repeats are removed, and every different edited copy stays (`guidance_block_copies_removed`).
- **A marker that lost its pair:** OpenRig can't tell where that block starts or ends, so it adds no copy beside it and names it (`guidance_block_markers_damaged`). Put back the missing marker or remove the partial block, and OpenRig's next write keeps one block. `rig package install` leaves such a file as it is, names it in its result (`notes`), and installs the rest. A marker without its pair beside a complete block is named too (`guidance_block_marker_unpaired`), and the block is written.
- **Collected copies:** a copy that repeats an earlier one exactly is removed. Beside a copy you edited, OpenRig's own unedited copies are removed too, and every different edited copy stays (`guidance_block_copies_removed`).
- **A marker that lost its pair:** OpenRig can't tell where that block starts or ends, so it adds no copy beside it and names it (`guidance_block_markers_damaged`). Put back the missing marker or remove the partial block, and OpenRig's next write treats that block like any other. `rig package install` leaves such a file as it is, names it in its result (`notes`), and installs the rest. A marker without its pair beside a complete block is named too (`guidance_block_marker_unpaired`), and the block is written.
An exact resume doesn't type anything into the resumed conversation. So there, the restore result names the block (`guidanceNotes`), but the seat isn't told.
+2 -1
View File
@@ -202,7 +202,8 @@ LIFECYCLE); see the
its startup context is still pending for `rig seat continue`.
- **Oriented:** `verified`, `missing`, `rejected`, `n-a`, from the startup proof.
- **Attention codes:** `trust_gate`, `hook_trust_gate`, `update_gate`, `login_required`,
`mcp_gate`, `bypass_consent_gate`, `codex_auth_refusal`, `codex_client_incompatible`.
`mcp_gate`, `bypass_consent_gate`, `claude_resume_selection_prompt`,
`claude_gated_grants_gate`, `codex_auth_refusal`, `codex_client_incompatible`.
- **Restore outcome:** `resumed`, `fresh-primed`, `awaiting-decision`, `attention_required`,
`failed` (plus `rebuilt`, `operator_recovered` and the legacy `fresh`). A seat joined with
`rig attach` as an external CLI reads `left_attached`: restore leaves it as it is.
+3 -1
View File
@@ -141,7 +141,9 @@ reason when it's unknown); `rig roster show` and `find` show it as `Check-in:`,
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.
daemon, it says check-in is unavailable instead. Its `--json` output is unchanged. The TUI's
instance and rig tables list them the same way after their seats, with times in the viewer's zone; when the list can't be read,
they say check-in is unavailable, as `rig ps` does.
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.
+2
View File
@@ -8,6 +8,8 @@ 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.
**The network connector is experimental and unsupported.** Use it only if you choose to, at your own risk.
## 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
+7 -5
View File
@@ -24,7 +24,7 @@ A queue row is erased in one of two ways:
- events whose payload names it;
- its mission-control audit rows.
**Copies held with someone else go only when they're the owner's.** These are outbox and inbox entries that point at the row or wake for it, and stream reader actions and dispositions that name it (including `duplicate_of`). For account deletion, the owner is the account: both of a copy's sessions must be members. Otherwise the owner is the row's own source and destination. Any other copy is kept and listed under `keptCopies`:
**Copies held with someone else go only when they're the owner's.** These are outbox and inbox entries that point at the row or wake for it, and stream reader actions and dispositions that name it (including `duplicate_of`). For account deletion, the owner is the account: both of a copy's sessions must be members. Otherwise the owner is the row's own source and destination. OpenRig's own sessions (`daemon@kernel`, and any session starting `system:`), which send its wakes and notices, aren't counted when a copy has another session, so OpenRig's wake to the owner is the owner's. Any other copy is kept and listed under `keptCopies`:
- `mixed`: one of its sessions is the owner's;
- `foreign`: none of them are.
@@ -36,7 +36,7 @@ Name exactly one.
| Scope | Erases | Action |
|---|---|---|
| `--members <file>` | Account deletion. Every row whose source and destination are both in the file, in any state, open work included. Add `--rig <id>` for the account rig's own records | delete |
| `--members <file>` | Account deletion. Every row whose source and destination are both in the file, or one in the file and the other OpenRig's own session, in any state, open work included. Add `--rig <id>` for the account rig's own records | delete |
| `--ids <file>` | Exactly the listed rows. A report's `qitems` entries, or a ledger's lines, keep each entry's own action. A ledger's entries are replayed only for the batches that committed (below) | `--action delete` (default for plain ids) or `--action scrub` |
| `--routine` | Closed rows past this daemon's retention windows (below) | scrub, then delete |
@@ -44,8 +44,10 @@ A file is one entry per line (blank lines and `#` comments are skipped; a line s
**Account deletion is exact.**
- The members file is the account's recorded membership: the exact session names of its seats, including departed ones. List every address form the account used, such as a host-suffixed form. Names are compared as given, never by pattern, so a row addressed through an unlisted form is neither erased nor reported.
- **Mixed rows:** a row with exactly one member endpoint is reported under `mixed` (with which endpoint is the member) and left untouched. Deciding who owns it is a separate decision. A row rerouted out of the account while the run is under way (by a fallback, say) is kept too, and reported as `changed-during-run`.
- **After the rows:** account deletion also removes outbox and inbox entries between two members that no row owns, and the members' stream items. An entry with one member endpoint, or a stream item something still references, is counted and left.
- **OpenRig's own sessions:** `daemon@kernel` and any `system:` session send OpenRig's own wakes and notices, such as the wake for a sweep finding, a wake escalation or a health finding. They belong to no account, so a row or entry between one of them and a member is the member's and is erased. One with no member endpoint, such as an OpenRig wake to another account's seat or an entry between two of OpenRig's own sessions, is never touched.
- **Mixed rows:** a row with one member endpoint and the other outside the account is reported under `mixed` (with which endpoint is the member) and left untouched. Deciding who owns it is a separate decision. A row rerouted out of the account while the run is under way (by a fallback, say) is kept too, and reported as `changed-during-run`.
- **After the rows:** account deletion also removes outbox and inbox entries that no row owns between two members, or between a member and OpenRig's own session, and the members' stream items. An entry with one member endpoint and the other outside the account, or a stream item something still references, is counted and left.
- **Runs on earlier versions** kept OpenRig's wake for a row they erased (as a mixed copy, then a mixed entry) and reported OpenRig's rows to a member as mixed. Rerunning the same command removes them.
**The account's rig.** A rig's own records outlive the rig. Events are kept past rig and node deletion by design, and snapshots, node and seat records and watchdog jobs have no key that cascades. `--rig <id>`, given with `--members`, erases them:
- the rig's events, including those of its nodes;
@@ -94,7 +96,7 @@ The command prints one JSON report (`--json` makes it a single line):
| `clean` | `complete`, and nothing was left: no `mixed` rows, mixed `keptCopies`, `gaps`, `unreadableEvents`, left-over entries, or rig records left or unknown. Only a clean report means the scope is fully erased. It's about this run's scope: a routine or members run's `clean` isn't affected by the ledger's other batches, and only a replay (`--ids` with a ledger) reports a batch it can't show committed, as the gap `ledger-unresolved` |
| `error` | why the run stopped (`stage` and `message`). Everything listed in `qitems` was committed before it; the command exits 2 |
| `qitems` | each row erased (or that would be), with its `action` and `state` |
| `mixed` | members scope: rows with one member endpoint, left untouched |
| `mixed` | members scope: rows with one member endpoint and the other outside the account, left untouched |
| `keptCopies` | copies of erased rows held with someone else, kept: `table`, `id`, `qitemId`, `ownership` (`mixed` or `foreign`) |
| `gaps` | rows not erased and why: `workflow-reference`; `not-found` for an id to scrub that doesn't exist; `changed-during-run` for a row that no longer qualified when its batch ran (reopened, rerouted out of the account, or written to so it left its window) or an absent id created since selection; `unreadable-event` for a row an unreadable event names; `ledger-unresolved` for a replayed entry whose batch can't be shown to have committed |
| `skipped` | ids scope, a ledger replay: entries whose batch rolled back, with the batch id; not replayed |
+1 -1
View File
@@ -76,7 +76,7 @@ Keys:
health.context_pressure.* context-pressure warning/critical percentages (defaults 95/99)
files.allowlist name:/abs/path,name:/abs/path
progress.scan_roots name:/abs/path,name:/abs/path
ui.timezone TUI IANA timezone (default America/Los_Angeles; reopen TUI after changing)
ui.timezone IANA timezone for the TUI's times, the Feed's included (default America/Los_Angeles; reopen TUI after changing)
ui.enabled serve the web UI and its terminal WebSocket (default off; restart the daemon)
ui.preview.* refresh_interval_seconds, max_pins, default_lines
ui.terminal.max_live_terminals
+3 -1
View File
@@ -142,7 +142,9 @@ const LONG_RUNNING_TIMEOUT_MS = 45_000;
export function downCommand(depsOverride?: DownDeps): Command {
const cmd = new Command("down").description("Tear down a rig")
.addHelpText("after", `
rig down stops every agent in the rig: their sessions end, and any work in progress stops with them.
rig down stops every agent OpenRig started in the rig: their sessions end, and any work in progress stops
with them. For a community harness only its pane stops: its own processes may keep running, and rig down
names it. A session OpenRig didn't start (adopted, bound or discovered) is left running, and rig down names it.
Before running it, check who is working (rig ps --nodes --rig <rig>) and that the person asked for it;
don't stop a team you didn't start unless asked. OpenRig snapshots the rig first (best-effort), and
rig up <rig> --existing brings it back, resuming each seat's conversation where its harness allows. With
+2 -2
View File
@@ -54,7 +54,7 @@ function line(b: Binding): string {
* another OpenRig hub), see where each connection stands, and disconnect one. */
export function networkCommand(depsOverride?: NetworkDeps): Command {
const cmd = new Command("network")
.description("Connect selected local seats to a remote hub, see their status, and disconnect them");
.description("Connect selected local seats to a remote hub, see their status, and disconnect them. Experimental and unsupported: use it only if you choose to, at your own risk");
const getDeps = (): NetworkDeps => depsOverride ?? { lifecycleDeps: realDeps(), clientFactory: (url: string) => new DaemonClient(url) };
const client = async () => {
@@ -157,7 +157,7 @@ export function networkCommand(depsOverride?: NetworkDeps): Command {
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 `Disconnected ${line(b)}\nRemove the participant on the hub too: until then, the hub still lists it.`;
});
});
+4 -2
View File
@@ -2189,8 +2189,10 @@ Examples:
"Name exactly one scope. What each one erases:",
" --members every row whose source and destination are both members, in any state, deleted with its transitions,",
" outbox and inbox copies, stream actions, events and audit rows; then member-to-member outbox and inbox",
" entries no row owns, and the members' stream items. A row with one member endpoint is reported under",
" mixed and left untouched. With --rig, also the rig's own events, snapshots and node and seat records.",
" entries no row owns, and the members' stream items. OpenRig's own sessions (daemon@kernel, system:*)",
" belong to no account, so its wakes and notices to a member are erased too. A row with one member",
" endpoint and the other outside the account is reported under mixed and left untouched. With --rig,",
" also the rig's own events, snapshots and node and seat records.",
" --ids the listed rows, deleted or scrubbed (a report's qitems entries keep their action); a deleted id",
" that's already gone keeps (or regains) its id marker.",
" --routine closed rows (done, canceled, denied, handed-off) past the windows, aged from when they closed.",
+2 -2
View File
@@ -1022,8 +1022,8 @@ Example:
}
if (opts.json) return;
const state = res.data.state;
console.log(state === "answered" ? `Decided: ${res.data.optionId}. The runner gives it to its agent at its next read.`
: state === "refused" ? "Decided: refused. The runner gives its agent the refusal at its next read."
console.log(state === "answered" ? `Decided: ${res.data.optionId}. A runner waiting on the request gets it now; one that isn't gets it at its next read.`
: state === "refused" ? "Decided: refused. A runner waiting on the request gets the refusal now; one that isn't gets it at its next read."
: `Nothing was decided: the request is ${state}.`);
});
@@ -16,7 +16,7 @@ import type {
} from "../domain/runtime-adapter.js";
import { resolveConcreteHint } from "../domain/runtime-adapter.js";
import type { ProjectionPlan, ProjectionEntry } from "../domain/projection-planner.js";
import { assessNativeResumeProbe, hasClaudeDrawnInput } from "../domain/native-resume-probe.js";
import { assessNativeResumeProbe, claudeTrustPromptFocus, hasClaudeDrawnInput } from "../domain/native-resume-probe.js";
import { resumeProbeEvidence } from "../domain/native-resume-probe-evidence.js";
import { resolveReadinessTimeoutMs } from "../domain/readiness-timeout.js";
import { subtreeNamesClaudeExecutable, claudeCommandSessionToken, listNativeProcesses, observeClaudeDelivery, observeClaudePaneProcess, observeClaudePaneRuntime, observeCodexPaneProcess, verifyClaudePaneProcess, verifyCodexPaneProcess, verifyPaneIdleShell, type ClaudeLaunchedProcess, type NativeProcessLister } from "../domain/native-process-lineage.js";
@@ -709,6 +709,10 @@ export class ClaudeCodeAdapter implements RuntimeAdapter {
const checkEvery = 5;
let attempts = windowAttempts;
let slowStart = false;
// #2820 item 2: the trust prompt's selection was moved from "No, exit" (once: its two options wrap), and the prompt
// was confirmed (once: a frame drawn before Claude took the Enter still shows the prompt).
let trustMoved = false;
let trustEntered = false;
for (let attempt = 0; attempt < attempts; attempt++) {
const paneCommand = await this.tmux.getPaneCommand(tmuxSession);
@@ -749,9 +753,25 @@ export class ClaudeCodeAdapter implements RuntimeAdapter {
slowStart = false;
break;
}
const enterResult = await this.tmux.sendKeys(tmuxSession, ["Enter"]);
if (!enterResult.ok) {
return { ok: false, error: `Claude trust prompt auto-drive failed: ${enterResult.message}`,
// #2820 item 2: Enter confirms the focused option, and Claude Code 2.1.322 opens this prompt on "No, exit". So
// Enter goes once, and only with the focus read on "Yes, I trust this folder" of the plain prompt's two options.
// On "No, exit" the selection moves down once (the two options wrap: a second Down would go back) and the next
// polls wait to see the focus on "Yes". A screen with no key to send (another option set, no cursor, a focus
// that never reaches "Yes") gets no confirmation; in the longer wait it ends at once, as without the auto-drive.
const focus = claudeTrustPromptFocus(paneContent);
const key = focus === "yes" && !trustEntered ? "Enter" : focus === "no" && !trustMoved ? "Down" : null;
if (!key) {
if (slowStart && !trustMoved && !trustEntered) {
slowStart = false;
break;
}
await this.sleep(200);
continue;
}
if (key === "Enter") trustEntered = true; else trustMoved = true;
const keyResult = await this.tmux.sendKeys(tmuxSession, [key]);
if (!keyResult.ok) {
return { ok: false, error: `Claude trust prompt auto-drive failed: ${keyResult.message}`,
probe: await resumeProbeEvidence(probe, paneContent, this.tmux, tmuxSession) };
}
await this.sleep(200);
@@ -136,6 +136,24 @@ export function assessNativeResumeProbe(
detail: "Claude is at a resume-selection prompt; an operator must choose the conversation to continue.",
};
}
// #2820 item 2: the gated-grants backstop is never answered by OpenRig (not even with
// recovery.auto_drive_provider_prompts): its default choice declines the folder's pre-approved tool permissions or
// exits, and approving them is the person's call. Checked before the plain trust prompt, whose texts it shares.
const gatedGrants = claudeGatedGrantsPrompt(paneContent);
if (gatedGrants === "live") {
return {
status: "attention_required",
code: "claude_gated_grants_gate",
detail: `Claude is at its workspace trust check that warns "This folder pre-approves N tool permissions" (from the folder's .claude/settings.json)${focusedChoice(paneContent)}. Review and choose in the seat's pane. OpenRig does not approve or bypass this review. No input was sent.`,
};
}
if (gatedGrants === "partial") {
return {
status: "inconclusive",
code: "awaiting_runtime",
detail: "Claude is still drawing its workspace trust check for the folder's pre-approved tool permissions.",
};
}
if (looksLikeClaudeTrustPrompt(paneContent)) {
return {
status: "inconclusive",
@@ -343,9 +361,112 @@ function looksLikeClaudeBypassConsentPrompt(paneContent: string): boolean {
return /\b(?:in|running in) Bypass Permissions mode\./.test(lines.slice(0, -3).join(" ").replace(/\s+/g, " "));
}
// Claude Code's "gated grants" backstop (2.1.319+, #2820 item 2). Its marks, which the plain workspace trust prompt
// lacks: the warning that the folder's .claude/settings.json pre-approves tool permissions, and the option that
// declines them. Its default choice declines them ("No, continue without these permissions") or exits ("No, exit").
// The marks are read on the whitespace-joined screen too, so a row that a narrow pane wraps still counts.
const CLAUDE_GATED_GRANTS_MARK = /This folder pre-approves \d+ tool permissions?\b|No, continue without these permissions/;
// One row of the backstop's marks, or of a part of one that a narrow pane wrapped.
const CLAUDE_GATED_GRANTS_MARK_ROW = /This folder pre-approves\b|No, continue without\b|without these permissions\b/;
const CLAUDE_TRUST_FOOTER = "Enter to confirm · Esc to cancel";
const CLAUDE_TRUST_YES = "Yes, I trust this folder";
const CLAUDE_TRUST_EXIT = "No, exit";
// An option row of Claude's select: an optional cursor (❯ or ›), an optional "1." and a "Yes, …" or "No, …" label.
const CLAUDE_TRUST_OPTION_ROW = /^\s*([❯›]\s*)?(?:\d+\.\s+)?((?:Yes|No), .*?)\s*$/;
/** The gated-grants backstop on Claude's current screen (claudeCurrentRows): "live" when it is complete ("Enter to
* confirm · Esc to cancel" is the last drawn row, with "Yes, I trust this folder" above it); "partial" while it is
* still being drawn; null when the current screen has none. A backstop left in the scrollback above a session that
* started is not current. The "Accessing workspace:" heading is not required: a long permission list can push it
* out of the capture. */
function claudeGatedGrantsPrompt(paneContent: string): "live" | "partial" | null {
const rows = claudeCurrentRows(paneContent);
if (!hasClaudeGatedGrantsMark(rows)) return null;
const mark = rows.map(row => CLAUDE_GATED_GRANTS_MARK_ROW.test(row)).lastIndexOf(true);
const drawn = rows.slice(Math.max(mark, 0)).filter(row => row.trim()).map(row => row.trim());
if (drawn.at(-1) !== CLAUDE_TRUST_FOOTER) return "partial";
return drawn.some(row => CLAUDE_TRUST_OPTION_ROW.exec(row)?.[2] === CLAUDE_TRUST_YES) ? "live" : "partial";
}
/** A mark of the gated-grants backstop in these rows: on their whitespace-joined text, so a row that a narrow pane
* wrapped still counts, or on a single row, so a warning still being drawn ("This folder pre-approves 2 tool" before
* the next row) counts too. */
function hasClaudeGatedGrantsMark(rows: string[]): boolean {
return CLAUDE_GATED_GRANTS_MARK.test(rows.join(" ").replace(/\s+/g, " "))
|| rows.some(row => CLAUDE_GATED_GRANTS_MARK_ROW.test(row));
}
/** The rows Claude drew after its last own element (input frame, header or reply): the screen a prompt is on now.
* Text above a session that started (a scrollback, a reply quoting a prompt's words) never decides what is current,
* and neither does a draft in the input box: an input frame ends at its closing rule. */
function claudeCurrentRows(paneContent: string): string[] {
const rows = claudeWithoutDrafts(paneContent.trimEnd().split(/\r?\n/));
let current = rows;
for (let at = rows.length - 1; at >= 0; at--) {
if (!claudeDrawnAfter(rows.slice(at))) continue;
const framed = CLAUDE_INPUT_RULE.test(rows[at]!) && /^\s*❯/.test(rows[at + 1] ?? "");
const closing = framed ? rows.findIndex((row, index) => index > at + 1 && CLAUDE_INPUT_RULE.test(row)) : -1;
current = rows.slice((closing >= 0 ? closing : at) + 1);
break;
}
// An input frame still being drawn (its opening rule and the ❯ row, no closing rule yet) holds a draft, not a dialog.
const opening = current.findIndex((row, index) => CLAUDE_INPUT_RULE.test(row) && /^\s*❯/.test(current[index + 1] ?? ""));
return opening >= 0 ? current.slice(0, opening) : current;
}
/** These rows with the text of every draft in Claude's input frames blanked (the ❯ kept), so a rule, a reply or a
* header pasted into a draft never reads as Claude's own UI. Claude draws the frame's rules from column 0 and a
* draft's continuation rows indented under the ❯, so a frame opens at a column-0 rule over the ❯ row and the first
* column-0 rule after it closes the frame; a frame with no closing rule yet holds a draft to the end. A frame quoted
* in a reply is indented like the reply: it blanks nothing. */
function claudeWithoutDrafts(rows: string[]): string[] {
const shown = [...rows];
for (let at = 0; at < rows.length; at++) {
if (!CLAUDE_FRAME_RULE.test(rows[at]!) || !/^\s*❯/.test(rows[at + 1] ?? "")) continue;
const closing = rows.findIndex((row, index) => index > at + 1 && CLAUDE_FRAME_RULE.test(row));
const end = closing >= 0 ? closing : rows.length;
shown[at + 1] = rows[at + 1]!.replace(/❯.*$/, "❯");
for (let index = at + 2; index < end; index++) shown[index] = "";
at = end - 1;
}
return shown;
}
/** ", with \"<label>\" highlighted" for the detail of the gated-grants gate, or nothing when no option is focused. */
function focusedChoice(paneContent: string): string {
const label = claudeFocusedOption(paneContent);
return label ? `, with "${label}" highlighted` : "";
}
/** The label of the focused option on Claude's current screen (the row with ❯ or ›), if one is drawn. */
function claudeFocusedOption(paneContent: string): string | null {
const focused = claudeCurrentRows(paneContent).map(row => CLAUDE_TRUST_OPTION_ROW.exec(row)).filter(match => match?.[1]);
return focused.at(-1)?.[2] ?? null;
}
/** The focus of Claude's plain workspace trust prompt (#2820 item 2), read from its last 12 drawn rows. An allowlist:
* "yes" or "no" only when the prompt's options are exactly "No, exit" and "Yes, I trust this folder" (in either
* order, numbered or not) and one of them carries the cursor (❯ or ›): "yes" on "Yes, I trust this folder", "no" on
* "No, exit" (Claude Code 2.1.322 opens the plain prompt there). Anything else is "unknown": another option set (the
* gated-grants backstop's "No, continue without these permissions" included), no cursor, or more than one. */
export function claudeTrustPromptFocus(paneContent: string): "yes" | "no" | "unknown" {
const rows = paneContent.trimEnd().split(/\r?\n/).filter(row => row.trim()).slice(-12);
const options = rows.map(row => CLAUDE_TRUST_OPTION_ROW.exec(row)).filter(match => match !== null);
const labels = options.map(match => match[2]);
if (labels.length !== 2 || !labels.includes(CLAUDE_TRUST_YES) || !labels.includes(CLAUDE_TRUST_EXIT)) return "unknown";
const focused = options.filter(match => match[1]);
if (focused.length !== 1) return "unknown";
return focused[0]![2] === CLAUDE_TRUST_YES ? "yes" : "no";
}
function looksLikeClaudeTrustPrompt(paneContent: string): boolean {
return paneContent.includes("Accessing workspace:")
&& paneContent.includes("Yes, I trust this folder");
// #2820 item 2: read on Claude's current screen only, and a screen with the backstop's marks is never the plain
// trust prompt, even still drawn: pressing Enter on it would decline the folder's grants or exit.
const current = claudeCurrentRows(paneContent);
const text = current.join("\n");
return text.includes("Accessing workspace:")
&& text.includes("Yes, I trust this folder")
&& !hasClaudeGatedGrantsMark(current);
}
// Claude's resume-selection prompt appears when `claude --resume` finds multiple
@@ -428,6 +549,8 @@ function claudeDrawnAfter(rows: string[]): boolean {
// On a named session Claude labels the frame's top rule (`─────…── probe-claude@rig ─`), so a rule may carry text after a space.
const CLAUDE_INPUT_RULE = /^\s*─{3,}(?:\s.*)?$/;
// The same rule drawn from column 0, as Claude draws its frame: a rule indented like a draft's row is the draft's.
const CLAUDE_FRAME_RULE = /^─{3,}(?:\s.*)?$/;
/** Claude's input frame: a rule, the ❯ row directly under it, and another rule below. A composer holding a draft that
* starts with "1." looks like a numbered option row; the frame is what tells them apart. */
+36 -20
View File
@@ -1,6 +1,7 @@
import { createHash, randomUUID } from "node:crypto";
import { appendFileSync, closeSync, openSync, readSync, statSync } from "node:fs";
import type Database from "better-sqlite3";
import { isOpenRigSender, OPENRIG_SENDER } from "../lib/pane-envelope.js";
/**
* Queue erasure: the maintained way to remove queue content, for closed-work retention and account deletion on a
@@ -13,11 +14,13 @@ import type Database from "better-sqlite3";
* The row's own copies follow it: its transitions, live and archived; events whose payload names it; its
* mission-control audit rows. Copies another party holds (outbox and inbox entries, stream reader actions and
* dispositions) go only when they're the owner's: both endpoints the account's (members scope) or the row's own
* (other scopes). Others are kept and reported.
* (other scopes). Others are kept and reported. OpenRig's own sessions (`daemon@kernel`, `system:*`), which send its
* wakes and notices, are no one's: a row, copy or entry is judged by its other sessions, and needs one of them.
*
* Scope is exact. Account deletion takes the account's recorded membership (exact session names): a row whose two
* endpoints are both members is deleted, whatever its state; a row with one member endpoint is reported as mixed and
* left untouched. Named with the account's rig, it also removes the rig's own records that outlive the rig. Routine
* Scope is exact. Account deletion takes the account's recorded membership (exact session names): a row between two
* members, or between a member and OpenRig, is deleted, whatever its state; a row with one member endpoint and the
* other outside the account is reported as mixed and left untouched. Named with the account's rig, it also removes
* the rig's own records that outlive the rig. Routine
* retention touches only closed rows (done, canceled, denied, handed-off; never failed or open work), aged from the
* start of their final closed state. A row a workflow still references is reported, never erased.
*
@@ -95,7 +98,8 @@ export interface EraseReport {
error?: { stage: Stage; message: string };
/** rows erased (applied, committed) or that would be (dry run) */
qitems: Array<{ qitemId: string; action: EraseAction; state: string }>;
/** members scope: rows with exactly one member endpoint, left untouched */
/** members scope: rows with one member endpoint and the other outside the account (OpenRig's own isn't), left
* untouched */
mixed: Array<{ qitemId: string; memberEndpoint: "source" | "destination" }>;
/** rows not erased, and why: a workflow references them; (ids scope) no such row to scrub; the row changed after
* selection so it no longer qualifies (reopened, rerouted out of the account, written to out of its window, or an
@@ -116,7 +120,8 @@ export interface EraseReport {
unreadableEvents: Array<{ seq: number; qitemIds: string[] }>;
/** copies erased with the rows, or that would be */
linked: { transitions: number; archivedTransitions: number; outbox: number; inbox: number; events: number; streamActions: number; missionControl: number };
/** members scope: entries between members that no queue row owns; mixed ones are counted and left */
/** members scope: entries no queue row owns between members, or a member and OpenRig; mixed ones are counted and
* left */
unlinked?: { outbox: number; inbox: number; streamItems: number; mixedEntries: number; referencedStreamItems: number };
/** members scope with rig: whether the rig was found and verified, its records erased and left per table, the
* tables whose records can't be counted (an unverified removed rig), and when its erasure completed */
@@ -425,6 +430,9 @@ export async function eraseQueue(db: Database.Database, opts: EraseOptions): Pro
const ledgerReason = (action: EraseAction) => scope.kind === "routine" && action === "scrub" ? "retention-content" : reason;
const memberSet = new Set(scope.kind === "members" ? scope.members : []);
const members = JSON.stringify([...memberSet]);
// Members scope: a row is the account's when one endpoint is a member and the other is a member or OpenRig's own.
const accountRow = (source: string, destination: string) => (memberSet.has(source) || memberSet.has(destination))
&& (memberSet.has(source) || isOpenRigSender(source)) && (memberSet.has(destination) || isOpenRigSender(destination));
// A ledger replay applies only the batches that committed, by their own commit line or this database's record of
// them. A rolled-back batch is skipped; one that is neither is reported and never replayed.
let listed = scope.kind === "ids" ? scope.entries : [];
@@ -488,10 +496,8 @@ export async function eraseQueue(db: Database.Database, opts: EraseOptions): Pro
ORDER BY qitem_id LIMIT @limit`).all({ members, after, limit: batchSize }) as Array<Omit<Candidate, "action">>;
const rows: Candidate[] = [];
for (const row of found) {
const fromMember = memberSet.has(row.source);
const toMember = memberSet.has(row.destination);
if (fromMember && toMember) rows.push({ ...row, action: "delete" });
else report.mixed.push({ qitemId: row.qitemId, memberEndpoint: fromMember ? "source" : "destination" });
if (accountRow(row.source, row.destination)) rows.push({ ...row, action: "delete" });
else report.mixed.push({ qitemId: row.qitemId, memberEndpoint: memberSet.has(row.source) ? "source" : "destination" });
}
return { rows, last: found.at(-1)?.qitemId ?? null, seen: found.length };
}
@@ -511,10 +517,14 @@ export async function eraseQueue(db: Database.Database, opts: EraseOptions): Pro
// Whose copies these are: the account's (members scope), or the row's own participants (other scopes).
const ownerOf = (candidate: Candidate) => scope.kind === "members" ? memberSet : new Set([candidate.source, candidate.destination]);
// OpenRig's own sessions (its wake for the row, say) aren't counted when the copy has any other: an OpenRig wake to
// the owner is the owner's, and one to no owner is foreign.
const ownership = (copy: Copy, owners: Set<string>): "owned" | "mixed" | "foreign" => {
const sessions = copy.sessions.filter((session): session is string => session !== null);
const owned = sessions.filter((session) => owners.has(session)).length;
return owned === sessions.length ? "owned" : owned > 0 ? "mixed" : "foreign";
const others = sessions.filter((session) => !isOpenRigSender(session));
const counted = others.length > 0 ? others : sessions;
const owned = counted.filter((session) => owners.has(session)).length;
return owned === counted.length ? "owned" : owned > 0 ? "mixed" : "foreign";
};
// Stream actions and dispositions this run deletes, so the unlinked pass plans on the same references either way.
const plannedActions: string[] = [];
@@ -635,7 +645,7 @@ export async function eraseQueue(db: Database.Database, opts: EraseOptions): Pro
else plan.dropped.push({ code: "changed-during-run", qitemId: candidate.qitemId });
} else if (referenced.has(candidate.qitemId)) {
plan.dropped.push({ code: "workflow-reference", qitemId: candidate.qitemId });
} else if (scope.kind === "members" && !(memberSet.has(now.source) && memberSet.has(now.destination))) {
} else if (scope.kind === "members" && !accountRow(now.source, now.destination)) {
// Rerouted since selection (a fallback, say): no longer the account's own row.
plan.dropped.push({ code: "changed-during-run", qitemId: candidate.qitemId });
} else if (scope.kind === "routine" && routineAction(now) !== candidate.action) {
@@ -787,10 +797,11 @@ export async function eraseQueue(db: Database.Database, opts: EraseOptions): Pro
return report;
}
/** Account deletion's second pass: outbox and inbox entries between two members that no queue row owns, and the
* members' stream items. An entry with one member endpoint, or a stream item something still references, is counted
* and left. Rows and references this run erases are counted as they were before it, so a dry run and an apply report
* the same set. */
/** Account deletion's second pass: outbox and inbox entries no queue row owns between two members, or between a
* member and OpenRig (its wake for a row erased earlier, say), and the members' stream items. An entry with one
* member endpoint and the other outside the account, or a stream item something still references, is counted and
* left. Rows and references this run erases are counted as they were before it, so a dry run and an apply report the
* same set. */
function eraseUnlinked(db: Database.Database, st: Statements,
plan: { members: string; plannedActions: string[]; plannedDispositions: string[]; erasedRows: string[] }, apply: boolean): NonNullable<EraseReport["unlinked"]> {
// A row this run erased still owns its copies here: they were reported with it (keptCopies), not as unowned.
@@ -799,9 +810,14 @@ function eraseUnlinked(db: Database.Database, st: Statements,
const ownedOutbox = `(COALESCE(audit_pointer, '') IN ${rows}
OR (outbox_id LIKE 'wake-intent-%' AND substr(outbox_id, 13) IN ${rows}))`;
const ownedInbox = `(COALESCE(absorbed_qitem_id, '') IN ${rows} OR COALESCE(audit_pointer, '') IN ${rows})`;
const both = `sender_session IN ${MEMBERS} AND destination_session IN ${MEMBERS}`;
const fromMember = `sender_session IN ${MEMBERS} AND destination_session NOT IN ${MEMBERS}`;
const toMember = `destination_session IN ${MEMBERS} AND sender_session NOT IN ${MEMBERS}`;
// A member, or OpenRig's own session: isOpenRigSender in SQL. The prefix is compared exactly, since LIKE ignores
// ASCII case and reads _ as a wildcard.
const accountSide = (column: string) =>
`(${column} IN ${MEMBERS} OR ${column} = '${OPENRIG_SENDER}' OR substr(${column}, 1, 7) = 'system:')`;
const both = `${accountSide("sender_session")} AND ${accountSide("destination_session")}
AND (sender_session IN ${MEMBERS} OR destination_session IN ${MEMBERS})`;
const fromMember = `sender_session IN ${MEMBERS} AND NOT ${accountSide("destination_session")}`;
const toMember = `destination_session IN ${MEMBERS} AND NOT ${accountSide("sender_session")}`;
// The same references the stream pass keeps an item for (queue-retention pruneStreamItems), less this run's own.
const classificationColumns = new Set((db.prepare("PRAGMA table_info(project_classifications)").all() as Array<{ name: string }>)
.map((column) => column.name));
@@ -115,6 +115,8 @@ export const ATTENTION_REQUIRED_READINESS_CODES = new Set([
"login_required",
"mcp_gate",
"bypass_consent_gate",
// Claude's gated-grants backstop (#2820 item 2): approving the folder's pre-approved tool permissions is the person's call.
"claude_gated_grants_gate",
// Claude's resume chooser or picker waits for a person to choose a conversation; startup stops waiting and says so.
"claude_resume_selection_prompt",
// Codex auth refusal (stored OAuth token can no longer be refreshed).
@@ -6,6 +6,7 @@ import nodePath from "node:path";
import { describe, it, expect, vi, afterEach } from "vitest";
import { ClaudeCodeAdapter, type ClaudeAdapterFsOps } from "../src/adapters/claude-code-adapter.js";
import type { NodeBinding, ResolvedStartupFile } from "../src/domain/runtime-adapter.js";
import { isAttentionRequiredReadinessCode } from "../src/domain/runtime-adapter.js";
import type { ProjectionPlan, ProjectionEntry } from "../src/domain/projection-planner.js";
import type { TmuxAdapter } from "../src/adapters/tmux.js";
import { claudePostureFlag } from "../src/adapters/yolo-mode.js";
@@ -1101,7 +1102,7 @@ describe("Claude Code runtime adapter", () => {
});
describe("with provider-prompt auto-driving on, a trust prompt in the longer wait", () => {
const trust = "Accessing workspace:\n/fixture\n1. Yes, I trust this folder\n2. No, exit";
const trust = "Accessing workspace:\n/fixture\n❯ 1. Yes, I trust this folder\n 2. No, exit";
it.each([["a Codex", codex], ["another conversation's Claude", otherClaude]])(
"from %s that took the pane is not answered: main's result, no Enter", async (_label, arrival) => {
@@ -1123,6 +1124,16 @@ describe("Claude Code runtime adapter", () => {
expect((tmux.sendKeys as ReturnType<typeof vi.fn>).mock.calls.length).toBeGreaterThan(1);
});
it("with no key to send (a prompt drawn without a cursor) ends the longer wait as it does without the auto-drive", async () => {
const cursorless = "Accessing workspace:\n/fixture\n1. Yes, I trust this folder\n2. No, exit";
const screen = (read: number) => (read < 20 ? "" : cursorless);
const driven = await run({ autoDrive: true, screen });
const plain = await run({ screen });
expect(driven.result).toEqual(plain.result);
expect(driven.reads).toBe(plain.reads);
expect(driven.tmux.sendKeys).toHaveBeenCalledTimes(1);
});
it("in the quick window is answered as before, whoever holds the pane", async () => {
const { tmux } = await run({ autoDrive: true, rows: () => [...booting, codex], screen: (read) => (read < 3 ? trust : "") });
expect((tmux.sendKeys as ReturnType<typeof vi.fn>).mock.calls.length).toBeGreaterThan(1);
@@ -1459,3 +1470,127 @@ describe("Claude Code runtime adapter", () => {
// grep confirms provisionActivityHooks/upsertCommandHook/etc. removed
// from adapter source.
});
// #2820 item 2: with recovery.auto_drive_provider_prompts on, the plain workspace trust prompt is answered with Enter,
// but Claude Code's "gated grants" backstop never is: its default choice declines the folder's pre-approved tool
// permissions (or exits), and approving them is the person's call. The launch stops as attention_required, with the
// screen as evidence, and no key goes to the pane after the launch command.
describe("Claude gated grants backstop is never auto-driven (#2820 item 2)", () => {
const capture = JSON.parse(fs.readFileSync(new URL("./fixtures/claude-trust-git-root/trust-checks.json", import.meta.url), "utf8")) as { gatedGrantsScreen: string[] };
const backstop = capture.gatedGrantsScreen.join("\n");
async function launch(screens: string[], cwd = "/project") {
const tmux = mockTmux();
(tmux.getPaneCommand as ReturnType<typeof vi.fn>).mockResolvedValue("claude");
const capturePane = tmux.capturePaneContent as ReturnType<typeof vi.fn>;
for (const screen of screens.slice(0, -1)) capturePane.mockResolvedValueOnce(screen);
capturePane.mockResolvedValue(screens.at(-1));
const adapter = new ClaudeCodeAdapter({ tmux, fsOps: mockFs(), sleep: async () => {}, autoDriveProviderPrompts: true });
const result = await adapter.launchHarness(makeBinding(cwd), { name: "dev-impl@test-rig", resumeToken: "abc-123" });
return { tmux, result };
}
it("stops as attention_required and sends nothing after the launch command", async () => {
const { tmux, result } = await launch([backstop]);
expect(result).toMatchObject({ ok: false, recovery: "attention_required" });
// The launch command is the only call (it ends with its own Enter); the plain trust prompt takes a 2nd one.
expect(tmux.sendKeys).toHaveBeenCalledTimes(1);
});
it("sends nothing when the seat's git root is the home folder", async () => {
const { tmux, result } = await launch([backstop.replace("<lab>/repo/cadeiras/rig/seat", "/home/agent")], "/home/agent");
expect(result).toMatchObject({ ok: false, recovery: "attention_required" });
expect(tmux.sendKeys).toHaveBeenCalledTimes(1);
});
it("sends nothing while the backstop is still being drawn, nor once it is complete", async () => {
const partial = capture.gatedGrantsScreen.slice(0, -3).join("\n");
const { tmux, result } = await launch([partial, partial, backstop]);
expect(result).toMatchObject({ ok: false, recovery: "attention_required" });
expect(tmux.sendKeys).toHaveBeenCalledTimes(1);
});
// Claude Code 2.1.322's plain trust prompt (no pre-approved permissions) opens with the focus on "No, exit": an
// Enter there quits Claude. The auto-drive moves the selection down once and presses Enter only once the focused row
// reads "Yes, I trust this folder".
const plainCapture = fs.readFileSync(new URL("./fixtures/claude-trust-git-root/plain-trust-2.1.322.txt", import.meta.url), "utf8")
.split("\n").filter(row => !row.startsWith("# ")).join("\n");
const plainNo = plainCapture;
const plainYes = plainCapture.replace("❯ No, exit", " No, exit").replace(" Yes, I trust this folder", "❯ Yes, I trust this folder");
const ready = ["Claude Code v2.1.322", "❯ Ready"].join("\n");
const keys = (tmux: TmuxAdapter) => (tmux.sendKeys as ReturnType<typeof vi.fn>).mock.calls.map(call => (call[1] as string[]).join(" "));
it("moves the plain trust prompt's focus from 'No, exit' to 'Yes' before pressing Enter (2.1.322)", async () => {
const { tmux, result } = await launch([plainNo, plainYes, ready]);
expect(result).toMatchObject({ ok: true });
expect(keys(tmux)).toEqual(["Enter", "Down", "Enter"]);
});
it("never presses Enter on 'No, exit', and moves it only once: a 2nd Down would wrap back to 'No, exit'", async () => {
const { tmux, result } = await launch([plainNo]);
expect(result).toMatchObject({ ok: false });
expect(keys(tmux)).toEqual(["Enter", "Down"]);
});
// A Claude-like select: Down moves the focus and wraps after the last option, and each key is drawn only some reads
// later (stale frames). Enter on "No, exit" quits Claude; Enter on "Yes" goes on to the session.
it("with stale frames and a wrapping select, sends one Down and presses Enter on 'Yes' only", async () => {
const tmux = mockTmux();
let calls = 0, focusYes = false, entered: "yes" | "no" | null = null, staleReads = 0, last = "";
(tmux.capturePaneContent as ReturnType<typeof vi.fn>).mockImplementation(async () => {
if (staleReads > 0 && last) { staleReads -= 1; return last; }
last = entered === "yes" ? ready : entered === "no" ? "" : focusYes ? plainYes : plainNo;
return last;
});
(tmux.getPaneCommand as ReturnType<typeof vi.fn>).mockImplementation(async () => (entered === "no" ? "zsh" : "claude"));
(tmux.sendKeys as ReturnType<typeof vi.fn>).mockImplementation(async (_session: string, keysSent: string[]) => {
calls += 1;
if (calls === 1) return { ok: true as const }; // the launch command's own Enter
if (keysSent.join(" ") === "Down") { focusYes = !focusYes; staleReads = 3; }
if (keysSent.join(" ") === "Enter" && entered === null) { entered = focusYes ? "yes" : "no"; staleReads = 2; }
return { ok: true as const };
});
const adapter = new ClaudeCodeAdapter({ tmux, fsOps: mockFs(), sleep: async () => {}, autoDriveProviderPrompts: true });
const result = await adapter.launchHarness(makeBinding("/project"), { name: "dev-impl@test-rig", resumeToken: "abc-123" });
expect(entered).toBe("yes");
expect(keys(tmux).slice(1)).toEqual(["Down", "Enter"]);
expect(result).toMatchObject({ ok: true });
});
it("drives a plain prompt drawn below an earlier session that quoted the backstop's words", async () => {
const earlier = ["⏺ The folder's backstop reads \"This folder pre-approves 2 tool permissions\" and focuses",
" \"No, continue without these permissions\".", "", "────────────────", "❯ ", "────────────────", ""].join("\n");
const { tmux, result } = await launch([earlier + plainNo, earlier + plainYes, ready]);
expect(result).toMatchObject({ ok: true });
expect(keys(tmux)).toEqual(["Enter", "Down", "Enter"]);
});
it("sends nothing to the 40-column backstop whose warning a long permission list scrolled out", async () => {
const rows = fs.readFileSync(new URL("./fixtures/claude-trust-git-root/backstop-40col-2.1.322.txt", import.meta.url), "utf8")
.split("\n").filter(row => !row.startsWith("# "));
const from = rows.findIndex(row => row.includes("⚠ This folder pre-approves"));
const to = rows.findIndex(row => row.includes("configuration."));
const { tmux, result } = await launch([[...rows.slice(0, from), ...rows.slice(to + 1)].join("\n")]);
expect(result).toMatchObject({ ok: false, recovery: "attention_required" });
expect(keys(tmux)).toEqual(["Enter"]);
});
it("sends nothing to a trust prompt drawn without a cursor: the label cannot be checked", async () => {
const cursorless = plainCapture.replace("❯ No, exit", " No, exit");
const { tmux, result } = await launch([cursorless]);
expect(result).toMatchObject({ ok: false });
expect(keys(tmux)).toEqual(["Enter"]);
});
it("sends nothing to the backstop in a 40-column pane, whose rows wrap and cut its marks (real capture)", async () => {
const narrow = fs.readFileSync(new URL("./fixtures/claude-trust-git-root/backstop-40col-2.1.322.txt", import.meta.url), "utf8")
.split("\n").filter(row => !row.startsWith("# ")).join("\n");
const { tmux, result } = await launch([narrow]);
expect(result).toMatchObject({ ok: false, recovery: "attention_required" });
expect(keys(tmux)).toEqual(["Enter"]);
});
it("is a readiness code that stops startup waiting for attention", () => {
expect(isAttentionRequiredReadinessCode("claude_gated_grants_gate")).toBe(true);
});
});
@@ -0,0 +1,32 @@
# Claude Code 2.1.322, the gated-grants backstop in a 40-column tmux pane (T-005154 lab: fake HOME, no credential,
# no key sent): the warning and the decline option wrap across rows. Captured 2026-11-12 with tmux capture-pane -p.
────────────────────────────────────────
Accessing workspace:
<lab>/backstop/rep
o/cadeiras/rig/seat
Quick safety check: Is this a project
you created or one you trust? (Like
your own code, a well-known open
source project, or work from your
team). If not, take a moment to review
what's in this folder first.
Claude Code'll be able to read, edit,
and execute files here.
⚠ This folder pre-approves 2 tool
permissions in .claude/settings.json:
Bash(ls:*) and Bash(git status:*)
These will apply without asking. Only
proceed if you trust this
configuration.
Security guide
❯ No, continue without these
Yes, I trust this folder
Enter to confirm · Esc to cancel
@@ -0,0 +1,47 @@
# Real capture (12/11/2026): Claude Code 2.1.322, fresh HOME after OpenRig's pre-launch seed with no trust, a seat
# without .claude/settings.json; tmux 150x45. The plain workspace trust prompt opens with the focus on 'No, exit'.
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Accessing workspace:
<lab>/simples/repo/cadeiras/rig/seat
Quick safety check: Is this a project you created or one you trust? (Like your own code, a well-known open source project, or work from your team).
If not, take a moment to review what's in this folder first.
Claude Code'll be able to read, edit, and execute files here.
Security guide
❯ No, exit
Yes, I trust this folder
Enter to confirm · Esc to cancel
@@ -4,6 +4,7 @@ import {
assessNativeResumeProbe,
buildNativeResumeCommand,
buildCodexResumeCore,
claudeTrustPromptFocus,
isProbeShellReady,
} from "../src/domain/native-resume-probe.js";
@@ -1418,3 +1419,185 @@ describe("Claude's Resume session picker", () => {
.toMatchObject({ status: "resumed", code: "active_runtime" });
});
});
// #2820 item 2: Claude Code's "gated grants" backstop (2.1.319+). It looks like the workspace trust prompt
// ("Accessing workspace:", "Yes, I trust this folder"), but it also asks to approve the tool permissions the folder's
// .claude/settings.json pre-approves, and its default choice declines them ("No, continue without these permissions")
// or exits ("No, exit"). OpenRig must never answer it, not even with recovery.auto_drive_provider_prompts.
describe("Claude gated grants backstop (#2820 item 2)", () => {
// A real capture: Claude Code 2.1.319 in a lab git repo (see claude-trust-git-root.test.ts).
const capture = JSON.parse(fs.readFileSync(new URL("./fixtures/claude-trust-git-root/trust-checks.json", import.meta.url), "utf8")) as { gatedGrantsScreen: string[] };
const screen = capture.gatedGrantsScreen.join("\n");
const probe = (paneContent: string) => assessNativeResumeProbe({ runtime: "claude-code", paneCommand: "claude", paneContent });
const gate = { status: "attention_required", code: "claude_gated_grants_gate" };
it("the captured screen, focus on 'No, continue without these permissions', is its own gate, never trust_gate", () => {
expect(probe(screen)).toMatchObject(gate);
expect(probe(screen).detail).toContain("OpenRig does not approve or bypass this review. No input was sent.");
});
it("is the same gate with the focus moved to 'Yes, I trust this folder'", () => {
const yes = screen.replace("❯ No, continue without these permissions", " No, continue without these permissions")
.replace(" Yes, I trust this folder", "❯ Yes, I trust this folder");
expect(probe(yes)).toMatchObject(gate);
});
it("is the same gate in the variant with nothing trusted yet, whose default choice is 'No, exit'", () => {
expect(probe(screen.replace("❯ No, continue without these permissions", "❯ No, exit"))).toMatchObject(gate);
});
it("is the same gate when the git root is the home folder (the case item 1 deliberately does not seed)", () => {
expect(probe(screen.replace("<lab>/repo/cadeiras/rig/seat", "/home/agent"))).toMatchObject(gate);
});
it("is the same gate drawn with blank rows between its parts and a long permission list", () => {
const rows = capture.gatedGrantsScreen.flatMap(row => [row, ""]);
rows.splice(rows.findIndex(row => row.includes("Bash(ls:*)")) + 1, 0, ...Array.from({ length: 30 }, (_, n) => ` Bash(tool-${n}:*)`));
expect(probe(rows.join("\n"))).toMatchObject(gate);
});
it("a backstop still being drawn is not a trust prompt to drive: it waits for the next read", () => {
const partial = capture.gatedGrantsScreen.slice(0, capture.gatedGrantsScreen.findIndex(row => row.includes("Security guide")));
expect(probe(partial.join("\n"))).toMatchObject({ status: "inconclusive", code: "awaiting_runtime" });
const noFooter = capture.gatedGrantsScreen.slice(0, -1).join("\n");
expect(probe(noFooter)).toMatchObject({ status: "inconclusive", code: "awaiting_runtime" });
});
it("a backstop left in the scrollback above a session that started is neither this gate nor trust_gate", () => {
const later = [screen, "", " ▐▛███▜▌ Claude Code v2.1.319", "", "────────────────", "❯ ", "────────────────"].join("\n");
expect(probe(later).code).not.toBe("claude_gated_grants_gate");
expect(probe(later).code).not.toBe("trust_gate");
});
it("is the same gate in a 40-column pane, whose rows wrap and cut its marks (real capture), never trust_gate", () => {
const narrow = fs.readFileSync(new URL("./fixtures/claude-trust-git-root/backstop-40col-2.1.322.txt", import.meta.url), "utf8")
.split("\n").filter(row => !row.startsWith("# ")).join("\n");
expect(narrow).not.toMatch(/No, continue without these permissions/);
expect(probe(narrow)).toMatchObject(gate);
expect(claudeTrustPromptFocus(narrow)).toBe("unknown");
});
it("a 40-column backstop captured before its wrapped warning is complete waits, never resumed", () => {
const rows = fs.readFileSync(new URL("./fixtures/claude-trust-git-root/backstop-40col-2.1.322.txt", import.meta.url), "utf8")
.split("\n").filter(row => !row.startsWith("# "));
const partial = rows.slice(0, rows.findIndex(row => row.includes("⚠ This folder pre-approves")) + 1).join("\n");
expect(partial).not.toMatch(/tool permissions/);
expect(probe(partial)).toMatchObject({ status: "inconclusive", code: "awaiting_runtime" });
});
it("is the same gate in 40 columns when a long permission list scrolled the whole warning out", () => {
const rows = fs.readFileSync(new URL("./fixtures/claude-trust-git-root/backstop-40col-2.1.322.txt", import.meta.url), "utf8")
.split("\n").filter(row => !row.startsWith("# "));
const from = rows.findIndex(row => row.includes("⚠ This folder pre-approves"));
const to = rows.findIndex(row => row.includes("configuration."));
const scrolled = [...rows.slice(0, from), ...rows.slice(to + 1)].join("\n");
expect(scrolled).not.toMatch(/pre-approves/);
expect(probe(scrolled)).toMatchObject(gate);
});
it("is the same gate drawn with numbered options", () => {
const numbered = screen.replace("❯ No, continue without these permissions", "❯ 1. No, continue without these permissions")
.replace(" Yes, I trust this folder", " 2. Yes, I trust this folder");
expect(probe(numbered)).toMatchObject(gate);
});
it("a reply quoting the backstop's words above a fresh plain prompt does not hide that prompt", () => {
const plain = fs.readFileSync(new URL("./fixtures/claude-trust-git-root/plain-trust-2.1.322.txt", import.meta.url), "utf8")
.split("\n").filter(row => !row.startsWith("# ")).join("\n");
const earlier = ["⏺ It reads \"This folder pre-approves 2 tool permissions\" and \"No, continue without these permissions\".",
"", "────────────────", "❯ ", "────────────────", ""].join("\n");
expect(probe(earlier + plain)).toMatchObject({ status: "inconclusive", code: "trust_gate" });
});
it("a draft in Claude's input box that reads like the backstop's option is never the gate", () => {
const started = [" ▐▛███▜▌ Claude Code v2.1.322", "", "⏺ Done.", "", "────────────────────────────────",
"❯ No, continue without the tests", "────────────────────────────────", " ⏵⏵ auto mode on (shift+tab to cycle)"].join("\n");
expect(probe(started)).toMatchObject({ status: "resumed" });
});
it("nor is that draft while the input frame's closing rule is not captured yet", () => {
const drawing = [" ▐▛███▜▌ Claude Code v2.1.322", "", "⏺ Done.", "", "────────────────────────────────",
"❯ No, continue without the tests"].join("\n");
expect(probe(drawing)).toMatchObject({ status: "resumed" });
});
// A draft's text never moves the cut: Claude draws its frame's rules from column 0 and a draft's continuation rows
// indented under the ❯, so a rule, a reply or a header pasted into a draft is the draft's, not Claude's.
const header = " ▐▛███▜▌ Claude Code v2.1.322";
const rule = "────────────────────────────────";
it.each([
["a pasted rule", " ────────"],
["a pasted reply", "⏺ Earlier output"],
["a pasted header", " Claude Code v2.1.322"],
])("a multi-line draft with %s above the backstop's words is never the gate", (_case, pasted) => {
const draft = ["❯ Review this example:", pasted, " No, continue without the tests"];
const closed = [header, "", "⏺ Done.", "", rule, ...draft, rule, " ⏵⏵ auto mode on (shift+tab to cycle)"].join("\n");
expect(probe(closed)).toMatchObject({ status: "resumed" });
const drawing = [header, "", "⏺ Done.", "", rule, ...draft].join("\n");
expect(probe(drawing)).toMatchObject({ status: "resumed" });
});
it("a draft that mentions a Claude Code version reads resumed, closed or still open (maintainer's case)", () => {
const draft = ["Claude Code v2.1.322", rule, "❯ Explain this Claude Code v2.1.322 message:", " No, continue without the tests"];
expect(probe([...draft, rule, " ⏵⏵ accept edits on (shift+tab to cycle)"].join("\n"))).toMatchObject({ status: "resumed" });
expect(probe(draft.join("\n"))).toMatchObject({ status: "resumed" });
});
it("a draft that starts with a pasted header is never the gate either", () => {
const started = [header, "", "⏺ Done.", "", rule, "❯ Claude Code v2.1.322 asks:", " No, continue without the tests", rule].join("\n");
expect(probe(started)).toMatchObject({ status: "resumed" });
});
it("is the same gate below an old reply that quotes an input frame, with no input frame after it", () => {
// a quoted frame is indented like the reply: it is no frame of Claude's, so it never blanks the rows below it
const quoted = [header, "", "⏺ The screen looked like:", " ────────", " ❯ hi", " ────────", "", "$ claude --resume x", ""].join("\n");
expect(probe(`${quoted}\n${capture.gatedGrantsScreen.join("\n")}`)).toMatchObject(gate);
});
it("is the same gate below an old session whose input frame holds a draft (N1)", () => {
const earlier = [header, "", "⏺ Done.", "", rule, "❯ Review this example:", " ────────", " more text", rule, ""].join("\n");
expect(probe(`${earlier}\n${screen}`)).toMatchObject(gate);
});
it("names the focused choice in the gate's detail", () => {
expect(probe(screen).detail).toContain("\"No, continue without these permissions\"");
const yes = screen.replace("❯ No, continue without these permissions", " No, continue without these permissions")
.replace(" Yes, I trust this folder", "❯ Yes, I trust this folder");
expect(probe(yes).detail).toContain("\"Yes, I trust this folder\"");
});
it("the plain workspace trust prompt is still trust_gate (it stays auto-drivable)", () => {
const plain = ["Accessing workspace:", "/some/workspace", "", "Quick safety check: Is this a project you created or one you trust?",
"❯ 1. Yes, I trust this folder", " 2. No, exit"].join("\n");
expect(probe(plain)).toMatchObject({ status: "inconclusive", code: "trust_gate" });
});
});
// #2820 item 2: the auto-drive presses a key on the trust prompt only for an allowlisted screen.
describe("claudeTrustPromptFocus (#2820 item 2)", () => {
const plain = fs.readFileSync(new URL("./fixtures/claude-trust-git-root/plain-trust-2.1.322.txt", import.meta.url), "utf8")
.split("\n").filter(row => !row.startsWith("# ")).join("\n");
const backstop = (JSON.parse(fs.readFileSync(new URL("./fixtures/claude-trust-git-root/trust-checks.json", import.meta.url), "utf8")) as { gatedGrantsScreen: string[] }).gatedGrantsScreen.join("\n");
it("reads 'no' on the real 2.1.322 prompt, focused on 'No, exit'", () => {
expect(claudeTrustPromptFocus(plain)).toBe("no");
});
it("reads 'yes' once the focus is on 'Yes, I trust this folder'", () => {
expect(claudeTrustPromptFocus(plain.replace("❯ No, exit", " No, exit").replace(" Yes, I trust this folder", "❯ Yes, I trust this folder"))).toBe("yes");
});
it("reads numbered prompts and the › cursor", () => {
expect(claudeTrustPromptFocus("Accessing workspace:\n/w\n❯ 1. Yes, I trust this folder\n 2. No, exit")).toBe("yes");
expect(claudeTrustPromptFocus("Accessing workspace:\n/w\n 1. Yes, I trust this folder\n› 2. No, exit")).toBe("no");
});
it("is 'unknown' without a cursor: the label cannot be checked", () => {
expect(claudeTrustPromptFocus("Accessing workspace:\n/w\n1. Yes, I trust this folder\n2. No, exit")).toBe("unknown");
});
it("is 'unknown' on the backstop's options, even with the focus moved to 'Yes'", () => {
expect(claudeTrustPromptFocus(backstop)).toBe("unknown");
expect(claudeTrustPromptFocus(backstop.replace("❯ No, continue without these permissions", " No, continue without these permissions")
.replace(" Yes, I trust this folder", "❯ Yes, I trust this folder"))).toBe("unknown");
});
it("is 'unknown' on any other option set", () => {
expect(claudeTrustPromptFocus(plain.replace(" Yes, I trust this folder", " Yes, I trust this folder\n No, ask me later"))).toBe("unknown");
});
});
+112 -3
View File
@@ -39,11 +39,13 @@ beforeEach(() => {
});
afterEach(() => db.close());
/** A row whose every content field and linked copy carries `secret-<id>`, with its history at chosen ages. */
async function row(id: string, source: string, destination: string, history: Array<{ state: string; daysAgo: number }> = []) {
/** A row whose every content field and linked copy carries `secret-<id>`, with its history at chosen ages. `openrig`:
* OpenRig created it (a sweep finding, an escalation), so the create stages its wake from OpenRig's own session. */
async function row(id: string, source: string, destination: string, history: Array<{ state: string; daysAgo: number }> = [],
wakeTrigger?: "openrig") {
const secret = `secret-${id}`;
await repo.create({ qitemId: id, sourceSession: source, destinationSession: destination, body: `${secret} body`, summary: `${secret} summary`,
tags: [`${secret}-tag`] });
tags: [`${secret}-tag`], wakeTrigger });
db.prepare("UPDATE queue_transitions SET ts = ?, transition_note = ? WHERE qitem_id = ?").run(ago(400), `${secret} created`, id);
for (const step of history) {
const { transitionId } = log.append({ qitemId: id, state: step.state, actorSession: destination, transitionNote: `${secret} note` });
@@ -682,3 +684,110 @@ describe("round 3 controls", () => {
expect(everything()).toContain("secret-l2-new body");
});
});
describe("OpenRig's own wakes and notices", () => {
const DAEMON = "daemon@kernel";
const HEALTH = "system:health";
const members = { kind: "members" as const, members: [A, B] };
const wakeOf = (id: string) => db.prepare("SELECT sender_session AS from_, destination_session AS to_ FROM outbox_entries WHERE outbox_id = ?")
.get(`wake-intent-${id}`);
const loose = (table: "outbox_entries" | "inbox_entries", id: string, from: string, to: string, body: string) => {
if (table === "outbox_entries") {
db.prepare(`INSERT INTO outbox_entries (outbox_id, sender_session, destination_session, body, ts_dispatched) VALUES (?, ?, ?, ?, ?)`)
.run(id, from, to, body, NOW);
} else {
db.prepare(`INSERT INTO inbox_entries (inbox_id, sender_session, destination_session, body, ts_dropped) VALUES (?, ?, ?, ?, ?)`)
.run(id, from, to, body, NOW);
}
};
it("an OpenRig-triggered finding to a member erases clean, with OpenRig's wake for it and its notices", async () => {
await row("f-finding", A, A, [], "openrig");
// The premise: the finding's wake is staged from OpenRig, not from the member named as its source.
expect(wakeOf("f-finding")).toEqual({ from_: DAEMON, to_: A });
await row("f-escalation", DAEMON, B, [], "openrig");
await row("f-health", HEALTH, A, [{ state: "done", daysAgo: 2 }], "openrig");
loose("outbox_entries", "o-notice", DAEMON, A, "secret-loose-notice");
loose("inbox_entries", "i-notice", HEALTH, B, "secret-loose-inbox");
const dry = await eraseQueue(db, { scope: members, apply: false, nowIso: NOW });
const report = await eraseQueue(db, { scope: members, apply: true, nowIso: NOW });
expect({ ...report, applied: false }).toEqual(dry);
expect(report.qitems.map((q) => q.qitemId)).toEqual(["f-escalation", "f-finding", "f-health"]);
expect(report.mixed).toEqual([]);
expect(report.keptCopies).toEqual([]);
expect(report.unlinked).toMatchObject({ outbox: 1, inbox: 1, mixedEntries: 0 });
expect(report.clean).toBe(true);
const all = everything();
expect(all).not.toContain("secret-f-");
expect(all).not.toContain("secret-loose-");
});
it("an OpenRig wake to another account's seat is kept, and a row OpenRig woke with one member endpoint stays mixed", async () => {
await row("f-own", A, B, [], "openrig");
await row("x-finding", OUT, OUT, [], "openrig");
await row("x-escalation", DAEMON, OUT, [], "openrig");
await row("x-mixed", OUT, A, [], "openrig");
loose("outbox_entries", "o-elsewhere", DAEMON, OUT, "secret-loose-elsewhere");
const report = await eraseQueue(db, { scope: members, apply: true, nowIso: NOW });
expect(report.qitems.map((q) => q.qitemId)).toEqual(["f-own"]);
expect(report.mixed).toEqual([{ qitemId: "x-mixed", memberEndpoint: "destination" }]);
expect(report.unlinked).toMatchObject({ outbox: 0, mixedEntries: 0 });
expect(report.clean).toBe(false);
const all = everything();
for (const id of ["x-finding", "x-escalation", "x-mixed"]) {
expect(exists(id)).toBe(true);
expect(all).toContain(`secret-${id} body`);
}
expect(wakeOf("x-finding")).toEqual({ from_: DAEMON, to_: OUT });
expect(wakeOf("x-mixed")).toEqual({ from_: DAEMON, to_: A });
expect(all).toContain("secret-loose-elsewhere");
expect(all).not.toContain("secret-f-own");
});
it("OpenRig's entries with itself are untouched, and a session that only looks like OpenRig's is outside the account", async () => {
await row("f-own", A, B, [], "openrig");
loose("outbox_entries", "o-self", DAEMON, DAEMON, "secret-loose-self");
loose("outbox_entries", "o-health", HEALTH, DAEMON, "secret-loose-health");
loose("inbox_entries", "i-self", HEALTH, DAEMON, "secret-loose-inbox-self");
// isOpenRigSender is exact: "System:" isn't OpenRig's prefix.
loose("outbox_entries", "o-lookalike", "System:health", A, "secret-loose-lookalike");
const report = await eraseQueue(db, { scope: members, apply: true, nowIso: NOW });
expect(report.qitems.map((q) => q.qitemId)).toEqual(["f-own"]);
expect(report.unlinked).toMatchObject({ outbox: 0, inbox: 0, mixedEntries: 1 });
expect(report.clean).toBe(false);
const all = everything();
for (const body of ["secret-loose-self", "secret-loose-health", "secret-loose-inbox-self", "secret-loose-lookalike"]) expect(all).toContain(body);
expect(all).not.toContain("secret-f-own");
});
it("rerunning the same plan over what an earlier daemon left removes it: the erased row's OpenRig wake, and its OpenRig rows", async () => {
await row("r-finding", A, A, [], "openrig");
await row("r-escalation", DAEMON, B, [], "openrig");
// What an earlier daemon's run leaves: it deleted r-finding but kept OpenRig's wake for it as mixed, and left
// r-escalation untouched as a mixed row. Built here by deleting r-finding and restoring its wake as it was.
const wake = db.prepare("SELECT * FROM outbox_entries WHERE outbox_id = 'wake-intent-r-finding'").get() as Record<string, unknown>;
await eraseQueue(db, { scope: { kind: "ids", entries: [{ qitemId: "r-finding", action: "delete" }] }, apply: true, nowIso: NOW });
const columns = Object.keys(wake);
db.prepare(`INSERT OR REPLACE INTO outbox_entries (${columns.join(", ")}) VALUES (${columns.map(() => "?").join(", ")})`)
.run(...columns.map((c) => wake[c]));
expect([exists("r-finding"), marker("r-finding") !== undefined, exists("r-escalation")]).toEqual([false, true, true]);
expect(everything()).toContain("secret-r-finding summary");
const rerun = await eraseQueue(db, { scope: members, apply: true, nowIso: NOW });
expect(rerun.qitems.map((q) => q.qitemId)).toEqual(["r-escalation"]);
expect(rerun.unlinked).toMatchObject({ outbox: 1, mixedEntries: 0 });
expect(rerun.clean).toBe(true);
expect(everything()).not.toContain("secret-r-");
});
it("routine retention deletes OpenRig's wake for a row with the row, and OpenRig's own rows keep theirs together", async () => {
await row("t-old", A, B, [{ state: "done", daysAgo: 40 }], "openrig");
await row("t-self", DAEMON, DAEMON, [{ state: "done", daysAgo: 40 }], "openrig");
expect(wakeOf("t-old")).toEqual({ from_: DAEMON, to_: B });
const report = await eraseQueue(db, { scope: { kind: "routine", contentDays: 0, metadataDays: 30 }, apply: true, nowIso: NOW });
expect(report.qitems.map((q) => [q.qitemId, q.action])).toEqual([["t-old", "delete"], ["t-self", "delete"]]);
expect(report.keptCopies).toEqual([]);
expect(report.clean).toBe(true);
expect(everything()).not.toContain("secret-t-");
});
});
+49
View File
@@ -0,0 +1,49 @@
import { CHECK_IN_DISPLAY, describeCheckIn, type CheckInStatus } from "@openrig/daemon/connection-contract";
import { wrapDetailLines, type ContentLine } from "./detail.js";
import { displayTime } from "./time.js";
import type { ConnectedAssistant } from "./types.js";
/** The hosted-members answer as connected assistants; null when it isn't one. A status this TUI doesn't know reads
* unknown, as in `rig ps`. */
export function toConnectedAssistants(body: unknown): ConnectedAssistant[] | null {
const members = (body as { members?: unknown } | null)?.members;
if (!Array.isArray(members)) return null;
return members.flatMap((member: Record<string, unknown>) => {
if (typeof member?.seat !== "string" || !member.seat) return [];
const known = typeof member.status === "string" && member.status in CHECK_IN_DISPLAY;
return [{ seat: member.seat, checkIn: {
status: known ? member.status as CheckInStatus : "unknown",
lastCheckInAt: typeof member.lastCheckInAt === "string" ? member.lastCheckInAt : null,
expectedMinutes: typeof member.expectedMinutes === "number" ? member.expectedMinutes : null,
onRequest: member.onRequest === true,
...(known && typeof member.reason === "string" ? { reason: member.reason } : {}),
} }];
});
}
/** The hosted-members read as the list, or why it couldn't be read, in `rig ps`'s words: an older daemon's 404, a failed
* read, or an answer that isn't one. A failed read isn't an empty list. */
export function connectedAssistantsOf(answer: { status: number; body: unknown }): { assistants: ConnectedAssistant[] } | { unavailable: string } {
if (answer.status === 404) return { unavailable: "this daemon doesn't serve it" };
if (answer.status >= 400) return { unavailable: `the read failed: HTTP ${answer.status}` };
const assistants = toConnectedAssistants(answer.body);
return assistants ? { assistants } : { unavailable: "the daemon's answer couldn't be read" };
}
/** The connected assistants under a seat table, each with its check-in line in the daemon's words and the time in the
* viewer's zone; only one rig's when `rig` is given. Nothing when there are none; one line saying check-in is
* unavailable, with the reason, when the list couldn't be read. */
export function connectedAssistantLines(assistants: ConnectedAssistant[] | undefined, unavailable: string | undefined, rig: string | null,
filter: string | null, width: number, timeZone?: string): ContentLine[] {
if (unavailable) return [{ text: "" }, ...wrapDetailLines([{ text: `Connected assistants: check-in unavailable (${unavailable})` }], width)];
const shown = (assistants ?? [])
.filter((a) => !rig || a.seat.endsWith(`@${rig}`))
.filter((a) => !filter || a.seat.includes(filter));
if (shown.length === 0) return [];
return [
{ text: "" },
{ text: "Connected assistants (outside the terminal; each checks its own queue):" },
...wrapDetailLines(shown.map((a) => ({ text: ` ${a.seat} ${describeCheckIn({ ...a.checkIn,
lastCheckInAt: a.checkIn.lastCheckInAt === null ? null : displayTime(a.checkIn.lastCheckInAt, timeZone) })}` })), width),
];
}
+8
View File
@@ -419,6 +419,14 @@ export class DaemonClient {
const query = [item ? `item=${encodeURIComponent(item)}` : null, view ? `view=${encodeURIComponent(view)}` : null].filter(Boolean).join("&");
return this.get(`/api/attention${query ? `?${query}` : ""}`);
}
/** Connected assistants (roster members outside any terminal) and their check-in. Optional: an older daemon has no
* such route. */
/** This daemon's connected assistants, as the status and body it answered; an older daemon answers 404. A failed read
* isn't an empty list, so the caller is given the status to tell them apart. */
async hostedMembers(): Promise<{ status: number; body: unknown }> {
const res = await this.optionalFetchImpl(`${this.baseUrl}/api/queue/hosted-members`, { headers: this.headers, signal: AbortSignal.timeout(5_000) });
return { status: res.status, body: res.ok ? await res.json().catch(() => null) : null };
}
queueItem(qitemId: string, options: { optional?: boolean } = {}) {
return this.get(`/api/queue/${encodeURIComponent(qitemId)}`, options.optional ? this.optionalFetchImpl : this.fetchImpl);
}
+12
View File
@@ -24,6 +24,7 @@ import { parse as parseYaml } from "yaml";
import type { AgentRow, FleetSnapshot, HealthCoverage, HealthRecord, HostNode, NeedsItem, PodNode, QueueRead, RecentTransitionSnap, SeatActivitySummary, SeatEffortRead, SliceDetailSnap, SpecEntry, ViewState } from "./types.js";
import { isHumanSeatSession } from "./pulse/pulse-model.js";
import { sanitizeHostDisplayName } from "./topology/host-label.js";
import { connectedAssistantsOf } from "./connected-assistants.js";
// Narrow read-shapes: just the served fields this module consumes (names match
// the daemon's serialized output — see the Phase-2 endpoint-shape survey).
@@ -572,6 +573,15 @@ export async function hydrateSnapshot(
// A drilled-into host that isn't this one: its pages read none of this host's seats or queue changes.
const drilledHost = viewContext?.section === "topology" ? viewContext.drill.find((segment) => segment.kind === "host")?.name : undefined;
const remoteDrill = !!drilledHost && drilledHost !== (instanceHealth?.selfHostId?.trim() || "local");
// Optional, like the Slack manifest: a failed read isn't a page failure. But it isn't an empty list either, so the seat
// tables say check-in is unavailable, as `rig ps` does. Read only for the instance and rig tables that list them, and
// only this daemon's, never a remote host's.
const listsAssistants = !viewContext || (viewContext.section === "topology" && viewContext.viewTab === "table"
&& (topologyLeaf?.kind === "host" || topologyLeaf?.kind === "rig"));
const connectedAssistants = listsAssistants && !remoteDrill
? await client.hostedMembers().then(connectedAssistantsOf,
(error: unknown) => ({ unavailable: `the read failed: ${error instanceof Error ? error.message : String(error)}` }))
: null;
const recentTransitionsRig = currentRigName ?? (!viewContext ? summaries?.[0]?.name : null) ?? null;
const recentTransitionsScope = topologyLeaf?.kind === "host"
? { kind: "instance" } as const
@@ -685,6 +695,8 @@ export async function hydrateSnapshot(
displayName: ownName && ownName !== "localhost" ? ownName : undefined,
reachable: true,
rigs: rigs.sort(byRigName),
...(connectedAssistants ? "unavailable" in connectedAssistants
? { connectedAssistantsUnavailable: connectedAssistants.unavailable } : { connectedAssistants: connectedAssistants.assistants } : {}),
};
// A remote host is any registered host, or one the attention aggregate answered for. Its reachability is the aggregate's
// answer where there is one, else the registry's probe. Only a drilled-into remote host's rigs are read, through this
+3
View File
@@ -31,6 +31,7 @@ import type { CrashCartModel } from "./crash-cart/crash-cart-model.js";
import type { DaemonState, DaemonUnverifiedEvidence } from "./crash-cart/contract.js";
import { runtimeMarkSegs } from "./topology/runtime-marks.js";
import { hostLabel, hostReachabilityLabel } from "./topology/host-label.js";
import { connectedAssistantLines } from "./connected-assistants.js";
import { barCells, flashActive, reducedMotion, spinnerFrame } from "./motion.js";
import { explorerWidth, MOTION_FRAME_MS } from "./visual-layout.js";
import type { ColorMode, Token } from "./theme.js";
@@ -867,6 +868,7 @@ function instanceContentLines(
});
}
}
lines.push(...connectedAssistantLines(host.connectedAssistants, host.connectedAssistantsUnavailable, null, state.filter, contentWidth, state.timeZone));
lines.push({ text: "" }, { text: host.rigs.some(r => r.inventoryUnavailable) ? `${host.rigs.length} rigs · inventory incomplete · ${seatCount} seats read` : `${host.rigs.length} rigs · ${seatCount} seats · ${workingCount} working · ${attentionCount} need attention${attentionUnknown ? ` · ${attentionUnknown} attention unknown` : ""} · ${openCount}${queueIncomplete(snap) ? "+ sampled" : ""} open rows` });
lines.push(...recentLines(snap, scope, contentWidth, false, state.timeZone));
return lines;
@@ -1107,6 +1109,7 @@ function contentLines(state: ViewState, snap: FleetSnapshot, contentWidth: numbe
zones,
});
}
if (!podFilter) lines.push(...connectedAssistantLines(host.connectedAssistants, host.connectedAssistantsUnavailable, rig.name, state.filter, contentWidth, state.timeZone));
lines.push({ text: "" });
const working = rows.filter((agent) => ["active", "working", "running"].includes(agent.status)).length;
const attention = rows.filter((agent) => /attention|needs|blocked|unknown|failed/.test(agent.status)).length;
+12
View File
@@ -97,6 +97,18 @@ export interface HostNode {
/** true/false only when a probe answered; null keeps missing or unknown distinct. */
reachable: boolean | null;
rigs: RigNode[];
/** Roster members outside any terminal (assistants reaching the team over MCP) and their check-in, read from this
* daemon only. Absent when not read, or when the read failed. */
connectedAssistants?: ConnectedAssistant[];
/** Why the connected assistants couldn't be read (an older daemon, a failed read, an unusable answer); absent when
* they were read or not asked for. */
connectedAssistantsUnavailable?: string;
}
/** A connected assistant's check-in as this daemon reports it. */
export interface ConnectedAssistant {
seat: string;
checkIn: Pick<import("@openrig/daemon/connection-contract").MemberCheckIn, "status" | "lastCheckInAt" | "expectedMinutes" | "onRequest" | "reason">;
}
export type SpecKind = "rig" | "agent" | "workflow";
+2
View File
@@ -37,6 +37,7 @@ const SPEC_4A_ROUTES = [
"/api/provider/status",
"/api/provider/usage/hosts",
"/api/telemetry/usage/cost",
"/api/queue/hosted-members",
];
describe("daemon client = the §4.A table, one module, nothing else (FR-8/FR-9)", () => {
@@ -75,6 +76,7 @@ describe("daemon client = the §4.A table, one module, nothing else (FR-8/FR-9)"
await c.providerStatus();
await c.usageAcrossHosts();
await c.usageCost();
await c.hostedMembers();
expect(seen.sort()).toEqual([...SPEC_4A_ROUTES].sort());
});
+63
View File
@@ -6,6 +6,7 @@ import { hydrateSnapshot } from "../src/hydrate.js";
import { renderScreen } from "../src/render.js";
import { createViewState } from "../src/state.js";
import { rowStatusGlyph, statusGlyph } from "../src/topology/glyphs.js";
import { displayTime } from "../src/time.js";
// Fixtures mirror the SERVED shapes traced firsthand at 5f3b5bd4 (Phase-2
// endpoint-shape survey): real field names, real enum values, real evidence
@@ -162,6 +163,7 @@ const FIXTURES: Record<string, unknown> = {
"/api/queue/list?state=pending&limit=50": [],
"/api/queue/list?state=done,handed-off&sort=updated&limit=20": [],
"/api/queue/recent-transitions?scope=rig&rig=myrig&limit=20": [],
"/api/queue/hosted-members": { hostId: "mm2-openrig1", members: [] },
};
function fixtureClient(
@@ -173,6 +175,8 @@ function fixtureClient(
const route = String(url).replace("http://x", "");
calls?.push(route);
const failure = overrides[route];
// Status 0 stands for a read that never got an answer, such as a dropped connection.
if (failure?.status === 0) throw new Error("fetch failed");
if (failure) return { ok: false, status: failure.status, json: async () => failure.body ?? null } as Response;
if (route in responses) return { ok: true, json: async () => responses[route] } as Response;
if (!(route in FIXTURES)) throw new Error(`unexpected route in test: ${route}`);
@@ -752,6 +756,65 @@ describe("snapshot hydration over the §4.A reads (Phase 2)", () => {
});
});
it("lists connected assistants and their check-in under the seat tables, one rig's in the rig view", async () => {
const hosted = { hostId: "mm2-openrig1", members: [
{ seat: "chat@myrig", rung: false, status: "check-in-overdue", lastCheckInAt: "2026-11-12T13:05:00.000Z", expectedMinutes: 60, onRequest: false, reporter: "openrig-observed" },
{ seat: "desk@myrig", rung: false, status: "on-request", lastCheckInAt: "2026-11-12T12:00:00.000Z", expectedMinutes: null, onRequest: true, reporter: "openrig-observed" },
{ seat: "bot@downrig", rung: false, status: "a-newer-status", lastCheckInAt: null, expectedMinutes: null, onRequest: false, reporter: "openrig-observed", reason: "not shown" },
] };
const snap = await hydrateSnapshot(fixtureClient({}, { "/api/queue/hosted-members": hosted }));
expect(snap.readErrors.some((error) => error.includes("hosted"))).toBe(false);
const rigView = createViewState({ instanceId: "t", getSnapshot: () => snap });
rigView.dispatch({ type: "drill", resource: "rig", name: "myrig" });
const rigLines = renderScreen(rigView.get(), snap, { cols: 220, rows: 60 }).lines.join("\n");
expect(rigLines).toContain("Connected assistants (outside the terminal; each checks its own queue):");
expect(rigLines).toContain(`chat@myrig overdue: last check-in ${displayTime("2026-11-12T13:05:00.000Z")}, expected every 60 min; its schedule may be off or waiting for an approval`);
expect(rigLines).toContain(`desk@myrig on request: it checks its queue when a person asks it; last check-in ${displayTime("2026-11-12T12:00:00.000Z")}`);
expect(rigLines).not.toContain("bot@downrig");
const instanceView = createViewState({ instanceId: "t", getSnapshot: () => snap });
instanceView.dispatch({ type: "drill", resource: "host", name: snap.hosts[0]!.name });
const instanceLines = renderScreen(instanceView.get(), snap, { cols: 160, rows: 60 }).lines.join("\n");
expect(instanceLines).toContain("chat@myrig overdue:");
// A status this TUI doesn't know reads unknown, without the newer daemon's reason.
expect(instanceLines).toContain("bot@downrig unknown");
expect(instanceLines).not.toContain("not shown");
});
it("a known-empty list of connected assistants stays quiet", async () => {
const snap = await hydrateSnapshot(fixtureClient());
expect(snap.hosts[0]!.connectedAssistants).toEqual([]);
expect(snap.hosts[0]!.connectedAssistantsUnavailable).toBeUndefined();
const view = createViewState({ instanceId: "t", getSnapshot: () => snap });
view.dispatch({ type: "drill", resource: "rig", name: "myrig" });
expect(renderScreen(view.get(), snap, { cols: 160, rows: 60 }).lines.join("\n")).not.toContain("Connected assistants");
});
it.each([
["an older daemon without the route", { overrides: { "/api/queue/hosted-members": { status: 404 } } }, "this daemon doesn't serve it"],
["a failed read", { overrides: { "/api/queue/hosted-members": { status: 500 } } }, "the read failed: HTTP 500"],
["a dropped connection", { overrides: { "/api/queue/hosted-members": { status: 0 } } }, "the read failed: fetch failed"],
["an answer without a members list", { responses: { "/api/queue/hosted-members": { hostId: "mm2-openrig1" } } }, "the daemon's answer couldn't be read"],
])("%s says check-in is unavailable, not that there are none", async (_case, setup, reason) => {
const snap = await hydrateSnapshot(fixtureClient("overrides" in setup ? setup.overrides : {}, "responses" in setup ? setup.responses : {}));
expect(snap.hosts[0]!.connectedAssistants).toBeUndefined();
expect(snap.hosts[0]!.connectedAssistantsUnavailable).toBe(reason);
// Optional, like the other enrichment: the page itself still reads as whole.
expect(snap.readErrors).toEqual([]);
const line = `Connected assistants: check-in unavailable (${reason})`;
const rigView = createViewState({ instanceId: "t", getSnapshot: () => snap });
rigView.dispatch({ type: "drill", resource: "rig", name: "myrig" });
const rigLines = renderScreen(rigView.get(), snap, { cols: 160, rows: 60 }).lines.join("\n");
expect(rigLines).toContain(line);
expect(rigLines).not.toContain("each checks its own queue");
const instanceView = createViewState({ instanceId: "t", getSnapshot: () => snap });
instanceView.dispatch({ type: "drill", resource: "host", name: snap.hosts[0]!.name });
expect(renderScreen(instanceView.get(), snap, { cols: 160, rows: 60 }).lines.join("\n")).toContain(line);
});
it("shows confirmed missing sessions as detached unless lifecycle still requires attention", async () => {
const base = (FIXTURES["/api/rigs/01JRIG/nodes"] as Array<Record<string, unknown>>)[0]!;
const nodes = [
@@ -66,7 +66,9 @@ it("a 24-rig landing fetches names only; a selected rig never reads unrelated in
]);
// The rig Table reads health once without fetching other rigs' node inventories.
expect(calls.filter(c => c.startsWith("/api/health"))).toEqual(["/api/health?limit=200"]);
expect(calls).toHaveLength(10);
// One read of this daemon's connected assistants, which the rig Table lists after its seats.
expect(calls.filter(c => c === "/api/queue/hosted-members")).toHaveLength(1);
expect(calls).toHaveLength(11);
expect(snap.health).toMatchObject({ availability: "loaded", total: 0, records: [] });
expect(renderScreen(view.get(), snap, { cols: 220, rows: 60 }).lines.join("\n")).toContain("no findings served; not a healthy verdict");
});