mirror of
https://github.com/mvschwarz/openrig.git
synced 2026-11-13 18:49:34 -10:00
Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
02e7fd1083 | ||
|
|
45d390d157 | ||
|
|
0da9a30622 | ||
|
|
8dcc06eb2b | ||
|
|
795dcc8538 | ||
|
|
7539373d5c | ||
|
|
bd08e0f094 | ||
|
|
c2815a6139 | ||
|
|
a1dd3333b4 | ||
|
|
0a6d575bd8 | ||
|
|
94fa158ce2 | ||
|
|
315316301a | ||
|
|
f809178714 | ||
|
|
27444ad275 | ||
|
|
3b32f76d12 | ||
|
|
8476bf03d5 | ||
|
|
2c24b49e4f | ||
|
|
921e09cce3 | ||
|
|
675af15159 | ||
|
|
e6e0702045 | ||
|
|
ac921ac5d1 | ||
|
|
bfd3a7f596 | ||
|
|
240598c11d | ||
|
|
aefbf29938 |
No files matched your search
@@ -84,12 +84,14 @@ Shared test vectors are in `schemas/fixtures/identity-vectors.json`.
|
||||
|
||||
`seats` gives a `pod.member` the runtimes it may use, and the profile each runtime uses. A member it doesn't list keeps
|
||||
the runtime `rig.yaml` gives it. `presets` names full mappings, and `recommended` names one of them, which must be
|
||||
`rig.yaml` as written. `rig bundle create`, `rig bundle configurations` and `rig bundle check` refuse a file that breaks
|
||||
these rules.
|
||||
`rig.yaml` as written. `rig bundle check` reports a file that breaks these rules as a finding, and
|
||||
`rig bundle configurations` names the problem instead of listing.
|
||||
|
||||
`--preset` and `--seat` choose a configuration (see the [rig bundle reference](rig-bundle.md)). Any mix of each seat's
|
||||
declared runtimes can be built, not only the presets; a runtime a seat doesn't declare is refused, and nothing is built.
|
||||
Without either flag, create builds `rig.yaml` as written. The built archive's manifest records
|
||||
declared runtimes can be built, not only the presets. A runtime a seat doesn't declare, or a choice from a file that
|
||||
breaks these rules, is refused, and nothing is built. Without either flag, `rig bundle create`, and `rig bundle inspect`,
|
||||
`rig bundle install` and `rig up` of a GitHub folder link, use `rig.yaml` as written and don't check
|
||||
`configurations.yaml`. The built archive's manifest records
|
||||
`configuration: { id, preset }` outside the package digest; `preset` is there only when `--preset` or `--seat` chose a
|
||||
mapping that matches a declared preset.
|
||||
|
||||
|
||||
@@ -20,7 +20,8 @@ The CLI itself finds the daemon in these orders:
|
||||
`$OPENRIG_HOME/daemon.json` when it holds a valid `pid` and `port`; else the config keys `daemon.host` and
|
||||
`daemon.port` (environment `OPENRIG_HOST` and `OPENRIG_PORT`), which default to `127.0.0.1:7433`.
|
||||
- **Status** (`rig status`, `rig daemon status`): `OPENRIG_URL` (or `RIGGED_URL`) first, probed directly; else
|
||||
the state file below.
|
||||
the state file below. If no state is read, probe the configured `daemon.host` and `daemon.port` instead (defaulting
|
||||
to `127.0.0.1:7433`).
|
||||
- **Start and stop** (`rig daemon start`, `stop`): the state file, `$OPENRIG_HOME/daemon.json`, then the legacy
|
||||
`~/.rigged/daemon.json`.
|
||||
|
||||
@@ -179,8 +180,7 @@ With `needs-me.read` supported:
|
||||
`revision` and `about`. `revision` is the request's opaque decision revision: the same value as that row's
|
||||
`decisionRevision`, and what an answer can name as `expectedRevision` so it applies only to the version the person
|
||||
read. `about` lists the requests it concerns by id: a row parked on the person is itself the request, and an ask is
|
||||
about the open rows blocked on it (the newest 100, with `aboutTruncated: true` when there are more). An empty `about`
|
||||
isn't proof that it's about nothing: a request that names it only in its text isn't counted.
|
||||
about the open rows blocked on it (at most 100; empty when none are recorded).
|
||||
- **A snapshot watermark:** the response's `watermark` is the newest event `seq` read before the snapshot. Follow
|
||||
`GET /api/events` from it with `Last-Event-ID: <watermark>`: every event after the snapshot is replayed, some possibly
|
||||
already reflected in it. A click that records or changes an answer emits `queue.answer_recorded` even while the set
|
||||
@@ -192,37 +192,7 @@ With `needs-me.read` supported:
|
||||
footer. `episode` names the park an answer belongs to, or is null. `recordedIdentity` is the identity provenance
|
||||
recorded when the answer row was created. An answer row's own read has `replyTo`, the request it answers. A partial
|
||||
set of choices stays on the request's `humanAnswers` until the whole set is returned. A runner's permission request
|
||||
or a host pairing request is answered in place, with no answer row. `answersFrom: "this-daemon"` says where they were
|
||||
read: an answer another host holds isn't among them, so an empty list isn't proof that nobody answered.
|
||||
|
||||
### What a connection supports, and what happened to a delivery (`member-connection.v1`)
|
||||
|
||||
`GET /api/member-connection/capabilities` lists each delivery route this daemon declares, with what it supports in four
|
||||
groups: `observe` (`dialog`, `turnStart`), `control` (`submit`), `nativeIdentity` (`sessionId`, `resume`) and
|
||||
`continuity` (`managedCompaction`, `restorePacketConfirmation`, `fork`). The routes are `typed` (OpenRig types into the
|
||||
member's terminal; capabilities by runtime, with `*` for any other), `codex-queue` (Codex's own queue command), a hosted
|
||||
member's `hosted-trigger`, and a person's `gateway`. A route with `armed: false` is declared but not used: nothing is
|
||||
delivered on it until a setting arms it.
|
||||
|
||||
Each capability reads `supported`, `not-supported`, `unavailable` (the route has it, but this member can't use it now,
|
||||
such as a seat with no session recorded as current), `not-applicable` (it means nothing on this route) or `unknown`. A
|
||||
missing key means `unknown`. None of them means idle or success, and a declaration isn't readiness: whether a seat has a
|
||||
current session comes from what OpenRig has recorded, not from looking at its pane or process. A daemon without the route (HTTP 404) predates the contract: treat
|
||||
every capability as unknown and keep using what works today.
|
||||
|
||||
`?session=<address>` adds `member`: `{ member, route, runtime, capabilities, reason? }` for the member that address
|
||||
names: a person the human registry resolves (or the terminal person's own `human@host`), a hosted member, or a seat. An
|
||||
address shaped like a person's, such as `<id>@external`, is a person only when the registry resolves it. A person is
|
||||
resolved first, so when the registry can't be read, any address it could resolve to a person (`<id>@external`, or any
|
||||
`member@rig`, since a person's id can be spelled that way) comes back unknown, even if a seat or hosted member has that name. That
|
||||
answer, and an address none of them has, comes back with `route: null`, every capability `unknown`, and the reason.
|
||||
|
||||
Each typed send also records what happened to it, in the daemon's `transport.delivery_evidence` event, as
|
||||
`outcome: { fact, reporter, route }`. `fact` is `accepted` (typed and submitted, with `renderVerified: true` when
|
||||
the screen showed it), `held`, `not-delivered`, `failed-effect-unknown` or `unknown`. A prompt answer typed without Enter on a send that
|
||||
succeeded is `unknown`: whether the prompt took it isn't known; if the send failed after typing, it's
|
||||
`failed-effect-unknown`. `reporter` says who established it.
|
||||
None of them means the member read the work: picking it up is a claim on the row.
|
||||
or a host pairing request is answered in place, with no answer row.
|
||||
|
||||
## Route details
|
||||
|
||||
@@ -262,6 +232,7 @@ None of them means the member read the work: picking it up is a claim on the row
|
||||
Success is 201 with `instance`, `spec`, `entryQitemId` and `entryOwnerSession`, any `advisories`, and
|
||||
`scopeIgnored` when a scope wasn't applied. The instance keeps `rootObjective`, which every instance read returns
|
||||
(`/api/workflow/list`, `/api/workflow/<id>` and its `trace`). An instance started before it was kept reads `null`.
|
||||
- **`GET /api/workflow/list`** accepts exact `project`, `mission`, `slice`, `rig` (the bound rig), and `name` (the workflow name) filters, repeatable `tag` filters on the instance's free-form scope tags, and `limit` from 1 to 10,000. Filters combine with AND and apply before the limit; results keep their existing oldest-first order. Instances without the requested scope or binding do not match. Without these filters, existing list behavior is unchanged.
|
||||
- **`GET /api/provider/usage`** returns `{ hostUsage }`, this host's usage rows (`host: "local"`, a `provider`
|
||||
and a `state`). A Claude row's `windows` are the seats' status-line readings, one entry per reading, each with
|
||||
its `window`, `usedPercent`, `resetsAt`, `asOf` and `seatSession`. A Codex row has `windows: []`. Treating the
|
||||
|
||||
@@ -26,9 +26,11 @@ A person can also bind to a local bridge adapter using a `relay` binding:
|
||||
`rig gateway human add bob --display-name "Bob" --delivery-class B --binding "relay:local-bridge:file:/etc/openrig/relay.env:primary:handle=bob-ops"`
|
||||
(see [Gateway Relay Reference](gateway-relay.md) for endpoint, secret provisioning, and custody architecture).
|
||||
`human@host` is the unnamed person at the terminal; `human@kernel` is also accepted as a human/gate address.
|
||||
These aliases (including `human-<name>@host` and `human-<name>@kernel`) are not agent sessions: reply with
|
||||
`rig queue create --destination human@host --human-intent update --summary "<one line>" --evidence-ref "<path>" --body "..." --verify`,
|
||||
substituting the sender's address and your summary, evidence path and reply. A reply destination doesn't identify
|
||||
These aliases (including `human-<name>@host` and `human-<name>@kernel`) are not agent sessions. A row addressed to
|
||||
`human@host` names no person: it asks no one, waits on Steering and in the Feed, and OpenRig reports it as undeliverable. To reply to a person, use
|
||||
their registered address:
|
||||
`rig queue create --destination <their address> --human-intent update --summary "<one line>" --evidence-ref "<path>" --body "..." --verify`,
|
||||
substituting your summary, evidence path and reply. A reply destination doesn't identify
|
||||
who acted or determine who may answer an ask. Clients acting as a registered person name that person's
|
||||
`actorSession`; a seat identity header takes precedence. The terminal's primary-user authority records the unnamed
|
||||
`human@host` actor, not the person whose queue is being viewed.
|
||||
|
||||
@@ -208,8 +208,8 @@ curl -fsSL https://raw.githubusercontent.com/mvschwarz/openrig/v0.7.12/scripts/i
|
||||
|
||||
The same command without `--dry-run`,
|
||||
`curl -fsSL https://raw.githubusercontent.com/mvschwarz/openrig/v0.7.12/scripts/install.sh | sh`, installs the
|
||||
latest published `@openrig/cli` with `npm install -g`,
|
||||
runs the Node.js and SQLite check, then `rig setup --dry-run` and `rig setup`. `rig setup` checks both Claude Code and
|
||||
latest published `@openrig/cli` with `npm install -g`, runs the Node.js and SQLite check if the installed checker is
|
||||
present (otherwise it reports the check skipped), then runs `rig setup --dry-run` and `rig setup`. `rig setup` checks both Claude Code and
|
||||
Codex and may install a missing one, as described below. A failed step prints
|
||||
`FAILED [n/4] <command or check> (exit <code>)` for steps 1–3. If step 4 is not ready, it reports
|
||||
`INSTALLED, SETUP NOT COMPLETE` and points to the details from `rig setup` above. Follow that output and any Fix, then rerun
|
||||
@@ -308,11 +308,12 @@ team. `rig daemon start --no-kernel` is for automation or an explicit request to
|
||||
omit the kernel; it leaves you without that operator.
|
||||
|
||||
On a fresh instance, explicit daemon startup chooses the kernel variant from
|
||||
successful native auth probes: Claude alone, Codex alone, or both. It starts the
|
||||
kernel in the background without a project starter. An absent unused provider is
|
||||
fine; if both accounts are authenticated, the kernel uses both even when your
|
||||
later project uses just one. A request to use only one provider for everything
|
||||
is a separate choice.
|
||||
the providers selected by `rig setup --providers` that pass native auth probes:
|
||||
Claude alone, Codex alone, or both. If no choice was recorded, it considers every
|
||||
signed-in provider. `OPENRIG_PROVIDER_SELECTED` in the daemon's environment
|
||||
overrides the saved choice. It starts the kernel in the background without a
|
||||
project starter. An absent unused provider is fine. The kernel choice and a
|
||||
later project's provider choice are separate.
|
||||
|
||||
`/api/kernel/status` retains the chosen template (`rig.yaml`,
|
||||
`rig-claude-only.yaml` or `rig-codex-only.yaml`) across daemon restarts and
|
||||
|
||||
@@ -124,10 +124,12 @@ manual replay. A recurring reminder keeps its next normal cycle under a new occu
|
||||
finishing its accounting does not type the same occurrence twice.
|
||||
|
||||
Exhausted retries end only the failed occurrence, with its cause and next action; a recurring
|
||||
reminder keeps its next normal cycle. A permanent transport failure leaves a terminal job:
|
||||
correct the destination and register a replacement reminder. A one-shot park timer records its
|
||||
failed or unconfirmed wake on the parked row before it ends. A retryable failure is recorded
|
||||
there while the timer stays armed. Deliberately held
|
||||
reminder keeps its next normal cycle, and a permanent transport failure leaves it a terminal job:
|
||||
correct the destination and register a replacement reminder. A one-shot park timer (`--wake-after`)
|
||||
has no later cycle, so neither the retry limit nor a permanent transport failure ends it while its
|
||||
task is still set aside: each failure before input is recorded on the parked row while the timer
|
||||
stays armed, and it retries until it's delivered or the park ends. If input may have reached the
|
||||
seat, it records the unconfirmed wake on the parked row and ends. Deliberately held
|
||||
input keeps its existing retained-message custody. Condition watches and parked-owner policy
|
||||
behavior are unchanged. This does not replay failed occurrences recorded by older versions.
|
||||
|
||||
@@ -289,11 +291,14 @@ Unknown: not said yet.
|
||||
stopped (the first fire comes one interval after you register it), and it stops when the agent that registered it
|
||||
is replaced. It's fine for agent-to-agent reminders. Your own watch timers also show as `periodic-reminder` in
|
||||
`rig watchdog list`: that's the one-shot timer `--wake-after` arms, not a registered repeating reminder. It's retired
|
||||
when it fires or when the task stops being set aside. A wake held back because you were typing (a retained
|
||||
delivery) wasn't delivered, so it doesn't use the timer up: it's tried again at each interval until an attempt goes
|
||||
through (delivered or failed), which retires it. A timer another task shares through `--wake-watchdog` stays live
|
||||
for that task when this task is handed off or stopped, and the same rule applies to its wake. None of this is a
|
||||
delivery guarantee.
|
||||
after delivery, when the occurrence ends, or when the task stops being set aside. A wake held back because you were typing (a retained
|
||||
delivery) wasn't delivered, so it doesn't use the timer up. A failure known to have happened before input reached
|
||||
the seat also keeps the same wake owed and retries on the existing cadence until delivery or the park ends. If input
|
||||
may have reached the seat, the occurrence ends without automatic replay; inspect the receipt before retrying.
|
||||
A timer another task shares through `--wake-watchdog` stays live for that task when this task is
|
||||
handed off or stopped, and a held-back wake doesn't use it up. Once this task's park has ended, though,
|
||||
a failure before input to that task is retried only up to `queue.wake_retry_cap` times (a permanent
|
||||
transport failure ends it at once), and then the timer ends. None of this is a delivery guarantee.
|
||||
- **Transcript bytes as "usage".** `context-usage-threshold` measures an agent's transcript, not an account's
|
||||
allowance. For an allowance, see "A usage warning" above.
|
||||
|
||||
|
||||
@@ -324,6 +324,90 @@ envelope. An OpenRig older than 0.7.3 doesn't read a recorded envelope, so after
|
||||
the seat launches without it. The field is also supported on legacy flat Codex nodes; other
|
||||
runtimes reject it.
|
||||
|
||||
For an explicit filesystem policy, use `filesystem` **instead of** `sandbox` and its
|
||||
workspace-write fields. This is the same per-seat selection and audited setter:
|
||||
|
||||
```yaml
|
||||
cwd: /workspace/shared
|
||||
env:
|
||||
CODEX_HOME: /accounts/codex # existing account home; never copied
|
||||
codex_permissions:
|
||||
approval: never
|
||||
filesystem:
|
||||
":minimal": read
|
||||
":workspace_roots": write
|
||||
"/workspace/shared/private": deny
|
||||
network_access: false
|
||||
```
|
||||
|
||||
The mapping accepts native `read`, `write` and `deny` values at absolute paths,
|
||||
`~/path`, or `:root`, `:minimal`, `:workspace_roots` (alias `:project_roots`),
|
||||
`:tmpdir` and `:slash_tmp`.
|
||||
It must be nonempty; nested subpath maps and arbitrary Codex settings are not part
|
||||
of this option. Omitted network access becomes `false`. Include the read access
|
||||
your tools and installed Codex executable need; this custom profile adds no
|
||||
workspace, temporary, queue-state, seat-folder or Git-directory write grants of
|
||||
its own. Native Codex decides whether the host can enforce the supplied rules.
|
||||
Filesystem approval accepts `never` or `on-request`; the retired `untrusted`
|
||||
approval is rejected before the selection is saved.
|
||||
|
||||
OpenRig emits the policy as invocation-local `permissions.openrig-seat` and
|
||||
`default_permissions` overrides, with the selected approval. It writes no policy
|
||||
file, so two seats can share both `CODEX_HOME` and `cwd` without overwriting each
|
||||
other. Clearing the selection changes only that seat's record. Existing
|
||||
account-scoped `codex_config_fragment` resources and their root-key rejection
|
||||
stay unchanged.
|
||||
|
||||
Before dispatch, OpenRig compares Codex's native configuration with the seat's
|
||||
selection. Positive evidence of access widening, a conflicting profile or
|
||||
approval choice, an excluding managed allowlist, or a missing/empty selected
|
||||
profile refuses launch. Compatible managed defaults and allowlists, harmless
|
||||
descriptions and provably narrower flat rules are accepted. Legacy sandbox
|
||||
settings are inert under the invocation's explicit permission-profile selection.
|
||||
Null fields are treated as absent, including unfamiliar optional fields.
|
||||
Managed `defaultPermissions` is a fallback, not a forced selection; the
|
||||
effective profile and managed allowlist determine whether the agent's choice holds.
|
||||
|
||||
A timeout, reader failure, unfamiliar representation or unsupported managed
|
||||
requirement continues with the authored flags and reports `policy not verified:
|
||||
<reason>` in the launch observation and status. The policy is never dropped or
|
||||
swapped, and account/project settings are never edited to make the check pass.
|
||||
Absent selection or approval fields, unfamiliar approval strings or profile formats,
|
||||
and unclear overlap between native selectors and authored path rules are also unverified.
|
||||
An authored selector that may cover an extra grant is considered before a literal
|
||||
ancestor would reject that grant, except that an explicit non-root deny ancestor
|
||||
always takes precedence over possible selector coverage. A full-root deny, written
|
||||
as `/` or `:root`, is a default narrower grants may refine: possible authored
|
||||
selector coverage stays unverified, while a proven outside grant still refuses.
|
||||
Codex 0.167.2's `:minimal` adds system read defaults, not `/home` or `/Users`
|
||||
user-data coverage; extra grants there under a root deny or with no root rule still refuse unless
|
||||
another authored rule may cover them. Other minimal-path coverage stays unexpanded.
|
||||
Duplicate aliases from a
|
||||
lower layer leave their own coverage unverified; they do not hide a known widening
|
||||
at another path.
|
||||
Inconclusive coverage warnings name the extra rule and access. An excluding managed
|
||||
allowlist is reported before an effective selection or approval mismatch.
|
||||
Concrete refusals name the conflicting rule and offer a remedy; handover preserves
|
||||
that remedy while leaving the predecessor running.
|
||||
Without an explicit `CODEX_HOME`, OpenRig resolves the normal account home and
|
||||
pins it for both the read and launch; an unresolvable home is reported as
|
||||
unverified. A named `codex_config_profile` is retained but unverified because the
|
||||
native reader cannot load that layer on this path. A `launch_wrapper` is also
|
||||
retained and unverified: it may change the effective home/configuration, so a
|
||||
read without that wrapper cannot certify the launch.
|
||||
|
||||
The filesystem selection replaces permission-mode and team/kernel defaults,
|
||||
including ambient YOLO. Fresh launches, both resume paths and restore emit the
|
||||
same selection. Hand-resuming from the command shown by `rig ps` does not yet
|
||||
carry this filesystem policy. A rebuild uses the saved filesystem policy ahead of an observed
|
||||
predecessor sandbox; clearing or replacing the policy after a snapshot takes
|
||||
effect on restore. Status reports the plan and its limits, not observed native
|
||||
enforcement. Handover checks the successor's filesystem selection before
|
||||
signaling the predecessor; a concrete conflict leaves that predecessor running.
|
||||
Configuration can change between the preflight and native startup;
|
||||
the read and launch are not atomic. Codex's sandbox governs local command
|
||||
execution, not every connector, account or external service.
|
||||
|
||||
For an existing seat, put the envelope in a JSON file, or change its profile, with the existing
|
||||
audited permission command:
|
||||
|
||||
|
||||
@@ -24,9 +24,15 @@ a shell prompt holds them. Keep the default for a seat that may fall back to a s
|
||||
|
||||
Runtime permissions are separate. Recipient and interactive-prompt checks still
|
||||
apply. `--raw` and `--force` do not bypass the typing guard. A deliberate
|
||||
`--dangerously-interact --reason` remains available at every interruption level
|
||||
`--dangerously-interact --reason` remains available in every mode, `hold` included,
|
||||
and uses the existing-input check below. Direct human input remains available.
|
||||
|
||||
An ordinary `rig send` types the message inside its From/To envelope, whose first
|
||||
line is `From:`, so a message that starts with `/` stays literal text rather than
|
||||
running as the agent's slash command. `--raw` and `--dangerously-interact` type the
|
||||
exact text, with no envelope. Claude Code (2.1.322) turns a pasted tab into four
|
||||
spaces, so tabs reach a Claude Code seat as spaces.
|
||||
|
||||
A message sent to a busy Codex seat joins its running turn and may redirect it.
|
||||
For separate work, create a queue row instead:
|
||||
`rig queue create --destination <seat> --summary "<one line>" --body-file <file>`.
|
||||
|
||||
@@ -132,6 +132,10 @@ reaction on any other message, including a person's reply in the thread, is igno
|
||||
`reaction_added` event: add both under **OAuth & Permissions** and **Event Subscriptions**, then
|
||||
reinstall the app to the workspace.
|
||||
|
||||
Human-row posts suppress link and media previews by default. Run `rig slack setup --unfurl on` to
|
||||
allow Slack previews, or `rig slack setup --unfurl off` to suppress them again. The selection reaches
|
||||
the running connector on its next rewire or daemon restart; it does not remove already posted previews.
|
||||
|
||||
To have reactions ignored instead, run `rig slack setup --reactions off`. The agent that asked
|
||||
never hears of a reaction, including one still waiting to be retried, and a person answers an ask by
|
||||
typing a reply in its thread. Slack still sends the event and the manifest keeps it, so switching
|
||||
|
||||
@@ -1166,14 +1166,19 @@ Exit codes:
|
||||
}
|
||||
|
||||
if (limited.length === 0) {
|
||||
// The daemon identity rides on every empty-fleet line: with more than
|
||||
// one daemon in a house (OPENRIG_URL, hosts.yaml), a targetless "No rigs"
|
||||
// invites reading another daemon's answer as this one's — an empty fleet
|
||||
// read from the wrong daemon reads as a dead fleet.
|
||||
const daemonLabel = ` · daemon ${client.baseUrl}`;
|
||||
if (parsedFilter) {
|
||||
console.log(`No rigs match --filter ${parsedFilter.key}=${parsedFilter.value}`);
|
||||
console.log(`No rigs match --filter ${parsedFilter.key}=${parsedFilter.value}${daemonLabel}`);
|
||||
} else if (archivedCount > 0 && !opts.includeArchived) {
|
||||
// Proven-empty with the history pointer, never a bare "No rigs"
|
||||
// while archived history exists.
|
||||
console.log(`No active rigs · ${archivedCount} archived (rig ps --include-archived)`);
|
||||
console.log(`No active rigs · ${archivedCount} archived (rig ps --include-archived)${daemonLabel}`);
|
||||
} else {
|
||||
console.log("No rigs");
|
||||
console.log(`No rigs${daemonLabel}`);
|
||||
}
|
||||
// A host can have connected assistants and no terminal rigs at all.
|
||||
await printConnectedAssistants(client, opts.rig);
|
||||
@@ -1192,7 +1197,7 @@ Exit codes:
|
||||
// FR-1 display element 1: the host rollup line.
|
||||
const rollupSeats = tableRows.reduce((n, e) => n + e.nodeCount, 0);
|
||||
const rollupAttention = tableRows.reduce((n, e) => n + (e.attentionCount ?? 0), 0);
|
||||
console.log(`${tableRows.length} rig${tableRows.length === 1 ? "" : "s"} · ${rollupSeats} seat${rollupSeats === 1 ? "" : "s"} · ${rollupAttention} need${rollupAttention === 1 ? "s" : ""} attention`);
|
||||
console.log(`${tableRows.length} rig${tableRows.length === 1 ? "" : "s"} · ${rollupSeats} seat${rollupSeats === 1 ? "" : "s"} · ${rollupAttention} need${rollupAttention === 1 ? "s" : ""} attention · daemon ${client.baseUrl}`);
|
||||
|
||||
// Human output: apply default truncation budget unless --full.
|
||||
const humanList = (opts.full || limit !== null) ? tableRows : tableRows.slice(0, HUMAN_RIG_BUDGET);
|
||||
|
||||
@@ -1402,8 +1402,8 @@ export function queueCommand(depsOverride?: QueueDeps): Command {
|
||||
.option("--blocked-on <blocker>", "For state=blocked: the blocker — a qitem id (must exist and be live), a human seat (FR-6 park; requires summary + evidence_ref), or a typed non-qitem gate 'fold:<what>' / 'auth:<what>' / 'external:<what>'")
|
||||
.option("--wake-watchdog <jobId>", "For state=blocked: attach an existing live watchdog id targeting the row owner")
|
||||
.option("--wake-after <duration>", "For state=blocked: atomically arm a timer (for example 90s, 15m, 2h)", wakeDurationSeconds)
|
||||
.option("--summary <text>", "Summary persisted onto the item (human-seat parks, or standalone summary update without --state)")
|
||||
.option("--evidence-ref <path>", "Pointer to the durable artifact, persisted onto the item on a human-seat park or a done close (--state done). For a code result, a JSON file of kind openrig.code-result/v1 (repo, base and revision as full commit ids, paths) lets a reader diff it exactly")
|
||||
.option("--summary <text>", "Summary persisted onto the item, with or without a state change (a blank one isn't stored)")
|
||||
.option("--evidence-ref <path>", "Pointer to the durable artifact, persisted onto the item with a state change (a park, a done close; a blank one isn't stored). For a code result, a JSON file of kind openrig.code-result/v1 (repo, base and revision as full commit ids, paths) lets a reader diff it exactly")
|
||||
.option("--note <text>", "Transition note for the audit log")
|
||||
.addHelpText("after", `
|
||||
After reading an existing remote successor, record its exact closure target, including the host:
|
||||
|
||||
@@ -78,6 +78,10 @@ export function renderShortStamp(stampISO: string): string {
|
||||
return `${stampISO.slice(5, 7)}-${stampISO.slice(8, 10)} ${stampISO.slice(11, 16)}Z`;
|
||||
}
|
||||
|
||||
/** The address OpenRig records an answer typed at this machine under (the daemon's UNATTRIBUTED_ACTOR). It names nobody,
|
||||
* and a row there asks no one (it waits on Steering and in the Feed, and OpenRig reports it as undeliverable), so a reply hint never points at it. */
|
||||
const UNATTRIBUTED_PERSON = "human@host";
|
||||
|
||||
export function wrapSendBody(
|
||||
sender: string | undefined,
|
||||
recipient: string,
|
||||
@@ -108,6 +112,8 @@ export function wrapSendBody(
|
||||
}
|
||||
const reply = senderLabel.endsWith("@external")
|
||||
? `↩ Reply if needed: rig queue create --destination ${senderLabel}${meta?.replyToQitem ? ` --human-intent update --reply-to ${meta.replyToQitem}` : ""} --summary "<one line>" --body "..." --verify`
|
||||
: personAddress === UNATTRIBUTED_PERSON
|
||||
? `↩ ${senderLabel} names no person: a reply there asks no one. It waits on Steering and in the Feed, and OpenRig reports it as undeliverable. To ask the person back, use their registered address (rig gateway human list lists who's registered).`
|
||||
: isHumanSeatSessionRef(personAddress)
|
||||
? `↩ Reply if needed: rig queue create --destination ${senderLabel} --human-intent update --summary "<one line>" --evidence-ref "<path>" --body "..." --verify`
|
||||
: meta?.senderReachable === false
|
||||
|
||||
@@ -188,6 +188,7 @@ export function slackCommand(deps: SlackDeps = {}): Command {
|
||||
.option("--secrets-env-file <path>", "path to the 0600 env file with SLACK_BOT_TOKEN / SLACK_APP_TOKEN")
|
||||
.option("--required-scopes <csv>", "comma-separated bot scopes to require at verify time")
|
||||
.option("--reactions <mode>", "what a person's emoji reaction on an OpenRig post does: route (default) makes a row for the seat that asked; off ignores reactions, so an acknowledging emoji costs no agent turn")
|
||||
.option("--unfurl <mode>", "link and media previews on human-row posts: off (default) or on; takes effect when the connector rewires")
|
||||
.option("--reason <reason>", "Reason recorded with the configuration change", "configure human delivery")
|
||||
.option("--actor <actor>", "Named operator when outside a managed seat")
|
||||
.action(async (opts) => {
|
||||
@@ -203,6 +204,7 @@ export function slackCommand(deps: SlackDeps = {}): Command {
|
||||
secretsEnvFile: opts.secretsEnvFile ?? cur.secretsEnvFile,
|
||||
requiredScopes: opts.requiredScopes ? String(opts.requiredScopes).split(",").map((s: string) => s.trim()).filter(Boolean) : cur.requiredScopes,
|
||||
...(opts.reactions !== undefined ? { reactions: opts.reactions } : {}),
|
||||
...(opts.unfurl !== undefined ? { unfurl: opts.unfurl } : {}),
|
||||
};
|
||||
const { runChannelOperation, channelStateDigest } = await import("@openrig/daemon/gateway-slack");
|
||||
const result = await runChannelOperation({
|
||||
|
||||
@@ -516,8 +516,15 @@ Examples:
|
||||
|
||||
cmd
|
||||
.command("list")
|
||||
.description("List workflow instances; optionally filter by status")
|
||||
.description("List workflow instances with optional exact filters")
|
||||
.option("--status <s>", "Filter by status (active | waiting | completed | failed | aborted)")
|
||||
.option("--project <id>", "Match the instance project")
|
||||
.option("--mission <id>", "Match the instance mission")
|
||||
.option("--slice <id>", "Match the instance slice")
|
||||
.option("--rig <name>", "Match the bound rig")
|
||||
.option("--name <workflow>", "Match the workflow name")
|
||||
.option("--tag <tag>", "Match a scope tag; repeat to require all tags", (tag: string, previous: string[]) => [...previous, tag], [])
|
||||
.option("--limit <n>", "Maximum matching instances (1-10000)")
|
||||
.option("--json", "JSON output for agents")
|
||||
.addHelpText("after", `
|
||||
Examples:
|
||||
@@ -525,10 +532,12 @@ Examples:
|
||||
$ rig workflow list --status active --json
|
||||
$ rig workflow list --status waiting | jq -r '.instances[].instanceId'
|
||||
`)
|
||||
.action(async (opts: { status?: string; json?: boolean }) => {
|
||||
.action(async (opts: { status?: string; project?: string; mission?: string; slice?: string; rig?: string; name?: string; tag: string[]; limit?: string; json?: boolean }) => {
|
||||
const deps = getDeps();
|
||||
const params = new URLSearchParams();
|
||||
if (opts.status) params.set("status", opts.status);
|
||||
for (const field of ["project", "mission", "slice", "rig", "name", "limit"] as const) if (opts[field] !== undefined) params.set(field, opts[field]!);
|
||||
for (const tag of opts.tag) params.append("tag", tag);
|
||||
const qs = params.toString();
|
||||
await withClient(deps, async (client) => {
|
||||
const res = await client.get<unknown>(`/api/workflow/list${qs ? `?${qs}` : ""}`);
|
||||
|
||||
@@ -325,7 +325,6 @@ function withoutDaemonLinkedRows<T>(row: T): T {
|
||||
delete fields.successorsTruncated;
|
||||
delete fields.successorNote;
|
||||
delete fields.answers;
|
||||
delete fields.answersFrom;
|
||||
return fields as T;
|
||||
}
|
||||
|
||||
@@ -652,11 +651,35 @@ function sharedInstructions(has: (tool: string) => boolean): string[] {
|
||||
const SHARED_INSTRUCTIONS = sharedInstructions(() => true);
|
||||
const INSTRUCTIONS = [...SHARED_INSTRUCTIONS, MEMBER_WORKFLOW].join("\n");
|
||||
|
||||
/** For a connection that relays a person's request to another assistant (an external caller, or the front door): which one
|
||||
* they mean is theirs to say when more than one fits, never inferred from the agent's own history. The listing steps need
|
||||
* rig_team, so a connection without it is told only to ask. Pickup is said only where it's true: another connected
|
||||
* assistant waits for its person; on the front door, a running team seat is woken, and one sent to anyway waits until it's
|
||||
* back. A member, which works items, isn't given it. */
|
||||
function askWhichAssistant(canList: boolean, frontDoor: boolean): string {
|
||||
if (!canList) {
|
||||
return "If more than one assistant could be the one your person means, ask which; don't pick from your own history or memory. If your person names one clearly, go ahead.";
|
||||
}
|
||||
return [
|
||||
"Before sending a request to another assistant, list the team's members.",
|
||||
"If more than one could be the one your person means, ask which, using their names from the list (like \"Sam's Claude\"); if the list shows only addresses, describe each in plain words from what the list says about it (like \"the Claude assistant\"), never reading the address out.",
|
||||
"Don't pick from your own history or memory.",
|
||||
"If the list shows the chosen one detached or stopped, or a connected assistant with no check-in yet or overdue, say so before sending and ask whether to send it anyway.",
|
||||
"If the list says the chosen one's person was removed from the team, don't send; tell your person and ask whether to send it to someone else.",
|
||||
...(frontDoor ? ["When you send to a running team seat, tell your person that seat will pick it up on its own."] : []),
|
||||
"When you send to another connected assistant, tell your person it will be picked up the next time that assistant's person opens it, or on a schedule they've set up.",
|
||||
...(frontDoor ? ["If you sent it anyway, tell your person it waits until that one is back."] : []),
|
||||
"If your person names one clearly, or says to send it anyway to one that isn't connected, go ahead without asking again.",
|
||||
"If your person still asks to send to one whose person was removed, tell them it can't be delivered: requests to a removed person's assistant are closed unanswered.",
|
||||
].join(" ");
|
||||
}
|
||||
|
||||
/** rig mcp serve --front-door: the seat is a person's agent in their own app, the front door to their team, not a member
|
||||
* that works its inbox. The team's questions to it are the person's to answer. */
|
||||
export const FRONT_DOOR_WORKFLOW_VERSION = "front-door/v2";
|
||||
export const FRONT_DOOR_WORKFLOW_VERSION = "front-door/v3";
|
||||
export const FRONT_DOOR_WORKFLOW = [
|
||||
`Front door (${FRONT_DOOR_WORKFLOW_VERSION}). This seat is a person's agent in their own app: you hand the team their work and bring back what it produced, and you aren't one of its members.`,
|
||||
askWhichAssistant(true, true),
|
||||
"Items addressed to your seat (rig_queue_list with owned set) are usually the team's questions about work you handed it. They're the person's to answer, not yours: show each to the person with the team's draft, and record only what the person tells you.",
|
||||
"To record an answer, claim the item (rig_queue_claim), then close it done with closure reason no-follow-on and exactly what the person typed in resolution, with no label, quotation marks or words of your own (rig_queue_update). If the person isn't there, leave the item open and tell them it's waiting. Never choose an answer for them, and don't claim an item you can't close with their words.",
|
||||
"Nothing wakes this conversation when the team finishes: check your work and your items when the person asks or comes back.",
|
||||
@@ -694,8 +717,11 @@ function externalInboxInstructions(tools: ReadonlySet<string>): string {
|
||||
function instructionsFor(access: McpAccess | undefined, frontDoor = false): string {
|
||||
if (!access?.external) return frontDoor ? FRONT_DOOR_INSTRUCTIONS : INSTRUCTIONS;
|
||||
const tools = externalTools(access.external);
|
||||
const instructions = tools.has("rig_queue_claim") && tools.has("rig_queue_update") ? externalInboxInstructions(tools)
|
||||
const workflow = tools.has("rig_queue_claim") && tools.has("rig_queue_update") ? externalInboxInstructions(tools)
|
||||
: tools.has("rig_question_list") || tools.has("rig_question_answer") ? EXTERNAL_PERSON_INSTRUCTIONS : EXTERNAL_INSTRUCTIONS;
|
||||
// Only a grant with team/list may reach another connected assistant's seat, and it lists the team with rig_team.
|
||||
const instructions = tools.has("rig_queue_create")
|
||||
? `${workflow}\n${askWhichAssistant(tools.has("rig_team"), false)}` : workflow;
|
||||
return tools.has("rig_team") ? `Discover the team this grant connects you to by calling rig_team without rigId. A sole granted rig is selected automatically; with several, it returns the granted names to choose from.\n${instructions}` : instructions;
|
||||
}
|
||||
|
||||
@@ -1690,7 +1716,7 @@ export function createMcpServer(client: DaemonClient, options: { seat?: string;
|
||||
resolution: z.string().optional().describe("The outcome the item keeps, stored only by the update that closes an open item (as rig queue update --resolution)"),
|
||||
reopen: z.boolean().optional().describe("Reopen a closed item: give an active state (pending, in-progress or blocked) and a note (as rig queue update --reopen)"),
|
||||
summary: z.string().optional().describe("Replace the one-line summary"),
|
||||
evidenceRef: z.string().optional().describe("Pointer to the durable artifact, stored on the item when closing with state done or parking on a human seat; other updates refuse it. For a code result, a JSON file of kind openrig.code-result/v1 with repo, base and revision (full commit ids) and paths lets a reader diff it exactly"),
|
||||
evidenceRef: z.string().optional().describe("Pointer to the durable artifact, stored on the item with a state change (a park, a done close; a blank one isn't stored). For a code result, a JSON file of kind openrig.code-result/v1 with repo, base and revision (full commit ids) and paths lets a reader diff it exactly"),
|
||||
blockedOn: z.string().optional().describe("What it waits on, when blocking: another qitemId (this item returns to pending when that one closes), or the address of the person this item came from, not a shared channel (they're asked with this item's summary, and their answer returns it to you in progress)"),
|
||||
wakeAfterSeconds: z.number().int().positive().optional().describe("Wake this seat after this many seconds, when blocking. Delivered only to a seat with a terminal: an attached app can't receive it today, so the item just waits until it is checked."),
|
||||
}),
|
||||
|
||||
@@ -1110,11 +1110,10 @@ describe("rig mcp serve --http --grant-service on the daemon's routes", () => {
|
||||
db.prepare("UPDATE queue_items SET destination_session = 'human-x@external' WHERE qitem_id = ?").run(own);
|
||||
await repo.createHumanAnswer({ sourceSession: "human-x@external", destinationSession: CALLER, body: "The person's private reasoning",
|
||||
inboundReplyTo: own, nudge: false } as never);
|
||||
expect(await (await fetch(`${daemonUrl}/api/queue/${own}`)).json()).toMatchObject({ answers: [{ by: "human-x@external" }], answersFrom: "this-daemon" });
|
||||
expect(await (await fetch(`${daemonUrl}/api/queue/${own}`)).json()).toMatchObject({ answers: [{ by: "human-x@external" }] });
|
||||
const shown = await asExternal("rig_queue_show", { qitemId: own });
|
||||
expect(shown.isError).toBe(false);
|
||||
expect(shown.structured.item).not.toHaveProperty("answers");
|
||||
expect(shown.structured.item).not.toHaveProperty("answersFrom");
|
||||
expect(shown.text).not.toContain("private reasoning");
|
||||
});
|
||||
|
||||
|
||||
@@ -19,6 +19,16 @@ function mockClient(overrides?: {
|
||||
return client;
|
||||
}
|
||||
|
||||
// What a connection that relays a person's request is told when more than one assistant could be the one they mean. With
|
||||
// rig_team it lists the team first; pickup is said only where it's true for the path.
|
||||
const ASK_LISTED = "Before sending a request to another assistant, list the team's members. If more than one could be the one your person means, ask which, using their names from the list (like \"Sam's Claude\"); if the list shows only addresses, describe each in plain words from what the list says about it (like \"the Claude assistant\"), never reading the address out. Don't pick from your own history or memory. If the list shows the chosen one detached or stopped, or a connected assistant with no check-in yet or overdue, say so before sending and ask whether to send it anyway. If the list says the chosen one's person was removed from the team, don't send; tell your person and ask whether to send it to someone else.";
|
||||
const ASK_RUNNING_PICKUP = "When you send to a running team seat, tell your person that seat will pick it up on its own.";
|
||||
const ASK_CONNECTED_PICKUP = "When you send to another connected assistant, tell your person it will be picked up the next time that assistant's person opens it, or on a schedule they've set up.";
|
||||
const ASK_SENT_ANYWAY = "If you sent it anyway, tell your person it waits until that one is back.";
|
||||
const ASK_UNLISTED = "If more than one assistant could be the one your person means, ask which; don't pick from your own history or memory. If your person names one clearly, go ahead.";
|
||||
const ASK_GO_AHEAD = "If your person names one clearly, or says to send it anyway to one that isn't connected, go ahead without asking again.";
|
||||
const ASK_REMOVED_FACT = "If your person still asks to send to one whose person was removed, tell them it can't be delivered: requests to a removed person's assistant are closed unanswered.";
|
||||
|
||||
describe("MCP Server", () => {
|
||||
let mcpClient: Client;
|
||||
let daemonClient: DaemonClient;
|
||||
@@ -395,6 +405,10 @@ describe("MCP Server", () => {
|
||||
expect(instructions).not.toContain(MEMBER_WORKFLOW);
|
||||
expect(instructions).not.toContain("without asking whether you may");
|
||||
for (const part of ["the person's to answer", "record only what the person tells you", "Never choose an answer for them", "exactly what the person typed in resolution, with no label"]) expect(FRONT_DOOR_WORKFLOW).toContain(part);
|
||||
// It hands the team the person's work, so which assistant they mean is theirs to say when several fit. Its list shows
|
||||
// team seats and connected assistants: only a running team seat picks a request up on its own.
|
||||
expect(FRONT_DOOR_WORKFLOW).toContain(`${ASK_LISTED} ${ASK_RUNNING_PICKUP} ${ASK_CONNECTED_PICKUP} ${ASK_SENT_ANYWAY} ${ASK_GO_AHEAD} ${ASK_REMOVED_FACT}`);
|
||||
expect(FRONT_DOOR_WORKFLOW).not.toContain("<name>");
|
||||
// An agent told to say the words are the person's wrapped them as `The person's answer: "…"`, so the stored answer wasn't what they typed.
|
||||
expect(FRONT_DOOR_WORKFLOW).not.toContain("saying they're the person's");
|
||||
const front = await mcpClient.callTool({ name: "rig_whoami", arguments: {} });
|
||||
@@ -877,11 +891,33 @@ describe("MCP Server", () => {
|
||||
expect(instructions).not.toContain(MEMBER_WORKFLOW_VERSION);
|
||||
expect(instructions).not.toContain("basically authorized");
|
||||
expect(instructions).toContain("You may omit destination");
|
||||
// Asked to "send my Claude assistant one request" on a team with four Claude seats, a client picked one from its own history.
|
||||
// Without rig_team it can't list the team, and its destinations aren't other connected assistants: it's told only to ask.
|
||||
expect(instructions).toContain(ASK_UNLISTED);
|
||||
expect(instructions).not.toContain("list the team's members");
|
||||
expect(instructions).not.toContain("removed from the team");
|
||||
expect(instructions).not.toContain("closed unanswered");
|
||||
expect(instructions).not.toMatch(/picked up|pick it up/);
|
||||
expect(instructions).not.toMatch(/rig_whoami|rig_team|rig_queue_handoff|rig_queue_decide/);
|
||||
await external.close();
|
||||
await server.close();
|
||||
});
|
||||
|
||||
it("an external request grant with team/list lists the team before asking which assistant, and says when another connected one picks up", async () => {
|
||||
const server = createMcpServer(mockClient(), { seat: "cus-1-caller@team",
|
||||
access: { principal: "cus-1", owner: false, rigs: ["team"], roots: [], workspace: false, external: { objects: { queue: ["create", "show", "list"], team: ["list"] } } } });
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
const external = new Client({ name: "external-client", version: "1.0.0" });
|
||||
await server.connect(serverTransport);
|
||||
await external.connect(clientTransport);
|
||||
const instructions = external.getInstructions() ?? "";
|
||||
expect(instructions).toContain(`${ASK_LISTED} ${ASK_CONNECTED_PICKUP} ${ASK_GO_AHEAD} ${ASK_REMOVED_FACT}`);
|
||||
expect(instructions).not.toContain(ASK_RUNNING_PICKUP);
|
||||
expect(instructions).not.toContain(ASK_SENT_ANYWAY);
|
||||
await external.close();
|
||||
await server.close();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a full inbox grant", { queue: ["create", "show", "list", "claim", "update"], team: ["list"] }],
|
||||
["a narrow inbox grant", { queue: ["claim", "update"] }],
|
||||
@@ -899,6 +935,10 @@ describe("MCP Server", () => {
|
||||
expect(named.filter((tool) => !offered.has(tool))).toEqual([]);
|
||||
expect(instructions).not.toMatch(/rig_whoami|rig_queue_handoff|rig_queue_decide/);
|
||||
expect(instructions.includes("rig_team")).toBe(offered.has("rig_team"));
|
||||
// Only a grant that can hand the team work is told to ask which assistant the person means; with team/list it lists the
|
||||
// team first and may reach another connected assistant, so it's told when that one picks the request up.
|
||||
expect(instructions.includes("ask which")).toBe(offered.has("rig_queue_create"));
|
||||
if (offered.has("rig_queue_create")) expect(instructions).toContain(`${ASK_LISTED} ${ASK_CONNECTED_PICKUP} ${ASK_GO_AHEAD} ${ASK_REMOVED_FACT}`);
|
||||
await external.close();
|
||||
await server.close();
|
||||
});
|
||||
@@ -911,6 +951,8 @@ describe("MCP Server", () => {
|
||||
"Tools marked read-only change nothing. A seat whose activity is unknown is not idle, and an accepted request (a restore's attemptId) is not a finished one.",
|
||||
"A question reserved for a person is theirs to answer: don't answer it on their behalf. rig_queue_decide records a decision only inside the decision room of the mode they have on, beside their answers and never as one.",
|
||||
]) expect(instructions).toContain(paragraph);
|
||||
// A member works items rather than relaying a person's request, so it isn't told to ask which assistant they mean.
|
||||
expect(instructions).not.toContain("ask which");
|
||||
});
|
||||
|
||||
it("shows a connected assistant's person plain titles and openings, keeping each tool's rules and hints", async () => {
|
||||
|
||||
@@ -155,6 +155,6 @@ describe("rig ps: connected assistants and their check-in status", () => {
|
||||
expect(process.exitCode ?? 0).toBe(0);
|
||||
}
|
||||
rigs = [];
|
||||
expect((await run([])).join("\n")).toContain("No rigs\n\nConnected assistants: check-in unavailable");
|
||||
expect((await run([])).join("\n")).toContain(`No rigs · daemon http://127.0.0.1:${port}\n\nConnected assistants: check-in unavailable`);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { serve } from "@hono/node-server";
|
||||
import { Hono } from "hono";
|
||||
import { Command } from "commander";
|
||||
import { psCommand } from "../src/commands/ps.js";
|
||||
import { DaemonClient } from "../src/client.js";
|
||||
import { STATE_FILE } from "../src/daemon-lifecycle.js";
|
||||
import { psRoutes } from "../../daemon/src/routes/ps.js";
|
||||
import { PsProjectionService } from "../../daemon/src/domain/ps-projection.js";
|
||||
import { createFullTestDb } from "../../daemon/test/helpers/test-app.js";
|
||||
|
||||
let close: (() => Promise<void>) | undefined;
|
||||
afterEach(async () => { await close?.(); close = undefined; vi.restoreAllMocks(); });
|
||||
|
||||
/** Serves /api/ps over a fresh test db. activeRigs=0 yields a daemon whose
|
||||
* only rig is archived — the "No active rigs" empty-fleet shape. */
|
||||
async function fixture(activeRigs = 1) {
|
||||
const db = createFullTestDb();
|
||||
if (activeRigs > 0) {
|
||||
db.prepare("INSERT INTO rigs (id, name) VALUES ('r', 'fixture')").run();
|
||||
db.prepare("INSERT INTO nodes (id, rig_id, logical_id) VALUES ('n', 'r', 'builder')").run();
|
||||
db.prepare("INSERT INTO sessions (id, node_id, session_name, status) VALUES ('s', 'n', 'fixture-builder', 'running')").run();
|
||||
}
|
||||
db.prepare("INSERT INTO rigs (id, name, archived_at) VALUES ('archived', 'archived-fixture', datetime('now'))").run();
|
||||
db.prepare("INSERT INTO nodes (id, rig_id, logical_id) VALUES ('archived-n', 'archived', 'builder')").run();
|
||||
db.prepare("INSERT INTO sessions (id, node_id, session_name, status) VALUES ('archived-s', 'archived-n', 'archived-builder', 'running')").run();
|
||||
const app = new Hono();
|
||||
app.use("*", async (c, next) => { c.set("psProjectionService" as never, new PsProjectionService({ db }) as never); await next(); });
|
||||
app.route("/api/ps", psRoutes);
|
||||
const server = serve({ fetch: app.fetch, port: 0, hostname: "127.0.0.1" });
|
||||
await new Promise<void>((resolve) => server.on("listening", resolve));
|
||||
const port = (server.address() as { port: number }).port;
|
||||
close = () => new Promise<void>((resolve, reject) => { server.close((err) => { db.close(); err ? reject(err) : resolve(); }); });
|
||||
const client = new DaemonClient(`http://127.0.0.1:${port}`);
|
||||
const deps = { clientFactory: () => client, lifecycleDeps: {
|
||||
exists: (p: string) => p === STATE_FILE,
|
||||
readFile: () => JSON.stringify({ pid: 123, port, db: "fixture.sqlite", startedAt: new Date().toISOString() }),
|
||||
fetch: async () => ({ ok: true }), isProcessAlive: () => true,
|
||||
spawn: vi.fn(), kill: vi.fn(), writeFile: vi.fn(), removeFile: vi.fn(), mkdirp: vi.fn(), openForAppend: vi.fn(),
|
||||
} };
|
||||
const command = new Command().addCommand(psCommand(deps as never));
|
||||
return { baseUrl: `http://127.0.0.1:${port}`, command };
|
||||
}
|
||||
|
||||
it("names the daemon on the rollup line when rigs are listed", async () => {
|
||||
const { baseUrl, command } = await fixture(1);
|
||||
const log = vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
await command.parseAsync(["node", "rig", "ps"]);
|
||||
const rollup = log.mock.calls.flat().find((l) => /needs? attention/.test(String(l)));
|
||||
expect(rollup).toBeDefined();
|
||||
expect(String(rollup)).toMatch(/1 rig · 1 seat · 0 need attention · daemon http:\/\/127\.0\.0\.1:\d+$/);
|
||||
expect(String(rollup)).toContain(`daemon ${baseUrl}`);
|
||||
});
|
||||
|
||||
it("names the daemon on the empty-fleet lines — the wrong-daemon trap case", async () => {
|
||||
const { baseUrl, command } = await fixture(0);
|
||||
const log = vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
await command.parseAsync(["node", "rig", "ps"]);
|
||||
const lines = log.mock.calls.flat().map(String).join("\n");
|
||||
expect(lines).toContain(`No active rigs · 1 archived (rig ps --include-archived) · daemon ${baseUrl}`);
|
||||
});
|
||||
|
||||
it("names the daemon on the filter-miss line", async () => {
|
||||
const { baseUrl, command } = await fixture(1);
|
||||
const log = vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
await command.parseAsync(["node", "rig", "ps", "--filter", "lifecycleState=attention_required"]);
|
||||
const miss = log.mock.calls.flat().find((l) => String(l).startsWith("No rigs match"));
|
||||
expect(String(miss)).toContain(`daemon ${baseUrl}`);
|
||||
});
|
||||
@@ -257,7 +257,7 @@ describe("PL-012 ps --filter contextUsage.* + CTX field", () => {
|
||||
await makeCmd().parseAsync(["node", "rig", "ps", "--filter", filter]);
|
||||
});
|
||||
expect(result.exitCode).toBeUndefined();
|
||||
expect(result.logs).toEqual([`No rigs match --filter ${key}=${value}`]);
|
||||
expect(result.logs).toEqual([`No rigs match --filter ${key}=${value} · daemon http://127.0.0.1:${port}`]);
|
||||
expect(result.errLogs).toHaveLength(1);
|
||||
expect(result.errLogs[0]).toContain(key);
|
||||
expect(result.errLogs[0]).toContain("was not applied");
|
||||
|
||||
@@ -165,7 +165,7 @@ describe("queue writes refused for a host token the daemon doesn't know", () =>
|
||||
["a remote's refusal", { status: 502, data: { error: "remote_queue_write_failed", hostId: "vps-b", failureClass: "remote-error", remoteStatus: 400, detail: "HTTP 400" } }],
|
||||
["an auth failure", { status: 502, data: { error: "remote_queue_write_failed", hostId: "vps-b", failureClass: "auth-failed", detail: "401" } }],
|
||||
["an internal error", { status: 500, data: { error: "internal_error", message: "boom" } }],
|
||||
["a 400 this list doesn't name", { status: 400, data: { error: "summary_evidence_not_persistable", message: "x" } }],
|
||||
["a 400 this list doesn't name", { status: 400, data: { error: "closure_fields_not_admitted", message: "x" } }],
|
||||
];
|
||||
for (const [label, reply] of UNPROVEN) {
|
||||
it(`never says it after ${label}`, async () => {
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
// 51-06 D2 — REAL CLI acceptance boundary (Guard implementation-verdict correction). A genuine
|
||||
// `queueCommand` invocation talks over LOOPBACK HTTP to the real candidate queueRoutes +
|
||||
// QueueRepository, backed by a migration-faithful test DB (incl. 044 summary + 048 evidence_ref).
|
||||
// No pre-baked response: if the daemon route/repo stopped rejecting (or mutated before responding),
|
||||
// these tests would fail. Proves normal + --json reject, UNCHANGED item/transition/event state after
|
||||
// the HTTP call, and the successful human-park control — all end to end.
|
||||
// 51-06 D2, narrowed — REAL CLI acceptance boundary. A genuine `queueCommand` invocation talks over
|
||||
// LOOPBACK HTTP to the real candidate queueRoutes + QueueRepository, backed by a migration-faithful test DB
|
||||
// (incl. 044 summary + 048 evidence_ref). No pre-baked response. A state change that carries --summary or
|
||||
// --evidence-ref is applied and stores them; a blank --summary is reported as not stored, never dropped silently.
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from "vitest";
|
||||
import { serve } from "@hono/node-server";
|
||||
import { Hono } from "hono";
|
||||
@@ -107,27 +105,29 @@ describe("51-06 D2 — real CLI->loopback HTTP->queueRoutes/QueueRepository acce
|
||||
});
|
||||
afterEach(() => { vi.unstubAllEnvs(); });
|
||||
|
||||
it("normal: --summary on a non-park update -> real 400, nonzero exit, item/transition/event UNCHANGED", async () => {
|
||||
const beforeTxns = txnCount(id), beforeEvents = eventCount();
|
||||
const { out, exit } = await runCli(["update", id, "--actor", "dev-x@rig", "--state", "in-progress", "--summary", "DROPME"]);
|
||||
expect(exit).toBe(1);
|
||||
expect(out).toContain("summary_evidence_not_persistable");
|
||||
expect(out).toContain("invalidFields");
|
||||
// unchanged item/metadata/transition/event state AFTER the real HTTP call
|
||||
const item = repo.getByIdOrThrow(id);
|
||||
expect(item.state).toBe("pending");
|
||||
expect(item.summary).toBeNull();
|
||||
expect(txnCount(id)).toBe(beforeTxns);
|
||||
expect(eventCount()).toBe(beforeEvents);
|
||||
it("normal: --summary and --evidence-ref on a state change are applied and stored (exit 0)", async () => {
|
||||
const beforeTxns = txnCount(id);
|
||||
const { exit } = await runCli(["update", id, "--state", "in-progress", "--summary", "KEEP", "--evidence-ref", "/proof/e.md"]);
|
||||
expect(exit).toBeFalsy();
|
||||
expect(repo.getByIdOrThrow(id)).toMatchObject({ state: "in-progress", summary: "KEEP", evidenceRef: "/proof/e.md" });
|
||||
expect(txnCount(id)).toBe(beforeTxns + 1);
|
||||
});
|
||||
|
||||
it("--json: same reject as structured JSON with nonzero exit, state UNCHANGED", async () => {
|
||||
const { out, exit } = await runCli(["update", id, "--actor", "dev-x@rig", "--state", "in-progress", "--evidence-ref", "/e.md", "--json"]);
|
||||
expect(exit).toBe(1);
|
||||
const body = JSON.parse(out) as { error: string; invalidFields?: string[] };
|
||||
expect(body.error).toBe("summary_evidence_not_persistable");
|
||||
expect(body.invalidFields).toEqual(["evidenceRef"]);
|
||||
expect(repo.getByIdOrThrow(id).evidenceRef).toBeNull();
|
||||
it("a finished seat's park on a typed gate with --summary and --evidence-ref parks and stores both (--json)", async () => {
|
||||
await runCli(["update", id, "--state", "in-progress"]);
|
||||
const { out, exit } = await runCli(["block", id, "--on", "external:relay-reply", "--summary", "Relayed; waiting on the reply", "--evidence-ref", "/proof/relay.md", "--json"]);
|
||||
expect(exit).toBeFalsy();
|
||||
expect(JSON.parse(out)).toMatchObject({ state: "blocked", summary: "Relayed; waiting on the reply", evidenceRef: "/proof/relay.md" });
|
||||
expect(repo.getByIdOrThrow(id)).toMatchObject({ state: "blocked", blockedOn: "external:relay-reply", summary: "Relayed; waiting on the reply", evidenceRef: "/proof/relay.md" });
|
||||
});
|
||||
|
||||
it.each([false, true])("a blank --summary is applied without it and reported as not stored (json=%s)", async (json) => {
|
||||
db.prepare("UPDATE queue_items SET summary = ? WHERE qitem_id = ?").run("Original subject", id);
|
||||
const { out, exit } = await runCli(["update", id, "--state", "in-progress", "--summary", " ", ...(json ? ["--json"] : [])]);
|
||||
expect(exit).toBeFalsy();
|
||||
expect(repo.getByIdOrThrow(id)).toMatchObject({ state: "in-progress", summary: "Original subject" });
|
||||
if (json) expect(JSON.parse(out).advisories).toEqual([expect.objectContaining({ code: "summary_not_stored", field: "summary" })]);
|
||||
else expect(out).toContain(`The summary was blank, so it wasn't stored: ${id} keeps its summary`);
|
||||
});
|
||||
|
||||
it("CONTROL: real-CLI human-seat park PERSISTS summary + evidence (exit 0)", async () => {
|
||||
|
||||
@@ -11,7 +11,15 @@ describe("wrapSendBody — pre-release CLI/daemon Item 2 (email-style envelope)"
|
||||
expect(out).toContain('↩ Reply: rig send driver-3@my-rig "..."');
|
||||
});
|
||||
|
||||
it.each(["human@kernel", "human@host", "human-alice@kernel", "human-alice@host"])(
|
||||
// An answer typed at this machine is recorded as human@host, which names nobody: a reply there asks no one, waits on
|
||||
// Steering and in the Feed, and OpenRig reports it as undeliverable, so its reply hint says so and points to the person's registered address.
|
||||
it.each(["human@host", "human@host@host-origin"])("never points %s's reply at the unattributed address", (sender) => {
|
||||
const last = wrapSendBody(sender, "driver@rig", "Answered.").split("\n").at(-1);
|
||||
expect(last).toBe(`↩ ${sender} names no person: a reply there asks no one. It waits on Steering and in the Feed, and OpenRig reports it as undeliverable. To ask the person back, use their registered address (rig gateway human list lists who's registered).`);
|
||||
expect(last).not.toContain("rig queue create");
|
||||
});
|
||||
|
||||
it.each(["human@kernel", "human-alice@kernel", "human-alice@host"])(
|
||||
"gives %s a queue update reply with the existing human-route fields",
|
||||
(sender) => {
|
||||
const body = "Please check this.\nKeep the actor unchanged.";
|
||||
|
||||
@@ -121,6 +121,19 @@ describe("S10 CLI cutover — admin verbs route to the daemon", () => {
|
||||
});
|
||||
|
||||
describe("S10 CLI cutover — config surfaces survive on the daemon-homed modules", () => {
|
||||
it("saves and reports the human-row preview choice", async () => {
|
||||
const home = mkdtempSync(join(tmpdir(), "slack-preview-"));
|
||||
homes.push(home);
|
||||
const logs: string[] = [];
|
||||
const deps: SlackDeps = { home, log: message => logs.push(message), clientFactory: () => ({ get: async () => { throw new Error("offline"); } }) };
|
||||
await run(slackCommand(deps), ["setup", "--unfurl", "on"]);
|
||||
expect(JSON.parse(readFileSync(join(home, "slack-connector.json"), "utf8")).unfurl).toBe("on");
|
||||
logs.length = 0;
|
||||
await run(slackCommand(deps), ["status"]);
|
||||
expect(logs.join("\n")).toContain("human-row previews");
|
||||
expect(logs.join("\n")).toContain("on");
|
||||
});
|
||||
|
||||
it("retires the legacy alert-tag setup knob", () => {
|
||||
const { deps } = makeDeps();
|
||||
const setup = slackCommand(deps).commands.find((command) => command.name() === "setup");
|
||||
|
||||
@@ -311,6 +311,15 @@ describe("rig workflow CLI (PL-004 Phase D)", () => {
|
||||
expect(calls.find((c) => c.path === "/api/workflow/list?status=active")).toBeDefined();
|
||||
});
|
||||
|
||||
it("passes combined workflow filters and repeated tags to the list API", async () => {
|
||||
const url = "/api/workflow/list?status=active&project=p&mission=m&slice=s&rig=rig&name=wf&limit=4&tag=one&tag=two";
|
||||
const { deps, calls } = makeDeps({ routes: { [`GET ${url}`]: { status: 200, data: [] } } });
|
||||
const program = createProgram({ workflowDeps: deps });
|
||||
program.exitOverride();
|
||||
await program.parseAsync(["node", "rig", "workflow", "list", "--status", "active", "--project", "p", "--mission", "m", "--slice", "s", "--rig", "rig", "--name", "wf", "--limit", "4", "--tag", "one", "--tag", "two", "--json"]);
|
||||
expect(calls.find((call) => call.path === url)).toBeDefined();
|
||||
});
|
||||
|
||||
it("show GETs /api/workflow/:instanceId", async () => {
|
||||
const { deps, calls } = makeDeps({
|
||||
routes: { "GET /api/workflow/inst-1": { status: 200, data: { instanceId: "inst-1" } } },
|
||||
|
||||
+4
-1
@@ -106,7 +106,10 @@ You are about to lose every connection you have built. Spend this turn making th
|
||||
3. **Open the map with a summary** of 10 to 20 lines: who you are, what you hold, what mattered in this
|
||||
window, what is next and who authorizes it, and any hold in force. **Publish that summary as your seat
|
||||
recap** too: save it, plus a line naming the map's path, to a file and run
|
||||
`rig context recap-write --file <that file>`, which writes your own seat's recap. If your world profile has a seat
|
||||
`rig context recap-write --file <that file>`, which writes your own seat's recap. Give the file's literal absolute
|
||||
path, with no shell variable assignment or command substitution: Claude Code's allow rules don't match past an
|
||||
assignment (apart from a few known-safe variables), and an ask or deny rule still wins, so such a command can stop at
|
||||
an approval prompt, and OpenRig won't send `/compact` while it waits. If your world profile has a seat
|
||||
recap atom, it loads this recap, and an old recap would be served as if it were current.
|
||||
4. **Then write the connections.** Choose what this seat needs; these are examples, not a template:
|
||||
- **State:** rows you hold (id, state), branches and PR heads, the hold or release in force and who gave
|
||||
|
||||
@@ -127,8 +127,8 @@ person needs in their project or home folder and name that path.
|
||||
joining as optional, with the effects below. Ask the person yes or no after this short explanation:
|
||||
- This adds me as a named member of the team, with my name on messages.
|
||||
- In a plain shell, joining writes no files in your project or personal settings.
|
||||
- Inside tmux on 0.6.11, my sender and reply address is your existing tmux session name, even a number like `0`.
|
||||
`rig attach --self` returns that address and `rig whoami` confirms it; `--display-name` does not change it.
|
||||
- Inside tmux, my sender and reply address is `<member>@<rig>`, even when your tmux session is named `0`;
|
||||
`rig attach --self` returns it and `rig whoami` confirms it; `--display-name` does not change it.
|
||||
- Inside tmux, other agents can type into this window, and stopping the team (`rig down`) also closes this tmux
|
||||
session (both from source, not hand-tested). Transcript recording and, for Claude Code, writing
|
||||
`.openrig/context-collector.cjs` and `.claude/settings.local.json` for the status line were hand-tested on 0.6.11.
|
||||
@@ -147,7 +147,8 @@ person needs in their project or home folder and name that path.
|
||||
`rig queue create --source <their id>@external --destination <seat> --summary "<one line>" --body-file <file>`: the
|
||||
seat sees that name, recorded as declared, and can reply to them if they're registered (`rig gateway human list`).
|
||||
A declared name is a claim, not a seat's own identity: for a team that acts only on seat identity, the attached
|
||||
shell above is the route.
|
||||
shell above is the route. For work whose questions and result must come back to this session, use a return
|
||||
address ("If the person stays with you" below), not a declared name.
|
||||
- **Who answers OpenRig's questions:** read `rig gateway participants` (its `default:` line) before the handoff.
|
||||
- A default person is there: say requests and asks that name nobody go to them (a pairing request or an ask can
|
||||
name someone else), and don't offer again.
|
||||
@@ -168,9 +169,10 @@ person needs in their project or home folder and name that path.
|
||||
said. Find the `operator.agent` row in `rig ps --nodes --rig kernel --json`, take its `canonicalSessionName`
|
||||
(never the logical ID or a guessed name) and send:
|
||||
`rig send <canonicalSessionName> 'This is the agent that installed OpenRig. The person will answer in your pane. Goal: <goal>. Project folder: <absolute path>. Branch: <branch>.'`
|
||||
If the person stays here, replace "The person will answer in your pane" with "The person stays with me; send me your questions and
|
||||
results to relay." Carry their constraints, which logins they have (an installed provider that isn't signed in
|
||||
doesn't count), and any permission choice they made, chosen or declined, in either handoff.
|
||||
If the person stays here, hand the goal over as a task from your own address instead, so the operator's questions
|
||||
and the result come back to you ("If the person stays with you" below). Carry their constraints, which logins they
|
||||
have (an installed provider that isn't signed in doesn't count), and any permission choice they made, chosen or
|
||||
declined, in either handoff.
|
||||
Or the person types the goal and folder in the operator's pane. If they give you a goal later, forward it the same
|
||||
way. The operator helps them pick a team that fits their logins, starts it (`rig up`) only on their yes to the plan it
|
||||
shows, and gives the goal to the team's lead. Before that yes, it says what launching into their folder changes for their own agent there; relay
|
||||
@@ -181,11 +183,54 @@ person needs in their project or home folder and name that path.
|
||||
Check those logins (`claude auth status`, `codex login status`), or go by what the person told you. If one is missing
|
||||
or you can't tell, say so before launching and let them choose: the operator adapts the team to the logins they have,
|
||||
or they sign in first.
|
||||
- **Relay the operator's questions** unless the person declined the Codex offer below and explicitly chose the operator route: the operator asks in its own pane, and the person may not be looking there.
|
||||
After each step you hand it, read its screen with `rig capture <canonicalSessionName>`. When it asks the person
|
||||
something (start this team? which folder? which option?), ask them here in the operator's words and send their
|
||||
answer back with `rig send`, or tell them to answer in the operator's pane. Unlike a prompt or a menu, a question
|
||||
doesn't show up as a stopped seat, so don't leave it to a background wait.
|
||||
- **If the person stays with you** (unless they declined the Codex offer below and explicitly chose the operator
|
||||
route), you're their front door to the team: you hand it the goal, bring its questions to them and bring back what
|
||||
it produced, through the task queue rather than the operator's screen.
|
||||
- **Your return address:** if this session joined the team (above), it's the `OPENRIG_SESSION_NAME` that
|
||||
`rig attach` printed. Otherwise agree one with the person on the kernel's rig, such as `claude-app@kernel` or
|
||||
`codex-app@kernel`. It's an address the queue takes tasks for; nothing is launched for it and no file is written.
|
||||
If the person keeps more than one of these conversations, give each its own address (for example
|
||||
`claude-app-2@kernel`); one address shares its questions.
|
||||
To tell the team what it's for, the person can add it to a roster as a hosted member
|
||||
(`docs/reference/hosted-members.md` in the OpenRig package).
|
||||
Put it in front of every `rig queue` command: `OPENRIG_SESSION_NAME=<address> rig queue ...` (add
|
||||
`OPENRIG_HOME=<home>` when OpenRig doesn't use the default home). A `--source` name only labels the one task it's
|
||||
on: claiming and answering the team's questions need the address in `OPENRIG_SESSION_NAME`.
|
||||
- **Hand over the goal:** write it to a file with what the message above carries (that you're the agent that
|
||||
installed OpenRig and the person stays with you, the goal, folder, branch, constraints, logins and permission
|
||||
choices), and end it with this paragraph, filling in your address:
|
||||
|
||||
> To ask me anything, create a queue item to `<address>` (`rig queue create --destination <address> ...`), then
|
||||
> block this item on that new item's id (`rig queue block <this id> --on <question id>`), so my answer wakes you. I
|
||||
> check it when the person asks. Don't ask in your own terminal: the person isn't there. If you hand this item on,
|
||||
> copy this paragraph into the new item. When you finish, put the outcome in this item's resolution and any file in
|
||||
> its evidence ref.
|
||||
|
||||
Then run
|
||||
`OPENRIG_SESSION_NAME=<address> rig queue create --destination <canonicalSessionName> --summary "<the goal in a sentence>" --body-file <file> --verify`.
|
||||
Tell the person the task ID it prints, and keep the goal, your address and that ID: they're how you find this work
|
||||
again.
|
||||
- **The team's questions** come to your address as tasks:
|
||||
`OPENRIG_SESSION_NAME=<address> rig queue list --owned --state pending,in-progress`. Read each in full
|
||||
(`rig queue show <id> --full`) and show the person the whole question in the team's words. Record only what they
|
||||
tell you, a condition included ("yes, but only on a branch"): claim it, then
|
||||
`OPENRIG_SESSION_NAME=<address> rig queue update <id> --state done --closure-reason no-follow-on --resolution "<their words>"`.
|
||||
Add no label, quotation marks or notes of your own, and don't turn their words into a yes or a no: the agent that
|
||||
asked decides what they mean. You speak as yourself, never as the person. If they aren't there to answer, leave
|
||||
it open and tell them it's waiting; never answer for them.
|
||||
- **A question only on the operator's screen:** if the operator asks in its pane and nothing reached your address,
|
||||
read it with `rig capture <canonicalSessionName>`, show the person, and send their words as a new task to the
|
||||
operator that names your task's ID, not as keys typed into its pane.
|
||||
- **Delivery isn't the task's state.** A task's state says where the work is: pending (created and readable, not
|
||||
yet claimed), claimed or in progress (an agent took it), handed off (follow the next item) or done (read its
|
||||
resolution). Whether its agent was woken is a separate fact, the wake outcome `--verify` reports: `verified` (it
|
||||
rendered in the seat's pane) or `claimed` (picked up); `delivered-ack-pending` (sent, render unconfirmed: not
|
||||
proof it was woken); `retained` (the seat's typing guard held the wake, the task is still there to read, and it
|
||||
isn't retried automatically: wake the task's destination once its input is free with
|
||||
`rig send <destination> "task <id> is yours"`); `failed` (the wake didn't land, and the task is still
|
||||
owed: wake it the same way); `indeterminate` or `still-pending` (unknown, neither failed nor delivered: check
|
||||
before you wake it again). A pending task with no wake isn't lost or done.
|
||||
- **Nothing wakes this chat** when the team asks or finishes: check your address when the person asks or comes back.
|
||||
- **If the operator answers with a model error,** such as "… not supported when using Codex with a ChatGPT account", its
|
||||
Codex sign-in works but that account can't run the model. OpenRig put the operator on Codex because the sign-in
|
||||
passed. Tell the person which model failed. If Claude Code is signed in, offer to move the operator to it; on their
|
||||
@@ -216,9 +261,9 @@ person needs in their project or home folder and name that path.
|
||||
that keep asking, for their project only (`applying-a-permission-policy`); tell it what they chose.
|
||||
Another kind of menu you can answer with
|
||||
the key that screen shows, or ask the person. Capture it again before sending anything more.
|
||||
- **Replies:** in a plain shell, other agents can't type into this session. Read work sent to you with
|
||||
`rig queue list --destination <your address>` and `rig queue show <id> --full`, and read an agent's screen with
|
||||
`rig capture <seat>@<rig>`.
|
||||
- **Replies:** in a plain shell, other agents can't type into this session. Their questions and work for you arrive
|
||||
at your return address ("If the person stays with you" above). `rig capture <seat>@<rig>` shows what an agent is
|
||||
doing; it isn't how answers reach you.
|
||||
|
||||
### Codex: one offer, once, after OpenRig starts
|
||||
|
||||
@@ -257,21 +302,29 @@ offer, so the person sees the real file, not a placeholder:
|
||||
|
||||
Follow these steps by default. Only when the person declined the Codex offer above and explicitly chose the operator route does the operator own this follow-through.
|
||||
|
||||
- **Find the team's task:** the operator gives the goal to the team's lead as a queue task: `dev-build@starter`, or
|
||||
`orch-lead` in `workshop` and `factory` (for starter and factory, `rig specs preview <name> --kind rig` says what
|
||||
each seat does; for a running team, `rig ps --nodes --rig <rig>`). Find it with
|
||||
`rig queue list --destination <seat>@<rig> -a`.
|
||||
- **Find the team's task:** if you gave the operator a task, start from it: when the operator hands it to the team's
|
||||
lead, `rig queue show <id> --json` lists the next item under `successors`. Otherwise, or if the operator started a
|
||||
new task for the lead (`dev-build@starter`, or `orch-lead` in `workshop` and `factory`; for starter and factory,
|
||||
`rig specs preview <name> --kind rig` says what each seat does; for a running team, `rig ps --nodes --rig <rig>`),
|
||||
find it with `rig queue list --destination <seat>@<rig> -a`.
|
||||
- **Follow it to the result:** a task that changed hands isn't finished. `rig queue show <id> --full` names the seat it
|
||||
went to, and that seat's next task is the one whose `handedOffFrom` is that ID
|
||||
(`rig queue list --destination <seat>@<rig> -a -o json`). Follow each handoff until an agent reports the result, and
|
||||
use `rig capture <seat>@<rig>` to see what it's doing. Then read what it produced and tell the person what the team
|
||||
actually did (the branch, commit, review or PR text), not just that you sent it.
|
||||
(`rig queue list --destination <seat>@<rig> -a -o json`). Follow each handoff until an agent reports the result,
|
||||
and report what the record says; `rig capture <seat>@<rig>` only shows what an agent is doing right now. Then read
|
||||
what it produced and tell the person what the team actually did (the branch, commit, review or PR text), not just
|
||||
that you sent it.
|
||||
- **Give the team more work:** write the goal to a file: what to change, in which repository and branch, what done
|
||||
looks like, and that the result comes back to you (the branch or commit, the review, any PR text). Then
|
||||
`rig queue create --source <your name> --destination <seat>@<rig> --summary "<the goal in a sentence>" --body-file <file>`, and tell that agent with
|
||||
`rig send <seat>@<rig> "task <id> is yours"`. A message informs, and a queue task is the work someone owns.
|
||||
`--source` names you when this session hasn't joined the team.
|
||||
looks like, and that the result comes back to you (the branch or commit, the review, any PR text), ending with the
|
||||
reply paragraph above. Then
|
||||
`OPENRIG_SESSION_NAME=<address> rig queue create --destination <seat>@<rig> --summary "<the goal in a sentence>" --body-file <file> --verify`.
|
||||
A message informs, and a queue task is the work someone owns. Read its wake outcome as above before you send
|
||||
anything else.
|
||||
- **Then ask what's next.** If no team can take the work, fix that or ask the person. Don't quietly do it yourself.
|
||||
- **Coming back later:** in a new session, use the same return address and the task IDs you gave the person. Read
|
||||
each with `rig queue show <id> --json` and follow its `successors` to the newest item, as above;
|
||||
`OPENRIG_SESSION_NAME=<address> rig queue list --mine -a` lists everything this address sent or owns, finished work
|
||||
included (without `-a` it shows only open items). Follow that work rather than creating it again.
|
||||
Adding OpenRig's MCP plugin to this app later starts a new session; it doesn't carry this conversation over.
|
||||
- **Other ways to work with the team:** `rig send <seat>@<rig> "..."` types into an agent's terminal,
|
||||
`rig capture <seat>@<rig>` reads its screen, and `rig ps --nodes --rig <rig>` shows who's on it.
|
||||
|
||||
|
||||
@@ -11,8 +11,8 @@ import { execRuntimeProbe } from "./runtime-probe-exec.js";
|
||||
import { shellQuote } from "./shell-quote.js";
|
||||
import { codexPostureArg } from "./yolo-mode.js";
|
||||
import { observeCodexSandbox } from "../domain/permission-drift.js";
|
||||
import { codexEnvelopeArgs } from "../domain/codex-rebuild-permissions.js";
|
||||
import { codexMemberEnvelope, observeCodexEnvelope, type CodexMemberPermissions } from "../domain/codex-member-permissions.js";
|
||||
import { codexMemberLaunch, type CodexMemberPermissions } from "../domain/codex-member-permissions.js";
|
||||
import { codexPolicyWarning, resolveCodexFilesystemHome, verifyCodexFilesystemPolicy, type CodexFilesystemVerifier } from "../domain/codex-filesystem-preflight.js";
|
||||
import { unknownDaemonSupportMessage, type CodexDaemonSupportDetector } from "../domain/codex-daemon-support.js";
|
||||
import { codexNetworkDefaultArg, type CodexNetworkDefaultReader } from "../domain/codex-network-default.js";
|
||||
|
||||
@@ -40,6 +40,7 @@ interface CodexResumeOptions {
|
||||
readNetworkDefault?: CodexNetworkDefaultReader;
|
||||
/** launch.codex_login_shell: true keeps Codex's own login shells for tool commands. Absent: off. */
|
||||
codexLoginShell?: () => boolean;
|
||||
verifyFilesystemPolicy?: CodexFilesystemVerifier;
|
||||
/** Ensure the managed Codex config (hooks, trust) just before a resume, as a runtime-adapter launch does, in the
|
||||
* seat's own home when it has one. */
|
||||
ensureManagedConfig?: (codexHome?: string) => Promise<void>;
|
||||
@@ -93,7 +94,17 @@ export class CodexResumeAdapter {
|
||||
if (wrapped && !this.options.seatLaunchEnvironment) {
|
||||
return { ok: false, code: "resume_failed", message: "launch_wrapper support unavailable; no agent started." };
|
||||
}
|
||||
const codexHome = seatCodexHome ?? this.options.codexHome;
|
||||
const filesystem = codexPermissions && "filesystem" in codexPermissions ? codexPermissions : undefined;
|
||||
const codexHome = seatCodexHome ?? this.options.codexHome ?? (filesystem ? resolveCodexFilesystemHome() : undefined);
|
||||
let policyWarning: string | undefined;
|
||||
if (filesystem) {
|
||||
try {
|
||||
const verified = await (this.options.verifyFilesystemPolicy ?? verifyCodexFilesystemPolicy)({ permissions: filesystem, cwd, codexHome, launchPath: this.options.launchPath, launchWrapper,
|
||||
codexConfigProfile: codexConfigProfile?.trim() || undefined });
|
||||
if (!verified.ok) return { ok: false, code: "resume_failed", message: verified.error };
|
||||
if (!verified.verified) policyWarning = codexPolicyWarning(verified.reason);
|
||||
} catch { policyWarning = codexPolicyWarning("Native Codex configuration reader failed"); }
|
||||
}
|
||||
|
||||
// Only a seat's own home is passed on, so a call for a seat without one is exactly as before.
|
||||
await (seatCodexHome ? this.options.ensureManagedConfig?.(seatCodexHome) : this.options.ensureManagedConfig?.());
|
||||
@@ -120,15 +131,16 @@ export class CodexResumeAdapter {
|
||||
}
|
||||
|
||||
const profileArg = codexConfigProfile ? ` -p ${shellQuote(codexConfigProfile)}` : "";
|
||||
const envelope = codexPermissions ? codexMemberEnvelope(codexPermissions) : undefined;
|
||||
const posture = envelope ? profileArg + codexEnvelopeArgs(envelope) : codexPostureArg(profileArg, process.env, resolvedPosture);
|
||||
const appliedLaunch = envelope ? observeCodexEnvelope(envelope) : observeCodexSandbox(posture);
|
||||
const postureArg = posture + operationalLaunchArg("codex", envelope ? { nonInterruptive }
|
||||
const choice = codexPermissions ? codexMemberLaunch(codexPermissions) : undefined;
|
||||
const posture = choice ? profileArg + choice.args : codexPostureArg(profileArg, process.env, resolvedPosture);
|
||||
const appliedLaunch = choice ? choice.observation : observeCodexSandbox(posture);
|
||||
if (policyWarning) appliedLaunch.reason = policyWarning;
|
||||
const postureArg = posture + operationalLaunchArg("codex", choice ? { nonInterruptive }
|
||||
: { kernelAuthority, teamPermissionDefault, nonInterruptive, launchPosture: resolvedPosture });
|
||||
const readNetworkDefault = this.options.readNetworkDefault;
|
||||
const networkArg = envelope ? "" : await codexNetworkDefaultArg(seatCodexHome && readNetworkDefault ? ((dir: string) => readNetworkDefault(dir, seatCodexHome)) : readNetworkDefault,
|
||||
const networkArg = choice ? "" : await codexNetworkDefaultArg(seatCodexHome && readNetworkDefault ? ((dir: string) => readNetworkDefault(dir, seatCodexHome)) : readNetworkDefault,
|
||||
appliedLaunch, cwd, tmuxSessionName);
|
||||
const workspaceArg = !envelope && teamPermissionDefault && !codexConfigProfile?.trim()
|
||||
const workspaceArg = !choice && teamPermissionDefault && !codexConfigProfile?.trim()
|
||||
&& appliedLaunch.state === "observed" && appliedLaunch.value === "workspace-write"
|
||||
? codexTeamWorkspaceArg(this.options.prepareTeamWorkspace, tmuxSessionName) : "";
|
||||
// The seat's own writable roots, as a launch gets them: its git metadata dirs (so it can still commit) and its topology
|
||||
@@ -152,7 +164,7 @@ export class CodexResumeAdapter {
|
||||
|
||||
const launchEnv = [this.options.launchPath ? `PATH=${shellQuote(this.options.launchPath)}` : "", codexHome ? `CODEX_HOME=${shellQuote(codexHome)}` : ""].filter(Boolean);
|
||||
const staged = this.options.seatLaunchEnvironment
|
||||
? await this.options.seatLaunchEnvironment.command(tmuxSessionName, cmd, { codexCwd: cwd, runtime: "codex", ...(seatCodexHome ? { codexHome: seatCodexHome } : {}), ...(wrapped ? { launchWrapper: wrapped } : {}) })
|
||||
? await this.options.seatLaunchEnvironment.command(tmuxSessionName, cmd, { codexCwd: cwd, runtime: "codex", ...((filesystem ? codexHome : seatCodexHome) ? { codexHome: filesystem ? codexHome : seatCodexHome } : {}), ...(wrapped ? { launchWrapper: wrapped } : {}) })
|
||||
: launchEnv.length ? `env ${launchEnv.join(" ")} ${cmd}` : cmd;
|
||||
if (beforeNativeDispatch && !beforeNativeDispatch()) return { ok: false, code: "attention_required", message: "Selected history changed during Codex resume preparation; no native command was sent." };
|
||||
const textResult = beforeNativeDispatch
|
||||
@@ -164,7 +176,7 @@ export class CodexResumeAdapter {
|
||||
|
||||
const result = await this.verifyResume(tmuxSessionName);
|
||||
const launchFacts = daemonSupport ? { ...appliedLaunch, daemonOptOut: daemonSupport.kind === "supported" } : appliedLaunch;
|
||||
return result.ok ? { ...result, appliedLaunch: launchFacts } : result;
|
||||
return result.ok ? { ...result, appliedLaunch: launchFacts, ...(policyWarning ? { warnings: [policyWarning] } : {}) } : result;
|
||||
}
|
||||
|
||||
// Mirrors ClaudeResumeAdapter.verifyResume: poll the pane, run the native
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { codexEnvelopeArgs } from "../domain/codex-rebuild-permissions.js";
|
||||
import { codexMemberEnvelope, observeCodexEnvelope, readProfileFingerprint, type CodexProfileObservation, type ProfileFingerprint } from "../domain/codex-member-permissions.js";
|
||||
import { codexMemberLaunch, observeCodexEnvelope, readProfileFingerprint, type CodexProfileObservation, type ProfileFingerprint } from "../domain/codex-member-permissions.js";
|
||||
import { codexPolicyWarning, resolveCodexFilesystemHome, verifyCodexFilesystemPolicy, type CodexFilesystemDecision, type CodexFilesystemVerifier } from "../domain/codex-filesystem-preflight.js";
|
||||
import { operationalLaunchArg } from "./kernel-authority.js";
|
||||
import nodePath from "node:path";
|
||||
import fs from "node:fs";
|
||||
@@ -176,6 +177,10 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
|
||||
// the real probe by default.
|
||||
private verifyProfilePreflight: (profile: string, cwd: string, home?: string) => Promise<CodexProfileProbeResult>;
|
||||
private profileFingerprint: (path: string) => Promise<ProfileFingerprint>;
|
||||
private verifyFilesystemPolicy: CodexFilesystemVerifier;
|
||||
// A handover checks the exact binding before retiring its predecessor. Consume
|
||||
// that result once at dispatch, rather than repeat a refusal after cutover.
|
||||
private filesystemPreflight = new WeakMap<NodeBinding, CodexFilesystemDecision>();
|
||||
// #69: whether the installed Codex supports --no-daemon. Startup wires the real probe;
|
||||
// absent (unit tests, other embedders) keeps the existing invocation unchanged.
|
||||
private detectDaemonSupport?: CodexDaemonSupportDetector;
|
||||
@@ -238,6 +243,7 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
|
||||
verifyProfilePreflight?: (profile: string, cwd?: string, home?: string) => Promise<CodexProfileProbeResult>;
|
||||
/** The setter's optional profile hash; defaults to a bounded, non-blocking read. */
|
||||
profileFingerprint?: (path: string) => Promise<ProfileFingerprint>;
|
||||
verifyFilesystemPolicy?: CodexFilesystemVerifier;
|
||||
detectDaemonSupport?: CodexDaemonSupportDetector;
|
||||
readNetworkDefault?: CodexNetworkDefaultReader;
|
||||
codexLoginShell?: () => boolean;
|
||||
@@ -275,6 +281,7 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
|
||||
this.codexHome = deps.codexHome;
|
||||
this.seatHome = deps.seatHome;
|
||||
this.profileFingerprint = deps.profileFingerprint ?? readProfileFingerprint;
|
||||
this.verifyFilesystemPolicy = deps.verifyFilesystemPolicy ?? verifyCodexFilesystemPolicy;
|
||||
this.launchPath = deps.launchPath;
|
||||
this.detectDaemonSupport = deps.detectDaemonSupport;
|
||||
this.readNetworkDefault = deps.readNetworkDefault;
|
||||
@@ -309,8 +316,10 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
|
||||
|
||||
/** The home a seat's Codex uses: its own from its member or rig `env:`, else the daemon's explicit CODEX_HOME. Undefined
|
||||
* keeps the legacy OS/PID home behavior. */
|
||||
private homeFor(binding: { nodeId?: string; accountHome?: string | null } | undefined): string | undefined {
|
||||
return this.ownHome(binding) ?? this.codexHome;
|
||||
private homeFor(binding: { nodeId?: string; accountHome?: string | null; codexPermissions?: NodeBinding["codexPermissions"] } | undefined): string | undefined {
|
||||
const selected = this.ownHome(binding) ?? this.codexHome;
|
||||
return binding?.codexPermissions && "filesystem" in binding.codexPermissions
|
||||
? selected ?? resolveCodexFilesystemHome(undefined, this.fs.homedir) : selected;
|
||||
}
|
||||
|
||||
/** Only the seat's own CODEX_HOME, undefined when it declares none. Probes and readers get it as an extra argument
|
||||
@@ -319,8 +328,8 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
|
||||
return binding?.accountHome ?? (binding?.nodeId ? this.seatHome?.(binding.nodeId, binding.accountHome === null) : undefined);
|
||||
}
|
||||
|
||||
private ownHomeCommandOpt(binding: { nodeId?: string; accountHome?: string | null }): { codexHome?: string } {
|
||||
const own = this.ownHome(binding);
|
||||
private ownHomeCommandOpt(binding: NodeBinding): { codexHome?: string } {
|
||||
const own = binding.codexPermissions && "filesystem" in binding.codexPermissions ? this.homeFor(binding) : this.ownHome(binding);
|
||||
return own ? { codexHome: own } : {};
|
||||
}
|
||||
|
||||
@@ -465,7 +474,8 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
|
||||
// Codex's "continue without trusting" choice writes no state, so an existing install with no hooks.state entry for any
|
||||
// of OpenRig's hooks may be an unrecorded skip, or an older install that never granted them. OpenRig trusts its own
|
||||
// exact shipped hooks there as on a first install (#17). Any recorded choice for one of them, or a layer it can't read,
|
||||
// leaves native review in place. A proven owned grant may renew its content approval.
|
||||
// leaves native review in place. A proven owned grant may renew its content approval, and its declarations when a new
|
||||
// shipped bundle changes them and every approval still matches OpenRig's own record.
|
||||
const firstInstall = !this.fs.exists(cacheRoot) && !layers.some(layer => layer.state === "read"
|
||||
&& Object.hasOwn((parseToml(layer.content).plugins ?? {}) as object, CODEX_CORE_PLUGIN_KEY));
|
||||
const noOwnHookChoice = (read: CodexConfigLayerRead[]) => {
|
||||
@@ -482,14 +492,20 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
|
||||
let content = before;
|
||||
const planned = planOwnedCodexContentApproval({ configPath, content, layers: currentLayers, shipped, installed: cachedDir, freshGrant });
|
||||
if (!planned) return;
|
||||
for (const [key, hash] of Object.entries(planned.trustedHashes)) content = upsertCodexHookTrust(content, key, hash);
|
||||
// The declaration writer ends the file with one newline; keep the owner's own ending.
|
||||
if (content !== before) content = content.replace(/\n*$/, /\n*$/.exec(before)?.[0] ?? "");
|
||||
for (const [key, hash] of Object.entries(planned.hashes)) content = upsertCodexHookTrust(content, key, hash, "trusted_content_hash");
|
||||
// The line writer must not alter examples in strings or duplicate quoted keys.
|
||||
try {
|
||||
const expected = parseToml(before) as { hooks: { state: Record<string, Record<string, unknown>> } };
|
||||
for (const [key, hash] of Object.entries(planned.trustedHashes)) expected.hooks.state[key]!.trusted_hash = hash;
|
||||
for (const [key, hash] of Object.entries(planned.hashes)) expected.hooks.state[key]!.trusted_content_hash = hash;
|
||||
if (!isDeepStrictEqual(parseToml(content), expected)) return;
|
||||
} catch { return; } // Leave native review and owner bytes intact for unsupported TOML spellings.
|
||||
if (this.fs.readFile(configPath) !== before) return; // A concurrent native choice wins.
|
||||
// A concurrent native choice wins: in this file, or in any layer the plan read (a layer appearing, changing,
|
||||
// disappearing or becoming unreadable counts).
|
||||
if (this.fs.readFile(configPath) !== before || !isDeepStrictEqual(readLayers(), currentLayers)) return;
|
||||
if (content !== before) this.fs.writeFile(configPath, content);
|
||||
recordOwnedCodexApproval(configPath, planned.approval);
|
||||
};
|
||||
@@ -891,6 +907,36 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
|
||||
return { delivered, failed, ...(warnings.length ? { warnings } : {}) };
|
||||
}
|
||||
|
||||
/** No managed config writes, pane input, termination or bindings change here. */
|
||||
async preflightLaunch(binding: NodeBinding): Promise<{ ok: true; warnings?: string[] } | { ok: false; error: string }> {
|
||||
const decision = await this.checkFilesystemPolicy(binding);
|
||||
if (!decision) return { ok: true };
|
||||
if (!decision.ok) return decision;
|
||||
const profile = await this.checkProfileLoad(binding);
|
||||
if (!profile.ok) return profile;
|
||||
this.filesystemPreflight.set(binding, decision);
|
||||
return decision.verified ? { ok: true } : { ok: true, warnings: [codexPolicyWarning(decision.reason)] };
|
||||
}
|
||||
|
||||
private async checkFilesystemPolicy(binding: NodeBinding): Promise<CodexFilesystemDecision | undefined> {
|
||||
if (!binding.codexPermissions || !("filesystem" in binding.codexPermissions)) return undefined;
|
||||
try {
|
||||
return await this.verifyFilesystemPolicy({ permissions: binding.codexPermissions, cwd: binding.cwd,
|
||||
codexHome: this.homeFor(binding), launchPath: this.launchPath, launchWrapper: binding.launchWrapper,
|
||||
codexConfigProfile: binding.codexConfigProfile?.trim() || undefined });
|
||||
} catch {
|
||||
return { ok: true, verified: false, reason: "Native Codex configuration reader failed" };
|
||||
}
|
||||
}
|
||||
|
||||
private async checkProfileLoad(binding: NodeBinding): Promise<{ ok: true } | { ok: false; error: string }> {
|
||||
const profile = binding.codexConfigProfile?.trim();
|
||||
if (!profile) return { ok: true };
|
||||
const own = this.ownHome(binding);
|
||||
const probe = await (own ? this.verifyProfilePreflight(profile, binding.cwd, own) : this.verifyProfilePreflight(profile, binding.cwd));
|
||||
return probe.ok ? { ok: true } : { ok: false, error: `${probe.error}${probe.migrationHint ? `\n Fix: ${probe.migrationHint}` : ""}` };
|
||||
}
|
||||
|
||||
async launchHarness(
|
||||
binding: NodeBinding,
|
||||
opts: { name: string; resumeToken?: string; forkSource?: import("../domain/runtime-adapter.js").ForkSource; beforeNativeDispatch?: () => boolean },
|
||||
@@ -914,6 +960,7 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
|
||||
const prepared = await this.prepareLaunch(binding, opts.name, undefined, { installCorePlugin: !opts.resumeToken });
|
||||
if (!prepared.ok) return prepared;
|
||||
const { modelArg, effortArg, appliedLaunch, postureArg, queueStateDirArg, gitDirArg, seatFolderArg, daemonArg, networkArg, loginShellArg } = prepared;
|
||||
const policyNotice = appliedLaunch.reason?.startsWith("policy not verified:") ? { warnings: [appliedLaunch.reason] } : {};
|
||||
|
||||
// Fork branch: `codex fork <parent_thread_id>`. Captures the NEW thread id
|
||||
// post-fork. Parent thread id is NOT persisted onto the new seat record
|
||||
@@ -954,7 +1001,7 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
|
||||
// For a handover a missed capture is pending metadata, not a failed launch: the fork returns
|
||||
// without a token and the handover's readiness checks still decide success. Any other fork
|
||||
// keeps its unsent context pending for `rig seat continue`, which verifies the child first.
|
||||
if (opts.forkSource.pendingIdAllowed) return { ok: true, appliedLaunch };
|
||||
if (opts.forkSource.pendingIdAllowed) return { ok: true, appliedLaunch, ...policyNotice };
|
||||
return {
|
||||
ok: false,
|
||||
error: "codex fork: could not capture new post-fork thread id",
|
||||
@@ -962,7 +1009,7 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
|
||||
forkIdentityPending: true,
|
||||
};
|
||||
}
|
||||
return { ok: true, resumeToken: threadId, resumeType: "codex_id", appliedLaunch };
|
||||
return { ok: true, resumeToken: threadId, resumeType: "codex_id", appliedLaunch, ...policyNotice };
|
||||
}
|
||||
|
||||
// OPR.0.4.8.2: one posture decision (codexPostureArg) for the fresh launch too — YOLO forces
|
||||
@@ -989,17 +1036,17 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
|
||||
if (opts.resumeToken) {
|
||||
const verification = await this.verifyResumeLaunch(binding.tmuxSession, updatePrompt, { resumeToken: opts.resumeToken, ...this.ownHomeOpt(binding) });
|
||||
if (!verification.ok) return verification;
|
||||
return { ok: true, resumeToken: opts.resumeToken, resumeType: "codex_id", appliedLaunch,
|
||||
return { ok: true, resumeToken: opts.resumeToken, resumeType: "codex_id", appliedLaunch, ...policyNotice,
|
||||
...(verification.resumedProcess ? { resumedProcess: verification.resumedProcess } : {}) };
|
||||
}
|
||||
|
||||
const threadId = await this.captureFreshThreadId(binding, updatePrompt);
|
||||
if (updatePrompt.failure) return updatePrompt.failure;
|
||||
if (threadId) {
|
||||
return { ok: true, resumeToken: threadId, resumeType: "codex_id", appliedLaunch };
|
||||
return { ok: true, resumeToken: threadId, resumeType: "codex_id", appliedLaunch, ...policyNotice };
|
||||
}
|
||||
|
||||
return { ok: true, appliedLaunch };
|
||||
return { ok: true, appliedLaunch, ...policyNotice };
|
||||
}
|
||||
|
||||
/** The command launchHarness would type to resume `resumeToken`, wrapped in the seat launch environment,
|
||||
@@ -1007,7 +1054,7 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
|
||||
async buildResumeCommand(
|
||||
binding: NodeBinding,
|
||||
opts: { name: string; resumeToken: string; running?: RunningCodexLaunch; launchShell?: string },
|
||||
): Promise<{ ok: true; command: string; core: string; appliedLaunch: AppliedLaunchObservation } | { ok: false; error: string }> {
|
||||
): Promise<{ ok: true; command: string; core: string; appliedLaunch: AppliedLaunchObservation; warnings?: string[] } | { ok: false; error: string }> {
|
||||
if (binding.launchWrapper?.length && !this.seatLaunchEnvironment) {
|
||||
return { ok: false, error: "launch_wrapper support unavailable; no agent started." };
|
||||
}
|
||||
@@ -1022,7 +1069,8 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
|
||||
} catch {
|
||||
return { ok: false, error: "launch_wrapper unavailable; no agent started." };
|
||||
}
|
||||
return { ok: true, command, core, appliedLaunch: prepared.appliedLaunch };
|
||||
return { ok: true, command, core, appliedLaunch: prepared.appliedLaunch,
|
||||
...(prepared.appliedLaunch.reason?.startsWith("policy not verified:") ? { warnings: [prepared.appliedLaunch.reason] } : {}) };
|
||||
}
|
||||
|
||||
/** Type a command buildResumeCommand built into the pane's shell, then verify the resume as launchHarness
|
||||
@@ -1073,6 +1121,10 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
|
||||
* prepared parts come from the running Codex instead, and no Codex process is started to decide them. */
|
||||
private async prepareLaunch(binding: NodeBinding, name: string, running: RunningCodexLaunch | undefined,
|
||||
opts: { installCorePlugin: boolean }): Promise<PreparedCodexLaunch | { ok: false; error: string }> {
|
||||
const checkedBeforeCutover = this.filesystemPreflight.get(binding);
|
||||
const decision = checkedBeforeCutover ?? await this.checkFilesystemPolicy(binding);
|
||||
this.filesystemPreflight.delete(binding);
|
||||
if (decision && !decision.ok) return decision;
|
||||
// The config write and, for a seat that selected openrig-core, its install run as one step under the config lock, so
|
||||
// concurrent launches never interleave them. An unselected seat's launch never installs.
|
||||
// A seat with its own CODEX_HOME gets OpenRig's managed config (hooks, feature flag) and plugin in that home.
|
||||
@@ -1091,15 +1143,17 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
|
||||
const effortArg = effort ? ` -c ${shellQuote(`model_reasoning_effort="${effort}"`)}` : "";
|
||||
const profile = binding.codexConfigProfile?.trim();
|
||||
const profileArg = profile ? ` -p ${shellQuote(profile)}` : "";
|
||||
// A handover rebuild's observed predecessor envelope, else the seat's own envelope, replaces the posture decision.
|
||||
const memberEnvelope = binding.codexRebuildPermissions || !binding.codexPermissions ? undefined : codexMemberEnvelope(binding.codexPermissions);
|
||||
const envelope = binding.codexRebuildPermissions ?? memberEnvelope;
|
||||
const posture = envelope
|
||||
const filesystemPermissions = binding.codexPermissions && "filesystem" in binding.codexPermissions ? binding.codexPermissions : undefined;
|
||||
// An authored filesystem policy always wins over a stale observed legacy envelope. Legacy rebuilds keep their carry behavior.
|
||||
const memberChoice = binding.codexPermissions && (!binding.codexRebuildPermissions || filesystemPermissions) ? codexMemberLaunch(binding.codexPermissions) : undefined;
|
||||
const envelope = memberChoice ? undefined : binding.codexRebuildPermissions;
|
||||
const posture = memberChoice ? profileArg + memberChoice.args : envelope
|
||||
? profileArg + codexEnvelopeArgs(envelope)
|
||||
: codexPostureArg(profileArg, process.env, binding.launchPosture);
|
||||
const appliedLaunch: AppliedLaunchObservation = envelope ? observeCodexEnvelope(envelope) : observeCodexSandbox(posture);
|
||||
const appliedLaunch: AppliedLaunchObservation = memberChoice?.observation ?? (envelope ? observeCodexEnvelope(envelope) : observeCodexSandbox(posture));
|
||||
if (decision && !decision.verified) appliedLaunch.reason = codexPolicyWarning(decision.reason);
|
||||
// The seat's envelope is not full access, so a policy's full_bypass extras don't follow it.
|
||||
const postureArg = posture + operationalLaunchArg(this.runtime, memberEnvelope ? { ...binding, kernelAuthority: false, launchPosture: undefined } : binding);
|
||||
const postureArg = posture + operationalLaunchArg(this.runtime, memberChoice ? { ...binding, kernelAuthority: false, launchPosture: undefined } : binding);
|
||||
|
||||
if (running) {
|
||||
// The running Codex already loaded its profile; drift in -p is the caller's to compare.
|
||||
@@ -1107,10 +1161,10 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
|
||||
// conversation id, as on every resume, so the resume proof reads the id even when a dir has a space.
|
||||
return { ok: true, model, modelArg, effort, effortArg, profile, appliedLaunch, postureArg,
|
||||
queueStateDirArg: "",
|
||||
gitDirArg: running.addDirs.map((dir) => ` --add-dir ${shellQuote(dir)}`).join(""),
|
||||
gitDirArg: (filesystemPermissions ? [] : running.addDirs).map((dir) => ` --add-dir ${shellQuote(dir)}`).join(""),
|
||||
seatFolderArg: "",
|
||||
daemonOptOut: running.daemonOptOut, daemonArg: running.daemonOptOut ? " --no-daemon" : "",
|
||||
networkArg: running.networkOverride ? ` -c ${shellQuote(CODEX_NETWORK_DEFAULT_OVERRIDE)}` : "",
|
||||
networkArg: !filesystemPermissions && running.networkOverride ? ` -c ${shellQuote(CODEX_NETWORK_DEFAULT_OVERRIDE)}` : "",
|
||||
loginShellArg: running.nonLoginShell ? codexNonLoginShellArg : "" };
|
||||
}
|
||||
|
||||
@@ -1118,19 +1172,14 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
|
||||
// [profiles.<name>] table or invalid TOML must fail BEFORE the opaque
|
||||
// `codex -p <profile> resume` failure. An absent .config.toml passes
|
||||
// (Codex default-layers it; advisor Option B).
|
||||
if (profile) {
|
||||
const probeResult = await (own ? this.verifyProfilePreflight(profile, binding.cwd, own) : this.verifyProfilePreflight(profile, binding.cwd));
|
||||
if (!probeResult.ok) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `${probeResult.error}${probeResult.migrationHint ? `\n Fix: ${probeResult.migrationHint}` : ""}`,
|
||||
};
|
||||
}
|
||||
if (profile && !checkedBeforeCutover) {
|
||||
const loaded = await this.checkProfileLoad(binding);
|
||||
if (!loaded.ok) return loaded;
|
||||
}
|
||||
// Codex rejects writable --add-dir roots under a read-only sandbox. Only
|
||||
// suppress OpenRig's generated roots when later project layers cannot make it writable.
|
||||
// A seat envelope states its sandbox: read-only gets no generated roots; workspace-write keeps them.
|
||||
const suppressAutoAddDirs = memberEnvelope ? memberEnvelope.sandboxPolicy.type === "read-only"
|
||||
const suppressAutoAddDirs = memberChoice ? memberChoice.suppressAutoAddDirs
|
||||
: Boolean(!binding.codexRebuildPermissions && profile && posture === profileArg && this.profileRemainsReadOnly(profile, binding.cwd, home));
|
||||
// Issue #121: fresh, resume and fork get the same git metadata dirs, so a restored or forked seat can still commit.
|
||||
// A rebuild keeps the writable roots its observed envelope names instead.
|
||||
@@ -1139,7 +1188,7 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
|
||||
// The seat's own topology folder, so it can keep its LEARNED.md and recap: the same launches and the same suppression.
|
||||
const seatFolder = binding.codexRebuildPermissions || suppressAutoAddDirs ? undefined : this.prepareSeatFolder?.(name);
|
||||
const seatFolderArg = seatFolder ? ` --add-dir ${shellQuote(seatFolder)}` : "";
|
||||
const teamWorkspaceArg = !envelope && binding.teamPermissionDefault && !profile
|
||||
const teamWorkspaceArg = !memberChoice && !envelope && binding.teamPermissionDefault && !profile
|
||||
&& appliedLaunch.state === "observed" && appliedLaunch.value === "workspace-write"
|
||||
? codexTeamWorkspaceArg(this.prepareTeamWorkspace, name) : "";
|
||||
const queueStateDirArg = binding.codexRebuildPermissions || suppressAutoAddDirs
|
||||
@@ -1153,7 +1202,7 @@ export class CodexRuntimeAdapter implements RuntimeAdapter {
|
||||
const daemonOptOut = daemonSupport?.kind === "supported";
|
||||
const daemonArg = daemonOptOut ? " --no-daemon" : "";
|
||||
// #275: on the plain floor, network access unless Codex reports an opt-out or policy. An envelope states its own.
|
||||
const networkArg = envelope ? ""
|
||||
const networkArg = memberChoice || envelope ? ""
|
||||
: await codexNetworkDefaultArg(own && this.readNetworkDefault ? ((cwd: string) => this.readNetworkDefault!(cwd, own)) : this.readNetworkDefault, appliedLaunch, binding.cwd, name);
|
||||
|
||||
// The launch facts keep the probed daemon choice, so a printed recovery command can repeat it; no probe, no fact.
|
||||
|
||||
@@ -1237,8 +1237,10 @@ export class TmuxAdapter {
|
||||
const identity = this.freshManaged.get(target)?.nodeId ?? target;
|
||||
const submit = keys.some(isSubmitKey);
|
||||
const check = async () => {
|
||||
if (this.deliveryGuard?.needsInputCheck(identity)) await this.deliveryGuard.beforeInput(identity, submit);
|
||||
// The caller's checks can wait (a conversation lookup), so they run first and the guard's input read runs
|
||||
// last, as in sendText (#3076): input typed while they wait is seen, and a key is not sent onto it.
|
||||
if (options?.beforeKeys) await options.beforeKeys();
|
||||
if (this.deliveryGuard?.needsInputCheck(identity)) await this.deliveryGuard.beforeInput(identity, submit);
|
||||
};
|
||||
await check();
|
||||
beforeWrite(); beforeInput?.();
|
||||
|
||||
@@ -28,11 +28,8 @@ export interface AttentionItem {
|
||||
/** A queue request's decision revision: the same opaque token its single-row read returns and a settling act can name. */
|
||||
revision?: string;
|
||||
/** The requests this is about, by ID: a parked row is itself the request; an ask is about the open rows blocked on it
|
||||
* (at most 100). Empty when no request is recorded as waiting on it, which isn't proof that it's about nothing: a
|
||||
* request that names it only in its text isn't counted. */
|
||||
* (at most 100). Empty when no request is recorded as waiting on it. */
|
||||
about?: string[];
|
||||
/** Present when more than 100 open rows are blocked on this ask: `about` is the newest 100, not all of them. */
|
||||
aboutTruncated?: true;
|
||||
}
|
||||
export interface AttentionDetail {
|
||||
item: AttentionItem;
|
||||
|
||||
@@ -63,6 +63,8 @@ export const POST_COMPACT_RESTORE_COOLDOWN_MS_DEFAULT = 10 * 60_000;
|
||||
// writing the restore map can take a minute+; the wait returns as soon as the
|
||||
// seat is idle, so this only bounds a pathological never-idle case.
|
||||
export const MANUAL_PREP_WAIT_MS_DEFAULT = 180_000;
|
||||
/** How often a manual attempt reads its seat while it waits (for the map, or after a /compact the seat wasn't idle for). */
|
||||
export const MANUAL_SEAT_READ_INTERVAL_MS = 5_000;
|
||||
// Operational ceiling, not a measured optimum. Existing context polls advance auto preparation.
|
||||
export const AUTO_PREP_WAIT_MS_DEFAULT = 25 * 60_000;
|
||||
// How long a stopped attempt holds automatic compaction off for its seat before a fresh attempt may begin. Without it one
|
||||
@@ -224,7 +226,7 @@ export function buildCompactCommand(compactInstruction: string): string {
|
||||
}
|
||||
|
||||
function buildPreCompactPrepPrompt(input: {
|
||||
usedPercentage: number;
|
||||
usedPercentage: number | null;
|
||||
thresholdPercent: number;
|
||||
preCompactInstruction?: string | null;
|
||||
/** The policy's compaction instruction when it is too long for the /compact command. */
|
||||
@@ -239,7 +241,7 @@ function buildPreCompactPrepPrompt(input: {
|
||||
]
|
||||
: [
|
||||
"OpenRig automatic compaction preparation is now required.",
|
||||
`Current context usage is ${input.usedPercentage}%; configured compaction threshold is ${input.thresholdPercent}%.`,
|
||||
`Current context usage is ${input.usedPercentage ?? "unknown"}%; configured compaction threshold is ${input.thresholdPercent}%.`,
|
||||
`The ${AUTO_PREP_WAIT_MS_DEFAULT / 60_000}-minute ceiling starts after preparation delivery returns; completing the restore map and becoming idle must fit within it.`,
|
||||
];
|
||||
pieces.push(
|
||||
@@ -253,6 +255,7 @@ function buildPreCompactPrepPrompt(input: {
|
||||
pieces.push(
|
||||
`Write this attempt's complete restore map to ${JSON.stringify(input.preparation.mapPath + ".tmp")}, using your ordinary file-edit tool. Append the exact completion marker below as its LAST line, then finish and close the file. OpenRig will atomically publish it to ${JSON.stringify(input.preparation.mapPath)}; do not run a shell command to rename or publish it. Never write the final file incrementally.`,
|
||||
`Completion marker: ${input.preparation.marker}`,
|
||||
"To avoid one cause of approval prompts, which hold /compact until someone answers them: write files with your file-edit tool (acceptEdits covers your working directory, not a preparation root outside it), and if you publish a seat recap, run rig context recap-write --file with the file's literal absolute path, with no shell variable assignment or command substitution, so an allow rule for rig commands can match it.",
|
||||
"The marker identifies this attempt and occupant; it does not certify the map's quality. Keep the normal ranked restore-map content.",
|
||||
`Near the top of the map, copy this note word for word; the restore request will have you read it: ${MANAGED_COMPACT_TRUST_NOTE}`,
|
||||
...(input.overflowCompactInstruction?.trim()
|
||||
@@ -498,6 +501,10 @@ export interface PreparationState {
|
||||
mapUsedPercentage?: number;
|
||||
/** A record too old to resume that this attempt replaced (see `getStrandedCompaction`): its restore may have been owed. */
|
||||
supersedes?: StrandedCompaction;
|
||||
/** A manual attempt's latest reading of its seat showed a prompt (a permission request its preparation turn reached,
|
||||
* say) that holds /compact: since when, and when it was last seen. `current` is false when a later reading couldn't
|
||||
* establish the seat's state, so the prompt is an earlier observation. Cleared when a reading shows idle or work. */
|
||||
awaitingInput?: { since: number; reason: string; observedAt: number; current: boolean };
|
||||
}
|
||||
/** An open record from before a restart, too old to resume: the seat's restore steps may still be owed. */
|
||||
export interface StrandedCompaction { attemptId: string; mapPath: string; phase: string; recordedAt: string }
|
||||
@@ -1409,7 +1416,6 @@ export class ClaudeCompactionEnforcer {
|
||||
return { triggered: false, stage: "skipped-or-failed", reason: "already_in_progress" };
|
||||
}
|
||||
if (input.runtime !== "claude-code") return this.recordManualFailure(input.sessionName, "runtime_filter");
|
||||
if (input.usedPercentage == null) return this.recordManualFailure(input.sessionName, "no_usage_data");
|
||||
// The preparation prompt cannot be written to such a seat either, so the whole attempt is refused up front.
|
||||
if (this.paneUnknownProtected(input.sessionName)) return this.recordManualFailure(input.sessionName, "pane_unknown_protected");
|
||||
const actor = opts.actor ?? { source: "caller" as const, session: null };
|
||||
@@ -1429,34 +1435,69 @@ export class ClaudeCompactionEnforcer {
|
||||
};
|
||||
this.setManualStage(input.sessionName, "preparing", undefined, opts.operatorInitiated === true);
|
||||
await this.deliverPreparation(input, attempt);
|
||||
// Manual preparation can pause for an ordinary approval, before or after the map is complete. OpenRig never answers
|
||||
// it. It keeps the latest completed reading of the seat on the attempt (awaitingInput), recorded before deadline
|
||||
// reconciliation, so --state and the expiry reason describe the seat now rather than an earlier prompt.
|
||||
const observe = (reading: { ok: boolean; reason?: string; activity?: { state?: string } } | null) => {
|
||||
const state = reading === null ? "unknown" : reading.ok ? "idle"
|
||||
: reading.reason === "target_needs_input" ? "needs_input" : reading.activity?.state ?? "unknown";
|
||||
if (state === "needs_input") {
|
||||
attempt.awaitingInput = { since: attempt.awaitingInput?.since ?? this.now(), reason: "target_needs_input", observedAt: this.now(), current: true };
|
||||
} else if (state === "unknown") {
|
||||
if (attempt.awaitingInput) attempt.awaitingInput = { ...attempt.awaitingInput, current: false };
|
||||
} else delete attempt.awaitingInput;
|
||||
};
|
||||
// While the map is written, one bounded reading every MANUAL_SEAT_READ_INTERVAL_MS, never one per map check. The first
|
||||
// comes an interval after delivery: a reading taken as the preparation turn starts tells nothing.
|
||||
let nextRead = this.now() + MANUAL_SEAT_READ_INTERVAL_MS;
|
||||
while (attempt.status === "waiting" && !opts.skipMap && !this.mapReady(attempt)) {
|
||||
const remaining = attempt.deadlineAt! - this.now();
|
||||
if (remaining > 0 && this.now() >= nextRead) {
|
||||
let reading;
|
||||
try { reading = await this.sessionTransport.waitUntilIdle(input.sessionName, Math.min(remaining, CAPTURE_READABLE_BUDGET_MS), attempt.controller.signal, { singleObservation: true, allowDraft: true }); }
|
||||
catch { reading = null; }
|
||||
observe(reading);
|
||||
nextRead = this.now() + MANUAL_SEAT_READ_INTERVAL_MS;
|
||||
}
|
||||
this.reconcilePreparations();
|
||||
if (attempt.status !== "waiting") break;
|
||||
await this.sleep(Math.min(250, Math.max(1, attempt.deadlineAt! - this.now())));
|
||||
}
|
||||
if (attempt.status !== "waiting") return failed(attempt.reason ?? "preparation_incomplete");
|
||||
// Manual preparation can pause for an ordinary approval after the map is complete.
|
||||
// Keep the same classifier/deadline and wait outside the input lease; never answer it.
|
||||
let idle;
|
||||
do {
|
||||
const remaining = attempt.deadlineAt! - this.now();
|
||||
if (remaining <= 0) return failed(this.mapReady(attempt) ? "map_complete_seat_never_idle" : "preparation_incomplete");
|
||||
try { idle = await this.sessionTransport.waitUntilIdle(input.sessionName, remaining, attempt.controller.signal, { allowDraft: true }); }
|
||||
catch { idle = { ok: false, reason: "transport_unavailable" }; }
|
||||
this.reconcilePreparations();
|
||||
if (idle.ok || idle.reason !== "target_needs_input" || attempt.status !== "waiting") break;
|
||||
await this.sleep(Math.min(250, Math.max(1, attempt.deadlineAt! - this.now())));
|
||||
this.reconcilePreparations();
|
||||
} while (attempt.status === "waiting");
|
||||
if (!idle.ok || attempt.status !== "waiting") {
|
||||
// The transport was given this attempt's remaining budget; name its timeout like preparation expiry.
|
||||
const reason = attempt.reason ?? (idle.ok ? "preparation_incomplete"
|
||||
: idle.reason === "wait_for_idle_timeout"
|
||||
? this.mapReady(attempt) ? "map_complete_seat_never_idle" : "preparation_incomplete"
|
||||
: idle.reason);
|
||||
return failed(reason);
|
||||
// The budget ran out: name a prompt the latest reading showed, else as before.
|
||||
const expired = () => attempt.awaitingInput?.current ? "preparation_needs_input"
|
||||
: this.mapReady(attempt) ? "map_complete_seat_never_idle" : "preparation_incomplete";
|
||||
let compact: { ok: boolean; reason?: string; deferredBy?: { reason?: string; activity?: { state?: string } } };
|
||||
for (;;) {
|
||||
let idle;
|
||||
do {
|
||||
const remaining = attempt.deadlineAt! - this.now();
|
||||
if (remaining <= 0) return failed(expired());
|
||||
// The wait can run to the deadline. Each reading it completes reaches the attempt as it lands, so a --state read or
|
||||
// deadline reconciliation during the wait never takes an answered prompt for a current one.
|
||||
try { idle = await this.sessionTransport.waitUntilIdle(input.sessionName, remaining, attempt.controller.signal,
|
||||
{ allowDraft: true, onObservation: (activity) => observe({ ok: false, activity }) }); }
|
||||
catch { idle = { ok: false, reason: "transport_unavailable" }; }
|
||||
observe(idle);
|
||||
this.reconcilePreparations();
|
||||
if (idle.ok || idle.reason !== "target_needs_input" || attempt.status !== "waiting") break;
|
||||
await this.sleep(Math.min(250, Math.max(1, attempt.deadlineAt! - this.now())));
|
||||
this.reconcilePreparations();
|
||||
} while (attempt.status === "waiting");
|
||||
if (!idle.ok || attempt.status !== "waiting") {
|
||||
// The transport was given this attempt's remaining budget; name its timeout like preparation expiry.
|
||||
const reason = attempt.reason ?? (idle.ok ? "preparation_incomplete"
|
||||
: idle.reason === "wait_for_idle_timeout" ? expired() : idle.reason);
|
||||
return failed(reason);
|
||||
}
|
||||
compact = await this.sendPreparedCompact(input, attempt, opts.skipMap === true);
|
||||
// The seat wasn't idle at the send after all (its preparation turn reached a prompt, or did more work): nothing was
|
||||
// written, so wait again within this attempt's deadline rather than disarm. The send reads the pane while the idle
|
||||
// wait can take a hook's idle, so pause one reading interval first: a disagreement can't loop sends without a break.
|
||||
if (compact.ok || compact.reason !== "waiting_for_idle") break;
|
||||
observe({ ok: false, ...compact.deferredBy });
|
||||
await this.sleep(Math.min(MANUAL_SEAT_READ_INTERVAL_MS, Math.max(1, attempt.deadlineAt! - this.now())));
|
||||
}
|
||||
const compact = await this.sendPreparedCompact(input, attempt, opts.skipMap === true);
|
||||
if (!compact.ok) {
|
||||
const outcome = failed(compact.reason ?? "send_failed");
|
||||
// A /compact whose result was lost still owes its restore steps, and this request authorizes them.
|
||||
@@ -1590,7 +1631,7 @@ export class ClaudeCompactionEnforcer {
|
||||
const composed = composeManagedCompactCommand({ compactInstruction: attempt.compactInstruction, mapPath: attempt.mapPath });
|
||||
prep = await this.sessionTransport.send(input.sessionName, buildPreCompactPrepPrompt({
|
||||
overflowCompactInstruction: composed.instructionInCommand ? null : attempt.compactInstruction,
|
||||
usedPercentage: input.usedPercentage!, thresholdPercent: policy.thresholdPercent,
|
||||
usedPercentage: input.usedPercentage ?? null, thresholdPercent: policy.thresholdPercent,
|
||||
preCompactInstruction: policy.preCompactInstruction, preparation: attempt, constructedAt: this.now(),
|
||||
}), { openrigNotice: true, allowDraftWhileIdle: true, ...idleGate, beforeWrite: () => {
|
||||
this.reconcilePreparations();
|
||||
@@ -1634,7 +1675,7 @@ export class ClaudeCompactionEnforcer {
|
||||
this.reconcilePreparations();
|
||||
}
|
||||
|
||||
private async sendPreparedCompact(input: EnforcerInput, attempt: PreparationAttempt, skipMap: boolean): Promise<{ok: boolean; reason?: string}> {
|
||||
private async sendPreparedCompact(input: EnforcerInput, attempt: PreparationAttempt, skipMap: boolean): Promise<{ok: boolean; reason?: string; deferredBy?: { reason?: string; activity?: { state?: string } }}> {
|
||||
const check = () => {
|
||||
this.reconcilePreparations();
|
||||
this.checkAttemptPolicy(input, attempt);
|
||||
@@ -1705,13 +1746,15 @@ export class ClaudeCompactionEnforcer {
|
||||
if (notSent && typeof windowReason === "string" && HOLD_REASONS.has(windowReason) && this.holdPrepared(input.sessionName, attempt, windowReason)) {
|
||||
return { ok: false, reason: PREPARED_AWAITING_WINDOW };
|
||||
}
|
||||
// Only a known pre-input idle deferral keeps the automatic attempt armed for a later poll; the transport
|
||||
// marks those `not_reached`. Reconciliation still bounds the idle grace and stops on an occupant change.
|
||||
// Only a known pre-input idle deferral keeps the attempt armed: an automatic one for a later poll, a manual one for
|
||||
// the rest of its deadline (its caller waits again). The transport marks those `not_reached`. Reconciliation still
|
||||
// bounds the idle grace and stops on an occupant change.
|
||||
// A typing-guard draft hold (`draft_*`) is `not_reached` too, but it is a refusal, not an idle wait: it stops
|
||||
// as not sent, and a fresh attempt may begin after the retry cooldown.
|
||||
const draftHold = policyDraftHold || (typeof result.reason === "string" && result.reason.startsWith("draft_"));
|
||||
if (attempt.mode === "automatic" && attempt.status === "waiting" && notSent && phase === "not_reached" && !draftHold) {
|
||||
return { ok: false, reason: "waiting_for_idle" };
|
||||
if (attempt.status === "waiting" && notSent && phase === "not_reached" && !draftHold
|
||||
&& (attempt.mode === "automatic" || this.now() < attempt.deadlineAt!)) {
|
||||
return { ok: false, reason: "waiting_for_idle", deferredBy: { reason: result.reason, activity: result.activity } };
|
||||
}
|
||||
// A compact may have been sent despite a lost result. Never replay automatically.
|
||||
attempt.compact = notSent ? "not_sent" : "uncertain";
|
||||
@@ -1790,7 +1833,9 @@ export class ClaudeCompactionEnforcer {
|
||||
else if (!attempt.prepared && attempt.deadlineAt !== null && this.now() >= this.compactDeadline(attempt)!) {
|
||||
const ready = this.mapReady(attempt);
|
||||
if (!(ready && this.holdPrepared(session, attempt, "map_complete_seat_never_idle"))) {
|
||||
this.stopPreparation(session, ready ? "map_complete_seat_never_idle" : "preparation_incomplete");
|
||||
// A manual attempt whose latest reading is a prompt says so (only the manual wait records awaitingInput).
|
||||
this.stopPreparation(session, attempt.awaitingInput?.current ? "preparation_needs_input"
|
||||
: ready ? "map_complete_seat_never_idle" : "preparation_incomplete");
|
||||
}
|
||||
}
|
||||
if (enabled) attempt.policyWasEnabled = true;
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import {
|
||||
CODEX_SEAT_PERMISSION_PROFILE,
|
||||
codexFilesystemOverrides,
|
||||
type CodexFilesystemAccess,
|
||||
type CodexFilesystemPermissions,
|
||||
} from "./codex-member-permissions.js";
|
||||
import { readCodexConfiguration } from "./codex-network-default.js";
|
||||
|
||||
export type CodexFilesystemDecision =
|
||||
| { ok: true; verified: true }
|
||||
| { ok: true; verified: false; reason: string }
|
||||
| { ok: false; error: string };
|
||||
const verified = (): CodexFilesystemDecision => ({ ok: true, verified: true });
|
||||
const refuse = (error: string, remedy: string): CodexFilesystemDecision => ({ ok: false, error: `${error}\nFix: ${remedy}` });
|
||||
const unknown = (reason: string): CodexFilesystemDecision => ({ ok: true, verified: false, reason });
|
||||
export const codexPolicyWarning = (reason: string): string => `policy not verified: ${reason}`;
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
// Null means absent, including options added by a later native reader.
|
||||
const present = (record: Record<string, unknown>) => Object.entries(record).filter(([, value]) => value != null);
|
||||
function combine(...checks: CodexFilesystemDecision[]): CodexFilesystemDecision {
|
||||
let inconclusive: Extract<CodexFilesystemDecision, { verified: false }> | undefined;
|
||||
for (const check of checks) {
|
||||
if (!check.ok) return check;
|
||||
if (!check.verified) inconclusive ??= check;
|
||||
}
|
||||
return inconclusive ?? verified();
|
||||
}
|
||||
const accessRank = { deny: 0, read: 1, write: 2 };
|
||||
const isAccess = (value: unknown): value is CodexFilesystemAccess => value === "read" || value === "write" || value === "deny";
|
||||
const canonicalKey = (key: string) => key === ":project_roots" ? ":workspace_roots" : key;
|
||||
function ambiguousKeys(keys: string[]): Set<string> {
|
||||
const seen = new Set<string>(), ambiguous = new Set<string>();
|
||||
for (const key of keys.map(canonicalKey)) {
|
||||
if (seen.has(key)) ambiguous.add(key);
|
||||
seen.add(key);
|
||||
}
|
||||
return ambiguous;
|
||||
}
|
||||
const literalAbsolute = (key: string) => path.isAbsolute(key) && path.normalize(key) === key && !/[?*\[\]{}]/.test(key);
|
||||
const nativeSelectors = new Set([":root", ":minimal", ":workspace_roots", ":tmpdir", ":slash_tmp"]);
|
||||
const literalHomePath = (key: string) => key.startsWith("~/") && path.normalize(key) === key && !/[?*\[\]{}]/.test(key);
|
||||
|
||||
/** Compare only established flat coverage. Native expansion, inheritance and
|
||||
* unfamiliar syntax stay unknown; this is not a second sandbox implementation. */
|
||||
function compareFilesystem(actual: unknown, permissions: CodexFilesystemPermissions): CodexFilesystemDecision {
|
||||
if (actual == null) return refuse("Rule permissions.openrig-seat.filesystem: the agent declares read/write/deny rules, but the effective Codex profile has no mapping.",
|
||||
"Select a Codex profile that retains the agent's filesystem rules, or deliberately change the agent's codex_permissions.");
|
||||
if (!isRecord(actual)) return unknown("Codex selected filesystem mapping has an unfamiliar representation");
|
||||
const entries = present(actual);
|
||||
if (!entries.length) return refuse("Rule permissions.openrig-seat.filesystem: the agent declares read/write/deny rules, but the effective Codex mapping is empty.",
|
||||
"Restore the intended filesystem mapping in the effective Codex profile before launching.");
|
||||
const authored = Object.fromEntries(Object.entries(permissions.filesystem).map(([key, value]) => [canonicalKey(key), value]));
|
||||
const effective = Object.fromEntries(entries.map(([key, value]) => [canonicalKey(key), value]));
|
||||
const authoredAmbiguous = ambiguousKeys(Object.keys(permissions.filesystem));
|
||||
const ambiguous = new Set([...authoredAmbiguous, ...ambiguousKeys(entries.map(([key]) => key))]);
|
||||
const at = (rules: Record<string, unknown>, key: string, extraAccess?: CodexFilesystemAccess): CodexFilesystemAccess | undefined => {
|
||||
if (ambiguous.has(key)) return undefined;
|
||||
if (isAccess(rules[key])) return rules[key];
|
||||
const fullRoot = rules[":root"] ?? (literalAbsolute(path.sep) ? rules[path.sep] : undefined);
|
||||
const rootAccess = isAccess(fullRoot) ? fullRoot : "deny";
|
||||
const ancestors = Object.keys(rules).filter(root => (literalAbsolute(root) || literalHomePath(root)) && key.startsWith(root.endsWith(path.sep) ? root : root + path.sep))
|
||||
.sort((a, b) => b.length - a.length);
|
||||
const root = ancestors[0];
|
||||
const ancestorAccess = root ? rules[root] : rootAccess;
|
||||
// Native selectors/home paths can overlap authored literal paths or other
|
||||
// selectors. Do not infer a widening where an existing grant may cover it;
|
||||
// native expansion remains Codex's job, not another policy engine here.
|
||||
// Only the agent's own ambiguity can affect coverage of another key;
|
||||
// duplicate aliases introduced by a lower layer stay local to those aliases.
|
||||
// Non-root denies are restrictions; either full-root spelling is a
|
||||
// default that narrower grants may refine under Codex's native rules.
|
||||
const denyAncestor = root !== undefined && root !== path.sep && rules[root] === "deny";
|
||||
// Codex 0.167.2's Linux/macOS minimal defaults are system paths, not
|
||||
// these user-data roots. Other minimal coverage stays unexpanded.
|
||||
const outsideMinimal = literalAbsolute(key) && /^\/(?:home|Users)(?:\/|$)/i.test(key);
|
||||
const possibleCoverage = extraAccess !== undefined && !denyAncestor
|
||||
&& (!isAccess(ancestorAccess) || accessRank[extraAccess] > accessRank[ancestorAccess])
|
||||
&& (authoredAmbiguous.size > 0 || Object.entries(rules).some(([rule, access]) => rule !== ":root" && rule !== path.sep
|
||||
&& !(rule === ":minimal" && outsideMinimal)
|
||||
&& (nativeSelectors.has(key) || literalHomePath(key) || !literalAbsolute(rule))
|
||||
&& isAccess(access) && accessRank[access] >= accessRank[extraAccess]));
|
||||
if (nativeSelectors.has(key)) return key !== ":root" && possibleCoverage ? undefined : rootAccess;
|
||||
if (!literalAbsolute(key) && !literalHomePath(key)) return undefined;
|
||||
if (key !== path.sep && possibleCoverage) return undefined;
|
||||
if (root) return isAccess(rules[root]) ? rules[root] : undefined;
|
||||
if (isAccess(fullRoot)) return fullRoot;
|
||||
if (literalHomePath(key)) return "deny";
|
||||
if (Object.keys(rules).some(rule => !literalAbsolute(rule) && rule !== ":minimal")) return undefined;
|
||||
// :minimal read cannot grant write; its native read coverage is not
|
||||
// enumerated here, so extra reads outside a literal ancestor stay unknown.
|
||||
if (rules[":minimal"] != null && !outsideMinimal) return rules[":minimal"] === "read" ? "read" : undefined;
|
||||
return "deny";
|
||||
};
|
||||
const checks: CodexFilesystemDecision[] = [];
|
||||
const unfamiliar = entries.some(([, value]) => !isAccess(value));
|
||||
for (const [key, value] of Object.entries(effective)) {
|
||||
if (!isAccess(value)) { checks.push(unknown("Codex returned an unfamiliar filesystem access value or nested mapping")); continue; }
|
||||
const expected = at(authored, key, value);
|
||||
if (expected === undefined) { checks.push(unknown(`Filesystem rule ${JSON.stringify(key)}: the effective configuration grants ${value}; agent coverage could not be compared.`)); continue; }
|
||||
if (accessRank[value] > accessRank[expected]) return refuse(
|
||||
`Filesystem rule ${JSON.stringify(key)}: agent coverage is at most ${expected}; a lower Codex layer (account or trusted project) grants ${value}.`,
|
||||
"Remove the conflicting lower-layer grant, or deliberately update the agent's codex_permissions to the intended access.");
|
||||
if (!(key in authored) && value === "read" && expected === "read" && !Object.keys(authored).some(root =>
|
||||
root === ":root" || (literalAbsolute(root) && literalAbsolute(key) && key.startsWith(root.endsWith(path.sep) ? root : root + path.sep)))) {
|
||||
checks.push(unknown(`Filesystem rule ${JSON.stringify(key)}: native minimal read coverage could not be compared.`));
|
||||
}
|
||||
}
|
||||
for (const [key, access] of Object.entries(authored)) {
|
||||
if (key in effective) continue;
|
||||
const remaining = at(effective, key);
|
||||
if (remaining !== undefined && accessRank[remaining] > accessRank[access] && !unfamiliar) return refuse(
|
||||
`Filesystem rule ${JSON.stringify(key)}: the agent requires ${access}; the effective Codex policy omits that restriction and grants ${remaining}.`,
|
||||
"Restore the agent's restriction in the effective Codex profile, or deliberately change the agent's codex_permissions.");
|
||||
checks.push(unknown("An authored filesystem rule is absent from the effective mapping"));
|
||||
}
|
||||
return combine(...checks);
|
||||
}
|
||||
|
||||
const UNRELATED_REQUIREMENTS = new Set([
|
||||
"modelProvider", "modelProviders", "allowedLoginMethods", "cliAuthCredentialsStore", "chatgptBaseUrl",
|
||||
"additionalDeveloperInstructions", "allowedWindowsSandboxImplementations", "allowedWebSearchModes",
|
||||
"allowManagedHooksOnly", "allowBrowserAndComputerUse", "allowAppshots", "allowRemoteControl",
|
||||
"computerUse", "browserUse", "inAppBrowser", "hooks", "enforceResidency", "models", "sqliteHome",
|
||||
"logDir", "modelCatalogJson", "checkForUpdateOnStartup", "allowLoginShell", "feedback", "otel",
|
||||
// Legacy sandbox allowlists do not select a permission profile.
|
||||
"allowedSandboxModes",
|
||||
]);
|
||||
function compareRequirements(read: unknown, permissions: CodexFilesystemPermissions): CodexFilesystemDecision {
|
||||
if (!isRecord(read) || !("requirements" in read)) return unknown("Codex configRequirements/read returned an unrecognized response");
|
||||
const checks: CodexFilesystemDecision[] = [];
|
||||
if (present(read).some(([key]) => key !== "requirements" && key !== "supportsIndependentSpeedModes")) checks.push(unknown("Codex returned an unfamiliar requirements response field"));
|
||||
if (read.requirements == null) return combine(...checks);
|
||||
if (!isRecord(read.requirements)) return unknown("Codex managed requirements have an unfamiliar shape");
|
||||
for (const [key, value] of present(read.requirements)) {
|
||||
if (UNRELATED_REQUIREMENTS.has(key)) continue;
|
||||
if (key === "defaultPermissions" && typeof value === "string") {
|
||||
// A fallback, not a forced choice. The effective selection and allowlists
|
||||
// below establish whether Codex actually applied the agent's profile.
|
||||
continue;
|
||||
}
|
||||
if (key === "allowedApprovalPolicies" && Array.isArray(value) && value.every(policy => typeof policy === "string")) {
|
||||
if (!value.includes(permissions.approval)) return refuse("Rule allowedApprovalPolicies: the managed allowlist excludes the agent's approval choice.",
|
||||
"Ask the managed-policy owner to allow the intended approval, or select an allowed approval for the agent.");
|
||||
continue;
|
||||
}
|
||||
if (key === "allowedPermissionProfiles" && isRecord(value)) {
|
||||
if (value[CODEX_SEAT_PERMISSION_PROFILE] === false) return refuse("Rule allowedPermissionProfiles: the managed allowlist explicitly excludes the agent's filesystem profile.",
|
||||
"Ask the managed-policy owner to allow the agent's filesystem profile, or select an allowed policy for the agent.");
|
||||
const entries = present(value);
|
||||
if (entries.every(([, allowed]) => typeof allowed === "boolean")) {
|
||||
if (value[CODEX_SEAT_PERMISSION_PROFILE] !== true) return refuse("Rule allowedPermissionProfiles: the managed allowlist does not include the agent's filesystem profile.",
|
||||
"Ask the managed-policy owner to allow the agent's filesystem profile, or select an allowed policy for the agent.");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
checks.push(unknown("Codex returned an unsupported managed requirement"));
|
||||
}
|
||||
return combine(...checks);
|
||||
}
|
||||
|
||||
/** Positive conflicts refuse; unavailable evidence never replaces the authored
|
||||
* invocation or edits managed policy. Unknowns cannot mask a known conflict. */
|
||||
export function decideCodexFilesystemPolicy(request: {
|
||||
permissions: CodexFilesystemPermissions; configRead: unknown; requirementsRead: unknown;
|
||||
}): CodexFilesystemDecision {
|
||||
const { permissions, configRead, requirementsRead } = request;
|
||||
const requirements = compareRequirements(requirementsRead, permissions);
|
||||
if (!requirements.ok) return requirements;
|
||||
const checks: CodexFilesystemDecision[] = [requirements];
|
||||
if (!isRecord(configRead) || !isRecord(configRead.config)) return combine(...checks, unknown("Codex config/read did not return a recognized effective configuration"));
|
||||
const config = configRead.config;
|
||||
if (config.default_permissions == null || typeof config.default_permissions !== "string") checks.push(unknown("Codex permission selection is absent or has an unfamiliar representation"));
|
||||
else if (config.default_permissions !== CODEX_SEAT_PERMISSION_PROFILE) return refuse("Rule default_permissions: the agent selects its filesystem profile; the effective Codex configuration selects a different profile.",
|
||||
"Remove the conflicting account or trusted-project selection, or deliberately change the agent's codex_permissions.");
|
||||
if (typeof config.approval_policy !== "string" || !["never", "on-request", "untrusted"].includes(config.approval_policy)) checks.push(unknown("Codex approval selection is absent or unfamiliar"));
|
||||
else if (config.approval_policy !== permissions.approval) return refuse("Rule approval_policy: the effective Codex configuration conflicts with the agent's approval choice.",
|
||||
"Align the account, trusted-project or managed approval policy with the agent's intended approval choice.");
|
||||
if (config.permissions == null) return refuse("Rule permissions.openrig-seat: the agent selects a filesystem profile, but the effective Codex configuration has no profile mapping.",
|
||||
"Restore the selected profile in the effective Codex configuration before launching.");
|
||||
if (!isRecord(config.permissions)) return combine(...checks, unknown("Codex permission profiles have an unfamiliar representation"));
|
||||
const selected = config.permissions[CODEX_SEAT_PERMISSION_PROFILE];
|
||||
if (selected == null) return refuse("Rule permissions.openrig-seat: the agent selects a filesystem profile that is absent from the effective Codex configuration.",
|
||||
"Restore the selected profile in the effective Codex configuration before launching.");
|
||||
if (!isRecord(selected)) return combine(...checks, unknown("Codex selected profile has an unfamiliar representation"));
|
||||
if (!present(selected).length) return refuse("Rule permissions.openrig-seat: the agent selects filesystem read/write/deny rules, but the effective Codex profile is empty.",
|
||||
"Restore the selected profile's intended filesystem rules before launching.");
|
||||
const unfamiliarProfile = present(selected).some(([key]) => key !== "filesystem" && key !== "network" && key !== "description");
|
||||
if (unfamiliarProfile) checks.push(unknown("Codex returned an unfamiliar selected profile option"));
|
||||
if (!(unfamiliarProfile && selected.filesystem == null)) checks.push(compareFilesystem(selected.filesystem, permissions));
|
||||
const network = selected.network;
|
||||
if (!isRecord(network)) checks.push(unknown("Codex selected network policy could not be compared"));
|
||||
else {
|
||||
if (network.enabled === true && !permissions.network_access) return refuse("Rule network.enabled: the agent denies network access; the effective Codex profile allows it.",
|
||||
"Remove the conflicting lower-layer network grant, or deliberately enable network_access in the agent's codex_permissions.");
|
||||
if (typeof network.enabled !== "boolean") checks.push(unknown("Codex selected network access is unfamiliar"));
|
||||
if (present(network).some(([key]) => key !== "enabled")) checks.push(unknown("Codex returned unfamiliar network options"));
|
||||
}
|
||||
return combine(...checks);
|
||||
}
|
||||
|
||||
/** Pin the normal account home for this opt-in path so the reader and dispatch
|
||||
* do not accidentally use different pane-shell defaults. */
|
||||
export function resolveCodexFilesystemHome(home?: string, normalHome?: string): string | undefined {
|
||||
try {
|
||||
const resolved = home ?? process.env.CODEX_HOME ?? path.join(normalHome ?? os.homedir(), ".codex");
|
||||
return resolved && path.isAbsolute(resolved) && !/[\0\r\n]/.test(resolved) ? resolved : undefined;
|
||||
} catch { return undefined; }
|
||||
}
|
||||
|
||||
export async function verifyCodexFilesystemPolicy(request: {
|
||||
permissions: CodexFilesystemPermissions; cwd: string; codexHome?: string;
|
||||
launchPath?: string; launchWrapper?: readonly string[]; codexConfigProfile?: string;
|
||||
}): Promise<CodexFilesystemDecision> {
|
||||
if (request.launchWrapper?.length) return unknown("launch_wrapper may change the effective home or configuration; the unwrapped reader cannot certify it");
|
||||
// app-server does not expose this CLI profile layer on the supported path.
|
||||
// Keep -p on the actual invocation and leave enforcement to Codex.
|
||||
if (request.codexConfigProfile?.trim()) return unknown("the native reader cannot load the selected codex_config_profile");
|
||||
const codexHome = resolveCodexFilesystemHome(request.codexHome);
|
||||
if (!codexHome) return unknown("the actual Codex account home could not be resolved");
|
||||
try {
|
||||
const read = await readCodexConfiguration({ cwd: request.cwd, codexHome, launchPath: request.launchPath,
|
||||
args: ["-c", `approval_policy=${JSON.stringify(request.permissions.approval)}`,
|
||||
...codexFilesystemOverrides(request.permissions).flatMap(value => ["-c", value]),
|
||||
"-c", "features.plugins=false", "-c", "features.apps=false"] });
|
||||
if (!read.ok) return unknown(read.reason);
|
||||
return decideCodexFilesystemPolicy({ permissions: request.permissions, configRead: read.configRead, requirementsRead: read.requirementsRead });
|
||||
} catch { return unknown("Native Codex configuration reader failed"); }
|
||||
}
|
||||
|
||||
export type CodexFilesystemVerifier = typeof verifyCodexFilesystemPolicy;
|
||||
@@ -4,12 +4,14 @@ import { constants as fsConstants } from "node:fs";
|
||||
import { open } from "node:fs/promises";
|
||||
import { isAbsolute } from "node:path";
|
||||
import type { CodexPermissionEnvelope } from "./codex-rebuild-permissions.js";
|
||||
import { codexEnvelopeArgs } from "./codex-rebuild-permissions.js";
|
||||
import { shellQuote } from "../adapters/shell-quote.js";
|
||||
import type { AppliedLaunchObservation } from "./permission-drift.js";
|
||||
|
||||
/** A Codex seat's own sandbox and approval choice, emitted as explicit flags on its managed launches and resumes.
|
||||
* Full access is not an envelope: it stays the full_bypass mode. Normalized, a workspace-write envelope states every
|
||||
* field the emitter sets, so nothing falls back to a profile's value for them. */
|
||||
export interface CodexMemberPermissions {
|
||||
export interface CodexSandboxPermissions {
|
||||
sandbox: "workspace-write" | "read-only";
|
||||
approval: "never" | "on-request" | "untrusted";
|
||||
network_access?: boolean;
|
||||
@@ -18,20 +20,60 @@ export interface CodexMemberPermissions {
|
||||
exclude_slash_tmp?: boolean;
|
||||
}
|
||||
|
||||
export type CodexFilesystemAccess = "read" | "write" | "deny";
|
||||
|
||||
/** An explicit native filesystem policy, mutually exclusive with the legacy sandbox fields. */
|
||||
export interface CodexFilesystemPermissions {
|
||||
filesystem: Record<string, CodexFilesystemAccess>;
|
||||
approval: Exclude<CodexSandboxPermissions["approval"], "untrusted">;
|
||||
network_access?: boolean;
|
||||
sandbox?: never;
|
||||
writable_roots?: never;
|
||||
exclude_tmpdir_env_var?: never;
|
||||
exclude_slash_tmp?: never;
|
||||
}
|
||||
|
||||
export type CodexMemberPermissions = CodexSandboxPermissions | CodexFilesystemPermissions;
|
||||
|
||||
const KEYS = ["sandbox", "approval", "network_access", "writable_roots", "exclude_tmpdir_env_var", "exclude_slash_tmp"];
|
||||
const WORKSPACE_ONLY = ["network_access", "writable_roots", "exclude_tmpdir_env_var", "exclude_slash_tmp"];
|
||||
const FILESYSTEM_KEYS = ["filesystem", "approval", "network_access"];
|
||||
const FILESYSTEM_SPECIAL_PATHS = new Set([":root", ":minimal", ":workspace_roots", ":project_roots", ":tmpdir", ":slash_tmp"]);
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
|
||||
export function validateCodexMemberPermissions(value: unknown, label = "codex_permissions"): CodexMemberPermissions {
|
||||
if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label}: expected a mapping with sandbox and approval`);
|
||||
const raw = value as Record<string, unknown>;
|
||||
for (const key of Object.keys(raw)) if (!KEYS.includes(key)) throw new Error(`${label}.${key}: unsupported key; supported keys are ${KEYS.join(", ")}`);
|
||||
const sandbox = raw.sandbox;
|
||||
if (!isRecord(value)) throw new Error(`${label}: expected a mapping with sandbox or filesystem, and approval`);
|
||||
const raw = value;
|
||||
const keys = "filesystem" in raw ? FILESYSTEM_KEYS : KEYS;
|
||||
for (const key of Object.keys(raw)) if (!keys.includes(key)) throw new Error(`${label}.${key}: unsupported key; supported keys are ${keys.join(", ")}`);
|
||||
const approval = raw.approval;
|
||||
if (sandbox === "danger-full-access") throw new Error(`${label}.sandbox: full access is the full_bypass mode, not an envelope; select it with --mode full_bypass`);
|
||||
if (sandbox !== "workspace-write" && sandbox !== "read-only") throw new Error(`${label}.sandbox: expected workspace-write or read-only`);
|
||||
if (approval !== "never" && approval !== "on-request" && approval !== "untrusted") {
|
||||
throw new Error(`${label}.approval: expected never, on-request or untrusted`);
|
||||
}
|
||||
if ("filesystem" in raw) {
|
||||
if (approval === "untrusted") {
|
||||
throw new Error(`${label}.approval: untrusted is not supported with filesystem; expected never or on-request`);
|
||||
}
|
||||
if (!isRecord(raw.filesystem) || Object.keys(raw.filesystem).length === 0) {
|
||||
throw new Error(`${label}.filesystem: expected a nonempty mapping of paths to read, write or deny`);
|
||||
}
|
||||
const filesystem: CodexFilesystemPermissions["filesystem"] = {};
|
||||
for (const [path, access] of Object.entries(raw.filesystem)) {
|
||||
if (/[\0\r\n]/.test(path) || !(isAbsolute(path) || path.startsWith("~/") || FILESYSTEM_SPECIAL_PATHS.has(path))) {
|
||||
throw new Error(`${label}.filesystem: expected an absolute path, ~/path or a supported native special path; got ${JSON.stringify(path)}`);
|
||||
}
|
||||
if (access !== "read" && access !== "write" && access !== "deny") {
|
||||
throw new Error(`${label}.filesystem[${JSON.stringify(path)}]: expected read, write or deny`);
|
||||
}
|
||||
filesystem[path] = access;
|
||||
}
|
||||
if (raw.network_access !== undefined && typeof raw.network_access !== "boolean") throw new Error(`${label}.network_access: expected true or false`);
|
||||
return { approval, filesystem, network_access: raw.network_access === true };
|
||||
}
|
||||
const sandbox = raw.sandbox;
|
||||
if (sandbox === "danger-full-access") throw new Error(`${label}.sandbox: full access is the full_bypass mode, not an envelope; select it with --mode full_bypass`);
|
||||
if (sandbox !== "workspace-write" && sandbox !== "read-only") throw new Error(`${label}.sandbox: expected workspace-write or read-only`);
|
||||
if (sandbox === "read-only") {
|
||||
const extra = WORKSPACE_ONLY.find(key => raw[key] !== undefined);
|
||||
if (extra) throw new Error(`${label}.${extra}: only valid with sandbox workspace-write`);
|
||||
@@ -42,26 +84,48 @@ export function validateCodexMemberPermissions(value: unknown, label = "codex_pe
|
||||
}
|
||||
const roots = raw.writable_roots ?? [];
|
||||
if (!Array.isArray(roots)) throw new Error(`${label}.writable_roots: expected a list of absolute paths`);
|
||||
roots.forEach((root, index) => {
|
||||
const writableRoots: string[] = [];
|
||||
roots.forEach((root: unknown, index) => {
|
||||
if (typeof root !== "string" || !root.trim() || !isAbsolute(root) || /[\0\r\n]/.test(root)) {
|
||||
throw new Error(`${label}.writable_roots[${index}]: expected an absolute path without newlines`);
|
||||
}
|
||||
writableRoots.push(root);
|
||||
});
|
||||
return {
|
||||
sandbox: "workspace-write", approval,
|
||||
network_access: raw.network_access === true, writable_roots: [...roots] as string[],
|
||||
network_access: raw.network_access === true, writable_roots: writableRoots,
|
||||
exclude_tmpdir_env_var: raw.exclude_tmpdir_env_var === true, exclude_slash_tmp: raw.exclude_slash_tmp === true,
|
||||
};
|
||||
}
|
||||
|
||||
/** The native policy codexEnvelopeArgs emits for this choice. */
|
||||
export function codexMemberEnvelope(permissions: CodexMemberPermissions): CodexPermissionEnvelope {
|
||||
export function codexMemberEnvelope(permissions: CodexSandboxPermissions): CodexPermissionEnvelope {
|
||||
if (permissions.sandbox === "read-only") return { approvalPolicy: permissions.approval, sandboxPolicy: { type: "read-only" } };
|
||||
return { approvalPolicy: permissions.approval, sandboxPolicy: { type: "workspace-write",
|
||||
writable_roots: permissions.writable_roots ?? [], network_access: permissions.network_access === true,
|
||||
exclude_tmpdir_env_var: permissions.exclude_tmpdir_env_var === true, exclude_slash_tmp: permissions.exclude_slash_tmp === true } };
|
||||
}
|
||||
|
||||
/** Invocation-local profile: never written into the account home or the shared project. */
|
||||
export const CODEX_SEAT_PERMISSION_PROFILE = "openrig-seat";
|
||||
|
||||
export function codexFilesystemOverrides(permissions: CodexFilesystemPermissions): string[] {
|
||||
const entries = Object.entries(permissions.filesystem).map(([path, access]) => `${JSON.stringify(path)}=${JSON.stringify(access)}`).join(",");
|
||||
return [`default_permissions=${JSON.stringify(CODEX_SEAT_PERMISSION_PROFILE)}`,
|
||||
`permissions={${JSON.stringify(CODEX_SEAT_PERMISSION_PROFILE)}={filesystem={${entries}},network={enabled=${permissions.network_access === true}}}}`];
|
||||
}
|
||||
|
||||
/** The same authored choice reaches launch, both resumes and the status plan. This reports argv, not enforcement. */
|
||||
export function codexMemberLaunch(permissions: CodexMemberPermissions): { args: string; observation: AppliedLaunchObservation; suppressAutoAddDirs: boolean } {
|
||||
if ("filesystem" in permissions) {
|
||||
return { args: ` -a ${permissions.approval}` + codexFilesystemOverrides(permissions).map(value => ` -c ${shellQuote(value)}`).join(""),
|
||||
observation: { runtime: "codex", axis: "sandbox", state: "observed", value: `permissions:${CODEX_SEAT_PERMISSION_PROFILE}`,
|
||||
reason: "emitted_launch_arguments", ...(permissions.approval === "never" ? { approvalPolicy: "never" } : {}) }, suppressAutoAddDirs: true };
|
||||
}
|
||||
const envelope = codexMemberEnvelope(permissions);
|
||||
return { args: codexEnvelopeArgs(envelope), observation: observeCodexEnvelope(envelope), suppressAutoAddDirs: permissions.sandbox === "read-only" };
|
||||
}
|
||||
|
||||
/** What an emitted envelope's arguments ask for; the native result still needs its own observation. */
|
||||
export function observeCodexEnvelope(envelope: CodexPermissionEnvelope): AppliedLaunchObservation {
|
||||
return { runtime: "codex", axis: "sandbox", state: "observed", value: envelope.sandboxPolicy.type,
|
||||
|
||||
@@ -122,57 +122,67 @@ export const CODEX_NETWORK_READER_DEADLINE_MS = 4_000;
|
||||
|
||||
/** The production reader: asynchronous, so the daemon keeps serving while Codex starts. */
|
||||
export function codexNetworkDefaultReader(options: CodexNetworkReaderOptions = {}): CodexNetworkDefaultReader {
|
||||
const deadlineMs = options.deadlineMs ?? CODEX_NETWORK_READER_DEADLINE_MS;
|
||||
const graceMs = options.graceMs ?? 500;
|
||||
const maxOutputBytes = options.maxOutputBytes ?? 4 * 1024 * 1024;
|
||||
return async (cwd, seatHome) => {
|
||||
const codexHome = seatHome ?? options.codexHome;
|
||||
const started = performance.now();
|
||||
const env = {
|
||||
...process.env,
|
||||
...(options.launchPath ? { PATH: options.launchPath } : {}),
|
||||
...(options.home ? { HOME: options.home } : {}),
|
||||
...(codexHome ? { CODEX_HOME: codexHome } : {}),
|
||||
};
|
||||
// The launch flag `-s workspace-write` is `sandbox_mode` for the server; plugins and apps are
|
||||
// switched off for the reader only. app-server serves stdio by default.
|
||||
const args = ["-c", 'sandbox_mode="workspace-write"', "-c", "features.plugins=false", "-c", "features.apps=false", "app-server"];
|
||||
let child: ReturnType<typeof spawn>;
|
||||
try {
|
||||
// Its own process group, so cleanup reaches the reader's descendants and nothing else.
|
||||
child = spawn("codex", args, { cwd, env, stdio: ["pipe", "pipe", "ignore"], detached: true });
|
||||
} catch (error) {
|
||||
return { ...no(`codex app-server could not start: ${firstLine(error)}`), elapsedMs: Math.round(performance.now() - started) };
|
||||
}
|
||||
const decision = await converse(child, cwd, deadlineMs, maxOutputBytes);
|
||||
await stopGroup(child, graceMs);
|
||||
const result = await readCodexConfiguration({ ...options, cwd, codexHome: seatHome ?? options.codexHome,
|
||||
args: ["-c", 'sandbox_mode="workspace-write"', "-c", "features.plugins=false", "-c", "features.apps=false"] });
|
||||
const decision = result.ok ? decideCodexNetworkDefault(result.configRead, result.requirementsRead) : no(result.reason);
|
||||
return { ...decision, elapsedMs: Math.round(performance.now() - started) };
|
||||
};
|
||||
}
|
||||
|
||||
function converse(child: ReturnType<typeof spawn>, cwd: string, deadlineMs: number, maxOutputBytes: number): Promise<CodexNetworkDecision> {
|
||||
export type CodexConfigurationRead = { ok: true; configRead: unknown; requirementsRead: unknown } | { ok: false; reason: string };
|
||||
const unread = (reason: string): CodexConfigurationRead => ({ ok: false, reason });
|
||||
|
||||
/** One native config read with the caller's launch overrides. No thread, turn or persistent server. */
|
||||
export async function readCodexConfiguration(options: CodexNetworkReaderOptions & { cwd: string; args: readonly string[] }): Promise<CodexConfigurationRead> {
|
||||
const deadlineMs = options.deadlineMs ?? CODEX_NETWORK_READER_DEADLINE_MS;
|
||||
const graceMs = options.graceMs ?? 500;
|
||||
const maxOutputBytes = options.maxOutputBytes ?? 4 * 1024 * 1024;
|
||||
const { cwd, codexHome } = options;
|
||||
const env = {
|
||||
...process.env,
|
||||
...(options.launchPath ? { PATH: options.launchPath } : {}),
|
||||
...(options.home ? { HOME: options.home } : {}),
|
||||
...(codexHome ? { CODEX_HOME: codexHome } : {}),
|
||||
};
|
||||
// app-server serves stdio by default. The caller states the same permission overrides as its launch.
|
||||
const args = [...options.args, "app-server"];
|
||||
let child: ReturnType<typeof spawn>;
|
||||
try {
|
||||
// Its own process group, so cleanup reaches the reader's descendants and nothing else.
|
||||
child = spawn("codex", args, { cwd, env, stdio: ["pipe", "pipe", "ignore"], detached: true });
|
||||
} catch (error) {
|
||||
return unread(`codex app-server could not start: ${firstLine(error)}`);
|
||||
}
|
||||
const decision = await converse(child, cwd, deadlineMs, maxOutputBytes);
|
||||
await stopGroup(child, graceMs);
|
||||
return decision;
|
||||
}
|
||||
|
||||
function converse(child: ReturnType<typeof spawn>, cwd: string, deadlineMs: number, maxOutputBytes: number): Promise<CodexConfigurationRead> {
|
||||
return new Promise((resolve) => {
|
||||
const answers = new Map<number, Record<string, unknown>>();
|
||||
let buffered = "";
|
||||
let received = 0;
|
||||
let settled = false;
|
||||
const finish = (decision: CodexNetworkDecision) => {
|
||||
const finish = (decision: CodexConfigurationRead) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(deadline);
|
||||
resolve(decision);
|
||||
};
|
||||
const deadline = setTimeout(() => finish(no(`codex app-server did not answer within ${deadlineMs} ms`)), deadlineMs);
|
||||
const deadline = setTimeout(() => finish(unread(`codex app-server did not answer within ${deadlineMs} ms`)), deadlineMs);
|
||||
const send = (message: Record<string, unknown>) => {
|
||||
if (child.stdin?.writable) child.stdin.write(`${JSON.stringify(message)}\n`);
|
||||
};
|
||||
child.on("error", (error) => finish(no(`codex app-server could not start: ${firstLine(error)}`)));
|
||||
child.on("exit", () => finish(no("codex app-server exited before answering")));
|
||||
child.stdin?.on("error", () => finish(no("codex app-server closed its input before answering")));
|
||||
child.on("error", (error) => finish(unread(`codex app-server could not start: ${firstLine(error)}`)));
|
||||
child.on("exit", () => finish(unread("codex app-server exited before answering")));
|
||||
child.stdin?.on("error", () => finish(unread("codex app-server closed its input before answering")));
|
||||
child.stdout?.setEncoding("utf8");
|
||||
child.stdout?.on("data", (chunk: string) => {
|
||||
received += Buffer.byteLength(chunk);
|
||||
if (received > maxOutputBytes) return finish(no("codex app-server answered with more output than expected"));
|
||||
if (received > maxOutputBytes) return finish(unread("codex app-server answered with more output than expected"));
|
||||
buffered += chunk;
|
||||
let newline: number;
|
||||
while ((newline = buffered.indexOf("\n")) >= 0) {
|
||||
@@ -183,7 +193,7 @@ function converse(child: ReturnType<typeof spawn>, cwd: string, deadlineMs: numb
|
||||
try { message = JSON.parse(line); } catch { continue; }
|
||||
// Only responses to our own requests: notifications and server requests carry a method.
|
||||
if (!isRecord(message) || typeof message.id !== "number" || "method" in message) continue;
|
||||
if (message.error !== undefined) return finish(no(`codex app-server returned an error for request ${message.id}`));
|
||||
if (message.error !== undefined) return finish(unread(`codex app-server returned an error for request ${message.id}`));
|
||||
if (message.id === 1) {
|
||||
send({ method: "initialized", params: {} });
|
||||
send({ id: 2, method: "config/read", params: { includeLayers: true, cwd } });
|
||||
@@ -192,7 +202,7 @@ function converse(child: ReturnType<typeof spawn>, cwd: string, deadlineMs: numb
|
||||
}
|
||||
answers.set(message.id, message);
|
||||
if (answers.has(2) && answers.has(3)) {
|
||||
return finish(decideCodexNetworkDefault(answers.get(2)!.result, answers.get(3)!.result));
|
||||
return finish({ ok: true, configRead: answers.get(2)?.result, requirementsRead: answers.get(3)?.result });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -79,10 +79,14 @@ export function codexLegacyPluginTrustPath(configPath: string): string {
|
||||
interface OwnedApproval { schema: 1; plugin: string; contentHash: string; declarations: Record<string, string> }
|
||||
export const ownedCodexApprovalPath = (configPath: string) => path.join(path.dirname(configPath), ".openrig-core-hook-trust.json");
|
||||
|
||||
/** No native baseline is changed. Existing declarations must already be approved; only content approval may advance. */
|
||||
/**
|
||||
* No native baseline is changed. Content approval advances for approved declarations. A declaration changed by a new
|
||||
* shipped bundle is renewed only from OpenRig's own record (#17): every approval must still equal the recorded
|
||||
* declaration and content. `trustedHashes` names the declarations to rewrite; `hashes` the content approvals.
|
||||
*/
|
||||
export function planOwnedCodexContentApproval(input: {
|
||||
configPath: string; content: string; layers: CodexConfigLayerRead[]; shipped: string; installed: string; freshGrant?: boolean;
|
||||
}): { hashes: Record<string, string>; approval: OwnedApproval } | undefined {
|
||||
}): { hashes: Record<string, string>; trustedHashes: Record<string, string>; approval: OwnedApproval } | undefined {
|
||||
try {
|
||||
if (codexPluginContentHash(input.shipped, true) !== codexPluginContentHash(input.installed, true)) return;
|
||||
// The trees just matched byte for byte, so approve the shipped bytes rather than a second read of the cache.
|
||||
@@ -111,26 +115,41 @@ export function planOwnedCodexContentApproval(input: {
|
||||
const states = doc.hooks?.state ?? {};
|
||||
for (const [key, hash] of Object.entries(declarations)) {
|
||||
const state = states[key];
|
||||
if (!state || (state.enabled !== undefined && state.enabled !== true) || state.trusted_hash !== hash
|
||||
if (!state || (state.enabled !== undefined && state.enabled !== true) || typeof state.trusted_hash !== "string"
|
||||
|| Object.keys(state).some(field => !["enabled", "trusted_hash", "trusted_content_hash"].includes(field))
|
||||
|| findTomlTable(input.content.split("\n"), ["hooks", "state", key]) < 0
|
||||
|| docs.some(layer => otherChoice(layer.doc, key, layer.path !== input.configPath))) return;
|
||||
}
|
||||
const approval: OwnedApproval = { schema: 1, plugin: CODEX_CORE_PLUGIN_KEY, contentHash, declarations };
|
||||
const hashes = Object.fromEntries(Object.keys(declarations).map(key => [key, contentHash]));
|
||||
if (input.freshGrant) return { hashes, approval };
|
||||
if (Object.keys(declarations).every(key => states[key].trusted_content_hash === contentHash)) return { hashes: {}, approval };
|
||||
const changed = Object.entries(declarations).filter(([key, hash]) => states[key].trusted_hash !== hash);
|
||||
const parseRecord = (saved: string): OwnedApproval | undefined => {
|
||||
const previous: OwnedApproval = JSON.parse(saved);
|
||||
return previous.schema === 1 && previous.plugin === CODEX_CORE_PLUGIN_KEY && /^sha256:[a-f0-9]{64}$/.test(previous.contentHash)
|
||||
&& Object.keys(previous.declarations).length === 6 ? previous : undefined;
|
||||
};
|
||||
if (changed.length > 0) {
|
||||
// Only OpenRig's own saved record proves these approvals are its earlier grant; the legacy fallback below doesn't.
|
||||
const saved = readRecord(ownedCodexApprovalPath(input.configPath));
|
||||
const previous = saved === undefined ? undefined : parseRecord(saved);
|
||||
if (input.freshGrant || !previous) return;
|
||||
for (const key of Object.keys(declarations)) {
|
||||
if (states[key].trusted_hash !== previous.declarations[key] || states[key].trusted_content_hash !== previous.contentHash) return;
|
||||
}
|
||||
return { hashes, trustedHashes: Object.fromEntries(changed), approval };
|
||||
}
|
||||
if (input.freshGrant) return { hashes, trustedHashes: {}, approval };
|
||||
if (Object.keys(declarations).every(key => states[key].trusted_content_hash === contentHash)) return { hashes: {}, trustedHashes: {}, approval };
|
||||
const baseline = readRecord(codexLegacyPluginTrustPath(input.configPath));
|
||||
if (Object.keys(declarations).every(key => (states[key].trusted_content_hash ?? baseline) === contentHash)) return { hashes, approval };
|
||||
if (Object.keys(declarations).every(key => (states[key].trusted_content_hash ?? baseline) === contentHash)) return { hashes, trustedHashes: {}, approval };
|
||||
const saved = readRecord(ownedCodexApprovalPath(input.configPath));
|
||||
const previous: OwnedApproval = saved === undefined ? { schema: 1, plugin: CODEX_CORE_PLUGIN_KEY,
|
||||
contentHash: LEGACY_CONTENT, declarations: legacyDeclarations } : JSON.parse(saved);
|
||||
if (previous.schema !== 1 || previous.plugin !== CODEX_CORE_PLUGIN_KEY || !/^sha256:[a-f0-9]{64}$/.test(previous.contentHash)
|
||||
|| Object.keys(previous.declarations).length !== 6) return;
|
||||
const previous = saved === undefined ? { schema: 1 as const, plugin: CODEX_CORE_PLUGIN_KEY,
|
||||
contentHash: LEGACY_CONTENT, declarations: legacyDeclarations } : parseRecord(saved);
|
||||
if (!previous) return;
|
||||
for (const [key, hash] of Object.entries(declarations)) {
|
||||
if (previous.declarations[key] !== hash || (states[key].trusted_content_hash ?? baseline) !== previous.contentHash) return;
|
||||
}
|
||||
return { hashes, approval };
|
||||
return { hashes, trustedHashes: {}, approval };
|
||||
} catch { return undefined; } // Unknown ownership or config leaves native review in place.
|
||||
}
|
||||
|
||||
|
||||
@@ -186,139 +186,3 @@ export function readWakeOutcome(recorded: string | null | undefined): WakeOutcom
|
||||
if (recorded.startsWith("failed:")) return at("not-delivered", "terminal");
|
||||
return at("unknown", null);
|
||||
}
|
||||
|
||||
/** A delivery route as the member-connection contract names it. `typed` is OpenRig typing into the member's terminal
|
||||
* (what `WakeRoute` calls `terminal`); `codex-queue` is Codex's own queue command, a route that doesn't type. */
|
||||
export type ConnectionRoute = "typed" | "codex-queue" | "hosted-trigger" | "gateway";
|
||||
|
||||
/** What a connection says about one capability. `unavailable`: the connection has it, but it can't be used for this member
|
||||
* now (a terminal seat with no session recorded as current). `not-applicable`: it means nothing on this route (a dialog check on a webhook).
|
||||
* A client reads an absent key as `unknown`, never as `not-supported`, idle or success. */
|
||||
export type Declared = "supported" | "not-supported" | "unavailable" | "not-applicable" | "unknown";
|
||||
|
||||
/** A connection's declared capabilities, in the design's four groups. Each says what this build of OpenRig can do on the
|
||||
* route, not what the member's program could do. */
|
||||
export interface ConnectionCapabilities {
|
||||
observe: {
|
||||
/** A dialog or picker on the member's screen is read before typing, so a send doesn't answer it. */
|
||||
dialog: Declared;
|
||||
/** A turn's start is correlated to the delivery that caused it. */
|
||||
turnStart: Declared;
|
||||
};
|
||||
control: {
|
||||
/** OpenRig can submit input for the member (type and press Enter). */
|
||||
submit: Declared;
|
||||
};
|
||||
nativeIdentity: {
|
||||
/** The program's own session id is captured. */
|
||||
sessionId: Declared;
|
||||
/** A stopped member can be resumed into its own conversation. */
|
||||
resume: Declared;
|
||||
};
|
||||
continuity: {
|
||||
/** OpenRig runs the member's compaction when its context fills. */
|
||||
managedCompaction: Declared;
|
||||
/** A handover's restore packet is seen leaving the member's input box, not only typed and submitted. */
|
||||
restorePacketConfirmation: Declared;
|
||||
/** A handover can fork the member's conversation. */
|
||||
fork: Declared;
|
||||
};
|
||||
}
|
||||
|
||||
/** One route's declaration. A route that isn't armed is declared but not used: nothing is delivered on it until a
|
||||
* setting arms it. */
|
||||
export interface RouteDeclaration {
|
||||
route: ConnectionRoute;
|
||||
armed: boolean;
|
||||
/** Capabilities by runtime for the typed route (`*` is any other runtime); one set for the others. */
|
||||
capabilities: Record<string, ConnectionCapabilities>;
|
||||
}
|
||||
|
||||
const caps = (dialog: Declared, turnStart: Declared, submit: Declared, sessionId: Declared, resume: Declared,
|
||||
managedCompaction: Declared, restorePacketConfirmation: Declared, fork: Declared): ConnectionCapabilities =>
|
||||
({ observe: { dialog, turnStart }, control: { submit }, nativeIdentity: { sessionId, resume },
|
||||
continuity: { managedCompaction, restorePacketConfirmation, fork } });
|
||||
|
||||
/** What this build declares on each route. Turn starts aren't correlated to deliveries yet on any route. Managed compaction
|
||||
* and restore-packet confirmation read Claude Code's own screen, so other runtimes don't have them. Codex's queue command
|
||||
* is declared and not armed: nothing uses it until a route setting does, and what it would support is unknown until it's built. A hosted member's trigger and a person's
|
||||
* gateway carry no terminal, so the terminal capabilities don't apply to them. */
|
||||
export const ROUTE_DECLARATIONS: readonly RouteDeclaration[] = [
|
||||
{ route: "typed", armed: true, capabilities: {
|
||||
"claude-code": caps("supported", "not-supported", "supported", "supported", "supported", "supported", "supported", "supported"),
|
||||
codex: caps("supported", "not-supported", "supported", "supported", "supported", "not-supported", "not-supported", "supported"),
|
||||
"*": caps("not-supported", "not-supported", "supported", "unknown", "unknown", "not-supported", "not-supported", "unknown"),
|
||||
} },
|
||||
{ route: "codex-queue", armed: false, capabilities: {
|
||||
codex: caps("not-applicable", "unknown", "unknown", "unknown", "unknown", "unknown", "not-applicable", "unknown"),
|
||||
} },
|
||||
{ route: "hosted-trigger", armed: true, capabilities: {
|
||||
"*": caps("not-applicable", "unknown", "not-applicable", "unknown", "unknown", "not-applicable", "not-applicable", "not-applicable"),
|
||||
} },
|
||||
{ route: "gateway", armed: true, capabilities: {
|
||||
"*": caps("not-applicable", "not-applicable", "not-applicable", "not-applicable", "not-applicable", "not-applicable", "not-applicable", "not-applicable"),
|
||||
} },
|
||||
];
|
||||
|
||||
/** The capabilities this build declares for a route and runtime: the runtime's own entry, else the route's `*` entry,
|
||||
* else every capability unknown. */
|
||||
export function declaredCapabilities(route: ConnectionRoute, runtime: string | null | undefined): ConnectionCapabilities {
|
||||
const declared = ROUTE_DECLARATIONS.find((d) => d.route === route)?.capabilities;
|
||||
return (runtime ? declared?.[runtime] : undefined) ?? declared?.["*"] ?? UNKNOWN_CAPABILITIES;
|
||||
}
|
||||
|
||||
const UNKNOWN_CAPABILITIES = caps("unknown", "unknown", "unknown", "unknown", "unknown", "unknown", "unknown", "unknown");
|
||||
|
||||
/** One member's connection as the daemon resolves it: the route it's reached on and its runtime, with that route's
|
||||
* declaration. `unavailable` marks what the route has but this member can't use now. Null route: the address names no
|
||||
* member this daemon can reach, and every capability is unknown. */
|
||||
export interface MemberConnection {
|
||||
member: string;
|
||||
route: ConnectionRoute | null;
|
||||
runtime: string | null;
|
||||
capabilities: ConnectionCapabilities;
|
||||
/** Why the route is null, or why a capability is unavailable. */
|
||||
reason?: string;
|
||||
}
|
||||
// A declaration says what a route can do, never that the member is ready now: `live` below is what OpenRig has recorded
|
||||
// as the seat's current session, not an observed pane or process.
|
||||
|
||||
export function memberConnection(member: string, found: { kind: "person" } | { kind: "hosted" }
|
||||
| { kind: "seat"; runtime: string | null; /** A session recorded as current, not an observed pane. */ live: boolean }
|
||||
| { kind: "none"; reason: string }): MemberConnection {
|
||||
if (found.kind === "person") return { member, route: "gateway", runtime: null, capabilities: declaredCapabilities("gateway", null) };
|
||||
if (found.kind === "hosted") return { member, route: "hosted-trigger", runtime: null, capabilities: declaredCapabilities("hosted-trigger", null) };
|
||||
if (found.kind === "none") return { member, route: null, runtime: null, capabilities: UNKNOWN_CAPABILITIES, reason: found.reason };
|
||||
const declared = declaredCapabilities("typed", found.runtime);
|
||||
if (found.live) return { member, route: "typed", runtime: found.runtime, capabilities: declared };
|
||||
// A seat with no session recorded as current keeps its declaration; what needs its terminal can't be used until it has one.
|
||||
const live = (value: Declared): Declared => value === "supported" ? "unavailable" : value;
|
||||
return { member, route: "typed", runtime: found.runtime, reason: "it has no session recorded as current",
|
||||
capabilities: { ...declared, observe: { dialog: live(declared.observe.dialog), turnStart: declared.observe.turnStart },
|
||||
control: { submit: live(declared.control.submit) } } };
|
||||
}
|
||||
|
||||
/** What a typed send's input reached, as the transport reads it from the send's result (`writtenFact`). */
|
||||
export type WrittenFact = "submitted" | "submit_only" | "text_only" | "text_submit_unknown" | "uncertain" | "none" | "unknown";
|
||||
|
||||
/** What a typed send's own result says happened to it, in the shared words, read from what its input reached (`written`,
|
||||
* the transport's own reading) so the two can't disagree. Submitted is `accepted` (with `renderVerified` when the screen
|
||||
* showed it). Held by a guard is `held`. Text typed without Enter on a send that otherwise succeeded (a prompt answer
|
||||
* sent without one) is `unknown`: whether the prompt took it isn't known. Input that may have landed on a failed send is
|
||||
* `failed-effect-unknown`, and none written is `not-delivered`. Anything else is `unknown`. None of them means the
|
||||
* member read the work. */
|
||||
export function readSendOutcome(result: { ok: boolean; outcome?: string; verified?: boolean }, written: WrittenFact):
|
||||
ReportedFact<DeliveryFact> & { route: "typed"; renderVerified?: true } {
|
||||
const at = (fact: DeliveryFact, extra: { renderVerified?: true } = {}) => ({ fact, reporter: "openrig-observed" as const, route: "typed" as const, ...extra });
|
||||
if (result.outcome === "retained") return at("held");
|
||||
switch (written) {
|
||||
case "submitted":
|
||||
case "submit_only":
|
||||
return result.outcome === "delivered" && result.verified === true ? at("accepted", { renderVerified: true }) : at("accepted");
|
||||
case "text_only": return at(result.ok ? "unknown" : "failed-effect-unknown");
|
||||
case "uncertain":
|
||||
case "text_submit_unknown": return at("failed-effect-unknown");
|
||||
case "none": return at("not-delivered");
|
||||
default: return at("unknown");
|
||||
}
|
||||
}
|
||||
@@ -61,6 +61,8 @@ export interface SlackConnectorConfig {
|
||||
* "off" = reactions are ignored, so an acknowledging emoji costs no agent turn. Not in DEFAULT_CONFIG, like `channelMap`.
|
||||
*/
|
||||
reactions?: SlackReactionsMode;
|
||||
/** Link and media previews on human-row posts; absent defaults to off. */
|
||||
unfurl?: "on" | "off";
|
||||
}
|
||||
|
||||
export const SLACK_REACTIONS_MODES = ["route", "off"] as const;
|
||||
@@ -119,6 +121,9 @@ function validateConfig(cfg: SlackConnectorConfig, opts: { reading?: boolean } =
|
||||
if (!opts.reading && cfg.reactions !== undefined && !SLACK_REACTIONS_MODES.includes(cfg.reactions)) {
|
||||
throw new Error(`reactions must be one of ${SLACK_REACTIONS_MODES.join(", ")} (got ${String(cfg.reactions)})`);
|
||||
}
|
||||
if (!opts.reading && cfg.unfurl !== undefined && cfg.unfurl !== "on" && cfg.unfurl !== "off") {
|
||||
throw new Error(`unfurl must be on or off (got ${String(cfg.unfurl)})`);
|
||||
}
|
||||
}
|
||||
|
||||
export function configPathFor(home?: string): string {
|
||||
@@ -176,6 +181,7 @@ export function staticReadiness(cfg: SlackConnectorConfig, hasBotToken: boolean,
|
||||
{ ok: Boolean(cfg.inboundDestination), label: "inbound-destination",
|
||||
detail: cfg.inboundDestination === INHERIT_INBOUND_DESTINATION ? `${INHERIT_INBOUND_DESTINATION} (the host's default receiving agent)` : cfg.inboundDestination },
|
||||
{ ok: cfg.enabled, label: "enabled", detail: cfg.enabled ? "yes" : "no (run `rig slack enable`)" },
|
||||
{ ok: true, label: "human-row previews", detail: cfg.unfurl === "on" ? "on" : "off" },
|
||||
...channelMapReadiness(cfg),
|
||||
...botInboxReadiness(cfg),
|
||||
...forwardReadiness(cfg),
|
||||
|
||||
@@ -474,6 +474,8 @@ export interface PostChatMessageInput {
|
||||
blocks?: unknown[];
|
||||
/** Thread reply: the PARENT message's ts (never a reply's ts — the affordance discriminator). */
|
||||
thread_ts?: string;
|
||||
unfurl_links?: boolean;
|
||||
unfurl_media?: boolean;
|
||||
}
|
||||
|
||||
export type PostChatMessageResult =
|
||||
@@ -505,6 +507,8 @@ export async function postChatMessage(
|
||||
const body: Record<string, unknown> = { channel: input.channel, text: input.text };
|
||||
if (input.blocks?.length) body.blocks = input.blocks;
|
||||
if (input.thread_ts) body.thread_ts = input.thread_ts;
|
||||
if (input.unfurl_links !== undefined) body.unfurl_links = input.unfurl_links;
|
||||
if (input.unfurl_media !== undefined) body.unfurl_media = input.unfurl_media;
|
||||
let r = await callWebApi("chat.postMessage", token, body, fetchImpl, timeoutMs);
|
||||
if (!r.ok && r.status === 429) {
|
||||
const waitMs = (r.retryAfterSeconds ?? 0) * 1000;
|
||||
|
||||
@@ -41,6 +41,8 @@ export interface SubsystemSlackDeliveryOpts {
|
||||
* (no map) nothing is recorded and the channel is resolved as before. */
|
||||
pinChannel?: boolean;
|
||||
sourceLabel: string; // host/box/rig — from config, never hardcoded (item 7)
|
||||
/** Human-row previews; absent defaults off. */
|
||||
unfurl?: "on" | "off";
|
||||
/** This daemon's machine name, read per post, shown after a seat sender (message.ts `machine`). */
|
||||
machine?: () => string | null;
|
||||
bodyExcerpt?: number;
|
||||
@@ -332,7 +334,8 @@ function deliverSinglePart(opts: SubsystemSlackDeliveryOpts, markEpisode = true)
|
||||
};
|
||||
const postInput = (possibleRepeat = false) => {
|
||||
const shown = render(possibleRepeat, q.stateUnconfirmed === true, q.quietUnreadable === true);
|
||||
return { channel, text: shown.text, blocks: shown.blocks, thread_ts: threadTs };
|
||||
const unfurl = opts.unfurl === "on";
|
||||
return { channel, text: shown.text, blocks: shown.blocks, thread_ts: threadTs, unfurl_links: unfurl, unfurl_media: unfurl };
|
||||
};
|
||||
const payloadHash = () => createHash("sha256").update(JSON.stringify({ channel, text: render().text, blocks: render().blocks, thread_ts: threadTs })).digest("hex");
|
||||
const failurePrefix = `${decision.decisionId}${TRANSPORT_FAILURE_RECEIPT_PREFIX}`;
|
||||
|
||||
@@ -638,6 +638,7 @@ export function buildSlackGatewayWire(opts: SlackWireOpts): GatewayWire {
|
||||
},
|
||||
pinChannel: Boolean(cfg.channelMap?.length),
|
||||
sourceLabel: cfg.sourceLabel,
|
||||
unfurl: cfg.unfurl === "on" ? "on" : "off",
|
||||
// P6: each post names the machine it comes from, the daemon's own host id.
|
||||
machine: () => getSelfHostId(),
|
||||
fetchImpl: opts.fetchImpl,
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import type Database from "better-sqlite3";
|
||||
import { memberConnection, type MemberConnection } from "./connection-contract.js";
|
||||
import { registeredPeople, resolveRegisteredHumanAddress } from "./gateway/human-registry.js";
|
||||
import type { QueueRepository } from "./queue-repository.js";
|
||||
import { resolveGuardTarget } from "./seat-delivery-guard.js";
|
||||
import { isHumanSeatSessionRef, parseSessionName } from "./session-name.js";
|
||||
import { resolveCurrentSessionAddress } from "./session-registry.js";
|
||||
|
||||
/** The connection an address is reached on, as this daemon resolves it: a person (the gateway), a hosted member (its
|
||||
* trigger), else the seat it addresses, read by seat rather than by the newest session row with that name, and live
|
||||
* when a session is recorded as its current one (a record, not an observed pane). A person is one the human registry
|
||||
* resolves, or the reserved terminal person's seat (`human@host`, `human-<x>@kernel|host`); an address shaped like a
|
||||
* person's (`<id>@external`) that the registry doesn't resolve isn't one. A person is resolved before a hosted member
|
||||
* or seat, as the queue does, so when the registry can't be read, any spelling it could resolve to a person (an
|
||||
* `@external` address or a canonical `member@rig`) reads unknown rather than as whatever else has that name. Nobody
|
||||
* registered yet is a readable registry with no one in it. An address none of them has reads every capability
|
||||
* unknown too, with its own reason. */
|
||||
export function resolveMemberConnection(db: Database.Database, queue: Pick<QueueRepository, "humanRegistry" | "isHostedMember"> | undefined,
|
||||
member: string): MemberConnection {
|
||||
const parsed = parseSessionName(member);
|
||||
const terminalPersonSeat = isHumanSeatSessionRef(member) && parsed.kind !== "external";
|
||||
const people = queue ? registeredPeople(queue.humanRegistry()) : null;
|
||||
if (terminalPersonSeat || (people && resolveRegisteredHumanAddress(member, people) !== null)) {
|
||||
return memberConnection(member, { kind: "person" });
|
||||
}
|
||||
if (!people && (parsed.kind === "external" || parsed.kind === "canonical")) {
|
||||
return memberConnection(member, { kind: "none", reason: "the person registry couldn't be read, so whether a person has this address is unknown" });
|
||||
}
|
||||
if (queue?.isHostedMember(member)) return memberConnection(member, { kind: "hosted" });
|
||||
const target = resolveGuardTarget(db, member);
|
||||
if (!target) return memberConnection(member, { kind: "none", reason: "no seat, hosted member or registered person has this address on this daemon" });
|
||||
const node = db.prepare("SELECT runtime FROM nodes WHERE id = ?").get(target.nodeId) as { runtime: string | null } | undefined;
|
||||
return memberConnection(member, { kind: "seat", runtime: node?.runtime ?? null,
|
||||
live: resolveCurrentSessionAddress(db, member)?.nodeId === target.nodeId });
|
||||
}
|
||||
@@ -110,9 +110,12 @@ export function buildCodexResumeDisplay(
|
||||
const profile = input.codexConfigProfile ?? null;
|
||||
const profileArg = profile ? ` -p ${shellQuote(profile)}` : "";
|
||||
const effectivePosture = input.resolvedPosture ?? "floor";
|
||||
const envelope = input.codexPermissions ? codexMemberEnvelope(input.codexPermissions) : undefined;
|
||||
const permissions = input.codexPermissions;
|
||||
const hasFilesystemPolicy = permissions !== undefined && "filesystem" in permissions;
|
||||
const envelope = permissions && !("filesystem" in permissions) ? codexMemberEnvelope(permissions) : undefined;
|
||||
// Derive displayed flags from the same three inputs adapters/codex-resume.ts uses (member permission envelope,
|
||||
// resolved posture with an empty env so ambient OPENRIG_YOLO never leaks, and operationalLaunchArg).
|
||||
// A filesystem choice currently uses the posture fallback here; label that omission below.
|
||||
const posture = envelope ? profileArg + codexEnvelopeArgs(envelope) : codexPostureArg(profileArg, {}, effectivePosture);
|
||||
const postureArg = posture + operationalLaunchArg(
|
||||
"codex",
|
||||
@@ -163,6 +166,17 @@ export function buildCodexResumeDisplay(
|
||||
&& recorded.state === "observed"
|
||||
&& recorded.value !== null;
|
||||
|
||||
if (hasFilesystemPolicy) {
|
||||
return {
|
||||
command,
|
||||
status: hasObservedRecord ? "recorded_uncertain" : "no_recorded_launch",
|
||||
label: composeCodexResumeLabel(
|
||||
`shown command uses posture fallback ${postureArg.trim()}; does not carry the agent's filesystem policy (managed resume carries it)`,
|
||||
hasLaunchWrapper,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
if (!envelope && input.emptySavedPosture) {
|
||||
const fallbackClause = `saved posture empty, showing fallback ${currentFlags} (managed resume posture unknown)`;
|
||||
if (!hasObservedRecord) {
|
||||
|
||||
@@ -4,8 +4,7 @@
|
||||
import type Database from "better-sqlite3";
|
||||
import { NativePermissionStore, type StoredNativePermissionSelection } from "./native-permission-store.js";
|
||||
import { claudePostureFlag, codexPostureArg, planModelAliasNotice, yoloEnabled } from "../adapters/yolo-mode.js";
|
||||
import { codexEnvelopeArgs } from "./codex-rebuild-permissions.js";
|
||||
import { codexMemberEnvelope } from "./codex-member-permissions.js";
|
||||
import { codexMemberLaunch } from "./codex-member-permissions.js";
|
||||
import { KERNEL_CLAUDE_ALLOW, TEAM_CLAUDE_ALLOW, TEAM_CLAUDE_ASK } from "../adapters/kernel-authority.js";
|
||||
import { RigRepository } from "./rig-repository.js";
|
||||
import type { NodeBinding } from "./runtime-adapter.js";
|
||||
@@ -94,7 +93,7 @@ export function planPermissionAccount(db: Database.Database, nodeId: string, sea
|
||||
// A Codex seat's envelope replaces the posture decision with its own flags, as the launch does.
|
||||
const envelope = runtime === "codex" ? planned.codexPermissions : undefined;
|
||||
const nativeArgument = runtime === "claude-code" ? claudePostureFlag(env, posture, mode)
|
||||
: envelope ? `${profile ? ` -p ${profile}` : ""}${codexEnvelopeArgs(codexMemberEnvelope(envelope))}`.trim()
|
||||
: envelope ? `${profile ? ` -p ${profile}` : ""}${codexMemberLaunch(envelope).args}`.trim()
|
||||
: codexPostureArg(profile ? ` -p ${profile}` : "", env, posture).trim();
|
||||
const openRigAdds: PermissionAccount["openRigAdds"] = { claudeAllow: [], claudeAsk: [], notes: [] };
|
||||
const unknown = [NOT_READ, UNVERIFIED,
|
||||
@@ -119,7 +118,11 @@ export function planPermissionAccount(db: Database.Database, nodeId: string, sea
|
||||
controls.push(`rig seat set-permissions ${seat} --rules <file.json> --reason "<why>"`);
|
||||
}
|
||||
if (envelope) {
|
||||
openRigAdds.notes.push(envelope.sandbox === "workspace-write"
|
||||
if ("filesystem" in envelope) openRigAdds.notes.push(
|
||||
"Invocation-local filesystem policy; OpenRig adds no writable directories or network grant. No shared policy file is written.",
|
||||
"Each launch reads native configuration and refuses a legacy sandbox or a merged policy mismatch. A named codex_config_profile is unsupported with this choice.",
|
||||
"This status describes the saved plan; native enforcement is not observed here.");
|
||||
else openRigAdds.notes.push(envelope.sandbox === "workspace-write"
|
||||
? "Extra writable roots for OpenRig's queue state, and git metadata folders on a fresh launch, beside the envelope's own roots."
|
||||
: "No extra writable roots: the envelope is read-only.",
|
||||
`Network access ${envelope.sandbox === "workspace-write" && envelope.network_access ? "on" : "off"}, as the envelope states; OpenRig adds no network setting of its own.`,
|
||||
|
||||
@@ -268,7 +268,8 @@ export function diagnoseRuntimePosture(input: {
|
||||
const launchArguments = applied?.state === "observed" && applied.runtime === input.runtime
|
||||
&& (input.runtime === "claude-code" || input.runtime === "codex");
|
||||
const enforcement = launchArguments
|
||||
? unknownEnforcement(applied.axis, applied.value, null, "native_permission_effect_unverified")
|
||||
? unknownEnforcement(applied.axis, applied.value, null,
|
||||
applied.runtime === "codex" && applied.reason?.startsWith("policy not verified:") ? applied.reason : "native_permission_effect_unverified")
|
||||
: input.runtime === "claude-code"
|
||||
? inspectClaude(input.cwd, input.applied, input.fs)
|
||||
: inspectLaunchBoundRuntime(input.runtime, input.applied);
|
||||
|
||||
@@ -520,14 +520,13 @@ export interface QueueUpdateInput {
|
||||
wakeMessage?: string;
|
||||
/**
|
||||
* OPR.0.4.4.19 FR-6 — park-time inputs. summary + evidence_ref are
|
||||
* updatable AT THE PARK MOMENT (state=blocked with a human-seat blocker),
|
||||
* not create-only: `rig queue block --summary --evidence-ref` persists
|
||||
* them onto the EXISTING item so the attention query + Packet 2 read
|
||||
* them. A done close also persists evidence_ref, so a finished row carries
|
||||
* its artifact. OPR.0.5.1 slice-51-06 D2: supplying either where it can't
|
||||
* be stored is REJECTED (QueueRepositoryError "summary_evidence_not_persistable")
|
||||
* before any mutation — not silently ignored — so a caller never believes
|
||||
* unpersistable metadata was saved.
|
||||
* updatable with any state change, not create-only: `rig queue block
|
||||
* --summary --evidence-ref` persists them onto the EXISTING item so the
|
||||
* attention query + Packet 2 read them, and a done close leaves its
|
||||
* artifact on the finished row. A human-seat park still requires them.
|
||||
* A blank value is not stored (it would erase the row's subject or
|
||||
* evidence link); the update route reports any value
|
||||
* the stored row doesn't carry, so a caller never believes it was saved.
|
||||
*/
|
||||
summary?: string | null;
|
||||
evidenceRef?: string | null;
|
||||
@@ -2579,7 +2578,7 @@ export class QueueRepository {
|
||||
}
|
||||
|
||||
/** The registered person an address names, so an ask back reaches them; null for anyone else, the unattributed
|
||||
* terminal actor included (it's a person address, but nothing is delivered there). */
|
||||
* terminal actor included (a person address, but a row there asks no one; it waits on Steering and in the Feed, and OpenRig reports it as undeliverable). */
|
||||
reachablePerson(address: string | null | undefined): string | null {
|
||||
if (!address || address === UNATTRIBUTED_ACTOR) return null;
|
||||
const registry = this.loadHumanRegistryFn();
|
||||
@@ -3455,6 +3454,7 @@ export class QueueRepository {
|
||||
}
|
||||
const hasNote = typeof input.transitionNote === "string" && input.transitionNote.trim().length > 0;
|
||||
const hasValidSummary = typeof input.summary === "string" && input.summary.trim().length > 0;
|
||||
const hasValidEvidenceRef = typeof input.evidenceRef === "string" && input.evidenceRef.trim().length > 0;
|
||||
const isGuardedTerminal = (["done", "canceled", "handed-off"] as const).includes(
|
||||
qitem.state as "done" | "canceled" | "handed-off",
|
||||
);
|
||||
@@ -3664,35 +3664,15 @@ export class QueueRepository {
|
||||
throw new QueueRepositoryError("invalid_human_notification", "An informational delivery cannot become a human approval park; author a separate decision request.");
|
||||
}
|
||||
// A park on a person by any address (a legacy human seat, or a registered person's own address or alias) keeps the
|
||||
// summary and evidence it names. validateHumanPark still requires them only for the legacy human-seat form.
|
||||
// summary and evidence it names, or the row's own where it names a blank one. validateHumanPark still requires them
|
||||
// only for the legacy human-seat form.
|
||||
const isHumanPark = input.state === "blocked" && !!effectiveBlockedOn && this.isPersonAddress(effectiveBlockedOn);
|
||||
// A done close can also store the artifact the work produced, so the finished row carries its link.
|
||||
const isDoneClose = input.state === "done";
|
||||
// OPR.0.5.1 slice-51-06 D2 refused the whole transition when summary/evidence_ref came with a state it
|
||||
// didn't store them for, so finished work could stay pending over optional metadata. A state change now
|
||||
// stores them (below), except a blank value; the route reports what wasn't stored.
|
||||
|
||||
// OPR.0.5.1 slice-51-06 D2 — summary/evidence_ref are persist-able ONLY at a human-seat park
|
||||
// (see the FR-6 note below). Silently ignoring them on any other transition is a data-loss trap
|
||||
// (the operator believes the metadata was saved). HARD-REJECT before ANY UPDATE/log/event so the
|
||||
// caller learns immediately and nothing is half-applied. null/undefined = absent (allowed);
|
||||
// empty string = present (a deliberate value → rejected on a non-park transition).
|
||||
if (!isHumanPark) {
|
||||
const invalidFields: Array<"summary" | "evidenceRef"> = [];
|
||||
if (input.summary != null) invalidFields.push("summary");
|
||||
if (input.evidenceRef != null && !isDoneClose) invalidFields.push("evidenceRef");
|
||||
if (invalidFields.length > 0) {
|
||||
const flags = invalidFields.map((f) => (f === "summary" ? "--summary" : "--evidence-ref")).join(" / ");
|
||||
const where = invalidFields.map((f) => f === "summary"
|
||||
? "summary persists on a human-seat park, or on its own (rig queue update <id> --summary … with no --state)"
|
||||
: "evidenceRef persists on a human-seat park or a done close").join("; ");
|
||||
throw new QueueRepositoryError(
|
||||
"summary_evidence_not_persistable",
|
||||
`${where}; the '${input.state}' transition cannot store ${invalidFields.length > 1 ? "them" : "it"}. Remove ${flags}, or use one of those.`,
|
||||
{ invalidFields },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// SWEEP-a (shape f2576102) — closure/blocked-field COHERENCE, beside the reference
|
||||
// reject above: an incoherent field must never silently persist (worse than a drop —
|
||||
// SWEEP-a (shape f2576102) — closure/blocked-field COHERENCE: an incoherent
|
||||
// field must never silently persist (worse than a drop —
|
||||
// the COALESCE below would write it). Admits-map, derived from LIVE schema use:
|
||||
// closure_reason/closure_target → state "done", OR the PARK-RECORD form
|
||||
// (state "blocked" with closureReason "blocked_on" — the workflow gate/park
|
||||
@@ -3770,8 +3750,8 @@ export class QueueRepository {
|
||||
let effectiveSummary = qitem.summary;
|
||||
let effectiveEvidenceRef = qitem.evidenceRef;
|
||||
if (isHumanPark) {
|
||||
effectiveSummary = input.summary ?? qitem.summary;
|
||||
effectiveEvidenceRef = input.evidenceRef ?? qitem.evidenceRef;
|
||||
effectiveSummary = hasValidSummary ? input.summary! : qitem.summary;
|
||||
effectiveEvidenceRef = hasValidEvidenceRef ? input.evidenceRef! : qitem.evidenceRef;
|
||||
const park = validateHumanPark({
|
||||
blockedOn: effectiveBlockedOn,
|
||||
summary: effectiveSummary,
|
||||
@@ -3899,15 +3879,13 @@ export class QueueRepository {
|
||||
input.qitemId
|
||||
);
|
||||
|
||||
// FR-6: park-time summary/evidence_ref are PERSISTED onto the existing
|
||||
// item (not merely validated-then-dropped) — visible to the attention
|
||||
// query and to Packet 2. A done close writes evidence_ref the same way.
|
||||
if (isHumanPark) {
|
||||
this.persistSummary(input.qitemId, input.summary ?? null);
|
||||
this.persistEvidenceRef(input.qitemId, input.evidenceRef ?? null);
|
||||
} else if (isDoneClose) {
|
||||
this.persistEvidenceRef(input.qitemId, input.evidenceRef ?? null);
|
||||
}
|
||||
// FR-6: summary/evidence_ref are PERSISTED onto the existing item (not
|
||||
// merely validated-then-dropped) — visible to the attention query, to
|
||||
// Packet 2 and to every reader of the row. Only non-blank values are
|
||||
// stored, on a park on a person too: a blank one would erase the row's
|
||||
// subject or evidence link, and the route reports it as not stored.
|
||||
if (hasValidSummary) this.persistSummary(input.qitemId, input.summary!);
|
||||
if (hasValidEvidenceRef) this.persistEvidenceRef(input.qitemId, input.evidenceRef!);
|
||||
|
||||
const transition = this.transitionLog.append({
|
||||
qitemId: input.qitemId,
|
||||
@@ -3991,9 +3969,9 @@ export class QueueRepository {
|
||||
closureReason: validation.closureReason ?? null,
|
||||
closureTarget: validation.closureTarget ?? null,
|
||||
actorSession: input.actorSession,
|
||||
// FR-1 × FR-6: the event carries the summary as of THIS mutation
|
||||
// FR-1 × FR-6: the event carries the summary as stored by THIS mutation
|
||||
// (park-time summary included) so surfaces refresh without a fetch.
|
||||
summary: effectiveSummary ?? null,
|
||||
summary: this.getById(input.qitemId)?.summary ?? null,
|
||||
});
|
||||
return { persistedEvent, persistedEvents: [...dependentEvents, persistedEvent] };
|
||||
}
|
||||
@@ -4560,9 +4538,11 @@ export class QueueRepository {
|
||||
}
|
||||
|
||||
/** A park's current question: its latest human-required transition, and that notification's final post receipt, if any. */
|
||||
/** The opaque revision of what a person decides on (#2446): the question (body, intent, questions) and its decision state
|
||||
* (open, blocked or terminal; who it's addressed to or parked on; its answers, a decision made for them, the current park,
|
||||
* and the replies returned). A label, a wake, a claim or a note on a park doesn't change it; a new park does, on any blocker. */
|
||||
/** The opaque revision of what a person decides on (#2446): the question (body, intent, questions, and the evidence it
|
||||
* points to, when it has any) and its decision state (open, blocked or terminal; who it's addressed to or parked on; its
|
||||
* answers, a decision made for them, the current park, and the replies returned). A label, a wake, a claim or a note on a
|
||||
* park doesn't change it; a new park does, on any blocker, and so does a new evidence pointer. A row with no evidence
|
||||
* keeps the revision it had before evidence counted. */
|
||||
decisionRevision(item: QueueItem, opts?: DecisionRevisionOptions): string {
|
||||
const phase = item.state === "blocked" ? "blocked" : item.state === "pending" || item.state === "in-progress" ? "open" : item.state;
|
||||
const excludeOp =
|
||||
@@ -4589,7 +4569,8 @@ export class QueueRepository {
|
||||
if (transitions[i]!.state === "blocked" && transitions[i - 1]?.state !== "blocked") parkEntry = transitions[i]!.transitionId;
|
||||
}
|
||||
const decision = [item.body, item.humanIntent ?? null, item.humanQuestions ?? null, phase, item.destinationSession, item.blockedOn,
|
||||
item.humanAnswers ?? null, item.delegatedDecision ?? null, this.currentHumanRequiredEpisode(item.qitemId)?.key ?? null, parkEntry, replies];
|
||||
item.humanAnswers ?? null, item.delegatedDecision ?? null, this.currentHumanRequiredEpisode(item.qitemId)?.key ?? null, parkEntry, replies,
|
||||
...(item.evidenceRef ? [item.evidenceRef] : [])];
|
||||
return `dr1-${createHash("sha256").update(JSON.stringify(decision)).digest("hex").slice(0, 24)}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ export function terminalAnswerMeaning(unattributed: string): string {
|
||||
* which reaches them where they answer. `asked` is null when no registered person resolves: removed since the ask, an
|
||||
* unreadable registry, or an ask to the unattributed actor itself. What to do then is this one sentence. */
|
||||
export function askBackRoute(asked: string | null, unattributed: string, request: string): string {
|
||||
const nowhere = `Don't write to ${unattributed}: nothing is delivered there.`;
|
||||
const nowhere = `A row to ${unattributed} names no person: it asks no one, waits on Steering and in the Feed, and OpenRig reports it as undeliverable, so don't ask them back there.`;
|
||||
if (asked) {
|
||||
return `If their answer is unclear or conditional, ask them back with an ask to ${asked} that names ${request}: `
|
||||
+ `rig queue create --destination ${asked} --summary "<your question>" --body-file <file>. It reaches them where they answer (the Feed, Steering, and Slack when it's connected). ${nowhere}`;
|
||||
|
||||
@@ -148,8 +148,9 @@ export function assessCurrentStateRehydrateEligibility(
|
||||
typeof session.resume_token === "string" && session.resume_token.length > 0
|
||||
);
|
||||
|
||||
if (node.podId && !hasStartupContext) {
|
||||
blockers.push(`node ${node.logicalId} is pod-aware but has no persisted startup context`);
|
||||
// A resume token is enough for a pod-aware seat too: restore resumes it with an empty plan and names the gap.
|
||||
if (node.podId && !hasStartupContext && !hasResumeToken) {
|
||||
blockers.push(`node ${node.logicalId} is pod-aware but has no persisted startup context or resume token`);
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -176,6 +176,7 @@ export interface RestoreCheckOpts {
|
||||
// --- Deps (framework-free per ADR-0001; reads from existing projections per ADR-0002) ---
|
||||
|
||||
export interface NodeInventoryEntry {
|
||||
codexConfigProfile?: string | null;
|
||||
nodeId?: string | null;
|
||||
rigId: string;
|
||||
rigName: string;
|
||||
@@ -192,6 +193,16 @@ export interface NodeInventoryEntry {
|
||||
tmuxAttachCommand: string | null;
|
||||
latestError: string | null;
|
||||
cwd?: string | null;
|
||||
/** The seat's recorded restore choice and resume token (the inventory carries them). */
|
||||
restorePolicy?: string | null;
|
||||
resumeType?: string | null;
|
||||
resumeToken?: string | null;
|
||||
}
|
||||
|
||||
/** The restore's own resume rule: a seat with a resume token, a resume type and the resume policy resumes. */
|
||||
function seatResumes(node: NodeInventoryEntry): boolean {
|
||||
return !!node.resumeToken && !!node.resumeType && node.resumeType !== "none" && node.runtime !== "terminal"
|
||||
&& (node.restorePolicy ?? "resume_if_possible") === "resume_if_possible";
|
||||
}
|
||||
|
||||
export interface RestoreCheckDeps {
|
||||
@@ -365,7 +376,7 @@ export class RestoreCheckService {
|
||||
// are not skipping (full, --ready/includeReady, or a non-ready seat).
|
||||
const omitReadyDetail = opts.compact && !opts.includeReady && readinessCheck.status === "green";
|
||||
|
||||
const startupContextCheck = this.checkStartupContext(node);
|
||||
const startupContextCheck = this.checkStartupContext(node, rig.name);
|
||||
if ("unknownChecks" in startupContextCheck) {
|
||||
return this.buildUnknown([
|
||||
...checks,
|
||||
@@ -455,6 +466,8 @@ export class RestoreCheckService {
|
||||
fsOps: { exists: this.deps.exists },
|
||||
servicesRecord: input.servicesRecord,
|
||||
currentRuntimes: Object.fromEntries(inventory.map((current) => [current.logicalId, current.runtime])),
|
||||
currentCodexProfiles: Object.fromEntries(inventory.filter((current) => current.codexConfigProfile !== undefined)
|
||||
.map((current) => [current.logicalId, current.codexConfigProfile!])),
|
||||
});
|
||||
const { blockers, warnings } = validation;
|
||||
return {
|
||||
@@ -897,7 +910,7 @@ export class RestoreCheckService {
|
||||
};
|
||||
}
|
||||
|
||||
private checkStartupContext(node: NodeInventoryEntry): { check: CheckEntry } | { unknownChecks: CheckEntry[] } {
|
||||
private checkStartupContext(node: NodeInventoryEntry, rigName: string): { check: CheckEntry } | { unknownChecks: CheckEntry[] } {
|
||||
const session = node.canonicalSessionName ?? node.logicalId;
|
||||
const check = `seat.${session}.startup-context`;
|
||||
const runningReady = node.sessionStatus === "running" && node.startupStatus === "ready";
|
||||
@@ -908,6 +921,7 @@ export class RestoreCheckService {
|
||||
check,
|
||||
runningReady,
|
||||
`Startup context cannot be inspected because node id is missing for ${session}`,
|
||||
rigName,
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -925,9 +939,26 @@ export class RestoreCheckService {
|
||||
}],
|
||||
};
|
||||
case "missing":
|
||||
// A seat that only ever resumed or was attached has a resume token and no saved startup context. Restore tries its
|
||||
// saved conversation without replaying a saved startup plan, as on any resume (a resume replays no startup context).
|
||||
// A pod-aware seat's restore names the gap; a legacy seat's resume path is unchanged and names none.
|
||||
if (seatResumes(node)) {
|
||||
return {
|
||||
check: {
|
||||
check,
|
||||
status: "yellow",
|
||||
evidence: `${probe.evidence}. Restore tries ${session}'s saved conversation without replaying a saved startup plan${node.podId ? ", and names this gap" : ""}.`,
|
||||
remediation: "No startup-context repair is needed to restore it.",
|
||||
remediationSafe: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
check: this.buildStartupContextAvailabilityCheck(check, runningReady, probe.evidence, rigName),
|
||||
};
|
||||
case "malformed":
|
||||
return {
|
||||
check: this.buildStartupContextAvailabilityCheck(check, runningReady, probe.evidence),
|
||||
check: this.buildStartupContextAvailabilityCheck(check, runningReady, probe.evidence, rigName),
|
||||
};
|
||||
case "ok":
|
||||
break;
|
||||
@@ -1008,12 +1039,14 @@ export class RestoreCheckService {
|
||||
check: string,
|
||||
runningReady: boolean,
|
||||
evidence: string,
|
||||
rigName: string,
|
||||
): CheckEntry {
|
||||
return {
|
||||
check,
|
||||
status: runningReady ? "yellow" : "red",
|
||||
evidence,
|
||||
remediation: "Recreate the seat startup context from the rig or agent spec before trusting replay inputs",
|
||||
// A fresh seat launch reads the saved startup context and refuses without one, so it isn't offered here.
|
||||
remediation: `No command records startup context for this seat yet. To see what restore would do for it, preview with: rig up ${shellQuote(rigName)} --existing --plan (read-only; it records nothing).`,
|
||||
remediationSafe: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -51,6 +51,7 @@ import type {
|
||||
Session,
|
||||
Checkpoint,
|
||||
RestoreSnapshotSelection,
|
||||
NodeStartupSnapshot,
|
||||
} from "./types.js";
|
||||
import { AppliedLaunchObservationStore } from "./applied-launch-observation-store.js";
|
||||
import { isShellForeground } from "./shell-classifier.js";
|
||||
@@ -440,6 +441,9 @@ export class RestoreOrchestrator {
|
||||
servicesRecord: this.rigRepo.getServicesRecord(rigId),
|
||||
freshLogicalIds: opts?.freshLogicalIds,
|
||||
currentRuntimes: Object.fromEntries((this.rigRepo.getRig(rigId)?.nodes ?? []).map((current) => [current.logicalId, current.runtime])),
|
||||
currentCodexProfiles: Object.fromEntries((this.rigRepo.getRig(rigId)?.nodes ?? [])
|
||||
.filter((current) => current.codexConfigProfile !== undefined)
|
||||
.map((current) => [current.logicalId, current.codexConfigProfile!])),
|
||||
});
|
||||
const topology = resolveSnapshotRestoreTopology(snapshot.data);
|
||||
// A required startup file that is missing holds only its own seat. That seat isn't launched, because it would start
|
||||
@@ -1822,7 +1826,8 @@ export class RestoreOrchestrator {
|
||||
// runtime and write Claude hooks into another agent's working folder
|
||||
// (with a saved context, the compatibility gate already stops that
|
||||
// mismatch), and a pod-aware agent must get no write from this recovery
|
||||
// at all — it still ends at the "Harness not started" gate, unchanged.
|
||||
// at all. With no saved context and a resume token, restore tries its resume
|
||||
// on an empty plan (replayCtx below), still without this recovery.
|
||||
const activityAdapter = opts?.adapters?.["claude-code"];
|
||||
const recoveryRuntime = startupCtx?.runtime
|
||||
?? (!isPodAware && liveRuntime === node.runtime ? node.runtime : null);
|
||||
@@ -2044,6 +2049,20 @@ export class RestoreOrchestrator {
|
||||
const replayContained = resumeRequested && !!resumeToken;
|
||||
const startupRuntime = startupCtx?.runtime ?? node.runtime ?? null;
|
||||
const startupAdapter = seatAdapter(opts?.adapters, startupRuntime, session?.communityHarness);
|
||||
// A seat that only ever resumed or was attached (attach, adopt, reconcile-session, a set resume token) has a resume
|
||||
// token but no saved startup context. A resume replays none anyway (replayContained), so restore tries the resume
|
||||
// with an empty plan and names the gap, rather than stopping on data the resume doesn't use. Guidance, activity hooks
|
||||
// and the guidance record read the saved context only, so no guidance is put back and no startup context is written
|
||||
// for this seat; the adapter's ordinary bootstrap and the seat's existing skill restoration still run, as on any resume.
|
||||
const resumeWithoutContext = isPodAware && !startupCtx && replayContained && startupRuntime !== null && startupRuntime !== "terminal";
|
||||
// A fresh seat launch reads the saved startup context and refuses without one, so a rollback names none for this seat.
|
||||
const noContextFresh = "This seat has no saved startup context, and no command records one for it yet, so no fresh start is offered here.";
|
||||
const replayCtx: NodeStartupSnapshot | null = startupCtx
|
||||
?? (resumeWithoutContext ? { runtime: startupRuntime!, projectionEntries: [], resolvedStartupFiles: [], startupActions: [] } : null);
|
||||
if (resumeWithoutContext && startupAdapter && launchResult) {
|
||||
warnings?.push(`Restore: ${node.logicalId}: no saved startup context, so restore tries its saved conversation without replaying a saved startup plan.`);
|
||||
activityHookGaps?.push("startup_context: no saved startup context; restore tried the saved conversation without replaying a saved startup plan.");
|
||||
}
|
||||
// New compute has no retained context filesystem. Restore the saved file selection, never conversation actions.
|
||||
const restoreEnvironmentContext = replayContained && !!startupAdapter?.environment && !!data.environmentBindingsByNode?.[node.id];
|
||||
|
||||
@@ -2056,13 +2075,14 @@ export class RestoreOrchestrator {
|
||||
&& baseStatus !== "resumed"
|
||||
&& startupRuntime !== null
|
||||
&& startupRuntime !== "terminal"
|
||||
&& (!startupCtx || !startupAdapter)
|
||||
&& (!replayCtx || !startupAdapter)
|
||||
) {
|
||||
// A deliberate fresh launch with no captured startup context is the
|
||||
// never-occupied-seat case from #49. The restore launcher has already
|
||||
// created a shell, so remove that provisional session before handing the
|
||||
// seat to the normal recipe-backed launch path. Resume requests stay on
|
||||
// the fail-closed path below: no durable context means no safe resume.
|
||||
// seat to the normal recipe-backed launch path. A resume with a token
|
||||
// goes on with an empty plan (replayCtx above); a resume without one stays
|
||||
// on the fail-closed path below: no durable context means no safe resume.
|
||||
if (!startupCtx && !resumeRequested && this.freshLaunch) {
|
||||
// Keep the usable provisional shell when the callback exists but its
|
||||
// recipe/member inputs are unavailable. A callback being present alone
|
||||
@@ -2099,23 +2119,23 @@ export class RestoreOrchestrator {
|
||||
};
|
||||
}
|
||||
}
|
||||
const cause = startupCtx ? `no ${startupRuntime} runtime adapter` : "no startup context";
|
||||
const cause = replayCtx ? `no ${startupRuntime} runtime adapter` : "no startup context";
|
||||
const error = `Harness not started: ${cause} for ${node.logicalId}.`;
|
||||
warnings?.push(`Restore: ${error}`);
|
||||
return { nodeId: node.id, logicalId: node.logicalId, status: "attention_required", error };
|
||||
}
|
||||
|
||||
// Attempt restore-safe startup replay if context available
|
||||
if (data.nodeStartupContext && opts?.adapters && launchResult) {
|
||||
if (startupCtx) {
|
||||
const adapter = seatAdapter(opts.adapters, startupCtx.runtime, session?.communityHarness);
|
||||
if ((data.nodeStartupContext || replayCtx) && opts?.adapters && launchResult) {
|
||||
if (replayCtx) {
|
||||
const adapter = seatAdapter(opts.adapters, replayCtx.runtime, session?.communityHarness);
|
||||
if (adapter) {
|
||||
// Prefilter: check which files/entries still exist
|
||||
const existsFn = opts.fsOps?.exists ?? (() => true);
|
||||
const sourceEntries = replayContained && !restoreEnvironmentContext ? [] : startupCtx.projectionEntries.map((e) => reanchorShippedProjectionEntry(e, undefined, existsFn));
|
||||
const sourceEntries = replayContained && !restoreEnvironmentContext ? [] : replayCtx.projectionEntries.map((e) => reanchorShippedProjectionEntry(e, undefined, existsFn));
|
||||
// #261: recognized built-in startup files follow the running install.
|
||||
const sourceFiles = replayContained && !restoreEnvironmentContext ? launchGuidance ?? [] : withContextEntryFloor(startupCtx.resolvedStartupFiles.map((f) => reanchorBuiltinStartupFile(f, undefined, undefined, existsFn)));
|
||||
const sourceActions = replayContained ? [] : startupCtx.startupActions;
|
||||
const sourceFiles = replayContained && !restoreEnvironmentContext ? launchGuidance ?? [] : withContextEntryFloor(replayCtx.resolvedStartupFiles.map((f) => reanchorBuiltinStartupFile(f, undefined, undefined, existsFn)));
|
||||
const sourceActions = replayContained ? [] : replayCtx.startupActions;
|
||||
const filteredEntries = sourceEntries.filter((e) => {
|
||||
if (!existsFn(e.absolutePath)) {
|
||||
warnings?.push(`Restore: missing projection entry ${e.absolutePath} (skipped)`);
|
||||
@@ -2153,7 +2173,7 @@ export class RestoreOrchestrator {
|
||||
// it is, an edited one is named, and a missing one whose recorded source is gone or has changed is not put back
|
||||
// with today's bytes. Only the rest is projected or installed. Nothing is re-resolved from today's spec. Native
|
||||
// resume replays nothing (sourceEntries is empty). The whole selection stays in the saved startup context.
|
||||
const seatSkills = (startupCtx.runtime === "claude-code" || startupCtx.runtime === "codex") && !replayContained ? seatSkillPathsForNode(this.db, node.id) : undefined;
|
||||
const seatSkills = (replayCtx.runtime === "claude-code" || replayCtx.runtime === "codex") && !replayContained ? seatSkillPathsForNode(this.db, node.id) : undefined;
|
||||
let replaySkip: { entryIds: Set<string>; files: Set<string> } | undefined;
|
||||
if (seatSkills) {
|
||||
const replay = seatSkillReplay({ entries: filteredEntries, files: filteredFiles, paths: seatSkills,
|
||||
@@ -2164,7 +2184,7 @@ export class RestoreOrchestrator {
|
||||
|
||||
// Build fresh projection plan (all safe_projection; replaySkip says which seat skills are left alone)
|
||||
const plan: import("./projection-planner.js").ProjectionPlan = {
|
||||
runtime: startupCtx.runtime,
|
||||
runtime: replayCtx.runtime,
|
||||
cwd: launchCwd,
|
||||
entries: filteredEntries.map((e) => ({
|
||||
...e,
|
||||
@@ -2181,7 +2201,7 @@ export class RestoreOrchestrator {
|
||||
const binding = {
|
||||
...launchResult.binding,
|
||||
// #875: the guidance file this seat's launch recorded; an older snapshot recorded none, so its file stays the rule's.
|
||||
guidanceFile: startupCtx.guidanceFile ?? null,
|
||||
guidanceFile: replayCtx.guidanceFile ?? null,
|
||||
// #3039: the resumed launch carries the guidance chosen above, so startup doesn't ask again and the adapter queues it.
|
||||
...(launchGuidance ? { guidanceLaunchInstructions: true as const } : {}),
|
||||
...(data.environmentBindingsByNode?.[node.id] ? { environmentRestore: data.environmentBindingsByNode[node.id] } : {}),
|
||||
@@ -2251,7 +2271,9 @@ export class RestoreOrchestrator {
|
||||
nodeId: node.id,
|
||||
logicalId: node.logicalId,
|
||||
status: "awaiting-decision",
|
||||
error: `Original session unresumable: resume attempted but the runtime reported fresh continuity. The blank session was rolled back; no session is running. If that degradation is acceptable, start only this seat fresh: ${this.freshSeatCommand(rigId, data, node.logicalId)}.`,
|
||||
error: resumeWithoutContext
|
||||
? `Original session unresumable: resume attempted but the runtime reported fresh continuity. The blank session was rolled back; no session is running. ${noContextFresh}`
|
||||
: `Original session unresumable: resume attempted but the runtime reported fresh continuity. The blank session was rolled back; no session is running. If that degradation is acceptable, start only this seat fresh: ${this.freshSeatCommand(rigId, data, node.logicalId)}.`,
|
||||
};
|
||||
}
|
||||
const finalStatus = (isPodAware && resumeRequested)
|
||||
@@ -2297,7 +2319,9 @@ export class RestoreOrchestrator {
|
||||
nodeId: node.id,
|
||||
logicalId: node.logicalId,
|
||||
status: "awaiting-decision",
|
||||
error: `Original session unresumable: ${startupResult.errors.join("; ")}. The blank session was rolled back; no session is running. OpenRig's records can't tell whether this conversation was ever used. If you know this seat was never used, nothing is lost by starting only this seat fresh, ${steps}. Otherwise restore the original session manually.`,
|
||||
error: resumeWithoutContext
|
||||
? `Original session unresumable: ${startupResult.errors.join("; ")}. The blank session was rolled back; no session is running. ${noContextFresh} Restore the original session manually.`
|
||||
: `Original session unresumable: ${startupResult.errors.join("; ")}. The blank session was rolled back; no session is running. OpenRig's records can't tell whether this conversation was ever used. If you know this seat was never used, nothing is lost by starting only this seat fresh, ${steps}. Otherwise restore the original session manually.`,
|
||||
};
|
||||
}
|
||||
return {
|
||||
|
||||
@@ -13,6 +13,8 @@ export function validatePreRestore(
|
||||
freshLogicalIds?: string[];
|
||||
/** The runtime each seat has now, by logical id. A seat not listed is read as its saved runtime. */
|
||||
currentRuntimes?: Record<string, string | null | undefined>;
|
||||
/** Current explicit seat selections; a missing key is unknown, null is an explicit absence. */
|
||||
currentCodexProfiles?: Record<string, string | null>;
|
||||
},
|
||||
): { blockers: RestoreValidationBlocker[]; warnings: string[] } {
|
||||
const blockers: RestoreValidationBlocker[] = [];
|
||||
@@ -88,6 +90,12 @@ export function validatePreRestore(
|
||||
}
|
||||
|
||||
for (const node of topology.intendedNodes) {
|
||||
if (node.runtime === "codex" && node.codexConfigProfile
|
||||
&& opts.currentRuntimes?.[node.logicalId] === "codex"
|
||||
&& opts.currentCodexProfiles && Object.hasOwn(opts.currentCodexProfiles, node.logicalId)
|
||||
&& opts.currentCodexProfiles[node.logicalId] === null) {
|
||||
warnings.push(`Restore pre-validation: ${node.logicalId} had Codex profile ${node.codexConfigProfile} in this snapshot, but its current seat selection has no named profile. Restore uses the current selection; an ordinary floor launch uses workspace-write instead. Review rig seat set-permissions before restoring if this change is unintended. The snapshot does not prove what a prior process enforced.`);
|
||||
}
|
||||
const checkpoint = checkpoints[node.id] ?? null;
|
||||
if (checkpoint && !node.cwd) {
|
||||
add({
|
||||
|
||||
@@ -23,6 +23,7 @@ import { validateResumeToken } from "./resume-token-validation.js";
|
||||
import { readProcessTable } from "./process-table.js";
|
||||
import type { HomeRuntime } from "./seat-runtime-home.js";
|
||||
import { readSeatClaudeMcp, type ClaudeMcp } from "./claude-mcp.js";
|
||||
import { ObservationPass } from "./process-observation-pass.js";
|
||||
|
||||
export interface ResumeRefreshSession {
|
||||
/** The seat, when known, so its own runtime home is read. */
|
||||
@@ -58,6 +59,8 @@ interface ResumeMetadataRefresherDeps {
|
||||
};
|
||||
/** #421 — start time of the pane's current Claude process; a sidecar sampled earlier is not used. */
|
||||
claudeProcessStartedAt?: ResumeTokenCaptureDeps["claudeProcessStartedAt"];
|
||||
/** One fresh identity lister per seat, shared only within a snapshot refresh. */
|
||||
claudeStartedAtForPass?: (pass: ObservationPass) => NonNullable<ResumeTokenCaptureDeps["claudeProcessStartedAt"]>;
|
||||
/** Provider root used by the daemon's Claude launches; no scan of other homes. */
|
||||
claudeConfigDir?: string;
|
||||
listClaudeProcesses?: NativeProcessLister;
|
||||
@@ -77,6 +80,7 @@ export class ResumeMetadataRefresher {
|
||||
private homeDir: string;
|
||||
private contextUsageStore: ResumeMetadataRefresherDeps["contextUsageStore"] | null;
|
||||
private claudeProcessStartedAt: ResumeMetadataRefresherDeps["claudeProcessStartedAt"] | null;
|
||||
private claudeStartedAtForPass: ResumeMetadataRefresherDeps["claudeStartedAtForPass"];
|
||||
private claudeConfigDir: string;
|
||||
private seatHome?: (nodeId: string, runtime: HomeRuntime) => string | undefined;
|
||||
private listClaudeProcesses: NativeProcessLister | undefined;
|
||||
@@ -112,6 +116,7 @@ export class ResumeMetadataRefresher {
|
||||
this.homeDir = deps.homeDir ?? os.homedir();
|
||||
this.contextUsageStore = deps.contextUsageStore ?? null;
|
||||
this.claudeProcessStartedAt = deps.claudeProcessStartedAt ?? null;
|
||||
this.claudeStartedAtForPass = deps.claudeStartedAtForPass;
|
||||
this.claudeConfigDir = deps.claudeConfigDir ?? process.env.CLAUDE_CONFIG_DIR ?? nodePath.join(this.homeDir, ".claude");
|
||||
this.seatHome = deps.seatHome;
|
||||
this.listClaudeProcesses = deps.listClaudeProcesses;
|
||||
@@ -151,6 +156,8 @@ export class ResumeMetadataRefresher {
|
||||
},
|
||||
): Promise<void> {
|
||||
const fillNullOnly = opts?.fillNullOnly === true;
|
||||
const claudeStartedAt = fillNullOnly && this.claudeStartedAtForPass
|
||||
? this.claudeStartedAtForPass(new ObservationPass()) : this.claudeProcessStartedAt;
|
||||
// Snapshot-time discovery is SINGLE-ATTEMPT (mini-req 2): the 8-attempt
|
||||
// 250ms-sleep loop exists for the adoption boundary racing a booting codex;
|
||||
// on a recurring tick it multiplied `ps` spawns per seat, forever.
|
||||
@@ -207,7 +214,7 @@ export class ResumeMetadataRefresher {
|
||||
if (sidecar?.ok) {
|
||||
const token = sidecar.data.session_id;
|
||||
if (typeof token === "string" && token.trim().length > 0
|
||||
&& !(await isClaudeSidecarFromEarlierProcess(sidecar.data.sampled_at, session.sessionName, this.claudeProcessStartedAt))) {
|
||||
&& !(await isClaudeSidecarFromEarlierProcess(sidecar.data.sampled_at, session.sessionName, claudeStartedAt))) {
|
||||
this.sessionRegistry.updateResumeToken(session.sessionId, "claude_id", token.trim(), "scrape");
|
||||
}
|
||||
}
|
||||
@@ -231,7 +238,7 @@ export class ResumeMetadataRefresher {
|
||||
if (sidecar?.ok) {
|
||||
const derived = sidecar.data.session_id;
|
||||
if (typeof derived === "string" && derived.trim().length > 0 && derived.trim() === session.resumeToken
|
||||
&& !(await isClaudeSidecarFromEarlierProcess(sidecar.data.sampled_at, session.sessionName, this.claudeProcessStartedAt))) {
|
||||
&& !(await isClaudeSidecarFromEarlierProcess(sidecar.data.sampled_at, session.sessionName, claudeStartedAt))) {
|
||||
this.sessionRegistry.markResumeProbeResult(session.sessionId, "resumable");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,7 +131,7 @@ export function addRigEdge(
|
||||
if (LAUNCH_DEPENDENCY_KINDS.has(input.kind) && createsLaunchCycle(rig.edges, candidate)) {
|
||||
return {
|
||||
ok: false, code: "edge_cycle",
|
||||
message: `a ${input.kind} edge from ${input.from} to ${input.to} would make launch order cycle, and launch and restore refuse a cycle`,
|
||||
message: `a ${input.kind} edge from ${input.from} to ${input.to} would make launch order cycle; launch and restore require an acyclic order`,
|
||||
};
|
||||
}
|
||||
if (input.plan) return { ok: true, rigId: input.rigId, outcome: "would_add", edge };
|
||||
|
||||
@@ -253,6 +253,9 @@ export interface RuntimeAdapter {
|
||||
/** Claude's managed capability/launch seam, shared with seat selection. */
|
||||
readonly claudeManagedLaunch?: import("./claude-managed-launch.js").ClaudeManagedLaunch;
|
||||
readonly runtime: string;
|
||||
/** Check launch preconditions before an in-place handover ends the predecessor.
|
||||
* A concrete conflict refuses; an inconclusive check may allow launch with a warning. */
|
||||
preflightLaunch?(binding: NodeBinding): Promise<{ ok: true; warnings?: string[] } | { ok: false; error: string }>;
|
||||
/** The file an adapter's project() writes for a skill when it lives outside
|
||||
* the Claude project tree, for "already in place" detection. Absent = the
|
||||
* instantiator's default target. */
|
||||
|
||||
@@ -518,7 +518,9 @@ export class SeatHandoverService {
|
||||
if (permissionOverride.codexPermissions) {
|
||||
// Saved envelopes retain ordinary launch additions; only an observed predecessor
|
||||
// policy uses the exact carry path. Describe policy, not an observed native delta.
|
||||
const directoryPolicy = permissionOverride.codexPermissions.sandbox === "workspace-write"
|
||||
const directoryPolicy = "filesystem" in permissionOverride.codexPermissions
|
||||
? "with its explicit filesystem policy and no additional writable directory grants"
|
||||
: permissionOverride.codexPermissions.sandbox === "workspace-write"
|
||||
? "with OpenRig's usual Git metadata, seat-folder and pod-state writable roots as on a fresh launch"
|
||||
: "without additional writable directory grants, as on a read-only fresh launch";
|
||||
permissionContinuity = { state: "selection_used", detail: `The seat's saved permission envelope was used ${directoryPolicy}. This describes launch policy, not an observed difference. The predecessor policy was not carried; native successor equivalence is unverified.`
|
||||
@@ -617,7 +619,9 @@ export class SeatHandoverService {
|
||||
// The registry binding is unchanged (commit never ran). A resolve_pane failure leaves the live
|
||||
// retiree wholly untouched; a failure after the in-place respawn leaves the seat re-wakeable from
|
||||
// its provider session file (never destroyed). Inspect tmux/daemon logs and retry.
|
||||
guidance: "The seat's registry binding is unchanged. If the failure was after the in-place respawn, the seat is re-wakeable from its provider session file. Inspect tmux/daemon logs and retry.",
|
||||
guidance: launch.code === "successor_preflight_failed"
|
||||
? `The predecessor is still running and its binding is unchanged. ${launch.message}`
|
||||
: "The seat's registry binding is unchanged. If the failure was after the in-place respawn, the seat is re-wakeable from its provider session file. Inspect tmux/daemon logs and retry.",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -779,7 +783,7 @@ export class SeatHandoverService {
|
||||
sourceOutcome,
|
||||
launchAdditionNotes,
|
||||
startedWithoutRequired,
|
||||
launchWarnings: coreCopyNotes,
|
||||
launchWarnings: [...coreCopyNotes, ...(launch.warnings ?? [])],
|
||||
cleanup: () => this.successorLauncher.cleanup(launch.tmuxSession, launch.discoveredId, launch.activityGrantId),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -951,7 +951,7 @@ export class SeatLifecycleService {
|
||||
let persisted: PersistedEvent | null = null;
|
||||
const result = this.db.transaction(() => {
|
||||
// Read the current record for the audit; malformed old bytes stay visible as such and are replaced.
|
||||
const row = this.db.prepare("SELECT codex_permissions_json FROM nodes WHERE id = ? AND runtime = 'codex'").get(seat.nodeId) as { codex_permissions_json: string | null } | undefined;
|
||||
const row = this.db.prepare("SELECT codex_permissions_json, codex_config_profile FROM nodes WHERE id = ? AND runtime = 'codex'").get(seat.nodeId) as { codex_permissions_json: string | null; codex_config_profile: string | null } | undefined;
|
||||
if (!row) throw new Error("Seat runtime changed; the envelope was not changed.");
|
||||
let from: unknown = null;
|
||||
try { from = readCodexMemberPermissions(this.db, seat.nodeId) ?? null; }
|
||||
@@ -968,7 +968,7 @@ export class SeatLifecycleService {
|
||||
nodeId: seat.nodeId, from, to, ...(replaced ? { replaced } : {}), actor, reason, effect: "future_launches_only" });
|
||||
}
|
||||
return { ok: true as const, seat, from, to, changed, ...(replaced ? { replaced } : {}),
|
||||
effect: `The envelope applies at the next separately authorized managed launch or resume, as explicit sandbox and approval flags that a profile or policy posture doesn't override.${replaced ? " It replaces the seat's recorded permission mode." : ""} The current process and history are unchanged. Older readers may ignore it; check rollback compatibility and preserve restrictions before downgrading.` };
|
||||
effect: `The envelope applies at the next separately authorized managed launch or resume, ${"filesystem" in to ? "as explicit permission and approval flags, with native configuration conflicts refused and inconclusive checks reported as policy not verified." : "as explicit sandbox and approval flags that a profile or policy posture doesn't override."}${replaced ? " It replaces the seat's recorded permission mode." : ""} The current process and history are unchanged. Older readers may ignore it; check rollback compatibility and preserve restrictions before downgrading.` };
|
||||
})();
|
||||
if (persisted) this.eventBus.notifySubscribers(persisted);
|
||||
return result;
|
||||
|
||||
@@ -31,7 +31,6 @@ import {
|
||||
} from "./composer-prompts.js";
|
||||
export { inspectStartupStagedText } from "./startup-submission-evidence.js";
|
||||
import { OutboxHandler, OutboxHandlerError } from "./outbox-handler.js";
|
||||
import { readSendOutcome, type WrittenFact } from "./connection-contract.js";
|
||||
import { DraftAwareDelivery, type GuardedDeliverySummary, type QueueWakeFacts } from "./draft-aware-delivery.js";
|
||||
import type Database from "better-sqlite3";
|
||||
import type { RigRepository } from "./rig-repository.js";
|
||||
@@ -178,7 +177,7 @@ function enterWithheld(reason: string | undefined): boolean {
|
||||
* write that may have landed is uncertain. Text that was written reads text only when a pre-Enter check refused the
|
||||
* Enter, and otherwise text with the submission unknown, since Enter may have been attempted. A send that wrote
|
||||
* nothing says so. Anything else the result doesn't establish is unknown, never a guess. */
|
||||
export function writtenFact(result: SendResult): WrittenFact {
|
||||
export function writtenFact(result: SendResult): "submitted" | "submit_only" | "text_only" | "text_submit_unknown" | "uncertain" | "none" | "unknown" {
|
||||
if (result.ok && result.outcome !== "retained") {
|
||||
if (result.submitOnly) return "submit_only";
|
||||
return result.promptInteraction === "unverified" ? "text_only" : "submitted";
|
||||
@@ -2745,7 +2744,7 @@ export class SessionTransport {
|
||||
pane: seat.pane, occupantGeneration: seat.occupant, messageId: opts?.deliveryId ?? outboxIds[0] ?? attemptId, attemptId,
|
||||
admitted: admissionUnknown ? "unknown" : admitted.length > 0 ? { outboxIds: admitted } : "none", written: writtenFact(result),
|
||||
terminalObserved: { outcome: result.outcome ?? null, verified: result.verified ?? null }, inputBoundary: "unknown", source: "send_result",
|
||||
...wireFingerprint(wire), outcome: readSendOutcome(result, writtenFact(result)),
|
||||
...wireFingerprint(wire),
|
||||
});
|
||||
} catch (err) {
|
||||
if (!this.evidenceFailureLogged) {
|
||||
@@ -3931,12 +3930,13 @@ export class SessionTransport {
|
||||
|
||||
/** Wait on the existing classifier without occupying the input/lifecycle lease. With `singleObservation`, one
|
||||
* observation within `timeoutMs` and no wait after it: a busy reading returns at once. */
|
||||
async waitUntilIdle(sessionName: string, timeoutMs: number, signal?: AbortSignal, opts?: { singleObservation?: boolean; allowDraft?: true }) {
|
||||
async waitUntilIdle(sessionName: string, timeoutMs: number, signal?: AbortSignal, opts?: { singleObservation?: boolean; allowDraft?: true; onObservation?: (activity: AgentActivity) => void }) {
|
||||
const meta = this.getSessionMeta(sessionName);
|
||||
return this.waitForIdle({ sessionName, runtime: meta.runtime, attachmentType: meta.attachmentType, timeoutMs, signal,
|
||||
binding: { sessionName, nodeId: meta.nodeId, occupant: meta.occupant, pane: meta.pane },
|
||||
...(opts?.allowDraft ? { allowDraft: true } : {}),
|
||||
...(opts?.singleObservation ? { singleObservation: true } : {}) });
|
||||
...(opts?.singleObservation ? { singleObservation: true } : {}),
|
||||
...(opts?.onObservation ? { onObservation: opts.onObservation } : {}) });
|
||||
}
|
||||
|
||||
private async waitForIdle(input: {
|
||||
@@ -3955,6 +3955,8 @@ export class SessionTransport {
|
||||
allowUnknown?: boolean;
|
||||
/** One observation only: a reading that isn't idle ends the wait at once. */
|
||||
singleObservation?: boolean;
|
||||
/** Called with each observation that completes in time, so a caller can report the seat's state while it waits. */
|
||||
onObservation?: (activity: AgentActivity) => void;
|
||||
// Optional display value for timeout messages. The deadline always comes
|
||||
// from timeoutMs; when set, expiry reports this value instead, so a
|
||||
// re-wait running on a leftover budget still names the configured wait.
|
||||
@@ -4025,6 +4027,7 @@ export class SessionTransport {
|
||||
return expire();
|
||||
}
|
||||
last = activity;
|
||||
input.onObservation?.(activity);
|
||||
const waitedMs = input.timeoutMs - (deadline - Date.now());
|
||||
|
||||
if (activity.state === "idle" || (input.allowUnknown && activity.state === "unknown") || (input.allowDraft && this.deliversOverDraft(activity))) {
|
||||
|
||||
@@ -93,7 +93,8 @@ export function parseSkillFrontmatter(content: string): ParseResult {
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = parseYaml(fmText!);
|
||||
// The delimiter's preceding LF is outside the capture; on CRLF files its CR is not.
|
||||
parsed = parseYaml(fmText!.replace(/\r$/, ""));
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
return { ok: false, reason: `frontmatter YAML parse error: ${msg}` };
|
||||
|
||||
@@ -250,6 +250,21 @@ export class SuccessorSessionLauncher {
|
||||
};
|
||||
}
|
||||
|
||||
const binding = successorBinding(input.node, departingSession, pane.id, cwd, input.occupantGeneration);
|
||||
const adapter = input.node.runtime ? this.runtimeAdapters[input.node.runtime] : undefined;
|
||||
let preflightWarnings: string[] = [];
|
||||
if (adapter?.preflightLaunch) {
|
||||
try {
|
||||
const checked = await adapter.preflightLaunch(binding);
|
||||
if (!checked.ok) return { ok: false, code: "successor_preflight_failed", step: "create_successor",
|
||||
message: checked.error, replacementStarted: false };
|
||||
preflightWarnings = checked.warnings ?? [];
|
||||
} catch (error) {
|
||||
return { ok: false, code: "successor_preflight_failed", step: "create_successor",
|
||||
message: `Successor launch preflight threw: ${error instanceof Error ? error.message : String(error)}`, replacementStarted: false };
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Terminate the retiree IN PLACE, then respawn the now-dead pane WITHOUT -k so native scrollback
|
||||
// survives (respawn-pane -k CLEARS the pane history — verified on tmux 3.6a; that would defeat the
|
||||
// money-proof). The swap: set remain-on-exit so the pane survives the exit → graceful SIGTERM
|
||||
@@ -304,7 +319,7 @@ export class SuccessorSessionLauncher {
|
||||
// not repointed. When the harness launch was already sent and only readiness failed, the pane is NOT left as
|
||||
// a bare shell: the successor may still come up there, unadopted (#2985). The failure says so, so the caller
|
||||
// can tell the operator that a retry would end it.
|
||||
const started = await this.startAgent(input.node, departingSession, pane.id, cwd, input.forkSource, input.occupantGeneration);
|
||||
const started = await this.startAgent(input.node, departingSession, pane.id, cwd, input.forkSource, input.occupantGeneration, undefined, binding);
|
||||
if (!started.ok) {
|
||||
return { ok: false, code: started.code, step: "start_agent", message: started.message, replacementStarted: true,
|
||||
tmuxPane: pane.id, ...(started.launched ? { successorLaunched: true } : {}) };
|
||||
@@ -320,6 +335,7 @@ export class SuccessorSessionLauncher {
|
||||
cwd: input.node.cwd ?? undefined,
|
||||
});
|
||||
|
||||
const warnings = [...preflightWarnings, ...(respawned.warnings ?? [])];
|
||||
return {
|
||||
ok: true,
|
||||
discoveredId: discovered.id,
|
||||
@@ -330,7 +346,7 @@ export class SuccessorSessionLauncher {
|
||||
appliedLaunch: started.appliedLaunch,
|
||||
...(started.activityGrantId ? { activityGrantId: started.activityGrantId } : {}),
|
||||
retireeExit: terminated.path,
|
||||
...(respawned.warnings ? { warnings: respawned.warnings } : {}),
|
||||
...(warnings.length ? { warnings } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -397,6 +413,7 @@ export class SuccessorSessionLauncher {
|
||||
forkSource?: ForkSource,
|
||||
launchGeneration?: string | null,
|
||||
staged?: StagedLaunch,
|
||||
preparedBinding?: NodeBinding,
|
||||
): Promise<{ ok: true; activityGrantId?: string; resumeToken?: string; resumeType?: string; appliedLaunch?: AppliedLaunchObservation; notes?: string[] } | { ok: false; code: string; message: string; launched?: true }> {
|
||||
const adapter = node.runtime ? this.runtimeAdapters[node.runtime] : undefined;
|
||||
if (!adapter) {
|
||||
@@ -414,39 +431,7 @@ export class SuccessorSessionLauncher {
|
||||
// edge of the same seat, so its launch must read the seat's spec, else the
|
||||
// running topology silently drifts from the founder-designed one at every
|
||||
// handover. (config profile is still a tracked follow-on.)
|
||||
const binding: NodeBinding = {
|
||||
id: "",
|
||||
nodeId: node.id,
|
||||
attachmentType: "tmux",
|
||||
tmuxSession,
|
||||
tmuxWindow: null,
|
||||
tmuxPane,
|
||||
cmuxWorkspace: null,
|
||||
cmuxSurface: null,
|
||||
updatedAt: "",
|
||||
cwd: cwd ?? "",
|
||||
launchGeneration: launchGeneration ?? undefined,
|
||||
nonInterruptive: node.nonInterruptive,
|
||||
kernelAuthority: node.kernelAuthority,
|
||||
teamPermissionDefault: node.teamPermissionDefault,
|
||||
claudePermissions: node.claudePermissions,
|
||||
claudeMcp: node.runtime === "claude-code" ? node.claudeMcp : undefined,
|
||||
codexPermissions: node.codexPermissions,
|
||||
// Seam B: continuity — the successor launches at the departing seat's posture.
|
||||
...(node.launchPosture ? { launchPosture: node.launchPosture } : {}),
|
||||
...(node.permissionMode ? { permissionMode: node.permissionMode } : {}),
|
||||
// 0.5.2-07: the successor reads the seat's SPEC-pinned model (adapter emits -m/--model).
|
||||
model: node.model ?? undefined,
|
||||
// #75: the successor reads the seat's resolved effort (saved choice, else authored).
|
||||
effort: node.effort ?? undefined,
|
||||
advisor: node.advisor ?? undefined,
|
||||
// 0.5.2-07 A4-profile: the successor reads the seat's SPEC-pinned codex config profile (adapter emits -p).
|
||||
codexConfigProfile: node.codexConfigProfile ?? undefined,
|
||||
codexRebuildPermissions: node.codexRebuildPermissions,
|
||||
...(node.launchAdditions ? { launchAdditions: node.launchAdditions } : {}),
|
||||
...(node.launchWrapper?.length ? { launchWrapper: node.launchWrapper } : {}),
|
||||
...(staged?.binding ?? {}),
|
||||
};
|
||||
const binding = preparedBinding ?? successorBinding(node, tmuxSession, tmuxPane, cwd, launchGeneration, staged?.binding);
|
||||
|
||||
// Slice 16: a staged runtime-switch successor gets its target materials before its harness starts.
|
||||
let notes: string[] | undefined;
|
||||
@@ -578,6 +563,43 @@ export class SuccessorSessionLauncher {
|
||||
}
|
||||
}
|
||||
|
||||
function successorBinding(node: SuccessorNode, tmuxSession: string, tmuxPane: string, cwd: string | undefined,
|
||||
launchGeneration?: string | null, bindingOverrides?: StagedLaunch["binding"]): NodeBinding {
|
||||
return {
|
||||
id: "",
|
||||
nodeId: node.id,
|
||||
attachmentType: "tmux",
|
||||
tmuxSession,
|
||||
tmuxWindow: null,
|
||||
tmuxPane,
|
||||
cmuxWorkspace: null,
|
||||
cmuxSurface: null,
|
||||
updatedAt: "",
|
||||
cwd: cwd ?? "",
|
||||
launchGeneration: launchGeneration ?? undefined,
|
||||
nonInterruptive: node.nonInterruptive,
|
||||
kernelAuthority: node.kernelAuthority,
|
||||
teamPermissionDefault: node.teamPermissionDefault,
|
||||
claudePermissions: node.claudePermissions,
|
||||
claudeMcp: node.runtime === "claude-code" ? node.claudeMcp : undefined,
|
||||
codexPermissions: node.codexPermissions,
|
||||
// Seam B: continuity — the successor launches at the departing seat's posture.
|
||||
...(node.launchPosture ? { launchPosture: node.launchPosture } : {}),
|
||||
...(node.permissionMode ? { permissionMode: node.permissionMode } : {}),
|
||||
// 0.5.2-07: the successor reads the seat's SPEC-pinned model (adapter emits -m/--model).
|
||||
model: node.model ?? undefined,
|
||||
// #75: the successor reads the seat's resolved effort (saved choice, else authored).
|
||||
effort: node.effort ?? undefined,
|
||||
advisor: node.advisor ?? undefined,
|
||||
// 0.5.2-07 A4-profile: the successor reads the seat's SPEC-pinned codex config profile (adapter emits -p).
|
||||
codexConfigProfile: node.codexConfigProfile ?? undefined,
|
||||
codexRebuildPermissions: node.codexRebuildPermissions,
|
||||
...(node.launchAdditions ? { launchAdditions: node.launchAdditions } : {}),
|
||||
...(node.launchWrapper?.length ? { launchWrapper: node.launchWrapper } : {}),
|
||||
...(bindingOverrides ?? {}),
|
||||
};
|
||||
}
|
||||
|
||||
function compactEnv(input: Record<string, string | undefined>): Record<string, string> {
|
||||
const result: Record<string, string> = {};
|
||||
for (const [key, value] of Object.entries(input)) {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { BUILD_INFO, type BuildInfo } from "../build-info.js";
|
||||
import { TEAM_OPERATIONS_CONTRACT, type Support } from "./connection-contract.js";
|
||||
|
||||
export { TEAM_OPERATIONS_CONTRACT };
|
||||
/** The team-operations contract an app reads before relying on a job's fields: one contract version with per-job
|
||||
* capabilities, distinct from the build label. A capability is supported, not-supported or unknown; an absent key reads
|
||||
* unknown. */
|
||||
export const TEAM_OPERATIONS_CONTRACT = "team-operations.v1";
|
||||
|
||||
/** A team-operations capability: supported, not-supported or unknown; an absent key reads unknown. The contract an app
|
||||
* reads before relying on a job's fields is one version with per-job capabilities, distinct from the build label. */
|
||||
export type CapabilityValue = Support;
|
||||
export type CapabilityValue = "supported" | "not-supported" | "unknown";
|
||||
|
||||
/** needs-me: see what needs me, answer as me, follow it through. This build reads it (what needs the person, each
|
||||
* request's revision and what it's about, the answers returned to it, and a snapshot watermark). Answering under this
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { StartupSubmissionDiagnostic } from "./startup-submission-evidence.js";
|
||||
import type { readSendOutcome } from "./connection-contract.js";
|
||||
|
||||
export interface Rig {
|
||||
id: string;
|
||||
@@ -198,9 +197,7 @@ export type RigEvent =
|
||||
admitted: DeliveryEvidenceAdmitted;
|
||||
written: "submitted" | "submit_only" | "text_only" | "text_submit_unknown" | "uncertain" | "none" | "unknown";
|
||||
terminalObserved: DeliveryEvidenceObserved; inputBoundary: "unknown"; source: "send_result";
|
||||
wireSha256: string | null; wireBytes: number | null; writtenAt: string | null;
|
||||
/** The attempt's outcome in the shared words, from the same result: which fact, who established it, and the route. */
|
||||
outcome: ReturnType<typeof readSendOutcome> }
|
||||
wireSha256: string | null; wireBytes: number | null; writtenAt: string | null }
|
||||
/** A harness's own prompt hook, as it reported: a fingerprint and byte length of the prompt it received, its own session
|
||||
* and prompt or turn id, and the generation the hook ran as. A raw observation, never a message's attribution: neither
|
||||
* harness reports a prompt's origin, so which message (if any) it was isn't established, and each delivery record's
|
||||
|
||||
@@ -353,6 +353,28 @@ export class WorkflowInstanceStore {
|
||||
return rows.map(rowToInstance);
|
||||
}
|
||||
|
||||
/** Apply selectors before the optional bound and before expensive inspection. */
|
||||
listFiltered(filters: { status?: WorkflowInstanceStatus; project?: string; mission?: string; slice?: string; rig?: string; name?: string; tags?: string[]; limit?: number }): WorkflowInstance[] {
|
||||
const clauses: string[] = [];
|
||||
const args: Array<string | number> = [];
|
||||
if (filters.status) { clauses.push("status = ?"); args.push(filters.status); }
|
||||
if (filters.name) { clauses.push("workflow_name = ?"); args.push(filters.name); }
|
||||
if (filters.rig) { clauses.push(this.hasBoundRigColumn ? "bound_rig = ?" : "0"); if (this.hasBoundRigColumn) args.push(filters.rig); }
|
||||
for (const field of ["project", "mission", "slice"] as const) {
|
||||
if (!filters[field]) continue;
|
||||
clauses.push(this.hasScopeColumn ? `json_extract(scope_json, '$.${field}') = ?` : "0");
|
||||
if (this.hasScopeColumn) args.push(filters[field]!);
|
||||
}
|
||||
for (const tag of filters.tags ?? []) {
|
||||
clauses.push(this.hasScopeColumn ? "EXISTS (SELECT 1 FROM json_each(workflow_instances.scope_json, '$.tags') WHERE value = ?)" : "0");
|
||||
if (this.hasScopeColumn) args.push(tag);
|
||||
}
|
||||
const where = clauses.length ? ` WHERE ${clauses.join(" AND ")}` : "";
|
||||
const limit = filters.limit === undefined ? "" : " LIMIT ?";
|
||||
if (filters.limit !== undefined) args.push(filters.limit);
|
||||
return (this.db.prepare(`SELECT * FROM workflow_instances${where} ORDER BY created_at ASC${limit}`).all(...args) as InstanceRow[]).map(rowToInstance);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update frontier + status atomically. Caller is responsible for
|
||||
* wrapping in a transaction when this needs to compose with other
|
||||
|
||||
@@ -1845,8 +1845,9 @@ export class WorkflowRuntime {
|
||||
/** List instances (optionally filtered) with the deadline verdict attached. */
|
||||
listInstancesWithDeadline(
|
||||
status?: "active" | "waiting" | "completed" | "failed" | "aborted",
|
||||
filters?: Omit<Parameters<WorkflowInstanceStore["listFiltered"]>[0], "status">,
|
||||
): WorkflowInstanceWithInspection[] {
|
||||
const rows = status ? this.instanceStore.listByStatus(status) : this.instanceStore.listAll();
|
||||
const rows = filters ? this.instanceStore.listFiltered({ ...filters, status }) : status ? this.instanceStore.listByStatus(status) : this.instanceStore.listAll();
|
||||
return rows.map((row) => {
|
||||
const inspected = this.inspect(row.instanceId);
|
||||
return {
|
||||
|
||||
@@ -100,6 +100,10 @@ export function appendDeliveredSegment(envelope: string, deltaMs: number): strin
|
||||
return lines.join("\n") + rest;
|
||||
}
|
||||
|
||||
/** The address OpenRig records an answer typed at this machine under (the daemon's UNATTRIBUTED_ACTOR). It names nobody,
|
||||
* and a row there asks no one (it waits on Steering and in the Feed, and OpenRig reports it as undeliverable), so a reply hint never points at it. */
|
||||
const UNATTRIBUTED_PERSON = "human@host";
|
||||
|
||||
/** Wrap a tmux-pane body with the canonical From/To envelope. The
|
||||
* recipient pane sees both the sender's identity and a reply hint.
|
||||
* Cross-host nudges should NOT double-wrap: the remote rig wraps
|
||||
@@ -134,6 +138,8 @@ export function wrapPaneEnvelope(
|
||||
}
|
||||
const reply = senderLabel.endsWith("@external")
|
||||
? `↩ Reply if needed: rig queue create --destination ${senderLabel}${meta?.replyToQitem ? ` --human-intent update --reply-to ${meta.replyToQitem}` : ""} --summary "<one line>" --body "..." --verify`
|
||||
: personAddress === UNATTRIBUTED_PERSON
|
||||
? `↩ ${senderLabel} names no person: a reply there asks no one. It waits on Steering and in the Feed, and OpenRig reports it as undeliverable. To ask the person back, use their registered address (rig gateway human list lists who's registered).`
|
||||
: isHumanSeatSessionRef(personAddress)
|
||||
? `↩ Reply if needed: rig queue create --destination ${senderLabel} --human-intent update --summary "<one line>" --evidence-ref "<path>" --body "..." --verify`
|
||||
: isOpenRigSender(senderLabel)
|
||||
|
||||
@@ -90,8 +90,7 @@ export function attentionRoutes(): Hono {
|
||||
// A pairing request is also decided directly on this host's settings page, opened on this request (its row).
|
||||
...(q.evidenceRef?.startsWith("pair-request:") ? { settingsLink: { category: "instance", focus: q.qitemId, label: "Open pairing settings (Approve or Deny directly)" } } : {}),
|
||||
summary: q.summary || q.body.trim().split(/\r?\n/).find(Boolean) || "Request summary unavailable", urgency: q.priority, unblocks, at: q.tsUpdated, scope: p ? `project ${p.id}` : "instance · project unknown", project: p ? { id: p.id, root: p.root } : null, source: `/api/queue/${encodeURIComponent(q.qitemId)}`,
|
||||
revision: queue.decisionRevision(q), about: toPerson ? deps.slice(0, 100).map(d => d.qitem_id) : [q.qitemId],
|
||||
...(toPerson && deps.length > 100 ? { aboutTruncated: true as const } : {}) };
|
||||
revision: queue.decisionRevision(q), about: toPerson ? deps.slice(0, 100).map(d => d.qitem_id) : [q.qitemId] };
|
||||
const unbound = noConnector(toPerson ? q.destinationSession : q.blockedOn);
|
||||
const notSent = unbound || quiet.has(q.qitemId);
|
||||
const route = unanswered
|
||||
|
||||
@@ -63,8 +63,8 @@ export function compactionRoutes(opts?: { bearerToken?: string | null }): Hono {
|
||||
}
|
||||
|
||||
// Read the KNOWN context-usage projection BEFORE triggering. When usage is
|
||||
// absent / stale / unknown we pass null (never invent a value); the enforcer
|
||||
// returns an honest `no_usage_data` reason for a Claude seat.
|
||||
// absent / stale / unknown we pass null (never invent a value); an explicit
|
||||
// manual request doesn't depend on the threshold, so it proceeds without it.
|
||||
const usage = usageStore.getForNode(row.node_id, sessionName);
|
||||
const outcome = await enforcer.triggerManualCompact(
|
||||
{
|
||||
@@ -170,7 +170,8 @@ function manualOutcomeMessage(sessionName: string, outcome: Extract<ManualCompac
|
||||
const prep = outcome.preparation;
|
||||
if (!prep || prep.delivery === "not_sent") return manualReasonMessage(sessionName, outcome.reason);
|
||||
const effect = prep.delivery === "delivered" ? "Preparation was sent" : "Preparation may have reached the seat (delivery is unconfirmed)";
|
||||
const detail = (outcome.reason === "preparation_incomplete" || outcome.reason === "map_complete_seat_never_idle")
|
||||
const detail = (outcome.reason === "preparation_incomplete" || outcome.reason === "map_complete_seat_never_idle"
|
||||
|| outcome.reason === "preparation_needs_input")
|
||||
? manualReasonMessage(sessionName, outcome.reason)
|
||||
: outcome.restoreOwed
|
||||
? `/compact was not confirmed (${outcome.reason}) and is never sent again. Its restore steps follow in case it ran; the restore request tells the seat to say so and skip if it didn't compact.`
|
||||
@@ -202,6 +203,8 @@ function manualReasonMessage(sessionName: string, reason: string): string {
|
||||
return `The occupant generation could not be resolved for '${sessionName}'; no preparation or compact was sent. For the confirmed live seat, run rig reconcile-session ${shellQuote(sessionName)} --no-launch, then explicitly retry rig compact ${shellQuote(sessionName)}. Reconciliation does not restart this attempt.`;
|
||||
case "map_complete_seat_never_idle":
|
||||
return `Compaction for '${sessionName}': map complete, seat never idle within the bounded wait; managed compaction is disarmed. Inspect rig compact ${shellQuote(sessionName)} --state before an explicit retry.`;
|
||||
case "preparation_needs_input":
|
||||
return `Compaction for '${sessionName}' waited for the seat to answer a prompt (a permission request in its preparation turn, say) and it didn't become idle within the bounded wait; managed compaction is disarmed. Answer the prompt in the seat, then retry explicitly: rig compact ${shellQuote(sessionName)}. Inspect rig compact ${shellQuote(sessionName)} --state first.`;
|
||||
case "preparation_incomplete":
|
||||
return `The restore map was not completed in time for '${sessionName}'; managed compaction is disarmed. Inspect rig compact ${sessionName} --state, retry explicitly, or use --skip-map once.`;
|
||||
case "pane_unknown_protected":
|
||||
|
||||
@@ -211,6 +211,24 @@ export function queueRoutes(): Hono {
|
||||
message: `No wake is set for this park: nothing wakes ${item.destinationSession} on a timer while ${item.qitemId} waits on ${item.blockedOn}. To add one, park it again with --wake-after <duration> (or --wake-watchdog <job-id>). When ${item.blockedOn} clears, rig queue resolve ${item.qitemId} --decision <evidence> unparks it.`,
|
||||
};
|
||||
}
|
||||
/** A summary or evidence ref the update asked for but the stored row doesn't carry (a blank one, which isn't stored
|
||||
* because it would erase what the row has, or one the repository couldn't write): read from the stored row, so the
|
||||
* caller is told whatever the reason. */
|
||||
function unstoredAdvisories(body: { summary?: unknown; evidenceRef?: unknown }, item: QueueItem) {
|
||||
return ([["summary", "summary", "summary_not_stored"], ["evidenceRef", "evidence ref", "evidence_ref_not_stored"]] as const)
|
||||
.flatMap(([field, name, code]) => {
|
||||
const requested = body[field];
|
||||
const stored = item[field];
|
||||
if (typeof requested !== "string" || stored === requested) return [];
|
||||
const why = requested.trim().length === 0 ? `The ${name} was blank, so it wasn't stored` : `The ${name} wasn't stored`;
|
||||
return [{
|
||||
code,
|
||||
qitemId: item.qitemId,
|
||||
field,
|
||||
message: `${why}: ${item.qitemId} keeps ${stored ? `its ${name} "${stored}"` : `no ${name}`}. The rest of the update was applied.`,
|
||||
}];
|
||||
});
|
||||
}
|
||||
function getInbox(c: { get: (key: string) => unknown }): InboxHandler {
|
||||
return c.get("inboxHandler" as never) as InboxHandler;
|
||||
}
|
||||
@@ -312,9 +330,6 @@ export function queueRoutes(): Hono {
|
||||
: err.code === "reply_to_requires_update" ? 400
|
||||
: err.code === "reply_to_not_found" ? 400
|
||||
: err.code === "invalid_human_questions" ? 400
|
||||
// OPR.0.5.1 slice-51-06 D2: summary/evidence_ref on a non-park transition — a client
|
||||
// input error surfaced as a structured 400 (the daemon rejects before any mutation).
|
||||
: err.code === "summary_evidence_not_persistable" ? 400
|
||||
// OPR.0.4.6.WF3 FR-6: the frontier close-path guard — operator
|
||||
// misuse of a queue verb on a live workflow packet; structured
|
||||
// 400 with the what/why/fix message, never a 500.
|
||||
@@ -922,8 +937,9 @@ export function queueRoutes(): Hono {
|
||||
evidenceRef: body.evidenceRef,
|
||||
...resolveRecordedIdentity(c, identity), // P21 §4 era-stamp, plus the MCP adapter's caller on a direct attributed request (principal:v1)
|
||||
});
|
||||
const advisory = body.state === "blocked" ? parkWithoutWakeAdvisory(item) : null;
|
||||
return c.json({ ...item, ...(advisory ? { advisories: [advisory] } : {}) });
|
||||
const advisories = [body.state === "blocked" ? parkWithoutWakeAdvisory(item) : null, ...unstoredAdvisories(body, item)]
|
||||
.filter((advisory) => advisory !== null);
|
||||
return c.json({ ...item, ...(advisories.length > 0 ? { advisories } : {}) });
|
||||
} catch (err) {
|
||||
return errorResponse(c, err);
|
||||
}
|
||||
@@ -1558,10 +1574,8 @@ export function queueRoutes(): Hono {
|
||||
...item,
|
||||
// #2446: what a settling Mission Control act can be guarded with (expectedRevision).
|
||||
decisionRevision: repo.decisionRevision(item),
|
||||
// The answer rows returned to this row, read by their link rather than their text; empty when none came back here.
|
||||
// Only this daemon's rows are read: an answer another host holds isn't in them, so empty isn't proof of none.
|
||||
// The answer rows returned to this row, read by their link rather than their text; empty when none came back.
|
||||
answers: repo.answersForAsk(qitemId),
|
||||
answersFrom: "this-daemon",
|
||||
// A closed row's outcome (its note and reason) lives only in the transition log; omitted while the row is open.
|
||||
...(closing ? { closingTransition: {
|
||||
transitionId: closing.transitionId,
|
||||
|
||||
@@ -321,10 +321,20 @@ export function workflowRoutes(): Hono {
|
||||
// runtime.continue()'s enriched instance.
|
||||
app.get("/list", (c) => {
|
||||
const status = c.req.query("status");
|
||||
if (status === "active" || status === "waiting" || status === "completed" || status === "failed" || status === "aborted") {
|
||||
return c.json(getRuntime(c).listInstancesWithDeadline(status));
|
||||
const parsedStatus = status === "active" || status === "waiting" || status === "completed" || status === "failed" || status === "aborted" ? status : undefined;
|
||||
const rawLimit = c.req.query("limit");
|
||||
if (rawLimit !== undefined && (!/^[1-9]\d*$/.test(rawLimit) || Number(rawLimit) > 10000)) return c.json({ error: "limit_invalid", message: "limit must be an integer from 1 to 10000" }, 400);
|
||||
const fields = ["project", "mission", "slice", "rig", "name"] as const;
|
||||
const filters: { project?: string; mission?: string; slice?: string; rig?: string; name?: string; tags?: string[]; limit?: number } = {};
|
||||
for (const field of fields) {
|
||||
const value = c.req.query(field);
|
||||
if (value !== undefined) { if (!value.trim()) return c.json({ error: "filter_invalid", message: `${field} must not be empty` }, 400); filters[field] = value; }
|
||||
}
|
||||
return c.json(getRuntime(c).listInstancesWithDeadline());
|
||||
const tags = c.req.queries("tag");
|
||||
if (tags?.some((tag) => !tag.trim())) return c.json({ error: "filter_invalid", message: "tag must not be empty" }, 400);
|
||||
if (tags?.length) filters.tags = tags;
|
||||
if (rawLimit !== undefined) filters.limit = Number(rawLimit);
|
||||
return c.json(getRuntime(c).listInstancesWithDeadline(parsedStatus, Object.keys(filters).length ? filters : undefined));
|
||||
});
|
||||
|
||||
// Lists every cached workflow_spec with an `isBuiltIn` flag computed
|
||||
|
||||
@@ -39,8 +39,6 @@ import type { SelfAttachService } from "./domain/self-attach-service.js";
|
||||
import { rigsRoutes } from "./routes/rigs.js";
|
||||
import { OPERATION_CONTRACT, OPERATION_KINDS } from "./domain/operation-correlation.js";
|
||||
import { teamOperationsCapabilities } from "./domain/team-operations.js";
|
||||
import { MEMBER_CONNECTION_CONTRACT, ROUTE_DECLARATIONS } from "./domain/connection-contract.js";
|
||||
import { resolveMemberConnection } from "./domain/member-connection.js";
|
||||
import { sessionsRoutes, nodesRoutes, sessionAdminRoutes } from "./routes/sessions.js";
|
||||
import { adaptersRoutes } from "./routes/adapters.js";
|
||||
import { eventsRoute } from "./routes/events.js";
|
||||
@@ -800,13 +798,6 @@ export function createApp(deps: AppDeps): Hono {
|
||||
app.route("/api/rigs", rigsRoutes);
|
||||
app.get("/api/operations/capabilities", (c) => c.json({ contract: OPERATION_CONTRACT, kinds: OPERATION_KINDS }));
|
||||
app.get("/api/team-operations/capabilities", (c) => c.json(teamOperationsCapabilities()));
|
||||
// What each delivery route declares it supports, and with ?session=, the route and declaration of the member that
|
||||
// address names.
|
||||
app.get("/api/member-connection/capabilities", (c) => {
|
||||
const member = c.req.query("session")?.trim();
|
||||
return c.json({ contract: MEMBER_CONNECTION_CONTRACT, routes: ROUTE_DECLARATIONS,
|
||||
...(member ? { member: resolveMemberConnection(deps.rigRepo.db, deps.queueRepo, member) } : {}) });
|
||||
});
|
||||
app.route("/api/rigs/:rigId/sessions", sessionsRoutes);
|
||||
// Slice 24 — per-rig CMUX workspace launcher.
|
||||
app.route("/api/rigs/:rigId/cmux", rigCmuxRoutes);
|
||||
|
||||
@@ -116,7 +116,7 @@ import { setSelfHostId, setSelfHostIdSource } from "./domain/hosts/fanout-contra
|
||||
import { UpCommandRouter } from "./domain/up-command-router.js";
|
||||
import { RigTeardownOrchestrator } from "./domain/rig-teardown.js";
|
||||
import { ResumeMetadataRefresher } from "./domain/resume-metadata-refresher.js";
|
||||
import { observeClaudePaneStartedAt } from "./domain/native-process-lineage.js";
|
||||
import { observeClaudePaneStartedAt, listNativeProcessesOrThrow, listNativeProcesses } from "./domain/native-process-lineage.js";
|
||||
import { TranscriptStore } from "./domain/transcript-store.js";
|
||||
import { resumeRunningTranscriptCaptures, wireTranscriptCaptureStops } from "./domain/transcript-capture.js";
|
||||
import { probeSessionActivity, SessionTransport, inspectComposerInput, draftDeliveryAllows, readDraftDeliverySetting } from "./domain/session-transport.js";
|
||||
@@ -1417,7 +1417,9 @@ export async function createDaemon(opts?: DaemonOptions): Promise<DaemonResult>
|
||||
// #421 — the pane's current Claude process start time; a sidecar sampled earlier is not this
|
||||
// process's, so capture and null-fill skip it.
|
||||
const claudeProcessStartedAt = (sessionName: string) => observeClaudePaneStartedAt({ target: sessionName, tmux: tmuxAdapter });
|
||||
const resumeMetadataRefresher = new ResumeMetadataRefresher({ sessionRegistry, tmuxAdapter, contextUsageStore, claudeProcessStartedAt, codexHome: configuredCodexHome,
|
||||
const resumeMetadataRefresher = new ResumeMetadataRefresher({ sessionRegistry, tmuxAdapter, contextUsageStore, claudeProcessStartedAt,
|
||||
claudeStartedAtForPass: (pass) => (sessionName) => observeClaudePaneStartedAt({ target: sessionName, tmux: tmuxAdapter,
|
||||
listProcesses: pass.lister(listNativeProcessesOrThrow, listNativeProcesses) }), codexHome: configuredCodexHome,
|
||||
seatHome: (nodeId, runtime) => seatRuntimeHome(db, nodeId, runtime).home });
|
||||
const claimService = new ClaimService({
|
||||
db, rigRepo, sessionRegistry, discoveryRepo, eventBus, tmuxAdapter, transcriptStore,
|
||||
|
||||
@@ -4,7 +4,7 @@ import type { Database as DatabaseType } from "better-sqlite3";
|
||||
import { createFullTestDb } from "./helpers/test-app.js";
|
||||
import { SessionRegistry } from "../src/domain/session-registry.js";
|
||||
import { AppliedLaunchObservationStore } from "../src/domain/applied-launch-observation-store.js";
|
||||
import { observeClaudePermission } from "../src/domain/permission-drift.js";
|
||||
import { diagnoseRuntimePosture, observeClaudePermission, renderPermissionDriftSummary } from "../src/domain/permission-drift.js";
|
||||
|
||||
describe("AppliedLaunchObservationStore", () => {
|
||||
let db: DatabaseType;
|
||||
@@ -47,6 +47,23 @@ describe("AppliedLaunchObservationStore", () => {
|
||||
expect(db.prepare("SELECT COUNT(*) AS n FROM applied_launch_observations").get()).toEqual({ n: 1 });
|
||||
});
|
||||
|
||||
it("preserves an inconclusive Codex policy reason through storage and rendered status", () => {
|
||||
db.prepare("UPDATE nodes SET runtime = 'codex' WHERE id = 'node-1'").run();
|
||||
registry.registerSession("node-1", "dev-impl@r1");
|
||||
const generation = registry.currentOccupantTenure("node-1")!.generationUuid;
|
||||
const reason = "policy not verified: native read timed out";
|
||||
expect(store.recordGeneration(generation, { runtime: "codex", axis: "sandbox", state: "observed",
|
||||
value: "permissions:openrig-seat", reason })).toBe(true);
|
||||
const applied = store.readCurrent("node-1");
|
||||
expect(applied?.reason).toBe(reason);
|
||||
const diagnostic = diagnoseRuntimePosture({ runtime: "codex", cwd: "/work", applied,
|
||||
fs: { readFile: () => "", cwdReadable: () => true, commandAvailable: () => true, claudePermissionModes: () => null } });
|
||||
expect(diagnostic.enforcement).toMatchObject({ state: "unknown", reason });
|
||||
expect(renderPermissionDriftSummary(diagnostic)).toContain(reason);
|
||||
registry.mintOccupantTenure("node-1", "handover");
|
||||
expect(store.readCurrent("node-1")).toBeNull();
|
||||
});
|
||||
|
||||
it("never rebinds a delayed launch write onto a successor generation", () => {
|
||||
registry.registerSession("node-1", "dev-impl@r1");
|
||||
const launchedGeneration = registry.currentOccupantTenure("node-1")!.generationUuid;
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
// usage data short-circuit, send-failure no-dedup-update semantics.
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from "vitest";
|
||||
import { ClaudeCompactionEnforcer as ActualEnforcer, buildPostCompactRestorePrompt } from "../src/domain/claude-compaction-enforcer.js";
|
||||
import { ClaudeCompactionEnforcer as ActualEnforcer, MANUAL_SEAT_READ_INTERVAL_MS, buildPostCompactRestorePrompt } from "../src/domain/claude-compaction-enforcer.js";
|
||||
import { CAPTURE_READABLE_BUDGET_MS, SEND_READINESS_FRESHNESS_MS, type SessionTransport } from "../src/domain/session-transport.js";
|
||||
import type { ClaudeCompactionPolicy, SettingsStore } from "../src/domain/user-settings/settings-store.js";
|
||||
|
||||
@@ -1199,7 +1199,7 @@ describe("ClaudeCompactionEnforcer", () => {
|
||||
expect(enforcer.getManualCompactionState(SEAT)?.stage).toBe("preparing");
|
||||
|
||||
// DEGRADED duplicate: usedPercentage null (bad-sidecar projection). The guard
|
||||
// now PRECEDES the no_usage_data recordManualFailure path, so it must NOT record
|
||||
// PRECEDES every manual refusal, so it must NOT record
|
||||
// skipped-or-failed / erase the preparing marker (the bug rev1-r2 caught).
|
||||
const degraded = await enforcer.triggerManualCompact({ sessionName: SEAT, runtime: "claude-code", usedPercentage: null });
|
||||
expect(degraded).toEqual({ triggered: false, stage: "skipped-or-failed", reason: "already_in_progress" });
|
||||
@@ -1383,14 +1383,79 @@ describe("ClaudeCompactionEnforcer", () => {
|
||||
expect(enforcer.getManualCompactionState("codex@rig")?.stage).toBe("skipped-or-failed");
|
||||
});
|
||||
|
||||
it("no known usage sample → rejected with no_usage_data (never triggers blind)", async () => {
|
||||
it("no known usage sample: an explicit manual request still prepares and compacts; unknown usage isn't a reason to stop", async () => {
|
||||
const settings = makeSettingsStore(POLICY_ENABLED_AT_80);
|
||||
const { transport, send } = makeSessionTransport();
|
||||
const enforcer = new ClaudeCompactionEnforcer(settings, transport);
|
||||
const enforcer = new ClaudeCompactionEnforcer(settings, transport, { now: () => 1_700_000_000_000 });
|
||||
|
||||
const outcome = await enforcer.triggerManualCompact({ sessionName: SEAT, runtime: "claude-code", usedPercentage: null });
|
||||
expect(outcome).toEqual({ triggered: false, stage: "skipped-or-failed", reason: "no_usage_data" });
|
||||
expect(send).not.toHaveBeenCalled();
|
||||
expect(outcome).toEqual({ triggered: true, stage: "compact-sent" });
|
||||
const texts = send.mock.calls.map((call) => String(call[1]));
|
||||
expect(texts[0]).toContain("OpenRig manual compaction was requested for this seat");
|
||||
expect(texts[0]).not.toContain("null");
|
||||
expect(texts[1]).toMatch(/^\/compact /);
|
||||
});
|
||||
|
||||
it("the preparation request asks for a turn free of approval prompts: file-edit writes and a literal recap-write path", async () => {
|
||||
const settings = makeSettingsStore(POLICY_ENABLED_AT_80);
|
||||
const { transport, send } = makeSessionTransport();
|
||||
const enforcer = new ClaudeCompactionEnforcer(settings, transport, { now: () => 1_700_000_000_000 });
|
||||
await enforcer.triggerManualCompact({ sessionName: SEAT, runtime: "claude-code", usedPercentage: 20 });
|
||||
expect(String(send.mock.calls[0]![1])).toContain("To avoid one cause of approval prompts, which hold /compact until someone answers them: write files with your file-edit tool (acceptEdits covers your working directory, not a preparation root outside it), and if you publish a seat recap, run rig context recap-write --file with the file's literal absolute path, with no shell variable assignment or command substitution, so an allow rule for rig commands can match it.");
|
||||
});
|
||||
|
||||
it("when the idle wait and the /compact send disagree, each round pauses a reading interval, bounded by the deadline", async () => {
|
||||
const settings = makeSettingsStore(POLICY_ENABLED_AT_80);
|
||||
const { transport, send } = makeSessionTransport();
|
||||
// The idle wait reads idle (a hook), while every /compact finds the pane at a prompt and writes nothing.
|
||||
send.mockImplementation(async (_s: string, text: string) => text.startsWith("/compact")
|
||||
? { ok: false, sent: false, inputPhase: "not_reached", reason: "target_needs_input", activity: { state: "needs_input" } }
|
||||
: { ok: true });
|
||||
let clock = 1_700_000_000_000;
|
||||
const sleeps: number[] = [];
|
||||
const enforcer = new ClaudeCompactionEnforcer(settings, transport, { manualPrepWaitMs: 20_000, now: () => clock,
|
||||
sleep: async (ms) => { sleeps.push(ms); clock += ms; } });
|
||||
|
||||
const outcome = await enforcer.triggerManualCompact({ sessionName: SEAT, runtime: "claude-code", usedPercentage: 20 });
|
||||
expect(outcome).toMatchObject({ triggered: false, reason: "preparation_needs_input" });
|
||||
const compacts = send.mock.calls.filter((call) => String(call[1]).startsWith("/compact")).length;
|
||||
expect(compacts).toBeGreaterThan(1);
|
||||
expect(compacts).toBeLessThanOrEqual(20_000 / MANUAL_SEAT_READ_INTERVAL_MS + 1);
|
||||
// Every deferred send is followed by a pause, the last one running into the deadline.
|
||||
expect(sleeps.filter((ms) => ms === MANUAL_SEAT_READ_INTERVAL_MS).length).toBe(compacts);
|
||||
});
|
||||
|
||||
it("a /compact refused before input because the seat reached a prompt waits again within the deadline, then compacts", async () => {
|
||||
const settings = makeSettingsStore(POLICY_ENABLED_AT_80);
|
||||
const { transport, send } = makeSessionTransport();
|
||||
send.mockImplementationOnce(async () => ({ ok: true })); // the preparation request lands
|
||||
// The seat read idle, then its preparation turn reached a permission prompt before /compact: refused, nothing written.
|
||||
send.mockImplementationOnce(async () => ({ ok: false, sent: false, inputPhase: "not_reached", reason: "target_needs_input" }));
|
||||
const enforcer = new ClaudeCompactionEnforcer(settings, transport, { now: () => 1_700_000_000_000, sleep: async () => {} });
|
||||
|
||||
const outcome = await enforcer.triggerManualCompact({ sessionName: SEAT, runtime: "claude-code", usedPercentage: 20 });
|
||||
expect(outcome).toEqual({ triggered: true, stage: "compact-sent" });
|
||||
const texts = send.mock.calls.map((call) => String(call[1]));
|
||||
expect(texts.filter((text) => text.startsWith("/compact"))).toHaveLength(2);
|
||||
expect(enforcer.getPreparationState(SEAT)).toMatchObject({ status: "compact-sent" });
|
||||
});
|
||||
|
||||
it("a seat still at a prompt when the deadline passes stops naming the prompt, and --state showed what it waited on", async () => {
|
||||
const settings = makeSettingsStore(POLICY_ENABLED_AT_80);
|
||||
const { transport, send } = makeSessionTransport();
|
||||
let clock = 1_700_000_000_000;
|
||||
const enforcer = new ClaudeCompactionEnforcer(settings, transport, { manualPrepWaitMs: 1000, now: () => clock, sleep: async (ms) => { clock += ms; } });
|
||||
const seen: unknown[] = [];
|
||||
transport.waitUntilIdle = async () => {
|
||||
seen.push(enforcer.getPreparationState(SEAT)?.awaitingInput);
|
||||
return { ok: false, reason: "target_needs_input", error: "fixture", activity: { state: "needs_input" } as any, waitedMs: 0, attempts: 1 } as any;
|
||||
};
|
||||
|
||||
const outcome = await enforcer.triggerManualCompact({ sessionName: SEAT, runtime: "claude-code", usedPercentage: 20 });
|
||||
expect(outcome).toMatchObject({ triggered: false, stage: "skipped-or-failed", reason: "preparation_needs_input",
|
||||
preparation: { delivery: "delivered", compact: "not_sent" } });
|
||||
expect(seen.slice(1)).toContainEqual({ since: expect.any(Number), reason: "target_needs_input", observedAt: expect.any(Number), current: true });
|
||||
expect(send.mock.calls.filter((call) => String(call[1]).startsWith("/compact"))).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("bounded to the triggered seat: only that seat is sent to; no other seat gets manual state", async () => {
|
||||
|
||||
@@ -0,0 +1,557 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import os from "node:os";
|
||||
import type { CodexFilesystemPermissions } from "../src/domain/codex-member-permissions.js";
|
||||
import { decideCodexFilesystemPolicy, verifyCodexFilesystemPolicy } from "../src/domain/codex-filesystem-preflight.js";
|
||||
import { readCodexConfiguration } from "../src/domain/codex-network-default.js";
|
||||
|
||||
vi.mock("../src/domain/codex-network-default.js", () => ({ readCodexConfiguration: vi.fn() }));
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
const permissions: CodexFilesystemPermissions = {
|
||||
approval: "never", filesystem: { ":minimal": "read", "/work": "write", "/work/hidden": "deny" }, network_access: false,
|
||||
};
|
||||
function config() {
|
||||
return { config: { approval_policy: "never", default_permissions: "openrig-seat", sandbox_mode: null,
|
||||
sandbox_workspace_write: null, profile: null, permissions: { "openrig-seat": {
|
||||
description: null, extends: null, workspace_roots: null,
|
||||
filesystem: { "/work/hidden": "deny", "/work": "write", ":minimal": "read", glob_scan_max_depth: null },
|
||||
network: { enabled: false, allow_local_binding: null, allow_upstream_proxy: null,
|
||||
dangerously_allow_all_unix_sockets: null, dangerously_allow_non_loopback_proxy: null, domains: null,
|
||||
enable_socks5: null, enable_socks5_udp: null, mitm: null, mode: null, proxy_url: null, socks_url: null, unix_sockets: null },
|
||||
} } }, origins: {}, layers: [] };
|
||||
}
|
||||
function decide(configRead: unknown = config(), requirementsRead: unknown = { requirements: null }) {
|
||||
return decideCodexFilesystemPolicy({ permissions, configRead, requirementsRead });
|
||||
}
|
||||
|
||||
describe("Codex seat filesystem configuration preflight", () => {
|
||||
it("accepts the exact authored policy regardless of mapping key order", () => {
|
||||
expect(decide()).toEqual({ ok: true, verified: true });
|
||||
});
|
||||
|
||||
it("accepts the native nullable managed-policy response without overriding requirements", () => {
|
||||
expect(decide(config(), { requirements: { allowedApprovalPolicies: null, allowedApprovalsReviewers: null,
|
||||
allowedSandboxModes: null, allowedPermissionProfiles: null, defaultPermissions: null,
|
||||
featureRequirements: null, application: null, autoReview: null, network: null,
|
||||
futureFilesystemPolicy: null } })).toEqual({ ok: true, verified: true });
|
||||
});
|
||||
|
||||
it("allows other permission profiles in the shared home without selecting them", () => {
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions, { "other-seat": { filesystem: { ":root": "write" } } });
|
||||
expect(decide(read)).toEqual({ ok: true, verified: true });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["lower-layer extra write", { filesystem: { ...permissions.filesystem, "/poison": "write" }, network: { enabled: false } }],
|
||||
["changed deny", { filesystem: { ...permissions.filesystem, "/work/hidden": "read" }, network: { enabled: false } }],
|
||||
["missing deny", { filesystem: { ":minimal": "read", "/work": "write" }, network: { enabled: false } }],
|
||||
["network changed", { filesystem: permissions.filesystem, network: { enabled: true } }],
|
||||
["empty filesystem", { filesystem: {}, network: { enabled: false } }],
|
||||
])("refuses %s without disclosing its values", (_label, profile) => {
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions, { "openrig-seat": profile });
|
||||
expect(decide(read)).toMatchObject({ ok: false, error: expect.any(String) });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["wrong profile selection", { default_permissions: "other" }],
|
||||
["wrong approval", { approval_policy: "on-request" }],
|
||||
["missing profile map", { permissions: null }],
|
||||
])("refuses %s", (_label, patch) => {
|
||||
const read = config();
|
||||
Object.assign(read.config, patch);
|
||||
expect(decide(read)).toMatchObject({ ok: false });
|
||||
});
|
||||
|
||||
it.each([undefined, null, {}, { config: [] }])("reports missing or malformed configuration %#", read => {
|
||||
expect(decideCodexFilesystemPolicy({ permissions, configRead: read, requirementsRead: { requirements: null } })).toMatchObject({ ok: true, verified: false });
|
||||
});
|
||||
|
||||
it("accepts unrelated managed model settings and an approval allowlist that includes the choice", () => {
|
||||
expect(decide(config(), { requirements: { modelProvider: "openai", allowedApprovalPolicies: ["on-request", "never"],
|
||||
allowedPermissionProfiles: null, defaultPermissions: null, network: null, featureRequirements: null } })).toEqual({ ok: true, verified: true });
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ allowedApprovalPolicies: ["on-request"] },
|
||||
{ allowedPermissionProfiles: { "other": true } },
|
||||
{ allowedPermissionProfiles: { "openrig-seat": false } },
|
||||
])("does not bypass managed policy %#", requirements => {
|
||||
expect(decide(config(), { requirements })).toMatchObject({ ok: false });
|
||||
});
|
||||
|
||||
it.each([undefined, null, {}, { requirements: [] }, { requirements: null, futurePolicy: true }])("reports unreadable requirements %#", read => {
|
||||
expect(decideCodexFilesystemPolicy({ permissions, configRead: config(), requirementsRead: read })).toMatchObject({ ok: true, verified: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe("authored ancestor and selector coverage matrix", () => {
|
||||
const ancestors = {
|
||||
"root read": { "/": "read" },
|
||||
"root write": { "/": "write" },
|
||||
"root deny": { "/": "deny" },
|
||||
"native root deny": { ":root": "deny" },
|
||||
"literal read": { ":root": "read", "/work/hidden": "read" },
|
||||
"literal write": { ":root": "read", "/work/hidden": "write" },
|
||||
"literal deny": { ":root": "read", "/work": "write", "/work/hidden": "deny" },
|
||||
} satisfies Record<string, CodexFilesystemPermissions["filesystem"]>;
|
||||
type Outcome = "accept" | "not-verified" | "refuse";
|
||||
// Expected outcomes are authored from the rule, not computed by another
|
||||
// coverage comparator. Columns: read, write, read+aliases, write+aliases.
|
||||
// Authored uncertainty warns; lower-layer aliases cannot hide a known
|
||||
// widening. A non-root deny wins; a root deny is a refinable default.
|
||||
const matrix = [
|
||||
["root read", "none", "accept", "refuse", "not-verified", "refuse"],
|
||||
["root read", "read", "accept", "refuse", "not-verified", "refuse"],
|
||||
["root read", "write", "accept", "not-verified", "not-verified", "not-verified"],
|
||||
["root write", "none", "accept", "accept", "not-verified", "not-verified"],
|
||||
["root write", "read", "accept", "accept", "not-verified", "not-verified"],
|
||||
["root write", "write", "accept", "accept", "not-verified", "not-verified"],
|
||||
["root deny", "none", "refuse", "refuse", "refuse", "refuse"],
|
||||
["root deny", "read", "not-verified", "refuse", "not-verified", "refuse"],
|
||||
["root deny", "write", "not-verified", "not-verified", "not-verified", "not-verified"],
|
||||
["native root deny", "none", "refuse", "refuse", "refuse", "refuse"],
|
||||
["native root deny", "read", "not-verified", "refuse", "not-verified", "refuse"],
|
||||
["native root deny", "write", "not-verified", "not-verified", "not-verified", "not-verified"],
|
||||
["literal read", "none", "accept", "refuse", "not-verified", "refuse"],
|
||||
["literal read", "read", "accept", "refuse", "not-verified", "refuse"],
|
||||
["literal read", "write", "accept", "not-verified", "not-verified", "not-verified"],
|
||||
["literal write", "none", "accept", "accept", "not-verified", "not-verified"],
|
||||
["literal write", "read", "accept", "accept", "not-verified", "not-verified"],
|
||||
["literal write", "write", "accept", "accept", "not-verified", "not-verified"],
|
||||
["literal deny", "none", "refuse", "refuse", "refuse", "refuse"],
|
||||
["literal deny", "read", "refuse", "refuse", "refuse", "refuse"],
|
||||
["literal deny", "write", "refuse", "refuse", "refuse", "refuse"],
|
||||
] satisfies [keyof typeof ancestors, "none" | "read" | "write", Outcome, Outcome, Outcome, Outcome][];
|
||||
const cases = matrix.flatMap(([ancestor, selector, read, write, readAliases, writeAliases]) => [
|
||||
{ ancestor, selector, grant: "read", aliases: false, outcome: read },
|
||||
{ ancestor, selector, grant: "write", aliases: false, outcome: write },
|
||||
{ ancestor, selector, grant: "read", aliases: true, outcome: readAliases },
|
||||
{ ancestor, selector, grant: "write", aliases: true, outcome: writeAliases },
|
||||
]);
|
||||
it.each(cases)("$ancestor; selector=$selector; grant=$grant; aliases=$aliases => $outcome", ({ ancestor, selector, grant, aliases, outcome }) => {
|
||||
const own: CodexFilesystemPermissions = { ...permissions, filesystem: {
|
||||
...ancestors[ancestor], ...(selector === "none" ? {} : { ":workspace_roots": selector }),
|
||||
} };
|
||||
const aliasAccess = selector === "none" ? "read" : selector;
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions, { "openrig-seat": { filesystem: {
|
||||
...own.filesystem, ...(aliases ? { ":workspace_roots": aliasAccess, ":project_roots": aliasAccess } : {}),
|
||||
"/work/hidden/secret": grant,
|
||||
}, network: { enabled: false } } });
|
||||
const result = decideCodexFilesystemPolicy({ permissions: own, configRead: read, requirementsRead: { requirements: null } });
|
||||
if (outcome === "refuse") expect(result).toMatchObject({ ok: false, error: expect.stringContaining('"/work/hidden/secret"') });
|
||||
else if (outcome === "not-verified") expect(result).toMatchObject({ ok: true, verified: false });
|
||||
else expect(result).toEqual({ ok: true, verified: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe("root deny refinements", () => {
|
||||
it.each(["/", ":root"])('keeps selector overlap unverified beneath %s deny', root => {
|
||||
const own: CodexFilesystemPermissions = { ...permissions, filesystem: { [root]: "deny", ":slash_tmp": "write" } };
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions, { "openrig-seat": { filesystem: { ...own.filesystem, "/tmp/child": "write" }, network: { enabled: false } } });
|
||||
expect(decideCodexFilesystemPolicy({ permissions: own, configRead: read, requirementsRead: { requirements: null } }))
|
||||
.toMatchObject({ ok: true, verified: false });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["/", "/Users/x/.ssh/key"], [":root", "/Users/x/.ssh/key"],
|
||||
["/", "/home/x/.ssh/key"], [":root", "/home/x/.ssh/key"],
|
||||
])('refuses a user-data read outside minimal defaults beneath %s deny at %s', (root, key) => {
|
||||
const own: CodexFilesystemPermissions = { ...permissions, filesystem: { [root]: "deny", ":minimal": "read", "/work": "write" } };
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions, { "openrig-seat": { filesystem: { ...own.filesystem, [key]: "read" }, network: { enabled: false } } });
|
||||
expect(decideCodexFilesystemPolicy({ permissions: own, configRead: read, requirementsRead: { requirements: null } }))
|
||||
.toMatchObject({ ok: false, error: expect.stringContaining(JSON.stringify(key)) });
|
||||
});
|
||||
|
||||
it.each(["/", ":root"])('does not claim to expand minimal system reads beneath %s deny', root => {
|
||||
const own: CodexFilesystemPermissions = { ...permissions, filesystem: { [root]: "deny", ":minimal": "read" } };
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions, { "openrig-seat": { filesystem: { ...own.filesystem, "/usr/bin/tool": "read" }, network: { enabled: false } } });
|
||||
expect(decideCodexFilesystemPolicy({ permissions: own, configRead: read, requirementsRead: { requirements: null } }))
|
||||
.toMatchObject({ ok: true, verified: false });
|
||||
});
|
||||
|
||||
it.each(["/", ":root"])('retains other authored coverage for user data beneath %s deny', root => {
|
||||
const key = "/Users/x/.ssh/key";
|
||||
for (const [rule, expected] of [[":workspace_roots", "not-verified"], ["/Users/x", "accept"]] as const) {
|
||||
const own: CodexFilesystemPermissions = { ...permissions, filesystem: { [root]: "deny", ":minimal": "read", [rule]: "read" } };
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions, { "openrig-seat": { filesystem: { ...own.filesystem, [key]: "read" }, network: { enabled: false } } });
|
||||
const result = decideCodexFilesystemPolicy({ permissions: own, configRead: read, requirementsRead: { requirements: null } });
|
||||
if (expected === "accept") expect(result).toEqual({ ok: true, verified: true });
|
||||
else expect(result).toMatchObject({ ok: true, verified: false });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("minimal coverage without an authored root rule", () => {
|
||||
it.each(["/Users/x/.ssh/key", "/users/x/.ssh/key", "/HOME/x/.ssh/key"])("refuses an uncovered user-data read at %s", key => {
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions["openrig-seat"].filesystem, { [key]: "read" });
|
||||
const result = decide(read);
|
||||
expect(result).toMatchObject({ ok: false, error: expect.stringContaining(JSON.stringify(key)) });
|
||||
if (!result.ok) expect(result.error).toContain("Fix:");
|
||||
});
|
||||
|
||||
it("keeps an unexpanded system read unverified and names its key", () => {
|
||||
const key = "/opt/x";
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions["openrig-seat"].filesystem, { [key]: "read" });
|
||||
expect(decide(read)).toMatchObject({ ok: true, verified: false, reason: expect.stringContaining(JSON.stringify(key)) });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Codex seat filesystem verifier reader boundary", () => {
|
||||
it.each([["env", "CODEX_HOME=/other"], ["custom-wrapper"]])("reports a launch wrapper without certifying a different configuration %#", async launchWrapper => {
|
||||
vi.mocked(readCodexConfiguration).mockClear();
|
||||
expect(await verifyCodexFilesystemPolicy({ permissions, cwd: "/work", codexHome: "/account", launchWrapper }))
|
||||
.toMatchObject({ ok: true, verified: false, reason: expect.stringContaining("launch_wrapper") });
|
||||
expect(readCodexConfiguration).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["", "relative/home", "/absolute\nother"])("reports an unestablished account home %# before reading", async codexHome => {
|
||||
vi.mocked(readCodexConfiguration).mockClear();
|
||||
expect(await verifyCodexFilesystemPolicy({ permissions, cwd: "/work", codexHome })).toMatchObject({ ok: true, verified: false });
|
||||
expect(readCodexConfiguration).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the seat home and candidate invocation policy, never sandbox or per-command selection overrides", async () => {
|
||||
vi.mocked(readCodexConfiguration).mockResolvedValueOnce({ ok: true, configRead: config(), requirementsRead: { requirements: null } });
|
||||
expect(await verifyCodexFilesystemPolicy({ permissions, cwd: "/work", codexHome: "/account", launchPath: "/bin" })).toEqual({ ok: true, verified: true });
|
||||
expect(readCodexConfiguration).toHaveBeenLastCalledWith({ cwd: "/work", codexHome: "/account", launchPath: "/bin", args: [
|
||||
"-c", 'approval_policy="never"', "-c", 'default_permissions="openrig-seat"', "-c",
|
||||
'permissions={"openrig-seat"={filesystem={":minimal"="read","/work"="write","/work/hidden"="deny"},network={enabled=false}}}',
|
||||
"-c", "features.plugins=false", "-c", "features.apps=false",
|
||||
] });
|
||||
});
|
||||
|
||||
it("returns an unavailable read as unverified", async () => {
|
||||
vi.mocked(readCodexConfiguration).mockResolvedValueOnce({ ok: false, reason: "native read timed out" });
|
||||
expect(await verifyCodexFilesystemPolicy({ permissions, cwd: "/work", codexHome: "/account" })).toMatchObject({ ok: true, verified: false });
|
||||
});
|
||||
|
||||
it("names the filesystem rule, access on each side and a remedy without dumping configuration", () => {
|
||||
const read = config();
|
||||
read.config.permissions["openrig-seat"].filesystem["/work/hidden"] = "read";
|
||||
Object.assign(read.config, { privateSetting: "do-not-print-this-value" });
|
||||
expect(decide(read)).toMatchObject({ ok: false, error: expect.stringMatching(/\/work\/hidden.*agent.*deny.*(?:Codex|layer).*read/i) });
|
||||
const decision = decide(read);
|
||||
if (decision.ok) throw new Error("fixture must conflict");
|
||||
expect(decision.error).toContain("\nFix:");
|
||||
expect(decision.error).not.toContain("do-not-print-this-value");
|
||||
read.config.default_permissions = "private-profile-selection";
|
||||
const selection = decide(read);
|
||||
if (selection.ok) throw new Error("fixture must conflict");
|
||||
expect(selection.error).toContain("default_permissions");
|
||||
expect(selection.error).toContain("\nFix:");
|
||||
expect(selection.error).not.toContain("private-profile-selection");
|
||||
});
|
||||
|
||||
it("returns a thrown reader failure without exposing arbitrary error contents", async () => {
|
||||
vi.mocked(readCodexConfiguration).mockRejectedValueOnce(new Error("do not print this"));
|
||||
expect(await verifyCodexFilesystemPolicy({ permissions, cwd: "/work", codexHome: "/account" })).toEqual({
|
||||
ok: true, verified: false, reason: "Native Codex configuration reader failed",
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves the normal account home without an explicit CODEX_HOME", async () => {
|
||||
vi.stubEnv("CODEX_HOME", undefined);
|
||||
vi.mocked(readCodexConfiguration).mockResolvedValueOnce({ ok: true, configRead: config(), requirementsRead: { requirements: null } });
|
||||
expect(await verifyCodexFilesystemPolicy({ permissions, cwd: "/work" })).toEqual({ ok: true, verified: true });
|
||||
expect(readCodexConfiguration).toHaveBeenLastCalledWith(expect.objectContaining({ codexHome: `${os.homedir()}/.codex` }));
|
||||
});
|
||||
|
||||
it("keeps a named profile unverified instead of certifying the base configuration", async () => {
|
||||
vi.mocked(readCodexConfiguration).mockClear();
|
||||
expect(await verifyCodexFilesystemPolicy({ permissions, cwd: "/work", codexHome: "/account", codexConfigProfile: "model-only" }))
|
||||
.toMatchObject({ ok: true, verified: false, reason: expect.stringContaining("codex_config_profile") });
|
||||
expect(readCodexConfiguration).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("compatible policies and inconclusive reads", () => {
|
||||
it.each([":root", ":minimal"])(
|
||||
"refuses a known extra write grant at %s, including beside an unfamiliar representation", key => {
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions["openrig-seat"].filesystem, { [key]: "write", future: { access: "future" } });
|
||||
expect(decide(read)).toMatchObject({ ok: false });
|
||||
});
|
||||
|
||||
it("refuses full-root read beyond minimal read", () => {
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions["openrig-seat"].filesystem, { ":root": "read" });
|
||||
expect(decide(read)).toMatchObject({ ok: false });
|
||||
});
|
||||
|
||||
it.each([":workspace_roots", ":project_roots", ":tmpdir", ":slash_tmp", "~/x"])(
|
||||
"leaves extra %s coverage unverified when an authored path may already cover it", key => {
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions["openrig-seat"].filesystem, { [key]: "write" });
|
||||
expect(decide(read)).toMatchObject({ ok: true, verified: false });
|
||||
});
|
||||
|
||||
it("does not refuse a potentially redundant slash_tmp grant beside an authored /tmp grant", () => {
|
||||
const own = { ...permissions, filesystem: { ":root": "read", "/tmp": "write" } } satisfies CodexFilesystemPermissions;
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions, { "openrig-seat": { filesystem: { ...own.filesystem, ":slash_tmp": "write" }, network: { enabled: false } } });
|
||||
expect(decideCodexFilesystemPolicy({ permissions: own, configRead: read, requirementsRead: { requirements: null } }))
|
||||
.toMatchObject({ ok: true, verified: false });
|
||||
});
|
||||
|
||||
it("still refuses a selector write when no authored rule could cover write access", () => {
|
||||
const own = { ...permissions, filesystem: { ":root": "read" } } satisfies CodexFilesystemPermissions;
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions, { "openrig-seat": { filesystem: { ...own.filesystem, ":slash_tmp": "write" }, network: { enabled: false } } });
|
||||
expect(decideCodexFilesystemPolicy({ permissions: own, configRead: read, requirementsRead: { requirements: null } }))
|
||||
.toMatchObject({ ok: false });
|
||||
});
|
||||
|
||||
it("does not invent a selector conflict by collapsing ambiguous coverage aliases", () => {
|
||||
const own = { ...permissions, filesystem: { ":root": "read", ":project_roots": "write", ":workspace_roots": "deny" } } satisfies CodexFilesystemPermissions;
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions, { "openrig-seat": { filesystem: { ...own.filesystem, ":tmpdir": "write" }, network: { enabled: false } } });
|
||||
expect(decideCodexFilesystemPolicy({ permissions: own, configRead: read, requirementsRead: { requirements: null } }))
|
||||
.toMatchObject({ ok: true, verified: false, reason: expect.stringContaining("effective configuration grants") });
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ ":workspace_roots": "read", ":project_roots": "read" },
|
||||
{ ":project_roots": "read", ":workspace_roots": "read" },
|
||||
])("refuses an outside write despite lower-layer duplicate aliases %#", aliases => {
|
||||
const own = { ...permissions, filesystem: { ":root": "read", "/work": "write" } } satisfies CodexFilesystemPermissions;
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions, { "openrig-seat": { filesystem: { ...own.filesystem, ...aliases, "/outside": "write" }, network: { enabled: false } } });
|
||||
expect(decideCodexFilesystemPolicy({ permissions: own, configRead: read, requirementsRead: { requirements: null } }))
|
||||
.toMatchObject({ ok: false, error: expect.stringContaining('"/outside"') });
|
||||
});
|
||||
|
||||
it("leaves only the lower-layer duplicate aliases unverified when there is no separate conflict", () => {
|
||||
const own = { ...permissions, filesystem: { ":root": "read", "/work": "write" } } satisfies CodexFilesystemPermissions;
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions, { "openrig-seat": { filesystem: { ...own.filesystem,
|
||||
":workspace_roots": "read", ":project_roots": "read" }, network: { enabled: false } } });
|
||||
expect(decideCodexFilesystemPolicy({ permissions: own, configRead: read, requirementsRead: { requirements: null } }))
|
||||
.toMatchObject({ ok: true, verified: false });
|
||||
});
|
||||
|
||||
it("leaves an extra absolute rule unverified when a native selector may cover it", () => {
|
||||
const own = { ...permissions, filesystem: { ":root": "read", ":tmpdir": "write" } } satisfies CodexFilesystemPermissions;
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions, { "openrig-seat": { filesystem: { ...own.filesystem, "/tmp/child": "write" }, network: { enabled: false } } });
|
||||
expect(decideCodexFilesystemPolicy({ permissions: own, configRead: read, requirementsRead: { requirements: null } }))
|
||||
.toMatchObject({ ok: true, verified: false });
|
||||
const literal = { ...permissions, filesystem: { ":root": "read", "/work": "write" } } satisfies CodexFilesystemPermissions;
|
||||
Object.assign(read.config.permissions, { "openrig-seat": { filesystem: { ...literal.filesystem, "/outside": "write" }, network: { enabled: false } } });
|
||||
expect(decideCodexFilesystemPolicy({ permissions: literal, configRead: read, requirementsRead: { requirements: null } }))
|
||||
.toMatchObject({ ok: false });
|
||||
});
|
||||
|
||||
it("checks authored selectors before refusing a write beneath a read-only literal ancestor", () => {
|
||||
const own = { ...permissions, filesystem: { "/": "read", ":slash_tmp": "write" } } satisfies CodexFilesystemPermissions;
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions, { "openrig-seat": { filesystem: { ...own.filesystem, "/tmp/child": "write" }, network: { enabled: false } } });
|
||||
const result = decideCodexFilesystemPolicy({ permissions: own, configRead: read, requirementsRead: { requirements: null } });
|
||||
expect(result).toMatchObject({ ok: true, verified: false, reason: expect.stringContaining('"/tmp/child"') });
|
||||
expect(result).toMatchObject({ reason: expect.stringContaining("write") });
|
||||
});
|
||||
|
||||
it("still refuses a direct literal-root widening beside an authored selector", () => {
|
||||
const own = { ...permissions, filesystem: { "/": "read", ":slash_tmp": "write" } } satisfies CodexFilesystemPermissions;
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions, { "openrig-seat": { filesystem: { ...own.filesystem, "/": "write" }, network: { enabled: false } } });
|
||||
expect(decideCodexFilesystemPolicy({ permissions: own, configRead: read, requirementsRead: { requirements: null } }))
|
||||
.toMatchObject({ ok: false, error: expect.stringContaining('"/"') });
|
||||
});
|
||||
|
||||
it("refuses a read beneath the fixture's authored deny despite minimal read coverage", () => {
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions["openrig-seat"].filesystem, { "/work/hidden/secret": "read" });
|
||||
expect(decide(read)).toMatchObject({ ok: false, error: expect.stringContaining('"/work/hidden/secret"') });
|
||||
});
|
||||
|
||||
it("refuses a write beneath an authored deny despite an authored write selector", () => {
|
||||
const own = { ...permissions, filesystem: { ...permissions.filesystem, ":workspace_roots": "write" } } satisfies CodexFilesystemPermissions;
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions, { "openrig-seat": { filesystem: { ...own.filesystem, "/work/hidden/secret": "write" }, network: { enabled: false } } });
|
||||
expect(decideCodexFilesystemPolicy({ permissions: own, configRead: read, requirementsRead: { requirements: null } }))
|
||||
.toMatchObject({ ok: false, error: expect.stringContaining('"/work/hidden/secret"') });
|
||||
});
|
||||
|
||||
it("names the extra selector and access in an inconclusive coverage warning", () => {
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions["openrig-seat"].filesystem, { ":slash_tmp": "write" });
|
||||
const result = decide(read);
|
||||
expect(result).toMatchObject({ ok: true, verified: false, reason: expect.stringContaining('":slash_tmp"') });
|
||||
expect(result).toMatchObject({ reason: expect.stringContaining("write") });
|
||||
});
|
||||
|
||||
it.each(["never", "on-request"] satisfies CodexFilesystemPermissions["approval"][])(
|
||||
"reports an unfamiliar approval string as unverified for authored %s", approval => {
|
||||
const read = config();
|
||||
read.config.approval_policy = "future-native-approval";
|
||||
expect(decideCodexFilesystemPolicy({ permissions: { ...permissions, approval }, configRead: read, requirementsRead: { requirements: null } }))
|
||||
.toMatchObject({ ok: true, verified: false, reason: expect.stringContaining("approval") });
|
||||
});
|
||||
|
||||
it("still refuses a recognized untrusted approval instead of treating it as a future spelling", () => {
|
||||
const read = config();
|
||||
read.config.approval_policy = "untrusted";
|
||||
expect(decide(read)).toMatchObject({ ok: false, error: expect.stringContaining("approval_policy") });
|
||||
});
|
||||
|
||||
it("does not let an unfamiliar approval hide a known filesystem or network conflict", () => {
|
||||
const read = config();
|
||||
read.config.approval_policy = "future-native-approval";
|
||||
Object.assign(read.config.permissions["openrig-seat"].filesystem, { "/outside": "write" });
|
||||
expect(decide(read)).toMatchObject({ ok: false, error: expect.stringContaining('"/outside"') });
|
||||
Object.assign(read.config.permissions["openrig-seat"], { filesystem: permissions.filesystem, network: { enabled: true } });
|
||||
expect(decide(read)).toMatchObject({ ok: false, error: expect.stringContaining("network.enabled") });
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ allowedApprovalPolicies: ["on-request"] },
|
||||
{ allowedPermissionProfiles: { "openrig-seat": false } },
|
||||
])("reports an excluding managed allowlist ahead of effective selection or approval mismatches %#", requirements => {
|
||||
const read = config();
|
||||
Object.assign(read.config, { default_permissions: "other", approval_policy: "on-request" });
|
||||
expect(decide(read, { requirements })).toMatchObject({ ok: false, error: expect.stringContaining("managed allowlist") });
|
||||
read.config.default_permissions = "openrig-seat";
|
||||
expect(decide(read, { requirements })).toMatchObject({ ok: false, error: expect.stringContaining("managed allowlist") });
|
||||
});
|
||||
|
||||
it.each(["default_permissions", "approval_policy"])("reports absent or null %s without inventing a conflict", key => {
|
||||
for (const value of [undefined, null]) {
|
||||
const read = config();
|
||||
Object.assign(read.config, { [key]: value });
|
||||
expect(decide(read)).toMatchObject({ ok: true, verified: false });
|
||||
}
|
||||
});
|
||||
|
||||
it("reports a new profile representation without a filesystem field but keeps independent conflicts", () => {
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions, { "openrig-seat": { futureFilesystem: { access: "new-format" }, network: { enabled: false } } });
|
||||
expect(decide(read)).toMatchObject({ ok: true, verified: false });
|
||||
read.config.permissions["openrig-seat"].network.enabled = true;
|
||||
expect(decide(read)).toMatchObject({ ok: false });
|
||||
});
|
||||
|
||||
it("accepts an allowed effective selection even when the managed fallback selects another profile", () => {
|
||||
expect(decide(config(), { requirements: { defaultPermissions: "private-fallback-value",
|
||||
allowedPermissionProfiles: { "openrig-seat": true } } })).toEqual({ ok: true, verified: true });
|
||||
});
|
||||
|
||||
it("accepts a known selector grant already covered by an authored full-root grant", () => {
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions["openrig-seat"].filesystem, { ":root": "write", ":workspace_roots": "write", "~/x": "read" });
|
||||
expect(decideCodexFilesystemPolicy({ permissions: { ...permissions, filesystem: { ...permissions.filesystem, ":root": "write" } },
|
||||
configRead: read, requirementsRead: { requirements: null } })).toEqual({ ok: true, verified: true });
|
||||
});
|
||||
|
||||
it.each(["default_permissions", "approval_policy"])("reports a future %s representation without inventing a conflict", key => {
|
||||
const read = config();
|
||||
Object.assign(read.config, { [key]: { selection: "future-native-format" } });
|
||||
expect(decide(read)).toMatchObject({ ok: true, verified: false });
|
||||
});
|
||||
|
||||
it("refuses an explicitly excluded profile even beside unknown allowlist entries", () => {
|
||||
expect(decide(config(), { requirements: { allowedPermissionProfiles: { "openrig-seat": false, future: { allowed: true } } } }))
|
||||
.toMatchObject({ ok: false });
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ filesystem: permissions.filesystem, network: { enabled: false }, extends: ":workspace" },
|
||||
{ filesystem: permissions.filesystem, network: { enabled: false }, workspace_roots: { "/extra": true } },
|
||||
{ filesystem: permissions.filesystem, network: { enabled: false }, futurePolicy: true },
|
||||
{ filesystem: permissions.filesystem, network: { enabled: false, allow_local_binding: true } },
|
||||
{ filesystem: { ":workspace_roots": { ".": "write" } }, network: { enabled: false } },
|
||||
{ filesystem: { "/work": "allow" }, network: { enabled: false } },
|
||||
])("reports unfamiliar selected policy options %#", profile => {
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions, { "openrig-seat": profile });
|
||||
expect(decide(read)).toMatchObject({ ok: true, verified: false });
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ allowedApprovalPolicies: "never" }, { featureRequirements: { use_linux_sandbox_bwrap: false } },
|
||||
{ network: {} }, { futureFilesystemPolicy: true },
|
||||
])("reports unsupported requirements without refusing %#", requirements => {
|
||||
expect(decide(config(), { requirements })).toMatchObject({ ok: true, verified: false });
|
||||
});
|
||||
|
||||
it("keeps positive configuration and managed conflicts visible alongside unknowns", () => {
|
||||
const read = config();
|
||||
read.config.default_permissions = "other";
|
||||
expect(decide(read, { requirements: { futureManagedPolicy: true } })).toMatchObject({ ok: false });
|
||||
expect(decide(config(), { requirements: { futureManagedPolicy: true, allowedApprovalPolicies: ["on-request"] } }))
|
||||
.toMatchObject({ ok: false });
|
||||
expect(decideCodexFilesystemPolicy({ permissions, configRead: null, requirementsRead: { requirements: { allowedPermissionProfiles: { "openrig-seat": false } } } }))
|
||||
.toMatchObject({ ok: false });
|
||||
});
|
||||
|
||||
it("accepts inert legacy settings, a model-only profile and harmless descriptions", () => {
|
||||
const read = config();
|
||||
Object.assign(read.config, { sandbox_mode: "read-only", sandbox_workspace_write: { network_access: true }, profile: "model-only" });
|
||||
Object.assign(read.config.permissions["openrig-seat"], { description: "description only" });
|
||||
expect(decide(read)).toEqual({ ok: true, verified: true });
|
||||
});
|
||||
|
||||
it("treats every null profile field as absent, including future fields", () => {
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions["openrig-seat"], { futureProfile: null });
|
||||
Object.assign(read.config.permissions["openrig-seat"].filesystem, { futureFilesystem: null });
|
||||
Object.assign(read.config.permissions["openrig-seat"].network, { futureNetwork: null });
|
||||
expect(decide(read)).toEqual({ ok: true, verified: true });
|
||||
});
|
||||
|
||||
it("accepts a narrower filesystem policy and redundant subpath grants", () => {
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions["openrig-seat"].filesystem, { "/work": "read", "/work/child": "read" });
|
||||
expect(decide(read)).toEqual({ ok: true, verified: true });
|
||||
});
|
||||
|
||||
it("accepts matching managed selection and allowlists", () => {
|
||||
expect(decide(config(), { requirements: { defaultPermissions: "openrig-seat",
|
||||
allowedPermissionProfiles: { "openrig-seat": true }, allowedApprovalPolicies: ["on-request", "never"],
|
||||
allowedSandboxModes: ["read-only"] } })).toEqual({ ok: true, verified: true });
|
||||
});
|
||||
|
||||
it("compares the project_roots alias without silently collapsing conflicting spellings", () => {
|
||||
const withAlias: CodexFilesystemPermissions = { approval: "never", filesystem: { ":project_roots": "write" } };
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions, { "openrig-seat": { filesystem: { ":workspace_roots": "write" }, network: { enabled: false } } });
|
||||
expect(decideCodexFilesystemPolicy({ permissions: withAlias, configRead: read, requirementsRead: { requirements: null } }))
|
||||
.toEqual({ ok: true, verified: true });
|
||||
expect(decideCodexFilesystemPolicy({ permissions: { ...withAlias, filesystem: { ":workspace_roots": "deny", ":project_roots": "write" } },
|
||||
configRead: read, requirementsRead: { requirements: null } })).toMatchObject({ ok: true, verified: false });
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ configRead: null, requirementsRead: { requirements: null } },
|
||||
{ configRead: config(), requirementsRead: { requirements: [] } },
|
||||
{ configRead: config(), requirementsRead: { requirements: { futureManagedPolicy: true } } },
|
||||
])("reports an unreadable shape or unknown requirement without refusing %#", request => {
|
||||
expect(decideCodexFilesystemPolicy({ permissions, ...request })).toMatchObject({ ok: true, verified: false, reason: expect.any(String) });
|
||||
});
|
||||
|
||||
it.each(["future-access", { read: ["/nested"] }])("reports unfamiliar filesystem representation without refusing %j", access => {
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions["openrig-seat"].filesystem, { "/work/hidden": access });
|
||||
expect(decide(read)).toMatchObject({ ok: true, verified: false });
|
||||
});
|
||||
|
||||
it("still refuses a concrete extra write grant alongside an unfamiliar representation", () => {
|
||||
const read = config();
|
||||
Object.assign(read.config.permissions["openrig-seat"].filesystem, { "/poison": "write", "/future": { read: ["/nested"] } });
|
||||
expect(decide(read)).toMatchObject({ ok: false });
|
||||
});
|
||||
|
||||
it("reports a reader timeout without dropping or replacing the invocation policy", async () => {
|
||||
vi.mocked(readCodexConfiguration).mockResolvedValueOnce({ ok: false, reason: "native read timed out" });
|
||||
expect(await verifyCodexFilesystemPolicy({ permissions, cwd: "/work", codexHome: "/account" }))
|
||||
.toMatchObject({ ok: true, verified: false, reason: expect.stringContaining("timed out") });
|
||||
});
|
||||
});
|
||||
@@ -82,6 +82,71 @@ describe("the typed Codex envelope", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("a seat's explicit filesystem policy", () => {
|
||||
it("accepts the native project_roots alias without changing its authored spelling", () => {
|
||||
expect(validateCodexMemberPermissions({ approval: "never", filesystem: { ":project_roots": "write" } }))
|
||||
.toEqual({ approval: "never", filesystem: { ":project_roots": "write" }, network_access: false });
|
||||
});
|
||||
const policy = { approval: "never", filesystem: {
|
||||
":minimal": "read", ":workspace_roots": "read", "/lease/a": "write", "/lease/a/private": "deny",
|
||||
}, network_access: false };
|
||||
|
||||
it("accepts native read, write and deny entries without a legacy sandbox selection", () => {
|
||||
expect(validateCodexMemberPermissions(policy)).toEqual(policy);
|
||||
expect(validateCodexMemberPermissions({ approval: "on-request", filesystem: { ":minimal": "read" } }))
|
||||
.toEqual({ approval: "on-request", filesystem: { ":minimal": "read" }, network_access: false });
|
||||
});
|
||||
|
||||
it("keeps two seats' filesystem choices separate and clears only the selected seat", async () => {
|
||||
const f = fixture();
|
||||
const other = { approval: "on-request", filesystem: { ":minimal": "read", "/lease/b": "write" }, network_access: false };
|
||||
expect(await f.service.setPermissions(set(policy))).toMatchObject({ ok: true, to: policy });
|
||||
expect(await f.service.setPermissions({ ...set(other), seatRef: "dev-b@codex-team" })).toMatchObject({ ok: true, to: other });
|
||||
const store = new NativePermissionStore(f.db);
|
||||
expect(store.launchOverride(f.a.id, "codex").codexPermissions).toEqual(policy);
|
||||
expect(store.launchOverride(f.b.id, "codex").codexPermissions).toEqual(other);
|
||||
expect(await f.service.setPermissions({ seatRef: "dev-a@codex-team", mode: "inherit", actor: "operator@codex-team", reason: "Clear only A" }))
|
||||
.toMatchObject({ ok: true });
|
||||
expect(readCodexMemberPermissions(f.db, f.a.id)).toBeUndefined();
|
||||
expect(store.launchOverride(f.b.id, "codex").codexPermissions).toEqual(other);
|
||||
});
|
||||
|
||||
it("allows named-profile combinations in either setter direction and keeps the authored policy", async () => {
|
||||
const f = fixture();
|
||||
await f.service.setPermissions(set(reader));
|
||||
expect(await f.service.setPermissions({ seatRef: "dev-a@codex-team", codexProfile: "named", actor: "operator@codex-team", reason: "Select" }))
|
||||
.toMatchObject({ ok: true });
|
||||
expect(await f.service.setPermissions(set(policy))).toMatchObject({ ok: true });
|
||||
expect(readCodexMemberPermissions(f.db, f.a.id)).toEqual(policy);
|
||||
expect(await f.service.setPermissions({ seatRef: "dev-a@codex-team", codexProfile: "inherit", actor: "operator@codex-team", reason: "Clear" }))
|
||||
.toMatchObject({ ok: true });
|
||||
expect(await f.service.setPermissions(set(policy))).toMatchObject({ ok: true });
|
||||
expect(await f.service.setPermissions({ seatRef: "dev-a@codex-team", codexProfile: "named", actor: "operator@codex-team", reason: "Conflict" }))
|
||||
.toMatchObject({ ok: true });
|
||||
expect(readCodexMemberPermissions(f.db, f.a.id)).toEqual(policy);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ ...policy, approval: "untrusted" },
|
||||
{ ...policy, sandbox: "workspace-write" },
|
||||
{ ...policy, writable_roots: ["/another/root"] },
|
||||
{ ...policy, exclude_slash_tmp: true },
|
||||
{ ...policy, filesystem: {} },
|
||||
{ ...policy, filesystem: { "relative/path": "deny" } },
|
||||
{ ...policy, filesystem: { ":unknown": "write" } },
|
||||
{ ...policy, filesystem: { "/a\nb": "deny" } },
|
||||
{ ...policy, filesystem: { "/private": "none" } },
|
||||
{ ...policy, filesystem: { "/private": true } },
|
||||
{ ...policy, network_access: "yes" },
|
||||
])("rejects incomplete or mixed policy without replacing a saved choice: %j", async (invalid) => {
|
||||
expect(() => validateCodexMemberPermissions(invalid)).toThrow();
|
||||
const f = fixture();
|
||||
expect(await f.service.setPermissions(set(reader))).toMatchObject({ ok: true });
|
||||
expect(await f.service.setPermissions(set(invalid))).toMatchObject({ ok: false });
|
||||
expect(readCodexMemberPermissions(f.db, f.a.id)).toEqual(reader);
|
||||
});
|
||||
});
|
||||
|
||||
describe("a Codex seat's current envelope (offline, no native enforcement claim)", () => {
|
||||
it("gives two seats in one folder their own envelopes, as the seat's explicit choice", async () => {
|
||||
const f = fixture();
|
||||
@@ -249,7 +314,7 @@ describe("a Codex seat's current profile", () => {
|
||||
});
|
||||
|
||||
describe("both writers: the spec at creation, the setter afterwards, every launch reading the seat's record", () => {
|
||||
const authored = (profile: string, permissions?: CodexMemberPermissions) => ({ version: "0.2", name: "authored", pods: [{ id: "dev", label: "Dev", members: [
|
||||
const authored = (profile: string | undefined, permissions?: CodexMemberPermissions) => ({ version: "0.2", name: "authored", pods: [{ id: "dev", label: "Dev", members: [
|
||||
{ id: "impl", agent_ref: "local:impl.agent.yaml", profile: "default", runtime: "codex", cwd: "/same/project", codex_config_profile: profile,
|
||||
...(permissions ? { codex_permissions: permissions } : {}) },
|
||||
], edges: [] }], edges: [] });
|
||||
@@ -292,6 +357,27 @@ describe("both writers: the spec at creation, the setter afterwards, every launc
|
||||
expect(RigSpecSchema.validate(wrongRuntime).errors.join(" ")).toContain("codex_permissions");
|
||||
});
|
||||
|
||||
it("materializes and exports the filesystem choice with a named profile", async () => {
|
||||
const f = fixture();
|
||||
const policy: CodexMemberPermissions = { approval: "never", filesystem: { ":minimal": "read", "/lease/a": "write", "/lease/a/private": "deny" }, network_access: false };
|
||||
const raw = authored("model-only", policy);
|
||||
expect(RigSpecSchema.validate(raw).valid).toBe(true);
|
||||
const { setup, node, rigId } = await materialize(f.db, raw);
|
||||
expect(readCodexMemberPermissions(f.db, node.id)).toEqual(policy);
|
||||
const exported = new RigSpecExporter({ rigRepo: setup.rigRepo, sessionRegistry: setup.sessionRegistry, podRepo: new PodRepository(f.db) }).exportRig(rigId);
|
||||
const decoded = RigSpecSchema.normalize(RigSpecCodec.parse(RigSpecCodec.serialize(exported as import("../src/domain/types.js").RigSpec)));
|
||||
expect(decoded.pods[0]!.members[0]!.codexPermissions).toEqual(policy);
|
||||
expect(decoded.pods[0]!.members[0]!.codexConfigProfile).toBe("model-only");
|
||||
setup.sessionRegistry.registerSession(node.id, "dev-impl@authored");
|
||||
const service = new SeatLifecycleService({ db: f.db, rigRepo: setup.rigRepo, sessionRegistry: setup.sessionRegistry, eventBus: setup.eventBus,
|
||||
tmuxAdapter: {} as TmuxAdapter });
|
||||
expect(await service.setPermissions({ seatRef: "dev-impl@authored", codexProfile: "other-model", actor: "operator@authored", reason: "Model selection" }))
|
||||
.toMatchObject({ ok: true });
|
||||
expect(await service.setPermissions({ seatRef: "dev-impl@authored", codexPermissions: policy, actor: "operator@authored", reason: "Keep policy" }))
|
||||
.toMatchObject({ ok: true });
|
||||
expect(readCodexMemberPermissions(f.db, node.id)).toEqual(policy);
|
||||
});
|
||||
|
||||
it("restores with the seat's current profile, so an older snapshot can't bring back a replaced one", async () => {
|
||||
const f = fixture();
|
||||
const setup = createTestApp(f.db);
|
||||
@@ -322,6 +408,8 @@ describe("legacy flat specs carry the envelope too", () => {
|
||||
const exported = new RigSpecExporter({ rigRepo: f.rigRepo, sessionRegistry: new SessionRegistry(f.db) }).exportRig(f.a.rigId);
|
||||
const parsed = LegacyRigSpecCodec.parse(LegacyRigSpecCodec.serialize(exported as import("../src/domain/types.js").LegacyRigSpec));
|
||||
expect(LegacyRigSpecSchema.normalize(parsed).nodes.find(n => n.codexPermissions)!.codexPermissions).toEqual(lease);
|
||||
expect(LegacyRigSpecSchema.validate({ ...raw, nodes: [{ ...raw.nodes[0], codex_config_profile: "model-only",
|
||||
codex_permissions: { approval: "never", filesystem: { ":project_roots": "write" } } }] }).errors).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -9,12 +9,12 @@ import { createHash } from "node:crypto";
|
||||
import { parse } from "smol-toml";
|
||||
import { CodexRuntimeAdapter } from "../src/adapters/codex-runtime-adapter.js";
|
||||
import type { TmuxAdapter } from "../src/adapters/tmux.js";
|
||||
import { codexPluginContentHash, codexLegacyPluginTrustPath, planOwnedCodexContentApproval } from "../src/domain/codex-owned-plugin-trust.js";
|
||||
import { codexPluginContentHash, codexLegacyPluginTrustPath, planOwnedCodexContentApproval, recordOwnedCodexApproval } from "../src/domain/codex-owned-plugin-trust.js";
|
||||
|
||||
const shipped = path.resolve(import.meta.dirname, "../assets/plugins/openrig-core");
|
||||
const roots: string[] = [];
|
||||
afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); });
|
||||
function fixture(config = "", corruptCache = false, duringPluginAdd?: () => void) {
|
||||
function fixture(config = "", corruptCache = false, duringPluginAdd?: () => void, onConfigRead?: () => void) {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "owned-codex-hooks-")); roots.push(root);
|
||||
const plugin = path.join(root, "plugins/openrig-core"), home = path.join(root, "codex");
|
||||
fs.cpSync(shipped, plugin, { recursive: true }); fs.mkdirSync(home);
|
||||
@@ -23,7 +23,7 @@ function fixture(config = "", corruptCache = false, duringPluginAdd?: () => void
|
||||
const cache = path.join(home, "plugins/cache/openrig/openrig-core", version);
|
||||
const calls: string[][] = [];
|
||||
const adapter = () => new CodexRuntimeAdapter({ tmux: {} as TmuxAdapter, codexHome: home,
|
||||
fsOps: { readFile: p => fs.readFileSync(p, "utf8"), writeFile: (p,c) => fs.writeFileSync(p,c), exists: fs.existsSync, mkdirp: p => fs.mkdirSync(p,{recursive:true}) },
|
||||
fsOps: { readFile: p => { if (p === file) onConfigRead?.(); return fs.readFileSync(p, "utf8"); }, writeFile: (p,c) => fs.writeFileSync(p,c), exists: fs.existsSync, mkdirp: p => fs.mkdirSync(p,{recursive:true}) },
|
||||
resolveCorePluginDir: () => plugin, codexSystemConfigDir: path.join(root, "etc"),
|
||||
runCodexCli: async args => {
|
||||
calls.push(args);
|
||||
@@ -361,3 +361,126 @@ it("R2 oa fresh nonmatching bundle gains no declaration-only legacy approval", a
|
||||
expect(fs.existsSync(path.join(f.home, ".openrig-core-hook-trust.json"))).toBe(false);
|
||||
expect(Object.keys(f.read().hooks?.state ?? {})).toHaveLength(0);
|
||||
});
|
||||
|
||||
// #17: a home OpenRig granted for an earlier release whose Stop hook declaration differed (its timeout), recorded by
|
||||
// OpenRig's own planner and writer, then upgraded to the current shipped bundle.
|
||||
const stopKey = "openrig-core@openrig:hooks/codex.json:stop:0:0";
|
||||
const recordPath = (f: ReturnType<typeof fixture>) => path.join(f.home, ".openrig-core-hook-trust.json");
|
||||
function earlierReleaseGrant(f: ReturnType<typeof fixture>, extra = "") {
|
||||
const earlier = path.join(path.dirname(f.home), "earlier-shipped");
|
||||
fs.cpSync(shipped, earlier, { recursive: true });
|
||||
const manifestPath = path.join(earlier, "hooks/codex.json");
|
||||
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
|
||||
manifest.hooks.Stop[0].hooks[0].timeout += 5;
|
||||
fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
|
||||
const earlierCache = path.join(path.dirname(f.cache), "earlier");
|
||||
fs.cpSync(earlier, earlierCache, { recursive: true });
|
||||
const { computeCodexHookTrust } = createRequire(import.meta.url)(path.join(shipped, "hooks/scripts/codex-hook-trust.cjs"));
|
||||
const content = codexPluginContentHash(earlier);
|
||||
let config = `[marketplaces.openrig]\nsource = ${JSON.stringify(path.dirname(f.plugin))}\n\n[plugins."openrig-core@openrig"]\nenabled = true\n`;
|
||||
for (const [event, groups] of Object.entries(manifest.hooks) as Array<[string, Array<{ matcher?: string; hooks: Array<{ command: string; timeout: number }> }>]>) {
|
||||
groups.forEach((group, groupIndex) => group.hooks.forEach((handler, handlerIndex) => {
|
||||
const { key, hash } = computeCodexHookTrust(event, { ...handler, matcher: group.matcher, timeoutSec: handler.timeout,
|
||||
keySource: "openrig-core@openrig:hooks/codex.json", groupIndex, handlerIndex });
|
||||
config += `\n[hooks.state.${JSON.stringify(key)}]\ntrusted_hash = ${JSON.stringify(hash)}\ntrusted_content_hash = ${JSON.stringify(content)}\n`;
|
||||
}));
|
||||
}
|
||||
config += extra;
|
||||
fs.writeFileSync(f.file, config);
|
||||
const plan = planOwnedCodexContentApproval({ configPath: f.file, content: config,
|
||||
layers: [{ name: "user config", path: f.file, state: "read", content: config }], shipped: earlier, installed: earlierCache, freshGrant: true });
|
||||
expect(plan).toBeDefined();
|
||||
recordOwnedCodexApproval(f.file, plan!.approval);
|
||||
const stop = (parse(config) as any).hooks.state[stopKey];
|
||||
return { config, record: fs.readFileSync(recordPath(f), "utf8"), earlierStop: stop.trusted_hash as string, earlierContent: content };
|
||||
}
|
||||
|
||||
const outside = '\n[hooks.state."other-plugin@market:hooks/codex.json:stop:0:0"]\ntrusted_hash = "sha256:outside"\ntrusted_content_hash = "sha256:outside-content"\n\n\n';
|
||||
it("the first launch after an upgrade that changed a declaration renews OpenRig's own recorded approvals and its record", async () => {
|
||||
const f = fixture(), earlier = earlierReleaseGrant(f, outside);
|
||||
expect(earlier.earlierStop).not.toBe((await freshInstallStates())[stopKey].trusted_hash);
|
||||
expect(await f.adapter().ensureCodexCorePlugin()).toMatchObject({ outcome: "installed" });
|
||||
const states = f.read().hooks.state;
|
||||
const fresh = await freshInstallStates();
|
||||
expect(Object.fromEntries(Object.entries(states).filter(([key]) => key.startsWith("openrig-core@openrig:")))).toEqual(fresh);
|
||||
expect(states["other-plugin@market:hooks/codex.json:stop:0:0"]).toEqual({ trusted_hash: "sha256:outside", trusted_content_hash: "sha256:outside-content" });
|
||||
const text = fs.readFileSync(f.file, "utf8");
|
||||
expect(text.endsWith(outside)).toBe(true);
|
||||
expect(text.replace(/^trusted(_content)?_hash = .*\n/gm, "")).toBe(earlier.config.replace(/^trusted(_content)?_hash = .*\n/gm, ""));
|
||||
const record = JSON.parse(fs.readFileSync(recordPath(f), "utf8"));
|
||||
expect(record).toEqual({ schema: 1, plugin: "openrig-core@openrig", contentHash: codexPluginContentHash(shipped),
|
||||
declarations: Object.fromEntries(Object.entries(fresh).map(([key, state]: [string, any]) => [key, state.trusted_hash])) });
|
||||
const renewed = fs.readFileSync(f.file, "utf8");
|
||||
await f.adapter().ensureCodexCorePlugin();
|
||||
expect(fs.readFileSync(f.file, "utf8")).toBe(renewed);
|
||||
});
|
||||
|
||||
it("a restart after the new bundle was installed but before renewal renews the same way, without reinstalling", async () => {
|
||||
const f = fixture(); earlierReleaseGrant(f);
|
||||
fs.cpSync(f.plugin, f.cache, { recursive: true });
|
||||
expect(await f.adapter().ensureCodexCorePlugin()).toMatchObject({ outcome: "current" });
|
||||
expect(f.calls).toEqual([]);
|
||||
expect(f.read().hooks.state).toEqual(await freshInstallStates());
|
||||
});
|
||||
|
||||
it.each(["mismatched declaration", "mismatched content", "disabled", "other layer", "profile choice", "nested plugin entry", "record removed", "record of another plugin"])(
|
||||
"a changed declaration keeps Codex's review for %s", async condition => {
|
||||
const f = fixture(), earlier = earlierReleaseGrant(f);
|
||||
const header = `[hooks.state.${JSON.stringify(stopKey)}]`;
|
||||
const edit = (change: (text: string) => string) => fs.writeFileSync(f.file, change(fs.readFileSync(f.file, "utf8")));
|
||||
if (condition === "mismatched declaration") edit(text => text.replace(earlier.earlierStop, `sha256:${"0".repeat(64)}`));
|
||||
if (condition === "mismatched content") edit(text => text.replace(`${header}\ntrusted_hash = ${JSON.stringify(earlier.earlierStop)}\ntrusted_content_hash = "${earlier.earlierContent}"`,
|
||||
`${header}\ntrusted_hash = ${JSON.stringify(earlier.earlierStop)}\ntrusted_content_hash = "sha256:${"0".repeat(64)}"`));
|
||||
if (condition === "disabled") edit(text => text.replace(header, `${header}\nenabled = false`));
|
||||
if (condition === "other layer") {
|
||||
fs.mkdirSync(path.join(path.dirname(f.home), "etc"));
|
||||
fs.writeFileSync(path.join(path.dirname(f.home), "etc/config.toml"), `${header}\ntrusted_hash = ${JSON.stringify(earlier.earlierStop)}\n`);
|
||||
}
|
||||
if (condition === "profile choice") edit(text => `${text}\n[profiles.special.hooks.state.${JSON.stringify(stopKey)}]\nenabled = false\n`);
|
||||
if (condition === "nested plugin entry") edit(text => `${text}\n[profiles.special.plugins."openrig-core@openrig"]\nenabled = true\n`);
|
||||
if (condition === "record removed") fs.rmSync(recordPath(f));
|
||||
if (condition === "record of another plugin") fs.writeFileSync(recordPath(f), earlier.record.replace('"openrig-core@openrig"', '"other-plugin@market"'));
|
||||
const before = fs.readFileSync(f.file, "utf8"), record = fs.existsSync(recordPath(f)) ? fs.readFileSync(recordPath(f), "utf8") : undefined;
|
||||
expect(f.read().hooks.state[stopKey]).toBeDefined();
|
||||
await f.adapter().ensureCodexCorePlugin();
|
||||
expect(fs.readFileSync(f.file, "utf8")).toBe(before);
|
||||
expect(fs.existsSync(recordPath(f)) ? fs.readFileSync(recordPath(f), "utf8") : undefined).toBe(record);
|
||||
});
|
||||
|
||||
it("the planner names exactly the changed declaration to rewrite, from the earlier grant's record", async () => {
|
||||
const f = fixture(), earlier = earlierReleaseGrant(f);
|
||||
fs.cpSync(f.plugin, f.cache, { recursive: true });
|
||||
const plan = planOwnedCodexContentApproval({ configPath: f.file, content: earlier.config,
|
||||
layers: [{ name: "user config", path: f.file, state: "read", content: earlier.config }], shipped, installed: f.cache });
|
||||
expect(plan?.trustedHashes).toEqual({ [stopKey]: (await freshInstallStates())[stopKey].trusted_hash });
|
||||
expect(Object.values(plan!.hashes)).toEqual(Array(6).fill(codexPluginContentHash(shipped)));
|
||||
});
|
||||
|
||||
// Codex records a person's decline of another OpenRig hook after the planner fingerprinted the installed bundle and
|
||||
// before OpenRig writes: on the first read of config.toml that follows, in the user config or in the system layer.
|
||||
it.each(["user config", "other layer"])("a choice recorded in the %s while the renewal is being prepared wins: no renewal and no new record", async where => {
|
||||
const header = '[hooks.state."openrig-core@openrig:hooks/codex.json:session_start:0:0"]';
|
||||
const decline = (text: string) => text.replace(header, `${header}\nenabled = false`);
|
||||
let planned = false, injected = false;
|
||||
const f: ReturnType<typeof fixture> = fixture("", false, undefined, () => {
|
||||
if (!planned || injected) return;
|
||||
injected = true;
|
||||
if (where === "user config") fs.writeFileSync(f.file, decline(fs.readFileSync(f.file, "utf8")));
|
||||
else {
|
||||
fs.mkdirSync(path.join(path.dirname(f.home), "etc"), { recursive: true });
|
||||
fs.writeFileSync(path.join(path.dirname(f.home), "etc/config.toml"), `${header}\nenabled = false\n`);
|
||||
}
|
||||
});
|
||||
const earlier = earlierReleaseGrant(f);
|
||||
const readdir = fs.readdirSync;
|
||||
const spy = vi.spyOn(fs, "readdirSync").mockImplementation(((dir: fs.PathLike, ...rest: unknown[]) => {
|
||||
if (String(dir).startsWith(f.cache)) planned = true;
|
||||
return (readdir as (...args: unknown[]) => unknown)(dir, ...rest);
|
||||
}) as typeof fs.readdirSync);
|
||||
try {
|
||||
await f.adapter().ensureCodexCorePlugin();
|
||||
} finally { spy.mockRestore(); }
|
||||
expect(injected).toBe(true);
|
||||
expect(fs.readFileSync(f.file, "utf8")).toBe(where === "user config" ? decline(earlier.config) : earlier.config);
|
||||
expect(fs.readFileSync(recordPath(f), "utf8")).toBe(earlier.record);
|
||||
});
|
||||
@@ -138,6 +138,28 @@ function makeValidFlagPolicy(posture: "floor" | "full_bypass"): string {
|
||||
}
|
||||
|
||||
describe("Issue #2989 — native-resume-probe Codex show-and-label builder", () => {
|
||||
describe.each(["floor", "full_bypass", "auto"] as const)("filesystem policy with %s posture fallback", (resolvedPosture) => {
|
||||
it.each([false, true])("labels the omitted policy with recorded launch=%s, including wrappers", (hasRecord) => {
|
||||
const display = buildCodexResumeDisplay("tok-filesystem", {
|
||||
codexPermissions: { filesystem: { ":root": "read", "/work": "write" }, approval: "never" },
|
||||
resolvedPosture,
|
||||
recordedLaunch: hasRecord ? {
|
||||
runtime: "codex", axis: "sandbox", state: "observed", value: "permissions:openrig-seat",
|
||||
approvalPolicy: "never", reason: "emitted_launch_arguments",
|
||||
} : null,
|
||||
launchWrapper: ["env", "POLICY_WRAPPER=1"],
|
||||
});
|
||||
const fallback = buildCodexResumeDisplay("tok-filesystem", { resolvedPosture });
|
||||
expect(display.command).toBe(fallback.command);
|
||||
expect(display.command).not.toContain("default_permissions");
|
||||
expect(display.label).toContain("shown command uses posture fallback");
|
||||
expect(display.label).toContain("does not carry the agent's filesystem policy");
|
||||
expect(display.label).toContain("omits launch_wrapper");
|
||||
expect(display.label).not.toContain("a resume now uses");
|
||||
expect(display.status).toBe(hasRecord ? "recorded_uncertain" : "no_recorded_launch");
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
@@ -7,6 +7,9 @@ import Database from "better-sqlite3";
|
||||
import { parse as parseToml } from "smol-toml";
|
||||
import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
|
||||
import { CodexRuntimeAdapter, type CodexAdapterFsOps } from "../src/adapters/codex-runtime-adapter.js";
|
||||
import { CodexResumeAdapter } from "../src/adapters/codex-resume.js";
|
||||
import { SeatLaunchEnvironment } from "../src/domain/seat-launch-environment.js";
|
||||
import type { CodexFilesystemVerifier } from "../src/domain/codex-filesystem-preflight.js";
|
||||
import { ObservationPass } from "../src/domain/process-observation-pass.js";
|
||||
import { codexNonLoginShellArg } from "../src/domain/native-resume-probe.js";
|
||||
import type { NodeBinding, ResolvedStartupFile } from "../src/domain/runtime-adapter.js";
|
||||
@@ -2842,6 +2845,203 @@ describe("a seat's own permission envelope (argv only, not native enforcement)",
|
||||
});
|
||||
});
|
||||
|
||||
describe("a seat's explicit filesystem policy (argv and native-read preflight, not enforcement)", () => {
|
||||
const filesystemChoice = { approval: "never", filesystem: { ":minimal": "read", "/same": "write", "/same/private": "deny" }, network_access: false } satisfies import("../src/domain/codex-member-permissions.js").CodexFilesystemPermissions;
|
||||
|
||||
it.each(["fresh", "resume", "codex_id", "codex_last"])("keeps a wrapped filesystem launch and reports unverified policy on %s", async kind => {
|
||||
const tmux = mockTmux();
|
||||
const environment = new SeatLaunchEnvironment(tmux, { PATH: "/bin" }, "/same");
|
||||
const command = vi.spyOn(environment, "command").mockImplementation(async (_session, core) => core);
|
||||
const verifyFilesystemPolicy: CodexFilesystemVerifier = async request => request.launchWrapper?.length
|
||||
? { ok: true, verified: false, reason: "launch_wrapper can change the checked configuration" } : { ok: true, verified: true };
|
||||
const launchWrapper = ["env", "CODEX_HOME=/other"];
|
||||
const options = { codexHome: "/shared-home", verifyFilesystemPolicy, seatLaunchEnvironment: environment,
|
||||
sleep: async () => {} };
|
||||
if (kind === "fresh" || kind === "resume") {
|
||||
const adapter = new CodexRuntimeAdapter({ ...options, tmux, fsOps: mockFs() });
|
||||
const binding = { ...makeBinding("/same"), codexPermissions: filesystemChoice, launchWrapper };
|
||||
const result = kind === "fresh" ? await adapter.launchHarness(binding, { name: "dev-a@test-rig" })
|
||||
: await adapter.buildResumeCommand(binding, { name: "dev-a@test-rig", resumeToken: "thread-A" });
|
||||
expect(result).toMatchObject({ ok: true, appliedLaunch: { reason: expect.stringContaining("policy not verified: launch_wrapper") } });
|
||||
} else {
|
||||
const restore = new CodexResumeAdapter(tmux, { ...options, maxWaitMs: 0 });
|
||||
expect(await restore.resume("dev-a@test-rig", kind, "thread-A", "/same", undefined, "floor", undefined, undefined,
|
||||
undefined, undefined, undefined, undefined, filesystemChoice, undefined, launchWrapper))
|
||||
.toMatchObject({ ok: true, appliedLaunch: { reason: expect.stringContaining("policy not verified: launch_wrapper") } });
|
||||
}
|
||||
expect(command).toHaveBeenCalledWith(expect.any(String), expect.stringContaining('default_permissions="openrig-seat"'), expect.objectContaining({ launchWrapper }));
|
||||
});
|
||||
|
||||
it.each(["fresh", "resume"])("emits the selected policy on %s without extra writable roots or shared policy files", async path => {
|
||||
const tmux = mockTmux(), filesystem = mockFs();
|
||||
const writes = vi.spyOn(filesystem, "writeFile");
|
||||
const verifyFilesystemPolicy = vi.fn<CodexFilesystemVerifier>(async () => ({ ok: true, verified: true }));
|
||||
const adapter = new CodexRuntimeAdapter({ tmux, fsOps: filesystem, sleep: async () => {}, verifyFilesystemPolicy,
|
||||
codexHome: "/shared-home", resolveGitAddDirs: async () => ["/same/.git"], prepareSeatFolder: () => "/seat-state" });
|
||||
const binding = { ...makeBinding("/same"), codexPermissions: filesystemChoice, launchPosture: "full_bypass" as const };
|
||||
const result = path === "fresh" ? await adapter.launchHarness(binding, { name: "dev-a@test-rig" })
|
||||
: await adapter.buildResumeCommand(binding, { name: "dev-a@test-rig", resumeToken: "thread-A" });
|
||||
expect(result).toMatchObject({ ok: true });
|
||||
const command = path === "fresh" ? vi.mocked(tmux.sendText).mock.calls[0]![1] : "core" in result ? result.core : "";
|
||||
expect(command).toContain('default_permissions="openrig-seat"');
|
||||
expect(command).toContain('"/same/private"="deny"');
|
||||
expect(command).not.toMatch(/--add-dir|danger-full-access|sandbox_workspace_write| -s /);
|
||||
expect(verifyFilesystemPolicy).toHaveBeenCalledWith(expect.objectContaining({ permissions: filesystemChoice, cwd: "/same", codexHome: "/shared-home" }));
|
||||
expect(writes.mock.calls.every(([path]) => !path.endsWith(".codex/config.toml"))).toBe(true);
|
||||
});
|
||||
|
||||
it("refuses a native-read mismatch before dispatching any command", async () => {
|
||||
const tmux = mockTmux();
|
||||
const adapter = new CodexRuntimeAdapter({ tmux, fsOps: mockFs(), verifyFilesystemPolicy: async () => ({ ok: false, error: "lower profile adds a writable root" }) });
|
||||
expect(await adapter.launchHarness({ ...makeBinding("/same"), codexPermissions: filesystemChoice }, { name: "dev-a@test-rig" }))
|
||||
.toMatchObject({ ok: false, error: expect.stringContaining("lower profile") });
|
||||
expect(tmux.sendText).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["fresh", "resume"])("pins the normal account home on the native read and %s command", async kind => {
|
||||
const previous = process.env.CODEX_HOME;
|
||||
delete process.env.CODEX_HOME;
|
||||
try {
|
||||
const tmux = mockTmux();
|
||||
const verifyFilesystemPolicy = vi.fn<CodexFilesystemVerifier>(async () => ({ ok: true, verified: false, reason: "native read timed out" }));
|
||||
const adapter = new CodexRuntimeAdapter({ tmux, fsOps: { ...mockFs(), homedir: "/normal-account" }, sleep: async () => {}, verifyFilesystemPolicy });
|
||||
const binding = { ...makeBinding("/same"), codexPermissions: filesystemChoice };
|
||||
const result = kind === "fresh" ? await adapter.launchHarness(binding, { name: "dev-a@test-rig" })
|
||||
: await adapter.buildResumeCommand(binding, { name: "dev-a@test-rig", resumeToken: "thread-A" });
|
||||
expect(result).toMatchObject({ ok: true, appliedLaunch: { reason: "policy not verified: native read timed out" } });
|
||||
expect(verifyFilesystemPolicy).toHaveBeenCalledWith(expect.objectContaining({ codexHome: "/normal-account/.codex" }));
|
||||
const command = kind === "fresh" ? vi.mocked(tmux.sendText).mock.calls[0]?.[1] : "command" in result ? result.command : "";
|
||||
expect(command).toContain("CODEX_HOME='/normal-account/.codex'");
|
||||
expect(command).toContain('default_permissions="openrig-seat"');
|
||||
expect(command).toContain('"/same/private"="deny"');
|
||||
} finally {
|
||||
if (previous === undefined) delete process.env.CODEX_HOME;
|
||||
else process.env.CODEX_HOME = previous;
|
||||
}
|
||||
});
|
||||
|
||||
it("reports a thrown native reader as unverified before handover without changing config or sending input", async () => {
|
||||
const tmux = mockTmux(), filesystem = mockFs();
|
||||
const write = vi.spyOn(filesystem, "writeFile");
|
||||
const adapter = new CodexRuntimeAdapter({ tmux, fsOps: filesystem,
|
||||
verifyFilesystemPolicy: async () => { throw new Error("private error contents"); } });
|
||||
expect(await adapter.preflightLaunch({ ...makeBinding(), codexPermissions: filesystemChoice }))
|
||||
.toEqual({ ok: true, warnings: ["policy not verified: Native Codex configuration reader failed"] });
|
||||
expect(write).not.toHaveBeenCalled();
|
||||
expect(tmux.sendText).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("carries a pre-cutover check into one launch and checks again for a later launch", async () => {
|
||||
const tmux = mockTmux();
|
||||
const verifyFilesystemPolicy = vi.fn<CodexFilesystemVerifier>()
|
||||
.mockResolvedValueOnce({ ok: true, verified: false, reason: "native read timed out" })
|
||||
.mockResolvedValueOnce({ ok: false, error: "later policy conflict" });
|
||||
const adapter = new CodexRuntimeAdapter({ tmux, fsOps: mockFs(), sleep: async () => {}, verifyFilesystemPolicy });
|
||||
const binding = { ...makeBinding("/same"), codexPermissions: filesystemChoice };
|
||||
expect(await adapter.preflightLaunch(binding)).toMatchObject({ ok: true });
|
||||
expect(tmux.sendText).not.toHaveBeenCalled();
|
||||
expect(await adapter.launchHarness(binding, { name: "dev-a@test-rig" }))
|
||||
.toMatchObject({ ok: true, warnings: ["policy not verified: native read timed out"],
|
||||
appliedLaunch: { reason: "policy not verified: native read timed out" } });
|
||||
expect(verifyFilesystemPolicy).toHaveBeenCalledTimes(1);
|
||||
vi.mocked(tmux.sendText).mockClear();
|
||||
expect(await adapter.launchHarness(binding, { name: "dev-a@test-rig" })).toMatchObject({ ok: false, error: "later policy conflict" });
|
||||
expect(verifyFilesystemPolicy).toHaveBeenCalledTimes(2);
|
||||
expect(tmux.sendText).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ homes: ["/shared-home", "/shared-home"], cwds: ["/same", "/same"] },
|
||||
{ homes: ["/shared-home", "/shared-home"], cwds: ["/project-a", "/project-b"] },
|
||||
{ homes: ["/home-a", "/home-b"], cwds: ["/same", "/same"] },
|
||||
] satisfies { homes: [string, string]; cwds: [string, string] }[])("keeps A/B/A policies separate with home/cwd sharing: %j", async ({ homes, cwds }) => {
|
||||
const tmux = mockTmux();
|
||||
const verifyFilesystemPolicy = vi.fn<CodexFilesystemVerifier>(async () => ({ ok: true, verified: true }));
|
||||
const adapter = new CodexRuntimeAdapter({ tmux, fsOps: mockFs(), sleep: async () => {}, verifyFilesystemPolicy,
|
||||
seatHome: id => id === "A" ? homes[0] : homes[1] });
|
||||
const other: import("../src/domain/codex-member-permissions.js").CodexFilesystemPermissions = {
|
||||
approval: "on-request", filesystem: { ":minimal": "read", "/lease/b": "write" }, network_access: false,
|
||||
};
|
||||
for (const { id, cwd, permissions } of [
|
||||
{ id: "A", cwd: cwds[0], permissions: filesystemChoice },
|
||||
{ id: "B", cwd: cwds[1], permissions: other },
|
||||
{ id: "A", cwd: cwds[0], permissions: filesystemChoice },
|
||||
]) {
|
||||
expect(await adapter.launchHarness({ ...makeBinding(cwd), nodeId: id,
|
||||
codexPermissions: permissions }, { name: `dev-${id}@test-rig` })).toMatchObject({ ok: true });
|
||||
}
|
||||
const commands = vi.mocked(tmux.sendText).mock.calls.map(call => call[1]);
|
||||
expect(commands).toHaveLength(3);
|
||||
expect(commands[0]).toContain('"/same/private"="deny"');
|
||||
expect(commands[0]).not.toContain('"/lease/b"');
|
||||
expect(commands[1]).toContain('"/lease/b"="write"');
|
||||
expect(commands[1]).not.toContain('"/same/private"');
|
||||
expect(commands[2]).toEqual(commands[0]);
|
||||
expect(verifyFilesystemPolicy.mock.calls.map(call => call[0])).toEqual([
|
||||
expect.objectContaining({ codexHome: homes[0], cwd: cwds[0], permissions: filesystemChoice }),
|
||||
expect.objectContaining({ codexHome: homes[1], cwd: cwds[1], permissions: other }),
|
||||
expect.objectContaining({ codexHome: homes[0], cwd: cwds[0], permissions: filesystemChoice }),
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps a named configuration profile and the authored filesystem policy on resume", async () => {
|
||||
const tmux = mockTmux();
|
||||
const verifyFilesystemPolicy = vi.fn<CodexFilesystemVerifier>(async () => ({ ok: true, verified: false, reason: "profile reader unavailable" }));
|
||||
const adapter = new CodexRuntimeAdapter({ tmux, fsOps: mockFs(), verifyFilesystemPolicy,
|
||||
verifyProfilePreflight: async profile => ({ ok: true, profile }) });
|
||||
expect(await adapter.buildResumeCommand({ ...makeBinding("/same"), codexPermissions: filesystemChoice, codexConfigProfile: "named" },
|
||||
{ name: "dev-a@test-rig", resumeToken: "thread-A" })).toMatchObject({ ok: true,
|
||||
core: expect.stringMatching(/-p 'named' .*default_permissions="openrig-seat"/), appliedLaunch: { reason: "policy not verified: profile reader unavailable" } });
|
||||
expect(verifyFilesystemPolicy).toHaveBeenCalledWith(expect.objectContaining({ codexConfigProfile: "named" }));
|
||||
expect(tmux.sendText).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["codex_id", "codex_last"])("legacy restore %s carries the same policy and refuses a failed native read", async kind => {
|
||||
const tmux = mockTmux();
|
||||
const restore = new CodexResumeAdapter(tmux, { codexHome: "/shared-home", maxWaitMs: 0, sleep: async () => {},
|
||||
verifyFilesystemPolicy: async () => ({ ok: true, verified: true }), resolveGitAddDirs: async () => ["/same/.git"] });
|
||||
await restore.resume("dev-a@test-rig", kind, "thread-A", "/same", undefined, "full_bypass", undefined, undefined,
|
||||
undefined, undefined, undefined, undefined, filesystemChoice);
|
||||
const command = vi.mocked(tmux.sendText).mock.calls[0]![1];
|
||||
expect(command).toContain('default_permissions="openrig-seat"');
|
||||
expect(command).toContain('"/same/private"="deny"');
|
||||
expect(command).not.toMatch(/--add-dir|danger-full-access|sandbox_workspace_write| -s /);
|
||||
vi.mocked(tmux.sendText).mockClear();
|
||||
const refusing = new CodexResumeAdapter(tmux, { verifyFilesystemPolicy: async () => ({ ok: false, error: "policy mismatch" }) });
|
||||
expect(await refusing.resume("dev-a@test-rig", kind, "thread-A", "/same", undefined, "floor", undefined, undefined,
|
||||
undefined, undefined, undefined, undefined, filesystemChoice)).toMatchObject({ ok: false, message: "policy mismatch" });
|
||||
expect(tmux.sendText).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["fresh", "resume", "codex_id", "codex_last"])("checks a filesystem seat's named profile load before dispatch on %s", async kind => {
|
||||
const tmux = mockTmux();
|
||||
const verifyFilesystemPolicy: CodexFilesystemVerifier = async () => ({ ok: true, verified: false, reason: "profile configuration cannot be compared" });
|
||||
if (kind === "fresh" || kind === "resume") {
|
||||
const adapter = new CodexRuntimeAdapter({ tmux, fsOps: mockFs(), verifyFilesystemPolicy,
|
||||
verifyProfilePreflight: async profile => ({ ok: false, profile, error: "profile failed to load" }) });
|
||||
const binding = { ...makeBinding(), codexPermissions: filesystemChoice, codexConfigProfile: "broken" };
|
||||
const result = kind === "fresh" ? await adapter.launchHarness(binding, { name: "dev-a@test-rig" })
|
||||
: await adapter.buildResumeCommand(binding, { name: "dev-a@test-rig", resumeToken: "thread-A" });
|
||||
expect(result).toMatchObject({ ok: false, error: expect.stringContaining("profile failed to load") });
|
||||
} else {
|
||||
const restore = new CodexResumeAdapter(tmux, { verifyFilesystemPolicy, exec: async () => { throw new Error("profile failed to load"); } });
|
||||
expect(await restore.resume("dev-a@test-rig", kind, "thread-A", "/same", "broken", "floor", undefined, undefined,
|
||||
undefined, undefined, undefined, undefined, filesystemChoice)).toMatchObject({ ok: false, message: expect.stringContaining("profile failed to load") });
|
||||
}
|
||||
expect(tmux.sendText).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refuses a filesystem seat's broken named profile during pre-cutover checks", async () => {
|
||||
const tmux = mockTmux();
|
||||
const adapter = new CodexRuntimeAdapter({ tmux, fsOps: mockFs(),
|
||||
verifyFilesystemPolicy: async () => ({ ok: true, verified: false, reason: "profile configuration cannot be compared" }),
|
||||
verifyProfilePreflight: async profile => ({ ok: false, profile, error: "profile failed to load" }) });
|
||||
expect(await adapter.preflightLaunch({ ...makeBinding(), codexPermissions: filesystemChoice, codexConfigProfile: "broken" }))
|
||||
.toMatchObject({ ok: false, error: expect.stringContaining("profile failed to load") });
|
||||
expect(tmux.sendText).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// #875 Codex: on a fresh launch of a supported Codex, OpenRig's managed guidance goes in as the launch's developer
|
||||
// instructions (`-c developer_instructions`, Codex 0.164.0), so the person's tracked repository AGENTS.md and the Codex
|
||||
// home are left alone. Anything else keeps the repository AGENTS.md, as before.
|
||||
|
||||
@@ -5,7 +5,7 @@ import {compactionRoutes} from '../src/routes/compaction.js';
|
||||
import {mkdtempSync, mkdirSync, writeFileSync, renameSync, rmSync, readFileSync, symlinkSync, lstatSync, statSync, utimesSync, chmodSync, existsSync} from 'node:fs';
|
||||
import {tmpdir} from 'node:os';
|
||||
import {join, dirname} from 'node:path';
|
||||
import {ClaudeCompactionEnforcer, COMPACTION_RECORD_FILE, AUTO_PREP_WAIT_MS_DEFAULT, AUTO_RETRY_AFTER_STOP_MS_DEFAULT, MANUAL_PREP_WAIT_MS_DEFAULT} from '../src/domain/claude-compaction-enforcer.js';
|
||||
import {ClaudeCompactionEnforcer, COMPACTION_RECORD_FILE, AUTO_PREP_WAIT_MS_DEFAULT, AUTO_RETRY_AFTER_STOP_MS_DEFAULT, MANUAL_PREP_WAIT_MS_DEFAULT, MANUAL_SEAT_READ_INTERVAL_MS} from '../src/domain/claude-compaction-enforcer.js';
|
||||
import {SessionTransport, CAPTURE_READABLE_BUDGET_MS, SEND_READINESS_FRESHNESS_MS} from '../src/domain/session-transport.js';
|
||||
import {SeatDeliveryGuard} from '../src/domain/seat-delivery-guard.js';
|
||||
import {TmuxAdapter} from '../src/adapters/tmux.js';
|
||||
@@ -498,7 +498,7 @@ it('manual route preserves a non-timeout idle-wait refusal after map completion'
|
||||
it('preparation receipt: unresolved permission at deadline discloses the delivered prep and exact attempt',async()=>{
|
||||
const f=fixture();f.onSleep(async()=>{stageMap(f);f.activity('needs_input');});
|
||||
const res=await routeFixture(f)();const body=await res.json();
|
||||
expect(res.status).toBe(409);expect(body.reason).toBe('map_complete_seat_never_idle');
|
||||
expect(res.status).toBe(409);expect(body.reason).toBe('preparation_needs_input');expect(body.error).toContain('Answer the prompt in the seat');
|
||||
expect(body.preparation).toMatchObject({attemptId:f.e.getPreparationState(seat)!.attemptId,delivery:'delivered'});
|
||||
expect(body.error).toContain('Preparation was sent');expect(body.error).not.toContain('could not be sent');
|
||||
expect(body.error).toContain('disarmed');expect(compacts(f)).toHaveLength(0);expect(f.writes).toHaveLength(1);
|
||||
@@ -854,10 +854,74 @@ it('manual attention clears within the same attempt with one preparation and one
|
||||
});
|
||||
it('manual unresolved attention consumes the deadline and never revives',async()=>{
|
||||
const f=fixture();const start=f.clock();f.onSleep(async()=>{stageMap(f);f.activity('needs_input');});
|
||||
expect(await f.e.triggerManualCompact(input,{operatorInitiated:true})).toMatchObject({triggered:false,reason:'map_complete_seat_never_idle'});
|
||||
expect(await f.e.triggerManualCompact(input,{operatorInitiated:true})).toMatchObject({triggered:false,reason:'preparation_needs_input'});
|
||||
expect(f.clock()).toBe(start+1000);expect(compacts(f)).toHaveLength(0);
|
||||
f.activity('idle');stageMap(f);await f.e.maybeAutoCompact(input);expect(compacts(f)).toHaveLength(0);
|
||||
});
|
||||
// The manual wait reads the seat while the map is written too, and the attempt keeps only the latest reading: a prompt
|
||||
// is reported while it's there and named at expiry only when the latest reading still shows it.
|
||||
const readsBy=(ms:number)=>Math.floor(ms/MANUAL_SEAT_READ_INTERVAL_MS)+1;
|
||||
it('manual: a prompt before the map is reported in --state and names the expiry',async()=>{
|
||||
const f=fixture(20_000);const seen:any[]=[];
|
||||
f.onSleep(async()=>{f.activity('needs_input');seen.push(f.e.getPreparationState(seat)?.awaitingInput);});
|
||||
expect(await f.e.triggerManualCompact(input,{operatorInitiated:true})).toMatchObject({triggered:false,reason:'preparation_needs_input'});
|
||||
expect(seen).toContainEqual(expect.objectContaining({reason:'target_needs_input',current:true}));
|
||||
expect(compacts(f)).toHaveLength(0);
|
||||
});
|
||||
it('manual: a prompt before the map, answered, then the completed map compacts on the same attempt',async()=>{
|
||||
const f=fixture(20_000);let n=0;let attempt='';const seen:any[]=[];
|
||||
f.onSleep(async()=>{n++;attempt||=f.e.getPreparationState(seat)!.attemptId;seen.push(f.e.getPreparationState(seat)?.awaitingInput);
|
||||
if(n<30)f.activity('needs_input');else{f.activity('idle');stageMap(f);}});
|
||||
expect((await f.e.triggerManualCompact(input,{operatorInitiated:true})).triggered).toBe(true);
|
||||
expect(seen).toContainEqual(expect.objectContaining({current:true}));
|
||||
expect(f.e.getPreparationState(seat)).toMatchObject({attemptId:attempt,status:'compact-sent'});
|
||||
expect(compacts(f)).toHaveLength(1);
|
||||
});
|
||||
it.each(['running','unknown'] as const)('manual: a prompt answered into %s is not reported as current at expiry',async(after)=>{
|
||||
const f=fixture(20_000);let n=0;vi.spyOn(Date,'now').mockImplementation(()=>f.clock());
|
||||
f.onSleep(async()=>{n++;stageMap(f);f.activity(n<8?'needs_input':after);});
|
||||
expect(await f.e.triggerManualCompact(input,{operatorInitiated:true})).toMatchObject({triggered:false,reason:'map_complete_seat_never_idle'});
|
||||
const state=f.e.getPreparationState(seat)!;
|
||||
if(after==='running')expect(state.awaitingInput).toBeUndefined();
|
||||
else expect(state.awaitingInput).toMatchObject({reason:'target_needs_input',current:false});
|
||||
expect(compacts(f)).toHaveLength(0);
|
||||
});
|
||||
it('manual: prompt, then idle, then busy before the map is done: no stale prompt, the map expiry as before',async()=>{
|
||||
const f=fixture(20_000);let n=0;
|
||||
f.onSleep(async()=>{n++;f.activity(n<30?'needs_input':n<50?'idle':'running');});
|
||||
expect(readsBy(20_000)).toBeGreaterThanOrEqual(4);
|
||||
expect(await f.e.triggerManualCompact(input,{operatorInitiated:true})).toMatchObject({triggered:false,reason:'preparation_incomplete'});
|
||||
expect(f.e.getPreparationState(seat)!.awaitingInput).toBeUndefined();
|
||||
expect(compacts(f)).toHaveLength(0);
|
||||
});
|
||||
// The idle wait after the map can run to the deadline, so readings it completes must reach the attempt as they land: a
|
||||
// --state read (which also reconciles the deadline) during that wait describes the seat now.
|
||||
it.each(['running','unknown'] as const)('manual: a prompt answered into %s while the post-map wait runs; --state reads during the wait, and at the deadline, see no current prompt',async(after)=>{
|
||||
const f=fixture(20_000);vi.spyOn(Date,'now').mockImplementation(()=>f.clock());
|
||||
let n=0;let prompt:any;let attempt='';
|
||||
f.onSleep(async()=>{n++;if(n===1){attempt=f.e.getPreparationState(seat)!.attemptId;stageMap(f);f.activity('needs_input');}
|
||||
else if(n===2){prompt=f.e.getPreparationState(seat)?.awaitingInput;f.activity(after);}});
|
||||
// After the prompt the seat works on, or can't be read; on the third such reading of one wait, two --state reads land:
|
||||
// one as it is, one at the deadline, while that wait is still in flight.
|
||||
const read=(f.transport as any).classifySendReadiness;let later=0;let during:any;let atDeadline:any;
|
||||
(f.transport as any).classifySendReadiness=async(...args:any[])=>{
|
||||
if(n>=2&&++later===3){
|
||||
during=f.e.getPreparationState(seat)?.awaitingInput??null;
|
||||
f.advance(f.e.getPreparationState(seat)!.deadlineAt!-f.clock());
|
||||
atDeadline=f.e.getPreparationState(seat);
|
||||
}
|
||||
return read(...args);
|
||||
};
|
||||
const outcome=await f.e.triggerManualCompact(input,{operatorInitiated:true});
|
||||
expect(prompt).toMatchObject({reason:'target_needs_input',current:true});
|
||||
// A working seat clears the prompt; one that can't be read keeps it only as an earlier observation, never a current one.
|
||||
const earlier=after==='running'?undefined:expect.objectContaining({reason:'target_needs_input',current:false});
|
||||
expect(during??undefined).toEqual(earlier);
|
||||
expect(atDeadline).toMatchObject({attemptId:attempt,status:'stopped',reason:'map_complete_seat_never_idle'});
|
||||
expect(atDeadline.awaitingInput).toEqual(earlier);
|
||||
expect(outcome).toMatchObject({triggered:false,reason:'map_complete_seat_never_idle'});
|
||||
expect(compacts(f)).toHaveLength(0);
|
||||
});
|
||||
it('manual default accepts a map after120s but before180s',async()=>{
|
||||
expect(MANUAL_PREP_WAIT_MS_DEFAULT).toBe(180_000);
|
||||
const f=fixture(null);const start=f.clock();f.onSleep(async()=>{if(f.clock()>=start+130_000)stageMap(f);});
|
||||
|
||||
@@ -3,7 +3,7 @@ import { TerminalPolicyStore } from "../src/domain/terminal-policy.js";
|
||||
//
|
||||
// Proves: the route resolves the target + reads the EXISTING context-usage
|
||||
// projection BEFORE calling the enforcer (known usage permits a manual request
|
||||
// independently of the threshold); non-Claude → 422 runtime_filter; unknown usage → 409 no_usage_data
|
||||
// independently of the threshold); non-Claude → 422 runtime_filter; unknown usage still prepares and compacts
|
||||
// (route passes null, never invents a value); ambiguous → 409; missing field →
|
||||
// 400; enforcer-unwired → 503. Reuses the shipped SessionTransport + the SAME
|
||||
// ClaudeCompactionEnforcer (no second path).
|
||||
@@ -277,7 +277,7 @@ describe("compaction routes — POST /api/compaction/trigger", () => {
|
||||
expect(sentTexts).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("unknown usage (no sample persisted) → 409 no_usage_data (never triggers blind)", async () => {
|
||||
it("unknown usage (no sample persisted): an explicit manual request doesn't depend on the threshold, so it prepares and compacts", async () => {
|
||||
seed();
|
||||
const { app, sentTexts } = buildApp();
|
||||
const res = await app.request("/api/compaction/trigger", {
|
||||
@@ -285,9 +285,11 @@ describe("compaction routes — POST /api/compaction/trigger", () => {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ session: "dev-impl@my-rig" }),
|
||||
});
|
||||
expect(res.status).toBe(409);
|
||||
expect((await res.json()).reason).toBe("no_usage_data");
|
||||
expect(sentTexts).toHaveLength(0);
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toMatchObject({ ok: true, stage: "compact-sent" });
|
||||
expect(sentTexts[0]).toContain("OpenRig manual compaction was requested for this seat");
|
||||
expect(sentTexts[0]).not.toContain("null");
|
||||
expect(sentTexts.some((text) => text.startsWith("/compact"))).toBe(true);
|
||||
});
|
||||
|
||||
it("ambiguous session across rigs → 409", async () => {
|
||||
|
||||
@@ -201,6 +201,29 @@ describe("an opt-in decision revision on the settling verbs (#2446)", () => {
|
||||
expect(await f.act({ verb: "approve", qitemId: id, expectedRevision: read })).toMatchObject({ status: 200, body: { closedQitem: { state: "done" } } });
|
||||
});
|
||||
|
||||
it("a new evidence pointer on an open ask is a new decision: an answer read under the earlier pointer conflicts, with nothing written", async () => {
|
||||
const f = fixture();
|
||||
const id = (await f.repo.create({ sourceSession: ASKER, destinationSession: PERSON, body: "Approve the release notes", summary: "Notes?",
|
||||
humanIntent: "decision", evidenceRef: "/proof/notes-v1.md", nudge: false })).qitemId;
|
||||
const read = await f.revision(id);
|
||||
f.repo.update({ qitemId: id, actorSession: ASKER, state: "pending", evidenceRef: "/proof/notes-v2.md" });
|
||||
expect(f.repo.getById(id)).toMatchObject({ state: "pending", evidenceRef: "/proof/notes-v2.md" });
|
||||
expect(await f.revision(id)).not.toBe(read);
|
||||
const before = f.written(id);
|
||||
expect(await f.act({ verb: "approve", qitemId: id, expectedRevision: read }))
|
||||
.toMatchObject({ status: 409, body: { error: "decision_revision_changed", currentRevision: await f.revision(id) } });
|
||||
expect(f.written(id)).toEqual(before);
|
||||
});
|
||||
|
||||
it("a row with no evidence keeps the revision it had before evidence counted", async () => {
|
||||
// A fixed id, so the revision (which names the row's park episode) is the same on every run; the value is the one
|
||||
// this ask had before evidence counted.
|
||||
const f = fixture();
|
||||
const id = (await f.repo.create({ qitemId: "qitem-revision-control", sourceSession: ASKER, destinationSession: PERSON,
|
||||
body: "Synthetic two-question ask", summary: "Ship?", humanIntent: "decision", humanQuestions: QUESTIONS, nudge: false })).qitemId;
|
||||
expect(await f.revision(id)).toBe("dr1-bed30769297c81fe419c3520");
|
||||
});
|
||||
|
||||
it("repairs a direct-answer partial commit on retry without duplicating the reply row, then reconciles subsequent retries", async () => {
|
||||
const f = fixture();
|
||||
const row = await f.repo.create({ sourceSession: ASKER, destinationSession: PERSON, body: "Ship the relay?", summary: "Ship?", humanIntent: "decision", nudge: false });
|
||||
|
||||
@@ -1314,4 +1314,31 @@ describe("#3076: a draft typed between the guard's read and the paste", () => {
|
||||
const sent = await f.send("attach-quiet", "Wake timer fired again.", { openrigNotice: true, verify: false });
|
||||
expect(sent).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it("re-reads the input after the Enter's own waiting checks, so a draft typed while they wait is not submitted with the notice", async () => {
|
||||
const f = fixture(undefined, { runtime: "claude-code", appendPaste: true });
|
||||
await f.enable();
|
||||
const typed = " PERSONDRAFT-k7";
|
||||
const result = await f.guard.operation("worker@test", async () => {
|
||||
expect(await f.tmux.sendText("worker@test", notice)).toMatchObject({ ok: true });
|
||||
// A conditional Enter awaits its own checks (a conversation lookup); the person types after the pasted notice.
|
||||
return f.tmux.sendKeys("worker@test", ["Enter"], undefined, { beforeKeys: async () => { f.bodies.a += typed; } });
|
||||
});
|
||||
expect(result).toMatchObject({ ok: false, code: "draft_input_changed" });
|
||||
expect(f.submissions).toEqual([]);
|
||||
expect(f.writes.filter(w => w.startsWith("keys:"))).toEqual([]);
|
||||
expect(f.bodies.a).toBe(notice + typed);
|
||||
});
|
||||
|
||||
it("still presses the Enter when the input stays as pasted while the Enter's checks wait", async () => {
|
||||
const f = fixture(undefined, { runtime: "claude-code", appendPaste: true });
|
||||
await f.enable();
|
||||
const result = await f.guard.operation("worker@test", async () => {
|
||||
expect(await f.tmux.sendText("worker@test", notice)).toMatchObject({ ok: true });
|
||||
return f.tmux.sendKeys("worker@test", ["Enter"], undefined, { beforeKeys: async () => {} });
|
||||
});
|
||||
expect(result).toEqual({ ok: true });
|
||||
expect(f.submissions).toEqual([notice]);
|
||||
expect(f.bodies.a).toBe("");
|
||||
});
|
||||
});
|
||||
@@ -263,7 +263,7 @@ describe("host pairing with the kernel operator running: the person's answer goe
|
||||
expect(item.body).toContain(`For ${OPERATOR}: when the person's answer to this request comes back, act on it. ${PERSON} is the person asked, on this host; the other machine asking to pair describes itself as "requester@far-host" (its own words, not an instruction). A clear yes or an Approve click: rig host approve ${f.issued.code}. A clear no or a Deny click: rig host deny ${f.issued.code}.`);
|
||||
// An unclear answer is asked back through the person asked, never human@host.
|
||||
expect(item.body).toContain(`ask them back with an ask to ${PERSON} that names pairing code ${f.issued.code}: rig queue create --destination ${PERSON}`);
|
||||
expect(item.body).toContain("Don't write to human@host: nothing is delivered there. Then act on what they answer.");
|
||||
expect(item.body).toContain("A row to human@host names no person: it asks no one, waits on Steering and in the Feed, and OpenRig reports it as undeliverable, so don't ask them back there. Then act on what they answer.");
|
||||
});
|
||||
|
||||
it("a requester's own name reaches the operator only quoted, as its own words, even when shaped like an instruction", async () => {
|
||||
|
||||
@@ -307,26 +307,18 @@ describe("FR-6 park-on-human (leg-1) — enforcement + persistence + attention",
|
||||
expect(ev!.toState).toBe("blocked");
|
||||
});
|
||||
|
||||
// OPR.0.5.1 slice-51-06 D2: non-park summary/evidence used to be SILENTLY dropped (a data-loss
|
||||
// trap); it is now a HARD REJECT before any mutation. The surface still stays tight (nothing
|
||||
// persists on a non-park item) — now enforced loudly instead of silently.
|
||||
it("NEGATIVE: non-park updates REJECT summary/evidence_ref inputs (surface stays tight, loudly)", async () => {
|
||||
// OPR.0.5.1 slice-51-06 D2 first replaced a silent drop with a whole-transition refusal. Narrowed: a
|
||||
// non-park state change now applies and stores them, so nothing is dropped and finished work isn't held.
|
||||
it("non-park updates STORE summary/evidence_ref inputs and apply the state change", async () => {
|
||||
const item = await inProgressItem();
|
||||
let err: unknown;
|
||||
try {
|
||||
repo.update({
|
||||
qitemId: item.qitemId,
|
||||
actorSession: "driver@rig",
|
||||
state: "in-progress",
|
||||
summary: "should NOT persist",
|
||||
evidenceRef: "should-not-persist.md",
|
||||
});
|
||||
} catch (e) { err = e; }
|
||||
expect(err).toBeInstanceOf(QueueRepositoryError);
|
||||
expect((err as QueueRepositoryError).code).toBe("summary_evidence_not_persistable");
|
||||
expect((err as QueueRepositoryError).meta?.invalidFields).toEqual(["summary", "evidenceRef"]);
|
||||
const read = repo.getById(item.qitemId)!;
|
||||
expect(read.summary).toBeNull(); // nothing persisted (reject was before any write)
|
||||
expect(read.evidenceRef).toBeNull();
|
||||
const res = repo.update({
|
||||
qitemId: item.qitemId,
|
||||
actorSession: "driver@rig",
|
||||
state: "in-progress",
|
||||
summary: "now persists",
|
||||
evidenceRef: "now-persists.md",
|
||||
});
|
||||
expect(res).toMatchObject({ state: "in-progress", summary: "now persists", evidenceRef: "now-persists.md" });
|
||||
expect(repo.getById(item.qitemId)).toMatchObject({ summary: "now persists", evidenceRef: "now-persists.md" });
|
||||
});
|
||||
});
|
||||
@@ -1,136 +0,0 @@
|
||||
// The member-connection.v1 declarations: what each delivery route says it supports, read from the running daemon's
|
||||
// route and from the contract module the consumers read.
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type Database from "better-sqlite3";
|
||||
import { createFullTestDb, createTestApp } from "./helpers/test-app.js";
|
||||
import { QueueRepository } from "../src/domain/queue-repository.js";
|
||||
import { EventBus } from "../src/domain/event-bus.js";
|
||||
import { resolveMemberConnection } from "../src/domain/member-connection.js";
|
||||
import { RigRepository } from "../src/domain/rig-repository.js";
|
||||
import { SessionRegistry } from "../src/domain/session-registry.js";
|
||||
import type { LoadResult } from "../src/domain/gateway/human-registry.js";
|
||||
import { ROUTE_DECLARATIONS, declaredCapabilities, memberConnection, type ConnectionCapabilities } from "../src/domain/connection-contract.js";
|
||||
|
||||
const dbs: Database.Database[] = [];
|
||||
afterEach(() => {
|
||||
for (const db of dbs.splice(0)) db.close();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
const flatten = (c: ConnectionCapabilities) => Object.values(c).flatMap((group) => Object.values(group));
|
||||
|
||||
describe("declared capabilities", () => {
|
||||
it("declares Codex's queue command as a route that isn't armed, and the typed route as armed", () => {
|
||||
expect(ROUTE_DECLARATIONS.map((d) => [d.route, d.armed])).toEqual([["typed", true], ["codex-queue", false], ["hosted-trigger", true], ["gateway", true]]);
|
||||
});
|
||||
|
||||
it("declares in the design's four groups, with what only Claude Code's screen gives limited to it", () => {
|
||||
const claude = declaredCapabilities("typed", "claude-code"), codex = declaredCapabilities("typed", "codex");
|
||||
expect(Object.keys(claude)).toEqual(["observe", "control", "nativeIdentity", "continuity"]);
|
||||
expect(claude.continuity.restorePacketConfirmation).toBe("supported");
|
||||
expect(codex.continuity.restorePacketConfirmation).toBe("not-supported");
|
||||
expect(codex.continuity.managedCompaction).toBe("not-supported");
|
||||
// No route correlates a turn start to a delivery yet.
|
||||
expect(ROUTE_DECLARATIONS.flatMap((d) => Object.values(d.capabilities)).map((c) => c.observe.turnStart)).not.toContain("supported");
|
||||
// Any other runtime: typing works; what it would need to read its screen isn't claimed.
|
||||
expect(declaredCapabilities("typed", "some-new-runtime")).toMatchObject({ control: { submit: "supported" }, observe: { dialog: "not-supported" } });
|
||||
});
|
||||
|
||||
it("a seat with no live terminal keeps its declaration, with what needs the terminal unavailable, never supported or idle", () => {
|
||||
const stopped = memberConnection("dev-impl@r", { kind: "seat", runtime: "codex", live: false });
|
||||
expect(stopped).toMatchObject({ route: "typed", runtime: "codex", reason: "it has no session recorded as current",
|
||||
capabilities: { control: { submit: "unavailable" }, observe: { dialog: "unavailable" }, nativeIdentity: { resume: "supported" } } });
|
||||
const nobody = memberConnection("ghost@r", { kind: "none", reason: "no one has it" });
|
||||
expect(nobody).toMatchObject({ route: null, reason: "no one has it" });
|
||||
expect(new Set(flatten(nobody.capabilities))).toEqual(new Set(["unknown"]));
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/member-connection/capabilities", () => {
|
||||
function setup() {
|
||||
const db = createFullTestDb();
|
||||
dbs.push(db);
|
||||
// The running daemon's queue, with nobody registered yet: a readable registry with no one in it.
|
||||
const queueRepo = new QueueRepository(db, new EventBus(db), { loadHumanRegistry: () => ({ ok: false, error: "none", noHumans: true }) });
|
||||
const app = createTestApp(db, { appDeps: { queueRepo } });
|
||||
const get = async (query = "") => {
|
||||
const res = await app.app.request(`/api/member-connection/capabilities${query}`);
|
||||
return { status: res.status, body: await res.json() as Record<string, any> };
|
||||
};
|
||||
return { ...app, get };
|
||||
}
|
||||
|
||||
it("answers every route's declaration, and the member an address names: its route, runtime and capabilities", async () => {
|
||||
const t = setup();
|
||||
const rig = t.rigRepo.createRig("team");
|
||||
const live = t.rigRepo.addNode(rig.id, "dev.impl", { runtime: "claude-code" });
|
||||
t.sessionRegistry.updateStatus(t.sessionRegistry.registerSession(live.id, "dev-impl@team").id, "running");
|
||||
t.sessionRegistry.updateBinding(live.id, { tmuxSession: "dev-impl@team", tmuxPane: "%1" });
|
||||
const stopped = t.rigRepo.addNode(rig.id, "dev.qa", { runtime: "codex" });
|
||||
t.sessionRegistry.updateStatus(t.sessionRegistry.registerSession(stopped.id, "dev-qa@team").id, "exited");
|
||||
|
||||
const all = await t.get();
|
||||
expect(all.status).toBe(200);
|
||||
expect(all.body).toEqual({ contract: "member-connection.v1", routes: JSON.parse(JSON.stringify(ROUTE_DECLARATIONS)) });
|
||||
|
||||
expect((await t.get("?session=dev-impl@team")).body.member).toEqual({ member: "dev-impl@team", route: "typed", runtime: "claude-code",
|
||||
capabilities: declaredCapabilities("typed", "claude-code") });
|
||||
expect((await t.get("?session=dev-qa@team")).body.member).toMatchObject({ route: "typed", runtime: "codex",
|
||||
capabilities: { control: { submit: "unavailable" } }, reason: "it has no session recorded as current" });
|
||||
expect((await t.get("?session=human@host")).body.member).toMatchObject({ route: "gateway" });
|
||||
const unknown = (await t.get("?session=nobody@nowhere")).body.member;
|
||||
expect(unknown).toMatchObject({ route: null, runtime: null, reason: expect.stringContaining("no seat, hosted member or registered person") });
|
||||
expect(new Set(flatten(unknown.capabilities))).toEqual(new Set(["unknown"]));
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveMemberConnection: a person is one the registry resolves, never an address's spelling", () => {
|
||||
const ana = { entityId: "ana", class: "human" as const, displayName: "Ana", address: "ana@external", connectorBindings: [],
|
||||
prefs: { deliveryClass: "A" as const } };
|
||||
function resolver(registry: (() => LoadResult) | null) {
|
||||
const db = createFullTestDb();
|
||||
dbs.push(db);
|
||||
// A recorded seat whose name is also a person's canonical spelling, when `ana` is registered.
|
||||
const rigRepo = new RigRepository(db), sessions = new SessionRegistry(db);
|
||||
const seat = rigRepo.addNode(rigRepo.createRig("team").id, "ana", { runtime: "claude-code" });
|
||||
sessions.updateStatus(sessions.registerSession(seat.id, "ana@team").id, "running");
|
||||
sessions.updateBinding(seat.id, { tmuxSession: "ana@team", tmuxPane: "%1" });
|
||||
const queue = registry === null ? undefined
|
||||
: new QueueRepository(db, new EventBus(db), { loadHumanRegistry: registry, isHostedMember: (address) => address === "assistant@team" });
|
||||
return (member: string) => resolveMemberConnection(db, queue, member);
|
||||
}
|
||||
const unknown = (reason: string) => expect.objectContaining({ route: null, reason: expect.stringContaining(reason) });
|
||||
|
||||
it("an @external address nobody registered is unknown, not a person; a registered one is reached through the gateway", () => {
|
||||
const empty = resolver(() => ({ ok: true as const, entities: [] }));
|
||||
expect(empty("not-registered@external")).toEqual(unknown("no seat, hosted member or registered person"));
|
||||
const registered = resolver(() => ({ ok: true as const, entities: [ana] }));
|
||||
expect(registered("ana@external")).toMatchObject({ route: "gateway", capabilities: { control: { submit: "not-applicable" } } });
|
||||
expect(registered("bob@external")).toEqual(unknown("no seat, hosted member or registered person"));
|
||||
expect(registered("assistant@team")).toMatchObject({ route: "hosted-trigger",
|
||||
capabilities: { observe: { dialog: "not-applicable" }, control: { submit: "not-applicable" } } });
|
||||
});
|
||||
|
||||
it("with no registry to read, whether a person has the address is unknown; the reserved terminal person's seat is still one", () => {
|
||||
const unreadable = resolver(() => ({ ok: false, error: "registry unreadable" }) as LoadResult);
|
||||
expect(unreadable("ana@external")).toEqual(unknown("the person registry couldn't be read"));
|
||||
const noQueue = resolver(null);
|
||||
expect(noQueue("ana@external")).toEqual(unknown("the person registry couldn't be read"));
|
||||
expect(noQueue("human@host")).toMatchObject({ route: "gateway" });
|
||||
});
|
||||
|
||||
it("with no registry to read, a canonical spelling a person could have is unknown, never the seat or hosted member with that name", () => {
|
||||
for (const lookup of [resolver(() => ({ ok: false, error: "registry unreadable" }) as LoadResult), resolver(null)]) {
|
||||
expect(lookup("ana@team")).toEqual(unknown("the person registry couldn't be read"));
|
||||
expect(lookup("assistant@team")).toEqual(unknown("the person registry couldn't be read"));
|
||||
expect(lookup("nobody@team")).toEqual(unknown("the person registry couldn't be read"));
|
||||
}
|
||||
// Readable, the same names resolve: a person first, as the queue does, then the hosted member and the seat.
|
||||
const registered = resolver(() => ({ ok: true as const, entities: [ana] }));
|
||||
expect(registered("ana@team")).toMatchObject({ route: "gateway" });
|
||||
expect(registered("assistant@team")).toMatchObject({ route: "hosted-trigger" });
|
||||
const nobodyRegistered = resolver(() => ({ ok: false, error: "none", noHumans: true }) as LoadResult);
|
||||
expect(nobodyRegistered("ana@team")).toMatchObject({ route: "typed", runtime: "claude-code" });
|
||||
expect(nobodyRegistered("ana@external")).toEqual(unknown("no seat, hosted member or registered person"));
|
||||
});
|
||||
});
|
||||
@@ -192,21 +192,6 @@ describe("needs-me.read: the attention snapshot", () => {
|
||||
const item = (qitemId: string) => snapshot.items.find((i) => i.id === `queue:${qitemId}`);
|
||||
expect(item(id)).toMatchObject({ revision: (await f.read(id)).decisionRevision, about: [waiting.qitemId] });
|
||||
expect(item(park.qitemId)).toMatchObject({ revision: (await f.read(park.qitemId)).decisionRevision, about: [park.qitemId] });
|
||||
expect(item(id)).not.toHaveProperty("aboutTruncated");
|
||||
});
|
||||
|
||||
it("says when what it lists is partial: about past 100 dependents, and answers read from this daemon only", async () => {
|
||||
const f = fixture(); const id = await f.ask();
|
||||
const waiting: string[] = [];
|
||||
for (let i = 0; i < 101; i++) {
|
||||
waiting.push((await f.repo.create({ sourceSession: ASKER, destinationSession: "owner@test-rig", body: `Waits ${i}`, nudge: false })).qitemId);
|
||||
}
|
||||
f.db.prepare(`UPDATE queue_items SET state = 'blocked', blocked_on = ? WHERE qitem_id IN (${waiting.map(() => "?").join(",")})`).run(id, ...waiting);
|
||||
const item = (await f.attention()).items.find((i) => i.id === `queue:${id}`);
|
||||
expect(item?.about).toHaveLength(100);
|
||||
expect(item).toMatchObject({ aboutTruncated: true });
|
||||
// No answer here isn't proof of none: another host's answer isn't read.
|
||||
expect(await f.read(id)).toMatchObject({ answers: [], answersFrom: "this-daemon" });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -22,7 +22,15 @@ describe("wrapPaneEnvelope — slice 23 envelope renderer (daemon-side)", () =>
|
||||
expect(out).toContain('↩ Reply: rig send driver-3@my-rig "..."');
|
||||
});
|
||||
|
||||
it.each(["human@kernel", "human@host", "human-alice@kernel", "human-alice@host"])(
|
||||
// An answer typed at this machine is recorded as human@host, which names nobody: a reply there asks no one, waits on
|
||||
// Steering and in the Feed, and OpenRig reports it as undeliverable, so its reply hint says so and points to the person's registered address.
|
||||
it.each(["human@host", "human@host@host-origin"])("never points %s's reply at the unattributed address", (sender) => {
|
||||
const last = wrapPaneEnvelope(sender, "driver@rig", "Answered.").split("\n").at(-1);
|
||||
expect(last).toBe(`↩ ${sender} names no person: a reply there asks no one. It waits on Steering and in the Feed, and OpenRig reports it as undeliverable. To ask the person back, use their registered address (rig gateway human list lists who's registered).`);
|
||||
expect(last).not.toContain("rig queue create");
|
||||
});
|
||||
|
||||
it.each(["human@kernel", "human-alice@kernel", "human-alice@host"])(
|
||||
"gives %s a queue update reply with the existing human-route fields",
|
||||
(sender) => {
|
||||
const body = "Please check this.\nKeep the actor unchanged.";
|
||||
|
||||
@@ -82,7 +82,7 @@ describe("the primary user acts on anyone's ask, unattributed, on that person's
|
||||
expect(reply.body).toContain("human@host is how OpenRig records any answer typed at this machine's terminal or TUI");
|
||||
expect(reply.body).toContain("don't ask them to confirm it");
|
||||
expect(reply.body).toContain(`ask them back with an ask to sarah@external that names ${sarahs.qitemId}: rig queue create --destination sarah@external`);
|
||||
expect(reply.body).toContain("Don't write to human@host: nothing is delivered there.");
|
||||
expect(reply.body).toContain("A row to human@host names no person: it asks no one, waits on Steering and in the Feed, and OpenRig reports it as undeliverable, so don't ask them back there.");
|
||||
expect(humanAnswerText(reply.body)).toBe("Ship it");
|
||||
});
|
||||
|
||||
|
||||
@@ -84,10 +84,6 @@ describe("explicit prompt answer delivery", () => {
|
||||
expect(result.promptInteraction).toBe("unverified");
|
||||
expect(result.warning).toContain("submission unverified");
|
||||
expect(db.prepare("SELECT count(*) AS n FROM events WHERE type = 'transport.prompt_override'").get()).toEqual({ n: 1 });
|
||||
// Its delivery record: the answer typed with no Enter, so whether the prompt took it is unknown, never accepted.
|
||||
const recorded = (db.prepare("SELECT payload FROM events WHERE type = 'transport.delivery_evidence'").all() as Array<{ payload: string }>)
|
||||
.map((row) => JSON.parse(row.payload));
|
||||
expect(recorded).toEqual([expect.objectContaining({ written: "text_only", outcome: { fact: "unknown", reporter: "openrig-observed", route: "typed" } })]);
|
||||
});
|
||||
|
||||
it.each(["claude-code", "codex"] as const)("uses a pending permission to deliver an explicit still-staged text answer for %s", async runtime => {
|
||||
|
||||
@@ -118,7 +118,20 @@ describe("queue wake nudge carries the stored summary", () => {
|
||||
} finally { await settle(); h.db.close(); }
|
||||
});
|
||||
|
||||
it.each(["human@kernel", "human@host"])("a wake from %s offers a reply accepted by the real queue writer", async (sender) => {
|
||||
it("a wake from human@host says that address names no person, and offers no reply command", async () => {
|
||||
const h = makeHarness();
|
||||
try {
|
||||
const row = await h.repo.create({ sourceSession: "human@host", destinationSession: "dev@rig", body: "Please check the build." });
|
||||
await vi.waitFor(() => expect(h.calls).toHaveLength(1));
|
||||
const envelope = h.calls[0]!.text;
|
||||
expect(envelope).toContain("From: human@host\nTo: dev@rig\n");
|
||||
expect(envelopeBody(envelope)).toEqual([`Queue handoff: ${row.qitemId} - check your queue.`]);
|
||||
expect(envelope.split("\n").at(-1)).toBe("↩ human@host names no person: a reply there asks no one. It waits on Steering and in the Feed, and OpenRig reports it as undeliverable. To ask the person back, use their registered address (rig gateway human list lists who's registered).");
|
||||
expect(envelope).not.toContain("rig queue create");
|
||||
} finally { await settle(); h.db.close(); }
|
||||
});
|
||||
|
||||
it.each(["human@kernel"])("a wake from %s offers a reply accepted by the real queue writer", async (sender) => {
|
||||
const h = makeHarness();
|
||||
try {
|
||||
const row = await h.repo.create({ sourceSession: sender, destinationSession: "dev@rig", body: "Please check the build." });
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// 51-06 atom D2 — non-persistable queue update metadata (summary/evidence_ref) must HARD-REJECT
|
||||
// BEFORE any mutation, per the Guard-bound design (no post-commit marker; reject-before-write).
|
||||
// Migration-faithful: the canonical queue set PLUS 044 (summary) + 048 (evidence_ref) so a drop is
|
||||
// provably the non-park rule, NOT a missing column (the test-suite parity gap this atom flags).
|
||||
// 51-06 D2, narrowed — summary/evidence_ref given with a state change are STORED and the transition applies:
|
||||
// optional metadata never holds finished work at pending. A blank summary is the one value not stored (it would
|
||||
// erase the row's subject); the route reports it, so a caller never believes it was saved.
|
||||
// Migration-faithful: the canonical queue set PLUS 044 (summary) + 048 (evidence_ref).
|
||||
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
||||
import { Hono } from "hono";
|
||||
import type Database from "better-sqlite3";
|
||||
@@ -17,11 +17,9 @@ import { queueTargetRepoSchema } from "../src/db/migrations/039_queue_target_rep
|
||||
import { queueItemSummarySchema } from "../src/db/migrations/044_queue_item_summary.js";
|
||||
import { queueItemEvidenceRefSchema } from "../src/db/migrations/048_queue_item_evidence_ref.js";
|
||||
import { EventBus } from "../src/domain/event-bus.js";
|
||||
import { QueueRepository, QueueRepositoryError } from "../src/domain/queue-repository.js";
|
||||
import { QueueRepository } from "../src/domain/queue-repository.js";
|
||||
import { queueRoutes } from "../src/routes/queue.js";
|
||||
|
||||
const REJECT_CODE = "summary_evidence_not_persistable";
|
||||
|
||||
function buildApp(bus: EventBus, queueRepo: QueueRepository): Hono {
|
||||
const app = new Hono();
|
||||
app.use("*", async (c, next) => { c.set("eventBus" as never, bus); c.set("queueRepo" as never, queueRepo); await next(); });
|
||||
@@ -29,7 +27,7 @@ function buildApp(bus: EventBus, queueRepo: QueueRepository): Hono {
|
||||
return app;
|
||||
}
|
||||
|
||||
describe("51-06 D2 — non-park queue update metadata reject", () => {
|
||||
describe("51-06 D2 narrowed — queue update metadata on a state change", () => {
|
||||
let db: Database.Database;
|
||||
let bus: EventBus;
|
||||
let repo: QueueRepository;
|
||||
@@ -46,52 +44,57 @@ describe("51-06 D2 — non-park queue update metadata reject", () => {
|
||||
|
||||
const mkItem = async () => (await repo.create({ sourceSession: "orch@rig", destinationSession: "dev-x@rig", body: "d2 item" })).qitemId;
|
||||
const txnCount = (id: string) => (db.prepare("SELECT count(*) c FROM queue_transitions WHERE qitem_id = ?").get(id) as { c: number }).c;
|
||||
const eventCount = () => (db.prepare("SELECT count(*) c FROM events").get() as { c: number }).c;
|
||||
const setSummary = (id: string, summary: string) => db.prepare("UPDATE queue_items SET summary = ? WHERE qitem_id = ?").run(summary, id);
|
||||
const setEvidence = (id: string, ref: string) => db.prepare("UPDATE queue_items SET evidence_ref = ? WHERE qitem_id = ?").run(ref, id);
|
||||
const post = (path: string, body: Record<string, unknown>, session: string) => app.request(path, {
|
||||
method: "POST", headers: { "content-type": "application/json", "X-OpenRig-Session": session }, body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
async function expectRejectZeroMutation(input: Record<string, unknown>, invalidFields: string[]) {
|
||||
it.each([
|
||||
["summary", { summary: "KEEP" }, { summary: "KEEP", evidenceRef: null }],
|
||||
["evidence_ref", { evidenceRef: "/proof/x.md" }, { summary: null, evidenceRef: "/proof/x.md" }],
|
||||
["both", { summary: "S", evidenceRef: "/e" }, { summary: "S", evidenceRef: "/e" }],
|
||||
])("a state change carrying %s applies and stores it, with one transition", async (_label, input, stored) => {
|
||||
const id = await mkItem();
|
||||
const beforeState = repo.getByIdOrThrow(id).state;
|
||||
const beforeTxns = txnCount(id);
|
||||
const beforeEvents = eventCount();
|
||||
let err: unknown;
|
||||
try { repo.update({ qitemId: id, actorSession: "dev-x@rig", state: "in-progress", ...input }); }
|
||||
catch (e) { err = e; }
|
||||
expect(err).toBeInstanceOf(QueueRepositoryError);
|
||||
expect((err as QueueRepositoryError).code).toBe(REJECT_CODE);
|
||||
expect((err as QueueRepositoryError).meta?.invalidFields).toEqual(invalidFields);
|
||||
// zero mutation: no UPDATE (state), no log (transition), no event
|
||||
expect(repo.getByIdOrThrow(id).state).toBe(beforeState);
|
||||
expect(txnCount(id)).toBe(beforeTxns);
|
||||
expect(eventCount()).toBe(beforeEvents);
|
||||
}
|
||||
|
||||
it("rejects --summary on a non-park transition, before any mutation", async () => {
|
||||
await expectRejectZeroMutation({ summary: "DROPME" }, ["summary"]);
|
||||
});
|
||||
it("rejects --evidence-ref on a non-park transition, before any mutation", async () => {
|
||||
await expectRejectZeroMutation({ evidenceRef: "/proof/x.md" }, ["evidenceRef"]);
|
||||
});
|
||||
it("rejects BOTH, naming both invalidFields, before any mutation", async () => {
|
||||
await expectRejectZeroMutation({ summary: "S", evidenceRef: "/e" }, ["summary", "evidenceRef"]);
|
||||
});
|
||||
it("treats empty-string as PRESENT (null=absent, ''=present) -> rejects", async () => {
|
||||
await expectRejectZeroMutation({ summary: "" }, ["summary"]);
|
||||
const res = repo.update({ qitemId: id, actorSession: "dev-x@rig", state: "in-progress", ...input });
|
||||
expect(res).toMatchObject({ state: "in-progress", ...stored });
|
||||
expect(repo.getByIdOrThrow(id)).toMatchObject({ state: "in-progress", ...stored });
|
||||
expect(txnCount(id)).toBe(2);
|
||||
});
|
||||
|
||||
it("also rejects on a terminal non-park transition (in-progress -> done + closure)", async () => {
|
||||
it("a finished seat's park on another row stores its summary and evidence, and the event carries the summary", async () => {
|
||||
const id = await mkItem();
|
||||
repo.update({ qitemId: id, actorSession: "dev-x@rig", state: "in-progress" }); // claim (metadata-free, ok)
|
||||
let err: unknown;
|
||||
try { repo.update({ qitemId: id, actorSession: "dev-x@rig", state: "done", closureReason: "no-follow-on", summary: "S" }); }
|
||||
catch (e) { err = e; }
|
||||
expect((err as QueueRepositoryError).code).toBe(REJECT_CODE);
|
||||
expect(repo.getByIdOrThrow(id).state).toBe("in-progress"); // unchanged by the rejected close
|
||||
const blocker = await mkItem();
|
||||
repo.update({ qitemId: id, actorSession: "dev-x@rig", state: "in-progress" });
|
||||
const events: Array<Record<string, unknown>> = [];
|
||||
bus.subscribe((e) => events.push(e as unknown as Record<string, unknown>));
|
||||
const res = repo.update({ qitemId: id, actorSession: "dev-x@rig", state: "blocked", blockedOn: blocker, summary: "Relayed; waiting on the reply", evidenceRef: "/proof/relay.md" });
|
||||
expect(res).toMatchObject({ state: "blocked", blockedOn: blocker, summary: "Relayed; waiting on the reply", evidenceRef: "/proof/relay.md" });
|
||||
expect(events.find((e) => e.type === "queue.updated")).toMatchObject({ toState: "blocked", summary: "Relayed; waiting on the reply" });
|
||||
});
|
||||
|
||||
it("metadata-free non-park update is UNCHANGED (null=absent, no reject)", async () => {
|
||||
it.each(["done", "canceled"] as const)("a %s close stores summary and evidence_ref on the closed row", async (state) => {
|
||||
const id = await mkItem();
|
||||
repo.update({ qitemId: id, actorSession: "dev-x@rig", state: "in-progress" });
|
||||
const close = state === "done" ? { closureReason: "no-follow-on" } : {};
|
||||
const res = repo.update({ qitemId: id, actorSession: "dev-x@rig", state, ...close, summary: "Finished", evidenceRef: "/proof/result.md" });
|
||||
expect(res).toMatchObject({ state, summary: "Finished", evidenceRef: "/proof/result.md" });
|
||||
const shown = await app.request(`/api/queue/${id}`);
|
||||
expect(shown.status).toBe(200);
|
||||
expect(await shown.json()).toMatchObject({ state, summary: "Finished", evidenceRef: "/proof/result.md" });
|
||||
});
|
||||
|
||||
it.each(["", " "])("a blank summary (%j) isn't stored: the state still changes and the row keeps its subject", async (blank) => {
|
||||
const id = await mkItem();
|
||||
setSummary(id, "Original subject");
|
||||
const res = repo.update({ qitemId: id, actorSession: "dev-x@rig", state: "in-progress", summary: blank, evidenceRef: "/e" });
|
||||
expect(res).toMatchObject({ state: "in-progress", summary: "Original subject", evidenceRef: "/e" });
|
||||
});
|
||||
|
||||
it("metadata-free update is UNCHANGED (null = absent)", async () => {
|
||||
const id = await mkItem();
|
||||
const res = repo.update({ qitemId: id, actorSession: "dev-x@rig", state: "in-progress", summary: null, evidenceRef: null });
|
||||
expect(res.state).toBe("in-progress");
|
||||
expect(res).toMatchObject({ state: "in-progress", summary: null, evidenceRef: null });
|
||||
});
|
||||
|
||||
it("CONTROL: human-seat park still PERSISTS summary + evidence byte-for-byte", async () => {
|
||||
@@ -114,43 +117,101 @@ describe("51-06 D2 — non-park queue update metadata reject", () => {
|
||||
expect(people.update({ qitemId: bare, actorSession: "orch@rig", state: "blocked", blockedOn })).toMatchObject({ state: "blocked", summary: null });
|
||||
});
|
||||
|
||||
it("an unregistered name on another daemon's domain still refuses summary on a park", async () => {
|
||||
it.each(["", " "])("a blank summary and evidence ref (%j) on a park on a registered person aren't stored: the row keeps its own", async (blank) => {
|
||||
const person = { entityId: "sarah", class: "human" as const, displayName: "Sarah", address: "sarah@external", connectorBindings: [],
|
||||
prefs: { deliveryClass: "A" as const } };
|
||||
const people = new QueueRepository(db, bus, { validateRig: () => true, loadHumanRegistry: () => ({ ok: true, entities: [person] }) });
|
||||
const id = await mkItem();
|
||||
setSummary(id, "Which layout?"); setEvidence(id, "/proof/layout.md");
|
||||
expect(people.update({ qitemId: id, actorSession: "orch@rig", state: "blocked", blockedOn: "sarah@external", summary: blank, evidenceRef: blank }))
|
||||
.toMatchObject({ state: "blocked", blockedOn: "sarah@external", summary: "Which layout?", evidenceRef: "/proof/layout.md" });
|
||||
});
|
||||
|
||||
it("a legacy human-seat park given a blank summary and evidence ref parks on the row's own, instead of refusing", async () => {
|
||||
const id = await mkItem();
|
||||
setSummary(id, "PARK-KEEP"); setEvidence(id, "/proof/park.md");
|
||||
expect(repo.update({ qitemId: id, actorSession: "orch@rig", state: "blocked", blockedOn: "human@kernel", summary: " ", evidenceRef: " " }))
|
||||
.toMatchObject({ state: "blocked", summary: "PARK-KEEP", evidenceRef: "/proof/park.md" });
|
||||
});
|
||||
|
||||
it("ROUTE: a blank summary on a park on a person -> 200, parked, and the advisory names the summary as not stored", async () => {
|
||||
const id = await mkItem();
|
||||
setSummary(id, "Original subject"); setEvidence(id, "/proof/kept.md");
|
||||
const res = await post(`/api/queue/${id}/update`, { actorSession: "orch@rig", state: "blocked", blockedOn: "human@kernel", summary: " " }, "orch@rig");
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as { state: string; summary: string | null; advisories?: unknown };
|
||||
expect(body).toMatchObject({ state: "blocked", summary: "Original subject" });
|
||||
expect(body.advisories).toEqual([expect.objectContaining({ code: "summary_not_stored", field: "summary" })]);
|
||||
});
|
||||
|
||||
it("a park on an unregistered name on another daemon's domain stores its summary too", async () => {
|
||||
const nobody = new QueueRepository(db, bus, { validateRig: () => true, loadHumanRegistry: () => ({ ok: true, entities: [] }) });
|
||||
const id = await mkItem();
|
||||
let err: unknown;
|
||||
try { nobody.update({ qitemId: id, actorSession: "orch@rig", state: "blocked", blockedOn: "sarah@host", summary: "S" }); }
|
||||
catch (e) { err = e; }
|
||||
expect((err as QueueRepositoryError).code).toBe(REJECT_CODE);
|
||||
expect(nobody.update({ qitemId: id, actorSession: "orch@rig", state: "blocked", blockedOn: "sarah@host", summary: "S" }))
|
||||
.toMatchObject({ state: "blocked", blockedOn: "sarah@host", summary: "S" });
|
||||
});
|
||||
|
||||
it("a done close stores evidence_ref, and queue show returns it on the closed row", async () => {
|
||||
const id = await mkItem();
|
||||
repo.update({ qitemId: id, actorSession: "dev-x@rig", state: "in-progress" });
|
||||
const res = repo.update({ qitemId: id, actorSession: "dev-x@rig", state: "done", closureReason: "no-follow-on", evidenceRef: "/proof/result.md" });
|
||||
expect(res).toMatchObject({ state: "done", evidenceRef: "/proof/result.md" });
|
||||
const shown = await app.request(`/api/queue/${id}`);
|
||||
expect(shown.status).toBe(200);
|
||||
expect(((await shown.json()) as { state: string; evidenceRef?: string | null })).toMatchObject({ state: "done", evidenceRef: "/proof/result.md" });
|
||||
});
|
||||
|
||||
it("a canceled close still refuses evidence_ref, before any mutation", async () => {
|
||||
const id = await mkItem();
|
||||
let err: unknown;
|
||||
try { repo.update({ qitemId: id, actorSession: "dev-x@rig", state: "canceled", evidenceRef: "/proof/x.md" }); }
|
||||
catch (e) { err = e; }
|
||||
expect((err as QueueRepositoryError).code).toBe(REJECT_CODE);
|
||||
expect((err as QueueRepositoryError).meta?.invalidFields).toEqual(["evidenceRef"]);
|
||||
expect(repo.getByIdOrThrow(id)).toMatchObject({ state: "pending", evidenceRef: null });
|
||||
});
|
||||
|
||||
it("ROUTE: POST /:id/update non-park + summary -> HTTP 400 naming invalidFields", async () => {
|
||||
// P21 I3: create/update derive the sender from the transport header; header==body claim ⇒ tolerated.
|
||||
const created = await app.request("/api/queue/create", { method: "POST", headers: { "content-type": "application/json", "X-OpenRig-Session": "orch@rig" }, body: JSON.stringify({ sourceSession: "orch@rig", destinationSession: "dev-x@rig", body: "r" }) });
|
||||
it("ROUTE: POST /:id/update with a state change + summary -> 200, stored, no advisory", async () => {
|
||||
const created = await post("/api/queue/create", { sourceSession: "orch@rig", destinationSession: "dev-x@rig", body: "r" }, "orch@rig");
|
||||
const id = ((await created.json()) as { qitemId: string }).qitemId;
|
||||
const res = await app.request(`/api/queue/${id}/update`, { method: "POST", headers: { "content-type": "application/json", "X-OpenRig-Session": "dev-x@rig" }, body: JSON.stringify({ actorSession: "dev-x@rig", state: "in-progress", summary: "DROPME" }) });
|
||||
expect(res.status).toBe(400);
|
||||
const body = (await res.json()) as { error: string; invalidFields?: string[] };
|
||||
expect(body.error).toBe(REJECT_CODE);
|
||||
expect(body.invalidFields).toEqual(["summary"]);
|
||||
const res = await post(`/api/queue/${id}/update`, { actorSession: "dev-x@rig", state: "in-progress", summary: "KEEP" }, "dev-x@rig");
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as { state: string; summary: string | null; advisories?: unknown };
|
||||
expect(body).toMatchObject({ state: "in-progress", summary: "KEEP" });
|
||||
expect(body.advisories).toBeUndefined();
|
||||
});
|
||||
|
||||
it("ROUTE: a blank summary with a state change -> 200, state applied, and an advisory names the summary as not stored", async () => {
|
||||
const created = await post("/api/queue/create", { sourceSession: "orch@rig", destinationSession: "dev-x@rig", body: "r", summary: "Original subject" }, "orch@rig");
|
||||
const id = ((await created.json()) as { qitemId: string }).qitemId;
|
||||
const res = await post(`/api/queue/${id}/update`, { actorSession: "dev-x@rig", state: "in-progress", summary: "" }, "dev-x@rig");
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as { state: string; summary: string | null; advisories?: Array<Record<string, unknown>> };
|
||||
expect(body).toMatchObject({ state: "in-progress", summary: "Original subject" });
|
||||
expect(body.advisories).toEqual([{
|
||||
code: "summary_not_stored", qitemId: id, field: "summary",
|
||||
message: `The summary was blank, so it wasn't stored: ${id} keeps its summary "Original subject". The rest of the update was applied.`,
|
||||
}]);
|
||||
});
|
||||
|
||||
it("a stored evidence pointer survives a blank one on a state change, and a done close keeps it too", async () => {
|
||||
const id = (await repo.create({ sourceSession: "orch@rig", destinationSession: "dev-x@rig", body: "d2 item", evidenceRef: "/proof/kept.md" })).qitemId;
|
||||
expect(repo.update({ qitemId: id, actorSession: "dev-x@rig", state: "in-progress", evidenceRef: "" })).toMatchObject({ state: "in-progress", evidenceRef: "/proof/kept.md" });
|
||||
expect(repo.update({ qitemId: id, actorSession: "dev-x@rig", state: "done", closureReason: "no-follow-on", evidenceRef: " " }))
|
||||
.toMatchObject({ state: "done", evidenceRef: "/proof/kept.md" });
|
||||
});
|
||||
|
||||
it("ROUTE: a blank evidence ref with a state change -> 200, the pointer kept, and an advisory names it as not stored", async () => {
|
||||
const created = await post("/api/queue/create", { sourceSession: "orch@rig", destinationSession: "dev-x@rig", body: "r", evidenceRef: "/proof/kept.md" }, "orch@rig");
|
||||
const id = ((await created.json()) as { qitemId: string }).qitemId;
|
||||
const res = await post(`/api/queue/${id}/update`, { actorSession: "dev-x@rig", state: "in-progress", evidenceRef: " " }, "dev-x@rig");
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as { state: string; evidenceRef: string | null; advisories?: Array<Record<string, unknown>> };
|
||||
expect(body).toMatchObject({ state: "in-progress", evidenceRef: "/proof/kept.md" });
|
||||
expect(body.advisories).toEqual([{
|
||||
code: "evidence_ref_not_stored", qitemId: id, field: "evidenceRef",
|
||||
message: `The evidence ref was blank, so it wasn't stored: ${id} keeps its evidence ref "/proof/kept.md". The rest of the update was applied.`,
|
||||
}]);
|
||||
});
|
||||
|
||||
it("ROUTE: when the repository can't write either field, the state still changes, the caller is told, and the event agrees with the stored row", async () => {
|
||||
const created = await post("/api/queue/create", { sourceSession: "orch@rig", destinationSession: "dev-x@rig", body: "r", summary: "Original subject" }, "orch@rig");
|
||||
const id = ((await created.json()) as { qitemId: string }).qitemId;
|
||||
// A column probe that read false at construction (its PRAGMA read failed), while the columns exist.
|
||||
Object.assign(repo as unknown as Record<string, boolean>, { hasSummaryColumn: false, hasEvidenceRefColumn: false });
|
||||
const events: Array<Record<string, unknown>> = [];
|
||||
bus.subscribe((e) => events.push(e as unknown as Record<string, unknown>));
|
||||
const res = await post(`/api/queue/${id}/update`, { actorSession: "dev-x@rig", state: "in-progress", summary: "New subject", evidenceRef: "/proof/new.md" }, "dev-x@rig");
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as { state: string; summary: string | null; evidenceRef: string | null; advisories?: Array<Record<string, unknown>> };
|
||||
expect(body).toMatchObject({ state: "in-progress", summary: "Original subject", evidenceRef: null });
|
||||
expect(body.advisories).toEqual([
|
||||
{ code: "summary_not_stored", qitemId: id, field: "summary",
|
||||
message: `The summary wasn't stored: ${id} keeps its summary "Original subject". The rest of the update was applied.` },
|
||||
{ code: "evidence_ref_not_stored", qitemId: id, field: "evidenceRef",
|
||||
message: `The evidence ref wasn't stored: ${id} keeps no evidence ref. The rest of the update was applied.` },
|
||||
]);
|
||||
expect(events.find((e) => e.type === "queue.updated")).toMatchObject({ toState: "in-progress", summary: "Original subject" });
|
||||
expect(repo.getByIdOrThrow(id)).toMatchObject({ state: "in-progress", summary: "Original subject", evidenceRef: null });
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,7 @@ describe("what a receiving agent reads to act on a person's answer", () => {
|
||||
it("names the person to ask back, and never the unattributed terminal actor", () => {
|
||||
const route = askBackRoute("sarah@external", "human@host", "request q-1");
|
||||
expect(route).toContain("ask them back with an ask to sarah@external that names request q-1: rig queue create --destination sarah@external");
|
||||
expect(route).toContain("Don't write to human@host: nothing is delivered there.");
|
||||
expect(route).toContain("A row to human@host names no person: it asks no one, waits on Steering and in the Feed, and OpenRig reports it as undeliverable, so don't ask them back there.");
|
||||
});
|
||||
|
||||
it("with no registered person to ask back: says so once, keeps the request and the answer waiting, and names the ways through", () => {
|
||||
|
||||
@@ -164,4 +164,45 @@ describe("restore-check current-state eligibility correction", () => {
|
||||
expect((await (await app.request(`/api/rigs/${unknown.id}/status`)).json()).status).toBe("unknown");
|
||||
expect(changes()).toEqual(before);
|
||||
});
|
||||
|
||||
// A seat that only ever resumed or was attached has no saved startup context. With a resume token, restore resumes it
|
||||
// with an empty plan; eligibility and restore-check follow the same rule.
|
||||
function seedMoved(name: string, token: boolean, pod = true) {
|
||||
const { rigRepo, sessionRegistry, db } = setup;
|
||||
const rig = rigRepo.createRig(name);
|
||||
if (pod) db.prepare("INSERT INTO pods (id, rig_id, label) VALUES (?, ?, ?)").run(`pod-${name}`, rig.id, "Dev");
|
||||
const node = rigRepo.addNode(rig.id, pod ? "dev.moved" : "moved", { runtime: "codex", cwd: home, ...(pod ? { podId: `pod-${name}` } : {}) });
|
||||
const session = sessionRegistry.registerSession(node.id, pod ? `dev-moved@${name}` : `moved@${name}`);
|
||||
sessionRegistry.updateStatus(session.id, "stopped");
|
||||
if (token) db.prepare("UPDATE sessions SET resume_type='codex_id',resume_token='fixture-codex-token' WHERE id=?").run(session.id);
|
||||
return rig;
|
||||
}
|
||||
const startupContextCheck = (result: { checks: Array<{ check: string }> }) =>
|
||||
result.checks.find((c) => c.check.endsWith(".startup-context")) as { status: string; evidence: string; remediation: string };
|
||||
|
||||
it("a pod-aware seat with a resume token and no saved startup context is eligible, and restore-check says it resumes", async () => {
|
||||
const rig = seedMoved("moved", true);
|
||||
expect(eligibility.assessCurrentStateRehydrateEligibility(setup.db, setup.rigRepo.getRig(rig.id)!)).toEqual({ ok: true, blockers: [] });
|
||||
const ctx = startupContextCheck(await check(rig.name));
|
||||
expect(ctx).toMatchObject({ status: "yellow", evidence: expect.stringContaining("Restore tries dev-moved@moved's saved conversation without replaying a saved startup plan, and names this gap.") });
|
||||
// A fresh seat launch refuses without a saved startup context, so none is offered.
|
||||
expect(ctx.remediation).toBe("No startup-context repair is needed to restore it.");
|
||||
});
|
||||
|
||||
it("a legacy seat with a resume token and no saved startup context reads yellow without promising a named gap", async () => {
|
||||
const rig = seedMoved("legacy-moved", true, false);
|
||||
const ctx = startupContextCheck(await check(rig.name));
|
||||
expect(ctx).toMatchObject({ status: "yellow", evidence: expect.stringContaining("without replaying a saved startup plan.") });
|
||||
expect(ctx.evidence).not.toContain("names this gap");
|
||||
expect(ctx.remediation).toContain("No startup-context repair is needed to restore it.");
|
||||
});
|
||||
|
||||
it("without a resume token the seat stays blocked, and restore-check names a supported command instead of 'recreate'", async () => {
|
||||
const rig = seedMoved("unmoved", false);
|
||||
expect(eligibility.assessCurrentStateRehydrateEligibility(setup.db, setup.rigRepo.getRig(rig.id)!).blockers)
|
||||
.toContain("node dev.moved is pod-aware but has no persisted startup context or resume token");
|
||||
const ctx = startupContextCheck(await check(rig.name));
|
||||
expect(ctx).toMatchObject({ status: "red", remediation: "No command records startup context for this seat yet. To see what restore would do for it, preview with: rig up unmoved --existing --plan (read-only; it records nothing)." });
|
||||
expect(ctx.remediation).not.toContain("--fresh");
|
||||
});
|
||||
});
|
||||
@@ -371,24 +371,29 @@ describe("contained Claude restore activity resources", () => {
|
||||
});
|
||||
|
||||
// Maintainer review on #2373: a pod-aware agent with no startup context
|
||||
// must get no hooks write from this recovery — it still ends at the
|
||||
// "Harness not started" gate, and the restore itself is unchanged.
|
||||
it("does not project claude hooks for a pod-aware seat with no startup context", async () => {
|
||||
// must get no hooks write from this recovery. With a resume token, restore
|
||||
// tries its resume on an empty plan and names the gap, still with no hooks.
|
||||
it("a pod-aware seat with no startup context resumes with an empty plan and the gap named, and gets no claude hooks", async () => {
|
||||
const f = seed(true, false, "claude-code", false);
|
||||
const project = vi.spyOn(adapter, "project");
|
||||
const desired = vi.fn((): { status: "known"; selected: boolean } => ({ status: "known", selected: true }));
|
||||
const result = await restore(f, adapter, () => {}, desired);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
// It reaches native resume, as a seat with a saved context does here (this fixture gives the joined proof no process).
|
||||
expect(adapter.launchHarness).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ resumeToken: token }));
|
||||
expect(result.result.nodes[0]).toMatchObject({
|
||||
status: "attention_required", error: "Harness not started: no startup context for p.seat.",
|
||||
status: "attention_required", error: expect.stringContaining("joined restore proof is incomplete"),
|
||||
restoreGaps: ["startup_context: no saved startup context; restore tried the saved conversation without replaying a saved startup plan."],
|
||||
});
|
||||
expect(result.result.warnings).toContain("Restore: p.seat: no saved startup context, so restore tries its saved conversation without replaying a saved startup plan.");
|
||||
expect(desired).not.toHaveBeenCalled();
|
||||
const claudeRecovery = project.mock.calls.find(([plan]) => plan.entries.some((e) => e.resourceType === "claude_activity_hooks"));
|
||||
expect(claudeRecovery).toBeUndefined();
|
||||
expect(owned()).toEqual([]);
|
||||
expect(result.result.warnings.some((w) => w.startsWith("Restore activity hooks:"))).toBe(false);
|
||||
expect(result.result.nodes[0].restoreGaps).toBeUndefined();
|
||||
// Nothing is written for it: it still has no saved startup context.
|
||||
expect(db.prepare("SELECT * FROM node_startup_context WHERE node_id=?").get(f.node.id)).toBeUndefined();
|
||||
});
|
||||
|
||||
// CodeRabbit follow-up on #2373: the snapshot node may have no cwd while
|
||||
|
||||
@@ -2825,6 +2825,113 @@ describe("RestoreOrchestrator", () => {
|
||||
for (const opts of seen) expect(Object.keys(opts).sort()).toEqual(["name", "resumeToken", "resumeType"]);
|
||||
});
|
||||
|
||||
// A seat that only ever resumed or was attached has a resume token but no saved startup context. A resume replays none
|
||||
// anyway, so restore resumes it with an empty plan and names the gap, rather than stopping it.
|
||||
function seatWithoutStartupContext(runtime: "claude-code" | "codex", token: string | null, savedEmptyContext = false) {
|
||||
const rigName = savedEmptyContext ? "saved-rig" : "test-rig";
|
||||
const rig = rigRepo.createRig(rigName);
|
||||
db.prepare("INSERT INTO pods (id, rig_id, label) VALUES (?, ?, ?)").run(`pod-${rigName}`, rig.id, "Dev");
|
||||
const node = rigRepo.addNode(rig.id, "dev.moved", { runtime, podId: `pod-${rigName}` });
|
||||
const session = sessionRegistry.registerSession(node.id, `dev-moved@${rigName}`);
|
||||
sessionRegistry.updateStatus(session.id, "running");
|
||||
if (token) sessionRegistry.updateResumeToken(session.id, runtime === "codex" ? "codex_id" : "claude_id", token);
|
||||
if (savedEmptyContext) {
|
||||
db.prepare("INSERT INTO node_startup_context (node_id, projection_entries_json, resolved_files_json, startup_actions_json, runtime) VALUES (?, ?, ?, ?, ?)")
|
||||
.run(node.id, "[]", "[]", "[]", runtime);
|
||||
}
|
||||
const snap = snapshotCapture.captureSnapshot(rig.id, "test");
|
||||
sessionRegistry.updateStatus(session.id, "exited");
|
||||
db.prepare("DELETE FROM bindings WHERE node_id = ?").run(node.id);
|
||||
const adapter = {
|
||||
runtime,
|
||||
listInstalled: vi.fn(async () => []),
|
||||
project: vi.fn(async () => ({ projected: [], skipped: [], failed: [] })),
|
||||
deliverStartup: vi.fn(async () => ({ delivered: 0, failed: [] })),
|
||||
checkReady: vi.fn(async () => ({ ready: true })),
|
||||
launchHarness: vi.fn(async (_binding: unknown, opts: { resumeToken?: string }) => ({
|
||||
ok: true as const, resumeToken: opts.resumeToken ?? "fresh-token", resumeType: runtime === "codex" ? "codex_id" : "claude_id" })),
|
||||
};
|
||||
return { node, snap, adapter };
|
||||
}
|
||||
|
||||
it.each(["claude-code", "codex"] as const)("a pod-aware %s seat with a resume token and no saved startup context resumes with an empty plan and a named gap", async (runtime) => {
|
||||
const token = runtime === "codex" ? "019a0000-0000-7000-8000-00000000c0de" : "00000000-0000-4000-8000-0000000c1a0d";
|
||||
const { node, snap, adapter } = seatWithoutStartupContext(runtime, token);
|
||||
const orch = createOrchestrator({ listProcesses: nativeLineage(runtime, token) });
|
||||
const result = await orch.restore(snap.id, { adapters: { [runtime]: adapter } });
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(adapter.launchHarness).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ resumeToken: token }));
|
||||
const node0 = result.result.nodes[0]!;
|
||||
expect(node0.error ?? "").not.toContain("no startup context");
|
||||
// It ends where the same seat with a saved (empty) startup context ends: the resume is the same, only the gap differs.
|
||||
const saved = seatWithoutStartupContext(runtime, token, true);
|
||||
const withContext = await createOrchestrator({ listProcesses: nativeLineage(runtime, token) })
|
||||
.restore(saved.snap.id, { adapters: { [runtime]: saved.adapter } });
|
||||
expect(withContext.ok).toBe(true);
|
||||
if (!withContext.ok) return;
|
||||
const savedNode = withContext.result.nodes[0]!;
|
||||
expect({ status: node0.status, error: node0.error?.replaceAll("test-rig", "saved-rig") }).toEqual({ status: savedNode.status, error: savedNode.error });
|
||||
expect(savedNode.restoreGaps).toBeUndefined();
|
||||
if (runtime === "claude-code") expect(node0.status).toBe("resumed");
|
||||
expect(node0.restoreGaps).toEqual(["startup_context: no saved startup context; restore tried the saved conversation without replaying a saved startup plan."]);
|
||||
expect(result.result.warnings).toContain("Restore: dev.moved: no saved startup context, so restore tries its saved conversation without replaying a saved startup plan.");
|
||||
// Nothing is replayed or projected, and no startup context is written for it.
|
||||
for (const [plan] of adapter.project.mock.calls as unknown as Array<[{ entries: unknown[] }]>) expect(plan.entries).toEqual([]);
|
||||
for (const [files] of adapter.deliverStartup.mock.calls as unknown as Array<[unknown[]]>) expect(files).toEqual([]);
|
||||
expect(db.prepare("SELECT 1 FROM node_startup_context WHERE node_id = ?").get(node.id)).toBeUndefined();
|
||||
});
|
||||
|
||||
// The gap is named before the resume's outcome is known, so it never claims one: a resume that finds no conversation,
|
||||
// or fails, keeps the same attempt-neutral words and its own status.
|
||||
it.each([
|
||||
["finds no conversation", { ok: false as const, error: "Claude resume failed: no conversation found for the requested session", recovery: "retry_fresh", missingConversation: true as const }, "awaiting-decision"],
|
||||
["fails to start", { ok: false as const, error: "Claude resume failed: the harness exited" }, "failed"],
|
||||
] as const)("with no saved startup context, a resume that %s keeps its status and claims no resume", async (_label, launch, status) => {
|
||||
const token = "00000000-0000-4000-8000-0000000ba5e1";
|
||||
const { snap, adapter } = seatWithoutStartupContext("claude-code", token);
|
||||
adapter.launchHarness.mockResolvedValueOnce(launch as never);
|
||||
const result = await createOrchestrator({ listProcesses: nativeLineage("claude-code", token) }).restore(snap.id, { adapters: { "claude-code": adapter } });
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
const node0 = result.result.nodes[0]!;
|
||||
expect(adapter.launchHarness).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ resumeToken: token }));
|
||||
expect(node0.status).toBe(status);
|
||||
// A fresh seat launch refuses without a saved startup context, so the rollback offers none.
|
||||
expect(node0.error ?? "").not.toContain("--fresh");
|
||||
if (status === "awaiting-decision") expect(node0.error).toContain("This seat has no saved startup context, and no command records one for it yet, so no fresh start is offered here. Restore the original session manually.");
|
||||
expect(node0.restoreGaps).toEqual(["startup_context: no saved startup context; restore tried the saved conversation without replaying a saved startup plan."]);
|
||||
expect(result.result.warnings).toContain("Restore: dev.moved: no saved startup context, so restore tries its saved conversation without replaying a saved startup plan.");
|
||||
expect([...(node0.restoreGaps ?? []), ...result.result.warnings].filter((line) => line.includes("startup context"))
|
||||
.some((line) => /\bresumed\b/.test(line))).toBe(false);
|
||||
});
|
||||
|
||||
it("with no saved startup context, a seat with no resume token still waits for a decision, and starts no harness", async () => {
|
||||
const { snap, adapter } = seatWithoutStartupContext("claude-code", null);
|
||||
const orch = createOrchestrator();
|
||||
const result = await orch.restore(snap.id, { adapters: { "claude-code": adapter } });
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.result.nodes[0]).toMatchObject({ status: "awaiting-decision", error: expect.stringContaining("no resume token was captured") });
|
||||
expect(result.result.nodes[0]!.restoreGaps).toBeUndefined();
|
||||
expect(adapter.launchHarness).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("with no saved startup context, a deliberate fresh start isn't turned into a resume: it stops at the gate as before", async () => {
|
||||
const { snap, adapter } = seatWithoutStartupContext("claude-code", "00000000-0000-4000-8000-0000000f7e54");
|
||||
const orch = createOrchestrator();
|
||||
const result = await orch.restore(snap.id, { adapters: { "claude-code": adapter }, freshLogicalIds: ["dev.moved"] });
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
expect(result.result.nodes[0]).toMatchObject({ status: "attention_required", error: "Harness not started: no startup context for dev.moved." });
|
||||
expect(result.result.nodes[0]!.restoreGaps).toBeUndefined();
|
||||
expect(adapter.launchHarness).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("pod-aware chooser attention preserves the attempted native token for no-input reconciliation", async () => {
|
||||
const rig = rigRepo.createRig("test-rig");
|
||||
db.prepare("INSERT INTO pods (id, rig_id, label) VALUES (?, ?, ?)").run("pod-chooser", rig.id, "Dev");
|
||||
@@ -5957,6 +6064,24 @@ describe("RestoreOrchestrator", () => {
|
||||
});
|
||||
|
||||
describe("launch_wrapper native resume, fail-closed, and snapshot retention", () => {
|
||||
it.each(["replace", "clear"])("legacy Codex restore reads the live filesystem selection after snapshot (%s)", async change => {
|
||||
const rig = rigRepo.createRig("fs-restore");
|
||||
const oldPolicy = { approval: "never", filesystem: { ":minimal": "read", "/old": "write" }, network_access: false } satisfies import("../src/domain/codex-member-permissions.js").CodexFilesystemPermissions;
|
||||
const currentPolicy = { approval: "never", filesystem: { ":minimal": "read", "/current": "write", "/current/private": "deny" }, network_access: false };
|
||||
const node = rigRepo.addNode(rig.id, "codex-worker", { runtime: "codex", cwd: "/repo/codex", codexPermissions: oldPolicy });
|
||||
const session = sessionRegistry.registerSession(node.id, "dev-worker@fs-restore");
|
||||
db.prepare("UPDATE sessions SET resume_type = 'codex_id', resume_token = 'fs-thread', restore_policy = 'resume_if_possible' WHERE id = ?").run(session.id);
|
||||
sessionRegistry.updateStatus(session.id, "running");
|
||||
const snap = snapshotCapture.captureSnapshot(rig.id, "manual");
|
||||
db.prepare("UPDATE nodes SET codex_permissions_json = ? WHERE id = ?").run(change === "replace" ? JSON.stringify(currentPolicy) : null, node.id);
|
||||
sessionRegistry.updateStatus(session.id, "exited");
|
||||
const codexResume = mockCodexResume({ ok: true as const });
|
||||
expect(await createOrchestrator({ codex: codexResume, listProcesses: nativeLineage("codex", "fs-thread") }).restore(snap.id))
|
||||
.toMatchObject({ ok: true });
|
||||
const call = vi.mocked(codexResume.resume).mock.calls[0]!;
|
||||
expect(call[12]).toEqual(change === "replace" ? currentPolicy : undefined);
|
||||
});
|
||||
|
||||
it("passes current launch_wrapper as the new LAST arg after effort on Pi native resume and after beforeNativeDispatch (with undefined padding) on Codex native resume", async () => {
|
||||
const rig = rigRepo.createRig("r99");
|
||||
const piNode = rigRepo.addNode(rig.id, "pi-worker", {
|
||||
|
||||
@@ -48,6 +48,24 @@ const cases = [
|
||||
] as const;
|
||||
|
||||
describe("shared restore preconditions", () => {
|
||||
it("reports a saved profile cleared on the current Codex seat through restore-check", () => {
|
||||
const snapshot = data();
|
||||
snapshot.nodes[0]!.runtime = "codex";
|
||||
snapshot.nodes[0]!.codexConfigProfile = "limited";
|
||||
const current = { ...node(), runtime: "codex", codexConfigProfile: null };
|
||||
const service = new RestoreCheckService(deps({
|
||||
getNodeInventory: () => [current],
|
||||
getRestoreInputs: () => ({ snapshot: { id: "snapshot-1", kind: "manual", data: snapshot }, servicesRecord: null }),
|
||||
}));
|
||||
const check = service.check({ noHooks: true, noQueue: true }).checks.find((entry) => entry.check === "rig.test-rig.restore-preconditions");
|
||||
expect(check?.status).toBe("yellow");
|
||||
expect(check?.evidence).toContain("had Codex profile limited in this snapshot");
|
||||
expect(check?.evidence).toContain("does not prove what a prior process enforced");
|
||||
for (const profiles of [{ seat: "limited" }, {}, { seat: "other" }]) {
|
||||
expect(validatePreRestore(snapshot, { currentRuntimes: { seat: "codex" }, currentCodexProfiles: profiles }).warnings).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
it.each(cases)("preserves the exact refusal for missing %s", (missing, code, message, remediation) => {
|
||||
const result = validatePreRestore(data(), { fsOps: { exists: (path) => path !== missing }, servicesRecord: services() });
|
||||
expect(result).toEqual({
|
||||
|
||||
@@ -5,6 +5,7 @@ import Database from "better-sqlite3";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { ResumeMetadataRefresher } from "../src/domain/resume-metadata-refresher.js";
|
||||
import { deriveResumeToken } from "../src/domain/resume-token-capture.js";
|
||||
import { observeClaudePaneStartedAt } from "../src/domain/native-process-lineage.js";
|
||||
import { seedCodexThreads } from "./helpers/codex-state.js";
|
||||
import type { SessionRegistry } from "../src/domain/session-registry.js";
|
||||
import type { TmuxAdapter } from "../src/adapters/tmux.js";
|
||||
@@ -55,6 +56,30 @@ function createCodexLogsDb(homeDir: string, pid: number, threadId: string, dbNam
|
||||
}
|
||||
|
||||
describe("ResumeMetadataRefresher", () => {
|
||||
it("shares snapshot observations across Claude seats while retaining two samples per proof", async () => {
|
||||
const stamp = vi.fn();
|
||||
const sessionRegistry = { markResumeProbeResult: stamp } as unknown as SessionRegistry;
|
||||
const start = "Sun Oct 11 12:00:00 2026";
|
||||
const later = "Sun Oct 11 12:01:00 2026";
|
||||
const tmux = mockTmux({ getPanePid: vi.fn(async (name: string) => Number(name)) });
|
||||
const rows = [10, 20, 30].flatMap(pid => [
|
||||
{ pid, ppid: 1, pgid: pid, tpgid: pid + 1, executableName: "bash", command: "bash", startedAt: start },
|
||||
{ pid: pid + 1, ppid: pid, pgid: pid + 1, tpgid: pid + 1, executableName: "claude", command: "claude", startedAt: pid === 30 ? later : start },
|
||||
]);
|
||||
const list = vi.fn(async () => rows);
|
||||
const refresher = new ResumeMetadataRefresher({ sessionRegistry, tmuxAdapter: tmux,
|
||||
contextUsageStore: { readSidecar: () => ({ ok: true as const, data: { session_id: "token", sampled_at: new Date(Date.parse(start) + 1000).toISOString() } }) },
|
||||
claudeStartedAtForPass: pass => name => observeClaudePaneStartedAt({ target: name, tmux, listProcesses: pass.lister(list) }),
|
||||
});
|
||||
const seats = [10, 20, 30].map(pid => ({ sessionId: String(pid), sessionName: String(pid), runtime: "claude-code", resumeType: "claude_id", resumeToken: "token" }));
|
||||
await refresher.refresh(seats, { fillNullOnly: true });
|
||||
expect(stamp).toHaveBeenCalledTimes(2);
|
||||
expect(stamp).not.toHaveBeenCalledWith("30", "resumable");
|
||||
expect(list).toHaveBeenCalledTimes(4);
|
||||
await refresher.refresh(seats, { fillNullOnly: true });
|
||||
expect(list).toHaveBeenCalledTimes(8);
|
||||
});
|
||||
|
||||
it("PERF FIX 2 — the periodic snapshot refresh is SINGLE-ATTEMPT per codex seat: no x8 retry burst under failing discovery", async () => {
|
||||
const sessionRegistry = {
|
||||
isForkClaimingHeldToken: vi.fn(() => false),
|
||||
|
||||
@@ -94,7 +94,7 @@ describe("POST and DELETE /api/rigs/:rigId/edges", () => {
|
||||
]) {
|
||||
const refused = await add(body);
|
||||
expect(refused.status).toBe(400);
|
||||
expect(await refused.json()).toMatchObject({ ok: false, code: "edge_cycle" });
|
||||
expect(await refused.json()).toMatchObject({ ok: false, code: "edge_cycle", message: expect.stringContaining("launch and restore require an acyclic order") });
|
||||
}
|
||||
expect(state()).toEqual(before);
|
||||
|
||||
|
||||
@@ -694,7 +694,7 @@ describe("an answered request goes to the receiving agent, which decides while t
|
||||
expect(handed.body).toContain(`- **Who's who:** ${SEAT} is the agent asking to run the tool; ${asked} is the person it asked; human@host answered.`);
|
||||
expect(handed.body).toContain("human@host is how OpenRig records any answer typed at this machine's terminal or TUI");
|
||||
expect(handed.body).toContain(`ask them back with an ask to ${asked} that names request ${askId}`);
|
||||
expect(handed.body).toContain("Don't write to human@host: nothing is delivered there.");
|
||||
expect(handed.body).toContain("A row to human@host names no person: it asks no one, waits on Steering and in the Feed, and OpenRig reports it as undeliverable, so don't ask them back there.");
|
||||
expect(handed.body).toContain("Closing this item without deciding permits nothing");
|
||||
expect(await f.read(askId)).toMatchObject({ body: { state: "pending" } });
|
||||
expect(f.permits()).toHaveLength(0);
|
||||
|
||||
@@ -1293,6 +1293,83 @@ describe("SeatHandoverService", () => {
|
||||
detail: expect.stringContaining("without additional writable directory grants, as on a read-only fresh launch") } } } });
|
||||
});
|
||||
|
||||
it("rebuild keeps the saved filesystem policy instead of carrying a broader observed predecessor", async () => {
|
||||
const { node } = seedSeat();
|
||||
const own = { approval: "never", filesystem: { ":minimal": "read", "/work": "write", "/work/private": "deny" }, network_access: false };
|
||||
db.prepare("UPDATE nodes SET codex_permissions_json = ? WHERE id = ?").run(JSON.stringify(own), node.id);
|
||||
currentCodexPermissions.mockResolvedValue({ state: "observed", envelope: { approvalPolicy: "never", sandboxPolicy: { type: "danger-full-access" } },
|
||||
profile: null, processStartedAt: "Mon Apr 20 12:00:00 2026", observedAt: "2026-04-20T12:01:00Z" });
|
||||
const result = await service.handover({ seatRef: "dev-impl@seat-rig", source: "rebuild", reason: "context wall" });
|
||||
expect(result).toMatchObject({ ok: true, result: { sourceOutcome: { permissions: { state: "selection_used",
|
||||
detail: expect.stringContaining("explicit filesystem policy and no additional writable directory grants") } } } });
|
||||
const binding = launchHarness.mock.calls[0]![0];
|
||||
expect(binding.codexRebuildPermissions).toBeUndefined();
|
||||
expect(binding.codexPermissions).toEqual(own);
|
||||
});
|
||||
|
||||
it.each(["fresh", "fork:dev-impl@seat-rig", "rebuild"])(
|
||||
"keeps the predecessor running when filesystem preflight refuses before %s handover", async source => {
|
||||
const { node, sessionId } = seedSeat();
|
||||
if (!sessionId) throw new Error("fixture requires a current session");
|
||||
sessionRegistry.updateResumeToken(sessionId, "native-thread", "codex_id");
|
||||
const own = { approval: "never", filesystem: { ":minimal": "read", "/project": "write" } };
|
||||
db.prepare("UPDATE nodes SET codex_permissions_json = ? WHERE id = ?").run(JSON.stringify(own), node.id);
|
||||
const before = sessionRegistry.getBindingForNode(node.id);
|
||||
const remedy = "Fix: Remove the conflicting lower-layer access before another handover.";
|
||||
const verifyFilesystemPolicy = vi.fn(async () => ({ ok: false as const, error: `native policy refuses successor\n${remedy}` }));
|
||||
const adapter = new CodexRuntimeAdapter({ tmux: tmux(), codexHome: "/seat-home", verifyFilesystemPolicy,
|
||||
fsOps: { exists: () => false, readFile: () => "", writeFile: () => {}, mkdirp: () => {}, listFiles: () => [] } });
|
||||
const handover = new SeatHandoverService({ db, rigRepo, sessionRegistry, discoveryRepo, eventBus,
|
||||
tmuxAdapter: tmux(), runtimeAdapters: { codex: adapter }, sleep: async () => {}, readinessTimeoutMs: 50 });
|
||||
expect(await handover.handover({ seatRef: "dev-impl@seat-rig", source, reason: "check successor policy" }))
|
||||
.toMatchObject({ ok: false, code: "successor_create_failed", message: expect.stringContaining("native policy"),
|
||||
guidance: expect.stringContaining(remedy) });
|
||||
expect(verifyFilesystemPolicy).toHaveBeenCalledWith(expect.objectContaining({ codexHome: "/seat-home", cwd: "/project" }));
|
||||
expect(signalPaneProcess).not.toHaveBeenCalled();
|
||||
expect(respawnPane).not.toHaveBeenCalled();
|
||||
expect(killSession).not.toHaveBeenCalled();
|
||||
expect(sessionRegistry.getBindingForNode(node.id)).toEqual(before);
|
||||
});
|
||||
|
||||
it("checks the saved filesystem policy before signaling the predecessor and then hands over", async () => {
|
||||
const { node } = seedSeat();
|
||||
db.prepare("UPDATE nodes SET codex_permissions_json = ? WHERE id = ?")
|
||||
.run(JSON.stringify({ approval: "never", filesystem: { ":minimal": "read" } }), node.id);
|
||||
const verifyFilesystemPolicy = vi.fn(async () => ({ ok: true as const, verified: true as const }));
|
||||
const adapter = new CodexRuntimeAdapter({ tmux: tmux(), codexHome: "/seat-home", verifyFilesystemPolicy,
|
||||
fsOps: { exists: () => false, readFile: () => "", writeFile: () => {}, mkdirp: () => {} } });
|
||||
vi.spyOn(adapter, "launchHarness").mockImplementation(launchHarness);
|
||||
vi.spyOn(adapter, "checkReady").mockImplementation(checkReady);
|
||||
signalPaneProcess.mockImplementation(async () => {
|
||||
expect(verifyFilesystemPolicy).toHaveBeenCalledTimes(1);
|
||||
return { ok: true };
|
||||
});
|
||||
const handover = new SeatHandoverService({ db, rigRepo, sessionRegistry, discoveryRepo, eventBus,
|
||||
tmuxAdapter: tmux(), runtimeAdapters: { codex: adapter }, sleep: async () => {}, readinessTimeoutMs: 50 });
|
||||
expect(await handover.handover({ seatRef: "dev-impl@seat-rig", source: "fresh", reason: "check successor policy" }))
|
||||
.toMatchObject({ ok: true });
|
||||
expect(signalPaneProcess).toHaveBeenCalledTimes(1);
|
||||
expect(launchHarness).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("continues handover with the authored policy when native verification is inconclusive", async () => {
|
||||
const { node } = seedSeat();
|
||||
db.prepare("UPDATE nodes SET codex_permissions_json = ? WHERE id = ?")
|
||||
.run(JSON.stringify({ approval: "never", filesystem: { ":minimal": "read" } }), node.id);
|
||||
const verifyFilesystemPolicy = vi.fn(async () => ({ ok: true as const, verified: false as const, reason: "native read timed out" }));
|
||||
const adapter = new CodexRuntimeAdapter({ tmux: tmux(), codexHome: "/seat-home", verifyFilesystemPolicy,
|
||||
fsOps: { exists: () => false, readFile: () => "", writeFile: () => {}, mkdirp: () => {} } });
|
||||
vi.spyOn(adapter, "launchHarness").mockImplementation(launchHarness);
|
||||
vi.spyOn(adapter, "checkReady").mockImplementation(checkReady);
|
||||
const handover = new SeatHandoverService({ db, rigRepo, sessionRegistry, discoveryRepo, eventBus,
|
||||
tmuxAdapter: tmux(), runtimeAdapters: { codex: adapter }, sleep: async () => {}, readinessTimeoutMs: 50 });
|
||||
expect(await handover.handover({ seatRef: "dev-impl@seat-rig", source: "rebuild", reason: "keep authored policy" }))
|
||||
.toMatchObject({ ok: true, result: { warnings: expect.arrayContaining(["policy not verified: native read timed out"]) } });
|
||||
expect(verifyFilesystemPolicy).toHaveBeenCalledTimes(1);
|
||||
expect(launchHarness.mock.calls[0]?.[0]).toMatchObject({ codexPermissions: { filesystem: { ":minimal": "read" } } });
|
||||
expect(signalPaneProcess).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each(["observed", "unverified"] as const)("rebuild keeps saved-envelope launch additions when predecessor permissions are %s", async state => {
|
||||
const { node } = seedSeat({ codexConfigProfile: "locked" });
|
||||
const own = { sandbox: "workspace-write", approval: "on-request", writable_roots: ["/shared/state"],
|
||||
|
||||
@@ -21,7 +21,6 @@ import { externalCliAttachmentSchema } from "../src/db/migrations/019_external_c
|
||||
import { RigRepository } from "../src/domain/rig-repository.js";
|
||||
import { SessionRegistry } from "../src/domain/session-registry.js";
|
||||
import { classifyPaneActivity, classifyStyledFrame, draftDeliveryAllows, readDraftDeliverySetting, hasExpectedStagedText, inspectStartupStagedText, probeSessionActivity, promptTextIsFaint, SessionTransport, writtenFact, type TransportReadinessChecker } from "../src/domain/session-transport.js";
|
||||
import { readSendOutcome } from "../src/domain/connection-contract.js";
|
||||
import { SeatDeliveryGuard, resolveGuardTarget, type GuardTarget } from "../src/domain/seat-delivery-guard.js";
|
||||
import { ALL_MIGRATIONS } from "../src/db/all-migrations.js";
|
||||
import { outboxEntriesSchema } from "../src/db/migrations/027_outbox_entries.js";
|
||||
@@ -2786,38 +2785,6 @@ describe("SessionTransport", () => {
|
||||
expect(withEvidence.outcome).toBeUndefined();
|
||||
expect(fact).toMatchObject({ written: "submitted", terminalObserved: { outcome: null, verified: null } });
|
||||
expect(fact.messageId).toBe(fact.attemptId);
|
||||
// In the shared words: the typed route took it, as OpenRig saw. Never that the member read it.
|
||||
expect(fact.outcome).toEqual({ fact: "accepted", reporter: "openrig-observed", route: "typed" });
|
||||
});
|
||||
|
||||
it("records a typed wake to a Codex seat with its own labelled outcome, on the typed route", async () => {
|
||||
seedCanonicalRig("codex");
|
||||
await createTransport(typing(), { eventBus: new EventBus(db) }).send("dev-impl@my-rig", "hello");
|
||||
expect(evidence()).toEqual([expect.objectContaining({ sessionName: "dev-impl@my-rig",
|
||||
outcome: { fact: "accepted", reporter: "openrig-observed", route: "typed" } })]);
|
||||
});
|
||||
|
||||
it("reads each result shape's outcome in the shared words: unknown when the result doesn't establish one", () => {
|
||||
const s = "dev-impl@my-rig";
|
||||
expect([
|
||||
{ ok: true, sessionName: s },
|
||||
{ ok: true, sessionName: s, verified: true, outcome: "delivered" },
|
||||
{ ok: true, sessionName: s, verified: false, outcome: "rendered-unconfirmed" },
|
||||
{ ok: true, sessionName: s, outcome: "retained", sent: false, verified: false },
|
||||
{ ok: false, sessionName: s, outcome: "failed", inputPhase: "attempted" },
|
||||
{ ok: false, sessionName: s, sent: true, outcome: "failed", inputPhase: "written", reason: "submit_refused" },
|
||||
{ ok: false, sessionName: s, sent: false, inputPhase: "not_reached" },
|
||||
{ ok: false, sessionName: s, reason: "transport_unavailable" },
|
||||
// A prompt answer typed without Enter: it succeeded, but whether the prompt took it isn't known.
|
||||
{ ok: true, sessionName: s, sent: true, verified: false, outcome: "rendered-unconfirmed", promptInteraction: "unverified" },
|
||||
// Text written and Enter refused before it was pressed: the text may sit in the input box.
|
||||
{ ok: false, sessionName: s, sent: true, outcome: "failed", inputPhase: "written", reason: "draft_input_changed" },
|
||||
].map((result) => {
|
||||
const outcome = readSendOutcome(result, writtenFact(result as Parameters<typeof writtenFact>[0]));
|
||||
return outcome.fact === "accepted" && outcome.renderVerified ? "accepted, render verified" : outcome.fact;
|
||||
}))
|
||||
.toEqual(["accepted", "accepted, render verified", "accepted", "held", "failed-effect-unknown", "failed-effect-unknown",
|
||||
"not-delivered", "unknown", "unknown", "failed-effect-unknown"]);
|
||||
});
|
||||
|
||||
it("uses the caller's delivery id as the message, and gives each attempt its own id", async () => {
|
||||
|
||||
@@ -914,6 +914,24 @@ describe("plugin skills in the managed loadout", () => {
|
||||
expect(resolvePluginSkills({ pluginId: "core", pluginRoot: plugin, runtime: "claude-code", pluginType: "codex" }).entries).toEqual([]);
|
||||
});
|
||||
|
||||
it.each(["claude-code", "codex"] as const)("loads a CRLF plugin skill with realistic multiline frontmatter for %s", (runtime) => {
|
||||
const f = fixture([]);
|
||||
const plugin = writePlugin(f.root, [".claude-plugin", ".codex-plugin"], ["applying-a-permission-policy"]);
|
||||
const file = join(plugin, "skills", "applying-a-permission-policy", "SKILL.md");
|
||||
const original = readFileSync(new URL("../assets/plugins/openrig-core/skills/applying-a-permission-policy/SKILL.md", import.meta.url), "utf8").replace(/\r\n/g, "\n");
|
||||
const resolve = () => resolvePluginSkills({ pluginId: "core", pluginRoot: plugin, runtime });
|
||||
writeFileSync(file, original, "utf8");
|
||||
expect(resolve().entries.map((entry) => entry.id)).toEqual(["applying-a-permission-policy"]);
|
||||
writeFileSync(file, original.replace(/\n/g, "\r\n"), "utf8");
|
||||
const crlf = resolve();
|
||||
expect(crlf.warnings).toEqual([]);
|
||||
expect(crlf.entries.map((entry) => entry.id)).toEqual(["applying-a-permission-policy"]);
|
||||
const result = reconcileSkillLoadout({ loadout: loadoutOf(crlf.entries, f.root), runtime, cwd: f.project, topologyOwner: "seat-a", apply: true });
|
||||
expect(result).toMatchObject({ ok: true, applied: true });
|
||||
const harness = runtime === "codex" ? ".agents" : ".claude";
|
||||
expect(readFileSync(join(f.project, harness, "skills", "applying-a-permission-policy", "SKILL.md"), "utf8")).toBe(original.replace(/\n/g, "\r\n"));
|
||||
});
|
||||
|
||||
it("skips a plugin skill it cannot copy exactly and says why", () => {
|
||||
const f = fixture([]);
|
||||
const plugin = writePlugin(f.root, [".claude-plugin"], ["good", "linked"]);
|
||||
|
||||
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user