Multiplayer agent harness for work.
Keep loop fires admitted through handover and repair inbox sync (#1473)
Regan Bell1a66338380c5
diff --git a/src/loops/inbox-loop.ts b/src/loops/inbox-loop.tsindex 977a090e8..3aaad9593 100644--- a/src/loops/inbox-loop.ts+++ b/src/loops/inbox-loop.ts@@ -7,7 +7,7 @@ const INBOX_LOOP_NAME = "Inbox";const INBOX_LOOP_SURFACE = "inbox";-export const INBOX_SYNC_TASK_VERSION = 3;+export const INBOX_SYNC_TASK_VERSION = 4;export const INBOX_SYNC_CRON_TITLE = "Inbox sync";@@ -23,7 +23,7 @@ const INBOX_SUCCESS_CONDITION =export function renderInboxSyncTask(loopId: string): string {return `Inbox sync v${INBOX_SYNC_TASK_VERSION}. Keep the user's QM inbox loop current: every Slack message and email genuinely WAITING ON A REPLY FROM THEM gets a ledger item with a ready-to-send draft in their own voice. The inbox UI is the only delivery surface — never message the user, and NEVER send a reply yourself; you produce drafts only.-1. GET $AGENT_API_URL/v1/loops/${loopId}/items (agent capability header) — note existing items: skip any dedupeKey already tracked unless a NEWER inbound message has arrived since (compare sourceAt); re-post such items with the fresh message and a fresh draft.+1. GET $AGENT_API_URL/v1/loops/${loopId}/items (agent capability header) — note existing items: skip complete items already tracked unless a NEWER inbound message has arrived since (compare sourceAt); re-post such items with the fresh message and a fresh draft. Refresh an agent draft when sourceAt is newer than proposal.at, even if the ledger already contains the latest message; realtime updates refresh message data before drafting. Preserve human-edited drafts. Repair incomplete open items first: an existing dedupeKey with missing sourcePayload, title, snippet, source metadata, or proposal is unfinished work, not a reason to skip it. Re-read its original conversation using the dedupeKey and summary, then ingest the complete item and draft under that same dedupeKey even when no newer message arrived. Never invent message content from a summary; if the source is unavailable, leave the item pending for retry.- Closed-loop detection: for every item still in state "held" or "pending", re-read its thread. If the LATEST message is FROM THE USER THEMSELVES — their own Slack userId on Slack, or their own email address in the From line on Gmail — they already replied outside QM, so POST $AGENT_API_URL/v1/loops/${loopId}/items/<itemId>/action with {"kind":"replied","args":{"text":"<their message, <=200 chars>"}} to close it. This applies to both Gmail and Slack items. Do NOT reopen or redraft an item the user has already answered.2. Keep a lastScanAt watermark in a state file on your workspace (e.g. ~/workspace/inbox-sync/STATE.md); scan each connected source since that watermark (fall back to ~3 days on first run), and advance the watermark only after a successful pass, so outages and missed fires backfill instead of leaving silent gaps. Skip a source whose app is not connected. Judge "waiting on a reply" like a good chief of staff, with a deliberate asymmetry: (a) NEEDS REPLY: direct questions, requests, intros, and personal messages that expect acknowledgment; when in any doubt, this bucket. (b) PROBABLY RESOLVED: the transcript reads closed (a thanks, a "sounds good", a thread someone else already answered) but a reasonable person might still send a word; post the item anyway with "probablyResolved": true in the item body and a draft included; the UI shows these in a muted section. NEVER silently drop a human conversation you judged resolved; demote it instead. (c) SKIP entirely: only unmistakable machine noise (newsletters, receipts, calendar notices, bot chatter). Human words never skip; the lowest they go is probablyResolved.- Gmail (use the google-workspace skill): INBOX threads where the LAST message is inbound and the user is in To or Cc. sourceKey = the Gmail threadId. Record gmail metadata: threadId, messageId, the RFC-2822 Message-ID header (rfcMessageId), subject, and the reply recipients (to = reply-all sender+others minus the user; cc as appropriate).diff --git a/src/loops/loop-fire.ts b/src/loops/loop-fire.tsindex d70e6c587..edd579414 100644--- a/src/loops/loop-fire.ts+++ b/src/loops/loop-fire.ts@@ -1,3 +1,5 @@+import { WorkAdmissionClosed, type AdmittedWork } from "../util/admitted-work.ts";+import { renderInboxSyncTask } from "./inbox-loop.ts";import { cronTriggerAuthority } from "../cron/authority.ts";import type { CronStore } from "../cron/cron-store.ts";import { boundLoopCron } from "./authority.ts";@@ -30,6 +32,7 @@ import { ledgerState } from "./ledger-view.ts";import { adapterForItem } from "./sources/index.ts";export interface LoopFireDeps {+ admittedWork?: AdmittedWork;loops: LoopStore;crons?: Pick<CronStore, "get">;samePerson?: (a: string, b: string) => Promise<boolean>;@@ -364,6 +367,7 @@ function shipPrompt(loop: Loop, output: LoopOutput, note?: string): string {}export function createLoopFireService(deps: LoopFireDeps): LoopFireService {+ const admitted = <T>(work: () => Promise<T>): Promise<T> => deps.admittedWork?.run(work) ?? work();async function stageTurn(loop: Loop,fireKey: string,@@ -461,6 +465,16 @@ export function createLoopFireService(deps: LoopFireDeps): LoopFireService {}async function fire(loopId: string, fireKey: string, cronId?: string): Promise<LoopFireResult> {+ try {+ const work = () => fireAdmitted(loopId, fireKey, cronId);+ return await admitted(work);+ } catch (error) {+ if (error instanceof WorkAdmissionClosed) return { status: "refused", note: error.message };+ throw error;+ }+ }++ async function fireAdmitted(loopId: string, fireKey: string, cronId?: string): Promise<LoopFireResult> {const loop = await deps.loops.get(loopId);if (!loop) return { status: "failed", note: "loop not found" };try {@@ -472,6 +486,20 @@ export function createLoopFireService(deps: LoopFireDeps): LoopFireService {return { status: "silent", note: "duplicate fire key" };}const threadRef = loopFireThreadRef(loopId, fireKey);+ if (loop.surface === "inbox") {+ if (!isRunnable(loop)) return { status: "silent", note: "loop is not runnable" };+ let failure: string | undefined;+ try {+ const outcome = await stageTurn(loop, `${fireKey}:sync`, threadRef, renderInboxSyncTask(loop.id));+ if (!outcome.ran && !outcome.authzFailed) return { status: "silent", note: "duplicate fire key" };+ failure = stageFailure("inbox sync", outcome)?.error.message;+ } catch (error) {+ failure = errMessage(error);+ }+ await deps.loops.recordFireOutcome(loopId, failure !== undefined);+ await applyGovernor(loopId);+ return failure !== undefined ? { status: "failed", note: failure } : { status: "silent" };+ }const maxAttempts = loop.caps?.maxItemAttempts ?? DEFAULT_MAX_ATTEMPTS;const grants = await deps.grants.byLoop(loopId);const workReplies = new Map<string, string>();@@ -720,5 +748,12 @@ export function createLoopFireService(deps: LoopFireDeps): LoopFireService {return itemTurn(loop, item, itemActionPrompt(loop, item, kind, args), fireKey, actorId);}- return { fire, shipOutput, returnOutput, sweepStale, followUp, itemAction };+ return {+ fire,+ shipOutput: (...args) => admitted(() => shipOutput(...args)),+ returnOutput,+ sweepStale,+ followUp: (...args) => admitted(() => followUp(...args)),+ itemAction: (...args) => admitted(() => itemAction(...args)),+ };}diff --git a/src/wiring.ts b/src/wiring.tsindex 4a4386250..de987eb31 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -2219,6 +2219,7 @@ export function buildApp(fireDropResolution({ deliveries, idempotency, identity, run: (req) => app.turn(req), directory }, drop): undefined;const loopFire: LoopFireService = createLoopFireService({+ admittedWork,crons,samePerson: (a, b) => app.samePerson(a, b),loops: loopStore,diff --git a/test/loop-fire.test.ts b/test/loop-fire.test.tsindex c8eca02cd..28298316b 100644--- a/test/loop-fire.test.ts+++ b/test/loop-fire.test.ts@@ -1,3 +1,5 @@+import { createAdmittedWork } from "../src/util/admitted-work.ts";+import { renderInboxSyncTask } from "../src/loops/inbox-loop.ts";import { createCronStore, type CreateCronInput } from "../src/cron/cron-store.ts";import { createScheduler } from "../src/cron/scheduler.ts";import assert from "node:assert/strict";@@ -36,6 +38,7 @@ type Responder = (req: TurnRequest) => string | Promise<string>;function service(respond: Responder,overrides?: {+ admittedWork?: ReturnType<typeof createAdmittedWork>;grants?: ReturnType<typeof createShipGrantStore>;samePerson?: (a: string, b: string) => Promise<boolean>;},@@ -49,6 +52,7 @@ function service(const turns: TurnRequest[] = [];const idempotency = createIdempotencyStore();const fire = createLoopFireService({+ admittedWork: overrides?.admittedWork,crons,samePerson: overrides?.samePerson,loops,@@ -60,8 +64,11 @@ function service(idempotency,identity: fakeIdentity() as never,run: async (req): Promise<TurnResult> => {- turns.push(req);- return { status: "ok", reply: await respond(req), sessionId: `s${turns.length}` };+ const run = async (): Promise<TurnResult> => {+ turns.push(req);+ return { status: "ok", reply: await respond(req), sessionId: `s${turns.length}` };+ };+ return overrides?.admittedWork ? overrides.admittedWork.run(run) : run();},},});@@ -668,7 +675,9 @@ test("legacy inbox sync cron is not a grant source for inbox event turns", asyncconst s = service(HAPPY);const loop = await makeLoop(s.loops, { surface: "inbox" });const cron = await bindCron(s, loop, { loopId: undefined, unattendedGrants: ["admin.sessions.read"] });- assert.equal((await s.fire.fire(loop.id, "slack-event")).status, "ok");+ assert.equal((await s.fire.fire(loop.id, "slack-event")).status, "silent");+ assert.equal(s.turns.length, 1);+ assert.equal(s.turns[0]?.text, renderInboxSyncTask(loop.id));assert.ok(s.turns.every((turn) => turn.unattendedGrants === undefined));assert.equal((await s.fire.fire(loop.id, "invalid-delegation", cron.id)).status, "failed");});@@ -730,3 +739,112 @@ test("privileged item turns recognize the owner's verified directory alias", asyassert.equal(refused.ok, false);assert.equal(s.turns.length, before);});++test("an admitted loop drains all stages after ownership closes", async () => {+ const admission = createAdmittedWork();+ let finishIntake!: () => void;+ let enteredIntake!: () => void;+ const started = new Promise<void>((resolve) => {+ enteredIntake = resolve;+ });+ const release = new Promise<void>((resolve) => {+ finishIntake = resolve;+ });+ const s = service(+ async (req) => {+ if (stage(req) === "intake") {+ enteredIntake();+ await release;+ }+ return HAPPY(req);+ },+ { admittedWork: admission },+ );+ const loop = await makeLoop(s.loops);+ const running = s.fire.fire(loop.id, "handover");+ await started;+ admission.pause();+ let drained = false;+ const drain = admission.drained().then(() => {+ drained = true;+ });+ await Promise.resolve();+ assert.equal(drained, false);+ const refused = await s.fire.fire(loop.id, "after-handover");+ assert.equal(refused.status, "refused");+ assert.equal((await s.loops.get(loop.id))?.consecutiveFailedFires ?? 0, 0);+ finishIntake();+ assert.equal((await running).status, "ok");+ await drain;+ assert.deepEqual(s.turns.map(stage), ["intake", "work", "judge"]);+ assert.equal((await s.outputs.awaitingReview(loop.id)).length, 1);+ assert.equal((await s.loops.get(loop.id))?.consecutiveFailedFires, 0);+});++test("inbox fires repair an existing shell without creating generic intake records", async () => {+ const s = service(async (req) => {+ assert.equal(req.text, renderInboxSyncTask(loop.id));+ await s.items.ingest([+ {+ loopId: loop.id,+ dedupeKey: "channel:123",+ source: "slack",+ sourceAt: 123,+ sourcePayload: {+ title: "#support",+ from: "Alex",+ snippet: "Can you help?",+ slack: { channelId: "channel", ts: "123" },+ },+ proposal: { by: "agent", data: { body: "Yes, I will take a look." } },+ },+ ]);+ return "Synced";+ });+ const loop = await makeLoop(s.loops, { surface: "inbox" });+ await s.items.enqueue({ loopId: loop.id, sourceKey: "channel:123", sourceSummary: "support request" });+ assert.equal((await s.fire.fire(loop.id, "sync-one")).status, "silent");+ assert.equal((await s.fire.fire(loop.id, "sync-one")).status, "silent");+ assert.equal(s.turns.length, 1);+ const rows = await s.items.byLoop(loop.id);+ assert.equal(rows.length, 1);+ assert.equal(rows[0]?.status, "ready");+ assert.equal(rows[0]?.sourcePayload?.title, "#support");+ assert.equal(rows[0]?.proposal?.data.body, "Yes, I will take a look.");+ assert.equal((await s.outputs.byLoop(loop.id)).length, 0);+});++test("closed admission leaves item follow-ups and ship attempts untouched", async () => {+ const admission = createAdmittedWork();+ const s = service(HAPPY, { admittedWork: admission });+ const loop = await makeLoop(s.loops);+ await s.fire.fire(loop.id, "first");+ const item = (await s.items.byLoop(loop.id))[0];+ const output = (await s.outputs.awaitingReview(loop.id))[0];+ assert.ok(item);+ assert.ok(output);+ admission.pause();+ await assert.rejects(s.fire.followUp(loop, item, "Please revise", loop.owner), /not accepting synchronous work/);+ await assert.rejects(s.fire.shipOutput(loop.id, output.id, loop.owner), /not accepting synchronous work/);+ await assert.rejects(s.fire.itemAction(loop, item, "revise", {}, loop.owner), /not accepting synchronous work/);+ assert.deepEqual(await s.items.get(item.id), item);+ assert.deepEqual(await s.outputs.get(output.id), output);+});++test("inbox sync exceptions count once and recover on a successful retry", async () => {+ let fail = true;+ const s = service(() => {+ if (fail) throw new Error("connector unavailable");+ return "Synced";+ });+ const loop = await makeLoop(s.loops, { surface: "inbox" });+ assert.equal((await s.fire.fire(loop.id, "broken")).status, "failed");+ assert.equal((await s.loops.get(loop.id))?.consecutiveFailedFires, 1);+ assert.equal((await s.items.byLoop(loop.id)).length, 0);+ fail = false;+ assert.equal((await s.fire.fire(loop.id, "recovery")).status, "silent");+ assert.equal((await s.loops.get(loop.id))?.consecutiveFailedFires, 0);+ await s.loops.setState(loop.id, "quarantined");+ assert.equal((await s.fire.fire(loop.id, "quarantined")).status, "silent");+ assert.equal(s.turns.length, 2);+});