Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Deliver scheduled messages to teammates without recipient consent (#2425)

Regan Bell296966962f46
diff --git a/package.json b/package.json
index 9c96b7f84..1281066b2 100644
--- a/package.json
+++ b/package.json
@@ -48,7 +48,7 @@
"sandbox:local:build": "bash scripts/local-sandbox-build.sh",
"sandbox:porter:build": "docker build --platform linux/amd64 -t \"${PORTER_SANDBOX_IMAGE:?Set PORTER_SANDBOX_IMAGE to the registry tag to publish}\" porter && docker push \"$PORTER_SANDBOX_IMAGE\"",
"deploy:porter-runner-image": "docker build --platform linux/amd64 -t \"${PORTER_DEPLOY_RUNNER_IMAGE:?Set PORTER_DEPLOY_RUNNER_IMAGE to the registry tag to publish}\" -f deploy/porter-runner/Dockerfile . && docker push \"$PORTER_DEPLOY_RUNNER_IMAGE\"",
- "test:pg": "node scripts/run-pg-tests.mjs test/batch-paths.test.ts test/session-append-many.test.ts test/cron-queue.test.ts test/postgres-migration-startup.test.ts test/postgres-swarms.test.ts test/postgres-store.test.ts test/postgres-tapeless-store.test.ts test/postgres-legacy-tape-steps.test.ts test/semantic-memory-pg.test.ts test/semantic-memory-http.test.ts test/semantic-memory-large-pg.test.ts test/postgres-instance-registry.test.ts test/readiness.test.ts test/postgres-grant-store.test.ts test/postgres-acl-file-id-migration.test.ts test/postgres-admin-grants.test.ts test/postgres-teams.test.ts test/postgres-decisions.test.ts test/postgres-file-artifact-store.test.ts test/postgres-file-upload-store.test.ts test/postgres-directory-store.test.ts test/postgres-linked-identity-membership.test.ts test/postgres-map.test.ts test/postgres-background-ownership.test.ts test/postgres-resource-search.test.ts test/deploy-store-pg.test.ts test/postgres-cron-fires.test.ts test/postgres-cron-run-as-migration.test.ts test/postgres-legacy-harness-migration.test.ts test/postgres-migration-adoption.test.ts test/postgres-migrations.test.ts test/postgres-metrics-sink.test.ts test/postgres-error-log.test.ts test/postgres-audit-log.test.ts test/postgres-app-page-views.test.ts test/postgres-budget.test.ts test/postgres-rate-limiter.test.ts test/postgres-credential-usage-sink.test.ts test/postgres-config-store.test.ts test/postgres-delivery-store.test.ts test/postgres-replay-dedupe.test.ts test/postgres-broker-sessions.test.ts test/postgres-egress-audit-sink.test.ts test/postgres-memory-service.test.ts test/run-signal-store.test.ts test/postgres-listener.test.ts test/postgres-run-activity-store.test.ts test/leader-lease.test.ts test/advisory-lock.test.ts test/loop-ingress-pg.test.ts test/persistence-init-retry.test.ts test/migrate-principals.test.ts test/postgres-surface-cache.test.ts test/slack-mirror-fidelity.test.ts test/run-retry-delay.test.ts test/run-priority.test.ts test/postgres-run-stream.test.ts test/migrate-main.test.ts",
+ "test:pg": "node scripts/run-pg-tests.mjs test/batch-paths.test.ts test/session-append-many.test.ts test/cron-queue.test.ts test/postgres-migration-startup.test.ts test/postgres-swarms.test.ts test/postgres-store.test.ts test/postgres-tapeless-store.test.ts test/postgres-legacy-tape-steps.test.ts test/semantic-memory-pg.test.ts test/semantic-memory-http.test.ts test/semantic-memory-large-pg.test.ts test/postgres-instance-registry.test.ts test/readiness.test.ts test/postgres-grant-store.test.ts test/postgres-acl-file-id-migration.test.ts test/postgres-admin-grants.test.ts test/postgres-teams.test.ts test/postgres-decisions.test.ts test/postgres-file-artifact-store.test.ts test/postgres-file-upload-store.test.ts test/postgres-directory-store.test.ts test/postgres-linked-identity-membership.test.ts test/postgres-map.test.ts test/postgres-background-ownership.test.ts test/postgres-resource-search.test.ts test/deploy-store-pg.test.ts test/postgres-cron-fires.test.ts test/postgres-cron-run-as-migration.test.ts test/postgres-trigger-recipient-consent-migration.test.ts test/postgres-legacy-harness-migration.test.ts test/postgres-migration-adoption.test.ts test/postgres-migrations.test.ts test/postgres-metrics-sink.test.ts test/postgres-error-log.test.ts test/postgres-audit-log.test.ts test/postgres-app-page-views.test.ts test/postgres-budget.test.ts test/postgres-rate-limiter.test.ts test/postgres-credential-usage-sink.test.ts test/postgres-config-store.test.ts test/postgres-delivery-store.test.ts test/postgres-replay-dedupe.test.ts test/postgres-broker-sessions.test.ts test/postgres-egress-audit-sink.test.ts test/postgres-memory-service.test.ts test/run-signal-store.test.ts test/postgres-listener.test.ts test/postgres-run-activity-store.test.ts test/leader-lease.test.ts test/advisory-lock.test.ts test/loop-ingress-pg.test.ts test/persistence-init-retry.test.ts test/migrate-principals.test.ts test/postgres-surface-cache.test.ts test/slack-mirror-fidelity.test.ts test/run-retry-delay.test.ts test/run-priority.test.ts test/postgres-run-stream.test.ts test/migrate-main.test.ts",
"livetest": "node scripts/api-livetest.ts",
"bench:memory": "node --env-file-if-exists=.env scripts/memory-bench.ts",
"prepare": "node .husky/install.mjs",
diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.ts
index 1ee6e6079..58fad06e5 100644
--- a/src/api/agent-api-catalog.ts
+++ b/src/api/agent-api-catalog.ts
@@ -347,19 +347,6 @@ const FAMILIES: AgentApiFamily[] = [
},
],
},
- {
- match: (m, p) => m === "POST" && /^\/v1\/triggers\/[^/]+\/consent$/.test(p),
- guidance:
- "If the person you're helping is told a teammate set up a recurring delivery (a cron or webhook that DMs them), THEY control whether it reaches them — not its behavior. When they say yes/no, call this with the ref id from the notice. Reversible anytime; only the recipient can decide.",
- routes: [
- {
- method: "POST",
- path: "/v1/triggers/:id/consent",
- summary:
- 'accept or decline a standing trigger\'s deliveries to you (a teammate\'s cron/webhook/watch that DMs you) — body {decision:"accept"|"decline"}; reversible; recipient-only',
- },
- ],
- },
{
match: (m, p) =>
((m === "POST" || m === "GET") && p === "/v1/pins") || (m === "DELETE" && /^\/v1\/pins\/[^/]+$/.test(p)),
diff --git a/src/api/app-messaging.ts b/src/api/app-messaging.ts
index 9b5d449e5..5346bc3ab 100644
--- a/src/api/app-messaging.ts
+++ b/src/api/app-messaging.ts
@@ -74,14 +74,12 @@ export function createMessagingMethods(
| "latestCronFireForThread"
| "setCronDestination"
| "setCronRuntime"
- | "setCronRecipientConsent"
| "createWebhook"
| "getWebhook"
| "listWebhooks"
| "listWebhookEvents"
| "setWebhookEnabled"
| "updateWebhook"
- | "setWebhookRecipientConsent"
| "pendingDeliveries"
| "enqueueDelivery"
| "ingestSurfaceEvents"
@@ -275,9 +273,6 @@ export function createMessagingMethods(
});
return deps.crons.get(id);
},
- setCronRecipientConsent(id, recipientConsent) {
- return deps.crons.setRecipientConsent(id, recipientConsent);
- },
async createWebhook(input) {
const webhook = await deps.webhooks.create(input);
deps.auditLog.record({
@@ -311,9 +306,6 @@ export function createMessagingMethods(
updateWebhook(id, patch) {
return deps.webhooks.update(id, patch);
},
- setWebhookRecipientConsent(id, recipientConsent) {
- return deps.webhooks.setRecipientConsent(id, recipientConsent);
- },
pendingDeliveries(type, claimMs) {
return claimMs && claimMs > 0 ? deps.deliveries.claimPending(type, claimMs) : deps.deliveries.pending(type);
},
diff --git a/src/api/app-types.ts b/src/api/app-types.ts
index 0f4bcc65d..422c3bd78 100644
--- a/src/api/app-types.ts
+++ b/src/api/app-types.ts
@@ -76,7 +76,6 @@ import type {
CronFireNote,
Delivery,
Destination,
- RecipientConsent,
SurfaceContextQuery,
SurfaceContextRequest,
SurfaceContextResult,
@@ -466,14 +465,12 @@ export interface App {
latestCronFireForThread(id: string, threadRef: string): Promise<CronFireLogEntry | undefined>;
setCronRuntime(id: string, runtime: Exclude<Cron["runtime"], undefined>): Promise<Cron | null>;
setCronDestination(id: string, destination: Destination | undefined): Promise<Cron | null>;
- setCronRecipientConsent(id: string, recipientConsent: RecipientConsent): Promise<void>;
createWebhook(input: CreateWebhookInput): Promise<Webhook>;
getWebhook(id: string): Promise<Webhook | null>;
listWebhookEvents(id: string, viewer: string): Promise<Array<WebhookEvent & { sessionId?: string }>>;
listWebhooks(): Promise<Webhook[]>;
setWebhookEnabled(id: string, enabled: boolean): Promise<void>;
updateWebhook(id: string, patch: { action: string }): Promise<Webhook | null>;
- setWebhookRecipientConsent(id: string, recipientConsent: RecipientConsent): Promise<void>;
pendingDeliveries(type: string, claimMs?: number): Promise<Delivery[]>;
enqueueDelivery(input: {
destination: Destination;
diff --git a/src/api/control-service.ts b/src/api/control-service.ts
index 87fdfeef8..a11e1abe9 100644
--- a/src/api/control-service.ts
+++ b/src/api/control-service.ts
@@ -14,8 +14,6 @@ import {
import { DEFAULT_CRON_TIMEZONE } from "../cron/schedule.ts";
import { resolveCapabilityDestination } from "./capability-destination.ts";
import { withSlackUnfurlOption, principalDestination } from "../reach/reach.ts";
-import { consentRequiredRecipient } from "../triggers/trigger-store.ts";
-import { sendConsentNotice } from "../triggers/consent-notice.ts";
import { notifyOwnerOfCronEdit, type CronEditDetail } from "../triggers/edit-notice.ts";
import { errMessage } from "../util/errors.ts";
import { AdminError } from "../admin/admin-service.ts";
@@ -466,9 +464,6 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad
}
if (destination) destination = withSlackUnfurlOption(destination, req.unfurlLinks);
- const standing = req.schedule.cron !== undefined || req.schedule.everyMs !== undefined;
- const consentRecipient = consentRequiredRecipient({ owner: capability.actorId, standing, destination });
-
const input: CreateCronInput = {
schedule: withDefaultTimezone(req.schedule, capability),
...(req.runtime !== undefined ? { runtime: req.runtime } : {}),
@@ -479,26 +474,12 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad
ownerScopeId,
...(typeof req.title === "string" ? { title: req.title } : {}),
...(destination ? { destination } : {}),
- ...(consentRecipient
- ? { recipientConsent: { recipientId: consentRecipient, status: "pending" as const } }
- : {}),
...(req.unattendedGrants !== undefined ? { unattendedGrants: req.unattendedGrants } : {}),
};
const sessionRef = req.session === false ? undefined : liveSessionRef(capability, ownerScopeId);
if (sessionRef) input.sessionRef = sessionRef;
try {
const cron = await app.createCron(input);
- if (consentRecipient) {
- const ownerMember = await app.directoryMember(capability.actorId);
- await sendConsentNotice((i) => app.enqueueDelivery(i), {
- triggerId: cron.id,
- recipientId: consentRecipient,
- ownerId: capability.actorId,
- ...(ownerMember?.displayName ? { ownerName: ownerMember.displayName } : {}),
- what:
- typeof req.title === "string" ? `a scheduled message ("${req.title}")` : "a recurring scheduled message",
- });
- }
return {
ok: true,
cron,
@@ -733,15 +714,6 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad
message: "destinationKey is not one of the destinations available for this conversation",
};
}
- // A webhook is standing (event-driven); a third-party-principal destination needs the
- // recipient's consent, same as a recurring cron. (Today destinationKey only resolves the
- // current conversation, so this won't fire — the gate is here so it stays correct if webhook
- // addressing ever widens.)
- const consentRecipient = consentRequiredRecipient({
- owner: capability.actorId,
- standing: true,
- destination: resolved.destination,
- });
const input: CreateWebhookInput = {
action: req.action,
verification: req.verification,
@@ -750,22 +722,9 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad
ownerScopeId: capability.scopeId,
...(req.filters?.length ? { filters: req.filters } : {}),
...(resolved.destination ? { destination: resolved.destination } : {}),
- ...(consentRecipient
- ? { recipientConsent: { recipientId: consentRecipient, status: "pending" as const } }
- : {}),
};
try {
const webhook = await app.createWebhook(input);
- if (consentRecipient) {
- const ownerMember = await app.directoryMember(capability.actorId);
- await sendConsentNotice((i) => app.enqueueDelivery(i), {
- triggerId: webhook.id,
- recipientId: consentRecipient,
- ownerId: capability.actorId,
- ...(ownerMember?.displayName ? { ownerName: ownerMember.displayName } : {}),
- what: "an event-triggered message",
- });
- }
const incomingPath = `/v1/webhooks/incoming/${webhook.id}`;
const base = publicBase ? publicBase.replace(/\/$/, "") : "";
return {
diff --git a/src/api/routes/crons.ts b/src/api/routes/crons.ts
index e53ed03ce..367a14481 100644
--- a/src/api/routes/crons.ts
+++ b/src/api/routes/crons.ts
@@ -7,7 +7,6 @@ import type { CapabilityClaims } from "../../auth/capability-token.ts";
import { errMessage } from "../../util/errors.ts";
import { sendJson } from "../http.ts";
import { isObj } from "./shared.ts";
-import { decideRecipientConsent } from "../../triggers/trigger-store.ts";
import { notifyOwnerOfCronEdit } from "../../triggers/edit-notice.ts";
import { canAdministerCron } from "../control-service.ts";
import { CRON_PATCH_NOTHING_TO_CHANGE } from "../control-service.ts";
@@ -451,32 +450,7 @@ async function cronById(ctx: ApiCtx): Promise<void> {
}
}
-async function triggerConsent(ctx: ApiCtx): Promise<void> {
- const { res, app, body, capability } = ctx;
- const id = ctx.params.id!;
- if (!capability)
- return sendJson(res, 403, { error: "forbidden", message: "consent requires an agent capability token" });
- const decision = isObj(body) ? body.decision : undefined;
- if (decision !== "accept" && decision !== "decline") {
- return sendJson(res, 400, { error: "bad_request", message: 'decision must be "accept" or "decline"' });
- }
- const cron = await app.getCron(id);
- const webhook = cron ? null : await app.getWebhook(id);
- const trigger = cron ?? webhook;
- if (!trigger) return sendJson(res, 404, { error: "not_found" });
- const decided = decideRecipientConsent(trigger.recipientConsent, capability.actorId, decision, Date.now());
- if (!decided.ok) {
- return decided.reason === "no_consent"
- ? sendJson(res, 400, { error: "bad_request", message: "this trigger has no recipient consent to decide on" })
- : sendJson(res, 403, { error: "forbidden", message: "only the delivery recipient can accept or decline this" });
- }
- if (cron) await app.setCronRecipientConsent(id, decided.consent);
- else await app.setWebhookRecipientConsent(id, decided.consent);
- return sendJson(res, 200, { ok: true, consent: decided.consent });
-}
-
export const cronRoutes: ReadonlyArray<Route<ApiCtx>> = [
- { method: "POST", path: "/v1/triggers/:id/consent", auth: "either", handle: triggerConsent },
{ method: "POST", path: "/v1/crons", auth: "either", handle: createCron },
{ method: "GET", path: "/v1/crons", auth: "either", handle: listCrons },
{ method: "POST", path: "/v1/crons/:id/disable", auth: "either", handle: disableCron },
diff --git a/src/api/routes/loops.ts b/src/api/routes/loops.ts
index fa622fc69..6e7d0dbe2 100644
--- a/src/api/routes/loops.ts
+++ b/src/api/routes/loops.ts
@@ -17,7 +17,6 @@ import { settleGroup } from "../../loops/triage.ts";
import type { CronStore } from "../../cron/cron-store.ts";
import { DEFAULT_CRON_TIMEZONE, userScheduleFromBody, validateUserSchedule } from "../../cron/schedule.ts";
import type { ScopedConfigStore } from "../../resolution/config-store.ts";
-import { consentRequiredRecipient } from "../../triggers/trigger-store.ts";
import { errMessage, swallow } from "../../util/errors.ts";
import { sendJson } from "../http.ts";
import { isObj, resolveCapabilityDestination } from "./shared.ts";
@@ -248,7 +247,6 @@ async function createLoop(ctx: ApiCtx): Promise<void> {
}
}
let destination;
- let recipientConsent;
if (b.destinationKey !== undefined) {
if (typeof b.destinationKey !== "string")
return sendJson(ctx.res, 400, { error: "bad_request", message: "destinationKey must be a string" });
@@ -259,8 +257,6 @@ async function createLoop(ctx: ApiCtx): Promise<void> {
return sendJson(ctx.res, 400, { error: "bad_request", message: "destinationKey is not available" });
if (!requireLiveHuman(ctx, acting)) return;
destination = resolved.destination;
- const recipientId = consentRequiredRecipient({ owner: acting.actorId, standing: true, destination });
- if (recipientId) recipientConsent = { recipientId, status: "pending" as const };
}
const ownerScopeId: ScopeId = scopeId("personal", acting.actorId);
const input: CreateLoopInput = {
@@ -280,7 +276,6 @@ async function createLoop(ctx: ApiCtx): Promise<void> {
...(governor && Object.keys(governor).length > 0 ? { governor } : {}),
...(schedule ? { schedule } : {}),
...(destination ? { destination } : {}),
- ...(recipientConsent ? { recipientConsent } : {}),
};
let loop: Loop;
let created: boolean;
@@ -470,18 +465,11 @@ async function patchLoop(ctx: ApiCtx): Promise<void> {
if (!requireLiveHuman(ctx, acting)) return;
if (b.destinationKey === null) {
patch.destination = null;
- patch.recipientConsent = null;
} else {
const resolved = resolveCapabilityDestination(ctx.capability, b.destinationKey);
if (!resolved.ok || !resolved.destination)
return sendJson(ctx.res, 400, { error: "bad_request", message: "destinationKey is not available" });
patch.destination = resolved.destination;
- const recipientId = consentRequiredRecipient({
- owner: loop.owner,
- standing: true,
- destination: resolved.destination,
- });
- patch.recipientConsent = recipientId ? { recipientId, status: "pending" } : null;
}
}
const updated = Object.keys(patch).length > 0 ? await deps.store.update(loop.id, patch) : loop;
diff --git a/src/api/server.ts b/src/api/server.ts
index 896622d9b..7fd78e360 100644
--- a/src/api/server.ts
+++ b/src/api/server.ts
@@ -125,7 +125,7 @@ function isAdminContentRead(pathname: string): boolean {
return false;
}
-function strictPostAllowed(pathname: string, body: unknown): boolean {
+function strictPostAllowed(pathname: string): boolean {
if (
pathname === "/v1/surface-context" ||
pathname === "/v1/projects" ||
@@ -135,10 +135,7 @@ function strictPostAllowed(pathname: string, body: unknown): boolean {
)
return true;
if (/^\/v1\/projects\/[^/]+(?:\/members(?:\/[^/]+)?)?$/.test(pathname)) return true;
- if (/^\/v1\/skills\/[^/]+\/restore$/.test(pathname)) return true;
- return (
- /^\/v1\/triggers\/[^/]+\/consent$/.test(pathname) && (body as { decision?: unknown } | null)?.decision === "decline"
- );
+ return /^\/v1\/skills\/[^/]+\/restore$/.test(pathname);
}
function capabilityFromHeaders(req: IncomingMessage): string | null {
@@ -311,7 +308,7 @@ async function gate(
capability &&
!requiredAud &&
method !== "GET" &&
- !strictPostAllowed(pathname, body) &&
+ !strictPostAllowed(pathname) &&
deps.config &&
(await deps.config.getSecurityPostureDurable(capability.scopeId)) === "strict"
) {
diff --git a/src/api/user-scoped-routes.ts b/src/api/user-scoped-routes.ts
index 76b008116..719b81c14 100644
--- a/src/api/user-scoped-routes.ts
+++ b/src/api/user-scoped-routes.ts
@@ -162,7 +162,6 @@ const SYSTEM: Rule[] = [
pat("POST", "/v1/keychain/grants/:id/revoke"),
pat("POST", "/v1/surface-context"),
pat("POST", "/v1/surface-file"),
- pat("POST", "/v1/triggers/:id/consent"),
];
const WRITE = new Set(["POST", "PUT", "DELETE", "PATCH"]);
diff --git a/src/cron/cron-store.ts b/src/cron/cron-store.ts
index 951e3c40f..09777b837 100644
--- a/src/cron/cron-store.ts
+++ b/src/cron/cron-store.ts
@@ -1,4 +1,4 @@
-import type { Cron, CronFireLogEntry, CronFireNote, CronSchedule, Destination, RecipientConsent } from "../types.ts";
+import type { Cron, CronFireLogEntry, CronFireNote, CronSchedule, Destination } from "../types.ts";
import { createMemoryMap, type DurableMap } from "../persistence/durable-map.ts";
import {
createMemoryCronFireStore,
@@ -11,7 +11,6 @@ import {
buildTriggerBase,
contentPart,
createDeduped,
- setTriggerRecipientConsent,
type CreateTriggerInput,
} from "../triggers/trigger-store.ts";
import { assertCronRuntime } from "./runtime.ts";
@@ -59,7 +58,6 @@ export interface CronStore {
delete(id: string): Promise<void>;
setEnabled(id: string, enabled: boolean): Promise<void>;
setDestination(id: string, destination: Destination | undefined): Promise<void>;
- setRecipientConsent(id: string, recipientConsent: RecipientConsent): Promise<void>;
beginFire(id: string, entry: CronFireLogEntry, opts?: { exclusive?: boolean }): Promise<BeginFireResult>;
sweepStrandedFires(now: number): Promise<number>;
pruneFires(now: number): Promise<number>;
@@ -167,9 +165,6 @@ export function createCronStore(
async setDestination(id, destination) {
await backing.merge(id, { destination });
},
- setRecipientConsent(id, recipientConsent) {
- return setTriggerRecipientConsent(backing, id, recipientConsent);
- },
async beginFire(id, entry, opts) {
if ((await backing.get(id)) === null) return { begun: false };
if (opts?.exclusive) return fires.beginExclusive(id, entry, staleRunningMs);
diff --git a/src/cron/scheduler.ts b/src/cron/scheduler.ts
index 4eb65e93e..5b08369e6 100644
--- a/src/cron/scheduler.ts
+++ b/src/cron/scheduler.ts
@@ -82,6 +82,7 @@ export interface SchedulerDeps {
jobQueue?: CronJobQueue;
requireQueueStart?: boolean;
sessions?: TriggerDeps["sessions"];
+ resolveRecipient?: TriggerDeps["resolveRecipient"];
skipFire?: (cron: Cron) => Promise<string | undefined>;
deleteCron?: (id: string) => Promise<void>;
fireLoop?: (
@@ -273,6 +274,7 @@ export function createScheduler(deps: SchedulerDeps): Scheduler {
...(deps.directory ? { directory: deps.directory } : {}),
...(deps.currentScopeMembers ? { currentScopeMembers: deps.currentScopeMembers } : {}),
...(deps.sessions ? { sessions: deps.sessions } : {}),
+ ...(deps.resolveRecipient ? { resolveRecipient: deps.resolveRecipient } : {}),
},
{
...cronTriggerAuthority(cron),
@@ -287,8 +289,6 @@ export function createScheduler(deps: SchedulerDeps): Scheduler {
},
...(cron.message !== undefined ? { message: cron.message } : {}),
...(cron.destination ? { destination: cron.destination } : {}),
- ...(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/loop-fire.ts b/src/loops/loop-fire.ts
index 506f953eb..1cc12c187 100644
--- a/src/loops/loop-fire.ts
+++ b/src/loops/loop-fire.ts
@@ -5,12 +5,11 @@ import type { CronStore } from "../cron/cron-store.ts";
import { boundLoopCron } from "./authority.ts";
import { samePerson } from "../directory/person.ts";
import type { Loop, LoopItem, LoopOutput, TurnRequest, TurnResult } from "../types.ts";
-import { runTrigger, type TriggerDeps, type TriggerOutcome } from "../triggers/run-trigger.ts";
+import { destinationVisible, runTrigger, type TriggerDeps, type TriggerOutcome } from "../triggers/run-trigger.ts";
import { reachEnqueue } from "../reach/reach.ts";
import { hashId } from "../util/crypto.ts";
import { errMessage } from "../util/errors.ts";
import { userFacingFailureClause } from "../core/failure-copy.ts";
-import { consentRequiredRecipient, recipientConsentSatisfied } from "../triggers/trigger-store.ts";
import { isRunnable, type LoopStore } from "./loop-store.ts";
import type { LoopItemLedger } from "./item-ledger.ts";
import type { LoopOutputStore } from "./output-store.ts";
@@ -605,13 +604,12 @@ export function createLoopFireService(deps: LoopFireDeps): LoopFireService {
await deps.loops.setState(loop.id, "quarantined");
}
await deps.loops.setHealth(loop.id, verdict.health, verdict.reason, verdict.throttle);
- const escalationRecipient = consentRequiredRecipient({
- owner: loop.owner,
- standing: true,
- destination: loop.destination,
- });
- const escalationConsented = recipientConsentSatisfied(loop, escalationRecipient);
- if (verdict.escalate && healthWorsened(previous, verdict.health) && loop.destination && escalationConsented) {
+ if (
+ verdict.escalate &&
+ healthWorsened(previous, verdict.health) &&
+ loop.destination &&
+ (await destinationVisible(deps.trigger, loop.owner, loop.destination))
+ ) {
const lines = [
`Loop "${loop.name}" is ${verdict.health}${verdict.reason ? `: ${verdict.reason}` : ""}.`,
...verdict.actions.map(
diff --git a/src/loops/loop-store.ts b/src/loops/loop-store.ts
index 8a122dc45..79d4d8a90 100644
--- a/src/loops/loop-store.ts
+++ b/src/loops/loop-store.ts
@@ -6,7 +6,6 @@ import type {
LoopState,
LoopTriageConfig,
Destination,
- RecipientConsent,
ShipActionPolicy,
} from "../types.ts";
import { createMemoryMap, type DurableMap } from "../persistence/durable-map.ts";
@@ -42,7 +41,6 @@ export interface LoopPatch {
successCondition?: string;
successChecks?: string[];
destination?: Destination | null;
- recipientConsent?: RecipientConsent | null;
shipActions?: ShipActionPolicy[];
caps?: LoopCaps;
governor?: LoopGovernorConfig;
@@ -158,7 +156,6 @@ export function createLoopStore(backing: DurableMap<Loop> = createMemoryMap<Loop
contentPart(input.governor),
contentPart(input.destination),
contentPart(input.ownerConsentedAt),
- contentPart(input.recipientConsent),
contentPart(input.cronId),
contentPart(input.schedule),
]);
@@ -205,7 +202,6 @@ export function createLoopStore(backing: DurableMap<Loop> = createMemoryMap<Loop
if (patch.successCondition !== undefined) fields.successCondition = patch.successCondition;
if (patch.successChecks !== undefined) fields.successChecks = patch.successChecks;
if (patch.destination !== undefined) fields.destination = patch.destination ?? undefined;
- if (patch.recipientConsent !== undefined) fields.recipientConsent = patch.recipientConsent ?? undefined;
if (patch.shipActions !== undefined) {
const shipActions = normalizeShipActions(patch.shipActions);
fields.shipActions = shipActions;
diff --git a/src/monitors/monitor-poller.ts b/src/monitors/monitor-poller.ts
index 724bcbcf0..c1991a325 100644
--- a/src/monitors/monitor-poller.ts
+++ b/src/monitors/monitor-poller.ts
@@ -40,6 +40,7 @@ export interface MonitorPollerDeps {
directory?: TriggerDeps["directory"];
currentScopeMembers?: CurrentScopeMembers;
sessions?: TriggerDeps["sessions"];
+ resolveRecipient?: TriggerDeps["resolveRecipient"];
now?: () => number;
maxFiresPerTick?: number;
leaderLease?: LeaderLease;
@@ -140,6 +141,7 @@ export function createMonitorPoller(deps: MonitorPollerDeps): MonitorPoller {
...(deps.directory ? { directory: deps.directory } : {}),
...(deps.currentScopeMembers ? { currentScopeMembers: deps.currentScopeMembers } : {}),
...(deps.sessions ? { sessions: deps.sessions } : {}),
+ ...(deps.resolveRecipient ? { resolveRecipient: deps.resolveRecipient } : {}),
};
async function fire(
diff --git a/src/triggers/consent-notice.ts b/src/triggers/consent-notice.ts
deleted file mode 100644
index aa05348b5..000000000
--- a/src/triggers/consent-notice.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import type { Destination } from "../types.ts";
-import { principalDestination } from "../reach/reach.ts";
-
-function composeConsentNotice(args: { triggerId: string; what: string; ownerName?: string }): string {
- const who = args.ownerName ?? "A teammate";
- return (
- `${who} set up ${args.what} to be delivered to you. It won't start until you accept.\n` +
- `Tell me "accept" to start receiving it, or "decline" to keep it off — you can stop it anytime. (ref: ${args.triggerId})`
- );
-}
-
-export async function sendConsentNotice(
- enqueue: (input: { destination: Destination; text: string; idempotencyKey: string }) => Promise<unknown>,
- args: { triggerId: string; recipientId: string; ownerId: string; ownerName?: string; what: string },
-): Promise<void> {
- await enqueue({
- destination: principalDestination(args.recipientId, args.ownerId),
- text: composeConsentNotice(args),
- idempotencyKey: `consent-notice:${args.triggerId}`,
- });
-}
diff --git a/src/triggers/keychain-ask.ts b/src/triggers/keychain-ask.ts
index d54584e33..93f46d507 100644
--- a/src/triggers/keychain-ask.ts
+++ b/src/triggers/keychain-ask.ts
@@ -61,12 +61,6 @@ export async function fireAskResolution(
surface: "keychain-ask",
...(cron?.runtime ? { runtime: cron.runtime } : {}),
deferWhenBusy: true,
- ...(cron
- ? {
- ...(cron.recipientConsent ? { recipientConsent: cron.recipientConsent } : {}),
- recipientConsentRequired: cron.schedule.everyMs !== undefined || cron.schedule.cron !== undefined,
- }
- : {}),
...(destination ? { destination } : {}),
...(ask.requesterThreadRef ? { threadRef: ask.requesterThreadRef } : {}),
});
diff --git a/src/triggers/run-trigger.ts b/src/triggers/run-trigger.ts
index 5a501342e..3a1f989ae 100644
--- a/src/triggers/run-trigger.ts
+++ b/src/triggers/run-trigger.ts
@@ -1,22 +1,13 @@
-import type {
- DeliveryProvenance,
- Destination,
- Principal,
- RecipientConsent,
- ScopeId,
- TurnRequest,
- TurnResult,
-} from "../types.ts";
+import type { DeliveryProvenance, Destination, Principal, ScopeId, TurnRequest, TurnResult } from "../types.ts";
import { actsAsScope, parseScopeId } from "../types.ts";
import type { IdentityService } from "../identity/identity-service.ts";
import type { DeliveryStore } from "../delivery/delivery-store.ts";
import type { IdempotencyStore } from "../idempotency/idempotency-store.ts";
import { turnModelOptions } from "../core/turn-options.ts";
import { userFacingFailureClause } from "../core/failure-copy.ts";
-import { principalDestination, reachEnqueue } from "../reach/reach.ts";
-import { consentRequiredRecipient, recipientConsentSatisfied } from "./trigger-store.ts";
+import { reachEnqueue } from "../reach/reach.ts";
import { isVisible, type VisibilityDirectory } from "../directory/visibility.ts";
-import type { DirectoryMember, DirectoryStore } from "../directory/directory-store.ts";
+import type { DirectoryMember, DirectoryStore, RecipientResolution } from "../directory/directory-store.ts";
import { samePerson } from "../directory/person.ts";
import type { CurrentScopeMembers } from "../resolution/scope-membership.ts";
import { isProjectGroupRef } from "../projects/project-store.ts";
@@ -39,6 +30,7 @@ export interface TriggerDeps {
conversationMembers?: DirectoryStore["conversationMembers"];
};
sessions?: { listByParticipant(principalId: string): Promise<readonly { scopeId: ScopeId }[]> };
+ resolveRecipient?: (query: string) => Promise<RecipientResolution>;
}
export interface TriggerSpec extends Pick<TurnRequest, "model" | "harness" | "fastMode" | "attachments"> {
@@ -54,8 +46,6 @@ export interface TriggerSpec extends Pick<TurnRequest, "model" | "harness" | "fa
message?: string;
threadRef?: string;
unattendedGrants?: string[];
- recipientConsent?: RecipientConsent;
- recipientConsentRequired?: boolean;
shadow?: boolean;
thinkingLevel?: string;
readOnly?: boolean;
@@ -174,7 +164,13 @@ export async function destinationVisible(
return isVisible(deps.directory, actorId, { kind: "channel", channelId: id });
}
if (destination.type === "group") return isVisible(deps.directory, actorId, { kind: "group", groupId: id });
- return true;
+ if (destination.type !== "principal" || samePerson(destination.target, actorId) || !deps.resolveRecipient)
+ return true;
+ const recipient = await deps.resolveRecipient(destination.target);
+ return (
+ recipient.kind === "one" &&
+ (samePerson(recipient.member.principalId, destination.target) || recipient.member.slackId === destination.target)
+ );
}
const SCHEDULED_SURFACES = new Set(["cron", "loop", "keychain-ask"]);
@@ -259,33 +255,13 @@ export async function runTrigger(deps: TriggerDeps, spec: TriggerSpec): Promise<
? (destinationIsHome && homeAccess.ok) || (await destinationVisible(deps, actorId, spec.destination))
: true;
const notVisibleNote = "destination is no longer visible to the cron owner — delivery skipped";
- const requiredRecipient = consentRequiredRecipient({
- owner: spec.owner,
- standing: spec.recipientConsentRequired === true,
- destination: spec.destination,
- });
- const consented = recipientConsentSatisfied(spec, requiredRecipient);
- const consentNote =
- spec.recipientConsent?.status === "declined"
- ? "recipient turned this delivery off — skipped"
- : "awaiting the recipient's consent — delivery skipped";
- const liveDelivery = spec.surface === "monitor" && Boolean(spec.destination) && consented && deliverable;
+ const liveDelivery = spec.surface === "monitor" && Boolean(spec.destination) && deliverable;
let status: TurnResult["status"] | undefined;
let note: string | undefined;
let userNote: string | undefined;
let reply: string | undefined;
let sessionId: string | undefined;
- const ownerSkipNotice = async () => {
- if (runsAsScope) return;
- await deps.deliveries.enqueue({
- destination: principalDestination(spec.owner, spec.owner),
- text: `Scheduled delivery skipped: ${consentNote}`,
- idempotencyKey: `${spec.fireKey}:err`,
- provenance: deliveryProvenance(spec, threadRef),
- ...(spec.shadow ? { shadow: true } : {}),
- });
- };
let deferred = false;
const ran = await deps.idempotency
.once(spec.fireKey, async () => {
@@ -293,12 +269,6 @@ export async function runTrigger(deps: TriggerDeps, spec: TriggerSpec): Promise<
if (spec.message !== undefined) {
status = "ok";
if (!spec.destination) return;
- if (!consented) {
- status = "refused";
- note = consentNote;
- await ownerSkipNotice();
- return;
- }
if (!deliverable) {
status = "refused";
note = notVisibleNote;
@@ -358,12 +328,6 @@ export async function runTrigger(deps: TriggerDeps, spec: TriggerSpec): Promise<
if (res.status === "ok" && (res.reply || res.attachments?.length)) {
if (!spec.destination) return;
if (liveDelivery) return;
- if (!consented) {
- status = "refused";
- note = consentNote;
- await ownerSkipNotice();
- return;
- }
if (!deliverable) {
status = "refused";
note = notVisibleNote;
@@ -403,7 +367,7 @@ export async function runTrigger(deps: TriggerDeps, spec: TriggerSpec): Promise<
...(sessionId ? { sessionId } : {}),
};
- if (spec.errorNotice && spec.destination && consented && deliverable && isTriggerFailure(outcome)) {
+ if (spec.errorNotice && spec.destination && deliverable && isTriggerFailure(outcome)) {
await deps.deliveries.enqueue({
destination: spec.destination,
text: spec.errorNotice(userNote ?? note ?? status!),
diff --git a/src/triggers/trigger-store.ts b/src/triggers/trigger-store.ts
index 4eb193392..4b4f9feda 100644
--- a/src/triggers/trigger-store.ts
+++ b/src/triggers/trigger-store.ts
@@ -1,4 +1,4 @@
-import type { Destination, RecipientConsent, ScopeId, TriggerBase } from "../types.ts";
+import type { Destination, ScopeId, TriggerBase } from "../types.ts";
import type { DurableMap } from "../persistence/durable-map.ts";
import { samePerson } from "../directory/person.ts";
import { canonicalJson } from "../util/objects.ts";
@@ -9,38 +9,6 @@ export interface CreateTriggerInput {
createdBy: string;
destination?: Destination;
ownerConsentedAt?: number;
- recipientConsent?: RecipientConsent;
-}
-
-export function consentRequiredRecipient(input: {
- owner: string;
- standing: boolean;
- destination?: Destination;
-}): string | undefined {
- if (!input.standing) return undefined;
- const d = input.destination;
- return d?.type === "principal" && !samePerson(d.target, input.owner) ? d.target : undefined;
-}
-
-export function recipientConsentSatisfied(
- input: { recipientConsent?: RecipientConsent },
- requiredRecipient?: string,
-): boolean {
- if (!requiredRecipient) return input.recipientConsent === undefined || input.recipientConsent.status === "accepted";
- return (
- input.recipientConsent?.status === "accepted" && samePerson(input.recipientConsent.recipientId, requiredRecipient)
- );
-}
-
-export function decideRecipientConsent(
- current: RecipientConsent | undefined,
- actorId: string,
- decision: "accept" | "decline",
- now: number,
-): { ok: true; consent: RecipientConsent } | { ok: false; reason: "no_consent" | "not_recipient" } {
- if (!current) return { ok: false, reason: "no_consent" };
- if (!samePerson(current.recipientId, actorId)) return { ok: false, reason: "not_recipient" };
- return { ok: true, consent: { ...current, status: decision === "accept" ? "accepted" : "declined", decidedAt: now } };
}
export function contentPart(value: unknown): string {
@@ -71,7 +39,6 @@ export function buildTriggerBase(input: CreateTriggerInput, id: string, createdA
createdAt,
...(input.destination ? { destination: input.destination } : {}),
...(input.ownerConsentedAt ? { ownerConsentedAt: input.ownerConsentedAt } : {}),
- ...(input.recipientConsent ? { recipientConsent: input.recipientConsent } : {}),
};
}
@@ -83,10 +50,10 @@ export async function setTriggerEnabled<T extends TriggerBase>(
await backing.merge(id, { enabled } as Partial<T>);
}
-export async function setTriggerRecipientConsent<T extends TriggerBase>(
- backing: DurableMap<T>,
- id: string,
- recipientConsent: RecipientConsent,
-): Promise<void> {
- await backing.merge(id, { recipientConsent } as Partial<T>);
-}
+export const DROP_RECIPIENT_CONSENT_MIGRATION = {
+ id: "durable-map/triggers/0001-drop-recipient-consent",
+ statements: ["crons", "webhooks", "loops"].flatMap((table) => [
+ `CREATE TABLE IF NOT EXISTS ${table} (id TEXT PRIMARY KEY, json JSONB NOT NULL)`,
+ `UPDATE ${table} SET json = json - 'recipientConsent' WHERE json ? 'recipientConsent'`,
+ ]),
+};
diff --git a/src/types.ts b/src/types.ts
index 40f7db19c..452f4e28b 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -191,12 +191,6 @@ export interface GrantedHandle {
permission: Permission;
}
-export interface RecipientConsent {
- recipientId: string;
- status: "pending" | "accepted" | "declined";
- decidedAt?: number;
-}
-
export interface TriggerBase {
id: string;
ownerScopeId: ScopeId;
@@ -207,7 +201,6 @@ export interface TriggerBase {
enabled: boolean;
createdAt: number;
lastFiredAt?: number;
- recipientConsent?: RecipientConsent;
}
export interface Destination {
diff --git a/src/webhooks/webhook-receiver.ts b/src/webhooks/webhook-receiver.ts
index b6820351e..32ff5ac6c 100644
--- a/src/webhooks/webhook-receiver.ts
+++ b/src/webhooks/webhook-receiver.ts
@@ -76,6 +76,7 @@ export function createWebhookReceiver(deps: WebhookReceiverDeps): WebhookReceive
run: deps.run,
...(deps.directory ? { directory: deps.directory } : {}),
...(deps.currentScopeMembers ? { currentScopeMembers: deps.currentScopeMembers } : {}),
+ ...(deps.resolveRecipient ? { resolveRecipient: deps.resolveRecipient } : {}),
};
return {
@@ -120,8 +121,6 @@ export function createWebhookReceiver(deps: WebhookReceiverDeps): WebhookReceive
fireKey,
surface: "webhook",
...(destination ? { destination } : {}),
- recipientConsentRequired: true,
- ...(wh.recipientConsent ? { recipientConsent: wh.recipientConsent } : {}),
errorNotice: (s) => `⚠️ Webhook did not complete: ${s}`,
})
.then(async (outcome) => {
diff --git a/src/webhooks/webhook-store.ts b/src/webhooks/webhook-store.ts
index af1376fca..5c6d3bb17 100644
--- a/src/webhooks/webhook-store.ts
+++ b/src/webhooks/webhook-store.ts
@@ -1,4 +1,4 @@
-import type { RecipientConsent, Webhook } from "../types.ts";
+import type { Webhook } from "../types.ts";
import { createMemoryMap, type DurableMap } from "../persistence/durable-map.ts";
import {
assertNoEscalation,
@@ -6,7 +6,6 @@ import {
contentPart,
createDeduped,
setTriggerEnabled,
- setTriggerRecipientConsent,
type CreateTriggerInput,
} from "../triggers/trigger-store.ts";
import { hashId } from "../util/crypto.ts";
@@ -36,7 +35,6 @@ export interface WebhookStore {
list(): Promise<Webhook[]>;
setEnabled(id: string, enabled: boolean): Promise<void>;
update(id: string, patch: { action: string }): Promise<Webhook | null>;
- setRecipientConsent(id: string, recipientConsent: RecipientConsent): Promise<void>;
recordFire(id: string, info: { at: number; deliveryId?: string; error?: string }): Promise<void>;
}
@@ -106,9 +104,6 @@ export function createWebhookStore(
update(id, patch) {
return backing.merge(id, { action: patch.action });
},
- setRecipientConsent(id, recipientConsent) {
- return setTriggerRecipientConsent(backing, id, recipientConsent);
- },
async recordFire(id, info) {
await backing.merge(id, {
lastFiredAt: info.at,
diff --git a/src/wiring.ts b/src/wiring.ts
index c071cc1ca..2e0843262 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -158,6 +158,7 @@ import { createBudgetTracker, estimateCostUsd } from "./ratelimit/budget.ts";
import type { SecurityScreenProbe } from "./security/security-screener.ts";
import { createPostgresBudgetTracker } from "./ratelimit/postgres-budget.ts";
import { createCronStore, DROP_RUN_AS_MIGRATION, type CronStore } from "./cron/cron-store.ts";
+import { DROP_RECIPIENT_CONSENT_MIGRATION } from "./triggers/trigger-store.ts";
import { LEGACY_HARNESS_MIGRATION } from "./model/legacy-harness-migration.ts";
import { createMemoryCronFireStore, createPostgresCronFireStore } from "./cron/fire-store.ts";
import { createLoopStore } from "./loops/loop-store.ts";
@@ -1955,6 +1956,7 @@ export function buildApp(
},
};
pgArtifactMap?.pool.registerMigration(DROP_RUN_AS_MIGRATION);
+ pgArtifactMap?.pool.registerMigration(DROP_RECIPIENT_CONSENT_MIGRATION);
pgArtifactMap?.pool.registerMigration({
id: "durable-map/turn_wall_clock_configs/0002-drop",
statements: [
@@ -2547,6 +2549,7 @@ export function buildApp(
orchestratorDeps.channelPolicy = channelPolicy;
orchestratorDeps.surfaceCache = surfaceCache;
orchestratorDeps.slackContextSource = config.slackContextSource ?? "live";
+ const resolveRecipient = (query: string) => app.resolveRecipient(query);
const askResolution = keychain
? (ask: KeychainAsk, grant?: KeychainGrant) =>
fireAskResolution(
@@ -2558,6 +2561,7 @@ export function buildApp(
directory,
currentScopeMembers,
sessions,
+ resolveRecipient,
getCron: (id) => crons.get(id),
getAsk: (id) => keychain.getAsk(id),
getGrant: (id) => keychain.getGrant(id),
@@ -2568,7 +2572,10 @@ export function buildApp(
: undefined;
const dropResolution = keychain
? (drop: DropResolution) =>
- fireDropResolution({ deliveries, idempotency, identity, run: (req) => app.turn(req), directory }, drop)
+ fireDropResolution(
+ { deliveries, idempotency, identity, run: (req) => app.turn(req), directory, resolveRecipient },
+ drop,
+ )
: undefined;
const loopFire: LoopFireService = createLoopFireService({
admittedWork,
@@ -2588,6 +2595,7 @@ export function buildApp(
directory,
currentScopeMembers,
sessions,
+ resolveRecipient,
},
});
const loopIngress = createLoopIngress({
@@ -2639,6 +2647,7 @@ export function buildApp(
directory,
currentScopeMembers,
sessions,
+ resolveRecipient,
fireLoop: (loopId, fireKey, cronId) => loopFire.fire(loopId, fireKey, cronId),
...(config.databaseUrl
? { jobQueue: createPgBossCronQueue(config.databaseUrl, undefined, config.cronFireConcurrency) }
@@ -2711,6 +2720,7 @@ export function buildApp(
directory,
currentScopeMembers,
sessions,
+ resolveRecipient,
leaderLease,
onProcessExit: finishCredentials,
heartbeatMs: config.monitorHeartbeatMs,
@@ -2730,6 +2740,7 @@ export function buildApp(
run: (req) => app.turn(req),
directory,
currentScopeMembers,
+ resolveRecipient,
});
const backgroundOwnership: BackgroundOwnershipControl | undefined = config.backgroundDeploymentId
? {
diff --git a/test/control-service.test.ts b/test/control-service.test.ts
index 164a789de..15e5d4e83 100644
--- a/test/control-service.test.ts
+++ b/test/control-service.test.ts
@@ -10,6 +10,7 @@ import { createControlService, type ControlService } from "../src/api/control-se
import { scopeId, type ScopeId } from "../src/types.ts";
import { CAPABILITY_TTL_MS, type CapabilityClaims } from "../src/auth/capability-token.ts";
import { testConfig } from "./support/test-config.ts";
+import { runNowSettled } from "./support/settle.ts";
const SECRET = "control-service-test";
@@ -288,7 +289,7 @@ test("cron create with `recipient` resolves a teammate by name and runs at the s
assert.equal(r.cron.message, "standup in 5");
});
-test("a RECURRING cron addressed to a teammate starts pending their consent and sends one notice", async () => {
+test("a recurring cron addressed to a teammate targets them directly and sends nothing at creation", async () => {
const { built, control } = setup();
await built.app.upsertDirectory([
{ principalId: "U1", displayName: "Alice", type: "internal" },
@@ -298,33 +299,39 @@ test("a RECURRING cron addressed to a teammate starts pending their consent and
{
title: "daily ping",
schedule: { cron: "0 9 * * *", timezone: "America/Los_Angeles" },
- action: "summarize",
+ text: "standup notes are due",
recipient: "Bob",
},
claims("U1"),
);
assert.ok(r.ok, JSON.stringify(r));
- assert.equal(r.cron.recipientConsent?.recipientId, "U2");
- assert.equal(r.cron.recipientConsent?.status, "pending");
- const notices = await built.deliveries.pending("principal");
- assert.equal(notices.length, 1);
- assert.equal(notices[0]!.destination.target, "U2");
- assert.match(notices[0]!.text, /set up .* to be delivered to you/);
+ assert.equal(r.cron.destination?.target, "U2");
+ assert.equal((await built.deliveries.pending("principal")).length, 0);
});
-test("a one-shot (firstFireAt) teammate DM needs no consent — a single scheduled message, like reach", async () => {
+test("a recurring teammate cron stops delivering once the recipient is no longer an addressable teammate", async () => {
const { built, control } = setup();
await built.app.upsertDirectory([
{ principalId: "U1", displayName: "Alice", type: "internal" },
{ principalId: "U2", displayName: "Bob", type: "internal" },
]);
const r = await control.createCron(
- { schedule: { firstFireAt: Date.now() + 1000 }, text: "ping", recipient: "Bob" },
+ { schedule: { everyMs: 3_600_000 }, text: "standup notes are due", recipient: "Bob" },
claims("U1"),
);
assert.ok(r.ok, JSON.stringify(r));
- assert.equal(r.cron.recipientConsent, undefined);
- assert.equal((await built.deliveries.pending("principal")).length, 0, "no consent notice for a one-shot send");
+ await runNowSettled(built.scheduler, r.cron.id);
+ assert.deepEqual(
+ (await built.deliveries.pending("principal")).map((d) => [d.destination.target, d.text]),
+ [["U2", "standup notes are due"]],
+ );
+ await built.app.upsertDirectory([
+ { principalId: "U1", displayName: "Alice", type: "internal" },
+ { principalId: "U2", displayName: "Bob", type: "guest" },
+ ]);
+ await runNowSettled(built.scheduler, r.cron.id);
+ assert.equal((await built.deliveries.pending("principal")).length, 1);
+ assert.equal((await built.crons.listFires(r.cron.id)).runs.at(-1)?.status, "refused");
});
test("a teammate-addressed cron runs in the OWNER's scope; the recipient is delivery-only (run scope ⊆ owner-accessible)", async () => {
@@ -345,7 +352,6 @@ test("a teammate-addressed cron runs in the OWNER's scope; the recipient is deli
claims("U1", scopeId("channel", "C9")),
);
assert.ok(personal.ok, JSON.stringify(personal));
- assert.equal(personal.cron.recipientConsent, undefined);
});
test("an ambiguous recipient name returns candidates, not a created cron", async () => {
diff --git a/test/cron-credential-resumption.test.ts b/test/cron-credential-resumption.test.ts
index 3715cafb5..b2c5c23d8 100644
--- a/test/cron-credential-resumption.test.ts
+++ b/test/cron-credential-resumption.test.ts
@@ -5,9 +5,8 @@ import { createDeliveryStore } from "../src/delivery/delivery-store.ts";
import { createIdempotencyStore } from "../src/idempotency/idempotency-store.ts";
import { createIdentityService } from "../src/identity/identity-service.ts";
import { fireAskResolution, type AskResolutionDeps } from "../src/triggers/keychain-ask.ts";
-import { runTrigger } from "../src/triggers/run-trigger.ts";
import type { KeychainAsk } from "../src/credentials/keychain.ts";
-import type { Cron, Destination, RecipientConsent, TurnRequest } from "../src/types.ts";
+import type { Cron, Destination, TurnRequest } from "../src/types.ts";
const recipient: Destination = {
type: "principal",
@@ -16,7 +15,7 @@ const recipient: Destination = {
onBehalfOf: "U_ALICE",
};
-async function fixture(consent?: RecipientConsent) {
+async function fixture() {
const crons = createCronStore();
const cron = await crons.create({
owner: "U_ALICE",
@@ -25,7 +24,6 @@ async function fixture(consent?: RecipientConsent) {
schedule: { everyMs: 60_000 },
action: "read the dummy account and report the result",
destination: recipient,
- ...(consent ? { recipientConsent: consent } : {}),
});
const deliveries = createDeliveryStore();
const requests: TurnRequest[] = [];
@@ -57,45 +55,8 @@ async function fixture(consent?: RecipientConsent) {
return { crons, cron, deps, ask, deliveries, requests };
}
-for (const status of [undefined, "pending", "declined"] as const) {
- test(`cron credential approval cannot deliver without recipient consent (${status ?? "missing"})`, async () => {
- const f = await fixture(status ? { recipientId: "U_BOB", status } : undefined);
- await runTrigger(f.deps, {
- owner: f.cron.owner,
- ownerScopeId: f.cron.ownerScopeId,
- input: f.cron.action!,
- fireKey: "original-cron-fire",
- surface: "cron",
- threadRef: f.ask.requesterThreadRef,
- destination: recipient,
- recipientConsentRequired: true,
- ...(f.cron.recipientConsent ? { recipientConsent: f.cron.recipientConsent } : {}),
- });
- assert.equal((await f.deliveries.pending("principal")).filter((d) => d.destination.target === "U_BOB").length, 0);
-
- await fireAskResolution(f.deps, f.ask);
-
- const pending = await f.deliveries.pending("principal");
- assert.equal(pending.filter((d) => d.destination.target === "U_BOB").length, 0);
- assert.equal(pending.filter((d) => d.idempotencyKey?.endsWith(":fallback")).length, 0);
- });
-}
-
-test("cron credential approval rechecks consent revoked while the ask was pending", async () => {
- const f = await fixture({ recipientId: "U_BOB", status: "accepted" });
- await f.crons.setRecipientConsent(f.cron.id, {
- recipientId: "U_BOB",
- status: "declined",
- decidedAt: Date.now(),
- });
-
- await fireAskResolution(f.deps, f.ask);
-
- assert.equal((await f.deliveries.pending("principal")).filter((d) => d.destination.target === "U_BOB").length, 0);
-});
-
-test("cron credential approval resumes the original fire once and delivers to the current consented destination", async () => {
- const f = await fixture({ recipientId: "U_BOB", status: "accepted" });
+test("cron credential approval resumes the original fire once and delivers to the current destination", async () => {
+ const f = await fixture();
const destination: Destination = {
type: "principal",
target: "U_CAROL",
@@ -103,7 +64,6 @@ test("cron credential approval resumes the original fire once and delivers to th
onBehalfOf: "U_ALICE",
};
await f.crons.setDestination(f.cron.id, destination);
- await f.crons.setRecipientConsent(f.cron.id, { recipientId: "U_CAROL", status: "accepted" });
await f.crons.update(f.cron.id, { unattendedGrants: ["allowed-job-grant"] });
await fireAskResolution(f.deps, f.ask);
@@ -127,7 +87,7 @@ test("cron credential approval resumes the original fire once and delivers to th
for (const changed of ["missing", "archived", "scope", "owner"] as const) {
test(`cron credential approval fails closed when the original cron is ${changed}`, async () => {
- const f = await fixture({ recipientId: "U_BOB", status: "accepted" });
+ const f = await fixture();
if (changed === "missing") await f.crons.delete(f.cron.id);
else if (changed === "archived") await f.crons.update(f.cron.id, { archived: true });
else {
@@ -147,7 +107,7 @@ for (const changed of ["missing", "archived", "scope", "owner"] as const) {
}
test("cron credential approval fails closed when no cron lookup is available", async () => {
- const f = await fixture({ recipientId: "U_BOB", status: "accepted" });
+ const f = await fixture();
delete f.deps.getCron;
const outcome = await fireAskResolution(f.deps, f.ask);
@@ -158,7 +118,7 @@ test("cron credential approval fails closed when no cron lookup is available", a
});
test("cron credential approval does not restore a removed delivery destination", async () => {
- const f = await fixture({ recipientId: "U_BOB", status: "accepted" });
+ const f = await fixture();
await f.crons.setDestination(f.cron.id, undefined);
await fireAskResolution(f.deps, f.ask);
@@ -170,7 +130,7 @@ test("cron credential approval does not restore a removed delivery destination",
for (const schedule of [{ everyMs: 60_000 }, { cron: "0 9 * * *", timezone: "UTC" }]) {
test(`cron credential approval does not resume a paused recurring job (${JSON.stringify(schedule)})`, async () => {
- const f = await fixture({ recipientId: "U_BOB", status: "accepted" });
+ const f = await fixture();
await f.crons.update(f.cron.id, { schedule });
await f.crons.setEnabled(f.cron.id, false);
@@ -183,7 +143,7 @@ for (const schedule of [{ everyMs: 60_000 }, { cron: "0 9 * * *", timezone: "UTC
}
test("cron credential approval resumes a disabled one-shot job in its original fire", async () => {
- const f = await fixture({ recipientId: "U_BOB", status: "accepted" });
+ const f = await fixture();
await f.crons.update(f.cron.id, { schedule: { firstFireAt: Date.now() + 60_000 } });
await f.crons.setEnabled(f.cron.id, false);
diff --git a/test/cron-credential-retry.test.ts b/test/cron-credential-retry.test.ts
index 218de4491..8aedc3b28 100644
--- a/test/cron-credential-retry.test.ts
+++ b/test/cron-credential-retry.test.ts
@@ -25,7 +25,6 @@ async function fixture(run: (request: TurnRequest) => Promise<TurnResult>) {
audienceScopeId: "personal:U_BOB",
onBehalfOf: "U_ALICE",
},
- recipientConsent: { recipientId: "U_BOB", status: "declined" },
});
const deliveries = createDeliveryStore();
const idempotency = createIdempotencyStore();
@@ -62,7 +61,6 @@ test("busy cron credential resolution leaves its fire retryable and resumes exac
? { status: "refused", refusalKind: "session_busy", reason: "conversation is busy" }
: { status: "ok", reply: "dummy scheduled result" };
});
- await f.crons.setRecipientConsent(f.cron.id, { recipientId: "U_BOB", status: "accepted" });
const fireKey = `ask:${f.ask.id}:approved`;
await assert.rejects(fireAskResolution(f.deps, f.ask));
@@ -85,7 +83,7 @@ test("busy cron credential resolution leaves its fire retryable and resumes exac
assert.equal(pending[0]!.text, "dummy scheduled result");
});
-test("failed cron credential resolution notifies only the owner even when its recipient declined delivery", async () => {
+test("failed cron credential resolution notifies only the owner", async () => {
let runs = 0;
const f = await fixture(async () => {
runs++;
@@ -115,7 +113,6 @@ test("a concurrent sweep cannot mark an in-flight busy resume notified before it
entered.resolve();
return release.promise;
});
- await f.crons.setRecipientConsent(f.cron.id, { recipientId: "U_BOB", status: "accepted" });
const asks = createMemoryMap<KeychainAsk>();
await asks.put(f.ask.id, f.ask);
const keychain = createKeychain({
diff --git a/test/cron-scheduler.test.ts b/test/cron-scheduler.test.ts
index d6e103c34..e48ccc34b 100644
--- a/test/cron-scheduler.test.ts
+++ b/test/cron-scheduler.test.ts
@@ -278,7 +278,6 @@ test("a personal cron with a principal destination delivers its real output to t
audienceScopeId: scopeId("personal", "U-alice"),
onBehalfOf: "U1",
},
- recipientConsent: { recipientId: "U-alice", status: "accepted" },
});
await runNowSettled(scheduler, cron.id);
assert.equal(calls[0]?.conversation.kind, "dm");
@@ -293,11 +292,11 @@ test("a personal cron with a principal destination delivers its real output to t
assert.equal(pending[0]?.text, "CRON-OUTPUT-XYZ");
});
-test("a recurring teammate-DM cron without current recipient consent is withheld", async () => {
- const { crons, deliveries, scheduler } = harness();
+test("a recurring verbatim reminder to a teammate delivers to the teammate", async () => {
+ const { crons, deliveries, calls, scheduler } = harness();
const cron = await crons.create({
- schedule: { everyMs: 1000 },
- action: "let Alice know the deploy is done",
+ schedule: { cron: "0 9 * * *", timezone: "America/Los_Angeles" },
+ message: "daily standup notes are due",
owner: "U1",
createdBy: "U1",
ownerScopeId: scopeId("personal", "U1"),
@@ -309,13 +308,13 @@ test("a recurring teammate-DM cron without current recipient consent is withheld
},
});
await runNowSettled(scheduler, cron.id);
+ assert.equal(calls.length, 0);
const pending = await deliveries.pending("principal");
assert.equal(pending.length, 1);
- assert.equal(pending[0]?.destination.target, "U1");
- assert.match(pending[0]?.text ?? "", /consent.*skipped/i);
+ assert.equal(pending[0]?.destination.target, "U-alice");
+ assert.equal(pending[0]?.text, "daily standup notes are due");
const { runs: stored } = await crons.listFires(cron.id);
- assert.equal(stored[0]?.status, "refused");
- assert.match(stored[0]?.note ?? "", /consent/);
+ assert.equal(stored[0]?.status, "ok");
});
test("a teammate-DM cron created in a channel delivers its real output (§10 parity gate)", async () => {
@@ -332,7 +331,6 @@ test("a teammate-DM cron created in a channel delivers its real output (§10 par
audienceScopeId: scopeId("personal", "U-alice"),
onBehalfOf: "U1",
},
- recipientConsent: { recipientId: "U-alice", status: "accepted" },
});
await runNowSettled(scheduler, cron.id);
assert.equal((await deliveries.pending("principal"))[0]?.text, "CRON-OUTPUT-XYZ");
diff --git a/test/delivery-store-contract.ts b/test/delivery-store-contract.ts
index c46b3a764..04bc1b2e3 100644
--- a/test/delivery-store-contract.ts
+++ b/test/delivery-store-contract.ts
@@ -317,25 +317,25 @@ export async function exerciseDeliveryExpiryRevive(
): Promise<void> {
const store = makeStore({ maxAgeMs: 300 });
- const consent = await store.enqueue({
+ const notice = await store.enqueue({
destination: { type: "slack", target: "C-gone" },
- text: "please approve this cron",
- idempotencyKey: "consent-notice:trigger-1",
+ text: "scheduled notice",
+ idempotencyKey: "notice:trigger-1",
provenance: {
trigger: "cron",
surface: "cron",
- fireKey: "consent-notice:trigger-1",
+ fireKey: "notice:trigger-1",
sourceScopeId: "personal:U-owner",
sourceThreadRef: "agent:main:cron:t1",
- sourceSessionId: "consent-session",
+ sourceSessionId: "notice-session",
},
});
await new Promise((r) => setTimeout(r, 400));
assert.deepEqual(await store.claimPending("slack", 60_000), [], "the overaged notice is swept, not handed out");
- assert.ok(((await store.get(consent.id))?.expiredAt ?? 0) > 0);
+ assert.ok(((await store.get(notice.id))?.expiredAt ?? 0) > 0);
assert.equal(
- (await store.sentCountsBySourceSessions([{ sessionId: "consent-session", threadRef: "agent:main:cron:t1" }])).get(
- "consent-session",
+ (await store.sentCountsBySourceSessions([{ sessionId: "notice-session", threadRef: "agent:main:cron:t1" }])).get(
+ "notice-session",
),
undefined,
"dropped rows never count as sent",
@@ -343,10 +343,10 @@ export async function exerciseDeliveryExpiryRevive(
const revived = await store.enqueue({
destination: { type: "slack", target: "C-restored" },
- text: "please approve this cron (retry)",
- idempotencyKey: "consent-notice:trigger-1",
+ text: "scheduled notice (retry)",
+ idempotencyKey: "notice:trigger-1",
});
- assert.equal(revived.id, consent.id, "the once-ever key still owns one row");
+ assert.equal(revived.id, notice.id, "the once-ever key still owns one row");
assert.equal(revived.deliveredAt, null);
assert.equal(revived.expiredAt, undefined, "a dropped once-ever notice re-enqueues instead of deadlocking");
assert.equal(revived.destination.target, "C-restored", "the revived row carries the fresh destination");
@@ -360,7 +360,7 @@ export async function exerciseDeliveryExpiryRevive(
const dedup = await store.enqueue({
destination: { type: "slack", target: "C-x" },
text: "same key after delivery",
- idempotencyKey: "consent-notice:trigger-1",
+ idempotencyKey: "notice:trigger-1",
});
assert.notEqual(dedup.deliveredAt, null, "a delivered key stays a dedup hit — no re-send after success");
diff --git a/test/loop-fire.test.ts b/test/loop-fire.test.ts
index 4da887e0f..7bdcb6b72 100644
--- a/test/loop-fire.test.ts
+++ b/test/loop-fire.test.ts
@@ -5,12 +5,14 @@ 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";
+import type { TriggerDeps } from "../src/triggers/run-trigger.ts";
import { createLoopStore } from "../src/loops/loop-store.ts";
import { createLoopItemLedger } from "../src/loops/item-ledger.ts";
import { createLoopOutputStore } from "../src/loops/output-store.ts";
import { createShipGrantStore } from "../src/loops/ship-grant-store.ts";
import { buildShipGrant } from "../src/loops/ship-gate.ts";
import { createIdempotencyStore } from "../src/idempotency/idempotency-store.ts";
+import { createDirectoryStore } from "../src/directory/directory-store.ts";
import { scopeId, type TurnRequest, type TurnResult } from "../src/types.ts";
function fakeIdentity() {
@@ -43,6 +45,8 @@ function service(
grants?: ReturnType<typeof createShipGrantStore>;
samePerson?: (a: string, b: string) => Promise<boolean>;
triageEnabledFor?: (owner: string) => Promise<boolean>;
+ directory?: ReturnType<typeof createDirectoryStore>;
+ resolveRecipient?: TriggerDeps["resolveRecipient"];
},
) {
const loops = createLoopStore();
@@ -66,6 +70,8 @@ function service(
deliveries: deliveries.store as never,
idempotency,
identity: fakeIdentity() as never,
+ ...(overrides?.directory ? { directory: overrides.directory } : {}),
+ ...(overrides?.resolveRecipient ? { resolveRecipient: overrides.resolveRecipient } : {}),
run: async (req): Promise<TurnResult> => {
const run = async (): Promise<TurnResult> => {
turns.push(req);
@@ -345,6 +351,32 @@ test("the scheduler sweep detects a stale loop that has never fired", async () =
assert.match(s.deliveries.sent[0]!.text, /trigger looks dead/);
});
+test("a stale-loop ping is withheld from a group DM its owner has left", async () => {
+ const directory = createDirectoryStore();
+ await directory.replace([
+ { principalId: "josh", displayName: "Josh", type: "internal" },
+ { principalId: "U2", displayName: "Bob", type: "internal" },
+ ]);
+ await directory.replaceGroups([{ groupId: "G1", principalId: "U2" }]);
+ const s = service(HAPPY, { directory });
+ const loop = await makeLoop(s.loops, {
+ governor: { staleFireMs: 1_000 },
+ destination: { type: "group", target: "G1", audienceScopeId: scopeId("group", "G1") },
+ });
+ await s.fire.sweepStale(loop.createdAt + 1_001);
+ assert.equal(s.deliveries.sent.length, 0);
+});
+
+test("a stale-loop ping still reaches the owner's web conversation", async () => {
+ const s = service(HAPPY, { directory: createDirectoryStore(), resolveRecipient: async () => ({ kind: "none" }) });
+ const loop = await makeLoop(s.loops, {
+ governor: { staleFireMs: 1_000 },
+ destination: { type: "web", target: "web:josh:t1", audienceScopeId: base.ownerScopeId },
+ });
+ await s.fire.sweepStale(loop.createdAt + 1_001);
+ assert.equal(s.deliveries.sent.length, 1);
+});
+
test("review saturation pings once and recovers after outputs drain", async () => {
const s = service(HAPPY);
const loop = await makeLoop(s.loops, {
diff --git a/test/orchestrator.test.ts b/test/orchestrator.test.ts
index cfd1a8f7e..e532a1ef2 100644
--- a/test/orchestrator.test.ts
+++ b/test/orchestrator.test.ts
@@ -300,6 +300,10 @@ test("a silent cron source run stays out of normal human chat history", async ()
test("a cron-delivered digest lands as a delivery event with origin, not recipient transcript history", async () => {
const built = freshApp();
+ await built.app.upsertDirectory([
+ { principalId: "U-carol", displayName: "Carol", type: "internal" },
+ { principalId: "U-alice", displayName: "Alice", type: "internal" },
+ ]);
const cron = await built.app.createCron({
schedule: { firstFireAt: Date.now() },
action: "deploy digest ready",
diff --git a/test/postgres-trigger-recipient-consent-migration.test.ts b/test/postgres-trigger-recipient-consent-migration.test.ts
new file mode 100644
index 000000000..d78887569
--- /dev/null
+++ b/test/postgres-trigger-recipient-consent-migration.test.ts
@@ -0,0 +1,48 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { DROP_RECIPIENT_CONSENT_MIGRATION } from "../src/triggers/trigger-store.ts";
+
+const URL = process.env.DATABASE_URL;
+const skip = URL ? false : "set DATABASE_URL (a Postgres) to run the recipient-consent migration test";
+
+test(
+ "dropping recipient consent strips the field from crons, webhooks and loops and keeps the rest",
+ { skip },
+ async () => {
+ const pg = (await import("pg")).default;
+ const pool = new pg.Pool({ connectionString: URL });
+ const tables = ["crons", "webhooks", "loops"];
+ try {
+ await pool.query(`DROP TABLE IF EXISTS ${tables.join(", ")}`);
+ for (const table of tables) {
+ await pool.query(`CREATE TABLE ${table} (id TEXT PRIMARY KEY, json JSONB NOT NULL)`);
+ await pool.query(`INSERT INTO ${table} (id, json) VALUES ('pending', $1), ('plain', $2)`, [
+ JSON.stringify({
+ id: "pending",
+ enabled: true,
+ destination: { type: "principal", target: "U2" },
+ recipientConsent: { recipientId: "U2", status: "pending" },
+ }),
+ JSON.stringify({ id: "plain", enabled: true }),
+ ]);
+ }
+
+ for (const run of [1, 2]) {
+ for (const sql of DROP_RECIPIENT_CONSENT_MIGRATION.statements) await pool.query(sql);
+ for (const table of tables) {
+ const rows = Object.fromEntries(
+ (await pool.query(`SELECT id, json FROM ${table}`)).rows.map((row) => [row.id, row.json]),
+ );
+ assert.deepEqual(
+ rows.pending,
+ { id: "pending", enabled: true, destination: { type: "principal", target: "U2" } },
+ `${table} run ${run}`,
+ );
+ assert.deepEqual(rows.plain, { id: "plain", enabled: true }, `${table} run ${run}`);
+ }
+ }
+ } finally {
+ await pool.end();
+ }
+ },
+);
diff --git a/test/public-architecture-docs.test.ts b/test/public-architecture-docs.test.ts
index edfe26bb6..f5e7c80b5 100644
--- a/test/public-architecture-docs.test.ts
+++ b/test/public-architecture-docs.test.ts
@@ -57,7 +57,6 @@ test("Strict posture describes its approval gate, exemptions, and direct-mutatio
server,
/pathname === "\/v1\/surface-context".*pathname === "\/v1\/memory\/search".*pathname\.startsWith\("\/v1\/run-signals\/"\)/s,
);
- assert.match(server, /decision === "decline"/);
assert.doesNotMatch(server, /Strict posture permits observation only/);
assert.doesNotMatch(adminUi, /every tool call/i);
});
diff --git a/test/shared-credential-resumption.test.ts b/test/shared-credential-resumption.test.ts
index 2a88ae153..3b204c360 100644
--- a/test/shared-credential-resumption.test.ts
+++ b/test/shared-credential-resumption.test.ts
@@ -44,7 +44,6 @@ async function fixture(scope: ScopeId = "channel:C_SHARED") {
audienceScopeId: "personal:U_REQUESTER",
onBehalfOf: "U_JOB_OWNER",
},
- recipientConsent: { recipientId: "U_REQUESTER", status: "accepted" },
});
const state: { members: Principal[] } = { members: [{ id: "U_REQUESTER", type: "internal" }] };
const requests: TurnRequest[] = [];
@@ -68,7 +67,6 @@ async function fixture(scope: ScopeId = "channel:C_SHARED") {
fireKey: "original-fire",
threadRef,
surface: "cron",
- recipientConsentRequired: true,
});
assert.equal(requests.length, 1);
assert.equal(requests[0]!.actor.externalId, `system:${scope}`);
@@ -130,17 +128,6 @@ for (const scope of ["channel:C_SHARED", "group:G_SHARED", "group:web-project-sh
});
}
-test("a scope approval still needs recipient consent for delivery", async () => {
- const f = await fixture();
- await f.crons.setRecipientConsent(f.cron.id, { recipientId: "U_REQUESTER", status: "declined" });
-
- const outcome = await fireAskResolution(f.deps, f.ask);
-
- assert.equal(outcome.status, "refused");
- assert.equal(f.requests.length, 1);
- assert.equal((await f.deliveries.pending("principal")).length, 0, "nobody's DM gets a conversation-owned notice");
-});
-
for (const scope of ["channel:C_SHARED", "group:G_SHARED", "group:web-project-shared"] as const) {
test(`shared asks in ${scope} deduplicate by job across actors and keep live requests separate`, async () => {
let now = 1_000_000;
diff --git a/test/trigger-consent.test.ts b/test/trigger-consent.test.ts
deleted file mode 100644
index 7b5a3dbba..000000000
--- a/test/trigger-consent.test.ts
+++ /dev/null
@@ -1,211 +0,0 @@
-import { describe, it } from "node:test";
-import assert from "node:assert/strict";
-import { runTrigger, type TriggerDeps } from "../src/triggers/run-trigger.ts";
-import {
- consentRequiredRecipient,
- recipientConsentSatisfied,
- decideRecipientConsent,
-} from "../src/triggers/trigger-store.ts";
-import { createDeliveryStore } from "../src/delivery/delivery-store.ts";
-import { createIdempotencyStore } from "../src/idempotency/idempotency-store.ts";
-import { createIdentityService } from "../src/identity/identity-service.ts";
-import { createMemoryMap } from "../src/persistence/durable-map.ts";
-import { scopeId, type Destination, type RecipientConsent, type TurnRequest, type TurnResult } from "../src/types.ts";
-
-describe("consentRequiredRecipient: who must consent before a standing delivery starts", () => {
- const dm = (target: string): Destination => ({
- type: "principal",
- target,
- audienceScopeId: scopeId("personal", target),
- onBehalfOf: "U-carol",
- });
-
- it("a standing delivery to a teammate's DM needs that teammate's consent", () => {
- assert.equal(consentRequiredRecipient({ owner: "U-carol", standing: true, destination: dm("U-alice") }), "U-alice");
- });
- it("DMing yourself needs no consent (it's your own inbox)", () => {
- assert.equal(consentRequiredRecipient({ owner: "U-carol", standing: true, destination: dm("U-carol") }), undefined);
- });
- it("a one-shot send needs no consent (a single message, like reach send-now)", () => {
- assert.equal(
- consentRequiredRecipient({ owner: "U-carol", standing: false, destination: dm("U-alice") }),
- undefined,
- );
- });
- it("a channel destination needs no recipient consent (parity-gated, not a private inbox)", () => {
- assert.equal(
- consentRequiredRecipient({ owner: "U-carol", standing: true, destination: { type: "slack", target: "C-eng" } }),
- undefined,
- );
- });
-});
-
-describe("recipientConsentSatisfied: the fire-time gate (record present ⇒ must be accepted)", () => {
- it("no record passes (one-shot / owner / channel / legacy pre-consent crons)", () => {
- assert.equal(recipientConsentSatisfied({}), true);
- });
- it("pending withholds, accepted delivers, declined withholds", () => {
- assert.equal(recipientConsentSatisfied({ recipientConsent: { recipientId: "U-alice", status: "pending" } }), false);
- assert.equal(recipientConsentSatisfied({ recipientConsent: { recipientId: "U-alice", status: "accepted" } }), true);
- assert.equal(
- recipientConsentSatisfied({ recipientConsent: { recipientId: "U-alice", status: "declined" } }),
- false,
- );
- });
-
- it("a required recipient needs an accepted record bound to that person", () => {
- assert.equal(recipientConsentSatisfied({}, "U-alice"), false);
- assert.equal(
- recipientConsentSatisfied({ recipientConsent: { recipientId: "U-bob", status: "accepted" } }, "U-alice"),
- false,
- );
- assert.equal(
- recipientConsentSatisfied({ recipientConsent: { recipientId: "U-alice", status: "accepted" } }, "U-alice"),
- true,
- );
- });
-});
-
-describe("decideRecipientConsent: only the recipient flips their own switch", () => {
- const pending: RecipientConsent = { recipientId: "U-alice", status: "pending" };
- it("the recipient may accept (on) and decline (off)", () => {
- const a = decideRecipientConsent(pending, "U-alice", "accept", 1000);
- assert.ok(a.ok && a.consent.status === "accepted" && a.consent.decidedAt === 1000);
- const d = decideRecipientConsent({ recipientId: "U-alice", status: "accepted" }, "U-alice", "decline", 2000);
- assert.ok(d.ok && d.consent.status === "declined");
- });
- it("a non-recipient (incl. the owner) cannot decide", () => {
- const r = decideRecipientConsent(pending, "U-carol", "accept", 1000);
- assert.ok(!r.ok && r.reason === "not_recipient");
- });
- it("there must be a consent gate to decide on", () => {
- const r = decideRecipientConsent(undefined, "U-alice", "accept", 1000);
- assert.ok(!r.ok && r.reason === "no_consent");
- });
-});
-
-function triggerDeps(run: (req: TurnRequest) => Promise<TurnResult>): TriggerDeps {
- return {
- deliveries: createDeliveryStore(),
- idempotency: createIdempotencyStore(createMemoryMap()),
- identity: createIdentityService(),
- run,
- };
-}
-
-describe("runTrigger: recipient-consent gate", () => {
- const toAlice: Destination = {
- type: "principal",
- target: "U-alice",
- audienceScopeId: scopeId("personal", "U-alice"),
- onBehalfOf: "U-carol",
- };
-
- it("withholds a composed delivery while the recipient hasn't accepted", async () => {
- const deps = triggerDeps(async () => ({ status: "ok", reply: "your digest" }));
- const out = await runTrigger(deps, {
- owner: "U-carol",
- ownerScopeId: scopeId("personal", "U-carol"),
- input: "compose",
- fireKey: "c1",
- surface: "cron",
- destination: toAlice,
- recipientConsent: { recipientId: "U-alice", status: "pending" },
- });
- assert.equal(
- (await deps.deliveries.pending("principal")).filter((delivery) => delivery.destination.target === "U-alice")
- .length,
- 0,
- "nothing reaches a recipient who hasn't accepted",
- );
- assert.match(out.note ?? "", /consent/);
- });
-
- it("delivers once the recipient has accepted", async () => {
- const deps = triggerDeps(async () => ({ status: "ok", reply: "your digest" }));
- await runTrigger(deps, {
- owner: "U-carol",
- ownerScopeId: scopeId("personal", "U-carol"),
- input: "compose",
- fireKey: "c2",
- surface: "cron",
- destination: toAlice,
- recipientConsent: { recipientId: "U-alice", status: "accepted" },
- });
- assert.equal((await deps.deliveries.pending("principal")).length, 1);
- });
-
- it("a standing teammate-DM with no consent record is withheld", async () => {
- const deps = triggerDeps(async () => ({ status: "ok", reply: "fyi" }));
- await runTrigger(deps, {
- owner: "U-carol",
- ownerScopeId: scopeId("personal", "U-carol"),
- input: "compose",
- fireKey: "c3",
- surface: "cron",
- destination: toAlice,
- recipientConsentRequired: true,
- });
- assert.equal(
- (await deps.deliveries.pending("principal")).filter((delivery) => delivery.destination.target === "U-alice")
- .length,
- 0,
- );
- });
-
- it("accepted consent for a prior recipient does not authorize a retargeted standing DM", async () => {
- const deps = triggerDeps(async () => ({ status: "ok", reply: "fyi" }));
- await runTrigger(deps, {
- owner: "U-carol",
- ownerScopeId: scopeId("personal", "U-carol"),
- input: "compose",
- fireKey: "c3-retarget",
- surface: "cron",
- destination: { ...toAlice, target: "U-bob", audienceScopeId: scopeId("personal", "U-bob") },
- recipientConsent: { recipientId: "U-alice", status: "accepted" },
- recipientConsentRequired: true,
- });
- assert.equal(
- (await deps.deliveries.pending("principal")).filter((delivery) => delivery.destination.target === "U-bob").length,
- 0,
- );
- });
-
- it("an unrelated turn refusal sends no consent notice (nothing was withheld for consent)", async () => {
- const deps = triggerDeps(async () => ({ status: "refused", reason: "runtime not approved" }));
- const out = await runTrigger(deps, {
- owner: "U-carol",
- ownerScopeId: scopeId("personal", "U-carol"),
- input: "compose",
- fireKey: "c-unrelated",
- surface: "cron",
- destination: toAlice,
- recipientConsentRequired: true,
- });
- assert.equal(out.status, "refused");
- assert.doesNotMatch(out.note ?? "", /consent/);
- assert.equal((await deps.deliveries.pending("principal")).length, 0, "no misleading skip notice to anyone");
- });
-
- it("withholds a verbatim relay too (a declined recipient gets nothing)", async () => {
- const deps = triggerDeps(async () => {
- throw new Error("a relay must not re-run a turn");
- });
- const out = await runTrigger(deps, {
- owner: "U-carol",
- ownerScopeId: scopeId("personal", "U-carol"),
- input: "",
- message: "standup in 5",
- fireKey: "c4",
- surface: "cron",
- destination: toAlice,
- recipientConsent: { recipientId: "U-alice", status: "declined" },
- });
- assert.equal(
- (await deps.deliveries.pending("principal")).filter((delivery) => delivery.destination.target === "U-alice")
- .length,
- 0,
- );
- assert.match(out.note ?? "", /turned this delivery off/);
- });
-});
diff --git a/test/webhook-receiver.test.ts b/test/webhook-receiver.test.ts
index 3c2d41944..80655ad39 100644
--- a/test/webhook-receiver.test.ts
+++ b/test/webhook-receiver.test.ts
@@ -253,27 +253,7 @@ test("silent-failure surfacing: a refused turn delivers a notice (the sender alr
assert.match((await webhooks.get(wh.id))?.lastError ?? "", /internal-only/);
});
-test("a third-party principal destination without recipient consent skips delivery and notifies the owner", async () => {
- const { webhooks, deliveries, calls, receiver } = harness();
- const wh = await webhooks.create({
- ownerScopeId: scopeId("personal", "U1"),
- owner: "U1",
- createdBy: "U1",
- action: "x",
- verification: { scheme: "github", secret: SECRET },
- destination: { type: "principal", target: "U2" },
- });
- const out = await receiver.deliver(wh.id, githubReq("{}"));
- assert.equal(out.status, 202);
- await flush();
- assert.equal(calls.length, 1);
- const pending = await deliveries.pending("principal");
- assert.equal(pending.length, 1);
- assert.equal(pending[0]?.destination.target, "U1");
- assert.match(pending[0]?.text ?? "", /consent/i);
-});
-
-test("a third-party principal destination with accepted consent delivers to the recipient", async () => {
+test("a third-party principal destination delivers to the recipient", async () => {
const { webhooks, deliveries, receiver } = harness();
const wh = await webhooks.create({
ownerScopeId: scopeId("personal", "U1"),
@@ -282,7 +262,6 @@ test("a third-party principal destination with accepted consent delivers to the
action: "x",
verification: { scheme: "github", secret: SECRET },
destination: { type: "principal", target: "U2" },
- recipientConsent: { recipientId: "U2", status: "accepted" },
});
await receiver.deliver(wh.id, githubReq("{}"));
await flush();