Multiplayer agent harness for work.
triggers: don't mistake a directory snapshot gap for lost membership (#456)
Regan Bell7b9004a54892
diff --git a/src/cron/scheduler.ts b/src/cron/scheduler.tsindex 333bbbc4a..9e437e382 100644--- a/src/cron/scheduler.ts+++ b/src/cron/scheduler.ts@@ -4,7 +4,7 @@ import type { IdentityService } from "../identity/identity-service.ts";import type { CronStore } from "./cron-store.ts";import type { DeliveryStore } from "../delivery/delivery-store.ts";import type { IdempotencyStore } from "../idempotency/idempotency-store.ts";-import { runTrigger } from "../triggers/run-trigger.ts";+import { runTrigger, type TriggerDeps } from "../triggers/run-trigger.ts";import type { CurrentScopeMembers } from "../resolution/scope-membership.ts";import type { VisibilityDirectory } from "../directory/visibility.ts";import type { DirectoryMember } from "../directory/directory-store.ts";@@ -43,6 +43,7 @@ export interface SchedulerDeps {};sweepAsks?: (now: number) => Promise<void>;jobQueue?: CronJobQueue;+ sessions?: TriggerDeps["sessions"];}function truncate(s: string, maxChars: number): string {@@ -125,6 +126,7 @@ export function createScheduler(deps: SchedulerDeps): Scheduler {run: deps.run,...(deps.directory ? { directory: deps.directory } : {}),...(deps.currentScopeMembers ? { currentScopeMembers: deps.currentScopeMembers } : {}),+ ...(deps.sessions ? { sessions: deps.sessions } : {}),},{owner: cron.owner,diff --git a/src/monitors/monitor-poller.ts b/src/monitors/monitor-poller.tsindex ca8d65307..57b1580c7 100644--- a/src/monitors/monitor-poller.ts+++ b/src/monitors/monitor-poller.ts@@ -36,6 +36,7 @@ export interface MonitorPollerDeps {run: (req: TurnRequest) => Promise<TurnResult>;directory?: TriggerDeps["directory"];currentScopeMembers?: CurrentScopeMembers;+ sessions?: TriggerDeps["sessions"];now?: () => number;maxFiresPerTick?: number;leaderLease?: LeaderLease;@@ -114,6 +115,7 @@ export function createMonitorPoller(deps: MonitorPollerDeps): MonitorPoller {run: deps.run,...(deps.directory ? { directory: deps.directory } : {}),...(deps.currentScopeMembers ? { currentScopeMembers: deps.currentScopeMembers } : {}),+ ...(deps.sessions ? { sessions: deps.sessions } : {}),};async function fire(diff --git a/src/resolution/scope-membership.ts b/src/resolution/scope-membership.tsindex cdf420c32..05593afe9 100644--- a/src/resolution/scope-membership.ts+++ b/src/resolution/scope-membership.ts@@ -126,7 +126,9 @@ export function createCurrentScopeMembers(deps: ScopeMembershipDeps): CurrentSco: null,),);- return included.filter((member): member is Principal => member !== null);+ const present = included.filter((member): member is Principal => member !== null);+ if (kind === "group" && present.length === 0) return undefined;+ return present;};}diff --git a/src/triggers/run-trigger.ts b/src/triggers/run-trigger.tsindex 9da9eae50..b6a14ac12 100644--- a/src/triggers/run-trigger.ts+++ b/src/triggers/run-trigger.ts@@ -18,6 +18,10 @@ import { isVisible, type VisibilityDirectory } from "../directory/visibility.ts"import { samePerson } from "../directory/person.ts";import type { CurrentScopeMembers } from "../resolution/scope-membership.ts";+const MEMBERSHIP_SKIP_NOTE = "the acting person is no longer a member of this trigger's home scope — run skipped";+const UNKNOWN_HOME_SKIP_NOTE =+ "this trigger's home scope is missing from the directory snapshot (roster sync gap) and the acting person has no session there — run skipped";+export interface TriggerDeps {deliveries: DeliveryStore;idempotency: IdempotencyStore;@@ -27,7 +31,9 @@ export interface TriggerDeps {directory?: VisibilityDirectory & {get(principalId: string): Promise<{ displayName: string } | null>;channelPrivacy?(channelId: string): Promise<boolean | undefined>;+ groupMembership?(groupId: string, principalId: string): Promise<boolean | undefined>;};+ sessions?: { listByParticipant(principalId: string): Promise<readonly { scopeId: ScopeId }[]> };}export interface TriggerSpec {@@ -99,20 +105,41 @@ async function relayAttribution(deps: TriggerDeps, spec: TriggerSpec): Promise<sreturn member?.displayName;}+async function participatesInScope(deps: TriggerDeps, actorId: string, scope: ScopeId): Promise<boolean> {+ const sessions = await deps.sessions?.listByParticipant(actorId).catch(() => []);+ return sessions?.some((s) => s.scopeId === scope) === true;+}+async function actorMayReadScope(deps: TriggerDeps,actorId: string,kind: string | null,ref: string,-): Promise<boolean> {- if (!ref) return false;- if (kind === "personal") return samePerson(actorId, ref);- if (!deps.directory) return kind !== "group" && kind !== "channel";- if (kind === "group") return isVisible(deps.directory, actorId, { kind: "group", groupId: ref });- if (kind !== "channel") return true;+ scope: ScopeId,+ snapshotGap: boolean,+): Promise<{ ok: boolean; note?: string }> {+ if (!ref) return { ok: false, note: MEMBERSHIP_SKIP_NOTE };+ if (kind === "personal") return samePerson(actorId, ref) ? { ok: true } : { ok: false, note: MEMBERSHIP_SKIP_NOTE };+ if (!deps.directory)+ return kind !== "group" && kind !== "channel" ? { ok: true } : { ok: false, note: MEMBERSHIP_SKIP_NOTE };+ if (kind === "group") {+ if (await isVisible(deps.directory, actorId, { kind: "group", groupId: ref })) return { ok: true };+ if (snapshotGap) {+ if (await participatesInScope(deps, actorId, scope)) return { ok: true };+ return { ok: false, note: UNKNOWN_HOME_SKIP_NOTE };+ }+ const known = await deps.directory.groupMembership?.(ref, actorId).catch(() => undefined);+ if (known === undefined && (await participatesInScope(deps, actorId, scope))) return { ok: true };+ return { ok: false, note: MEMBERSHIP_SKIP_NOTE };+ }+ if (kind !== "channel") return { ok: true };const isPrivate = await deps.directory.channelPrivacy?.(ref);- if (isPrivate === undefined) return false;- return isVisible(deps.directory, actorId, { kind: "channel", channelId: ref, isPrivate });+ if (isPrivate === undefined) {+ if (await participatesInScope(deps, actorId, scope)) return { ok: true };+ return { ok: false, note: UNKNOWN_HOME_SKIP_NOTE };+ }+ if (await isVisible(deps.directory, actorId, { kind: "channel", channelId: ref, isPrivate })) return { ok: true };+ return { ok: false, note: MEMBERSHIP_SKIP_NOTE };}export async function destinationVisible(@@ -170,7 +197,27 @@ export async function runTrigger(deps: TriggerDeps, spec: TriggerSpec): Promise<conversation = { kind: "group", channelRef: ownerRef, threadRef, ...(audience ? { audience } : {}) };}- const deliverable = spec.destination ? await destinationVisible(deps, actorId, spec.destination) : true;+ let homeAccess: { ok: boolean; note?: string };+ if (currentMembers !== undefined) {+ homeAccess = currentMembers.some((member) => samePerson(member.id, actorId))+ ? { ok: true }+ : { ok: false, note: MEMBERSHIP_SKIP_NOTE };+ } else if (!deps.directory) {+ homeAccess = { ok: true };+ } else {+ homeAccess = await actorMayReadScope(+ deps,+ actorId,+ ownerKind,+ ownerRef,+ spec.ownerScopeId,+ deps.currentScopeMembers !== undefined,+ );+ }+ const destinationIsHome = spec.destination?.audienceScopeId === spec.ownerScopeId;+ const deliverable = spec.destination+ ? (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,@@ -224,12 +271,8 @@ export async function runTrigger(deps: TriggerDeps, spec: TriggerSpec): Promise<});return;}- const canReadHome =- currentMembers === undefined- ? !deps.directory || (await actorMayReadScope(deps, actorId, ownerKind, ownerRef))- : currentMembers.some((member) => samePerson(member.id, actorId));- if (!canReadHome) {- note = "the acting person is no longer a member of this trigger's home scope — run skipped";+ if (!homeAccess.ok) {+ note = homeAccess.note ?? MEMBERSHIP_SKIP_NOTE;return;}const res = await deps.run({diff --git a/src/wiring.ts b/src/wiring.tsindex 83540e3d8..5cbcf493e 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -1266,6 +1266,7 @@ export function buildApp(leaderLease,directory,currentScopeMembers,+ sessions,...(config.databaseUrl? { jobQueue: createPgBossCronQueue(config.databaseUrl, undefined, config.cronFireConcurrency) }: {}),@@ -1287,6 +1288,7 @@ export function buildApp(run: (req) => app.turn(req),directory,currentScopeMembers,+ sessions,leaderLease,heartbeatMs: config.monitorHeartbeatMs,})diff --git a/test/run-trigger-home-scope.test.ts b/test/run-trigger-home-scope.test.tsnew file mode 100644index 000000000..3350d7457--- /dev/null+++ b/test/run-trigger-home-scope.test.ts@@ -0,0 +1,177 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";+import { runTrigger, type TriggerDeps } from "../src/triggers/run-trigger.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 { createCurrentScopeMembers } from "../src/resolution/scope-membership.ts";+import { scopeId, type ScopeId, type TurnRequest, type TurnResult } from "../src/types.ts";++const OWNER = "[email protected]";+const CHAN = "C0PRIVATE";+const SCOPE = scopeId("channel", CHAN);++function unknownChannelDirectory() {+ return {+ channelMember: async (_c: string, _pid: string) => false,+ groupMember: async (_g: string, _pid: string) => false,+ listChannelsFor: async (): Promise<{ channelId: string; name: string }[]> => [],+ channelPrivacy: async (): Promise<boolean | undefined> => undefined,+ list: async () => [{ principalId: OWNER, displayName: "Pete" }],+ get: async () => null,+ };+}++function deps(+ dir: ReturnType<typeof unknownChannelDirectory>,+ opts: { sessions?: TriggerDeps["sessions"]; onRun?: () => void } = {},+): TriggerDeps {+ const run = async (_r: TurnRequest): Promise<TurnResult> => {+ opts.onRun?.();+ return { status: "ok", reply: "posted" };+ };+ return {+ deliveries: createDeliveryStore(),+ idempotency: createIdempotencyStore(createMemoryMap()),+ identity: createIdentityService(),+ run,+ directory: dir,+ currentScopeMembers: createCurrentScopeMembers({ directory: dir }),+ ...(opts.sessions ? { sessions: opts.sessions } : {}),+ };+}++function spec(key: string) {+ return {+ owner: OWNER,+ ownerScopeId: SCOPE,+ input: "check apps",+ fireKey: `cron:home:${key}`,+ surface: "cron",+ destination: { type: "slack" as const, target: CHAN, audienceScopeId: SCOPE },+ };+}++describe("runTrigger home-scope gate when the directory snapshot dropped the channel", () => {+ it("falls back to session participation and runs", async () => {+ let ranTurn = false;+ const sessions = {+ listByParticipant: async (pid: string): Promise<readonly { scopeId: ScopeId }[]> =>+ pid === OWNER ? [{ scopeId: SCOPE }] : [],+ };+ const d = deps(unknownChannelDirectory(), { sessions, onRun: () => (ranTurn = true) });+ const out = await runTrigger(d, spec("participant"));+ assert.equal(ranTurn, true, "a session participant in the home scope keeps running through a roster sync gap");+ assert.equal(out.status, "ok");+ assert.equal(out.note, undefined);+ });++ it("skips with a note naming the snapshot gap, not lost membership, when there is no session either", async () => {+ let ranTurn = false;+ const sessions = { listByParticipant: async (): Promise<readonly { scopeId: ScopeId }[]> => [] };+ const d = deps(unknownChannelDirectory(), { sessions, onRun: () => (ranTurn = true) });+ const out = await runTrigger(d, spec("stranger"));+ assert.equal(ranTurn, false);+ assert.equal(out.authzFailed, false, "skip-not-disable survives");+ assert.match(out.note ?? "", /missing from the directory snapshot/);+ assert.doesNotMatch(out.note ?? "", /no longer a member/);+ });++ it("skips the same way when no session store is wired", async () => {+ let ranTurn = false;+ const d = deps(unknownChannelDirectory(), { onRun: () => (ranTurn = true) });+ const out = await runTrigger(d, spec("no-sessions"));+ assert.equal(ranTurn, false);+ assert.match(out.note ?? "", /missing from the directory snapshot/);+ });++ it("a directory that affirmatively knows the private channel and excludes the actor still skips as lost membership", async () => {+ const dir = {+ ...unknownChannelDirectory(),+ listChannelsFor: async () => [{ channelId: CHAN, name: "private" }],+ channelPrivacy: async (): Promise<boolean | undefined> => true,+ };+ let ranTurn = false;+ const sessions = {+ listByParticipant: async (): Promise<readonly { scopeId: ScopeId }[]> => [{ scopeId: SCOPE }],+ };+ const d = deps(dir, { sessions, onRun: () => (ranTurn = true) });+ const out = await runTrigger(d, spec("kicked"));+ assert.equal(ranTurn, false, "an affirmative roster still wins over session history");+ assert.match(out.note ?? "", /no longer a member/);+ });+});++const GROUP = "G0MPIM";+const GSCOPE = scopeId("group", GROUP);++function groupSpec(key: string) {+ return {+ owner: OWNER,+ ownerScopeId: GSCOPE,+ input: "check apps",+ fireKey: `cron:ghome:${key}`,+ surface: "cron",+ destination: { type: "slack" as const, target: GROUP, audienceScopeId: GSCOPE },+ };+}++describe("runTrigger home-scope gate for group homes", () => {+ it("a group missing from the snapshot falls back to session participation and runs", async () => {+ let ranTurn = false;+ const dir = unknownChannelDirectory();+ const sessions = {+ listByParticipant: async (pid: string): Promise<readonly { scopeId: ScopeId }[]> =>+ pid === OWNER ? [{ scopeId: GSCOPE }] : [],+ };+ const d = deps(dir, { sessions, onRun: () => (ranTurn = true) });+ const out = await runTrigger(d, groupSpec("gap"));+ assert.equal(ranTurn, true);+ assert.equal(out.note, undefined);+ });++ it("a group the snapshot affirmatively knows, excluding the actor, skips as lost membership despite session history", async () => {+ let ranTurn = false;+ const dir = {+ ...unknownChannelDirectory(),+ groupMember: async (_g: string, pid: string) => pid === "[email protected]",+ list: async () => [+ { principalId: OWNER, displayName: "Pete" },+ { principalId: "[email protected]", displayName: "Kim" },+ ],+ };+ const sessions = {+ listByParticipant: async (): Promise<readonly { scopeId: ScopeId }[]> => [{ scopeId: GSCOPE }],+ };+ const d = deps(dir, { sessions, onRun: () => (ranTurn = true) });+ const out = await runTrigger(d, groupSpec("kicked"));+ assert.equal(ranTurn, false, "an affirmative group roster wins over session history");+ assert.match(out.note ?? "", /no longer a member/);+ });++ it("without currentScopeMembers wired, an affirmative tri-state non-membership wins over session history", async () => {+ let ranTurn = false;+ const dir = {+ ...unknownChannelDirectory(),+ groupMembership: async (): Promise<boolean | undefined> => false,+ };+ const sessions = {+ listByParticipant: async (): Promise<readonly { scopeId: ScopeId }[]> => [{ scopeId: GSCOPE }],+ };+ const d: TriggerDeps = {+ deliveries: createDeliveryStore(),+ idempotency: createIdempotencyStore(createMemoryMap()),+ identity: createIdentityService(),+ run: async () => {+ ranTurn = true;+ return { status: "ok", reply: "posted" };+ },+ directory: dir,+ sessions,+ };+ const out = await runTrigger(d, groupSpec("tri-state"));+ assert.equal(ranTurn, false);+ assert.match(out.note ?? "", /no longer a member/);+ });+});