From a2bf0a1ad8fbb25cfb19ac85cb46ade18f47d6be Mon Sep 17 00:00:00 2001 From: Zachary Lowden Date: Fri, 4 Dec 2026 08:39:07 -0600 Subject: [PATCH 1/2] officers: approve an officer's task from the phone; a hand-off may name its target Two changes take the owner out of every step of an officer's hand-off but the decision itself. Phone buttons, officer tasks only. The approval card of an agent start on a task a built-in officer filed is pushed to the paired phone with exactly two signed buttons, Approve and start and Don't start (ask_answer per option; no inline answer, no Dismiss: push.Payload.AskOptionsOnly), and an expanded body naming the task, where it runs, the repository and the brief's first line. The answer path takes exactly those two answers from the device door (approvalSurfaceRefusal, phoneAnswerable) and completeHeld takes them as a tap (phoneApprovable); every other approval card keeps refusing the phone. The start stays bound to the hold's hash. The officer names the target. officer_task_handoff takes optional target (pod/claude-code, or host//claude with repo) and repo, checked against the owner's targets now (unknown or unavailable host, a blank, a runtime that needs a model: refused, nothing picked in its place, nothing recorded). With a target, muster files the held dispatch and the owner's card itself (agent_dispatch as the chief, a brief built from the task, no chief turn), and completes the owner's answer from its delivery (completeHandoffCard): agent_dispatch again with the arguments rebuilt from the hold, so every guard of a start runs. An approval of a hand-off card whose task changed since is refused on every door before it is recorded. A card muster cannot file undoes the hand-off. Without a target the chief's turn is unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/chief.md | 7 +- docs/officers-builtin.md | 59 +- docs/officers.md | 2 +- docs/push.md | 20 + docs/schema.md | 2 +- internal/api/attention.go | 36 +- internal/api/attention_delivery.go | 11 + internal/api/device_actions.go | 5 + internal/api/dispatch_approval.go | 50 +- internal/api/host_dispatch.go | 91 +++- internal/api/officer_card.go | 364 +++++++++++++ internal/api/officer_card_pg_test.go | 514 ++++++++++++++++++ internal/api/officer_push.go | 7 +- internal/api/officer_push_ledger_test.go | 3 +- internal/api/officer_push_test.go | 3 +- internal/api/officer_task_handoff.go | 185 ++++++- internal/api/server.go | 5 +- internal/api/stepup_gate_test.go | 6 +- internal/officers/builtin/handoffs.go | 14 + internal/officers/kickoff.go | 4 +- internal/officers/task_create_test.go | 1 + .../testdata/kickoff_builtin_host.golden | 2 +- internal/push/ask_options_only_test.go | 74 +++ internal/push/service.go | 37 +- 24 files changed, 1442 insertions(+), 60 deletions(-) create mode 100644 internal/api/officer_card.go create mode 100644 internal/api/officer_card_pg_test.go create mode 100644 internal/push/ask_options_only_test.go diff --git a/docs/chief.md b/docs/chief.md index 620972f7e..5ca183e3d 100644 --- a/docs/chief.md +++ b/docs/chief.md @@ -687,7 +687,12 @@ not type) with a `request_key`, it is no longer just refused. muster puts an or "a turn you did not type" when muster cannot tell; - its notification only opens the card: it has no answer buttons, because a lock screen cannot show the brief. Answers from the phone's notification - actions are refused. Tap the card itself, in muster or in the phone app; + actions are refused. Tap the card itself, in muster or in the phone app. + **The one exception is a task a built-in officer filed**: its approval card's + notification on the paired phone carries **Approve and start** and **Don't + start**, each confirmed with the phone's step-up key, and its expanded body + names the task, where it runs, the repository and the brief's first line + ([officers](officers-builtin.md#handing-a-task-to-the-chief-officer_task_handoff)); - its buttons are **Approve and start**, **Change repo** (when the repository is the chief's to choose, not one its task names: it opens the repository picker below, and the agent starts in the one you pick) and **Don't start**; when the chief left diff --git a/docs/officers-builtin.md b/docs/officers-builtin.md index e949e3651..54d211fdf 100644 --- a/docs/officers-builtin.md +++ b/docs/officers-builtin.md @@ -840,7 +840,8 @@ to use it for such work; its charter says what to do with a `task.done` item. When a task the officer filed needs an agent with a shell or a host, the officer may hand it to its owner's **chief**: -- `officer_task_handoff{task_id, why}` (why: one line) takes only a task +- `officer_task_handoff{task_id, why}` (why: one line; `target` and `repo` + are [below](#naming-the-target-a-card-with-no-chief-turn)) takes only a task **this officer filed** that is live and not complete — any other task answers "no such task". A task is handed off **at most once**, and an officer hands off **at most 3 a day**. Each hand-off is audited @@ -886,6 +887,62 @@ officer may hand it to its owner's **chief**: `dispatch_approve`, whose prompt merely points at an officer's task, is a task-less start and is not refused. +##### Naming the target: a card with no chief turn + +When the officer knows where the work must run, it adds `target` (and +`repo`): + +- `officer_task_handoff{task_id, why, target, repo?}` takes the targets + `agent_dispatch` takes, named whole and needing no model: + `pod/claude-code`, or `host//claude` with `repo` (`owner/name`, a + repository the owner connected). The target is checked against what the + owner has **now** — an unknown host, a host that cannot start that runtime + now, a blank (`host/?/claude`), a runtime that needs a model + (`host//opencode`, `pod/gateway`) and a pod kind this server does not + enable are each refused in plain words naming the owner's targets, and + **nothing else is picked in its place**. A refused target records nothing: + the task's one hand-off and the day's 3 are not spent. `repo` without + `target` is refused too. +- With a target, muster does not put the hand-off to the chief. It files the + held dispatch and the owner's approval card **directly**, as the chief's + `agent_dispatch` on the task would (the same guards: the owner's opt-in, + the caps, at most 6 approval cards an hour), with a brief **muster builds + from the task**: which officer filed it and why it needs an agent, then the + task's title and text. The card says the officer handed it off and shows + that brief whole. The hand-off is stamped delivered at once, so the sweep + never puts it to the chief; a card muster cannot file (the hourly cap, a + repository that is not connected, a task too long for a brief) undoes the + hand-off and the officer reads why. +- **The owner's answer is completed by muster**, with no chief turn and + whether or not the chief is running: **Approve and start** — in muster or + from the phone — runs `agent_dispatch` again as the chief, with the same + arguments rebuilt from the card's hold and the task, so the start is + bound to exactly what the card showed (single use, the same `request_key`, + every guard of a start). **Change repo** and a clone to choose open their + card as for the chief's own request, and their answer is completed the + same way. **Don't start** starts nothing and leaves the task on the board. + A start muster cannot make (a cap reached since, the opt-in withdrawn) + is shown on the card's answer with why; the officer is not told. ⚠ When the + card lapses unanswered (24 hours), the lapse note goes to the chief's chat + as for any dispatch card. +- **A changed task is never approved.** If the task's title or text changed + since its card was filed, the brief the card shows is no longer what would + start: **Approve and start** is refused on every door before it is + recorded, the card stays open, and the owner can choose **Don't start**. +- Without a target everything above (the chief's turn) is unchanged. + +##### Approving an officer's task from the phone + +The approval card of **any** task a built-in officer +filed — the chief's own or a hand-off's — is pushed to the owner's paired +phone with two buttons, **Approve and start** and **Don't start**, each the +card's own signed answer, confirmed with the phone's step-up key +([push.md](push.md#paired-phones-payload-v2)). The phone's answer is taken exactly as a +tap in muster: the chief's card is completed by the chief's next call, a +hand-off's by muster. Every other approval card — a task nobody's officer +filed, a team's card, a repository or clone card — still refuses an answer +from the phone and opens the card, as before. + ### People and outreach A plugin bound to the officer can report **engagement** with its owner's diff --git a/docs/officers.md b/docs/officers.md index 017f31922..37030d7c6 100644 --- a/docs/officers.md +++ b/docs/officers.md @@ -1568,7 +1568,7 @@ listing and again at dispatch): | `officer_my_state` `{section?}`, `officer_confirm_card` `{draft_id \| batch_id}`, `officer_refusal_refile` `{item_id, when, at?}`, `officer_refusal_drop` `{item_id}` | **builtin pod officers only**: no HQ call. Its own state, and — in a chat with its owner on its page only — a confirm card for its owner to decide (a draft, a batch, or its page's Re-file or Drop of a refusal: the tools only propose) — see [Chat with it](officers-builtin.md#chat-with-it) | | `officer_page_publish` `{title, blocks}` | **every officer** (HQ or builtin, pod or host, either pool): no HQ call. Publishes the officer's ONE page — made on the first call, a new version on every later one, whichever of its instances calls — shown on its screen in muster. Rolling and quiet: no notification. See [Its page](#its-page-officer_page_publish) | | `officer_task_create` `{item_id, title, body}` | **every builtin officer** (pod or host, either pool; never an HQ officer): no HQ call. Files a task on the officer's owner's board, marked as the officer's and linking the item it came from; at most 5 a day and 10 open per officer, an identical open one answered instead. The officer then reads and comments on its OWN tasks with `tasks_list`, `task_get` and `task_comment`, and is queued a `task.done` item each time one is completed or dismissed — see [When it needs a person or a shell](officers-builtin.md#when-it-needs-a-person-or-a-shell-officer_task_create) | -| `officer_task_handoff` `{task_id, why}` | **every builtin officer**, beside `officer_task_create`: no HQ call. Hands a task the officer filed (live, not complete) to its owner's chief, at most once per task and 3 a day; muster puts it to the chief once, as a turn, and the chief's `agent_dispatch` raises the owner's approval card — nothing starts without the owner's tap. See [Handing a task to the chief](officers-builtin.md#handing-a-task-to-the-chief-officer_task_handoff) | +| `officer_task_handoff` `{task_id, why, target?, repo?}` | **every builtin officer**, beside `officer_task_create`: no HQ call. Hands a task the officer filed (live, not complete) on, at most once per task and 3 a day. Without `target` muster puts it to the chief once, as a turn, and the chief's `agent_dispatch` raises the owner's approval card; with `target` (`pod/claude-code`, or `host//claude` with `repo`, checked against the owner's targets now) muster files that card itself, with no chief turn. Nothing starts without the owner's answer to the card, in muster or from the phone. See [Handing a task to the chief](officers-builtin.md#handing-a-task-to-the-chief-officer_task_handoff) | | `officer_ci_logs` `{pr}` | **shipping officers with a `ci_logs` block only**: no HQ call. GitHub and Kubernetes reads by muster-server; the failed CI tasks of the officer's OWN pull request, with log excerpts — see [`officer_ci_logs {pr}`](#officer_ci_logs-pr) | ### Its page (`officer_page_publish`) diff --git a/docs/push.md b/docs/push.md index 9e64665e8..a4a3ac715 100644 --- a/docs/push.md +++ b/docs/push.md @@ -263,6 +263,7 @@ until it is classified. | filed an outbound draft its plugin passed | yes (`plugin`) | the draft's card (`/attention?tab=drafts#draft-`) | | filed a day's follows and likes | yes (`plugin`), one per batch | the batch's card (`/attention?tab=drafts#outreach-<…>`) | | asked for a connector | yes (`connector`) | the request's card (`/connectors#connector-request-`, or the team's page) | +| handed a task off with a target, or a task it filed reached an approval card | yes (`attention`), with **Approve and start** and **Don't start** on a paired phone ([below](#paired-phones-payload-v2)) | the approval card (`/attention/open/ask-`) | | its plugin refused a draft | no: the draft went back to the officer; its "awaits your approval" notification is withdrawn | — | | its daily budget was reached (it is held for the day) | yes (`attention`), once per day | the officer's page (`/officers/?owner=`), where the hold is lifted or the day's cap raised | | its judgement pool is held by a refused cap escalation | yes (`attention`), once per hold; withdrawn when the hold ends | the officer's page, as above | @@ -444,6 +445,25 @@ as **payload v2**: ([what a card shows](mirroring.md#what-a-card-shows)). A browser's notification of it has no buttons that decide anything: a tap opens muster. +- An **officer's task's approval card** (the approval card of an agent start + on a task a built-in officer filed: the chief's own, or one muster filed for + an officer's hand-off that named its target, + [officers-builtin.md](officers-builtin.md#naming-the-target-a-card-with-no-chief-turn)) + is such an ask with exactly **two** buttons: its `ask.options` are **Approve + and start** and **Don't start**, and its `actions` are one `ask_answer` per + option and nothing else — no suggestion, no inline Answer, no Dismiss, even + after a fit. Its title is *Start an agent? · *; its body is four + lines — `Task #: `, `On: <where it runs>`, `Repo: <owner/name or + none>`, and the brief's first line (or, for a hand-off, the officer's why) — + with no options line. The challenge's `confirms` is that title and body, so + the step-up prompt shows what the tap decides. The signed answer is the + card's own answer, taken exactly as a tap in muster; the start stays bound + to the brief the card shows whole (a hand-off card whose task changed since + refuses **Approve and start** on every door, and the card stays open). A tap + on the body still opens the whole card. **Every other approval card** — the + chief's on a task no officer filed, a team's, a repository or clone card — + carries no buttons and its answer from the phone is refused, as before. An + app that predates option buttons draws the notification as any ask's. - A **connector request** (`connector`, an agent asking for a connector) carries `actions` too: `connector_approve` (**Approve**) and `connector_deny` (**Deny**), each with its `label` and the request's id as `target`. A tap diff --git a/docs/schema.md b/docs/schema.md index ecd4eeacc..ad7f2846a 100644 --- a/docs/schema.md +++ b/docs/schema.md @@ -219,7 +219,7 @@ buys only a word. | `0205` | [An officer's daily limit](officers-builtin.md#an-officers-page): `officer_defs.daily_limit_usd` (nullable, 0 to 1000 by `officer_defs_daily_limit_usd_check`), the daily spending limit its owner — or a manager of its team — set on the officer's page. NULL is none, so the declared `daily_budget_usd` (`MUSTER_OFFICERS`) applies, as before; a value takes precedence over it, and 0 is no limit. Every reader of a budget (the wake loop, the claim, a raise, the pages) applies it with today's raise (`0157`) through one rule (`officers.Officer.DailyBudget`). A change is audited (`officer.daily_limit`). No row-level security change: one column on `0118`'s owned def, under its policies and `0127`'s share class; `db.RLSOn` re-applies `0118`'s body, which never drops it. Rollback: an older image never reads the column (each officer goes back to its declared budget); the statements are in the migration's header. | | `0206` | [An ask's reference cards and an escalation's question](attention.md#reference-cards): `attention_asks.refs` (a JSON array of at most 5 `{"kind", "id"}` or `{"kind": "post", "url"}` pointers, `attention_asks_refs_shape`; drawn live under the viewer's own principal) and `officer_items.escalation` (a builtin officer's escalating complete's question, why, options and refs, `officer_items_escalation_shape`), both NULL before it. No row-level security change: two columns on owned tables, under `0025`/`0127`'s and `0118`/`0130`'s policies. Rollback: an older image never reads either column (asks show the question alone, an escalation is raised from its summary); the statements are in the migration's header. | | `0207` | [The chief on a host](design/three-components.md#the-chief-on-a-host): `chief_preferences.host` (the machine the owner chose for their chief, `''` for none) and the chief's spawn record, `spawn_id` (drawn from `host_dispatches`' sequence, like `0125`'s officer spawns), `spawn_window`, `spawn_session`, `spawn_refusal` and `spawned_at` (what the host's reply named). A mirrored call reaches the chief's tools only from that host, window and session. Written only with `MUSTER_CHIEF_RUNTIME=host`. `chief_preferences_host_shape` bounds them, and a record always names a host. No row-level security change: columns on `0060`'s owned table, under its policy. Rollback: an older image never reads the columns; the statements are in the migration's header. | -| `0208` | `officer_task_handoffs`: one row per task a builtin officer handed to its owner's chief with [`officer_task_handoff`](officers-builtin.md#handing-a-task-to-the-chief-officer_task_handoff) — `owner_id` (the officer's owner, the task's owner), `officer`, `task_id` (FK to `notes`, `ON DELETE CASCADE`), the `instance` that handed it off, its one-line `why` (1 to 500 characters), `created_at`, and `chief_turn_at`, stamped once by the conditional UPDATE that puts it to the chief as a turn (NULL while it waits for the sweep). `UNIQUE (owner_id, task_id)`: a task is handed off at most once. Owned, under forced row-level security (personal), re-applied by `db.RLSOn`. Rollback: an older image never reads it; the statements are in the migration's header. | +| `0208` | `officer_task_handoffs`: one row per task a builtin officer handed to its owner's chief with [`officer_task_handoff`](officers-builtin.md#handing-a-task-to-the-chief-officer_task_handoff) — `owner_id` (the officer's owner, the task's owner), `officer`, `task_id` (FK to `notes`, `ON DELETE CASCADE`), the `instance` that handed it off, its one-line `why` (1 to 500 characters), `created_at`, and `chief_turn_at`, stamped once by the conditional UPDATE that puts it to the chief as a turn (NULL while it waits for the sweep); a hand-off that [named its target](officers-builtin.md#naming-the-target-a-card-with-no-chief-turn) is stamped before muster files the owner's card instead, so the sweep never puts it to the chief, and its row is deleted when that card cannot be filed. `UNIQUE (owner_id, task_id)`: a task is handed off at most once. Owned, under forced row-level security (personal), re-applied by `db.RLSOn`. Rollback: an older image never reads it; the statements are in the migration's header. | | `0209` | [The chief on a host](design/three-components.md#as-built-pr-5b): `plugin_messages.status` may be `refused`, a message whose turn the chief's window can never take (the paste refuses its text). Nothing was typed, so it is not `unconfirmed`, and it is never queued again. Written only with `MUSTER_CHIEF_RUNTIME=host`. Only `plugin_messages_status_check` changes; no row-level security change. Rollback: the statements are in the migration's header. | To change the schema, add a new numbered file. diff --git a/internal/api/attention.go b/internal/api/attention.go index 9d2e0158e..b7f2c9237 100644 --- a/internal/api/attention.go +++ b/internal/api/attention.go @@ -202,6 +202,14 @@ type attentionItem struct { // noActions: its notification offers no chips and no signed answer // actions (a chief proposal's card, proposalCardFiled). Not serialised. noActions bool + // optionsOnly: its notification's only buttons are its options, each a + // signed answer — no inline Answer, no Dismiss, no suggestion (an + // officer's task's dispatch card: officerCardItem). Its title is + // pushTitle and its body pushText, whole lines, no options line. Not + // serialised. + optionsOnly bool + // pushTitle, when set, is the notification's title (optionsOnly's card). + pushTitle string // showSession is an officer's ask's "Show session" button on its // officer's page (officer_origin.go), "" everywhere else. Not serialised. showSession string @@ -1227,6 +1235,8 @@ func attentionNotification(it attentionItem, update bool) RouterNotification { // The signed ask actions are routed wherever the asks are // (device_actions.go): this item is one, so they are offered. n.AskActions = true + // An officer's task's dispatch card: its two buttons only. + n.AskOptionsOnly = it.optionsOnly } return n } @@ -1253,6 +1263,10 @@ const sessionPushTitle = "A session is waiting on you" // title, plained once at the sink, goNotify); a waiting session's fixed // sessionPushTitle. func attentionPushTitle(it attentionItem) string { + if it.pushTitle != "" && it.Kind == attentionKindAsk { + // An officer's task's dispatch card names what it asks to do. + return it.pushTitle + } if it.stepUp != nil && it.Kind == attentionKindAsk { // A step-up card names what it asks to do ("Post to X?"). return stepUpTitleText(it.stepUp) @@ -1304,7 +1318,7 @@ const ( // before notifyName's decorated one. "" (the title as it is) for no window, or // for an ask, question or notice with no human name. func attentionCodenameTitle(it attentionItem) (title, keep string) { - if it.stepUp != nil && it.Kind == attentionKindAsk { + if (it.stepUp != nil || it.pushTitle != "") && it.Kind == attentionKindAsk { // A step-up card is muster's own: no window to name. return "", "" } @@ -1393,6 +1407,18 @@ func attentionPushBody(it attentionItem) string { // line (Confirm and Refuse are the notification's own buttons). return push.CutClusters(pushLine(it.pushText), attentionPushBodyMax) } + if it.optionsOnly && it.pushText != "" && it.Kind == attentionKindAsk { + // An officer's task's dispatch card: its lines (task, where, repository, + // brief), each one line, no options line (Approve and start and Don't + // start are the notification's own buttons). + var parts []string + for _, l := range strings.Split(it.pushText, "\n") { + if l = pushLine(l); l != "" { + parts = append(parts, l) + } + } + return push.CutClusters(strings.Join(parts, "\n"), attentionPushBodyMax) + } opts := "" listed := it.Options if it.Kind == attentionKindQuestion { @@ -2571,7 +2597,13 @@ func (s *Server) answerAskFrom(ctx context.Context, id int64, answer string, src // A chief's dispatch APPROVAL card (dispatch_approval.go): never answered // from the phone's notification action, which cannot show the brief — // refused before anything is recorded or done; the card stays open. - if err := s.approvalSurfaceRefusal(ctx, id); err != nil { + if err := s.approvalSurfaceRefusal(ctx, id, answer); err != nil { + return a, err + } + // An officer's hand-off card whose task changed since it was filed + // (officer_card.go): its approval is refused on every door, the + // card left open, because the brief it shows is no longer what would start. + if err := s.handoffCardRefusal(ctx, id, answer); err != nil { return a, err } // A Release option of a routed task's ask (answer_release.go): checked diff --git a/internal/api/attention_delivery.go b/internal/api/attention_delivery.go index 773fe7632..c0dcc4c9f 100644 --- a/internal/api/attention_delivery.go +++ b/internal/api/attention_delivery.go @@ -340,6 +340,17 @@ func (s *Server) deliverAnswer(parent context.Context, owner, id int64) string { return leave("the agent could not be read") case ag.OwnerID != a.Owner: return settle(false, 0, "the agent is not the owner's") + } + // An officer's hand-off card (officer_card.go): muster filed it + // with no chief turn, and completes the owner's answer itself — no turn, + // so the chief need not be running. + if handled, o := s.completeHandoffCard(ctx, ag, a); handled { + if o.leave { + return leave(o.detail) + } + return settle(o.delivered, 0, o.detail) + } + switch { case !agentCanBeSent(ag.Status): return leave(deliveryWaitNotRunning(ag.Status)) case agents.KickoffOwed(ag): diff --git a/internal/api/device_actions.go b/internal/api/device_actions.go index edd2af27d..2482ea00f 100644 --- a/internal/api/device_actions.go +++ b/internal/api/device_actions.go @@ -314,6 +314,11 @@ func (s *Server) handleDeviceChallenge(w http.ResponseWriter, r *http.Request) { confirms = s.connectorRequestConfirms(r.Context(), target) } else { confirms = s.stepUpCardConfirms(r.Context(), body.Target) + if confirms == "" && body.Action == actionAskAnswer { + // An officer's task's approval card (officer_card.go): + // what an Approve and start (or Don't start) of it decides. + confirms = s.officerCardConfirms(r.Context(), body.Target) + } } if confirms != "" { out["confirms"] = confirms diff --git a/internal/api/dispatch_approval.go b/internal/api/dispatch_approval.go index e6ac14438..5927efa2c 100644 --- a/internal/api/dispatch_approval.go +++ b/internal/api/dispatch_approval.go @@ -223,6 +223,10 @@ type approvalRequest struct { // typed: a clone card in the owner's typed turn — no approval of the // chief's brief, only the clone of a request they typed. typed bool + // handoff is the officer's name when muster files the card for an + // officer's hand-off that named its target (officer_task_handoff.go): no + // chief asked for it, and the brief is muster's, built from the task. + handoff string } // repoChangeable reports whether the request's repository is the chief's to @@ -248,11 +252,14 @@ func approvalQuestionFor(r approvalRequest, repoBlank, cloneBlank bool) (string, case r.typed: b.WriteString("Which clone should this agent start in? You asked your chief for it in its chat, and the repository has " + "several clones on that host, none of them the only one your live sessions work in. Nothing starts until you choose.\n") + case r.handoff != "": + b.WriteString("Start this agent? " + one(r.handoff) + " filed this task and handed it off for an agent to do, naming where " + + "it should run. Nothing starts unless you approve it here.\n") default: b.WriteString("Start this agent? Your chief asked for it in a turn you did not type in its chat, so nothing starts unless " + "you approve it here.\n") } - if r.trigger != "" { + if r.trigger != "" && r.handoff == "" { b.WriteString("Your chief asked for this while handling " + r.trigger + ".\n") } where := one(r.target) @@ -290,9 +297,12 @@ func approvalQuestionFor(r approvalRequest, repoBlank, cloneBlank bool) (string, } else { b.WriteString("Task: none\n") } - if strings.TrimSpace(r.prompt) == "" { + switch { + case strings.TrimSpace(r.prompt) == "": b.WriteString("\nBrief: none (the agent is given the task's text).") - } else { + case r.handoff != "": + b.WriteString("\nThe brief muster built from the task — what the agent is told, exactly as shown:\n" + r.prompt) + default: b.WriteString("\nThe chief's brief — what the agent is told, exactly as shown:\n" + r.prompt) } q := b.String() @@ -505,7 +515,16 @@ func (s *Server) approvalCapRefusal(ctx context.Context, turn int64, key string) // view, or the phone's signed-in page — never from the phone's signed // notification action (the device door), whose lock screen showed a cut // question. Refused BEFORE anything is recorded: the card stays open. -func (s *Server) approvalSurfaceRefusal(ctx context.Context, id int64) error { +// +// 🔴 THE ONE EXCEPTION (operator decision, reversing #546 for officer tasks +// ONLY): the approval card of a task a built-in officer filed takes its two +// buttons' answers — "Approve and start" or "Don't start", exactly — from the +// phone's signed action (phoneApprovable). Its notification shows the task, +// where, the repository and the brief's first line; the hold's hash still +// binds the start to the brief shown whole on the card. Every other approval +// card (the chief's own, a team's, a session's) is refused as before, and so +// is any other answer to an officer's card from the phone. +func (s *Server) approvalSurfaceRefusal(ctx context.Context, id int64, answer string) error { st := s.hostDispatches() if st == nil { return nil @@ -520,8 +539,8 @@ func (s *Server) approvalSurfaceRefusal(ctx context.Context, id int64) error { } switch { case p.Via == authz.ViaDevice: - card, err := s.approvalCardAsk(ctx, id) - if err != nil || card { + d, card, err := s.approvalCardHold(ctx, id) + if err != nil || (card && !phoneAnswerable(d, answer)) { return errReleaseRefused(approvalNotOnTheCard) } case p.Via == authz.ViaSession && !stepup.Fresh(ctx, s.stepUpNow()): @@ -550,27 +569,34 @@ func (s *Server) approvalSurfaceRefusal(ctx context.Context, id int64) error { // can be one, so a hold that cannot be read never blocks the answer to any // other ask. func (s *Server) approvalCardAsk(ctx context.Context, id int64) (bool, error) { + _, card, err := s.approvalCardHold(ctx, id) + return card, err +} + +// approvalCardHold is approvalCardAsk with the card's hold detail (zero when +// it is not an approval card). +func (s *Server) approvalCardHold(ctx context.Context, id int64) (heldDetail, bool, error) { st := s.hostDispatches() if st == nil || s.ext.Attention == nil { - return false, nil + return heldDetail{}, false, nil } a, err := s.ext.Attention.Get(ctx, id) if err != nil || !a.OwnerCard || !slices.Contains(a.Options, declineLabel) { - return false, nil + return heldDetail{}, false, nil } h, err := st.CardHoldByAsk(ctx, id) if errors.Is(err, plugins.ErrHoldNotFound) { - return false, nil // an owner card the chief raised with those words: not a dispatch card + return heldDetail{}, false, nil // an owner card the chief raised with those words: not a dispatch card } if err != nil { s.logger.Printf("agent_dispatch: read the hold of card %d: %v", id, err) - return false, err + return heldDetail{}, false, err } var d heldDetail if json.Unmarshal(h.Detail, &d) != nil || !d.Approval { - return false, nil + return heldDetail{}, false, nil } - return true, nil + return d, true, nil } // approvalNext is a held answer's "next" for an approval card. diff --git a/internal/api/host_dispatch.go b/internal/api/host_dispatch.go index 1b29aa8e7..02bfbaf30 100644 --- a/internal/api/host_dispatch.go +++ b/internal/api/host_dispatch.go @@ -370,6 +370,21 @@ type heldDetail struct { // every later call with the key takes the clone from here, never asking // the host again. CloneDecision *cloneDecision `json:"clone_decision,omitempty"` + // OfficerTask is the task an APPROVAL card's request starts on when a + // built-in officer filed that task (isOfficerTask, read as the card was + // filed), and Officer that officer's id: the one kind of approval card a + // paired phone's signed answer may approve (phoneApprovable, + // officer_card.go). 0 and "" for every other card. + OfficerTask int64 `json:"officer_task,omitempty"` + Officer string `json:"officer,omitempty"` + // Summary is an officer's task's card as its notification says it + // (officerCardSummary): the task, where, the repository, the brief's + // first line. Display only — the hash binds the request. + Summary string `json:"summary,omitempty"` + // Handoff: the card was filed by muster for an officer's hand-off that + // named its target (officer_task_handoff with target), with no chief turn; + // the owner's answer is completed by muster itself (completeHandoffCard). + Handoff *handoffCard `json:"handoff,omitempty"` } // cardHoldDoor is the door a card hold is filed with (dispatch_request's are "mcp"). @@ -396,11 +411,20 @@ func (s *Server) fileHeldDispatch(ctx context.Context, a agents.Agent, in agentD } approval := isApprovalBlank(blanks[0]) var turn int64 + // An officer's hand-off that named its target (officer_task_handoff.go): + // muster files this card itself, in no chief turn. + origin, fromHandoff := handoffOriginOf(ctx) if approval && !req.typed { // 🔴 WHO ASKED, AND HOW OFTEN: the card says what started the chief's // turn, and an untyped turn may raise one approval card, a few an hour. + // A hand-off's card names the hand-off instead, and is counted by the + // same hourly cap (turn 0: no turn to count it in). var trigger string - turn, trigger = s.approvalTrigger(ctx, a) + if fromHandoff { + trigger, req.handoff = handoffTrigger(origin), ui.OfficerSourceName(origin.Officer) + } else { + turn, trigger = s.approvalTrigger(ctx, a) + } // A "Change repo" tap's repo card is the same request, already // counted: no cap applies to it. if !req.refile { @@ -475,6 +499,14 @@ func (s *Server) fileHeldDispatch(ctx context.Context, a agents.Agent, in agentD d := heldDetail{Door: cardHoldDoor, RequestKey: in.RequestKey, HeldHash: dispatchRequestHash(held, prompt), Target: held.Target, Blanks: blanks, Options: values, OwnerMessage: ownerMsg, Approval: approval, Turn: turn, Trigger: req.trigger, Refile: req.refile, CloneDecision: decision} + if approval && req.onTask && isOfficerTask(req.task) { + d.OfficerTask, d.Officer = req.task.ID, notes.OfficerOf(req.task.CreatedBy) + d.Summary = officerCardSummary(req, origin, fromHandoff) + } + if fromHandoff { + h := origin + d.Handoff = &h + } hold := &attention.WithAudit{Action: plugins.ActionDispatchHeld, Object: holdID, Detail: func(askID int64) map[string]any { d.AskID = askID var detail map[string]any @@ -497,7 +529,7 @@ func (s *Server) fileHeldDispatch(ctx context.Context, a agents.Agent, in agentD return refuse("the dispatch could not be held for your owner's answer; try again") } if approval { - s.proposalCardFiled(ask) + s.dispatchCardFiled(ctx, ask, d) } next := approvalNext(blanks[0]) if !isApprovalBlank(blanks[0]) { @@ -518,6 +550,33 @@ func (s *Server) fileHeldDispatch(ctx context.Context, a agents.Agent, in agentD return toolJSON(out) } +// heldCallHash is the hash call in (prompt its cleaned brief, t its host +// target, nil for a pod) is held under by a hold whose detail is d: the call +// with every blank d still holds cleared as fileHeldDispatch cleared it — the +// target's blanks, a held runtime's model, a held repository, a clone settled +// after the hold — and owner_asked off. +func heldCallHash(d heldDetail, in agentDispatchIn, t *hostTarget, prompt string) string { + asHeld := in + if t != nil { + asHeld.Target = t.withBlanks(d.Blanks).String() + } + asHeld.OwnerAsked = false + // A held runtime was held with NO model: the card chooses both. + if slices.Contains(d.Blanks, "runtime") { + asHeld.Model = "" + } + // A held repository was held with none: the repo card chooses it. + if slices.Contains(d.Blanks, blankRepo) { + asHeld.Repo = "" + } + // A clone settled after the hold (its host, repository or clone a blank) + // was held with none. + if cloneDependsOn(d.Blanks) { + asHeld.Clone = "" + } + return dispatchRequestHash(asHeld, prompt) +} + // heldCompletion is what an open card hold for this call's request_key says // about it: none (no hold), a replay of the hold's own call, the blank the // owner filled (accepted), or a refusal. @@ -582,25 +641,7 @@ func (s *Server) completeHeld(ctx context.Context, in agentDispatchIn, t *hostTa return heldCompletion{refusal: fmt.Sprintf(agentDispatchHeldNone, in.RequestKey)} } c := heldCompletion{hold: h, detail: d} - asHeld := in - if t != nil { - asHeld.Target = call.withBlanks(d.Blanks).String() - } - asHeld.OwnerAsked = false - // A held runtime was held with NO model: the card chooses both. - if slices.Contains(d.Blanks, "runtime") { - asHeld.Model = "" - } - // A held repository was held with none: the repo card chooses it. - if slices.Contains(d.Blanks, blankRepo) { - asHeld.Repo = "" - } - // A clone settled after the hold (its host, repository or clone a blank) - // was held with none. - if cloneDependsOn(d.Blanks) { - asHeld.Clone = "" - } - if dispatchRequestHash(asHeld, prompt) != d.HeldHash { + if heldCallHash(d, in, t, prompt) != d.HeldHash { c.refusal = fmt.Sprintf(agentDispatchHeldChanged, in.RequestKey) return c } @@ -672,7 +713,13 @@ func (s *Server) completeHeld(ctx context.Context, in agentDispatchIn, t *hostTa // refuses it before it is recorded (approvalSurfaceRefusal); this is the // same rule read back from the stored row. The phone's whole card is a // signed-in page (the browser door) and binds. - if isApprovalBlank(first) && ask.AnsweredVia.Via == attention.ViaDevice { + // + // 🔴 THE ONE EXCEPTION (operator decision on officer tasks): an approval + // card for a task a built-in officer filed (phoneApprovable) is answered + // from the phone's notification too — its two buttons, signed with the + // phone's step-up key, the brief summarised on the notification and bound + // here by the same held_hash as a tap. + if isApprovalBlank(first) && ask.AnsweredVia.Via == attention.ViaDevice && !phoneApprovable(d) { c.refusal = agentDispatchHeldPushAction return c } diff --git a/internal/api/officer_card.go b/internal/api/officer_card.go new file mode 100644 index 000000000..dd0d7bf28 --- /dev/null +++ b/internal/api/officer_card.go @@ -0,0 +1,364 @@ +package api + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "strconv" + "strings" + + "github.com/ZacxDev/muster/internal/agents" + "github.com/ZacxDev/muster/internal/attention" + "github.com/ZacxDev/muster/internal/fence" + "github.com/ZacxDev/muster/internal/notes" + "github.com/ZacxDev/muster/internal/plugins" + "github.com/ZacxDev/muster/internal/ui" +) + +// --------------------------------------------------------------------------- +// AN OFFICER'S TASK, APPROVED FROM THE PHONE, AND FILED WITHOUT A CHIEF TURN +// (operator decisions on officer tasks; docs/officers-builtin.md "Handing a +// task to the chief", docs/push.md). +// +// THE PROBLEM: an officer's task sat for hours on an approval card its owner +// learned of only through a notification with no buttons, after a chief turn +// that only re-said what the officer had already decided. Two changes take +// the owner out of every step but the decision itself: +// +// 1. PHONE BUTTONS (officer tasks ONLY). The approval card of a task a +// built-in officer filed (heldDetail.OfficerTask) is pushed with two +// buttons, "Approve and start" and "Don't start", each the ask's own +// signed answer (ask_answer, confirmed with the phone's step-up key), and +// an expanded body naming the task, where it runs, the repository and the +// brief's first line (officerCardSummary). The answer path takes exactly +// those two answers from the phone (approvalSurfaceRefusal, +// phoneAnswerable), and the completing call takes them as a tap +// (completeHeld, phoneApprovable). Every other approval card — the +// chief's own, a team's, a session's — still refuses the phone (#546). +// +// 2. THE OFFICER NAMES THE TARGET. officer_task_handoff with a target files +// the held dispatch and its card DIRECTLY — agent_dispatch as the chief, +// with the brief muster builds from the task (handoffBrief), in no chief +// turn — and the owner's answer is completed by muster itself +// (completeHandoffCard, from the answer's delivery): agent_dispatch again, +// the same arguments rebuilt from the hold, so every guard runs as for the +// chief's own call — the owner's opt-in, the caps, the officer rule, the +// single-use hold and its hash. +// +// 🔴 NOTHING STARTS AN OFFICER'S TASK BUT THE OWNER'S ANSWER TO ITS CARD. The +// hand-off files a card; only the owner's "Approve and start" — in the app or +// on the phone — reaches a start, and the start is agent_dispatch's, +// unchanged (officerStartRule under its lock). +// +// 🔴 THE BRIEF IS BOUND. The hold's hash binds the start to the arguments the +// card was filed with, the brief among them; a hand-off card's brief is +// rebuilt from the task at the answer (handoffCard.BriefHash), so an approval +// of a card whose task changed since is refused on every door before it is +// recorded (handoffCardRefusal), and the start refused if it got that far. +// --------------------------------------------------------------------------- + +// handoffCard is a hand-off card's part of its hold (heldDetail.Handoff): +// what muster rebuilds the dispatch from when the owner answers. +type handoffCard struct { + ID int64 `json:"id"` + Officer string `json:"officer"` + TaskID int64 `json:"task_id"` + Why string `json:"why"` + // Target and Repo are the officer's, as it named them. + Target string `json:"target"` + Repo string `json:"repo,omitempty"` + // BriefHash is the sha256 of the cleaned brief the card shows. + BriefHash string `json:"brief_hash"` +} + +// handoffOriginKey carries, on the context of the agent_dispatch call muster +// makes for a hand-off, the hand-off it is: set only by fileHandoffCard and +// completeHandoffCard, never from anything a caller sends. +type handoffOriginKey struct{} + +func withHandoffOrigin(ctx context.Context, h handoffCard) context.Context { + return context.WithValue(ctx, handoffOriginKey{}, h) +} + +func handoffOriginOf(ctx context.Context) (handoffCard, bool) { + h, ok := ctx.Value(handoffOriginKey{}).(handoffCard) + return h, ok && h.ID > 0 +} + +// handoffTrigger is what a hand-off card's hold records as its trigger. +func handoffTrigger(h handoffCard) string { + return ui.OfficerSourceName(h.Officer) + "'s hand-off of task #" + strconv.FormatInt(h.TaskID, 10) +} + +// handoffRequestKey is the request_key of hand-off id's dispatch. +func handoffRequestKey(id int64) string { return "officer-handoff-" + strconv.FormatInt(id, 10) } + +// handoffBrief is the brief muster builds for officer's hand-off of task n: +// who filed it and why it needs an agent, then the task's title and text — +// exactly what the card shows and the agent is told. +func handoffBrief(officer, why string, n notes.Note) string { + var b strings.Builder + b.WriteString(ui.OfficerSourceName(officer) + " filed this task and handed it off for an agent to do: " + strings.TrimSpace(why) + "\n") + b.WriteString("Task #" + strconv.FormatInt(n.ID, 10) + ": " + strings.TrimSpace(n.Title)) + if body := strings.TrimSpace(n.Body); body != "" { + b.WriteString("\n\n" + body) + } + return b.String() +} + +// briefHash is the hex sha256 of a cleaned brief. +func briefHash(prompt string) string { + sum := sha256.Sum256([]byte(prompt)) + return hex.EncodeToString(sum[:]) +} + +// phoneApprovable reports whether a card whose hold detail is d may be +// answered from the phone's notification: an APPROVAL card (its first blank +// blankApprove) for a task a built-in officer filed. A repository or clone +// card, and every card on another task, may not. +func phoneApprovable(d heldDetail) bool { + return d.Approval && d.OfficerTask > 0 && len(d.Blanks) > 0 && d.Blanks[0] == blankApprove +} + +// phoneAnswerable reports whether answer, from the phone, may be taken on a +// card whose hold detail is d: phoneApprovable, and exactly one of its two +// buttons — "Approve and start" or "Don't start". +func phoneAnswerable(d heldDetail, answer string) bool { + a := strings.TrimSpace(answer) + return phoneApprovable(d) && (a == approveLabel || a == declineLabel) +} + +// officerCardSummary is an officer's task's approval card as its +// notification says it, one line each: the task, where it runs, the +// repository, and why the officer handed it off (a hand-off's card) or the +// brief's first line. +func officerCardSummary(r approvalRequest, origin handoffCard, fromHandoff bool) string { + one := func(v string, n int) string { return fence.Cut(fence.Sanitize(strings.TrimSpace(v)), n) } + title := r.task.Title + if title == "" { + title, _, _ = strings.Cut(strings.TrimSpace(r.task.Body), "\n") + } + where := dispatchTargetLabel(r.target) + if t, ok := parseHostTarget(r.target); ok && t.Host != "" { + where = t.Host + ", " + spawnRuntimeLabel(t.Runtime) + } + repo := r.repo + if repo == "" { + repo = "none" + } + lines := []string{"Task #" + strconv.FormatInt(r.task.ID, 10) + ": " + one(title, 120), "On: " + one(where, 80), "Repo: " + one(repo, 100)} + switch { + case fromHandoff: + lines = append(lines, "Why: "+one(origin.Why, 200)) + case strings.TrimSpace(r.prompt) != "": + first, _, _ := strings.Cut(strings.TrimSpace(r.prompt), "\n") + lines = append(lines, "Brief: "+one(first, 200)) + default: + lines = append(lines, "Brief: none (the task's text)") + } + return strings.Join(lines, "\n") +} + +// officerCardTitle is an officer's task's card's notification title. +func officerCardTitle(officer string) string { + return "Start an agent? · " + ui.OfficerSourceName(officer) +} + +// dispatchCardFiled notifies an approval card fileHeldDispatch just filed +// with its hold (detail d): an officer's task's card through +// officerCardFiled, every other one as a proposal's (no buttons). +func (s *Server) dispatchCardFiled(_ context.Context, a attention.Ask, d heldDetail) { + if d.OfficerTask > 0 || d.Handoff != nil { + s.officerCardFiled(a, d) + return + } + s.proposalCardFiled(a) +} + +// officerCardFiled is an officer's task's approval card's +// notification (officerPushDispatchCard: a decision, so it pushes): on a +// person's phone, with its two buttons and its summary (officerCardItem); +// a team's, a repository card or a clone card as a proposal's, with none +// (askPushItem made a team's fit for a phone that may not answer it). +func (s *Server) officerCardFiled(a attention.Ask, d heldDetail) { + if d.Handoff == nil { + // The chief raised it in its turn (proposalCardFiled's own step). + s.noteChiefAsk(a) + } + ctx := s.attentionPrincipal(context.Background(), a.Owner) + it := s.askPushItem(ctx, a) + it.noActions = true + if phoneApprovable(d) && !s.ownerIsTeam(ctx, a.Owner) { + it = officerCardItem(it, d) + } + key := attentionAskKey(a.ID) + if s.officerPushSends(officerPushDispatchCard, a.Owner, attentionTag(key)) { + s.attentionNotify(a.Owner, it) + } + s.attentionChanged(a.Owner, key) +} + +// officerCardItem is item it of an officer's task's approval card +// made into its notification: the two buttons alone (optionsOnly), its title +// and its summary. +func officerCardItem(it attentionItem, d heldDetail) attentionItem { + officer := d.Officer + if officer == "" && d.Handoff != nil { + officer = d.Handoff.Officer + } + it.Options, it.suggestions = []string{approveLabel, declineLabel}, nil + it.noActions, it.optionsOnly = false, true + it.pushTitle, it.pushText = officerCardTitle(officer), d.Summary + return it +} + +// officerCardConfirms is what the phone's step-up prompt shows for a signed +// answer to ask id (the challenge's `confirms`, display only): an officer's +// task's approval card's title and summary, read as ctx's owner; "" for any +// other ask. +func (s *Server) officerCardConfirms(ctx context.Context, target string) string { + id, err := strconv.ParseInt(target, 10, 64) + if err != nil || id <= 0 { + return "" + } + d, card, err := s.approvalCardHold(ctx, id) + if err != nil || !card || !phoneApprovable(d) { + return "" + } + officer := d.Officer + return officerCardTitle(officer) + "\n" + pushLine(strings.ReplaceAll(d.Summary, "\n", " · ")) +} + +// The hand-off card's refusals. +const ( + // handoffCardStale: the task changed since its hand-off card was filed. + handoffCardStale = "the task changed since this card was filed, so the brief it shows is no longer what would start: nothing " + + "was started. Choose Don't start, then ask your chief to start it if it still needs an agent" + // handoffCardUnread: the card's task could not be read. + handoffCardUnread = "this card's task could not be read, so muster cannot show that its brief is current: nothing was started; try again" +) + +// handoffCardRefusal is the answer path's check of an approval (answer +// "Approve and start") of hand-off card id, before anything is recorded, on +// every door: the brief rebuilt from the task NOW must be the brief the card +// was filed with (handoffCard.BriefHash), else it is refused and the card +// stays open. nil for any other answer or card. +func (s *Server) handoffCardRefusal(ctx context.Context, id int64, answer string) error { + if strings.TrimSpace(answer) != approveLabel || s.ext.Notes == nil { + return nil + } + d, card, err := s.approvalCardHold(ctx, id) + if err != nil || !card || d.Handoff == nil || len(d.Blanks) == 0 || d.Blanks[0] != blankApprove { + return nil + } + n, err := s.ext.Notes.Get(ctx, d.Handoff.TaskID) + if err != nil { + return errReleaseRefused(handoffCardUnread) + } + prompt, ok := cleanPrompt(handoffBrief(d.Handoff.Officer, d.Handoff.Why, n)) + if !ok || briefHash(prompt) != d.Handoff.BriefHash { + return errReleaseRefused(handoffCardStale) + } + return nil +} + +// handoffOutcome is completeHandoffCard's verdict on a hand-off card's +// answer, as the delivery settles it. +type handoffOutcome struct { + leave bool // queued again (detail why): the sweep retries it + delivered bool + detail string +} + +// completeHandoffCard is the delivery of the owner's answer to a hand-off +// card a (its asker chief, the agent the card was raised as): handled false +// for any other ask — its answer is the chief's, delivered as a turn. +// +// "Don't start" leaves the task on the board and starts nothing. Any other +// answer is completed as the chief's own completing call would be: +// agent_dispatch, as chief, with the hand-off's arguments rebuilt from the +// hold and the task — the answer's repository or clone for a repository or +// clone card — so completeHeld judges the stored rows exactly as for the +// chief, and the start (or the next card, after "Change repo" or a clone +// still to choose) is agent_dispatch's. A refusal settles the delivery +// unconfirmed, saying why, on the owner's card. +func (s *Server) completeHandoffCard(ctx context.Context, chief agents.Agent, a attention.Ask) (bool, handoffOutcome) { + st := s.hostDispatches() + if st == nil || !a.OwnerCard { + return false, handoffOutcome{} + } + h, err := st.CardHoldByAsk(ctx, a.ID) + if errors.Is(err, plugins.ErrHoldNotFound) { + return false, handoffOutcome{} + } + if err != nil { + // A dispatch card whose hold cannot be read now: never the chief's + // turn in its place — queued again. + s.logger.Printf("officers: hand-off card %d: read its hold: %v", a.ID, err) + return true, handoffOutcome{leave: true, detail: "the card's dispatch could not be read"} + } + var d heldDetail + if json.Unmarshal(h.Detail, &d) != nil || d.Handoff == nil || len(d.Blanks) == 0 { + return false, handoffOutcome{} + } + ho := *d.Handoff + i, chose := a.ChosenOption() + var chosen string + if chose { + chosen = d.Options[a.Options[i]] + } + if chosen == declineValue { + s.logger.Printf("officers: hand-off %d: the owner chose Don't start on card %d: task %d stays on the board", ho.ID, a.ID, ho.TaskID) + return true, handoffOutcome{delivered: true} + } + if s.ext.Notes == nil { + return true, handoffOutcome{detail: "muster could not start it: this server has no task store"} + } + n, err := s.ext.Notes.Get(ctx, ho.TaskID) + if err != nil { + return true, handoffOutcome{detail: "muster could not start it: its task could not be read"} + } + in := agentDispatchIn{Target: ho.Target, TaskID: ho.TaskID, Repo: ho.Repo, Prompt: handoffBrief(ho.Officer, ho.Why, n), RequestKey: d.RequestKey} + switch d.Blanks[0] { + case blankRepo: + // The repository the owner picked, or typed (completeHeld judges it). + switch { + case chose && strings.HasPrefix(chosen, repoValuePref): + in.Repo = a.Options[i] + case !chose: + in.Repo = strings.TrimSpace(a.Answer) + } + case blankClone: + if chose && strings.HasPrefix(chosen, clonePref) { + in.Clone = strings.TrimPrefix(chosen, clonePref) + } + } + args, err := json.Marshal(in) + if err != nil { + return true, handoffOutcome{detail: "muster could not start it: its arguments could not be built"} + } + out, _ := s.dispatchTaskRoutingTool(withHandoffOrigin(ctx, ho), chief, agentDispatchTool, string(args)) + if why := dispatchOutError(out); why != "" { + s.logger.Printf("officers: hand-off %d: card %d answered %q, not started: %s", ho.ID, a.ID, a.Answer, why) + return true, handoffOutcome{detail: "muster could not start it: " + why} + } + s.logger.Printf("officers: hand-off %d: card %d answered %q: %s", ho.ID, a.ID, a.Answer, cutLog(out)) + return true, handoffOutcome{delivered: true} +} + +// dispatchOutError is agent_dispatch's refusal in out ("" for a start, a +// replay or a new card). +func dispatchOutError(out string) string { + var r struct { + Error string `json:"error"` + } + if json.Unmarshal([]byte(out), &r) != nil { + return "an answer muster could not read" + } + return r.Error +} + +// cutLog is a tool's answer cut for one log line. +func cutLog(s string) string { return fence.Cut(s, 300) } diff --git a/internal/api/officer_card_pg_test.go b/internal/api/officer_card_pg_test.go new file mode 100644 index 000000000..34b57590d --- /dev/null +++ b/internal/api/officer_card_pg_test.go @@ -0,0 +1,514 @@ +package api + +import ( + "context" + "encoding/json" + "fmt" + "strconv" + "strings" + "testing" + "time" + + "github.com/ZacxDev/muster/internal/agents" + "github.com/ZacxDev/muster/internal/attention" + "github.com/ZacxDev/muster/internal/authz" + "github.com/ZacxDev/muster/internal/notes" + "github.com/ZacxDev/muster/internal/officers" + "github.com/ZacxDev/muster/internal/officers/builtin" + "github.com/ZacxDev/muster/internal/push" + "github.com/ZacxDev/muster/internal/users" +) + +// AN OFFICER'S TASK, APPROVED FROM THE PHONE, AND FILED WITHOUT A CHIEF TURN +// (officer_card.go, officer_task_handoff.go) over real Postgres. +// +// The fixture's names are the approval fixture's (fictional, pairwise +// distinct); the officer is marketing:example, its instance +// officer-marketing-example-1. The tool names are literals (the contract). + +// handoffWorld is the approval fixture with the built-in officer store on, +// answers delivered at once, and the chief's turns recorded. +type handoffWorld struct { + *hostFixture + officer officers.Officer + inst agents.Agent + turns *handoffChief +} + +func newHandoffWorld(t *testing.T) *handoffWorld { + t.Helper() + f := newApprovalFixture(t) + // The owner's role is read from the users store as in production (an + // admin here: the fixture's GitHub App admits only one). + f.srv.ext.Users = users.NewPG(f.pool) + f.srv.EnableOfficerStore(builtin.NewStore(f.pool)) + t.Cleanup(func() { + _, _ = f.pool.Exec(authz.System(context.Background()), `DELETE FROM officer_task_handoffs WHERE owner_id = $1`, f.owner) + }) + noGrace := time.Duration(0) + f.srv.attention.graceOverride = &noGrace + rec := &handoffChief{agent: f.chief} + f.srv.answerTurn = rec.record + if c, err := f.srv.chiefAgent(f.asOwner); err != nil || c.ID != f.chief.ID { + t.Fatalf("the fixture's chief %d is not the owner's chief (%d, %v)", f.chief.ID, c.ID, err) + } + return &handoffWorld{hostFixture: f, turns: rec, + officer: officers.Officer{ID: "marketing:example", Owner: f.owner, Backend: officers.BackendBuiltin}, + inst: agents.Agent{Name: "officer-marketing-example-1", OwnerID: f.owner}} +} + +// handoff runs officer_task_handoff as the officer's instance, then waits +// for every delivery it started. +func (w *handoffWorld) handoff(task int64, args map[string]any) string { + if args == nil { + args = map[string]any{} + } + args["task_id"] = task + if _, ok := args["why"]; !ok { + args["why"] = "needs a shell on a host with the capture tool" + } + b, _ := json.Marshal(args) + out := w.srv.officerTaskHandoff(w.asOwner, w.inst, w.officer, string(b)) + w.srv.WaitForAttentionDeliveries() + return out +} + +// handoffRows is how many hand-offs task has. +func (w *handoffWorld) handoffRows(t *testing.T, task int64) int { + t.Helper() + var n int + if err := w.pool.QueryRow(authz.System(context.Background()), `SELECT count(*) FROM officer_task_handoffs WHERE task_id = $1`, task).Scan(&n); err != nil { + t.Fatal(err) + } + return n +} + +// holdOf is card id's hold detail. +func (f *hostFixture) holdOf(t *testing.T, id int64) heldDetail { + t.Helper() + h, err := f.plugins.CardHoldByAsk(f.asOwner, id) + if err != nil { + t.Fatalf("card %d's hold: %v", id, err) + } + var d heldDetail + if err := json.Unmarshal(h.Detail, &d); err != nil { + t.Fatal(err) + } + return d +} + +// startedOn is the owner's agents started on task id (pod starts). +func (f *hostFixture) startedOn(t *testing.T, id int64) int { + t.Helper() + n := 0 + for _, a := range f.ownersAgents(t) { + if a.NoteID != nil && *a.NoteID == id { + n++ + } + } + return n +} + +// officerCardCall is agent_dispatch on officer task id, pod/claude-code, with +// the approval fixture's brief. +func officerCardCall(id int64, key string) map[string]any { + return map[string]any{"target": "pod/claude-code", "prompt": apBrief, "task_id": id, "request_key": key} +} + +// TestAnOfficersTaskCardsPushHasItsTwoButtons: the approval card of an +// officer's task is pushed to the phone with exactly two signed buttons — +// Approve and start, Don't start — and a body naming the task, where, the +// repository and the brief's first line. CONTROL (the same instrument, the +// same run): an ordinary task's approval card is pushed with none. +func TestAnOfficersTaskCardsPushHasItsTwoButtons(t *testing.T) { + f := newApprovalFixture(t) + pusher := f.withPush(t) + n := f.officerNote(t, "officer-task-fixture capture ledger") + plain := f.task(t, "officer-task-fixture ordinary") + f.untypedTurn(t) + if text := f.callRaw(f.chief, agentDispatchTool, officerCardCall(n.ID, "push-officer-1")); !strings.Contains(text, `"blanks":["approve"]`) { + t.Fatalf("not an approval card: %s", text) + } + card := f.newestCard(t) + f.untypedTurn(t) + if text := f.callRaw(f.chief, agentDispatchTool, officerCardCall(plain.ID, "push-plain-1")); !strings.Contains(text, `"blanks":["approve"]`) { + t.Fatalf("control: not an approval card: %s", text) + } + other := f.newestCard(t) + f.srv.WaitForPushes() + p := pushFor(t, pusher, card.ID) + if p.Ask == nil || strings.Join(p.Ask.Options, "|") != approveLabel+"|"+declineLabel || len(p.Ask.Suggestions) != 0 { + t.Fatalf("the officer's card's chips: %+v", p.Ask) + } + if len(p.Actions) != 2 { + t.Fatalf("the officer's card's buttons: %+v; want exactly two", p.Actions) + } + for i, a := range p.Actions { + if a.ID != push.ActionAskAnswer || a.Target != strconv.FormatInt(card.ID, 10) || a.Option == nil || *a.Option != i || a.Input || a.Label != "" { + t.Fatalf("button %d: %+v; want ask_answer of option %d on card %d", i, a, i, card.ID) + } + } + for _, want := range []string{"Task #" + strconv.FormatInt(n.ID, 10) + ": officer-task-fixture capture ledger", + "On: Claude Code (your Claude account)", "Repo: none", "Brief: " + apBriefLine1} { + if !strings.Contains(p.Body, want) { + t.Errorf("the officer's card's body lacks %q:\n%s", want, p.Body) + } + } + if !strings.HasPrefix(p.Title, "Start an agent? · Marketing officer") { + t.Errorf("the officer's card's title: %q", p.Title) + } + if strings.Contains(p.Body, "Options:") { + t.Errorf("the officer's card's body carries an options line: %q", p.Body) + } + if q := pushFor(t, pusher, other.ID); q.Ask != nil || len(q.Actions) != 0 { + t.Fatalf("control: an ordinary task's approval card offers an answer: ask %+v, actions %+v", q.Ask, q.Actions) + } +} + +// TestAPhoneApprovesOnlyAnOfficersTaskCard: from the phone's signed action +// (the device door), an ordinary task's approval card is refused as before +// (#546) and stays open; an officer's task's card refuses any answer but its +// two buttons ("Change repo" included); its "Approve and start" is recorded +// from the device door and the chief's completing call then STARTS the agent +// on the task — the same effect as a tap in the app — the reservation naming +// the hold and the card. +func TestAPhoneApprovesOnlyAnOfficersTaskCard(t *testing.T) { + f := newApprovalFixture(t) + plain := f.task(t, "officer-task-fixture ordinary phone") + f.untypedTurn(t) + f.callRaw(f.chief, agentDispatchTool, officerCardCall(plain.ID, "phone-plain-1")) + pc := f.newestCard(t) + if _, err := f.srv.answerAskFrom(f.phone(), pc.ID, approveLabel, attention.AnswerSource{}); err == nil || !strings.HasSuffix(err.Error(), approvalNotOnTheCard) { + t.Fatalf("the phone's approval of an ordinary task's card: %v; want refused with %q", err, approvalNotOnTheCard) + } + if a, _ := f.srv.ext.Attention.Get(f.asOwner, pc.ID); a.Status != attention.Open { + t.Fatalf("the ordinary card after the phone's refused answer: %s; want open", a.Status) + } + + n := f.officerNote(t, "officer-task-fixture phone approve") + call := officerCardCall(n.ID, "phone-officer-1") + f.untypedTurn(t) + before := f.allReservations(t) + f.callRaw(f.chief, agentDispatchTool, call) + card := f.newestCard(t) + if _, err := f.srv.answerAskFrom(f.phone(), card.ID, changeRepoLabel, attention.AnswerSource{}); err == nil || !strings.HasSuffix(err.Error(), approvalNotOnTheCard) { + t.Fatalf("the phone's Change repo on an officer's card: %v; want refused", err) + } + a, err := f.srv.answerAskFrom(f.phone(), card.ID, approveLabel, attention.AnswerSource{}) + if err != nil { + t.Fatalf("the phone's Approve and start on an officer's card: %v", err) + } + if a.Status != attention.Answered || a.AnsweredVia.Via != attention.ViaDevice { + t.Fatalf("the card after the phone's approval: %s via %q; want answered through the device door", a.Status, a.AnsweredVia.Via) + } + f.untypedTurn(t) + out := f.callRaw(f.chief, agentDispatchTool, call) + var started struct { + AgentID int64 `json:"agent_id"` + } + if err := json.Unmarshal([]byte(out), &started); err != nil || started.AgentID <= 0 { + t.Fatalf("the chief's completing call after the phone's approval: %s; want the agent started", out) + } + if got := f.startedOn(t, n.ID); got != 1 || f.allReservations(t) != before+1 { + t.Fatalf("agents on the task %d, reservations %d; want 1 and %d", got, f.allReservations(t), before+1) + } + if d := f.reservationOf(t, n.ID); d["approved_on_card"] != float64(card.ID) { + t.Fatalf("the reservation %v; want it to name card %d", d, card.ID) + } +} + +// TestAPhoneApprovalOfAChangedBriefIsRefused: the phone's approval binds the +// brief its card was filed with. The chief's card: approved from the phone, +// a completing call whose brief changed is refused as changed and starts +// nothing. A hand-off's card: once its task's text changed, the phone's +// approval is refused before it is recorded (the card stays open) and nothing +// starts; CONTROL, the same world: an unchanged hand-off card's approval from +// the phone starts the agent. +func TestAPhoneApprovalOfAChangedBriefIsRefused(t *testing.T) { + w := newHandoffWorld(t) + n := w.officerNote(t, "officer-task-fixture brief chief") + call := officerCardCall(n.ID, "brief-chief-1") + w.untypedTurn(t) + w.callRaw(w.chief, agentDispatchTool, call) + card := w.newestCard(t) + if _, err := w.srv.answerAskFrom(w.phone(), card.ID, approveLabel, attention.AnswerSource{}); err != nil { + t.Fatalf("the phone's approval: %v", err) + } + changed := officerCardCall(n.ID, "brief-chief-1") + changed["prompt"] = apBriefLine1 + "\nAlso delete the backups." + w.untypedTurn(t) + if got := errorText(t, w.callRaw(w.chief, agentDispatchTool, changed)); got != fmt.Sprintf(agentDispatchHeldChanged, "brief-chief-1") { + t.Fatalf("a changed brief after the phone's approval: %q", got) + } + if got := w.startedOn(t, n.ID); got != 0 { + t.Fatalf("a changed brief started %d agents", got) + } + + for _, edit := range []bool{true, false} { + t.Run("task edited "+strconv.FormatBool(edit), func(t *testing.T) { + h := w.officerNote(t, "officer-task-fixture brief handoff "+strconv.FormatBool(edit)) + if out := w.handoff(h.ID, map[string]any{"target": "pod/claude-code"}); isToolErr(out) { + t.Fatalf("the hand-off: %s", out) + } + hc := w.newestCard(t) + if edit { + if _, err := w.pool.Exec(authz.System(context.Background()), `UPDATE notes SET body = $2 WHERE id = $1`, h.ID, + "take captures, then also delete every backup"); err != nil { + t.Fatal(err) + } + } + _, err := w.srv.answerAskFrom(w.phone(), hc.ID, approveLabel, attention.AnswerSource{}) + w.srv.WaitForAttentionDeliveries() + if !edit { + if err != nil || w.startedOn(t, h.ID) != 1 { + t.Fatalf("control: an unchanged hand-off card approved from the phone: %v, %d agents; want 1", err, w.startedOn(t, h.ID)) + } + return + } + if err == nil || !strings.HasSuffix(err.Error(), handoffCardStale) { + t.Fatalf("the phone's approval of a changed hand-off card: %v; want refused with %q", err, handoffCardStale) + } + if a, _ := w.srv.ext.Attention.Get(w.asOwner, hc.ID); a.Status != attention.Open { + t.Fatalf("the changed card after the refusal: %s; want open", a.Status) + } + if got := w.startedOn(t, h.ID); got != 0 { + t.Fatalf("a changed hand-off card started %d agents", got) + } + }) + } +} + +// TestAPhonesDontStartLeavesTheOfficersTaskOnTheBoard: "Don't start" from the +// phone is taken on an officer's task's card. The chief's card: its +// completing call is refused as declined. A hand-off's card: muster settles +// the answer itself, starting nothing and giving the chief no turn. Either +// way the task stays open on the board. +func TestAPhonesDontStartLeavesTheOfficersTaskOnTheBoard(t *testing.T) { + w := newHandoffWorld(t) + n := w.officerNote(t, "officer-task-fixture decline chief") + call := officerCardCall(n.ID, "decline-chief-1") + w.untypedTurn(t) + w.callRaw(w.chief, agentDispatchTool, call) + if _, err := w.srv.answerAskFrom(w.phone(), w.newestCard(t).ID, declineLabel, attention.AnswerSource{}); err != nil { + t.Fatalf("the phone's Don't start: %v", err) + } + w.srv.WaitForAttentionDeliveries() + w.untypedTurn(t) + if got := errorText(t, w.callRaw(w.chief, agentDispatchTool, call)); got != agentDispatchHeldDeclined { + t.Fatalf("after the phone's Don't start: %q", got) + } + h := w.officerNote(t, "officer-task-fixture decline handoff") + if out := w.handoff(h.ID, map[string]any{"target": "pod/claude-code"}); isToolErr(out) { + t.Fatalf("the hand-off: %s", out) + } + turns := len(w.turns.seen()) + hc := w.newestCard(t) + if _, err := w.srv.answerAskFrom(w.phone(), hc.ID, declineLabel, attention.AnswerSource{}); err != nil { + t.Fatalf("the phone's Don't start on the hand-off card: %v", err) + } + w.srv.WaitForAttentionDeliveries() + if a, _ := w.srv.ext.Attention.Get(w.asOwner, hc.ID); a.Delivery != attention.DeliveryDelivered { + t.Fatalf("the hand-off card's answer: delivery %q; want settled delivered", a.Delivery) + } + if got := len(w.turns.seen()); got != turns { + t.Fatalf("the chief got %d turns for the hand-off card's answer; want none", got-turns) + } + for _, id := range []int64{n.ID, h.ID} { + if got := w.startedOn(t, id); got != 0 { + t.Fatalf("Don't start started %d agents on task %d", got, id) + } + if cur, err := w.notes.Get(w.asOwner, id); err != nil || cur.Status != notes.StatusOpen { + t.Fatalf("task %d after Don't start: %+v (%v); want it open on the board", id, cur.Status, err) + } + } +} + +// TestAHandOffWithATargetFilesTheCardWithNoChiefTurn: officer_task_handoff +// with a target puts the owner's approval card in front of them directly — +// held, nothing reserved, the chief given no turn (now or by the sweep), the +// card showing the brief built from the task and naming the officer — and +// the owner's tap in the app starts the agent with no chief turn either: a +// pod, and a host with its repository. +func TestAHandOffWithATargetFilesTheCardWithNoChiefTurn(t *testing.T) { + for _, target := range []string{"pod/claude-code", "host/host-bravo/claude"} { + t.Run(target, func(t *testing.T) { + w := newHandoffWorld(t) + n := w.officerNote(t, "officer-task-fixture direct "+target) + args := map[string]any{"target": target} + if strings.HasPrefix(target, "host/") { + args["repo"] = apWidgets + } + before := w.allReservations(t) + out := w.handoff(n.ID, args) + if isToolErr(out) || !strings.Contains(out, `"status":"approval card filed for your owner"`) { + t.Fatalf("the hand-off: %s", out) + } + w.srv.putDueHandoffs(context.Background()) + w.srv.WaitForAttentionDeliveries() + if got := w.turns.seen(); len(got) != 0 { + t.Fatalf("the chief got %d turns; want none: %q", len(got), got) + } + card := w.newestCard(t) + d := w.holdOf(t, card.ID) + if d.Handoff == nil || d.Handoff.TaskID != n.ID || d.OfficerTask != n.ID || strings.Join(d.Blanks, ",") != blankApprove { + t.Fatalf("the card's hold: %+v; want a hand-off's approval card on task %d", d, n.ID) + } + for _, want := range []string{"Marketing officer (Example) filed this task and handed it off for an agent to do", + "needs a shell on a host with the capture tool", "Task #" + strconv.FormatInt(n.ID, 10) + ": officer-task-fixture direct", "take captures"} { + if !strings.Contains(card.Question, want) { + t.Errorf("the card lacks %q:\n%s", want, card.Question) + } + } + if w.allReservations(t) != before || len(w.m.spawnCalls()) != 0 { + t.Fatal("the hand-off reserved or spawned before the owner's answer") + } + w.tap(t, card.ID, approveLabel, authz.ViaSession) + w.srv.WaitForAttentionDeliveries() + if got := w.turns.seen(); len(got) != 0 { + t.Fatalf("the approval gave the chief %d turns; want none", len(got)) + } + if w.allReservations(t) != before+1 { + t.Fatalf("reservations %d after the approval; want %d", w.allReservations(t), before+1) + } + if strings.HasPrefix(target, "host/") { + if calls := w.m.spawnCalls(); len(calls) != 1 || calls[0].host != "host-bravo" || calls[0].req.Repo != apWidgets { + t.Fatalf("the spawn: %+v; want one on host-bravo in %s", calls, apWidgets) + } + } else if got := w.startedOn(t, n.ID); got != 1 { + t.Fatalf("agents on the task: %d; want 1", got) + } + if r := w.reservationOf(t, n.ID); r["approved_on_card"] != float64(card.ID) { + t.Fatalf("the reservation %v; want it to name card %d", r, card.ID) + } + if a, _ := w.srv.ext.Attention.Get(w.asOwner, card.ID); a.Delivery != attention.DeliveryDelivered { + t.Fatalf("the card's answer: delivery %q; want settled delivered", a.Delivery) + } + }) + } +} + +// TestAHandOffWithoutATargetStillStartsAChiefTurn (an INVARIANT GUARD of the +// existing path, green before this change too): with no target the hand-off +// is put to the chief as ONE turn and files no card. +func TestAHandOffWithoutATargetStillStartsAChiefTurn(t *testing.T) { + w := newHandoffWorld(t) + n := w.officerNote(t, "officer-task-fixture no target") + cards := len(w.cards(t)) + if out := w.handoff(n.ID, nil); isToolErr(out) || !strings.Contains(out, `"status":"handed to the chief"`) { + t.Fatalf("the hand-off: %s", out) + } + if got := w.turns.seen(); len(got) != 1 || !strings.Contains(got[0], "hands you task_id "+strconv.FormatInt(n.ID, 10)) { + t.Fatalf("the chief's turns: %q; want one naming the task", got) + } + if got := len(w.cards(t)); got != cards { + t.Fatalf("a hand-off with no target filed %d cards", got-cards) + } +} + +// TestAHandOffToATargetTheOwnerLacksIsRefused: an unknown host, an offline +// one, a runtime that needs a model, a blank, a host target with no +// repository and an unknown pod kind are each refused in plain words naming +// the owner's targets — no card, no chief turn, no hand-off recorded (the +// task's one hand-off and the day's count unspent) — and a repo with no +// target is refused. CONTROL: the same task then hands off on a real target. +func TestAHandOffToATargetTheOwnerLacksIsRefused(t *testing.T) { + w := newHandoffWorld(t) + n := w.officerNote(t, "officer-task-fixture bad target") + cards := len(w.cards(t)) + for _, c := range []struct { + args map[string]any + want string + }{ + {map[string]any{"target": "host/host-zulu/claude", "repo": apWidgets}, `host "host-zulu" is not one of your owner's hosts that can start a claude agent now.`}, + {map[string]any{"target": "host/host-delta/claude", "repo": apWidgets}, `host "host-delta" is not one of your owner's hosts that can start a claude agent now.`}, + {map[string]any{"target": "host/host-bravo/opencode", "repo": apWidgets}, "needs a model, which a hand-off does not name"}, + {map[string]any{"target": "host/?/claude", "repo": apWidgets}, "name the host and the runtime in full"}, + {map[string]any{"target": "host/host-bravo/claude"}, "a host target needs repo"}, + {map[string]any{"target": "pod/no-such-kind"}, `target "pod/no-such-kind": `}, + {map[string]any{"repo": apWidgets}, "repo is given with a target only"}, + } { + out := w.handoff(n.ID, c.args) + if !isToolErr(out) || !strings.Contains(errorText(t, out), c.want) { + t.Errorf("hand-off %v: %s; want refused with %q", c.args, out, c.want) + } + if c.args["target"] != nil && c.want != "a host target needs repo" && !strings.Contains(out, "Your owner's targets now: ") { + t.Errorf("hand-off %v: %s; want the owner's targets named", c.args, out) + } + } + if got := w.handoffRows(t, n.ID); got != 0 { + t.Fatalf("refused hand-offs recorded %d rows", got) + } + if got := len(w.cards(t)); got != cards || len(w.turns.seen()) != 0 { + t.Fatalf("refused hand-offs filed %d cards and %d chief turns", got-cards, len(w.turns.seen())) + } + if out := w.handoff(n.ID, map[string]any{"target": "host/host-bravo/claude", "repo": apWidgets}); isToolErr(out) { + t.Fatalf("control: a real target after the refusals: %s", out) + } + if got := w.handoffRows(t, n.ID); got != 1 { + t.Fatalf("control: %d hand-off rows; want 1", got) + } +} + +// TestNoPathStartsAHandedOffTaskWithoutTheOwnersApproval (the always-card +// rule, for the new door): after a hand-off with a target, nothing is +// reserved; the chief completing the same request itself waits on the card; +// the chief's own typed-turn owner_asked on the task raises a card rather than +// a start; a delivery of the still-open card starts nothing; and a card muster +// could not file (the owner's hourly approval cap) undoes the hand-off. Only +// the owner's answer — then — starts it, once. +func TestNoPathStartsAHandedOffTaskWithoutTheOwnersApproval(t *testing.T) { + w := newHandoffWorld(t) + n := w.officerNote(t, "officer-task-fixture always card") + before := w.allReservations(t) + if out := w.handoff(n.ID, map[string]any{"target": "pod/claude-code"}); isToolErr(out) { + t.Fatalf("the hand-off: %s", out) + } + card := w.newestCard(t) + d := w.holdOf(t, card.ID) + rebuilt := map[string]any{"target": "pod/claude-code", "task_id": n.ID, "request_key": d.RequestKey, + "prompt": handoffBrief(w.officer.ID, "needs a shell on a host with the capture tool", n)} + w.untypedTurn(t) + if got := errorText(t, w.callRaw(w.chief, agentDispatchTool, rebuilt)); got != agentDispatchHeldWaiting { + t.Fatalf("the chief completing the hand-off's request itself: %q; want it to wait on the card", got) + } + w.ownerTurn(t, w.chief, w.owner, "Start an agent on the capture task now.") + typed := officerCardCall(n.ID, "always-typed-1") + typed["owner_asked"] = true + if text := w.callRaw(w.chief, agentDispatchTool, typed); !strings.Contains(text, `"blanks":["approve"]`) { + t.Fatalf("the owner's typed turn on the handed-off task: %s; want a card", text) + } + if a, _ := w.srv.ext.Attention.Get(w.asOwner, card.ID); a.Status != attention.Open { + t.Fatalf("the hand-off card: %s; want open", a.Status) + } + if handled, o := w.srv.completeHandoffCard(w.asOwner, w.chief, card); !handled || o.delivered { + t.Fatalf("completing the OPEN hand-off card: handled %v, %+v; want handled and not started", handled, o) + } + if w.allReservations(t) != before || w.startedOn(t, n.ID) != 0 { + t.Fatal("an officer's handed-off task started without the owner's answer") + } + w.tap(t, card.ID, approveLabel, authz.ViaSession) + w.srv.WaitForAttentionDeliveries() + answered, _ := w.srv.ext.Attention.Get(w.asOwner, card.ID) + if handled, _ := w.srv.completeHandoffCard(w.asOwner, w.chief, answered); !handled { + t.Fatal("the answered card is not a hand-off card") + } + if got := w.startedOn(t, n.ID); got != 1 || w.allReservations(t) != before+1 { + t.Fatalf("after the owner's approval and a second completion: %d agents, %d reservations; want 1 and %d", got, w.allReservations(t), before+1) + } + + // The hourly cap reached: the card cannot be filed, so the hand-off is + // undone and the task can be handed off again later. + for i := 0; i < approvalCardsPerHour; i++ { + other := w.task(t, "officer-task-fixture cap "+strconv.Itoa(i)) + w.untypedTurn(t) + w.callRaw(w.chief, agentDispatchTool, officerCardCall(other.ID, "cap-"+strconv.Itoa(i))) + } + capped := w.officerNote(t, "officer-task-fixture capped") + out := w.handoff(capped.ID, map[string]any{"target": "pod/claude-code"}) + if !isToolErr(out) || !strings.Contains(out, "approval cards in front of your owner in the last hour") || w.handoffRows(t, capped.ID) != 0 { + t.Fatalf("a hand-off past the hourly cap: %s (%d rows); want refused and undone", out, w.handoffRows(t, capped.ID)) + } + if w.startedOn(t, capped.ID) != 0 { + t.Fatal("a capped hand-off started an agent") + } +} diff --git a/internal/api/officer_push.go b/internal/api/officer_push.go index 4e8139cda..99f783feb 100644 --- a/internal/api/officer_push.go +++ b/internal/api/officer_push.go @@ -104,6 +104,10 @@ const ( // officerPushNotifyOwner: an officer's instance called notify_owner // (toolNotifyOwner). officerPushNotifyOwner officerPush = "notify_owner" + // officerPushDispatchCard: the approval card of an agent start on a task + // an officer filed — muster's own for a hand-off that named its target, + // or the chief's (officerCardFiled). + officerPushDispatchCard officerPush = "dispatch_card" ) // officerPushes is THE classification: true for a path that asks the operator @@ -133,6 +137,7 @@ var officerPushes = map[officerPush]bool{ officerPushPageShared: false, // the owner opted in to unasked shares officerPushPageUpdated: false, // the page is in the officer's chat officerPushNotifyOwner: false, // a decision goes through officer_ask_person instead + officerPushDispatchCard: true, // approve the agent start, or don't start it } // officerPushSends reports whether path k pushes: its row in officerPushes. @@ -165,7 +170,7 @@ type officerCardRef struct { // opens. "" for a path that is not a decision (it never pushes). func officerDecisionCard(k officerPush, r officerCardRef) string { switch k { - case officerPushAsk, officerPushEscalation: + case officerPushAsk, officerPushEscalation, officerPushDispatchCard: // The tap route, resolved when tapped: the open ask's own page (its // card, its options and its answer box), else its item on the queue. return attentionOpenURL(r.ID) diff --git a/internal/api/officer_push_ledger_test.go b/internal/api/officer_push_ledger_test.go index dbe3d6e91..4930a82eb 100644 --- a/internal/api/officer_push_ledger_test.go +++ b/internal/api/officer_push_ledger_test.go @@ -56,6 +56,7 @@ var officerRouted = map[string]string{ "page_tools.go Server.pageShareAuto -> pushTask": string(officerPushPageShared), "notify_owner.go Server.pageUpdated -> pushTask": string(officerPushPageUpdated), "notify_owner.go Server.toolNotifyOwner -> goNotify": string(officerPushNotifyOwner), + "officer_card.go Server.officerCardFiled -> attentionNotify": string(officerPushDispatchCard), } // notOfficerRouted: every other call site, with why the table does not apply. @@ -96,7 +97,7 @@ var notOfficerRouted = map[string]string{ "chief_nudge.go Server.actAsk -> askFiled": "not officer-reachable: the chief's nudge", "chief_proposal.go Server.fileProposal -> proposalCardFiled": "not officer-reachable: the chief's proposal", "dispatch_hold_tools.go Server.pushSessionDispatch -> pushTask": "not officer-reachable: dispatch_request is refused to a host officer instance (hostInstanceTool)", - "host_dispatch.go Server.fileHeldDispatch -> proposalCardFiled": "not officer-reachable: the chief's held host dispatch", + "officer_card.go Server.dispatchCardFiled -> proposalCardFiled": "not officer-reachable: the chief's held dispatch of a task no officer filed (an officer's task's card, a hand-off's included, goes through officerCardFiled)", "host_dispatch_done.go Server.announceHostOutcome -> pushTask": "not officer-reachable: host dispatches only, not officer spawns", "host_dispatch_reconcile.go Server.orphanWindow -> askFiled": "not officer-reachable: a host dispatch's orphaned window", "hostjobs.go Server.hostJobReportFailed -> askFiled": "not officer-reachable: a host's jobs message muster could not record", diff --git a/internal/api/officer_push_test.go b/internal/api/officer_push_test.go index 36d264b3e..beda546b0 100644 --- a/internal/api/officer_push_test.go +++ b/internal/api/officer_push_test.go @@ -81,7 +81,7 @@ func TestEveryOfficerPushIsClassified(t *testing.T) { "ask": true, "escalation": true, "draft": true, "outreach_batch": true, "connector_request": true, "budget": true, "cap_hold": true, "restart_held": true, "draft_retrying": true, "draft_retry_ended": true, "draft_refused": false, "auto_restart": false, "budget_unreadable": false, "unclaimed": false, "page_published": false, "page_shared": false, - "page_updated": false, "notify_owner": false, + "page_updated": false, "notify_owner": false, "dispatch_card": true, } for k, d := range want { if got, ok := officerPushes[k]; !ok || got != d { @@ -116,6 +116,7 @@ func TestOfficerDecisionCardsAreTheirCards(t *testing.T) { {officerPushDraftRefused, officerCardRef{ID: "5317"}, ""}, {officerPushDraftRetrying, officerCardRef{ID: "5341"}, "/attention?tab=drafts#draft-5341"}, {officerPushDraftRetryEnded, officerCardRef{ID: "5343"}, "/attention?tab=drafts#draft-5343"}, + {officerPushDispatchCard, officerCardRef{ID: "ask-4759"}, "/attention/open/ask-4759"}, } { if got := officerDecisionCard(c.k, c.ref); got != c.want { t.Errorf("officerDecisionCard(%s, %+v) = %q, want %q", c.k, c.ref, got, c.want) diff --git a/internal/api/officer_task_handoff.go b/internal/api/officer_task_handoff.go index 44c95760d..8a50d86b4 100644 --- a/internal/api/officer_task_handoff.go +++ b/internal/api/officer_task_handoff.go @@ -12,6 +12,8 @@ import ( "github.com/ZacxDev/muster/internal/authz" "github.com/ZacxDev/muster/internal/chiefusage" "github.com/ZacxDev/muster/internal/fence" + "github.com/ZacxDev/muster/internal/github" + "github.com/ZacxDev/muster/internal/mirror" "github.com/ZacxDev/muster/internal/notes" "github.com/ZacxDev/muster/internal/officers" "github.com/ZacxDev/muster/internal/officers/builtin" @@ -46,6 +48,23 @@ import ( // open task THIS officer filed — another's reads "no such task" — at most // once per task, at most officers.MaxHandoffsPerDay a day; every hand-off is // audited (officer.task.handoff). +// +// WITH A TARGET (operator decision: the officer names where it runs): +// +// officer_task_handoff{task_id, why, target, repo?} the target checked +// against what the owner has NOW (handoffTargetRefusal: an unknown host, +// a host that cannot start agents, a target needing a model — refused, +// never another target in its place) ──▶ the row, stamped delivered at +// once so the sweep never puts it to the chief ──▶ agent_dispatch as the +// chief, muster's own call, with the brief built from the task +// (fileHandoffCard): the held dispatch and the owner's approval card, +// with NO chief turn. The owner's answer is completed by muster +// (completeHandoffCard). A card muster could not file undoes the row +// (DeleteHandoff) and the officer reads why. +// +// Still nothing starts from the call: the card is agent_dispatch's, every +// guard of a start runs on the owner's answer, and an officer's task starts +// only from the owner's approval of its card (officerStartRule). // --------------------------------------------------------------------------- // handoffMarker is the hand-off block's fence marker in the chief's turn. @@ -57,14 +76,24 @@ const officerTaskHandoffAuditAction = "officer.task.handoff" // officerTaskHandoffToolDef is officer_task_handoff's definition. func officerTaskHandoffToolDef() agents.ToolDef { return agents.ToolDef{Type: "function", Name: officers.ToolTaskHandoff, - Description: "Hand a task YOU filed (officer_task_create) to your owner's chief, when it needs an agent with a shell or a host to do it. " + - "muster puts it to the chief once; the chief decides what happens to it. A person must approve any agent the chief starts — your owner " + - "taps a card — so nothing starts from this call: do not say the work has started. If your owner taps \"Don't start\", the task stays on " + - "the board. A task is handed off at most once, and at most " + strconv.Itoa(officers.MaxHandoffsPerDay) + " a day.", + Description: "Hand a task YOU filed (officer_task_create) to an agent with a shell or a host, when it needs one. " + + "WITHOUT target, muster puts it to your owner's chief once and the chief decides where it runs. WITH target, muster puts your owner " + + "an approval card for it directly, with a brief built from the task, and no chief turn. Pick a target only when you know where the " + + "work must run: host/<host>/claude for a mirrored Claude Code agent on one of your owner's hosts (when the task needs that machine: " + + "a tool installed there, its files, its network), or pod/claude-code for a Claude Code agent in its own pod (any task that needs " + + "only a shell and a repository). A host target needs repo (owner/name, a repository your owner connected). An unknown host, or one " + + "that cannot start agents now, is refused — nothing else is picked in its place — and so is a target that needs a model; when you " + + "are unsure, leave target out. Either way a person must approve the agent — your owner taps a card — so nothing starts from this " + + "call: do not say the work has started. If your owner taps \"Don't start\", the task stays on the board. A task is handed off at " + + "most once, and at most " + strconv.Itoa(officers.MaxHandoffsPerDay) + " a day.", Parameters: objSchema(map[string]any{ "task_id": intProp("The task's id, as officer_task_create or tasks_list gave it.", 1, 1<<53), "why": map[string]any{"type": "string", "maxLength": builtin.MaxHandoffWhyRunes, "description": "One line: why it needs an agent (\"needs a shell on a host with the recall tool installed\")."}, + "target": map[string]any{"type": "string", "maxLength": 200, + "description": "Optional: where the agent runs — host/<host>/claude or pod/claude-code. Omit it to let the chief decide."}, + "repo": map[string]any{"type": "string", "maxLength": 200, + "description": "Optional, with target: the repository the agent works in, owner/name (required for a host target)."}, }, "task_id", "why")} } @@ -77,13 +106,19 @@ func (s *Server) officerTaskHandoff(ctx context.Context, a agents.Agent, o offic var in struct { TaskID int64 `json:"task_id"` Why string `json:"why"` + Target string `json:"target"` + Repo string `json:"repo"` } if err := json.Unmarshal([]byte(orEmptyJSON(arguments)), &in); err != nil || in.TaskID <= 0 { - return toolErr("arguments are {task_id, why}: task_id a task you filed") + return toolErr("arguments are {task_id, why, target?, repo?}: task_id a task you filed") } if why := builtin.HandoffWhyRefusal(in.Why); why != "" { return toolErr("%s", why) } + in.Target, in.Repo = strings.TrimSpace(in.Target), strings.TrimSpace(in.Repo) + if in.Repo != "" && in.Target == "" { + return toolErr("repo is given with a target only: name the target too, or leave both out for the chief to decide") + } octx := s.officerPrincipal(ctx, o.Owner) chief, err := s.chiefAgent(octx) if err != nil { @@ -92,6 +127,13 @@ func (s *Server) officerTaskHandoff(ctx context.Context, a agents.Agent, o offic } return toolErr("your owner has no chief running to hand the task to: leave it on the board (your owner sees it there)") } + if in.Target != "" { + // Checked BEFORE the row: a refused target spends neither the task's + // one hand-off nor the day's count. + if why := s.handoffTargetRefusal(octx, chief, in.Target, in.Repo); why != "" { + return toolErr("%s", why) + } + } h, err := s.officerStore.RecordHandoff(octx, builtin.Handoff{Owner: o.Owner, Officer: o.ID, TaskID: in.TaskID, Instance: a.Name, Why: in.Why}) switch { case err == nil: @@ -107,7 +149,10 @@ func (s *Server) officerTaskHandoff(ctx context.Context, a agents.Agent, o offic s.logger.Printf("officers: %s %s %d: %v", a.Name, officers.ToolTaskHandoff, in.TaskID, err) return toolErr("the hand-off could not be recorded") } - s.auditOfficerHandoff(octx, a, o, h) + if in.Target != "" { + return s.handoffWithTarget(octx, a, o, chief, h, in.Target, in.Repo) + } + s.auditOfficerHandoff(octx, a, o, h, nil) got := s.putHandoffToChief(octx, chief, h) s.logger.Printf("officers: %s handed task %d to chief %d (hand-off %d): %s", a.Name, h.TaskID, chief.ID, h.ID, got) return toolJSON(map[string]any{"handoff_id": h.ID, "task_id": h.TaskID, "status": "handed to the chief", @@ -118,7 +163,7 @@ func (s *Server) officerTaskHandoff(ctx context.Context, a agents.Agent, o offic // auditOfficerHandoff writes the audit_log row of officer o's instance a // handing task h.TaskID to the chief: the owner's row (as officerPrincipal // acts). A failed write is logged at ERROR, never silent. -func (s *Server) auditOfficerHandoff(ctx context.Context, a agents.Agent, o officers.Officer, h builtin.Handoff) { +func (s *Server) auditOfficerHandoff(ctx context.Context, a agents.Agent, o officers.Officer, h builtin.Handoff, extra map[string]any) { au, ok := s.ext.Users.(personalAuditor) p, signed := authz.From(ctx) if !ok || !signed { @@ -126,6 +171,9 @@ func (s *Server) auditOfficerHandoff(ctx context.Context, a agents.Agent, o offi return } detail := map[string]any{"officer": o.ID, "instance": a.Name, "handoff": h.ID, "why": h.Why} + for k, v := range extra { + detail[k] = v + } if err := au.Audit(ctx, users.Actor{UserID: p.UserID, Via: p.Via}, officerTaskHandoffAuditAction, "task:"+strconv.FormatInt(h.TaskID, 10), detail); err != nil { s.logger.Printf("ERROR audit: %s task:%d of officer %s: %v", officerTaskHandoffAuditAction, h.TaskID, o.ID, err) } @@ -208,3 +256,126 @@ func renderHandoffTurn(h builtin.Handoff, n notes.Note, officerName, nonce strin } return fence.Block{Preface: pre, Marker: handoffMarker, Count: 1, Lines: lines}.Render(nonce) } + +// handoffTargetRefusal is why target (and repo) cannot be a hand-off's, "" +// when they can: target must be one the owner has NOW — a pod kind this +// deployment enables (podKindOf), or host/<host>/claude on one of the +// owner's hosts that can start that runtime now (the host list agent_dispatch +// checks) — named whole, with no blank, and needing no model; a host target +// needs repo. Refused in plain words, with the owner's targets: never +// another target in its place. ctx acts as the owner. +func (s *Server) handoffTargetRefusal(ctx context.Context, chief agents.Agent, target, repo string) string { + list := func() string { + var out []string + for _, c := range s.dispatchTargetsNow(ctx).Choices { + if t, ok := parseHostTarget(c.Target); ok && t.Runtime != mirror.SpawnRuntimeClaude { + continue // a hand-off names no model + } + if c.Target == "pod/gateway" { + continue + } + out = append(out, c.Target) + } + if len(out) == 0 { + return " Your owner has no target an agent can start on now: leave target out, or leave the task on the board." + } + return " Your owner's targets now: " + strings.Join(out, ", ") + "." + } + if repo != "" && !github.ValidRepoName(repo) { + return "repo is owner/name (" + strconv.Quote(repo) + " is not one)" + } + if t, ok := parseHostTarget(target); ok { + switch { + case s.ownerIsTeam(ctx, agentOwnerID(chief)): + return "a team's chief starts pod/claude-code agents only: target " + strconv.Quote(target) + " is not one." + list() + case t.Host == "" || t.Runtime == "": + return "name the host and the runtime in full (host/<host>/claude): a hand-off leaves nothing blank." + list() + case t.Runtime != mirror.SpawnRuntimeClaude: + return "target " + strconv.Quote(target) + " needs a model, which a hand-off does not name: use host/" + t.Host + + "/claude, or leave target out for the chief to decide." + list() + case repo == "": + return "a host target needs repo: the repository the agent works in (owner/name)." + } + v, ok := s.hostView(ctx, t.Host) + if !ok || !hostSpawnable(v, t.Runtime) { + return "host " + strconv.Quote(t.Host) + " is not one of your owner's hosts that can start a " + t.Runtime + " agent now." + list() + } + return "" + } + if target == "pod/gateway" { + return "target pod/gateway needs a model, which a hand-off does not name: use pod/claude-code, or leave target out." + list() + } + if _, why := s.podKindOf(ctx, target); why != "" { + return "target " + strconv.Quote(target) + ": " + why + "." + list() + } + return "" +} + +// handoffWithTarget is officer_task_handoff with a target, after the row h +// was recorded: the row stamped delivered (the sweep never puts it to the +// chief), then the owner's card filed (fileHandoffCard). A card that could +// not be filed undoes the row, so the task can be handed off again. +func (s *Server) handoffWithTarget(octx context.Context, a agents.Agent, o officers.Officer, chief agents.Agent, h builtin.Handoff, target, repo string) string { + undo := func() { + if err := s.officerStore.DeleteHandoff(context.WithoutCancel(octx), h.ID); err != nil { + s.logger.Printf("ERROR officers: hand-off %d: undo after a refused card: %v", h.ID, err) + } + } + if ok, err := s.officerStore.MarkHandoffTurn(octx, h.ID); err != nil || !ok { + s.logger.Printf("officers: hand-off %d: stamp it delivered: %v (taken %v)", h.ID, err, ok) + undo() + return toolErr("the hand-off could not be recorded") + } + askID, why := s.fileHandoffCard(octx, chief, h, target, repo) + if why != "" { + undo() + s.logger.Printf("officers: %s hand-off of task %d to %s refused: %s", a.Name, h.TaskID, target, why) + return toolErr("muster could not put the task in front of your owner on %s: %s. Nothing was handed off: fix that and call again, "+ + "or leave target out for the chief to decide", target, why) + } + s.auditOfficerHandoff(octx, a, o, h, map[string]any{"target": target, "repo": repo, "card": askID}) + s.logger.Printf("officers: %s handed task %d to its owner's approval card %d on %s (hand-off %d)", a.Name, h.TaskID, askID, target, h.ID) + return toolJSON(map[string]any{"handoff_id": h.ID, "task_id": h.TaskID, "status": "approval card filed for your owner", "target": target, + "note": "your owner decides on the card (Approve and start, or Don't start), from muster or their phone. Nothing has started: do not " + + "say it has. When the task is finished muster queues you its " + officers.TaskDoneKind + " item; until then, do not hand it off again."}) +} + +// fileHandoffCard files hand-off h's dispatch on target (repo the officer's) +// as its owner's approval card: agent_dispatch as chief, muster's own call +// (withHandoffOrigin), with the brief built from the task. It answers the +// card's ask id, or why there is none. ctx acts as h's owner. +func (s *Server) fileHandoffCard(ctx context.Context, chief agents.Agent, h builtin.Handoff, target, repo string) (int64, string) { + if s.ext.Notes == nil { + return 0, "this server has no task store" + } + n, err := s.ext.Notes.Get(ctx, h.TaskID) + if err != nil { + return 0, "the task could not be read" + } + brief := handoffBrief(h.Officer, h.Why, n) + prompt, ok := cleanPrompt(brief) + if !ok { + return 0, "the task is too long for the brief an agent is given (8 KiB): shorten it, or leave target out for the chief to write one" + } + origin := handoffCard{ID: h.ID, Officer: h.Officer, TaskID: h.TaskID, Why: h.Why, Target: target, Repo: repo, BriefHash: briefHash(prompt)} + args, err := json.Marshal(agentDispatchIn{Target: target, TaskID: h.TaskID, Repo: repo, Prompt: brief, RequestKey: handoffRequestKey(h.ID)}) + if err != nil { + return 0, "the request could not be built" + } + out, _ := s.dispatchTaskRoutingTool(withHandoffOrigin(ctx, origin), chief, agentDispatchTool, string(args)) + var r map[string]any + if err := json.Unmarshal([]byte(out), &r); err != nil { + return 0, "an answer muster could not read" + } + held, _ := r["held"].(bool) + askID, _ := r[ui.OwnerCardAskIDKey].(float64) + switch { + case dispatchOutError(out) != "": + return 0, dispatchOutError(out) + case !held || askID <= 0: + // Never a start: an officer's task starts only from its card. A + // replay or a prior start of the task answers here. + return 0, "an agent was already started on this task" + } + return int64(askID), "" +} diff --git a/internal/api/server.go b/internal/api/server.go index b3139fe7d..2a56310d3 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -683,6 +683,9 @@ type RouterNotification struct { Update bool // AskActions: payload v2 offers Ask's signed actions (device_actions.go). AskActions bool + // AskOptionsOnly: of those, only an answer per option (push.Payload's; + // an officer's task's dispatch card, officer_card.go). + AskOptionsOnly bool // Actions: signed actions that are not an ask's (a connector request's // Approve and Deny, push.ConnectorActions), for payload v2 only. Actions []push.V2Action @@ -1891,7 +1894,7 @@ func (s *Server) goNotify(owner int64, event string, n RouterNotification, onDel if s.pushServed() { if drop = s.pushAllowed(ctx, to, event); drop == "" { rep := s.sendPush(ctx, to, push.Payload{Type: m.Type, ID: m.ID, Title: m.Title, Body: m.Body, Tag: m.Tag, Data: m.Data, - Ask: m.Ask, Update: m.Update, AskActions: m.AskActions, Actions: m.Actions, Silent: m.Silent}) + Ask: m.Ask, Update: m.Update, AskActions: m.AskActions, AskOptionsOnly: m.AskOptionsOnly, Actions: m.Actions, Silent: m.Silent}) n.outcome.addDelivered(rep.Devices, rep.Delivered) switch { case event == push.EventResolved: diff --git a/internal/api/stepup_gate_test.go b/internal/api/stepup_gate_test.go index d10f4ab02..7970ba576 100644 --- a/internal/api/stepup_gate_test.go +++ b/internal/api/stepup_gate_test.go @@ -569,17 +569,17 @@ func TestApprovingAnAgentStartInTheBrowserNeedsAFreshSignIn(t *testing.T) { } stale, fresh := time.Now().Add(-stepup.Window()-time.Minute), time.Now() for name, ctx := range map[string]context.Context{"stale": as(&stale), "no sign-in time": as(nil)} { - err := s.approvalSurfaceRefusal(ctx, 41) + err := s.approvalSurfaceRefusal(ctx, 41, approveLabel) if err == nil || !strings.Contains(err.Error(), DispatchCardStepUp) { t.Errorf("%s session, an approval card: %v, want %q", name, err, DispatchCardStepUp) } for _, other := range []int64{42, 43} { - if err := s.approvalSurfaceRefusal(ctx, other); err != nil { + if err := s.approvalSurfaceRefusal(ctx, other, approveLabel); err != nil { t.Errorf("%s session, ask %d (not an approval card): refused %v", name, other, err) } } } - if err := s.approvalSurfaceRefusal(as(&fresh), 41); err != nil { + if err := s.approvalSurfaceRefusal(as(&fresh), 41, approveLabel); err != nil { t.Errorf("control: a fresh session's approval: %v", err) } ctx := as(&stale) diff --git a/internal/officers/builtin/handoffs.go b/internal/officers/builtin/handoffs.go index 197d0c811..2d598a0ad 100644 --- a/internal/officers/builtin/handoffs.go +++ b/internal/officers/builtin/handoffs.go @@ -202,6 +202,20 @@ func (s *Store) MarkHandoffTurn(ctx context.Context, id int64) (bool, error) { return tag.RowsAffected() == 1, nil } +// DeleteHandoff removes hand-off id: a hand-off that named its target whose +// owner card muster could not file (internal/api officer_task_handoff.go) is +// undone, so the task may be handed off again and the day's count is not +// spent on a card nobody saw. Run as the officer's owner. +// +// A hand-off that names its target is never put to the chief: muster stamps +// its chief_turn_at (MarkHandoffTurn) BEFORE it files the owner's card, so the +// sweep (HandoffsDue) never takes it, and that stamp then means "delivered — +// as a card to the owner", not a chief turn. +func (s *Store) DeleteHandoff(ctx context.Context, id int64) error { + _, err := s.pool.Exec(ctx, `DELETE FROM officer_task_handoffs WHERE id = $1`, id) + return err +} + // UnmarkHandoffTurn gives hand-off id's turn back to the sweep (the chief's // runtime provably took nothing). func (s *Store) UnmarkHandoffTurn(ctx context.Context, id int64) error { diff --git a/internal/officers/kickoff.go b/internal/officers/kickoff.go index 3292cdc1e..e152cf7d8 100644 --- a/internal/officers/kickoff.go +++ b/internal/officers/kickoff.go @@ -111,7 +111,9 @@ func handoffNote(o Officer, caps Capabilities) string { } return fmt.Sprintf(" When a task you filed needs an agent with a shell or a host to do it, hand it to your owner's chief with %[1]s{task_id, why} (why: one line). "+ "The chief decides what happens to it; a person must approve any agent it starts, on a card your owner taps, so do not say the work has started. "+ - "A task is handed off at most once, and at most %[2]d a day.", ToolTaskHandoff, MaxHandoffsPerDay) + "When you know where the work must run, add target — host/<host>/claude with repo (owner/name) for one of your owner's hosts, or "+ + "pod/claude-code — and muster puts the approval card to your owner directly, with no chief turn; a target your owner does not have "+ + "now is refused, never replaced. A task is handed off at most once, and at most %[2]d a day.", ToolTaskHandoff, MaxHandoffsPerDay) } // The officer-task caps (enforced by internal/officers/builtin's diff --git a/internal/officers/task_create_test.go b/internal/officers/task_create_test.go index 6fd672411..e67e02d45 100644 --- a/internal/officers/task_create_test.go +++ b/internal/officers/task_create_test.go @@ -77,6 +77,7 @@ func TestEveryBuiltinKickoffTellsItToFileATask(t *testing.T) { "If your owner dismisses one, they do not want it done: never file it again (task_get still reads it).", "muster queues you a task.done item carrying the task's id, how it finished and its files", "hand it to your owner's chief with officer_task_handoff{task_id, why} (why: one line). The chief decides what happens to it; a person must approve any agent it starts", + "When you know where the work must run, add target — host/<host>/claude with repo (owner/name) for one of your owner's hosts, or pod/claude-code — and muster puts the approval card to your owner directly, with no chief turn; a target your owner does not have now is refused, never replaced.", } { if !strings.Contains(got, want) { t.Errorf("%s (tier %q, %s): the kickoff lacks %q", o.ID, o.Tier, o.RuntimeKind(), want) diff --git a/internal/officers/testdata/kickoff_builtin_host.golden b/internal/officers/testdata/kickoff_builtin_host.golden index 8f04290da..b97c51bc4 100644 --- a/internal/officers/testdata/kickoff_builtin_host.golden +++ b/internal/officers/testdata/kickoff_builtin_host.golden @@ -12,4 +12,4 @@ Start now: You watch, triage, record and dispatch. You never merge, deploy or release. You run as host-alpha's own user, with that user's files and credentials: use them only for what your charter asks. -When your work needs something you cannot do yourself — something only a person can do, or only a machine with a shell (a terminal capture, a command run on a host, a screenshot of a desktop) — do not escalate that you cannot do it: file a task on your owner's board with officer_task_create{item_id, title, body}. item_id is the item you are working (muster links it from the task); title says in a few plain words what you need done; body says, for a person who has not read the item, exactly what to do and why it unblocks your work. muster marks the task as yours and tells your owner. An identical task you already filed that is still open is answered instead of a second one; you may file at most 5 tasks a day and have at most 10 open. Then finish the item as your charter says (it may be waiting on the task). Your own tasks — only the ones you filed — you may list, read and comment on with tasks_list, task_get, task_comment; you cannot mark one complete: your owner does. If your owner dismisses one, they do not want it done: never file it again (task_get still reads it). Each time one of them is completed, or dismissed, muster queues you a task.done item carrying the task's id, how it finished and its files, so you pick the blocked work back up from there. When a task you filed needs an agent with a shell or a host to do it, hand it to your owner's chief with officer_task_handoff{task_id, why} (why: one line). The chief decides what happens to it; a person must approve any agent it starts, on a card your owner taps, so do not say the work has started. A task is handed off at most once, and at most 3 a day. The images and videos attached to a task you filed are media you may post: name one in officer_post_draft's media as task-<task_id>/<attachment id> (the task.done item lists each file's id). Only your own tasks' files; your owner still approves every draft. \ No newline at end of file +When your work needs something you cannot do yourself — something only a person can do, or only a machine with a shell (a terminal capture, a command run on a host, a screenshot of a desktop) — do not escalate that you cannot do it: file a task on your owner's board with officer_task_create{item_id, title, body}. item_id is the item you are working (muster links it from the task); title says in a few plain words what you need done; body says, for a person who has not read the item, exactly what to do and why it unblocks your work. muster marks the task as yours and tells your owner. An identical task you already filed that is still open is answered instead of a second one; you may file at most 5 tasks a day and have at most 10 open. Then finish the item as your charter says (it may be waiting on the task). Your own tasks — only the ones you filed — you may list, read and comment on with tasks_list, task_get, task_comment; you cannot mark one complete: your owner does. If your owner dismisses one, they do not want it done: never file it again (task_get still reads it). Each time one of them is completed, or dismissed, muster queues you a task.done item carrying the task's id, how it finished and its files, so you pick the blocked work back up from there. When a task you filed needs an agent with a shell or a host to do it, hand it to your owner's chief with officer_task_handoff{task_id, why} (why: one line). The chief decides what happens to it; a person must approve any agent it starts, on a card your owner taps, so do not say the work has started. When you know where the work must run, add target — host/<host>/claude with repo (owner/name) for one of your owner's hosts, or pod/claude-code — and muster puts the approval card to your owner directly, with no chief turn; a target your owner does not have now is refused, never replaced. A task is handed off at most once, and at most 3 a day. The images and videos attached to a task you filed are media you may post: name one in officer_post_draft's media as task-<task_id>/<attachment id> (the task.done item lists each file's id). Only your own tasks' files; your owner still approves every draft. \ No newline at end of file diff --git a/internal/push/ask_options_only_test.go b/internal/push/ask_options_only_test.go new file mode 100644 index 000000000..0277f0af9 --- /dev/null +++ b/internal/push/ask_options_only_test.go @@ -0,0 +1,74 @@ +package push + +import ( + "encoding/json" + "strings" + "testing" +) + +// TestAnOptionsOnlyAskOffersItsOptionsAlone: an ask pushed AskOptionsOnly (an +// officer's task's dispatch card) offers exactly an ask_answer per option, by +// index — no suggestion, no inline Answer, no Dismiss — in the payload as +// sent, and still after the fit drops its suggestions. CONTROL, the same +// payload without AskOptionsOnly: every button, Answer and Dismiss included. +func TestAnOptionsOnlyAskOffersItsOptionsAlone(t *testing.T) { + sent := func(only bool, body string, suggestions ...string) PayloadV2 { + t.Helper() + if len(suggestions) == 0 { + suggestions = []string{strings.Repeat("問", MaxNativeChip)} + } + p := Payload{Type: "attention", Title: strings.Repeat("\x01", MaxNativeTitle), Body: body, AskActions: true, AskOptionsOnly: only, + Ask: &V2Ask{ID: 4711, Options: []string{"Approve and start", "Don't start"}, Suggestions: suggestions}} + b, err := nativeBody(p) + if err != nil { + t.Fatal(err) + } + var v PayloadV2 + if err := json.Unmarshal(b, &v); err != nil { + t.Fatal(err) + } + return v + } + ids := func(v PayloadV2) string { + var out []string + for _, a := range v.Actions { + switch { + case a.Option != nil: + out = append(out, "option"+string(rune('0'+*a.Option))) + case a.Suggestion != nil: + out = append(out, "suggestion") + case a.Input: + out = append(out, "input") + default: + out = append(out, a.ID) + } + } + return strings.Join(out, ",") + } + if got := ids(sent(true, "Task #12: captures")); got != "option0,option1" { + t.Fatalf("an options-only ask's buttons: %s; want option0,option1", got) + } + if got := ids(sent(false, "Task #12: captures")); got != "option0,option1,suggestion,input,ask_dismiss" { + t.Fatalf("control: an ordinary ask's buttons: %s", got) + } + for _, a := range sent(true, "x").Actions { + if a.ID != ActionAskAnswer || a.Target != "4711" || a.Label != "" { + t.Fatalf("an options-only button: %+v", a) + } + } + // Too long to keep the suggestions (each character JSON-escaped to six + // bytes): the refit drops them and keeps the options alone, never Answer + // and Dismiss back. CONTROL: the same payload without AskOptionsOnly is + // refit too, and keeps its Answer and Dismiss. + wide := strings.Repeat("\u2028", MaxNativeChip) + long := sent(true, strings.Repeat("\x01", MaxNativeBody), wide, wide, wide) + if len(long.Ask.Suggestions) != 0 { + t.Fatalf("the fit kept %d suggestions: the payload was not over the cap, so this does not test the refit", len(long.Ask.Suggestions)) + } + if got := ids(long); got != "option0,option1" { + t.Fatalf("after the fit: %s; want option0,option1", got) + } + if got := ids(sent(false, strings.Repeat("\x01", MaxNativeBody), wide, wide, wide)); got != "option0,option1,input,ask_dismiss" { + t.Fatalf("control after the fit: %s", got) + } +} diff --git a/internal/push/service.go b/internal/push/service.go index f83114dfc..6b67fc673 100644 --- a/internal/push/service.go +++ b/internal/push/service.go @@ -38,6 +38,12 @@ type Payload struct { // AskActions: the server routes the signed ask actions, so payload v2 // offers them (PayloadV2.Actions). Payload v2 only. AskActions bool `json:"-"` + // AskOptionsOnly: of the ask's signed actions, payload v2 offers ONLY an + // ask_answer per option — no suggestion, no inline Answer, no Dismiss + // (askOptionActions). An officer's task's dispatch card (internal/api + // officer_card.go) is answered with its two buttons and nothing + // else. Read only with AskActions. Payload v2 only. + AskOptionsOnly bool `json:"-"` // Actions are signed actions that are not an ask's (a connector request's // Approve and Deny, ConnectorActions): payload v2 carries them as they // are. Payload v2 only; never set together with Ask. @@ -164,6 +170,31 @@ func askActions(a *V2Ask) []V2Action { V2Action{ID: ActionAskDismiss, Label: "Dismiss", Target: t}) } +// askOptionActions is a's buttons when only its options answer it +// (Payload.AskOptionsOnly): an ask_answer per option, by its index, and +// nothing else. +func askOptionActions(a *V2Ask) []V2Action { + t := strconv.FormatInt(a.ID, 10) + var out []V2Action + for i := range a.Options { + i := i + out = append(out, V2Action{ID: ActionAskAnswer, Target: t, Option: &i}) + } + return out +} + +// actionsFor is ask a's buttons as p offers them: none without AskActions, +// its options alone with AskOptionsOnly, else every one (askActions). +func (p Payload) actionsFor(a *V2Ask) []V2Action { + switch { + case !p.AskActions: + return nil + case p.AskOptionsOnly: + return askOptionActions(a) + } + return askActions(a) +} + // V2Ask is an attention ask's chips in payload v2. Each option and suggestion // is WHOLE or absent — a chip whose text was cut would answer something the // asker did not offer — so one longer than MaxNativeChip runes is left out of @@ -246,7 +277,7 @@ func nativeBody(p Payload) ([]byte, error) { } v.Ask = &a if v.Actions != nil { - v.Actions = askActions(v.Ask) + v.Actions = p.actionsFor(v.Ask) } if b, err = json.Marshal(v); err != nil { return nil, err @@ -268,9 +299,7 @@ func (p Payload) V2() PayloadV2 { v.Title, v.Body, v.URL, v.Update = CutClusters(p.Title, MaxNativeTitle), CutClusters(p.Body, MaxNativeBody), p.Data["url"], p.Update if p.Ask != nil { v.Ask = &V2Ask{ID: p.Ask.ID, Options: chips(p.Ask.Options), Suggestions: chips(p.Ask.Suggestions)} - if p.AskActions { - v.Actions = askActions(v.Ask) - } + v.Actions = p.actionsFor(v.Ask) } else if len(p.Actions) > 0 { v.Actions = append([]V2Action(nil), p.Actions...) } From 2469922d86a351fa11a0c710cbb97e0170955c43 Mon Sep 17 00:00:00 2001 From: Zachary Lowden <zacxdev@gmail.com> Date: Fri, 4 Dec 2026 09:09:33 -0600 Subject: [PATCH 2/2] officers: a hand-off's brief carries no task text; its card binds the task The task-text seam ledger (task_kickoff_ledger_test.go) caught handoffBrief copying the task's title and body into the agent's brief, outside the kickoff rule that every start on a task goes through. The brief is now muster's words and the officer's one line only; the task's title and text reach the agent after it through taskKickoffText, as on every start. The hand-off card shows the task's title and text instead (the first 1,500 characters; the whole task is on the board) and binds them with a hash of the task (handoffCard.TaskHash): an approval of a card whose task changed since is refused on every door before it is recorded, and the completion refuses a change that lands between the answer and the start. Both readers are ledgered as never reaching an agent. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --- docs/officers-builtin.md | 24 +++++---- docs/push.md | 4 +- internal/api/dispatch_approval.go | 23 ++++++++- internal/api/officer_card.go | 64 +++++++++++++----------- internal/api/officer_card_pg_test.go | 47 ++++++++++++++++- internal/api/officer_task_handoff.go | 15 +++--- internal/api/task_kickoff_ledger_test.go | 2 + 7 files changed, 125 insertions(+), 54 deletions(-) diff --git a/docs/officers-builtin.md b/docs/officers-builtin.md index 54d211fdf..515aa5240 100644 --- a/docs/officers-builtin.md +++ b/docs/officers-builtin.md @@ -906,13 +906,14 @@ When the officer knows where the work must run, it adds `target` (and - With a target, muster does not put the hand-off to the chief. It files the held dispatch and the owner's approval card **directly**, as the chief's `agent_dispatch` on the task would (the same guards: the owner's opt-in, - the caps, at most 6 approval cards an hour), with a brief **muster builds - from the task**: which officer filed it and why it needs an agent, then the - task's title and text. The card says the officer handed it off and shows - that brief whole. The hand-off is stamped delivered at once, so the sweep - never puts it to the chief; a card muster cannot file (the hourly cap, a - repository that is not connected, a task too long for a brief) undoes the - hand-off and the officer reads why. + the caps, at most 6 approval cards an hour), with **muster's own brief**: + which officer filed the task and why it needs an agent. The task's title + and text reach the agent after the brief, as on every start on a task. The + card says the officer handed it off and shows the task's title, its text + (the first 1,500 characters; the whole task is on the board) and the brief + whole. The hand-off is stamped delivered at once, so the sweep never puts + it to the chief; a card muster cannot file (the hourly cap, a repository + that is not connected) undoes the hand-off and the officer reads why. - **The owner's answer is completed by muster**, with no chief turn and whether or not the chief is running: **Approve and start** — in muster or from the phone — runs `agent_dispatch` again as the chief, with the same @@ -925,10 +926,11 @@ When the officer knows where the work must run, it adds `target` (and is shown on the card's answer with why; the officer is not told. ⚠ When the card lapses unanswered (24 hours), the lapse note goes to the chief's chat as for any dispatch card. -- **A changed task is never approved.** If the task's title or text changed - since its card was filed, the brief the card shows is no longer what would - start: **Approve and start** is refused on every door before it is - recorded, the card stays open, and the owner can choose **Don't start**. +- **A changed task is never approved.** The card binds the task's title and + text as they were when it was filed. If either changed since, **Approve and + start** is refused on every door before it is recorded, the card stays + open, and the owner can choose **Don't start**; a change that lands after + the answer but before muster completes it is refused there too. - Without a target everything above (the chief's turn) is unchanged. ##### Approving an officer's task from the phone diff --git a/docs/push.md b/docs/push.md index a4a3ac715..eb30f6957 100644 --- a/docs/push.md +++ b/docs/push.md @@ -458,8 +458,8 @@ as **payload v2**: with no options line. The challenge's `confirms` is that title and body, so the step-up prompt shows what the tap decides. The signed answer is the card's own answer, taken exactly as a tap in muster; the start stays bound - to the brief the card shows whole (a hand-off card whose task changed since - refuses **Approve and start** on every door, and the card stays open). A tap + to the request the card shows whole (a hand-off card whose task changed + since refuses **Approve and start** on every door, and the card stays open). A tap on the body still opens the whole card. **Every other approval card** — the chief's on a task no officer filed, a team's, a repository or clone card — carries no buttons and its answer from the phone is refused, as before. An diff --git a/internal/api/dispatch_approval.go b/internal/api/dispatch_approval.go index 5927efa2c..c04ebfd84 100644 --- a/internal/api/dispatch_approval.go +++ b/internal/api/dispatch_approval.go @@ -225,7 +225,7 @@ type approvalRequest struct { typed bool // handoff is the officer's name when muster files the card for an // officer's hand-off that named its target (officer_task_handoff.go): no - // chief asked for it, and the brief is muster's, built from the task. + // chief asked for it, the brief is muster's, and the card shows the task's text. handoff string } @@ -235,6 +235,10 @@ func (r approvalRequest) repoChangeable() bool { return !r.onTask || strings.TrimSpace(r.task.Repo) == "" } +// handoffCardBodyRunes bounds the task text a hand-off's card shows: the +// task is on the owner's board whole, and the card binds all of it. +const handoffCardBodyRunes = 1500 + // approvalQuestion is the card's text: the request in full, the brief last // and whole. ok false when it does not fit attention.MaxQuestionRunes (the // refusal then says by how much): a brief is never cut on the card, because @@ -294,6 +298,21 @@ func approvalQuestionFor(r approvalRequest, repoBlank, cloneBlank bool) (string, title, _, _ = strings.Cut(strings.TrimSpace(r.task.Body), "\n") } b.WriteString("Task: #" + strconv.FormatInt(r.task.ID, 10) + " " + one(fence.Cut(title, 120)) + "\n") + if r.handoff != "" { + // A hand-off's card: the task's own text, which the agent is given + // after the brief — the card binds it (handoffCard.TaskHash). + body := strings.TrimSpace(r.task.Body) + if utf8.RuneCountInString(body) > handoffCardBodyRunes { + body = fence.Cut(body, handoffCardBodyRunes) + "\n(cut here: the whole task is on your board)" + } + if body != "" { + lines := strings.Split(body, "\n") + for i, l := range lines { + lines[i] = fence.Sanitize(l) + } + b.WriteString("Task text:\n" + strings.Join(lines, "\n") + "\n") + } + } } else { b.WriteString("Task: none\n") } @@ -301,7 +320,7 @@ func approvalQuestionFor(r approvalRequest, repoBlank, cloneBlank bool) (string, case strings.TrimSpace(r.prompt) == "": b.WriteString("\nBrief: none (the agent is given the task's text).") case r.handoff != "": - b.WriteString("\nThe brief muster built from the task — what the agent is told, exactly as shown:\n" + r.prompt) + b.WriteString("\nmuster's brief — what the agent is told first, exactly as shown; the task follows it:\n" + r.prompt) default: b.WriteString("\nThe chief's brief — what the agent is told, exactly as shown:\n" + r.prompt) } diff --git a/internal/api/officer_card.go b/internal/api/officer_card.go index dd0d7bf28..79045c5cb 100644 --- a/internal/api/officer_card.go +++ b/internal/api/officer_card.go @@ -40,8 +40,10 @@ import ( // // 2. THE OFFICER NAMES THE TARGET. officer_task_handoff with a target files // the held dispatch and its card DIRECTLY — agent_dispatch as the chief, -// with the brief muster builds from the task (handoffBrief), in no chief -// turn — and the owner's answer is completed by muster itself +// with muster's own brief (handoffBrief: who handed it off and why; the +// task's own text reaches the agent through the kickoff rule, as on every +// start on a task), in no chief turn — and the owner's answer is +// completed by muster itself // (completeHandoffCard, from the answer's delivery): agent_dispatch again, // the same arguments rebuilt from the hold, so every guard runs as for the // chief's own call — the owner's opt-in, the caps, the officer rule, the @@ -53,10 +55,11 @@ import ( // unchanged (officerStartRule under its lock). // // 🔴 THE BRIEF IS BOUND. The hold's hash binds the start to the arguments the -// card was filed with, the brief among them; a hand-off card's brief is -// rebuilt from the task at the answer (handoffCard.BriefHash), so an approval -// of a card whose task changed since is refused on every door before it is -// recorded (handoffCardRefusal), and the start refused if it got that far. +// card was filed with, the brief among them. A hand-off card also shows the +// task's title and text, and binds them (handoffCard.TaskHash): an approval of +// a card whose task changed since is refused on every door before it is +// recorded (handoffCardRefusal), and the start is refused if it got that far +// (completeHandoffCard). // --------------------------------------------------------------------------- // handoffCard is a hand-off card's part of its hold (heldDetail.Handoff): @@ -69,8 +72,9 @@ type handoffCard struct { // Target and Repo are the officer's, as it named them. Target string `json:"target"` Repo string `json:"repo,omitempty"` - // BriefHash is the sha256 of the cleaned brief the card shows. - BriefHash string `json:"brief_hash"` + // TaskHash is the sha256 of the task's title and text as the card showed + // them (handoffTaskHash). + TaskHash string `json:"task_hash"` } // handoffOriginKey carries, on the context of the agent_dispatch call muster @@ -95,22 +99,22 @@ func handoffTrigger(h handoffCard) string { // handoffRequestKey is the request_key of hand-off id's dispatch. func handoffRequestKey(id int64) string { return "officer-handoff-" + strconv.FormatInt(id, 10) } -// handoffBrief is the brief muster builds for officer's hand-off of task n: -// who filed it and why it needs an agent, then the task's title and text — -// exactly what the card shows and the agent is told. -func handoffBrief(officer, why string, n notes.Note) string { - var b strings.Builder - b.WriteString(ui.OfficerSourceName(officer) + " filed this task and handed it off for an agent to do: " + strings.TrimSpace(why) + "\n") - b.WriteString("Task #" + strconv.FormatInt(n.ID, 10) + ": " + strings.TrimSpace(n.Title)) - if body := strings.TrimSpace(n.Body); body != "" { - b.WriteString("\n\n" + body) - } - return b.String() +// handoffBrief is the brief muster writes for officer's hand-off of task +// taskID: who handed it off and why it needs an agent. It carries no task +// text — the task's title and text follow it in the agent's first message +// through the kickoff rule (taskKickoffText), as on every start on a task — +// so the brief is muster's words and the officer's one line, both shown whole +// on the card. +func handoffBrief(officer, why string, taskID int64) string { + return ui.OfficerSourceName(officer) + " filed task #" + strconv.FormatInt(taskID, 10) + " and handed it off for an agent to do: " + + strings.TrimSpace(why) + "\nDo the task that follows this brief." } -// briefHash is the hex sha256 of a cleaned brief. -func briefHash(prompt string) string { - sum := sha256.Sum256([]byte(prompt)) +// handoffTaskHash is the hex sha256 of task n's title and text: what a +// hand-off card shows of the task and binds (handoffCard.TaskHash). It only +// compares; the text is never sent anywhere from here. +func handoffTaskHash(n notes.Note) string { + sum := sha256.Sum256([]byte(n.Title + "\x00" + n.Body)) return hex.EncodeToString(sum[:]) } @@ -242,9 +246,9 @@ const ( // handoffCardRefusal is the answer path's check of an approval (answer // "Approve and start") of hand-off card id, before anything is recorded, on -// every door: the brief rebuilt from the task NOW must be the brief the card -// was filed with (handoffCard.BriefHash), else it is refused and the card -// stays open. nil for any other answer or card. +// every door: the task NOW must be the task the card showed +// (handoffCard.TaskHash), else it is refused and the card stays open. nil for +// any other answer or card. func (s *Server) handoffCardRefusal(ctx context.Context, id int64, answer string) error { if strings.TrimSpace(answer) != approveLabel || s.ext.Notes == nil { return nil @@ -257,8 +261,7 @@ func (s *Server) handoffCardRefusal(ctx context.Context, id int64, answer string if err != nil { return errReleaseRefused(handoffCardUnread) } - prompt, ok := cleanPrompt(handoffBrief(d.Handoff.Officer, d.Handoff.Why, n)) - if !ok || briefHash(prompt) != d.Handoff.BriefHash { + if handoffTaskHash(n) != d.Handoff.TaskHash { return errReleaseRefused(handoffCardStale) } return nil @@ -320,7 +323,12 @@ func (s *Server) completeHandoffCard(ctx context.Context, chief agents.Agent, a if err != nil { return true, handoffOutcome{detail: "muster could not start it: its task could not be read"} } - in := agentDispatchIn{Target: ho.Target, TaskID: ho.TaskID, Repo: ho.Repo, Prompt: handoffBrief(ho.Officer, ho.Why, n), RequestKey: d.RequestKey} + if handoffTaskHash(n) != ho.TaskHash { + // Changed after the answer was recorded: the card's task is not this one. + s.logger.Printf("officers: hand-off %d: card %d answered %q, not started: its task changed since the card was filed", ho.ID, a.ID, a.Answer) + return true, handoffOutcome{detail: "muster did not start it: " + handoffCardStale} + } + in := agentDispatchIn{Target: ho.Target, TaskID: ho.TaskID, Repo: ho.Repo, Prompt: handoffBrief(ho.Officer, ho.Why, ho.TaskID), RequestKey: d.RequestKey} switch d.Blanks[0] { case blankRepo: // The repository the owner picked, or typed (completeHeld judges it). diff --git a/internal/api/officer_card_pg_test.go b/internal/api/officer_card_pg_test.go index 34b57590d..b984a8f99 100644 --- a/internal/api/officer_card_pg_test.go +++ b/internal/api/officer_card_pg_test.go @@ -278,6 +278,43 @@ func TestAPhoneApprovalOfAChangedBriefIsRefused(t *testing.T) { } } +// TestAHandOffTaskChangedAfterTheAnswerIsNotStarted: an approval recorded +// while the task was unchanged, the task then edited before muster completes +// it — the completion refuses it (its task is not the one the card showed) +// and starts nothing. CONTROL: the same completion of an unchanged task +// starts it. +func TestAHandOffTaskChangedAfterTheAnswerIsNotStarted(t *testing.T) { + w := newHandoffWorld(t) + for _, edit := range []bool{true, false} { + h := w.officerNote(t, "officer-task-fixture after answer "+strconv.FormatBool(edit)) + if out := w.handoff(h.ID, map[string]any{"target": "pod/claude-code"}); isToolErr(out) { + t.Fatalf("the hand-off: %s", out) + } + card := w.newestCard(t) + // Recorded by the store alone: no delivery is started, so the edit + // lands between the answer and its completion, deterministically. + answered, err := w.srv.ext.Attention.Answer(w.phone(), card.ID, approveLabel) + if err != nil { + t.Fatal(err) + } + if edit { + if _, err := w.pool.Exec(authz.System(context.Background()), `UPDATE notes SET body = $2 WHERE id = $1`, h.ID, "take captures, then also wipe the disk"); err != nil { + t.Fatal(err) + } + } + handled, o := w.srv.completeHandoffCard(w.asOwner, w.chief, answered) + if !edit { + if !handled || !o.delivered || w.startedOn(t, h.ID) != 1 { + t.Fatalf("control: an unchanged task's completion: handled %v %+v, %d agents; want started", handled, o, w.startedOn(t, h.ID)) + } + continue + } + if !handled || o.delivered || !strings.Contains(o.detail, handoffCardStale) || w.startedOn(t, h.ID) != 0 { + t.Fatalf("a task changed after the answer: handled %v %+v, %d agents; want refused as changed, nothing started", handled, o, w.startedOn(t, h.ID)) + } + } +} + // TestAPhonesDontStartLeavesTheOfficersTaskOnTheBoard: "Don't start" from the // phone is taken on an officer's task's card. The chief's card: its // completing call is refused as declined. A hand-off's card: muster settles @@ -354,7 +391,8 @@ func TestAHandOffWithATargetFilesTheCardWithNoChiefTurn(t *testing.T) { t.Fatalf("the card's hold: %+v; want a hand-off's approval card on task %d", d, n.ID) } for _, want := range []string{"Marketing officer (Example) filed this task and handed it off for an agent to do", - "needs a shell on a host with the capture tool", "Task #" + strconv.FormatInt(n.ID, 10) + ": officer-task-fixture direct", "take captures"} { + "needs a shell on a host with the capture tool", "Task: #" + strconv.FormatInt(n.ID, 10) + " officer-task-fixture direct", + "Task text:\ntake captures", "filed task #" + strconv.FormatInt(n.ID, 10) + " and handed it off for an agent to do"} { if !strings.Contains(card.Question, want) { t.Errorf("the card lacks %q:\n%s", want, card.Question) } @@ -374,6 +412,11 @@ func TestAHandOffWithATargetFilesTheCardWithNoChiefTurn(t *testing.T) { if calls := w.m.spawnCalls(); len(calls) != 1 || calls[0].host != "host-bravo" || calls[0].req.Repo != apWidgets { t.Fatalf("the spawn: %+v; want one on host-bravo in %s", calls, apWidgets) } + // The agent is told muster's brief, then the task itself. + p := w.m.spawnCalls()[0].req.Prompt + if i, j := strings.Index(p, "and handed it off for an agent to do"), strings.Index(p, "take captures"); i < 0 || j < 0 || j < i { + t.Fatalf("the spawned agent's prompt lacks the brief, then the task:\n%s", p) + } } else if got := w.startedOn(t, n.ID); got != 1 { t.Fatalf("agents on the task: %d; want 1", got) } @@ -466,7 +509,7 @@ func TestNoPathStartsAHandedOffTaskWithoutTheOwnersApproval(t *testing.T) { card := w.newestCard(t) d := w.holdOf(t, card.ID) rebuilt := map[string]any{"target": "pod/claude-code", "task_id": n.ID, "request_key": d.RequestKey, - "prompt": handoffBrief(w.officer.ID, "needs a shell on a host with the capture tool", n)} + "prompt": handoffBrief(w.officer.ID, "needs a shell on a host with the capture tool", n.ID)} w.untypedTurn(t) if got := errorText(t, w.callRaw(w.chief, agentDispatchTool, rebuilt)); got != agentDispatchHeldWaiting { t.Fatalf("the chief completing the hand-off's request itself: %q; want it to wait on the card", got) diff --git a/internal/api/officer_task_handoff.go b/internal/api/officer_task_handoff.go index 8a50d86b4..80388ccf7 100644 --- a/internal/api/officer_task_handoff.go +++ b/internal/api/officer_task_handoff.go @@ -56,7 +56,7 @@ import ( // a host that cannot start agents, a target needing a model — refused, // never another target in its place) ──▶ the row, stamped delivered at // once so the sweep never puts it to the chief ──▶ agent_dispatch as the -// chief, muster's own call, with the brief built from the task +// chief, muster's own call, with muster's brief (who handed it off, why) // (fileHandoffCard): the held dispatch and the owner's approval card, // with NO chief turn. The owner's answer is completed by muster // (completeHandoffCard). A card muster could not file undoes the row @@ -78,7 +78,7 @@ func officerTaskHandoffToolDef() agents.ToolDef { return agents.ToolDef{Type: "function", Name: officers.ToolTaskHandoff, Description: "Hand a task YOU filed (officer_task_create) to an agent with a shell or a host, when it needs one. " + "WITHOUT target, muster puts it to your owner's chief once and the chief decides where it runs. WITH target, muster puts your owner " + - "an approval card for it directly, with a brief built from the task, and no chief turn. Pick a target only when you know where the " + + "an approval card for it directly, showing the task and your why, and no chief turn. Pick a target only when you know where the " + "work must run: host/<host>/claude for a mirrored Claude Code agent on one of your owner's hosts (when the task needs that machine: " + "a tool installed there, its files, its network), or pod/claude-code for a Claude Code agent in its own pod (any task that needs " + "only a shell and a repository). A host target needs repo (owner/name, a repository your owner connected). An unknown host, or one " + @@ -342,7 +342,8 @@ func (s *Server) handoffWithTarget(octx context.Context, a agents.Agent, o offic // fileHandoffCard files hand-off h's dispatch on target (repo the officer's) // as its owner's approval card: agent_dispatch as chief, muster's own call -// (withHandoffOrigin), with the brief built from the task. It answers the +// (withHandoffOrigin), with muster's brief (handoffBrief); the card shows and +// binds the task's title and text (handoffCard.TaskHash). It answers the // card's ask id, or why there is none. ctx acts as h's owner. func (s *Server) fileHandoffCard(ctx context.Context, chief agents.Agent, h builtin.Handoff, target, repo string) (int64, string) { if s.ext.Notes == nil { @@ -352,12 +353,8 @@ func (s *Server) fileHandoffCard(ctx context.Context, chief agents.Agent, h buil if err != nil { return 0, "the task could not be read" } - brief := handoffBrief(h.Officer, h.Why, n) - prompt, ok := cleanPrompt(brief) - if !ok { - return 0, "the task is too long for the brief an agent is given (8 KiB): shorten it, or leave target out for the chief to write one" - } - origin := handoffCard{ID: h.ID, Officer: h.Officer, TaskID: h.TaskID, Why: h.Why, Target: target, Repo: repo, BriefHash: briefHash(prompt)} + brief := handoffBrief(h.Officer, h.Why, h.TaskID) + origin := handoffCard{ID: h.ID, Officer: h.Officer, TaskID: h.TaskID, Why: h.Why, Target: target, Repo: repo, TaskHash: handoffTaskHash(n)} args, err := json.Marshal(agentDispatchIn{Target: target, TaskID: h.TaskID, Repo: repo, Prompt: brief, RequestKey: handoffRequestKey(h.ID)}) if err != nil { return 0, "the request could not be built" diff --git a/internal/api/task_kickoff_ledger_test.go b/internal/api/task_kickoff_ledger_test.go index ed8427695..d6627a809 100644 --- a/internal/api/task_kickoff_ledger_test.go +++ b/internal/api/task_kickoff_ledger_test.go @@ -106,6 +106,8 @@ var expectedTaskTextReaders = map[string]string{ "auditOfficerTask": "the officer task's title in the owner's audit_log row; never sent to an agent", "officerTaskFinished": "reads only muster's own footer for the item number (officerTaskItem); the task.done item carries ids and file metadata, no task text", "renderHandoffTurn": "an officer's task hand-off to the chief: the task's title is fenced in the turn (fence.Block), as a routed task's is", + "officerCardSummary": "an officer's task's approval card's notification lines and the phone's step-up prompt, shown to a person; never sent to an agent", + "handoffTaskHash": "hashes a hand-off card's task to compare it with the one the card showed; the text is never sent", } // expectedKickoffBuilders is every unit that calls a kickoff helper: the