Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Add team scopes behind a feature flag (#1987)

Joshua France242436b9b9f8
diff --git a/package.json b/package.json
index 75dad7683..f69516ff0 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-instance-registry.test.ts test/readiness.test.ts test/postgres-grant-store.test.ts test/postgres-admin-grants.test.ts test/postgres-file-artifact-store.test.ts test/postgres-file-upload-store.test.ts test/postgres-directory-store.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-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/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-instance-registry.test.ts test/readiness.test.ts test/postgres-grant-store.test.ts test/postgres-admin-grants.test.ts test/postgres-teams.test.ts test/postgres-file-artifact-store.test.ts test/postgres-file-upload-store.test.ts test/postgres-directory-store.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-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/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/deps.ts b/src/api/deps.ts
index 5adc39242..94f2393bb 100644
--- a/src/api/deps.ts
+++ b/src/api/deps.ts
@@ -1,3 +1,4 @@
+import type { TeamStore } from "../teams/teams.ts";
import type { ExternalSlackPolicies } from "../resolution/external-slack.ts";
import type { ProviderKeys } from "../harness/pi-harness.ts";
import type { ModelGatewayTransportConfig } from "../model/provider-endpoints.ts";
@@ -121,6 +122,7 @@ export interface ServerDeps {
acl?: AclStore;
credentialUsage?: CredentialUsageSink;
featureFlags?: FeatureFlagStore;
+ teams?: TeamStore;
egressAudit?: EgressAuditSink;
brokerFetch?: BrokerFetch;
gitHttpFetch?: GitHttpFetch;
diff --git a/src/api/routes/admin-resources.ts b/src/api/routes/admin-resources.ts
index f93a62757..3f1a8b81e 100644
--- a/src/api/routes/admin-resources.ts
+++ b/src/api/routes/admin-resources.ts
@@ -1,3 +1,4 @@
+import type { TeamChange } from "../../teams/teams.ts";
import { parseAckEmoji } from "../../slack/config.ts";
import { orgId as configOrgId } from "../../config.ts";
import type { ServerDeps } from "../deps.ts";
@@ -363,6 +364,28 @@ export const ADMIN_RESOURCES: readonly AdminResource[] = [
return { ok: true };
},
},
+ {
+ id: "teams",
+ kind: "custom",
+ target: "org",
+ readKey: "teams",
+ label:
+ "Teams. Each team is a team:<id> scope shared by its members. Send { id, name?, isolatedInOpen?, addMembers?, addAdmins?, drop?, addRooms?, dropRooms? } or { id, remove: true }. Rooms are channel or group scopes where the team stays available; isolatedInOpen keeps it isolated when the org posture is Open.",
+ get: (deps) => deps.teams?.list(),
+ apply: async (ctx, actor, scope) => {
+ if (!ctx.deps.teams) return { error: "not available on this deployment", status: 404 };
+ const change = parseTeamChange(ctx.body);
+ if ("error" in change) return change;
+ await ctx.deps.teams.apply(change, actor.id);
+ audit(ctx.deps, {
+ principalId: actor.id,
+ action: change.remove ? "team.remove" : "team.update",
+ resource: `team:${change.id}`,
+ scopeLabel: scope,
+ });
+ return { ok: true };
+ },
+ },
{
id: "unfulfilled-insights",
kind: "boolean",
@@ -1202,3 +1225,34 @@ export function adminResourceManifest(): AdminResourceManifestEntry[] {
...(r.enumValues ? { enumValues: r.enumValues } : {}),
}));
}
+
+const TEAM_ID = /^[a-z0-9][a-z0-9-]{0,62}$/;
+const TEAM_LISTS = ["addMembers", "addAdmins", "drop", "addRooms", "dropRooms"] as const;
+
+function parseTeamChange(body: unknown): TeamChange | { error: string } {
+ const b = (body ?? {}) as Record<string, unknown>;
+ if (typeof b.id !== "string" || !TEAM_ID.test(b.id))
+ return { error: "teams requires id: lowercase letters, digits, -" };
+ if (b.remove === true) return { id: b.id, remove: true };
+ const lists: Partial<Record<(typeof TEAM_LISTS)[number], string[]>> = {};
+ for (const key of TEAM_LISTS) {
+ const v = b[key] ?? [];
+ if (!Array.isArray(v) || !v.every((x) => typeof x === "string" && x.trim()))
+ return { error: `${key} must be an array of non-empty strings` };
+ lists[key] = [...new Set(v as string[])];
+ }
+ const isRoom = (r: string) => {
+ const { kind, ref } = parseScopeId(r as ScopeId);
+ return (kind === "channel" || kind === "group") && !!ref;
+ };
+ if (![...lists.addRooms!, ...lists.dropRooms!].every(isRoom))
+ return { error: "rooms must be channel:<id> or group:<id> scopes" };
+ return {
+ id: b.id,
+ ...(typeof b.name === "string" && b.name.trim() ? { name: b.name.trim() } : {}),
+ ...(typeof b.isolatedInOpen === "boolean" ? { isolatedInOpen: b.isolatedInOpen } : {}),
+ ...lists,
+ addRooms: lists.addRooms as ScopeId[],
+ dropRooms: lists.dropRooms as ScopeId[],
+ };
+}
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.ts
index c3102db01..ea346fc9b 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -1,3 +1,4 @@
+import { scopeTeamsToTurn } from "../teams/teams.ts";
import { externalSlackRequestAllowed, currentExternalSlackRun } from "../resolution/external-slack.ts";
import { externalTools } from "./orchestrator/external-tools.ts";
import { memoryBoundedEntries, memoryContextPayload, nextMemoryContext } from "../memory/context-boundary.ts";
@@ -541,6 +542,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
input = { ...input, model: undefined, harness: undefined, thinkingLevel: undefined, fastMode: undefined };
const swarmEntryProvenance = input.swarm ? { origin: "automation", swarm: input.swarm } : {};
await deps.refreshModels?.();
+ input = await scopeTeamsToTurn(input, deps, external);
const { actor, conversation } = input;
const automatedTurn = input.origin.kind === "automation";
const ambientTurn = input.origin.kind === "ambient";
diff --git a/src/core/orchestrator/types.ts b/src/core/orchestrator/types.ts
index 8664fb334..44dbdd781 100644
--- a/src/core/orchestrator/types.ts
+++ b/src/core/orchestrator/types.ts
@@ -32,6 +32,7 @@ import type { CronStore } from "../../cron/cron-store.ts";
import type { WebhookStore } from "../../webhooks/webhook-store.ts";
import type { ConnectorTokenStore, Keychain, ServiceCredentialStore } from "../../credentials/keychain.ts";
import type { FeatureFlagStore } from "../../feature-flags.ts";
+import type { TeamStore } from "../../teams/teams.ts";
import type { CredentialUsageSink } from "../../admin/credential-usage-sink.ts";
import type { ConnectorStatusCache } from "../../credentials/connector-status.ts";
import type { ModelGateway } from "../../model/model-gateway.ts";
@@ -191,6 +192,7 @@ export interface OrchestratorDeps {
resolveConnectorClient?: OAuthClientResolver;
scratchExec?: boolean;
featureFlags?: FeatureFlagStore;
+ teams?: TeamStore;
credentialUsage?: CredentialUsageSink;
keychain?: Keychain;
serviceCreds?: ServiceCredentialStore;
diff --git a/src/feature-flags.ts b/src/feature-flags.ts
index 3de235d7d..2f1975fd4 100644
--- a/src/feature-flags.ts
+++ b/src/feature-flags.ts
@@ -11,6 +11,7 @@ export const FEATURE_NAMES = [
"external_app_sharing",
"loop_triage",
"swarms",
+ "team_scopes",
] as const;
export type FeatureName = (typeof FEATURE_NAMES)[number];
diff --git a/src/resolution/resolution-service.ts b/src/resolution/resolution-service.ts
index af5466ebb..3dc8b0775 100644
--- a/src/resolution/resolution-service.ts
+++ b/src/resolution/resolution-service.ts
@@ -50,8 +50,8 @@ export function createResolutionService(
...(!external ? [{ scopeId: orgScope, mountPath: "global", mode: "ro" as const }] : []),
{ scopeId: scope, mountPath: "", mode: "rw" },
];
- if (!external && isDm && actor.teamIds) {
- for (const tid of actor.teamIds) {
+ if (!external) {
+ for (const tid of (isDm ? actor.teamIds : conversation.teamIds) ?? []) {
layers.push({ scopeId: scopeId("team", tid), mountPath: `team-${tid}`, mode: "ro" });
}
}
diff --git a/src/resolution/scope-membership.ts b/src/resolution/scope-membership.ts
index a4fd0a474..46b4910b2 100644
--- a/src/resolution/scope-membership.ts
+++ b/src/resolution/scope-membership.ts
@@ -30,9 +30,14 @@ export interface ScopeMembershipDeps {
identity?: {
classify(externalId: string, isExternalGuest?: boolean): { type?: string; teamIds?: readonly string[] };
};
+ teams?: { isMember(principalId: string, teamId: string): Promise<boolean> };
sessions?: { listByParticipant(principalId: string): Promise<readonly { scopeId: ScopeId }[]> };
}
+async function teamMember(deps: ScopeMembershipDeps, principalId: string, teamId: string): Promise<boolean> {
+ return activePrincipal(deps, principalId) && (await deps.teams?.isMember(principalId, teamId)) === true;
+}
+
function activePrincipal(deps: ScopeMembershipDeps, principalId: string): boolean {
const type = deps.identity?.classify(principalId).type;
return type === undefined || type === "internal";
@@ -192,9 +197,7 @@ export function createCanReadScope(deps: ScopeMembershipDeps): CanReadScope {
const { kind, ref } = parseScopeId(targetScope);
if (kind === "org") return deps.identity?.classify(principalId).type === "internal";
if (kind === "personal") return samePerson(ref, principalId);
- if (kind === "team") {
- return deps.identity?.classify(principalId).teamIds?.includes(ref) === true;
- }
+ if (kind === "team") return teamMember(deps, principalId, ref);
if (kind === "group") return memberOfSharedScope(deps, kind, ref, principalId, targetScope);
if (kind === "channel") {
if (await memberOfSharedScope(deps, kind, ref, principalId, targetScope)) return true;
@@ -214,7 +217,7 @@ export function createCanWriteScope(deps: ScopeMembershipDeps): CanWriteScope {
const { kind, ref } = parseScopeId(targetScope);
if (kind === "org") return true;
if (kind === "personal") return samePerson(ref, principalId);
- if (kind === "team") return deps.identity?.classify(principalId).teamIds?.includes(ref) === true;
+ if (kind === "team") return teamMember(deps, principalId, ref);
if (kind === "channel" || kind === "group") return currentSharedScopeMember(deps, kind, ref, principalId);
return false;
};
diff --git a/src/teams/teams.ts b/src/teams/teams.ts
new file mode 100644
index 000000000..9dfb2d730
--- /dev/null
+++ b/src/teams/teams.ts
@@ -0,0 +1,221 @@
+import { foldPrincipalId, personIds, personKey } from "../directory/person.ts";
+import type { FeatureFlagStore } from "../feature-flags.ts";
+import { createPgPool, withPgTransaction } from "../persistence/pg-pool.ts";
+import { conversationScope } from "../resolution/resolution-service.ts";
+import type { SharingPosture } from "../resolution/sharing-posture.ts";
+import type { Conversation, Principal, ScopeId } from "../types.ts";
+import { scopeId } from "../types.ts";
+
+interface Team {
+ id: string;
+ name: string;
+ isolatedInOpen: boolean;
+ rooms: ScopeId[];
+ memberCount: number;
+}
+
+export interface TurnTeam {
+ id: string;
+ name: string;
+ isolatedInOpen: boolean;
+ configured: boolean;
+ present: ReadonlySet<string>;
+}
+
+export interface TeamChange {
+ id: string;
+ remove?: boolean;
+ name?: string;
+ isolatedInOpen?: boolean;
+ addMembers?: readonly string[];
+ addAdmins?: readonly string[];
+ drop?: readonly string[];
+ addRooms?: readonly ScopeId[];
+ dropRooms?: readonly ScopeId[];
+}
+
+export interface TeamStore {
+ list(): Promise<Team[]>;
+ forTurn(scope: ScopeId, principalIds: readonly string[]): Promise<TurnTeam[]>;
+ isMember(principalId: string, teamId: string): Promise<boolean>;
+ apply(change: TeamChange, actorId: string): Promise<void>;
+}
+
+const SCHEMA = [
+ `CREATE TABLE IF NOT EXISTS teams(
+ team_id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ isolated_in_open BOOLEAN NOT NULL DEFAULT FALSE,
+ created_by TEXT NOT NULL,
+ created_at BIGINT NOT NULL
+ )`,
+ `CREATE TABLE IF NOT EXISTS team_members(
+ team_id TEXT NOT NULL REFERENCES teams(team_id) ON DELETE CASCADE,
+ principal_id TEXT NOT NULL,
+ role TEXT NOT NULL CHECK (role IN ('member', 'admin')),
+ added_by TEXT NOT NULL,
+ added_at BIGINT NOT NULL,
+ PRIMARY KEY (team_id, principal_id)
+ )`,
+ `CREATE INDEX IF NOT EXISTS team_members_principal ON team_members (principal_id)`,
+ `CREATE TABLE IF NOT EXISTS team_rooms(
+ team_id TEXT NOT NULL REFERENCES teams(team_id) ON DELETE CASCADE,
+ scope_id TEXT NOT NULL,
+ PRIMARY KEY (team_id, scope_id)
+ )`,
+ `CREATE INDEX IF NOT EXISTS team_rooms_scope ON team_rooms (scope_id)`,
+];
+
+const keysOf = (id: string) => personIds(id).map(foldPrincipalId);
+const onTeam = (team: TurnTeam, principalId: string) => keysOf(principalId).some((k) => team.present.has(k));
+
+export function createPostgresTeamStore(
+ connectionString: string,
+ flags: Pick<FeatureFlagStore, "enabled">,
+ orgScope: ScopeId,
+): TeamStore {
+ const { q, pool } = createPgPool(connectionString, "teams/0001", SCHEMA);
+ const enabled = () => flags.enabled("team_scopes", orgScope);
+ return {
+ async list() {
+ if (!(await enabled())) return [];
+ const rows = await q(
+ `SELECT t.team_id, t.name, t.isolated_in_open,
+ (SELECT count(*)::int FROM team_members m WHERE m.team_id = t.team_id) AS member_count,
+ COALESCE((SELECT array_agg(r.scope_id ORDER BY r.scope_id) FROM team_rooms r WHERE r.team_id = t.team_id), '{}') AS rooms
+ FROM teams t ORDER BY t.team_id`,
+ );
+ return rows.map((r) => ({
+ id: r.team_id as string,
+ name: r.name as string,
+ isolatedInOpen: r.isolated_in_open as boolean,
+ rooms: r.rooms as ScopeId[],
+ memberCount: r.member_count as number,
+ }));
+ },
+ async forTurn(scope, principalIds) {
+ if (!(await enabled())) return [];
+ const rows = await q(
+ `SELECT t.team_id, t.name, t.isolated_in_open,
+ EXISTS (SELECT 1 FROM team_rooms r WHERE r.team_id = t.team_id AND r.scope_id = $1) AS configured,
+ array_agg(m.principal_id) AS present
+ FROM team_members m JOIN teams t ON t.team_id = m.team_id
+ WHERE m.principal_id = ANY($2)
+ GROUP BY t.team_id ORDER BY t.team_id`,
+ [scope, [...new Set(principalIds.flatMap(keysOf))]],
+ );
+ return rows.map((r) => ({
+ id: r.team_id as string,
+ name: r.name as string,
+ isolatedInOpen: r.isolated_in_open as boolean,
+ configured: r.configured as boolean,
+ present: new Set(r.present as string[]),
+ }));
+ },
+ async isMember(principalId, teamId) {
+ if (!(await enabled())) return false;
+ const rows = await q("SELECT 1 FROM team_members WHERE team_id = $1 AND principal_id = ANY($2) LIMIT 1", [
+ teamId,
+ keysOf(principalId),
+ ]);
+ return rows.length > 0;
+ },
+ async apply(c, actorId) {
+ const now = Date.now();
+ await withPgTransaction(await pool(), async (db) => {
+ if (c.remove) {
+ await db.query("DELETE FROM teams WHERE team_id = $1", [c.id]);
+ return;
+ }
+ await db.query(
+ `INSERT INTO teams (team_id, name, isolated_in_open, created_by, created_at)
+ VALUES ($1, COALESCE($2, $1), COALESCE($3, FALSE), $4, $5)
+ ON CONFLICT (team_id) DO UPDATE SET
+ name = COALESCE($2, teams.name),
+ isolated_in_open = COALESCE($3, teams.isolated_in_open)`,
+ [c.id, c.name ?? null, c.isolatedInOpen ?? null, actorId, now],
+ );
+ const people = [
+ ...(c.addMembers ?? []).map((p) => [personKey(p), "member"]),
+ ...(c.addAdmins ?? []).map((p) => [personKey(p), "admin"]),
+ ];
+ if (people.length)
+ await db.query(
+ `INSERT INTO team_members (team_id, principal_id, role, added_by, added_at)
+ SELECT $1, p, r, $4, $5 FROM unnest($2::text[], $3::text[]) AS x(p, r)
+ ON CONFLICT (team_id, principal_id) DO UPDATE SET role = EXCLUDED.role`,
+ [c.id, people.map(([p]) => p), people.map(([, r]) => r), actorId, now],
+ );
+ if (c.drop?.length)
+ await db.query("DELETE FROM team_members WHERE team_id = $1 AND principal_id = ANY($2)", [
+ c.id,
+ c.drop.map(personKey),
+ ]);
+ if (c.addRooms?.length)
+ await db.query(
+ "INSERT INTO team_rooms (team_id, scope_id) SELECT $1, unnest($2::text[]) ON CONFLICT DO NOTHING",
+ [c.id, c.addRooms],
+ );
+ if (c.dropRooms?.length)
+ await db.query("DELETE FROM team_rooms WHERE team_id = $1 AND scope_id = ANY($2)", [c.id, c.dropRooms]);
+ });
+ },
+ };
+}
+
+export function teamsForTurn(
+ teams: readonly TurnTeam[],
+ turn: { scope: ScopeId; actorId: string; audience: readonly Principal[]; posture: SharingPosture },
+): { teamIds: string[]; note?: string } {
+ const ownScope = turn.scope === scopeId("personal", turn.actorId);
+ const everyoneOn = (t: TurnTeam) => turn.audience.length > 0 && turn.audience.every((p) => onTeam(t, p.id));
+ const applies = teams.filter(
+ (t) =>
+ onTeam(t, turn.actorId) &&
+ (ownScope || t.configured || everyoneOn(t) || (turn.posture === "open" && !t.isolatedInOpen)),
+ );
+ const teamIds = applies.map((t) => t.id);
+ if (teamIds.length < 2) return { teamIds };
+ const configured = applies.filter((t) => t.configured).length;
+ const label = (t: TurnTeam) => `team:${t.id} (${t.name})${t.configured ? " — configured for this room" : ""}`;
+ return {
+ teamIds,
+ note: [
+ `Team scopes available in this turn: ${applies.map(label).join(", ")}.`,
+ configured === 1
+ ? "If two teams provide a credential or resource with the same name, use the team configured for this room."
+ : "If two teams provide a credential or resource with the same name, ask which team to use before acting.",
+ ].join(" "),
+ };
+}
+
+export async function scopeTeamsToTurn<
+ T extends { actor: Principal; conversation: Conversation; conversationHeader?: string },
+>(
+ input: T,
+ deps: {
+ teams?: TeamStore;
+ config?: { resolveSharingPostureDurable(personalId: ScopeId, targetId: ScopeId): Promise<SharingPosture> };
+ },
+ external: boolean,
+): Promise<T> {
+ if (external || !deps.teams) return input;
+ const { actor, conversation } = input;
+ const scope = conversationScope(conversation, actor.id);
+ const rows = await deps.teams.forTurn(scope, [actor.id, ...conversation.audience.map((p) => p.id)]);
+ if (!rows.length) return input;
+ const posture = (await deps.config?.resolveSharingPostureDurable(scopeId("personal", actor.id), scope)) ?? "isolated";
+ const { teamIds, note } = teamsForTurn(rows, { scope, actorId: actor.id, audience: conversation.audience, posture });
+ if (!teamIds.length) return input;
+ const stamp = (p: Principal): Principal => {
+ const own = rows.filter((t) => teamIds.includes(t.id) && onTeam(t, p.id)).map((t) => t.id);
+ return p.type === "internal" && own.length ? { ...p, teamIds: [...new Set([...(p.teamIds ?? []), ...own])] } : p;
+ };
+ const header = [input.conversationHeader?.trim(), note].filter(Boolean).join("\n\n");
+ return {
+ ...input,
+ actor: stamp(actor),
+ conversation: { ...conversation, audience: conversation.audience.map(stamp), teamIds },
+ ...(header ? { conversationHeader: header } : {}),
+ };
+}
diff --git a/src/types.ts b/src/types.ts
index bc3d8795c..b72e221d2 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -55,6 +55,7 @@ export function isSharedScope(id: ScopeId | undefined): boolean {
export type ConversationKind = "dm" | "channel" | "group";
export interface Conversation {
+ teamIds?: string[];
kind: ConversationKind;
threadRef: string;
channelRef?: string;
diff --git a/src/wiring.ts b/src/wiring.ts
index 25c100d7e..e4e0fe492 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -1,3 +1,4 @@
+import { createPostgresTeamStore, type TeamStore } from "./teams/teams.ts";
import type { SlackSessionStatusState } from "./slack/session-status.ts";
import { availableRuntimeError } from "./api/runtime-config.ts";
import { createApprovalStore } from "./core/approval-store.ts";
@@ -540,6 +541,7 @@ export interface BuiltApp {
files: FileArtifactStore;
fileUploads?: DirectFileUploads;
featureFlags: FeatureFlagStore;
+ teams?: TeamStore;
replayDedupe?: ReplayDedupe;
brokerSessions?: BrokerSessionStore;
directory: DirectoryStore;
@@ -702,6 +704,9 @@ export function buildApp(
const skillPacks = createSkillPackStore({ backing: artifactMap<SkillPack>("skill_packs") });
const skillBundles = createSkillBundleStore({ backing: artifactMap<SkillBundle>("skill_bundles") });
const featureFlags = createFeatureFlagStore(artifactMap<FeatureFlagRecord>("feature_flags"));
+ const teams = config.databaseUrl
+ ? createPostgresTeamStore(config.databaseUrl, featureFlags, scopeId("org", config.orgId))
+ : undefined;
const connectorStatusCache = createConnectorStatusCache(artifactMap<ConnectorStatusRecord>("connector_status"));
const slackInstallation = createSlackInstallationStore(
config.orgId,
@@ -1728,8 +1733,8 @@ export function buildApp(
isActiveMember: (principalId) => identity.isInternal(identity.classify(principalId)),
advisoryLock,
});
- const canReadScope = createCanReadScope({ managedGroups: projects, directory, identity, sessions });
- const canWriteScope = createCanWriteScope({ managedGroups: projects, directory, identity });
+ const canReadScope = createCanReadScope({ managedGroups: projects, directory, identity, teams, sessions });
+ const canWriteScope = createCanWriteScope({ managedGroups: projects, directory, identity, teams });
const canManageScope = createCanManageScope({ managedGroups: projects, directory, identity, sessions });
const managesArtifactHome = createManagesArtifactHome({ managedGroups: projects, directory }, canManageScope);
const currentScopeMembers = createCurrentScopeMembers({ managedGroups: projects, directory, identity });
@@ -2007,6 +2012,7 @@ export function buildApp(
tasks,
blobTransfer,
featureFlags,
+ teams,
credentialUsage,
connectorStatusCache,
resolveConnectorClient: resolveClient,
@@ -2896,6 +2902,7 @@ export function buildApp(
files,
...(fileUploads ? { fileUploads } : {}),
featureFlags,
+ teams,
...(replayDedupe ? { replayDedupe } : {}),
...(brokerSessions ? { brokerSessions } : {}),
directory,
diff --git a/test/postgres-teams.test.ts b/test/postgres-teams.test.ts
new file mode 100644
index 000000000..ba5feca3e
--- /dev/null
+++ b/test/postgres-teams.test.ts
@@ -0,0 +1,70 @@
+import { test, beforeEach } from "node:test";
+import assert from "node:assert/strict";
+import { createPostgresTeamStore } from "../src/teams/teams.ts";
+import { scopeId } from "../src/types.ts";
+
+const URL = process.env.DATABASE_URL;
+const skip = URL ? false : "set DATABASE_URL (a Postgres) to run the Postgres team tests";
+const org = scopeId("org", "default-org");
+const room = scopeId("channel", "C1");
+
+beforeEach(async () => {
+ if (!URL) return;
+ const pg = (await import("pg")).default;
+ const p = new pg.Pool({ connectionString: URL });
+ await p.query("DROP TABLE IF EXISTS qm_schema_migrations, team_rooms, team_members, teams CASCADE");
+ await p.end();
+});
+
+const store = (on = true) => createPostgresTeamStore(URL!, { enabled: async () => on }, org);
+
+test("pg teams: members are rows, edited one at a time, looked up by person", { skip }, async () => {
+ const teams = store();
+ const members = Array.from({ length: 1000 }, (_, i) => `p${i}@x.com`);
+ await teams.apply(
+ { id: "finance", name: "Finance", addMembers: members, addAdmins: ["[email protected]"], addRooms: [room] },
+ "a",
+ );
+ await teams.apply({ id: "legal", addMembers: ["[email protected]"] }, "a");
+
+ const [finance] = await teams.list();
+ assert.equal(finance!.memberCount, 1001);
+ assert.deepEqual(finance!.rooms, [room]);
+
+ assert.equal(await teams.isMember("[email protected]", "finance"), true);
+ await teams.apply({ id: "finance", drop: ["[email protected]"] }, "a");
+ assert.equal(await teams.isMember("[email protected]", "finance"), false);
+ assert.equal((await teams.list())[0]!.memberCount, 1000);
+
+ const turn = await teams.forTurn(room, ["[email protected]", "[email protected]"]);
+ assert.deepEqual(
+ turn.map((t) => [t.id, t.configured, [...t.present]]),
+ [
+ ["finance", true, ["[email protected]"]],
+ ["legal", false, ["[email protected]"]],
+ ],
+ );
+});
+
+test("pg teams: removing a team removes its members and rooms", { skip }, async () => {
+ const teams = store();
+ await teams.apply({ id: "finance", addMembers: ["[email protected]"], addRooms: [room] }, "a");
+ await teams.apply({ id: "finance", remove: true }, "a");
+ assert.deepEqual(await teams.list(), []);
+ assert.deepEqual(await teams.forTurn(room, ["[email protected]"]), []);
+ const pg = (await import("pg")).default;
+ const p = new pg.Pool({ connectionString: URL });
+ const { rows } = await p.query(
+ "SELECT (SELECT count(*) FROM team_members)::int + (SELECT count(*) FROM team_rooms)::int AS n",
+ );
+ await p.end();
+ assert.equal(rows[0].n, 0);
+});
+
+test("pg teams: the feature flag gates every read", { skip }, async () => {
+ await store().apply({ id: "finance", addMembers: ["[email protected]"] }, "a");
+ const off = store(false);
+ assert.deepEqual(await off.list(), []);
+ assert.deepEqual(await off.forTurn(room, ["[email protected]"]), []);
+ assert.equal(await off.isMember("[email protected]", "finance"), false);
+});
diff --git a/test/teams.test.ts b/test/teams.test.ts
new file mode 100644
index 000000000..b840116f3
--- /dev/null
+++ b/test/teams.test.ts
@@ -0,0 +1,116 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { scopeTeamsToTurn, teamsForTurn, type TeamStore, type TurnTeam } from "../src/teams/teams.ts";
+import { createCanReadScope, createCanWriteScope } from "../src/resolution/scope-membership.ts";
+import { scopeId, type Conversation, type Principal, type ScopeId } from "../src/types.ts";
+
+const person = (id: string): Principal => ({ id, type: "internal" }) as Principal;
+const team = (over: Partial<TurnTeam> = {}): TurnTeam => ({
+ id: "finance",
+ name: "Finance",
+ isolatedInOpen: false,
+ configured: false,
+ present: new Set(["[email protected]", "[email protected]"]),
+ ...over,
+});
+const turn = (
+ scope: ScopeId,
+ audience: string[],
+ posture: "open" | "isolated" = "isolated",
+ actorId = "[email protected]",
+) => ({
+ scope,
+ actorId,
+ audience: audience.map(person),
+ posture,
+});
+const room = scopeId("channel", "C1");
+
+test("isolated: a member's own DM gets the team", () => {
+ assert.deepEqual(teamsForTurn([team()], turn(scopeId("personal", "[email protected]"), ["[email protected]"])).teamIds, ["finance"]);
+});
+
+test("isolated: a room qualifies only while everyone present is on the team", () => {
+ assert.deepEqual(teamsForTurn([team()], turn(room, ["[email protected]", "[email protected]"])).teamIds, ["finance"]);
+ assert.deepEqual(teamsForTurn([team()], turn(room, ["[email protected]", "[email protected]", "[email protected]"])).teamIds, []);
+});
+
+test("isolated: configured rooms keep the team for members when a non-member joins", () => {
+ const t = team({ configured: true });
+ assert.deepEqual(teamsForTurn([t], turn(room, ["[email protected]", "[email protected]"])).teamIds, ["finance"]);
+ assert.deepEqual(teamsForTurn([t], turn(room, ["[email protected]", "[email protected]"], "isolated", "[email protected]")).teamIds, []);
+});
+
+test("open: available wherever a member speaks unless the team opts out", () => {
+ assert.deepEqual(teamsForTurn([team()], turn(room, ["[email protected]", "[email protected]"], "open")).teamIds, ["finance"]);
+ assert.deepEqual(teamsForTurn([team()], turn(room, ["[email protected]", "[email protected]"], "open", "[email protected]")).teamIds, []);
+ assert.deepEqual(
+ teamsForTurn([team({ isolatedInOpen: true })], turn(room, ["[email protected]", "[email protected]"], "open")).teamIds,
+ [],
+ );
+});
+
+test("multiple teams all apply; the note names the configured room's team or asks", () => {
+ const b = team({ id: "legal", name: "Legal" });
+ const asked = teamsForTurn([team(), b], turn(room, ["[email protected]", "[email protected]"]));
+ assert.deepEqual(asked.teamIds, ["finance", "legal"]);
+ assert.match(asked.note!, /ask which team/);
+ const preferred = teamsForTurn([team(), { ...b, configured: true }], turn(room, ["[email protected]", "[email protected]"]));
+ assert.match(preferred.note!, /team:legal \(Legal\) — configured for this room/);
+ assert.match(preferred.note!, /use the team configured for this room/);
+});
+
+const fakeStore = (teams: TurnTeam[]): TeamStore => ({
+ list: async () => [],
+ forTurn: async (_scope, ids) => teams.filter((t) => ids.some((id) => t.present.has(id.toLowerCase()))),
+ isMember: async (id, teamId) => teams.some((t) => t.id === teamId && t.present.has(id.toLowerCase())),
+ apply: async () => {},
+});
+const group = (audience: Principal[]) =>
+ ({ kind: "group", channelRef: "G1", threadRef: "t", audience }) as unknown as Conversation;
+const isolated = { resolveSharingPostureDurable: async () => "isolated" as const };
+const open = { resolveSharingPostureDurable: async () => "open" as const };
+
+test("scopeTeamsToTurn stamps teams only onto members and keeps their existing team ids", async () => {
+ const teams = fakeStore([team()]);
+ const out = await scopeTeamsToTurn(
+ {
+ actor: { ...person("[email protected]"), teamIds: ["legacy"] },
+ conversation: group([person("[email protected]"), person("[email protected]")]),
+ },
+ { teams, config: isolated },
+ false,
+ );
+ assert.deepEqual(out.actor.teamIds, ["legacy", "finance"]);
+ assert.deepEqual(out.conversation.teamIds, ["finance"]);
+ assert.deepEqual(
+ out.conversation.audience.map((p) => p.teamIds),
+ [["finance"], ["finance"]],
+ );
+
+ const guest = { id: "[email protected]", type: "guest" } as Principal;
+ const mixed = await scopeTeamsToTurn(
+ { actor: person("[email protected]"), conversation: group([person("[email protected]"), person("[email protected]"), guest]) },
+ { teams, config: open },
+ false,
+ );
+ assert.deepEqual(
+ mixed.conversation.audience.map((p) => p.teamIds),
+ [["finance"], undefined, undefined],
+ );
+});
+
+test("scopeTeamsToTurn leaves the turn untouched when no team applies or the turn is external", async () => {
+ const teams = fakeStore([team()]);
+ const input = { actor: person("[email protected]"), conversation: group([person("[email protected]"), person("[email protected]")]) };
+ assert.equal(await scopeTeamsToTurn(input, { teams, config: isolated }, false), input);
+ assert.equal(await scopeTeamsToTurn(input, { teams, config: open }, true), input);
+});
+
+test("team scope read and write follow team membership", async () => {
+ const teams = fakeStore([team()]);
+ const identity = { classify: () => ({ type: "internal" }) };
+ assert.equal(await createCanReadScope({ identity, teams })("[email protected]", scopeId("team", "finance")), true);
+ assert.equal(await createCanWriteScope({ identity, teams })("[email protected]", scopeId("team", "finance")), true);
+ assert.equal(await createCanReadScope({ identity, teams })("[email protected]", scopeId("team", "finance")), false);
+});