diff --git a/pkgs/fleet/book/concepts/bridge.md b/pkgs/fleet/book/concepts/bridge.md index 481e9d907..210b1c76f 100644 --- a/pkgs/fleet/book/concepts/bridge.md +++ b/pkgs/fleet/book/concepts/bridge.md @@ -38,6 +38,7 @@ commands): | `inbox [--agent A] [--groups g1,g2] [--commands \| --messages] [--all] [--since-id N] [--limit N] [--take] [--wait SECS] [--interval SECS]` | `GET /fleet//inbox?…` | Unread items by default; `--all` includes read ones; `--take` marks what it returns as read; `--wait` polls (default interval 15 s; wait capped at 24 h in source) until something arrives or the seconds pass. | | `post [--agent A] [--reply-to ID] [--to ADDR] [--instruction \| --kind K] ` | `POST /fleet//send` | A message to central by default. With `--reply-to` it answers that row (and marks it read). `--to` sends to any address instead: `drew`, `claude`, `chatgpt`, `connectors`, `agent:` (or a bare name), `group:`, `agents`, `all`; repeat or comma-separate. `--instruction` (or `--kind instruction`) makes it an instruction, which requires `--to`. | | `ack [--agent A] (--up-to ID \| ID...)` | `POST /fleet//ack` | Mark messages read: either a list of ids, or everything up to an id. | +| `work [--agent A] --state acted\|queued\|done [--task ID] ID...` | `POST /fleet//work` | Record the work-item lifecycle of your own instructions: `acted` (handled in-session), `queued` (became queue task `--task`), `done`. Forward only, from `received`; only the receiving agent can mark its own copy. | | `health` | `GET /healthz` | The bridge's health probe. No token. | Defaults and config: the agent name defaults to `$FLEET_AGENT`, then @@ -63,6 +64,18 @@ operations change read state: - `post --reply-to ID` answers a row and marks that row read. - `ack` marks explicit ids, or everything up to an id with `--up-to`. +Read state is not the whole story for instructions. An instruction is a +work item with a lifecycle the receiving agent records with `work`: +`received` → `acted` (handled in-session) or `queued` (it became a named +fleet queue task) → `done`, forward only, each recipient's copy +independent on a group send. The owner's pipeline shows the state and +the queue task id, so an instruction that is neither acted on nor +queued stays visible at `received` — the defect the task-it-or-queue-it +rule (in the reference chapter, and in the text the intake ladder hands +a woken agent) exists to prevent. Notes instructions carry the same +fields on the notes surface; connector-channel instructions store none — +their read state stands in for `acted`. + The registry side is equally simple: there is no separate enrolment store on the bridge. Saying `hello` _is_ registering — name, groups, and last-seen are refreshed on every hello — and `agents` reports the registry as the set diff --git a/pkgs/fleet/book/reference/bridge.md b/pkgs/fleet/book/reference/bridge.md index ae55f413e..4adb5d055 100644 --- a/pkgs/fleet/book/reference/bridge.md +++ b/pkgs/fleet/book/reference/bridge.md @@ -13,7 +13,7 @@ Two token families, both resolved **by name** through fleet-secrets; values are | Family | Secret name | Opens | URL shape | | --------------------------- | ------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------- | | Owner token (central verbs) | `message-bridge.access-token` (renamable via `[bridge] owner_token_name`) | `send`, `agents`, `log` | `/api//fleet/…` | -| Fleet token (agent verbs) | `message-bridge.fleet-token` | `hello`, `inbox`, `post`, `ack` — agent routes only; it cannot send commands | `/fleet//…` | +| Fleet token (agent verbs) | `message-bridge.fleet-token` | `hello`, `inbox`, `post`, `ack`, `work` — agent routes only; it cannot send commands | `/fleet//…` | | Per-agent credential | `bridge.-fleet-token` (the name the agent profile records) | The same agent routes, as that one agent only; its groups are the ones bound when the owner minted its bootstrap token | `/fleet//…` | | Notes token (notes family) | `bridge.-token` (renamable via `[bridge] notes_token_name`) | `notes send`, `notes inbox`, `notes ack` for the token's class/name identity | `Authorization: Bearer` header on `/notes/…` | @@ -346,6 +346,38 @@ $ fleet bridge ack --agent archer --up-to 412 Marks all of `archer`'s messages up to id 412 as read. +## fleet bridge work + +``` +fleet bridge work [--agent A] --state acted|queued|done [--task ID] ID... +``` + +| Flag | Argument | Default | Meaning | +| -------------------- | --------------------- | ------------------------------------- | ------------------------------------------------------------------ | +| `--agent` | `A` | `$FLEET_AGENT`, then `[bridge] agent` | Agent whose mailbox copy to mark. | +| `--state` | `acted\|queued\|done` | required | The lifecycle state to record. | +| `--task` | `ID` | — | The fleet queue task the instruction became; required for `queued`. | +| `ID...` (positional) | ids | required | The instruction rows to mark; several ids are marked one by one. | + +### Behaviour + +Agent verb (fleet token). Records the **work-item lifecycle** of instructions in this agent's own mailbox. Route: `POST /fleet//work` with `{agent, id, state, task_id?}` per id. An instruction starts at `received`; the receiving agent moves its own copy forward — `acted` (handled in-session), `queued` (it became a fleet queue task; `--task` names it), then `done`. States move only forward (`received` → `acted` | `queued` → `done`); re-marking the current state is a no-op. Only the receiving agent can mark a row: with a per-agent credential, naming another agent or another agent's row is the bridge's plain 404. The owner sees every row's state and task id in the pipeline, so an instruction that is neither acted on nor queued stays visible at `received`. Notes instructions carry the same lifecycle on the notes surface (`POST /notes/work`, same body shape); connector-channel instructions store no lifecycle fields — their read state stands in for `acted` in the pipeline. + +The rule the lifecycle serves, carried verbatim by this book, the verb's help text, and the woken-agent text the intake ladder hands out with a pushed command: + +> Task it or queue it. An instruction is a work item: do the work now, in this session, and reply — or queue it as a repo-task/v1 packet whose context_refs carry the bridge surface, the message id and the batch, and reply with the task id. Record the outcome with fleet bridge work: --state acted for work done in-session, --state queued --task for queued work, --state done when the work is finished. An instruction that is neither acted on nor queued is a defect: it stays at received, where the owner can see it stuck in the pipeline. + +### Exit codes + +`0` ok · `2` usage (including `--state queued` without `--task`) · `3` transport or credentials · `4` the bridge refused the request. + +### Example + +```console +$ fleet bridge work --agent archer --state queued --task 23500 412 +``` + +Records that archer queued instruction 412 as fleet queue task 23500. ## fleet bridge exchange ``` diff --git a/pkgs/fleet/crates/fleet-agent/src/next.rs b/pkgs/fleet/crates/fleet-agent/src/next.rs index 6b3b9f9c6..43d427f0e 100644 --- a/pkgs/fleet/crates/fleet-agent/src/next.rs +++ b/pkgs/fleet/crates/fleet-agent/src/next.rs @@ -33,6 +33,20 @@ use crate::{ DEFAULT_REPO, EXIT_NO_WORK, EXIT_OK, Out, R, World, argv, check_name, check_repo, parse, usage, }; +/// The task-it-or-queue-it rule handed to an agent woken by a pushed +/// command (design §4.6, #14372). Verbatim copy of fleet-bridge's +/// WORK_RULE; the same text stands in the fleet book +/// (pkgs/fleet/book/reference/bridge.md). Edit all three together. +pub const PUSH_WORK_RULE: &str = "\ +Task it or queue it. An instruction is a work item: do the work now, in \ +this session, and reply — or queue it as a repo-task/v1 packet whose \ +context_refs carry the bridge surface, the message id and the batch, and \ +reply with the task id. Record the outcome with fleet bridge work: \ +--state acted for work done in-session, --state queued --task for \ +queued work, --state done when the work is finished. An instruction \ +that is neither acted on nor queued is a defect: it stays at received, \ +where the owner can see it stuck in the pipeline."; + /// Labels that hold an issue (FDR-0012): a person set them on purpose. pub const HOLD_LABELS: [&str; 3] = ["held", "user/owned", "do-not-auto-edit"]; /// Labels on an issue that indexes other work and is not itself a @@ -603,6 +617,11 @@ pub fn next(world: &dyn World, args: &[String]) -> R<(Value, i32)> { "command_id": id, "instructions": message.get("body").and_then(Value::as_str).unwrap_or(""), "message": message, + // The task-it-or-queue-it rule (design §4.6, #14372): + // the same text the work verb's help and the fleet + // book carry (fleet-bridge's WORK_RULE) — keep all + // three verbatim-consistent. + "rule": PUSH_WORK_RULE, }); let then = vec![ format!( @@ -611,6 +630,11 @@ pub fn next(world: &dyn World, args: &[String]) -> R<(Value, i32)> { format!( "fleet bridge post --agent {agent} --reply-to {id} \"could not: \"" ), + format!("fleet bridge work --agent {agent} --state acted {id}"), + format!( + "fleet bridge work --agent {agent} --state queued --task {id}" + ), + format!("fleet bridge work --agent {agent} --state done {id}"), ]; return Ok(answer("push", task, then, log)); } diff --git a/pkgs/fleet/crates/fleet-bridge/src/lib.rs b/pkgs/fleet/crates/fleet-bridge/src/lib.rs index 289445803..4b3e7f2ce 100644 --- a/pkgs/fleet/crates/fleet-bridge/src/lib.rs +++ b/pkgs/fleet/crates/fleet-bridge/src/lib.rs @@ -63,6 +63,22 @@ const FLEET_TOKEN_LABEL: &str = "message-bridge/fleet-token/v1"; const DEFAULT_INTERVAL_SECS: u64 = 15; const MAX_WAIT_SECS: u64 = 24 * 3600; +/// The task-it-or-queue-it rule for instructions (design §4.6, +/// #14372). This exact text is carried in three places that must stay +/// verbatim-consistent: here (the work verb's help), the fleet book +/// (pkgs/fleet/book/reference/bridge.md), and the woken-agent text the +/// intake ladder hands out with a pushed command +/// (fleet-agent/src/next.rs). Edit all three together. +pub const WORK_RULE: &str = "\ +Task it or queue it. An instruction is a work item: do the work now, in \ +this session, and reply — or queue it as a repo-task/v1 packet whose \ +context_refs carry the bridge surface, the message id and the batch, and \ +reply with the task id. Record the outcome with fleet bridge work: \ +--state acted for work done in-session, --state queued --task for \ +queued work, --state done when the work is finished. An instruction \ +that is neither acted on nor queued is a defect: it stays at received, \ +where the owner can see it stuck in the pipeline."; + pub const USAGE: &str = "\ usage: fleet bridge [options] @@ -118,6 +134,10 @@ agent (fleet token): --instruction (or --kind instruction) makes it an instruction, which needs --to. ack [--agent A] (--up-to ID | ID...) mark messages read + work [--agent A] --state acted|queued|done [--task ID] ID... + record the work-item lifecycle of your own instructions: + acted (handled in-session), queued (became queue task --task), + done. States move only forward, from received. provisioning (single-use bootstrap token, minted by the owner): exchange --agent A --bootstrap TOKEN @@ -298,6 +318,22 @@ usage: fleet bridge ack [--agent A] (--up-to ID | ID...) agent (fleet token). Mark messages read." } + "work" => { + return Some(format!( + "\ +usage: fleet bridge work [--agent A] --state acted|queued|done [--task ID] ID... + +agent (fleet token). Record the work-item lifecycle of instructions in +your own mailbox: acted for work handled in-session, queued for work +that became a fleet queue task (give its id with --task), done when the +work is finished. States move only forward, from received; a row can +only be marked by the agent it was sent to. + +{WORK_RULE} + +{USAGE_FOOTER}" + )); + } "exchange" => { "\ usage: fleet bridge exchange --agent A --bootstrap TOKEN @@ -753,6 +789,8 @@ const VALUE_FLAGS: &[&str] = &[ "--interval", "--reply-to", "--up-to", + "--state", + "--task", "--bootstrap", "--scopes", "--ttl", @@ -1432,6 +1470,55 @@ pub fn execute(ctx: &mut Ctx, args: &[String]) -> R { let token = fleet_token(ctx)?; client_with(ctx, &token).call("POST", &format!("/fleet/{token}/ack"), Some(&payload)) } + "work" => { + let a = parse(rest, &[], &["--agent", "--state", "--task"])?; + let agent = agent_of(&a, &ctx.settings)?; + let state = a + .last("--state") + .ok_or_else(|| usage("work needs --state acted, queued or done"))?; + if !matches!(state.as_str(), "acted" | "queued" | "done") { + return Err(usage(format!( + "--state is acted, queued or done, not '{state}'" + ))); + } + let task = a.uint("--task")?; + if state == "queued" && task.is_none() { + return Err(usage( + "queued work needs --task: the fleet queue task id it became", + )); + } + let ids: Vec = + a.positional + .iter() + .map(|p| { + p.parse::().ok().filter(|n| *n > 0).ok_or_else(|| { + usage(format!("message id '{p}' is not a positive number")) + }) + }) + .collect::>()?; + if ids.is_empty() { + return Err(usage("work needs at least one message ID")); + } + let token = fleet_token(ctx)?; + let client = client_with(ctx, &token); + let mut marked = Vec::new(); + for id in &ids { + let mut payload = json!({ "agent": &agent, "id": id, "state": &state }); + if let Some(t) = task { + payload["task_id"] = json!(t); + } + marked.push(client.call( + "POST", + &format!("/fleet/{token}/work"), + Some(&payload), + )?); + } + if marked.len() == 1 { + Ok(marked.pop().unwrap()) + } else { + Ok(json!({ "marked": marked })) + } + } "exchange" => verb_exchange(ctx, rest), "notes" => verb_notes(ctx, rest), "health" => { diff --git a/pkgs/fleet/crates/fleet-bridge/src/tests.rs b/pkgs/fleet/crates/fleet-bridge/src/tests.rs index cb32db14c..c1b58e29c 100644 --- a/pkgs/fleet/crates/fleet-bridge/src/tests.rs +++ b/pkgs/fleet/crates/fleet-bridge/src/tests.rs @@ -192,6 +192,7 @@ fn every_verb_has_its_own_help() { "inbox", "post", "ack", + "work", "health", "exchange", "notes", @@ -235,6 +236,13 @@ fn usage_errors_exit_2_before_any_request() { ], vec!["ack", "--agent", "a"], vec!["ack", "--agent", "a", "0"], + vec!["work", "--agent", "a"], + vec!["work", "--agent", "a", "--state", "done"], + vec!["work", "--agent", "a", "--state", "sideways", "3"], + vec!["work", "--agent", "a", "--state", "received", "3"], + vec!["work", "--agent", "a", "--state", "queued", "3"], + vec!["work", "--agent", "a", "--state", "done", "0"], + vec!["work", "--agent", "a", "--state", "done", "--task", "x", "3"], vec!["log", "--limit", "many"], vec!["pipeline", "--limit", "many"], vec!["pipeline", "--bogus", "x"], @@ -471,6 +479,57 @@ fn ack_log_and_agents_shapes() { ); } +#[test] +fn work_marks_the_agents_own_rows_and_names_the_queue_task() { + let (url, seen) = fake_bridge(|_, _, _| { + (200, r#"{"message":{"id":3,"work_state":"queued","work_task_id":23500}}"#.into()) + }); + let s = secrets(&[(DEFAULT_BRIDGE_FLEET_TOKEN_NAME, "f".repeat(40).as_str())]); + let out = run_with( + &url, + &s, + &["work", "--agent", "muse-1", "--state", "queued", "--task", "23500", "3"], + "", + ) + .unwrap(); + assert_eq!(out["message"]["work_state"], "queued"); + run_with( + &url, + &s, + &["work", "--agent", "muse-1", "--state", "acted", "4", "5"], + "", + ) + .unwrap(); + let seen = seen.lock().unwrap(); + assert_eq!(seen[0].method, "POST"); + assert_eq!(seen[0].url, format!("/fleet/{}/work", "f".repeat(40))); + assert_eq!( + seen[0].body.as_ref().unwrap(), + &json!({"agent": "muse-1", "id": 3, "state": "queued", "task_id": 23500}) + ); + // Several ids are one request each, in order. + assert_eq!(seen.len(), 3); + assert_eq!( + seen[1].body.as_ref().unwrap(), + &json!({"agent": "muse-1", "id": 4, "state": "acted"}) + ); + assert_eq!( + seen[2].body.as_ref().unwrap(), + &json!({"agent": "muse-1", "id": 5, "state": "acted"}) + ); +} + +#[test] +fn work_help_carries_the_task_it_or_queue_it_rule() { + // #14372 acceptance: the help text and the book carry the same + // rule, verbatim. The book half is pinned by the text itself + // (pkgs/fleet/book/reference/bridge.md quotes WORK_RULE). + let text = verb_usage("work").unwrap(); + assert!(text.contains(WORK_RULE), "{text}"); + assert!(WORK_RULE.contains("repo-task/v1"), "{WORK_RULE}"); + assert!(WORK_RULE.contains("context_refs"), "{WORK_RULE}"); +} + #[test] fn pipeline_directory_credentials_and_revoke_shapes() { // #14374: the console's unified views and its revoke control, as diff --git a/pkgs/message-bridge/worker/README.md b/pkgs/message-bridge/worker/README.md index d6206765c..c1930c285 100644 --- a/pkgs/message-bridge/worker/README.md +++ b/pkgs/message-bridge/worker/README.md @@ -51,7 +51,7 @@ instead: see "Adding it to Claude". | `GET /api//messages` | JSON history: `direction`, `channel` (`claude`/`chatgpt`/`all`), `kind`, `since_id`, `before_id`, `unread_only`, `limit`, `order` | | `POST /api//messages` | JSON `{"body", "sender", "to", "kind"}`; `to` is `"claude"` (default), `"chatgpt"` or both as a list: one inbound row per recipient; `kind` is `"message"` (default) or `"instruction"` | | `POST /api//ack` | JSON `{"up_to_id": N}` or `{"ids": [...]}`, with `channel` (default `claude`): marks inbound messages read | -| `GET /api//pipeline` | One normalized feed over connector messages, fleet messages and notes, real senders shown: `kind`, `sender`, `receiver`, `surface`, `batch`, `unread_only`, `since_id`, `before_id`, `limit`, `order` | +| `GET /api//pipeline` | One normalized feed over connector messages, fleet messages and notes, real senders shown: `kind`, `sender`, `receiver`, `surface`, `batch`, `unread_only`, `work_state`, `since_id`, `before_id`, `limit`, `order`; rows carry the instruction work-item lifecycle (`work_state`, `work_task_id`) | | `GET /api//notes` | Owner read over the notes table (the same filters as the pipeline); rows carry recipient, sender, body and ack state | | `GET /api//agents` | Unified connected-agents list: fleet registry (groups, first/last seen, unread counts) and note identities (scopes, signal counter), each row marked by surface; notes have no presence | | `GET /api//oauth-events` | The last 100 connector sign-in events, newest first (registrations with the client's requested metadata, approvals, refusals with the reason); never a secret | @@ -62,6 +62,7 @@ instead: see "Adding it to Claude". | `POST /notes/send` | Identity Bearer token: JSON `{"to", "note"}`; `to` is one identity or a wildcard in either segment (`muse/*`, `*/archer`, `*/*`) | | `GET /notes/inbox` | Identity Bearer token: that identity's unacknowledged notes | | `POST /notes/ack` | Identity Bearer token: JSON `{"id"}`, `{"ids": [...]}` or `{"up_to_id": N}` acknowledges its own notes | +| `POST /notes/work` | Identity Bearer token: JSON `{"id", "state", "task_id"?}` records the work-item lifecycle of one of its own notes: `acted` \| `queued` (needs `task_id`) \| `done`, forward only from `received` | | `GET //` | Public wake signal: one bare UUID, the same shape for registered and unregistered paths, rotating on a per-path jittered schedule | | `GET /healthz` | `ok`, `configured`, `chatgpt_configured`, `version`, `token_fingerprint`; no data | | `POST /`, `POST /mcp` | The MCP server with an OAuth bearer token (channel from the approval); 401 with `resource_metadata` without one | @@ -103,6 +104,7 @@ their mailbox, mark what they handled, and post replies and reports back | `POST /fleet//hello` | fleet | `{agent, groups?}`: register or refresh an agent | | `GET /fleet//inbox` | fleet | `agent`, `groups`, `kind`, `since_id`, `unread_only` (default true), `mark_read`, `limit` | | `POST /fleet//ack` | fleet | `{agent, up_to_id \| ids}`: mark read | +| `POST /fleet//work` | fleet | `{agent, id, state, task_id?}`: the work-item lifecycle of one of the agent's own inbound rows — `acted` \| `queued` (needs `task_id`) \| `done`, forward only from `received`; a per-agent credential marks only its own rows, every refusal the plain 404 | | `POST /fleet//send` | fleet | `{agent, body, to?, kind?, reply_to?}`: to central, or to any address (see Any to any) | | `GET /api//fleet/agents` | owner | registered agents, groups, last seen, unread counts | | `GET /api//fleet/messages` | owner | `agent`, `direction`, `kind`, `since_id`, `before_id`, `limit`, `order` | diff --git a/pkgs/message-bridge/worker/src/fleet.js b/pkgs/message-bridge/worker/src/fleet.js index c11a13c2a..4f97d8f9c 100644 --- a/pkgs/message-bridge/worker/src/fleet.js +++ b/pkgs/message-bridge/worker/src/fleet.js @@ -18,6 +18,13 @@ // &unread_only=&mark_read=&limit=: the // agent's inbound rows, oldest first // POST /fleet//ack {agent, up_to_id | ids}: mark read +// POST /fleet//work {agent, id, state, task_id?}: +// record the work-item lifecycle of +// one of the agent's own inbound +// rows (design §4.6): state is +// acted | queued | done, moving +// only forward from received; +// queued names its queue task id // POST /fleet//send {agent, body, to?, kind?, reply_to?}: // a message from the agent. With no // to it goes to central (or, with @@ -166,7 +173,7 @@ import { MIN_TOKEN_LENGTH, matchTokenPath, safeEqual, tokenConfigured } from "./auth.js"; import { GLOB_SEGMENT, globMatch, isGlob } from "./glob.js"; -import { InputError, MAX_BODY, MAX_SENDER } from "./messages.js"; +import { InputError, MAX_BODY, MAX_SENDER, normalizeWorkMark, workTransitionError } from "./messages.js"; import { normalizeNoteIdentity, noteTokenHash } from "./notes.js"; import { pipelineFeed, unifiedAgents } from "./pipeline.js"; import { relay, replyAddress } from "./relay.js"; @@ -373,6 +380,8 @@ export function normalizeFleetOp(op, a = {}) { }; case "ack": return { agent: normalizeName(a.agent), ...ackArgs(a) }; + case "work": + return { agent: normalizeName(a.agent), ...normalizeWorkMark(a) }; case "post": return { agent: normalizeName(a.agent), @@ -485,6 +494,10 @@ export function fleetSchema(sql) { // Rows from before connectors and agents could message agents all came from central. const cols = sql.exec("PRAGMA table_info(fleet_message)").toArray(); if (!cols.some((c) => c.name === "from_addr")) sql.exec("ALTER TABLE fleet_message ADD COLUMN from_addr TEXT"); + // The instruction work-item lifecycle (#14372, design §4.6): null + // until the receiving agent marks the row; null reads as "received". + if (!cols.some((c) => c.name === "work_state")) sql.exec("ALTER TABLE fleet_message ADD COLUMN work_state TEXT"); + if (!cols.some((c) => c.name === "work_task_id")) sql.exec("ALTER TABLE fleet_message ADD COLUMN work_task_id INTEGER"); sql.exec("CREATE INDEX IF NOT EXISTS fleet_message_mailbox ON fleet_message (agent, direction, read_at)"); // Per-agent credentials (#14368): only the SHA-256 hash of a credential // is stored, never the value. scopes is a JSON array drawn from @@ -799,6 +812,33 @@ export function fleetOp(sql, op, a, now = new Date().toISOString()) { touch(sql, a.agent, null, now); return { acked, stats: mailboxStats(sql, a.agent) }; } + case "work": { + // Only the receiving agent's own inbound rows can be marked: the + // lookup is scoped to this mailbox, so another agent's row (or a + // row this agent sent) is simply not found. Transitions are + // forward-only (messages.js workTransitionError); a queued mark + // already named its task id at validation time, and a later mark + // without one keeps the recorded id. + const row = sql + .exec( + "SELECT id, work_state, work_task_id FROM fleet_message WHERE id = ? AND agent = ? AND direction = 'inbound'", + a.id, + a.agent, + ) + .toArray()[0]; + if (!row) return { error: `message ${a.id} is not in ${a.agent}'s mailbox` }; + const err = workTransitionError(row.work_state, a.state); + if (err) return { error: err }; + sql.exec( + "UPDATE fleet_message SET work_state = ?, work_task_id = ? WHERE id = ?", + a.state, + a.task_id ?? row.work_task_id ?? null, + a.id, + ); + touch(sql, a.agent, null, now); + const message = { ...sql.exec("SELECT * FROM fleet_message WHERE id = ?", a.id).toArray()[0] }; + return { message, stats: mailboxStats(sql, a.agent) }; + } case "post": { let batch = null; if (a.reply_to !== null) { @@ -1634,6 +1674,20 @@ async function agentRoute(request, store, what, url, delivered, cred = null) { if (cred && (!scoped("inbox") || credOwnName(d.agent, cred) === null)) return notFound(); return json(await store.fleet("ack", d)); } + if (what === "work") { + if (request.method !== "POST") return notAllowed("POST"); + const d = await readJson(request); + if (cred && (!scoped("inbox") || credOwnName(d.agent, cred) === null)) return notFound(); + try { + return json(await store.fleet("work", d)); + } catch (e) { + // With a credential every work refusal is the plain 404, like + // every other credential refusal: the caller learns nothing + // about rows that are not its own. + if (cred && e instanceof InputError) return notFound(); + throw e; + } + } if (what === "send") { if (request.method !== "POST") return notAllowed("POST"); const d = await readJson(request); diff --git a/pkgs/message-bridge/worker/src/index.js b/pkgs/message-bridge/worker/src/index.js index 4023e1452..a480b78e6 100644 --- a/pkgs/message-bridge/worker/src/index.js +++ b/pkgs/message-bridge/worker/src/index.js @@ -8,7 +8,7 @@ // Routes and auth: see routes.js and auth.js. The access token is the // Worker secret ACCESS_TOKEN; it is never in git. import { DurableObject } from "cloudflare:workers"; -import { OAUTH_CLIENT_IDLE, OAUTH_MAX_CLIENTS, OAUTH_MAX_EVENTS, OAUTH_PENDING_GRACE, OAUTH_REG_PER_SOURCE, ackSelector, normalizeChannel, normalizeNew, normalizeQuery, noteForInbox } from "./messages.js"; +import { OAUTH_CLIENT_IDLE, OAUTH_MAX_CLIENTS, OAUTH_MAX_EVENTS, OAUTH_PENDING_GRACE, OAUTH_REG_PER_SOURCE, ackSelector, normalizeChannel, normalizeNew, normalizeQuery, noteForInbox, workTransitionError } from "./messages.js"; import { enrollTokenClaimSql, enrollTokenGetSql, @@ -133,6 +133,15 @@ export class MessageStore extends DurableObject { this.sql.exec("ALTER TABLE note_message ADD COLUMN batch TEXT"); } this.sql.exec("CREATE INDEX IF NOT EXISTS note_message_inbox ON note_message (recipient, ack_at, id)"); + // The instruction work-item lifecycle (#14372, design §4.6): null + // until the receiving identity marks the note; null reads as + // "received". + if (!noteCols.some((c) => c.name === "work_state")) { + this.sql.exec("ALTER TABLE note_message ADD COLUMN work_state TEXT"); + } + if (!noteCols.some((c) => c.name === "work_task_id")) { + this.sql.exec("ALTER TABLE note_message ADD COLUMN work_task_id INTEGER"); + } } /** One fleet mailbox operation over arguments fleetCall validated. */ @@ -406,13 +415,31 @@ export class MessageStore extends DurableObject { noteInbox(identity) { return this.sql .exec( - "SELECT id, sender, body AS note, ts, kind, reply_to FROM note_message WHERE recipient = ? AND ack_at IS NULL ORDER BY id ASC", + "SELECT id, sender, body AS note, ts, kind, reply_to, work_state, work_task_id FROM note_message WHERE recipient = ? AND ack_at IS NULL ORDER BY id ASC", identity, ) .toArray() .map((r) => noteForInbox(r)); } + /** + * Work-item lifecycle (design §4.6): the receiving identity moves + * its own note forward; another identity's note is simply not + * found. State-dependent refusals come back as { error }, like the + * fleet ops (an InputError doesn't survive the RPC hop). + */ + noteWork(identity, { id, state, task_id }) { + const row = this.sql + .exec("SELECT id, work_state, work_task_id FROM note_message WHERE id = ? AND recipient = ?", id, identity) + .toArray()[0]; + if (!row) return { error: `note ${id} is not in ${identity}'s inbox` }; + const err = workTransitionError(row.work_state, state); + if (err) return { error: err }; + const taskId = task_id ?? row.work_task_id ?? null; + this.sql.exec("UPDATE note_message SET work_state = ?, work_task_id = ? WHERE id = ?", state, taskId, id); + return { id, work_state: state, work_task_id: taskId }; + } + noteAck(identity, { ids, up_to_id }) { const ts = new Date().toISOString(); let acked = 0; @@ -466,7 +493,7 @@ export class MessageStore extends DurableObject { const order = q.order === "desc" ? "DESC" : "ASC"; return this.sql .exec( - `SELECT id, ts, recipient, sender, body, ack_at FROM note_message WHERE ${where.join(" AND ")} ORDER BY id ${order} LIMIT ?`, + `SELECT id, ts, recipient, sender, body, ack_at, work_state, work_task_id FROM note_message WHERE ${where.join(" AND ")} ORDER BY id ${order} LIMIT ?`, ...args, q.limit ?? 50, ) @@ -679,6 +706,7 @@ function storeFor(env) { noteOrigin: (identity, id) => stub.noteOrigin(identity, id), noteInbox: (identity) => stub.noteInbox(identity), noteAck: (identity, sel) => stub.noteAck(identity, sel), + noteWork: (identity, mark) => stub.noteWork(identity, mark), noteSignal: (identity) => stub.noteSignal(identity), // Owner reads (pipeline.js): the query is validated in the Worker // by normalizePipelineQuery before these are called, like fleet. diff --git a/pkgs/message-bridge/worker/src/messages.js b/pkgs/message-bridge/worker/src/messages.js index a5a1e1a32..3104e1953 100644 --- a/pkgs/message-bridge/worker/src/messages.js +++ b/pkgs/message-bridge/worker/src/messages.js @@ -178,8 +178,8 @@ export const OAUTH_REG_PER_SOURCE = 10; * kind and reply_to ride along so a reply can thread onto the row * without naming its sender. */ -export function noteForInbox({ id, sender, note, ts, kind, reply_to }) { - return { id, from: kind === "instruction" ? null : sender, note, ts, kind, reply_to: reply_to ?? null }; +export function noteForInbox({ id, sender, note, ts, kind, reply_to, work_state = null, work_task_id = null }) { + return { id, from: kind === "instruction" ? null : sender, note, ts, kind, reply_to: reply_to ?? null, work_state, work_task_id }; } export class MemoryStore { @@ -342,7 +342,7 @@ export class MemoryStore { const notes = []; for (const recipient of recipients) { if (!this.noteCounters.has(recipient)) continue; - const row = { id: this.noteNextId++, ts: this.now(), recipient, from, note, ack_at: null, kind, reply_to, batch }; + const row = { id: this.noteNextId++, ts: this.now(), recipient, from, note, ack_at: null, kind, reply_to, batch, work_state: null, work_task_id: null }; this.noteRows.push(row); this.noteCounters.set(recipient, this.noteCounters.get(recipient) + 1); notes.push({ id: row.id, recipient, from, note, ts: row.ts, kind, reply_to, batch }); @@ -407,7 +407,19 @@ export class MemoryStore { async noteInbox(identity) { return this.noteRows .filter((r) => r.recipient === identity && r.ack_at === null) - .map((r) => noteForInbox({ id: r.id, sender: r.from, note: r.note, ts: r.ts, kind: r.kind, reply_to: r.reply_to })); + .map((r) => noteForInbox({ id: r.id, sender: r.from, note: r.note, ts: r.ts, kind: r.kind, reply_to: r.reply_to, work_state: r.work_state, work_task_id: r.work_task_id })); + } + // Work-item lifecycle (design §4.6): the receiving identity moves its + // own note forward; another identity's note is simply not found. + // State-dependent refusals come back as { error }, like the fleet ops. + async noteWork(identity, { id, state, task_id }) { + const row = this.noteRows.find((r) => r.id === id && r.recipient === identity); + if (!row) return { error: `note ${id} is not in ${identity}'s inbox` }; + const err = workTransitionError(row.work_state, state); + if (err) return { error: err }; + row.work_state = state; + row.work_task_id = task_id ?? row.work_task_id ?? null; + return { id: row.id, work_state: row.work_state, work_task_id: row.work_task_id }; } async noteAck(identity, { ids, up_to_id }) { const ts = this.now(); @@ -441,7 +453,7 @@ export class MemoryStore { rows = q.order === "desc" ? rows.slice().reverse() : rows; return rows .slice(0, q.limit ?? 50) - .map((r) => ({ id: r.id, ts: r.ts, recipient: r.recipient, sender: r.from, body: r.note, ack_at: r.ack_at })); + .map((r) => ({ id: r.id, ts: r.ts, recipient: r.recipient, sender: r.from, body: r.note, ack_at: r.ack_at, work_state: r.work_state, work_task_id: r.work_task_id })); } // Owner directory (pipeline.js): one row per registered identity, // scopes folded over its tokens (any token granting a scope grants @@ -597,6 +609,68 @@ export class MemoryStore { } } +/** + * The instruction work-item lifecycle (design §4.6, #14372), shared by + * the fleet and notes surfaces. A received instruction is a work item: + * the receiving agent records that it acted on it in-session (`acted`), + * queued it as a named fleet-queue task (`queued`, with the task id), + * and later that the work is finished (`done`). States move only + * forward — `received` -> `acted` | `queued` -> `done` — and re-marking + * the current state is a no-op, so a retry never fails. Rows store null + * until first marked; null reads as `received`. Only the receiving + * agent may move its own copy: the store ops scope every update to the + * caller's own mailbox/inbox, so another agent's row is simply not + * found. Connector-channel instructions carry no stored state in this + * build-out; the pipeline derives `received`/`acted` from read state. + */ +export const WORK_STATES = ["received", "acted", "queued", "done"]; +export const WORK_SETTABLE_STATES = ["acted", "queued", "done"]; + +/** The lifecycle state of a stored row: unmarked rows are at `received`. */ +export function workStateOf(row) { + return row?.work_state ?? "received"; +} + +/** + * Validates one work mark `{id, state, task_id?}` (the fleet verb body + * and the notes verb body share the shape); throws InputError. + * `queued` must name the queue task the instruction became. + */ +export function normalizeWorkMark(data) { + if (!data || typeof data !== "object" || Array.isArray(data)) throw new InputError("body must be a JSON object"); + if (!Number.isInteger(data.id) || data.id < 1) throw new InputError("id must be a positive integer"); + if (!WORK_SETTABLE_STATES.includes(data.state)) { + throw new InputError(`state must be one of ${WORK_SETTABLE_STATES.join(", ")}`); + } + const task_id = data.task_id === undefined || data.task_id === null ? null : data.task_id; + if (task_id !== null && (!Number.isInteger(task_id) || task_id < 1)) { + throw new InputError("task_id must be a positive integer"); + } + if (data.state === "queued" && task_id === null) { + throw new InputError("state queued needs task_id: the fleet queue task the instruction became"); + } + return { id: data.id, state: data.state, task_id }; +} + +/** + * The forward-only rule: null when `next` may follow `current`, else + * the refusal text. The graph is exactly the design's: from `received` + * an instruction is acted on or queued; from either it completes to + * `done`. Sideways steps (acted <-> queued), skipping the middle + * (received -> done) and every backward step are refused; re-marking + * the current state is a no-op, so a retry never fails. + */ +export function workTransitionError(current, next) { + const cur = current ?? "received"; + if (next === cur) return null; + const forward = + (cur === "received" && (next === "acted" || next === "queued")) || + ((cur === "acted" || cur === "queued") && next === "done"); + return forward + ? null + : `work_state moves only forward (received -> acted | queued -> done); ${cur} -> ${next} is not a step forward`; +} + /** Builds the id predicate for ack; throws InputError on bad input. */ export function ackSelector({ up_to_id, ids } = {}) { const hasUpTo = up_to_id !== undefined && up_to_id !== null; diff --git a/pkgs/message-bridge/worker/src/notes.js b/pkgs/message-bridge/worker/src/notes.js index 1b24b8506..230202515 100644 --- a/pkgs/message-bridge/worker/src/notes.js +++ b/pkgs/message-bridge/worker/src/notes.js @@ -19,7 +19,7 @@ import { safeEqual, tokenConfigured } from "./auth.js"; import { randomBatch } from "./fleet.js"; import { GLOB_SEGMENT, globMatch, isGlob } from "./glob.js"; -import { InputError, MAX_BODY } from "./messages.js"; +import { InputError, MAX_BODY, normalizeWorkMark } from "./messages.js"; export const NOTE_SEGMENT = /^[a-z0-9][a-z0-9._-]{0,63}$/; const RESERVED_SIGNAL_CLASSES = new Set([ @@ -266,6 +266,10 @@ async function readJson(request) { * replace `to` * GET /notes/inbox identity token; pending notes for that identity * POST /notes/ack identity token; {id | ids | up_to_id} + * POST /notes/work identity token; {id, state, task_id?}: the + * work-item lifecycle of one of the identity's + * own notes (design §4.6) — state acted | + * queued | done, forward only from received * Returns null when the path is not this API's. */ export async function handleNotes(request, env, url, getStore) { @@ -353,6 +357,13 @@ export async function handleNotes(request, env, url, getStore) { if (!auth.can_inbox) return json({ error: "this token has no inbox" }, 403); return json(await store.noteAck(auth.identity, normalizeNoteAck(await readJson(request)))); } + if (what === "work") { + if (request.method !== "POST") return new Response("Method Not Allowed", { status: 405, headers: { allow: "POST" } }); + if (!auth.can_inbox) return json({ error: "this token has no inbox" }, 403); + const out = await store.noteWork(auth.identity, normalizeWorkMark(await readJson(request))); + if (out && typeof out.error === "string") throw new InputError(out.error); + return json(out); + } return notFound(); } catch (err) { if (err instanceof InputError) return json({ error: err.message }, 400); diff --git a/pkgs/message-bridge/worker/src/pipeline.js b/pkgs/message-bridge/worker/src/pipeline.js index d48711009..a1191b497 100644 --- a/pkgs/message-bridge/worker/src/pipeline.js +++ b/pkgs/message-bridge/worker/src/pipeline.js @@ -16,7 +16,8 @@ // GET /api//agents fleet registry + note identities // // Normalized row: {surface, id, batch, ts, kind, sender_addr, -// sender_label, receiver, direction, read_at, reply_to, body}. +// sender_label, receiver, direction, read_at, reply_to, body, +// work_state, work_task_id}. // surface "connector" | "fleet" | "notes" // kind the surface's own kind: connector rows are "message" | // "instruction", fleet rows "message" | "command", notes @@ -33,15 +34,25 @@ // batch today, so null (a batch filter therefore only // matches fleet rows) // reply_to the fleet row a reply answers; null elsewhere today +// work_state the instruction work-item lifecycle (design §4.6): +// fleet and notes rows carry the state the receiving +// agent recorded (unmarked reads as "received"); +// connector instructions derive it from read state +// (unread "received", read "acted" — they store no +// lifecycle fields in this build-out); null on rows +// that are not work items (outbound rows, plain +// connector messages) +// work_task_id the fleet-queue task a `queued` instruction became; +// null unless the receiving agent recorded one // // Filters: kind, sender, receiver, surface, batch, unread_only, -// since_id, before_id, limit, order. since_id/before_id are per-surface +// work_state, since_id, before_id, limit, order. since_id/before_id are per-surface // id cursors (each surface numbers its own rows), applied on every // surface the query touches. sender/receiver match an address or its // bare name: "felix", "agent:felix" and — for notes — "muse/felix" all // name the same sender as far as the owner is concerned. -import { InputError, MAX_LIMIT } from "./messages.js"; +import { InputError, MAX_LIMIT, WORK_STATES } from "./messages.js"; export const PIPELINE_SURFACES = ["connector", "fleet", "notes"]; export const PIPELINE_KINDS = ["message", "instruction", "command", "note"]; @@ -84,9 +95,14 @@ export function normalizePipelineQuery(q = {}) { } const order = q.order === undefined || q.order === null || q.order === "" ? "asc" : String(q.order).toLowerCase(); if (order !== "asc" && order !== "desc") throw new InputError("order must be asc or desc"); + const work_state = q.work_state === undefined || q.work_state === null || q.work_state === "" ? "all" : String(q.work_state).toLowerCase(); + if (work_state !== "all" && !WORK_STATES.includes(work_state)) { + throw new InputError(`work_state must be all or one of ${WORK_STATES.join(", ")}`); + } return { surface, kind, + work_state, sender: textFilter(q.sender, "sender"), receiver: textFilter(q.receiver, "receiver"), batch: textFilter(q.batch, "batch", { lower: false }), @@ -147,6 +163,10 @@ export function projectConnector(m) { direction: m.direction, read_at: m.read_at ?? null, reply_to: null, + // Connector instructions store no lifecycle fields (§4.6): read + // state stands in — unread is `received`, read is `acted`. + work_state: inbound && m.kind === "instruction" ? (m.read_at ? "acted" : "received") : null, + work_task_id: null, body: m.body, channel: m.channel, }; @@ -166,6 +186,8 @@ export function projectFleet(m) { direction: m.direction, read_at: m.read_at ?? null, reply_to: m.reply_to ?? null, + work_state: inbound ? (m.work_state ?? "received") : null, + work_task_id: inbound ? (m.work_task_id ?? null) : null, body: m.body, agent: m.agent, }; @@ -184,6 +206,8 @@ export function projectNote(r) { direction: "inbound", read_at: r.ack_at ?? null, reply_to: null, + work_state: r.work_state ?? "received", + work_task_id: r.work_task_id ?? null, body: r.body, }; } @@ -192,6 +216,7 @@ export function projectNote(r) { function matches(e, q) { if (q.kind !== "all" && e.kind !== q.kind) return false; + if (q.work_state !== "all" && e.work_state !== q.work_state) return false; if (q.batch !== null && e.batch !== q.batch) return false; if (q.unread_only && !(e.direction === "inbound" && e.read_at === null)) return false; if (!addressMatches(q.sender, e.sender_addr, e.sender_label)) return false; @@ -230,7 +255,7 @@ function identityFilter(v) { */ export async function pipelineFeed(store, rawQuery = {}) { const q = normalizePipelineQuery(rawQuery); - const fetchLimit = q.sender || q.receiver || q.batch ? MAX_LIMIT : q.limit; + const fetchLimit = q.sender || q.receiver || q.batch || q.work_state !== "all" ? MAX_LIMIT : q.limit; const want = (s) => q.surface === "all" || q.surface === s; const kindFor = (...kinds) => q.kind === "all" || kinds.includes(q.kind); const entries = []; @@ -296,8 +321,9 @@ export async function notesOwnerFeed(store, rawQuery = {}) { }); const notes = rows .filter((r) => addressMatches(q.sender, r.sender) && addressMatches(q.receiver, r.recipient)) + .filter((r) => q.work_state === "all" || (r.work_state ?? "received") === q.work_state) .slice(0, q.limit) - .map((r) => ({ id: r.id, ts: r.ts, recipient: r.recipient, sender: r.sender, body: r.body, ack_at: r.ack_at ?? null })); + .map((r) => ({ id: r.id, ts: r.ts, recipient: r.recipient, sender: r.sender, body: r.body, ack_at: r.ack_at ?? null, work_state: r.work_state ?? null, work_task_id: r.work_task_id ?? null })); return { notes }; } diff --git a/pkgs/message-bridge/worker/test/work.test.mjs b/pkgs/message-bridge/worker/test/work.test.mjs new file mode 100644 index 000000000..c8a16724e --- /dev/null +++ b/pkgs/message-bridge/worker/test/work.test.mjs @@ -0,0 +1,276 @@ +// The instruction work-item lifecycle (src/fleet.js, src/notes.js, +// src/pipeline.js; design §4.6, #14372): a received instruction is a +// work item whose state the RECEIVING agent records — acted in-session, +// queued as a named fleet-queue task, then done — forward only, on its +// own copy only. Routed end to end through route(), with the real +// fleetOp SQL on node:sqlite and MemoryStore for the connector and +// notes surfaces — the same harness shape as pipeline.test.mjs and +// credentials.test.mjs. All token values are fixtures or Worker-minted +// inside the test; nothing here is a real credential. +// +// Oracles (named for the acceptance criteria): +// - an instruction's lifecycle is settable only by its receiving agent, +// and only forward through the states; +// - the owner pipeline shows an instruction at `queued` with its queue +// task id, and at `done` after the agent reports done; +// - group recipients carry independent lifecycles on the same batch; +// - connector instructions join at received/acted via read state. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { DatabaseSync } from "node:sqlite"; +import { fleetCall, fleetOp, fleetSchema, fleetToken } from "../src/fleet.js"; +import { MemoryStore } from "../src/messages.js"; +import { route } from "../src/routes.js"; + +const TOKEN = "o".repeat(20) + "0123456789abcdefXYZ_-"; +const CHATGPT = "c".repeat(40); +const DREW = "d".repeat(40); +const FELIX = "f".repeat(40); +const ARCHER = "a".repeat(40); +const env = { ACCESS_TOKEN: TOKEN, CHATGPT_TOKEN: CHATGPT }; +const BASE = "https://bridge.example"; + +/** The Durable Object's sql.exec over node:sqlite. */ +function sqlite() { + const db = new DatabaseSync(":memory:"); + return { + exec(q, ...args) { + const out = db.prepare(q).all(...args); + return { toArray: () => out, one: () => out[0] }; + }, + }; +} + +async function harness() { + const sql = sqlite(); + fleetSchema(sql); + let clock = 0; + const stub = { + fleet: (op, args) => fleetOp(sql, op, args, `2026-11-24T00:00:${String(clock++).padStart(2, "0")}Z`), + }; + const store = new MemoryStore(() => "2026-11-24T00:00:00.000Z"); + store.fleet = (op, args) => fleetCall(stub, op, args); + const call = (path, init) => route(new Request(BASE + path, init), env, () => store); + const post = (path, body, headers = {}) => + call(path, { method: "POST", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify(body) }); + const bearer = (token) => ({ authorization: `Bearer ${token}` }); + const ft = await fleetToken(env); + /** Mints and exchanges a bootstrap token; returns the agent's fleet credential. */ + const enroll = async (agent) => { + const mint = await post(`/api/${TOKEN}/enroll-tokens`, { agent, kind: "muse", groups: ["muse"] }); + assert.equal(mint.status, 201); + const { bootstrap_token } = await mint.json(); + const ex = await post(`/enroll/exchange`, { bootstrap_token, agent }); + assert.equal(ex.status, 201); + return (await ex.json()).fleet_token; + }; + return { + store, + ft, + enroll, + pipeline: (qs = {}) => call(`/api/${TOKEN}/pipeline?${new URLSearchParams(qs)}`), + register: (identity, token, extra = {}) => post("/notes/register", { identity, token, ...extra }, bearer(TOKEN)), + noteSend: (token, to, note) => post("/notes/send", { to, note }, bearer(token)), + noteWork: (token, body) => post("/notes/work", body, bearer(token)), + fleetHello: (body) => post(`/fleet/${ft}/hello`, body), + fleetInbox: (qs) => call(`/fleet/${ft}/inbox?${new URLSearchParams(qs)}`), + fleetWork: (body) => post(`/fleet/${ft}/work`, body), + credWork: (cred, body) => post(`/fleet/${cred}/work`, body), + ownerFleetSend: (body) => post(`/api/${TOKEN}/fleet/send`, body), + ownerSend: (body) => post(`/api/${TOKEN}/messages`, body), + }; +} + +async function pipelineRow(h, body) { + const res = await h.pipeline({ limit: "200" }); + assert.equal(res.status, 200); + const { messages } = await res.json(); + return messages.find((m) => m.body === body); +} + +test("work: a fleet instruction moves received -> queued (with its task id) -> done, and the pipeline shows each step", async () => { + const h = await harness(); + await h.fleetHello({ agent: "felix", groups: ["muse"] }); + const sent = await (await h.ownerFleetSend({ body: "do the thing", to: "agent:felix", kind: "command" })).json(); + const id = sent.messages[0].id; + + // Unmarked, the pipeline reads the row as received, with no task. + let row = await pipelineRow(h, "do the thing"); + assert.equal(row.surface, "fleet"); + assert.equal(row.work_state, "received"); + assert.equal(row.work_task_id, null); + + // The receiving agent queues it, naming the queue task it became. + const marked = await h.fleetWork({ agent: "felix", id, state: "queued", task_id: 23500 }); + assert.equal(marked.status, 200); + const markedBody = await marked.json(); + assert.equal(markedBody.message.work_state, "queued"); + assert.equal(markedBody.message.work_task_id, 23500); + + row = await pipelineRow(h, "do the thing"); + assert.equal(row.work_state, "queued", "the owner pipeline shows the instruction at queued"); + assert.equal(row.work_task_id, 23500, "... with its queue task id"); + + // The work_state filter finds exactly the stuck/queued views. + const queued = await (await h.pipeline({ work_state: "queued" })).json(); + assert.deepEqual(queued.messages.map((m) => m.body), ["do the thing"]); + const stuck = await (await h.pipeline({ work_state: "received", surface: "fleet" })).json(); + assert.deepEqual(stuck.messages, []); + + // The agent's own inbox row carries the state it recorded. + const inbox = await (await h.fleetInbox({ agent: "felix", unread_only: "false" })).json(); + assert.equal(inbox.messages[0].work_state, "queued"); + assert.equal(inbox.messages[0].work_task_id, 23500); + + // Done, reported by the agent; the recorded task id survives. + const done = await h.fleetWork({ agent: "felix", id, state: "done" }); + assert.equal(done.status, 200); + row = await pipelineRow(h, "do the thing"); + assert.equal(row.work_state, "done", "the pipeline shows done after the agent reports done"); + assert.equal(row.work_task_id, 23500); +}); + +test("work: transitions move only forward (acted | queued -> done), and queued names its task", async () => { + const h = await harness(); + await h.fleetHello({ agent: "felix", groups: ["muse"] }); + const sent = await (await h.ownerFleetSend({ body: "forward only", to: "agent:felix", kind: "command" })).json(); + const id = sent.messages[0].id; + + // received -> done skips the middle: refused. + let res = await h.fleetWork({ agent: "felix", id, state: "done" }); + assert.equal(res.status, 400); + assert.match((await res.json()).error, /only forward/); + + // queued without the task it became: refused at validation. + res = await h.fleetWork({ agent: "felix", id, state: "queued" }); + assert.equal(res.status, 400); + assert.match((await res.json()).error, /task_id/); + + // acted, then sideways to queued: refused. Acted again: a no-op. + assert.equal((await h.fleetWork({ agent: "felix", id, state: "acted" })).status, 200); + res = await h.fleetWork({ agent: "felix", id, state: "queued", task_id: 1 }); + assert.equal(res.status, 400); + assert.match((await res.json()).error, /only forward/); + assert.equal((await h.fleetWork({ agent: "felix", id, state: "acted" })).status, 200, "re-marking the current state is a no-op"); + + // done, then anything else: refused. + assert.equal((await h.fleetWork({ agent: "felix", id, state: "done" })).status, 200); + res = await h.fleetWork({ agent: "felix", id, state: "acted" }); + assert.equal(res.status, 400); + + // A state outside the lifecycle: refused at validation. + res = await h.fleetWork({ agent: "felix", id, state: "received" }); + assert.equal(res.status, 400); +}); + +test("work: group recipients carry independent lifecycles on the same batch", async () => { + const h = await harness(); + await h.fleetHello({ agent: "felix", groups: ["muse"] }); + await h.fleetHello({ agent: "archer", groups: ["muse"] }); + const sent = await (await h.ownerFleetSend({ body: "group order", to: "group:muse", kind: "command" })).json(); + assert.equal(sent.messages.length, 2); + const batch = sent.messages[0].batch; + assert.ok(sent.messages.every((m) => m.batch === batch), "one send, one batch"); + const felixRow = sent.messages.find((m) => m.agent === "felix"); + const archerRow = sent.messages.find((m) => m.agent === "archer"); + + assert.equal((await h.fleetWork({ agent: "felix", id: felixRow.id, state: "queued", task_id: 42 })).status, 200); + + const res = await h.pipeline({ surface: "fleet", batch }); + const { messages } = await res.json(); + const byAgent = new Map(messages.map((m) => [m.agent, m])); + assert.equal(byAgent.get("felix").work_state, "queued"); + assert.equal(byAgent.get("felix").work_task_id, 42); + assert.equal(byAgent.get("archer").work_state, "received", "the other recipient's copy is unmoved"); + + // Archer's copy moves on its own track. + assert.equal((await h.fleetWork({ agent: "archer", id: archerRow.id, state: "acted" })).status, 200); + const after = await (await h.pipeline({ surface: "fleet", batch })).json(); + const afterByAgent = new Map(after.messages.map((m) => [m.agent, m])); + assert.equal(afterByAgent.get("archer").work_state, "acted"); + assert.equal(afterByAgent.get("felix").work_state, "queued"); +}); + +test("work: a credential marks only its own rows — cross-agent marking is a plain 404", async () => { + const h = await harness(); + const felixCred = await h.enroll("felix"); + const archerCred = await h.enroll("archer"); + const sent = await (await h.ownerFleetSend({ body: "for felix only", to: "agent:felix", kind: "command" })).json(); + const id = sent.messages[0].id; + + // Archer's credential naming felix: refused at the name check. + let res = await h.credWork(archerCred, { agent: "felix", id, state: "acted" }); + assert.equal(res.status, 404); + // Archer's credential naming itself but felix's row id: the row is + // not in archer's mailbox, and the refusal is the same plain 404. + res = await h.credWork(archerCred, { agent: "archer", id, state: "acted" }); + assert.equal(res.status, 404); + // Felix's row is unmoved by either attempt. + let row = await pipelineRow(h, "for felix only"); + assert.equal(row.work_state, "received"); + + // Felix's own credential marks it — no owner token involved. + res = await h.credWork(felixCred, { agent: "felix", id, state: "acted" }); + assert.equal(res.status, 200, await res.text().catch(() => "")); + row = await pipelineRow(h, "for felix only"); + assert.equal(row.work_state, "acted"); + + // On the shared-token path a missing row is the ordinary 400 refusal. + res = await h.fleetWork({ agent: "felix", id: 999999, state: "acted" }); + assert.equal(res.status, 400); +}); + +test("work: notes instructions reuse the lifecycle on the notes surface", async () => { + const h = await harness(); + await h.register("user/drew", DREW); + await h.register("muse/felix", FELIX); + await h.register("muse/archer", ARCHER); + const delivered = await (await h.noteSend(DREW, "muse/felix", "note instruction")).json(); + const id = delivered.notes[0].id; + + let row = await pipelineRow(h, "note instruction"); + assert.equal(row.surface, "notes"); + assert.equal(row.work_state, "received"); + assert.equal(row.work_task_id, null); + + // Another identity cannot move felix's note, and learns nothing. + const cross = await h.noteWork(ARCHER, { id, state: "acted" }); + assert.equal(cross.status, 400); + assert.match((await cross.json()).error, /not in muse\/archer's inbox/); + row = await pipelineRow(h, "note instruction"); + assert.equal(row.work_state, "received", "the cross-identity attempt changed nothing"); + + // The receiving identity queues it with its task id, then finishes. + const marked = await h.noteWork(FELIX, { id, state: "queued", task_id: 777 }); + assert.equal(marked.status, 200); + assert.deepEqual(await marked.json(), { id, work_state: "queued", work_task_id: 777 }); + row = await pipelineRow(h, "note instruction"); + assert.equal(row.work_state, "queued"); + assert.equal(row.work_task_id, 777); + + assert.equal((await h.noteWork(FELIX, { id, state: "done" })).status, 200); + const backward = await h.noteWork(FELIX, { id, state: "acted" }); + assert.equal(backward.status, 400, "done -> acted is a backward step"); + row = await pipelineRow(h, "note instruction"); + assert.equal(row.work_state, "done"); +}); + +test("work: connector instructions join at received/acted through read state alone", async () => { + const h = await harness(); + await h.ownerSend({ body: "connector instruction", sender: "drew", to: "claude", kind: "instruction" }); + await h.ownerSend({ body: "connector message", sender: "drew", to: "claude", kind: "message" }); + + let row = await pipelineRow(h, "connector instruction"); + assert.equal(row.surface, "connector"); + assert.equal(row.work_state, "received", "unread connector instruction reads as received"); + assert.equal(row.work_task_id, null); + row = await pipelineRow(h, "connector message"); + assert.equal(row.work_state, null, "a plain connector message is not a work item"); + + const { messages } = await (await h.pipeline({ surface: "connector" })).json(); + const instruction = messages.find((m) => m.body === "connector instruction"); + await h.store.ack({ ids: [instruction.id], channel: "claude" }); + + row = await pipelineRow(h, "connector instruction"); + assert.equal(row.work_state, "acted", "read state stands in for acted on the connector surface"); +});