From c819c4b0aa408c1befe5324fbd6d9964cfc52d6d Mon Sep 17 00:00:00 2001 From: felix Date: Tue, 24 Nov 2026 13:43:28 +0000 Subject: [PATCH] bridge: unified owner pipeline, notes owner read, unified agents list (#14369) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Design §4.3 (S2): GET /api//pipeline serves one normalized feed over connector messages, fleet messages and notes; GET /api//notes is the owner's first read over note_message; GET /api//agents merges the fleet registry with note identities, each row marked by surface (notes rows say presence none rather than inventing a last_seen). Read projections over the existing tables only — no rows copied, no store migration. Owner views show the real sender on every surface; recipient projections (forAgent, commandForAgent) are untouched. New store surface: noteOwnerList + noteDirectory on both the Durable Object (SQL) and MemoryStore. Tests: test/pipeline.test.mjs names the cross-surface oracles (one-query provenance, kind+sender and receiver filter composition, ack-state agreement, side-by-side agents, unchanged recipient stripping). --- pkgs/message-bridge/worker/README.md | 3 + pkgs/message-bridge/worker/src/index.js | 51 +++ pkgs/message-bridge/worker/src/messages.js | 32 ++ pkgs/message-bridge/worker/src/pipeline.js | 348 ++++++++++++++++++ pkgs/message-bridge/worker/src/routes.js | 23 ++ .../worker/test/pipeline.test.mjs | 281 ++++++++++++++ 6 files changed, 738 insertions(+) create mode 100644 pkgs/message-bridge/worker/src/pipeline.js create mode 100644 pkgs/message-bridge/worker/test/pipeline.test.mjs diff --git a/pkgs/message-bridge/worker/README.md b/pkgs/message-bridge/worker/README.md index 7a521f5d0d..1a1636a772 100644 --- a/pkgs/message-bridge/worker/README.md +++ b/pkgs/message-bridge/worker/README.md @@ -51,6 +51,9 @@ 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//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 | | `GET /api//event-subscriptions` | ChatGPT's live event subscriptions: id, channel, callback host, created, expires; never the callback path or secret | | `GET /api//wake-hooks` | Wake hooks: address, kind, host, whether a token is set, when added; never the token or the URL's path | diff --git a/pkgs/message-bridge/worker/src/index.js b/pkgs/message-bridge/worker/src/index.js index a5899d9a70..78a30afc07 100644 --- a/pkgs/message-bridge/worker/src/index.js +++ b/pkgs/message-bridge/worker/src/index.js @@ -274,6 +274,53 @@ export class MessageStore extends DurableObject { return row ? { registered: true, counter: row.signal_counter } : { registered: false, counter: 0 }; } + /** Owner read over note_message (pipeline.js); sender/receiver are exact identities. */ + noteOwnerList(q = {}) { + const where = ["id > ?"]; + const args = [q.since_id ?? 0]; + if (q.before_id !== undefined && q.before_id !== null) { + where.push("id < ?"); + args.push(q.before_id); + } + if (q.unread_only) where.push("ack_at IS NULL"); + if (q.sender) { + where.push("sender = ?"); + args.push(q.sender); + } + if (q.receiver) { + where.push("recipient = ?"); + args.push(q.receiver); + } + 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 ?`, + ...args, + q.limit ?? 50, + ) + .toArray() + .map((r) => ({ ...r })); + } + + /** Owner directory of note identities (pipeline.js): scopes folded over each identity's tokens. */ + noteDirectory() { + return this.sql + .exec( + `SELECT i.identity AS identity, i.signal_counter AS signal_counter, i.created AS created, + COALESCE(MAX(t.can_send), 0) AS can_send, COALESCE(MAX(t.can_inbox), 0) AS can_inbox + FROM note_identity i LEFT JOIN note_token t ON t.identity = i.identity + GROUP BY i.identity ORDER BY i.identity`, + ) + .toArray() + .map((r) => ({ + identity: r.identity, + can_send: !!r.can_send, + can_inbox: !!r.can_inbox, + signal_counter: r.signal_counter, + created: r.created, + })); + } + eventSubGet(id) { const row = this.sql.exec("SELECT data FROM event_sub WHERE id = ?", id).toArray()[0]; return row ? JSON.parse(row.data) : null; @@ -458,6 +505,10 @@ function storeFor(env) { noteInbox: (identity) => stub.noteInbox(identity), noteAck: (identity, sel) => stub.noteAck(identity, sel), noteSignal: (identity) => stub.noteSignal(identity), + // Owner reads (pipeline.js): the query is validated in the Worker + // by normalizePipelineQuery before these are called, like fleet. + noteOwnerList: (q) => stub.noteOwnerList(q), + noteDirectory: () => stub.noteDirectory(), fleet: (op, args) => fleetCall(stub, op, args), }; } diff --git a/pkgs/message-bridge/worker/src/messages.js b/pkgs/message-bridge/worker/src/messages.js index 3d4e99c0cd..3150b9115b 100644 --- a/pkgs/message-bridge/worker/src/messages.js +++ b/pkgs/message-bridge/worker/src/messages.js @@ -232,6 +232,38 @@ export class MemoryStore { ? { registered: true, counter: this.noteCounters.get(identity) } : { registered: false, counter: 0 }; } + // Owner reads (pipeline.js): every note row in the table's own shape + // ({id, ts, recipient, sender, body, ack_at}); sender/receiver here + // are exact identity matches, address matching lives in pipeline.js. + async noteOwnerList(q = {}) { + let rows = this.noteRows.filter( + (r) => + (q.since_id === undefined || q.since_id === null || r.id > q.since_id) && + (q.before_id === undefined || q.before_id === null || r.id < q.before_id) && + (!q.unread_only || r.ack_at === null) && + (!q.sender || r.from === q.sender) && + (!q.receiver || r.recipient === q.receiver), + ); + 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 })); + } + // Owner directory (pipeline.js): one row per registered identity, + // scopes folded over its tokens (any token granting a scope grants + // it), plus the wake-signal counter. + async noteDirectory() { + return [...this.noteCounters.keys()].sort().map((identity) => { + let can_send = false; + let can_inbox = false; + for (const t of this.noteTokens.values()) { + if (t.identity !== identity) continue; + can_send = can_send || !!t.can_send; + can_inbox = can_inbox || !!t.can_inbox; + } + return { identity, can_send, can_inbox, signal_counter: this.noteCounters.get(identity), created: null }; + }); + } // Wake hooks (wake.js), same semantics as the Durable Object. async wakeHookGet(address) { const h = this.hooks.get(address); diff --git a/pkgs/message-bridge/worker/src/pipeline.js b/pkgs/message-bridge/worker/src/pipeline.js new file mode 100644 index 0000000000..d487110094 --- /dev/null +++ b/pkgs/message-bridge/worker/src/pipeline.js @@ -0,0 +1,348 @@ +// The owner's unified pipeline (design §4.3): one read over the three +// messaging surfaces the store holds — connector messages, fleet +// mailboxes and class/name notes — plus the owner's first read over +// notes and a unified connected-agents list. +// +// These are read projections over the existing tables: no row is +// copied, and nothing here touches a recipient-side projection. The +// anonymity rule stays where it has always lived (messages.js +// forAgent, fleet.js commandForAgent): a recipient never sees who sent +// an instruction or command. Owner surfaces are the opposite — every +// row below carries the real sender, on every surface. +// +// Routes (owner token only, wired in routes.js): +// GET /api//pipeline the normalized feed (this file) +// GET /api//notes owner read over note_message +// 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}. +// surface "connector" | "fleet" | "notes" +// kind the surface's own kind: connector rows are "message" | +// "instruction", fleet rows "message" | "command", notes +// are "note" (notes gain a kind of their own in S4) +// sender_addr who sent it, as an address: a from_addr +// ("agent:", "channel:") when the row has +// one, "user:drew" for what central sent, a notes +// identity ("muse/archer") on the notes surface +// receiver the mirror image: "channel:" for a connector +// row addressed to that assistant, "agent:" for a +// fleet mailbox row, the identity for a note, and +// "user:drew" for rows sent back to the owner +// batch the fleet batch id; connector and note rows have no +// batch today, so null (a batch filter therefore only +// matches fleet rows) +// reply_to the fleet row a reply answers; null elsewhere today +// +// Filters: kind, sender, receiver, surface, batch, unread_only, +// 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"; + +export const PIPELINE_SURFACES = ["connector", "fleet", "notes"]; +export const PIPELINE_KINDS = ["message", "instruction", "command", "note"]; +const PIPELINE_DEFAULT_LIMIT = 50; +const OWNER_ADDR = "user:drew"; +const AGENT_NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/; + +function intFilter(v, name, { min = 0, dflt = null } = {}) { + if (v === undefined || v === null || v === "") return dflt; + const n = Number(v); + if (!Number.isInteger(n) || n < min) throw new InputError(`${name} must be an integer >= ${min}`); + return n; +} + +function boolFilter(v, name) { + if (v === undefined || v === null || v === "") return false; + if (v === true || v === "true" || v === "1") return true; + if (v === false || v === "false" || v === "0") return false; + throw new InputError(`${name} must be true or false`); +} + +function textFilter(v, name, { lower = true } = {}) { + if (v === undefined || v === null || v === "") return null; + if (typeof v !== "string") throw new InputError(`${name} must be a string`); + // Addresses are case-insensitive; a batch id is case-sensitive base64url. + const s = lower ? v.trim().toLowerCase() : v.trim(); + if (s.length > 200) throw new InputError(`${name} is too long`); + return s || null; +} + +/** Validates a pipeline/notes query; throws InputError. */ +export function normalizePipelineQuery(q = {}) { + const surface = q.surface === undefined || q.surface === null || q.surface === "" ? "all" : String(q.surface).toLowerCase(); + if (surface !== "all" && !PIPELINE_SURFACES.includes(surface)) { + throw new InputError(`surface must be all or one of ${PIPELINE_SURFACES.join(", ")}`); + } + const kind = q.kind === undefined || q.kind === null || q.kind === "" ? "all" : String(q.kind).toLowerCase(); + if (kind !== "all" && !PIPELINE_KINDS.includes(kind)) { + throw new InputError(`kind must be all or one of ${PIPELINE_KINDS.join(", ")}`); + } + 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"); + return { + surface, + kind, + sender: textFilter(q.sender, "sender"), + receiver: textFilter(q.receiver, "receiver"), + batch: textFilter(q.batch, "batch", { lower: false }), + unread_only: boolFilter(q.unread_only, "unread_only"), + since_id: intFilter(q.since_id, "since_id"), + before_id: intFilter(q.before_id, "before_id", { min: 1 }), + limit: Math.min(intFilter(q.limit, "limit", { min: 1, dflt: PIPELINE_DEFAULT_LIMIT }), MAX_LIMIT), + order, + }; +} + +/** The bare name of an address: "agent:felix" -> "felix", "muse/felix" -> "felix". */ +function bareName(addr) { + if (typeof addr !== "string") return null; + const s = addr.toLowerCase(); + if (s.includes(":")) return s.slice(s.indexOf(":") + 1); + if (s.includes("/")) return s.slice(s.lastIndexOf("/") + 1); + return s; +} + +/** + * True when a sender/receiver filter names this address (or label). + * A bare name ("felix") matches every surface's spelling of it + * ("agent:felix", "muse/felix"); a full notes identity ("muse/felix") + * is exact — it does not also mean the fleet agent of that name, and + * an "agent:"/"channel:" filter never bare-matches an identity. + */ +export function addressMatches(filter, addr, label = null) { + if (!filter) return true; + const f = filter.toLowerCase(); + for (const cand of [addr, label]) { + if (typeof cand !== "string" || cand === "") continue; + const c = cand.toLowerCase(); + if (c === f) return true; + if (f.includes("/")) continue; // an identity filter is exact only + if (c.includes("/")) { + if (!f.includes(":") && bareName(c) === bareName(f)) return true; + continue; + } + if (bareName(c) === f || bareName(f) === c || bareName(c) === bareName(f)) return true; + } + return false; +} + +// ---- row projections (owner view: the real sender, always) ---- + +export function projectConnector(m) { + const inbound = m.direction === "inbound"; + return { + surface: "connector", + id: m.id, + batch: null, + ts: m.ts, + kind: m.kind, + sender_addr: m.from_addr ?? (inbound ? OWNER_ADDR : `channel:${m.channel}`), + sender_label: m.sender ?? null, + receiver: inbound ? `channel:${m.channel}` : OWNER_ADDR, + direction: m.direction, + read_at: m.read_at ?? null, + reply_to: null, + body: m.body, + channel: m.channel, + }; +} + +export function projectFleet(m) { + const inbound = m.direction === "inbound"; + return { + surface: "fleet", + id: m.id, + batch: m.batch ?? null, + ts: m.ts, + kind: m.kind, + sender_addr: inbound ? (m.from_addr ?? OWNER_ADDR) : `agent:${m.agent}`, + sender_label: m.sender ?? null, + receiver: inbound ? `agent:${m.agent}` : OWNER_ADDR, + direction: m.direction, + read_at: m.read_at ?? null, + reply_to: m.reply_to ?? null, + body: m.body, + agent: m.agent, + }; +} + +export function projectNote(r) { + return { + surface: "notes", + id: r.id, + batch: null, + ts: r.ts, + kind: "note", + sender_addr: r.sender, + sender_label: r.sender, + receiver: r.recipient, + direction: "inbound", + read_at: r.ack_at ?? null, + reply_to: null, + body: r.body, + }; +} + +// ---- the feed ---- + +function matches(e, q) { + if (q.kind !== "all" && e.kind !== q.kind) 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; + if (!addressMatches(q.receiver, e.receiver)) return false; + return true; +} + +function byTime(order) { + const dir = order === "desc" ? -1 : 1; + return (a, b) => { + if (a.ts !== b.ts) return (a.ts < b.ts ? -1 : 1) * dir; + if (a.surface !== b.surface) return (a.surface < b.surface ? -1 : 1) * dir; + return (a.id - b.id) * dir; + }; +} + +/** A receiver filter that names one fleet agent, for pushing the fleet read down. */ +function fleetAgentFilter(receiver) { + if (!receiver) return null; + const name = receiver.startsWith("agent:") ? receiver.slice("agent:".length) : receiver; + return AGENT_NAME.test(name) ? name : null; +} + +/** An exact notes identity filter (class/name), the only form pushed into the notes read. */ +function identityFilter(v) { + return v && v.includes("/") ? v : null; +} + +/** + * The unified feed. Each surface contributes its newest `limit` rows + * under the pushed-down filters (id cursors, kind, unread); the merge + * then applies the address/batch filters, sorts by ts and takes the + * page. When an address or batch filter is present the per-surface + * fetch widens to MAX_LIMIT, since those filters only apply after + * projection. + */ +export async function pipelineFeed(store, rawQuery = {}) { + const q = normalizePipelineQuery(rawQuery); + const fetchLimit = q.sender || q.receiver || q.batch ? 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 = []; + if (want("connector") && kindFor("message", "instruction")) { + const { messages } = await store.list({ + direction: "all", + kind: q.kind === "all" ? undefined : q.kind, + since_id: q.since_id ?? undefined, + before_id: q.before_id ?? undefined, + unread_only: q.unread_only, + limit: fetchLimit, + order: q.order, + }); + entries.push(...messages.map(projectConnector)); + } + if (want("fleet") && kindFor("message", "command") && typeof store.fleet === "function") { + const out = await store.fleet("messages", { + agent: fleetAgentFilter(q.receiver), + direction: "all", + kind: q.kind === "all" ? "all" : q.kind, + since_id: q.since_id ?? 0, + before_id: q.before_id, + limit: fetchLimit, + order: q.order, + }); + entries.push(...out.messages.map(projectFleet)); + } + if (want("notes") && kindFor("note") && typeof store.noteOwnerList === "function") { + const rows = await store.noteOwnerList({ + sender: identityFilter(q.sender), + receiver: identityFilter(q.receiver), + unread_only: q.unread_only, + since_id: q.since_id, + before_id: q.before_id, + limit: fetchLimit, + order: q.order, + }); + entries.push(...rows.map(projectNote)); + } + const messages = entries.filter((e) => matches(e, q)).sort(byTime(q.order)).slice(0, q.limit); + return { messages }; +} + +/** + * The owner's read over note_message (there was none: the owner could + * only look through an identity's own inbox). Same filters as the + * pipeline; rows come back in the table's own shape. A kind filter + * other than "note" matches nothing — every note is kind "note" until + * S4 gives notes kinds of their own. + */ +export async function notesOwnerFeed(store, rawQuery = {}) { + const q = normalizePipelineQuery(rawQuery); + if ((q.surface !== "all" && q.surface !== "notes") || (q.kind !== "all" && q.kind !== "note")) return { notes: [] }; + const fetchLimit = q.sender || q.receiver ? MAX_LIMIT : q.limit; + const rows = await store.noteOwnerList({ + sender: identityFilter(q.sender), + receiver: identityFilter(q.receiver), + unread_only: q.unread_only, + since_id: q.since_id, + before_id: q.before_id, + limit: fetchLimit, + order: q.order, + }); + const notes = rows + .filter((r) => addressMatches(q.sender, r.sender) && addressMatches(q.receiver, r.recipient)) + .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 })); + return { notes }; +} + +/** + * The unified connected-agents list: fleet registry rows (with unread + * counts) and note identities (with their token scopes), one row per + * surface registration, each marked by surface. Notes identities have + * no presence — the row says so (presence "none", last_seen null) + * rather than inventing one; their signal counter stands in as the + * only activity signal the surface keeps. + */ +export async function unifiedAgents(store) { + const agents = []; + if (typeof store.fleet === "function") { + const { agents: fleetAgents } = await store.fleet("agents", {}); + for (const a of fleetAgents) { + agents.push({ + surface: "fleet", + name: a.name, + groups: a.groups, + first_seen: a.first_seen, + last_seen: a.last_seen, + presence: "last_seen", + unread_commands: a.unread_commands, + unread_messages: a.unread_messages, + unread: (a.unread_commands ?? 0) + (a.unread_messages ?? 0), + inbound: a.inbound, + outbound: a.outbound, + }); + } + } + if (typeof store.noteDirectory === "function") { + for (const d of await store.noteDirectory()) { + agents.push({ + surface: "notes", + name: d.identity, + identity: d.identity, + scopes: { can_send: d.can_send, can_inbox: d.can_inbox }, + signal_counter: d.signal_counter, + first_seen: d.created ?? null, + last_seen: null, + presence: "none", + }); + } + } + agents.sort((a, b) => a.surface.localeCompare(b.surface) || a.name.localeCompare(b.name)); + return { agents }; +} diff --git a/pkgs/message-bridge/worker/src/routes.js b/pkgs/message-bridge/worker/src/routes.js index 7020fca956..8ba55cfec6 100644 --- a/pkgs/message-bridge/worker/src/routes.js +++ b/pkgs/message-bridge/worker/src/routes.js @@ -13,6 +13,16 @@ // GET /api//messages JSON history (direction, channel, // kind, since_id, before_id, unread_only, // limit, order) +// GET /api//pipeline one normalized feed over connector +// messages, fleet messages and notes +// (pipeline.js; kind, sender, receiver, +// surface, batch, unread_only, +// since_id, before_id, limit, order) +// GET /api//notes owner read over the notes table +// (pipeline.js; the same filters) +// GET /api//agents unified connected-agents list: +// fleet registry + note identities, +// each row marked by surface // POST /api//messages JSON {body, sender, to, kind}: store // an inbound message per recipient; to // is "claude" (default), "chatgpt" or @@ -59,6 +69,7 @@ import { InputError, normalizeKind, normalizeRecipients } from "./messages.js"; import { renderPage } from "./page.js"; import { normalizeHook, showHook, wakeAll, WAKE_ADDRESS } from "./wake.js"; import { handleNotes, handleSignal } from "./notes.js"; +import { notesOwnerFeed, pipelineFeed, unifiedAgents } from "./pipeline.js"; const MAX_FORM_BYTES = 64 * 1024; const PAGE_SIZE = 200; @@ -217,6 +228,18 @@ async function handleApi(request, store, rest, url, delivered) { } return new Response("Method Not Allowed", { status: 405, headers: { allow: "GET, POST" } }); } + if (what === "pipeline") { + if (request.method !== "GET") return new Response("Method Not Allowed", { status: 405, headers: { allow: "GET" } }); + return json(await pipelineFeed(store, Object.fromEntries(url.searchParams.entries()))); + } + if (what === "notes") { + if (request.method !== "GET") return new Response("Method Not Allowed", { status: 405, headers: { allow: "GET" } }); + return json(await notesOwnerFeed(store, Object.fromEntries(url.searchParams.entries()))); + } + if (what === "agents") { + if (request.method !== "GET") return new Response("Method Not Allowed", { status: 405, headers: { allow: "GET" } }); + return json(await unifiedAgents(store)); + } if (what === "oauth-events") { if (request.method !== "GET") return new Response("Method Not Allowed", { status: 405, headers: { allow: "GET" } }); return json({ events: await store.oauthEvents() }); diff --git a/pkgs/message-bridge/worker/test/pipeline.test.mjs b/pkgs/message-bridge/worker/test/pipeline.test.mjs new file mode 100644 index 0000000000..d22cd4ed79 --- /dev/null +++ b/pkgs/message-bridge/worker/test/pipeline.test.mjs @@ -0,0 +1,281 @@ +// The owner's unified pipeline (src/pipeline.js): one feed over +// connector messages, fleet mailboxes and notes, the owner's notes +// read, and the unified agents list. 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 +// fleet.test.mjs and notes.test.mjs. +// +// Oracles: the owner view is never sender-stripped (a fleet command, a +// connector instruction and a note show their real senders side by +// side), the cross-surface filters return exactly the matching rows, +// and the recipient-side projections (fleet commandForAgent via the +// agent inbox, messages.js forAgent) are unchanged. +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, forAgent } 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); + return { + store, + call, + ft, + pipeline: (qs = {}) => call(`/api/${TOKEN}/pipeline?${new URLSearchParams(qs)}`), + notesOwner: (qs = {}) => call(`/api/${TOKEN}/notes?${new URLSearchParams(qs)}`), + agents: () => call(`/api/${TOKEN}/agents`), + register: (identity, token, extra = {}) => + post("/notes/register", { identity, token, ...extra }, bearer(TOKEN)), + noteSend: (token, to, note) => post("/notes/send", { to, note }, bearer(token)), + noteAck: (token, body) => post("/notes/ack", body, bearer(token)), + fleetHello: (body) => post(`/fleet/${ft}/hello`, body), + fleetInbox: (qs) => call(`/fleet/${ft}/inbox?${new URLSearchParams(qs)}`), + fleetSend: (body) => post(`/fleet/${ft}/send`, body), + ownerFleetSend: (body) => post(`/api/${TOKEN}/fleet/send`, body), + ownerSend: (body) => post(`/api/${TOKEN}/messages`, body), + }; +} + +/** + * One of everything, across all three surfaces: + * - a fleet command from Drew to felix (batch B) + * - a fleet message from felix back to central (outbound post) + * - a connector instruction felix relayed to Claude (from_addr agent:felix) + * - a connector instruction Drew sent to Claude himself + * - a plain connector message to ChatGPT + * - a note from Drew to muse/felix, and one from muse/felix to muse/archer + */ +async function seeded() { + const h = await harness(); + await h.register("user/drew", DREW); + await h.register("muse/felix", FELIX); + await h.register("muse/archer", ARCHER, { can_send: false }); + await h.fleetHello({ agent: "felix", groups: ["muse"] }); + await h.fleetHello({ agent: "archer", groups: ["muse"] }); + + const cmd = await (await h.ownerFleetSend({ body: "fleet command body", to: "agent:felix", kind: "command", sender: "drew" })).json(); + assert.equal(cmd.messages.length, 1); + const batch = cmd.messages[0].batch; + assert.ok(batch); + + const relayed = await h.fleetSend({ agent: "felix", body: "agent instruction body", to: "claude", kind: "instruction" }); + assert.equal(relayed.status, 201, await relayed.text().catch(() => "")); + await h.fleetSend({ agent: "felix", body: "report to central", reply_to: cmd.messages[0].id }); + + await h.ownerSend({ body: "owner instruction body", sender: "drew", to: "claude", kind: "instruction" }); + await h.ownerSend({ body: "hello chatgpt", sender: "drew", to: "chatgpt", kind: "message" }); + + await h.noteSend(DREW, "muse/felix", "note for felix"); + await h.noteSend(FELIX, "muse/archer", "felix note to archer"); + return { ...h, batch }; +} + +test("pipeline: one query shows a fleet command, a connector instruction and a note, real senders on all three", async () => { + const { pipeline } = await seeded(); + const res = await pipeline({ limit: "200" }); + assert.equal(res.status, 200); + const { messages } = await res.json(); + const byBody = new Map(messages.map((m) => [m.body, m])); + + const cmd = byBody.get("fleet command body"); + assert.equal(cmd.surface, "fleet"); + assert.equal(cmd.kind, "command"); + assert.equal(cmd.sender_addr, "user:drew", "owner view: the command's real sender is shown"); + assert.equal(cmd.sender_label, "drew"); + assert.equal(cmd.receiver, "agent:felix"); + assert.equal(cmd.direction, "inbound"); + assert.ok(cmd.batch); + + const relayed = byBody.get("agent instruction body"); + assert.equal(relayed.surface, "connector"); + assert.equal(relayed.kind, "instruction"); + assert.equal(relayed.sender_addr, "agent:felix", "owner view: the instruction's real sender is shown"); + assert.equal(relayed.receiver, "channel:claude"); + + const own = byBody.get("owner instruction body"); + assert.equal(own.kind, "instruction"); + assert.equal(own.sender_addr, "user:drew"); + assert.equal(own.sender_label, "drew"); + + const note = byBody.get("note for felix"); + assert.equal(note.surface, "notes"); + assert.equal(note.kind, "note"); + assert.equal(note.sender_addr, "user/drew"); + assert.equal(note.receiver, "muse/felix"); + + const report = byBody.get("report to central"); + assert.equal(report.surface, "fleet"); + assert.equal(report.direction, "outbound"); + assert.equal(report.sender_addr, "agent:felix"); + assert.equal(report.receiver, "user:drew"); + assert.equal(report.reply_to, cmd.id, "the reply threads to the fleet row it answers (per-surface id)"); + + for (const m of messages) assert.ok(m.sender_addr, `no pipeline row is sender-stripped: ${JSON.stringify(m)}`); + const stamps = messages.map((m) => m.ts); + assert.deepEqual(stamps, [...stamps].sort(), "default order is oldest first across surfaces"); +}); + +test("pipeline filters compose across surfaces: kind+sender and receiver return exactly the matching rows", async () => { + const { pipeline, batch } = await seeded(); + + // Oracle 1: kind=instruction & sender=agent:felix — only the relayed + // connector instruction. The fleet command is kind "command" (the + // fleet spelling), Drew's instruction has another sender. + let rows = (await (await pipeline({ kind: "instruction", sender: "agent:felix" })).json()).messages; + assert.deepEqual(rows.map((m) => [m.surface, m.body]), [["connector", "agent instruction body"]]); + + // Oracle 2: receiver=felix — the fleet command (agent:felix) and the + // note (muse/felix), nothing else, on two surfaces. + rows = (await (await pipeline({ receiver: "felix" })).json()).messages; + assert.deepEqual( + rows.map((m) => [m.surface, m.body]).sort(), + [ + ["fleet", "fleet command body"], + ["notes", "note for felix"], + ], + ); + // The full identity form narrows the same filter to the note alone. + rows = (await (await pipeline({ receiver: "muse/felix" })).json()).messages; + assert.deepEqual(rows.map((m) => m.body), ["note for felix"]); + rows = (await (await pipeline({ receiver: "agent:felix" })).json()).messages; + assert.deepEqual(rows.map((m) => m.body), ["fleet command body"]); + + // Surface, kind and batch filters each stay inside their surface. + rows = (await (await pipeline({ surface: "notes" })).json()).messages; + assert.ok(rows.length === 2 && rows.every((m) => m.surface === "notes")); + rows = (await (await pipeline({ kind: "command" })).json()).messages; + assert.deepEqual(rows.map((m) => m.body), ["fleet command body"]); + rows = (await (await pipeline({ batch })).json()).messages; + assert.deepEqual(rows.map((m) => m.body).sort(), ["fleet command body", "report to central"]); + + // Sender in bare-name and identity forms names the same note sender. + rows = (await (await pipeline({ sender: "muse/felix" })).json()).messages; + assert.ok(rows.some((m) => m.body === "felix note to archer")); + assert.ok(rows.every((m) => m.sender_addr === "muse/felix" || m.sender_addr === "agent:felix")); +}); + +test("pipeline unread_only and the owner notes read share the ack state", async () => { + const h = await seeded(); + // Felix acks Drew's note through the identity API; the owner reads + // must agree it is read. + const inbox = await (await h.call("/notes/inbox", { headers: { authorization: `Bearer ${FELIX}` } })).json(); + assert.equal(inbox.notes.length, 1); + await h.noteAck(FELIX, { ids: [inbox.notes[0].id] }); + + const unread = (await (await h.pipeline({ unread_only: "true", limit: "200" })).json()).messages; + assert.ok(!unread.some((m) => m.body === "note for felix"), "acked note is not unread in the pipeline"); + assert.ok(unread.some((m) => m.body === "felix note to archer"), "unacked note is unread"); + assert.ok(unread.every((m) => m.direction === "inbound" && m.read_at === null)); + + const all = (await (await h.notesOwner({})).json()).notes; + assert.equal(all.length, 2); + const acked = all.find((n) => n.body === "note for felix"); + assert.equal(acked.sender, "user/drew"); + assert.equal(acked.recipient, "muse/felix"); + assert.ok(acked.ack_at, "owner read shows the ack the identity API recorded"); + + const onlyUnread = (await (await h.notesOwner({ unread_only: "true" })).json()).notes; + assert.deepEqual(onlyUnread.map((n) => n.body), ["felix note to archer"]); + const toArcher = (await (await h.notesOwner({ receiver: "muse/archer" })).json()).notes; + assert.deepEqual(toArcher.map((n) => [n.sender, n.body]), [["muse/felix", "felix note to archer"]]); + const fromDrew = (await (await h.notesOwner({ sender: "user/drew" })).json()).notes; + assert.deepEqual(fromDrew.map((n) => n.body), ["note for felix"]); + const none = (await (await h.notesOwner({ kind: "instruction" })).json()).notes; + assert.deepEqual(none, [], "notes are kind 'note' until S4; an instruction filter matches none"); +}); + +test("agents list: a fleet agent and a notes-only identity side by side, correctly surfaced", async () => { + const { agents } = await seeded(); + const res = await agents(); + assert.equal(res.status, 200); + const rows = (await res.json()).agents; + const byKey = new Map(rows.map((a) => [`${a.surface}:${a.name}`, a])); + + const fleetFelix = byKey.get("fleet:felix"); + assert.deepEqual(fleetFelix.groups, ["muse"]); + assert.ok(fleetFelix.first_seen && fleetFelix.last_seen, "fleet rows carry presence"); + assert.equal(fleetFelix.presence, "last_seen"); + assert.equal(fleetFelix.unread_commands, 0, "felix answered the command in the seed, so it is read"); + assert.ok(byKey.get("fleet:archer"), "the second fleet agent is listed"); + + const noteFelix = byKey.get("notes:muse/felix"); + assert.deepEqual(noteFelix.scopes, { can_send: true, can_inbox: true }); + assert.equal(noteFelix.presence, "none"); + assert.equal(noteFelix.last_seen, null, "notes identities have no presence; none is invented"); + assert.equal(noteFelix.signal_counter, 1, "one note delivered to muse/felix in the seed"); + + const noteArcher = byKey.get("notes:muse/archer"); + assert.deepEqual(noteArcher.scopes, { can_send: false, can_inbox: true }, "registration scopes are shown as registered"); + + const drew = byKey.get("notes:user/drew"); + assert.ok(drew, "a notes-only identity (no fleet mailbox) is in the same list"); + assert.equal(drew.surface, "notes"); +}); + +test("recipient projections are unchanged: no agent-facing response gains a sender", async () => { + const h = await seeded(); + // The fleet command reaches felix's inbox with no sender, exactly as + // before — while the pipeline test above shows the owner Drew's name. + const inbox = await (await h.fleetInbox({ agent: "archer", unread_only: "false" })).json(); + assert.equal(inbox.messages.length, 0); + const all = (await (await h.pipeline({ surface: "fleet", receiver: "felix" })).json()).messages; + assert.ok(all.length >= 1); + // A fresh command to archer, read through the agent route: + await h.ownerFleetSend({ body: "for archer", to: "agent:archer", kind: "command", sender: "drew" }); + const box = await (await h.fleetInbox({ agent: "archer" })).json(); + assert.equal(box.messages.length, 1); + assert.equal(box.messages[0].sender, null, "commandForAgent still strips the sender for the recipient"); + assert.equal(box.messages[0].from_addr, null); + // And the connector projection still strips an instruction's sender. + const stored = h.store.rows.find((r) => r.body === "agent instruction body"); + const seen = forAgent({ ...stored }); + assert.equal(seen.sender, undefined); + assert.equal(seen.from_addr, null); + assert.equal(stored.from_addr, "agent:felix", "the store row itself keeps the real sender"); +}); + +test("pipeline routes are owner-only and validate their filters", async () => { + const h = await seeded(); + for (const path of [`/api/nope/pipeline`, `/api/nope/notes`, `/api/nope/agents`, `/api/${h.ft}/pipeline`, `/api/${h.ft}/agents`]) { + assert.equal((await h.call(path)).status, 404, path); + } + assert.equal((await h.pipeline({ surface: "bogus" })).status, 400); + assert.equal((await h.pipeline({ kind: "bogus" })).status, 400); + assert.equal((await h.pipeline({ limit: "0" })).status, 400); + assert.equal((await h.pipeline({ order: "sideways" })).status, 400); + const post = await h.call(`/api/${TOKEN}/pipeline`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }); + assert.equal(post.status, 405); +});