Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

fix: preserve cron authority across native Loop stages (#1443)

Regan Bell8ac53f7a5233
diff --git a/src/api/control-service.ts b/src/api/control-service.ts
index 735f760ea..d68ec7470 100644
--- a/src/api/control-service.ts
+++ b/src/api/control-service.ts
@@ -1,3 +1,4 @@
+import { unattendedGrantRefusal } from "../cron/authority.ts";
import { isDeepStrictEqual } from "node:util";
import type { Cron, CronFireLogEntry, CronSchedule, Destination, Principal, Webhook } from "../types.ts";
import type { CreateCronInput, CronPatch } from "../cron/cron-store.ts";
@@ -325,21 +326,6 @@ function validateUnattendedGrants(grants: string[]): string | null {
return null;
}
-async function unattendedGrantRefusal(
- app: App,
- admin: AdminService | undefined,
- cron: Pick<Cron, "owner" | "ownerScopeId" | "runAs">,
- capability: CapabilityClaims,
-): Promise<string | null> {
- if (capability.liveActor !== true) return "unattended grants require a live turn started by the cron owner";
- if (!(await app.samePerson(cron.owner, capability.actorId))) return "only the cron owner may set unattended grants";
- if (!cron.ownerScopeId.startsWith("personal:") || (cron.runAs !== undefined && cron.runAs !== "owner"))
- return "unattended grants require a personal-scope cron that runs as its owner";
- const status = await admin?.adminStatusOf({ id: capability.actorId, type: "internal" }).catch(() => undefined);
- if (!status?.isAdmin) return "unattended grants require the cron owner to be a current org admin";
- return null;
-}
-
export function createControlService(app: App, scheduler?: Scheduler, admin?: AdminService): ControlService {
const notifyEdit = (
cron: Cron,
diff --git a/src/api/routes/loop-items.ts b/src/api/routes/loop-items.ts
index 31b28bd0c..b44cb1615 100644
--- a/src/api/routes/loop-items.ts
+++ b/src/api/routes/loop-items.ts
@@ -4,7 +4,7 @@ import { errMessage } from "../../util/errors.ts";
import { sendJson } from "../http.ts";
import { isObj } from "./shared.ts";
import { type ApiCtx, type Route } from "./route.ts";
-import { loadAdministrable, loopDeps, actingPrincipal, type LoopServiceDeps } from "./loops.ts";
+import { requireLoopAuthority, loadAdministrable, loopDeps, actingPrincipal, type LoopServiceDeps } from "./loops.ts";
import { parseScopeId } from "../../types.ts";
import { isLedgerState, ledgerItemView, ledgerState, sortLedgerItems } from "../../loops/ledger-view.ts";
import { loopItemId, type IngestEntryInput } from "../../loops/item-ledger.ts";
@@ -352,7 +352,8 @@ async function actOnItem(ctx: ApiCtx): Promise<void> {
}
if (!deps.fire) return sendJson(ctx.res, 404, { error: "not_found", message: "loop firing is not wired" });
- const turn = await deps.fire.itemAction(loop, item, kind, args);
+ if (!(await requireLoopAuthority(ctx, deps, loop))) return;
+ const turn = await deps.fire.itemAction(loop, item, kind, args, loaded.actorId);
if (!turn.ok) {
return sendJson(ctx.res, 502, { error: "action_failed", message: turn.userNote ?? "the agent turn did not run" });
}
@@ -369,6 +370,7 @@ async function followUpOnItem(ctx: ApiCtx): Promise<void> {
const loaded = await loadItem(ctx);
if (!loaded) return;
const { deps, loop, item } = loaded;
+ if (!(await requireLoopAuthority(ctx, deps, loop))) return;
const body = isObj(ctx.body) ? ctx.body : {};
const message = typeof body.message === "string" ? body.message.trim() : "";
if (!message) return sendJson(ctx.res, 400, { error: "bad_request", message: "message required" });
diff --git a/src/api/routes/loops.ts b/src/api/routes/loops.ts
index 5f2596b46..c6acac561 100644
--- a/src/api/routes/loops.ts
+++ b/src/api/routes/loops.ts
@@ -1,3 +1,5 @@
+import { boundLoopCron } from "../../loops/authority.ts";
+import { unattendedGrantRefusal } from "../../cron/authority.ts";
import type { Loop, LoopState } from "../../types.ts";
import { scopeId, type ScopeId } from "../../types.ts";
import type { CapabilityClaims } from "../../auth/capability-token.ts";
@@ -93,6 +95,24 @@ export async function loadAdministrable(
return { deps, loop, acting };
}
+export async function requireLoopAuthority(ctx: ApiCtx, deps: LoopServiceDeps, loop: Loop): Promise<boolean> {
+ let cron;
+ try {
+ cron = await boundLoopCron(loop, deps.crons);
+ } catch (e) {
+ sendJson(ctx.res, 409, { error: "authority_mismatch", message: errMessage(e) });
+ return false;
+ }
+ if (!cron?.unattendedGrants?.length) return true;
+ const principal = ctx.capability ?? (ctx.actor?.p ? { actorId: ctx.actor.p, liveActor: true } : undefined);
+ const refusal = principal
+ ? await unattendedGrantRefusal(ctx.app, ctx.deps.admin, cron, principal)
+ : "a privileged loop requires a live turn started by its owner";
+ if (!refusal) return true;
+ sendJson(ctx.res, 403, { error: "forbidden", message: refusal });
+ return false;
+}
+
const GATES = new Set(["auto", "hold"]);
function shipActionsFromBody(value: unknown): Loop["shipActions"] | null {
@@ -307,6 +327,7 @@ async function patchLoop(ctx: ApiCtx): Promise<void> {
const loaded = await loadAdministrable(ctx);
if (!loaded) return;
const { deps, loop, acting } = loaded;
+ if (!(await requireLoopAuthority(ctx, deps, loop))) return;
const b = isObj(ctx.body) ? ctx.body : {};
const patch: LoopPatch = {};
if (typeof b.playbook === "string" && b.playbook.trim()) {
@@ -426,6 +447,7 @@ async function fireLoopNow(ctx: ApiCtx): Promise<void> {
const loaded = await loadAdministrable(ctx);
if (!loaded) return;
const { deps, loop } = loaded;
+ if (!(await requireLoopAuthority(ctx, deps, loop))) return;
if (!deps.fire) return sendJson(ctx.res, 404, { error: "not_found", message: "loop firing is not wired" });
const fireKey = `loop:${loop.id}:manual:${Date.now()}`;
void deps.fire.fire(loop.id, fireKey).catch((e: unknown) => swallow(`manual fire of loop ${loop.id}`, e));
@@ -436,6 +458,7 @@ async function decideOutput(ctx: ApiCtx): Promise<void> {
const loaded = await loadAdministrable(ctx);
if (!loaded) return;
const { deps, loop, acting } = loaded;
+ if (!(await requireLoopAuthority(ctx, deps, loop))) return;
if (!requireLiveHuman(ctx, acting)) return;
if (!deps.fire) return sendJson(ctx.res, 404, { error: "not_found", message: "loop firing is not wired" });
const b = isObj(ctx.body) ? ctx.body : {};
@@ -471,6 +494,7 @@ async function graduateShipAction(ctx: ApiCtx): Promise<void> {
const loaded = await loadAdministrable(ctx);
if (!loaded) return;
const { deps, loop, acting } = loaded;
+ if (!(await requireLoopAuthority(ctx, deps, loop))) return;
if (!requireLiveHuman(ctx, acting)) return;
const b = isObj(ctx.body) ? ctx.body : {};
if (typeof b.shipAction !== "string" || !b.shipAction.trim())
@@ -499,6 +523,7 @@ async function setAutopilot(ctx: ApiCtx): Promise<void> {
const loaded = await loadAdministrable(ctx);
if (!loaded) return;
const { deps, loop, acting } = loaded;
+ if (!(await requireLoopAuthority(ctx, deps, loop))) return;
const b = isObj(ctx.body) ? ctx.body : {};
if (typeof b.enabled !== "boolean")
return sendJson(ctx.res, 400, { error: "bad_request", message: "enabled must be a boolean" });
diff --git a/src/cron/authority.ts b/src/cron/authority.ts
new file mode 100644
index 000000000..bb878b24e
--- /dev/null
+++ b/src/cron/authority.ts
@@ -0,0 +1,32 @@
+import type { Cron } from "../types.ts";
+import type { TriggerSpec } from "../triggers/run-trigger.ts";
+import type { CapabilityClaims } from "../auth/capability-token.ts";
+import type { App } from "../api/app.ts";
+import type { AdminService } from "../admin/admin-service.ts";
+
+type TriggerAuthority = Pick<TriggerSpec, "owner" | "ownerScopeId" | "runAs" | "unattendedGrants" | "members">;
+
+export function cronTriggerAuthority(cron: TriggerAuthority): TriggerAuthority {
+ return {
+ owner: cron.owner,
+ ownerScopeId: cron.ownerScopeId,
+ ...(cron.runAs ? { runAs: cron.runAs } : {}),
+ ...(cron.unattendedGrants ? { unattendedGrants: [...cron.unattendedGrants] } : {}),
+ ...(cron.members ? { members: cron.members } : {}),
+ };
+}
+
+export async function unattendedGrantRefusal(
+ app: App,
+ admin: AdminService | undefined,
+ cron: Pick<Cron, "owner" | "ownerScopeId" | "runAs">,
+ capability: Pick<CapabilityClaims, "actorId" | "liveActor">,
+): Promise<string | null> {
+ if (capability.liveActor !== true) return "unattended grants require a live turn started by the cron owner";
+ if (!(await app.samePerson(cron.owner, capability.actorId))) return "only the cron owner may set unattended grants";
+ if (!cron.ownerScopeId.startsWith("personal:") || (cron.runAs !== undefined && cron.runAs !== "owner"))
+ return "unattended grants require a personal-scope cron that runs as its owner";
+ const status = await admin?.adminStatusOf({ id: capability.actorId, type: "internal" }).catch(() => undefined);
+ if (!status?.isAdmin) return "unattended grants require the cron owner to be a current org admin";
+ return null;
+}
diff --git a/src/cron/scheduler.ts b/src/cron/scheduler.ts
index 58287143b..18d03a2ad 100644
--- a/src/cron/scheduler.ts
+++ b/src/cron/scheduler.ts
@@ -1,3 +1,4 @@
+import { cronTriggerAuthority } from "./authority.ts";
import { WorkAdmissionClosed, type AdmittedWork } from "../util/admitted-work.ts";
import { randomUUID } from "node:crypto";
import {
@@ -85,7 +86,11 @@ export interface SchedulerDeps {
jobQueue?: CronJobQueue;
requireQueueStart?: boolean;
sessions?: TriggerDeps["sessions"];
- fireLoop?: (loopId: string, fireKey: string) => Promise<{ status?: TurnResult["status"]; note?: string }>;
+ fireLoop?: (
+ loopId: string,
+ fireKey: string,
+ cronId: string,
+ ) => Promise<{ status?: TurnResult["status"]; note?: string }>;
}
function truncate(s: string, maxChars: number): string {
@@ -210,7 +215,7 @@ export function createScheduler(deps: SchedulerDeps): Scheduler {
result = { status: "failed", note: "loop service unavailable" };
} else
try {
- result = await deps.fireLoop(cron.loopId, fireKey);
+ result = await deps.fireLoop(cron.loopId, fireKey, cron.id);
} catch (e) {
result = { status: "failed", note: errMessage(e) };
}
@@ -240,8 +245,7 @@ export function createScheduler(deps: SchedulerDeps): Scheduler {
...(deps.sessions ? { sessions: deps.sessions } : {}),
},
{
- owner: cron.owner,
- ownerScopeId: cron.ownerScopeId,
+ ...cronTriggerAuthority(cron),
input: renderCronFireInput(cron, mentionRoster),
fireKey,
threadRef,
@@ -252,9 +256,6 @@ export function createScheduler(deps: SchedulerDeps): Scheduler {
},
...(cron.message !== undefined ? { message: cron.message } : {}),
...(cron.destination ? { destination: cron.destination } : {}),
- ...(cron.runAs ? { runAs: cron.runAs } : {}),
- ...(cron.unattendedGrants ? { unattendedGrants: cron.unattendedGrants } : {}),
- ...(cron.members ? { members: cron.members } : {}),
...(cron.recipientConsent ? { recipientConsent: cron.recipientConsent } : {}),
recipientConsentRequired: cron.schedule.everyMs !== undefined || cron.schedule.cron !== undefined,
deferWhenBusy: scheduledAt !== undefined && t - scheduledAt <= BUSY_DEFER_MAX_LATE_MS,
diff --git a/src/loops/authority.ts b/src/loops/authority.ts
new file mode 100644
index 000000000..273bcacc2
--- /dev/null
+++ b/src/loops/authority.ts
@@ -0,0 +1,26 @@
+import type { Cron, Loop } from "../types.ts";
+import type { CronStore } from "../cron/cron-store.ts";
+
+export async function boundLoopCron(
+ loop: Loop,
+ crons?: Pick<CronStore, "get">,
+ firingCronId?: string,
+): Promise<Cron | null> {
+ if (!loop.cronId) {
+ if (firingCronId) throw new Error("loop is not bound to the firing cron");
+ return null;
+ }
+ const cron = await crons?.get(loop.cronId);
+ if (
+ !cron ||
+ (firingCronId !== undefined && firingCronId !== cron.id) ||
+ cron.owner !== loop.owner ||
+ cron.ownerScopeId !== loop.ownerScopeId ||
+ (cron.runAs ?? "owner") !== (loop.runAs ?? "owner")
+ ) {
+ throw new Error("loop cron authority binding mismatch");
+ }
+ if (loop.surface === "inbox" && cron.loopId === undefined && firingCronId === undefined) return cron;
+ if (cron.loopId !== loop.id) throw new Error("loop cron authority binding mismatch");
+ return cron;
+}
diff --git a/src/loops/loop-fire.ts b/src/loops/loop-fire.ts
index bde3db431..d70e6c587 100644
--- a/src/loops/loop-fire.ts
+++ b/src/loops/loop-fire.ts
@@ -1,3 +1,7 @@
+import { cronTriggerAuthority } from "../cron/authority.ts";
+import type { CronStore } from "../cron/cron-store.ts";
+import { boundLoopCron } from "./authority.ts";
+import { samePerson } from "../directory/person.ts";
import type { Loop, LoopItem, LoopOutput, TurnResult } from "../types.ts";
import { runTrigger, type TriggerDeps, type TriggerOutcome } from "../triggers/run-trigger.ts";
import { reachEnqueue } from "../reach/reach.ts";
@@ -27,6 +31,8 @@ import { adapterForItem } from "./sources/index.ts";
export interface LoopFireDeps {
loops: LoopStore;
+ crons?: Pick<CronStore, "get">;
+ samePerson?: (a: string, b: string) => Promise<boolean>;
items: LoopItemLedger;
outputs: LoopOutputStore;
grants: ShipGrantStore;
@@ -48,9 +54,15 @@ interface ItemTurnResult {
}
export interface LoopFireService {
- fire(loopId: string, fireKey: string): Promise<LoopFireResult>;
+ fire(loopId: string, fireKey: string, cronId?: string): Promise<LoopFireResult>;
followUp(loop: Loop, item: LoopItem, message: string, actorId: string): Promise<LoopItem | null>;
- itemAction(loop: Loop, item: LoopItem, kind: string, args: Record<string, unknown>): Promise<ItemTurnResult>;
+ itemAction(
+ loop: Loop,
+ item: LoopItem,
+ kind: string,
+ args: Record<string, unknown>,
+ actorId: string,
+ ): Promise<ItemTurnResult>;
shipOutput(loopId: string, outputId: string, actorId: string, note?: string): Promise<LoopOutput | null>;
returnOutput(loopId: string, outputId: string, actorId: string, note: string): Promise<LoopOutput | null>;
sweepStale(now: number): Promise<void>;
@@ -352,15 +364,36 @@ function shipPrompt(loop: Loop, output: LoopOutput, note?: string): string {
}
export function createLoopFireService(deps: LoopFireDeps): LoopFireService {
- async function stageTurn(loop: Loop, fireKey: string, threadRef: string, input: string): Promise<TriggerOutcome> {
+ async function stageTurn(
+ loop: Loop,
+ fireKey: string,
+ threadRef: string,
+ input: string,
+ actorId?: string,
+ ): Promise<TriggerOutcome> {
+ let cron;
+ try {
+ const bound = await boundLoopCron(loop, deps.crons);
+ cron = bound?.loopId === loop.id ? bound : null;
+ } catch (e) {
+ return { authzFailed: true, ran: false, note: errMessage(e) };
+ }
+ if (cron?.unattendedGrants?.length && (!cron.enabled || cron.archived)) {
+ return { authzFailed: true, ran: false, note: "loop cron is disabled or archived" };
+ }
+ if (
+ cron?.unattendedGrants?.length &&
+ actorId !== undefined &&
+ !(await (deps.samePerson ?? samePerson)(cron.owner, actorId))
+ ) {
+ return { authzFailed: true, ran: false, note: "only the owner may direct a privileged loop turn" };
+ }
return runTrigger(deps.trigger, {
- owner: loop.owner,
- ownerScopeId: loop.ownerScopeId,
+ ...cronTriggerAuthority(cron ?? loop),
input,
fireKey,
threadRef,
surface: "loop",
- ...(loop.runAs ? { runAs: loop.runAs } : {}),
});
}
@@ -427,9 +460,14 @@ export function createLoopFireService(deps: LoopFireDeps): LoopFireService {
}
}
- async function fire(loopId: string, fireKey: string): Promise<LoopFireResult> {
+ async function fire(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 {
+ await boundLoopCron(loop, deps.crons, cronId);
+ } catch (e) {
+ return { status: "failed", note: errMessage(e) };
+ }
if (loop.state === "enabled" && (await deps.trigger.idempotency.committed(`${fireKey}:intake`))) {
return { status: "silent", note: "duplicate fire key" };
}
@@ -554,6 +592,7 @@ export function createLoopFireService(deps: LoopFireDeps): LoopFireService {
fireKey,
loopFireThreadRef(loopId, fireKey),
shipPrompt(loop, claimed, note),
+ actorId,
);
if (!outcome.ran && !outcome.authzFailed && (await deps.outputs.get(outputId))?.shipFireKey === fireKey) {
return deps.outputs.markUnconfirmed(outputId, claimToken);
@@ -624,8 +663,14 @@ export function createLoopFireService(deps: LoopFireDeps): LoopFireService {
}
}
- async function itemTurn(loop: Loop, item: LoopItem, input: string, fireKey: string): Promise<ItemTurnResult> {
- const outcome = await stageTurn(loop, fireKey, loopItemThreadRef(loop.id, item.id), input);
+ async function itemTurn(
+ loop: Loop,
+ item: LoopItem,
+ input: string,
+ fireKey: string,
+ actorId: string,
+ ): Promise<ItemTurnResult> {
+ const outcome = await stageTurn(loop, fireKey, loopItemThreadRef(loop.id, item.id), input, actorId);
const failure = stageFailure("item turn", outcome);
if (failure) return { ok: false, note: failure.error.message, userNote: failure.userMessage };
return {
@@ -639,7 +684,7 @@ export function createLoopFireService(deps: LoopFireDeps): LoopFireService {
await deps.items.appendThread(item.id, [{ role: "human", text: message, actorId }]);
const asked = (await deps.items.get(item.id)) ?? item;
const fireKey = `loop:${loop.id}:item:${item.id}:followup:${Date.now()}`;
- const turn = await itemTurn(loop, asked, followUpPrompt(loop, asked, message), fireKey);
+ const turn = await itemTurn(loop, asked, followUpPrompt(loop, asked, message), fireKey, actorId);
if (!turn.ok) {
await deps.items.appendThread(item.id, [
{ role: "system", text: `The agent could not answer: ${turn.userNote ?? "the turn did not run"}` },
@@ -669,9 +714,10 @@ export function createLoopFireService(deps: LoopFireDeps): LoopFireService {
item: LoopItem,
kind: string,
args: Record<string, unknown>,
+ actorId: string,
): Promise<ItemTurnResult> {
const fireKey = `loop:${loop.id}:item:${item.id}:action:${kind}:${Date.now()}`;
- return itemTurn(loop, item, itemActionPrompt(loop, item, kind, args), fireKey);
+ return itemTurn(loop, item, itemActionPrompt(loop, item, kind, args), fireKey, actorId);
}
return { fire, shipOutput, returnOutput, sweepStale, followUp, itemAction };
diff --git a/src/triggers/keychain-ask.ts b/src/triggers/keychain-ask.ts
index 50e9ebde3..74b0667dd 100644
--- a/src/triggers/keychain-ask.ts
+++ b/src/triggers/keychain-ask.ts
@@ -1,3 +1,4 @@
+import { cronTriggerAuthority } from "../cron/authority.ts";
import type { Keychain, KeychainAsk, KeychainGrant } from "../credentials/keychain.ts";
import type { AuditLog } from "../audit/audit-log.ts";
import type { Cron, Destination, ScopeId } from "../types.ts";
@@ -73,17 +74,13 @@ export async function fireAskResolution(
}
const destination = cron ? cron.destination : ask.requesterDestination;
const outcome = await runTrigger(deps, {
- owner: cron?.owner ?? ask.requesterId,
- ownerScopeId: ask.requesterScopeId,
+ ...cronTriggerAuthority(cron ?? { owner: ask.requesterId, ownerScopeId: ask.requesterScopeId }),
input: resolutionInput(ask, grant),
fireKey: `ask:${ask.id}:${ask.status}`,
surface: "keychain-ask",
deferWhenBusy: true,
...(cron
? {
- ...(cron.runAs ? { runAs: cron.runAs } : {}),
- ...(cron.members ? { members: cron.members } : {}),
- ...(cron.unattendedGrants ? { unattendedGrants: cron.unattendedGrants } : {}),
...(cron.recipientConsent ? { recipientConsent: cron.recipientConsent } : {}),
recipientConsentRequired: cron.schedule.everyMs !== undefined || cron.schedule.cron !== undefined,
}
diff --git a/src/wiring.ts b/src/wiring.ts
index 05167f29c..ecf2dab03 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -2210,6 +2210,8 @@ export function buildApp(
fireDropResolution({ deliveries, idempotency, identity, run: (req) => app.turn(req), directory }, drop)
: undefined;
const loopFire: LoopFireService = createLoopFireService({
+ crons,
+ samePerson: (a, b) => app.samePerson(a, b),
loops: loopStore,
items: loopItems,
outputs: loopOutputs,
@@ -2247,7 +2249,7 @@ export function buildApp(
directory,
currentScopeMembers,
sessions,
- fireLoop: (loopId, fireKey) => loopFire.fire(loopId, fireKey),
+ fireLoop: (loopId, fireKey, cronId) => loopFire.fire(loopId, fireKey, cronId),
...(config.databaseUrl
? { jobQueue: createPgBossCronQueue(config.databaseUrl, undefined, config.cronFireConcurrency) }
: {}),
diff --git a/test/loop-fire.test.ts b/test/loop-fire.test.ts
index ed5d3a7d0..c8eca02cd 100644
--- a/test/loop-fire.test.ts
+++ b/test/loop-fire.test.ts
@@ -1,3 +1,5 @@
+import { createCronStore, type CreateCronInput } from "../src/cron/cron-store.ts";
+import { createScheduler } from "../src/cron/scheduler.ts";
import assert from "node:assert/strict";
import { test } from "node:test";
import { createLoopFireService } from "../src/loops/loop-fire.ts";
@@ -29,10 +31,17 @@ function fakeDeliveries() {
};
}
-type Responder = (req: TurnRequest) => string;
+type Responder = (req: TurnRequest) => string | Promise<string>;
-function service(respond: Responder, overrides?: { grants?: ReturnType<typeof createShipGrantStore> }) {
+function service(
+ respond: Responder,
+ overrides?: {
+ grants?: ReturnType<typeof createShipGrantStore>;
+ samePerson?: (a: string, b: string) => Promise<boolean>;
+ },
+) {
const loops = createLoopStore();
+ const crons = createCronStore();
const items = createLoopItemLedger();
const outputs = createLoopOutputStore();
const grants = overrides?.grants ?? createShipGrantStore();
@@ -40,6 +49,8 @@ function service(respond: Responder, overrides?: { grants?: ReturnType<typeof cr
const turns: TurnRequest[] = [];
const idempotency = createIdempotencyStore();
const fire = createLoopFireService({
+ crons,
+ samePerson: overrides?.samePerson,
loops,
items,
outputs,
@@ -50,11 +61,11 @@ function service(respond: Responder, overrides?: { grants?: ReturnType<typeof cr
identity: fakeIdentity() as never,
run: async (req): Promise<TurnResult> => {
turns.push(req);
- return { status: "ok", reply: respond(req), sessionId: `s${turns.length}` };
+ return { status: "ok", reply: await respond(req), sessionId: `s${turns.length}` };
},
},
});
- return { loops, items, outputs, grants, fire, turns, deliveries, idempotency };
+ return { loops, crons, items, outputs, grants, fire, turns, deliveries, idempotency };
}
const base = { owner: "josh", createdBy: "josh", ownerScopeId: scopeId("personal", "josh") };
@@ -544,3 +555,178 @@ test("a paused loop refuses to fire", async () => {
assert.equal(result.status, "silent");
assert.equal(s.turns.length, 0);
});
+
+async function bindCron(
+ s: ReturnType<typeof service>,
+ loop: Awaited<ReturnType<typeof makeLoop>>,
+ over: Partial<CreateCronInput> = {},
+) {
+ const cron = await s.crons.create({
+ owner: loop.owner,
+ createdBy: over.owner ?? loop.owner,
+ ownerScopeId: loop.ownerScopeId,
+ schedule: { everyMs: 60_000 },
+ action: "fire loop",
+ loopId: loop.id,
+ ...(loop.runAs ? { runAs: loop.runAs } : {}),
+ ...over,
+ });
+ await s.loops.update(loop.id, { cronId: cron.id });
+ return cron;
+}
+
+for (const unattendedGrants of [undefined, ["admin.sessions.read"]]) {
+ test(`bound scheduled and manual loop turns use current cron grants: ${unattendedGrants}`, async () => {
+ const s = service(HAPPY);
+ const loop = await makeLoop(s.loops);
+ const cron = await bindCron(s, loop, { unattendedGrants, destination: { type: "slack", target: "C-alerts" } });
+ const scheduler = createScheduler({
+ crons: s.crons,
+ deliveries: s.deliveries.store as never,
+ idempotency: s.idempotency,
+ identity: fakeIdentity() as never,
+ run: async () => {
+ throw new Error("must delegate to loop");
+ },
+ fireLoop: (id, key, cronId) => s.fire.fire(id, key, cronId),
+ });
+ await scheduler.tick(cron.createdAt + 60_000);
+ assert.equal((await s.crons.listFires(cron.id)).runs[0]?.status, "ok");
+ assert.deepEqual(s.turns.map(stage), ["intake", "work", "judge"]);
+ await s.fire.fire(loop.id, "manual");
+ const output = (await s.outputs.awaitingReview(loop.id))[0]!;
+ await s.fire.shipOutput(loop.id, output.id, loop.owner);
+ for (const turn of s.turns) {
+ assert.deepEqual(turn.unattendedGrants, unattendedGrants);
+ assert.equal(turn.actor.externalId, loop.owner);
+ assert.equal(turn.triggered, true);
+ assert.equal(turn.triggerDestination, undefined);
+ assert.equal(turn.surfaceTools, undefined);
+ assert.equal(turn.readOnly, undefined);
+ }
+ assert.equal(s.deliveries.sent.length, 0);
+ });
+}
+
+test("bound loop stages reread grants after revocation", async () => {
+ const s = service(async (req) => {
+ if (stage(req) === "intake") await s.crons.update(cron.id, { unattendedGrants: [] });
+ return HAPPY(req);
+ });
+ const loop = await makeLoop(s.loops);
+ const cron = await bindCron(s, loop, { unattendedGrants: ["admin.sessions.read"] });
+ await s.fire.fire(loop.id, "revocation");
+ assert.deepEqual(
+ s.turns.map((t) => t.unattendedGrants),
+ [["admin.sessions.read"], [], []],
+ );
+ const output = (await s.outputs.awaitingReview(loop.id))[0]!;
+ await s.fire.shipOutput(loop.id, output.id, loop.owner);
+ assert.deepEqual(s.turns.at(-1)?.unattendedGrants, []);
+});
+
+for (const runAs of ["scopeShared", "scopeFloor"] as const) {
+ test(`bound loop preserves ${runAs} exclusions and member snapshot`, async () => {
+ const s = service(HAPPY);
+ const loop = await makeLoop(s.loops, { runAs, ownerScopeId: scopeId("channel", "C1") });
+ await bindCron(s, loop, { unattendedGrants: ["admin.sessions.read"], members: [{ id: "josh", type: "internal" }] });
+ const result = await s.fire.fire(loop.id, "shared");
+ assert.equal(result.status, "ok");
+ assert.equal(s.turns.length, 3);
+ for (const turn of s.turns) {
+ assert.equal(turn.unattendedGrants, undefined);
+ assert.equal(turn.ownerKeychainUnion, runAs === "scopeShared" ? true : undefined);
+ assert.equal(turn.conversation.kind, "channel");
+ }
+ });
+}
+
+test("bound loops reject missing crons, foreign scheduler bindings, and authority drift", async () => {
+ for (const over of [
+ { owner: "mallory" },
+ { ownerScopeId: scopeId("personal", "mallory") },
+ { runAs: "scopeFloor" as const },
+ { loopId: "another-loop" },
+ ]) {
+ const s = service(HAPPY);
+ const loop = await makeLoop(s.loops);
+ await bindCron(s, loop, over);
+ assert.equal((await s.fire.fire(loop.id, "mismatch")).status, "failed");
+ assert.equal(s.turns.length, 0);
+ }
+ const s = service(HAPPY);
+ const loop = await makeLoop(s.loops);
+ assert.equal((await s.fire.fire(loop.id, "unbound", "foreign")).status, "failed");
+ const cron = await bindCron(s, loop);
+ assert.equal((await s.fire.fire(loop.id, "foreign", "foreign")).status, "failed");
+ await s.crons.delete(cron.id);
+ assert.equal((await s.fire.fire(loop.id, "deleted")).status, "failed");
+ assert.equal(s.turns.length, 0);
+});
+
+test("legacy inbox sync cron is not a grant source for inbox event turns", async () => {
+ const 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.ok(s.turns.every((turn) => turn.unattendedGrants === undefined));
+ assert.equal((await s.fire.fire(loop.id, "invalid-delegation", cron.id)).status, "failed");
+});
+
+test("privileged item turns inherit grants only for the owner", async () => {
+ const s = service(HAPPY);
+ const created = await makeLoop(s.loops);
+ await bindCron(s, created, { unattendedGrants: ["admin.sessions.read"] });
+ await s.fire.fire(created.id, "setup");
+ const loop = (await s.loops.get(created.id))!;
+ const item = (await s.items.byLoop(loop.id))[0]!;
+ await s.fire.followUp(loop, item, "inspect", "josh");
+ assert.deepEqual(s.turns.at(-1)?.unattendedGrants, ["admin.sessions.read"]);
+ assert.equal((await s.fire.itemAction(loop, item, "inspect", {}, "josh")).ok, true);
+ const before = s.turns.length;
+ assert.equal((await s.fire.itemAction(loop, item, "inspect", {}, "mallory")).ok, false);
+ await s.fire.followUp(loop, item, "inspect", "mallory");
+ assert.equal(s.turns.length, before);
+});
+
+for (const patch of [{ enabled: false }, { archived: true }]) {
+ test(`disabled or archived bound cron cannot authorize loop turns: ${JSON.stringify(patch)}`, async () => {
+ const s = service(HAPPY);
+ const loop = await makeLoop(s.loops);
+ const cron = await bindCron(s, loop, { unattendedGrants: ["admin.sessions.read"] });
+ await s.crons.update(cron.id, patch);
+ assert.equal((await s.fire.fire(loop.id, "disabled")).status, "failed");
+ assert.equal(s.turns.length, 0);
+ });
+}
+
+test("pausing an unprivileged cron does not block held-item follow-up", async () => {
+ const s = service(HAPPY);
+ const created = await makeLoop(s.loops);
+ const cron = await bindCron(s, created);
+ await s.fire.fire(created.id, "setup");
+ await s.crons.setEnabled(cron.id, false);
+ await s.loops.setState(created.id, "paused");
+ const loop = (await s.loops.get(created.id))!;
+ const item = (await s.items.byLoop(loop.id))[0]!;
+ const before = s.turns.length;
+ await s.fire.followUp(loop, item, "inspect", loop.owner);
+ assert.equal(s.turns.length, before + 1);
+ assert.equal(s.turns.at(-1)?.unattendedGrants, undefined);
+});
+
+test("privileged item turns recognize the owner's verified directory alias", async () => {
+ const s = service(HAPPY, { samePerson: async (a, b) => a === "josh" && b === "[email protected]" });
+ const created = await makeLoop(s.loops);
+ await bindCron(s, created, { unattendedGrants: ["admin.sessions.read"] });
+ const loop = (await s.loops.get(created.id))!;
+ await s.fire.fire(loop.id, "alias-owner");
+ const item = (await s.items.byLoop(loop.id))[0]!;
+ const result = await s.fire.itemAction(loop, item, "custom", {}, "[email protected]");
+ assert.equal(result.ok, true);
+ assert.deepEqual(s.turns.at(-1)?.unattendedGrants, ["admin.sessions.read"]);
+ const before = s.turns.length;
+ const refused = await s.fire.itemAction(loop, item, "custom", {}, "[email protected]");
+ assert.equal(refused.ok, false);
+ assert.equal(s.turns.length, before);
+});
diff --git a/test/loop-routes.test.ts b/test/loop-routes.test.ts
index de1565577..ed9ba31e8 100644
--- a/test/loop-routes.test.ts
+++ b/test/loop-routes.test.ts
@@ -47,6 +47,8 @@ async function call(
actor = "josh",
mode: "capability" | "source" = "capability",
liveActor = true,
+ isAdmin = true,
+ managesScope = false,
): Promise<{ status: number; body: unknown }> {
const found = findRoute(loopRoutes as ReadonlyArray<Route<ApiCtx>>, method, path);
assert.ok(found, `no route for ${method} ${path}`);
@@ -69,10 +71,10 @@ async function call(
: null,
app: {
membershipControlsScope: async () => false,
- managesScope: async () => false,
+ managesScope: async () => managesScope,
samePerson: async (a: string, b: string) => a === b,
},
- deps: { loops: deps },
+ deps: { loops: deps, admin: { adminStatusOf: async () => ({ isAdmin }) } },
} as unknown as ApiCtx;
await found.route.handle(ctx);
return out;
@@ -702,3 +704,86 @@ test("only a live human can re-enable an archived loop", async () => {
assert.equal(revived.status, 200);
assert.equal((revived.body as { loop: Loop }).loop.state, "enabled");
});
+
+async function privilegedLoop(deps: LoopServiceDeps): Promise<Loop> {
+ const created = await call(deps, "POST", "/v1/loops", { ...CREATE, schedule: { everyMs: 60_000 } });
+ const loop = (created.body as { loop: Loop }).loop;
+ await deps.crons!.update(loop.cronId!, { unattendedGrants: ["admin.sessions.read"] });
+ return loop;
+}
+
+test("privileged loop config and manual fires use the cron live-owner-admin gate", async () => {
+ const deps = services();
+ const loop = await privilegedLoop(deps);
+ let fires = 0;
+ deps.fire = {
+ fire: async () => {
+ fires++;
+ return { status: "ok" };
+ },
+ } as never;
+ for (const [method, suffix, body] of [
+ ["PATCH", "", { playbook: "changed instructions" }],
+ ["PATCH", "", { successCondition: "changed condition" }],
+ ["PATCH", "", { state: "enabled" }],
+ ["POST", "/fire", {}],
+ ["POST", "/autopilot", { enabled: true }],
+ ["POST", "/grants", { shipAction: "open_pr" }],
+ ["POST", "/outputs/output/decide", { decision: "return", note: "new instructions" }],
+ ] as const) {
+ const path = `/v1/loops/${loop.id}${suffix}`;
+ assert.equal((await call(deps, method, path, body, "josh", "capability", false)).status, 403);
+ assert.equal((await call(deps, method, path, body, "josh", "capability", true, false)).status, 403);
+ assert.equal((await call(deps, method, path, body, "mallory", "capability", true, true, true)).status, 403);
+ assert.equal((await call(deps, method, path, body, "josh", "source")).status, 403);
+ }
+ assert.equal(fires, 0);
+ assert.equal((await deps.store.get(loop.id))?.playbook, loop.playbook);
+ const permitted = await call(deps, "PATCH", `/v1/loops/${loop.id}`, { playbook: "owner revision" });
+ assert.equal(permitted.status, 200);
+ assert.deepEqual((await deps.crons!.get(loop.cronId!))?.unattendedGrants, ["admin.sessions.read"]);
+ assert.equal((await call(deps, "POST", `/v1/loops/${loop.id}/fire`, {})).status, 200);
+ assert.equal(fires, 1);
+ await deps.crons!.update(loop.cronId!, { unattendedGrants: [] });
+ assert.equal(
+ (await call(deps, "PATCH", `/v1/loops/${loop.id}`, { playbook: "ordinary revision" }, "josh", "capability", false))
+ .status,
+ 200,
+ );
+});
+
+test("loop mutation and manual fire reject a drifted native binding", async () => {
+ const deps = services();
+ const loop = await privilegedLoop(deps);
+ await deps.crons!.update(loop.cronId!, { runAs: "scopeFloor" });
+ assert.equal((await call(deps, "PATCH", `/v1/loops/${loop.id}`, { playbook: "revision" })).status, 409);
+ assert.equal((await call(deps, "POST", `/v1/loops/${loop.id}/fire`, {})).status, 409);
+ assert.equal((await deps.store.get(loop.id))?.playbook, loop.playbook);
+});
+
+test("a legacy inbox sync cron cannot be re-enabled through an autonomous Loop patch", async () => {
+ const deps = services();
+ const { loop } = await deps.store.create({
+ owner: "josh",
+ createdBy: "josh",
+ ownerScopeId: scopeId("personal", "josh"),
+ ...CREATE,
+ surface: "inbox",
+ shipActions: [],
+ });
+ const cron = await deps.crons!.create({
+ owner: loop.owner,
+ createdBy: loop.owner,
+ ownerScopeId: loop.ownerScopeId,
+ schedule: { everyMs: 60_000 },
+ action: "Inbox sync v3.",
+ unattendedGrants: ["admin.sessions.read"],
+ });
+ await deps.store.update(loop.id, { cronId: cron.id, state: "paused" });
+ await deps.crons!.setEnabled(cron.id, false);
+ const refused = await call(deps, "PATCH", `/v1/loops/${loop.id}`, { state: "enabled" }, "josh", "capability", false);
+ assert.equal(refused.status, 403);
+ assert.equal((await deps.crons!.get(cron.id))?.enabled, false);
+ assert.equal((await call(deps, "PATCH", `/v1/loops/${loop.id}`, { state: "enabled" })).status, 200);
+ assert.equal((await deps.crons!.get(cron.id))?.enabled, true);
+});