Multiplayer agent harness for work.
Trim the session list and stop rebuilding it for scope lookups (#2495)
Regan Bellf780e39d5e4a
diff --git a/src/api/app-helpers.ts b/src/api/app-helpers.tsindex 365dd599f..4fb4cb9d7 100644--- a/src/api/app-helpers.ts+++ b/src/api/app-helpers.ts@@ -48,6 +48,7 @@ import {type Project,} from "../projects/project-store.ts";+import type { ParticipantScope } from "../sessions/session-store.ts";import type { App, AppDeps, ContextSummary, ProjectView, FileListPage } from "./app-types.ts";import { toFileItem } from "./app-types.ts";@@ -305,6 +306,14 @@ export function createAppHelpers(deps: AppDeps, app: App) {return sessions.filter((session) => allowed.get(session.scopeId) !== false);}+ async function scopesForViewer(principalId: string): Promise<ParticipantScope[]> {+ const scopes = await deps.sessions.participantScopes(principalId);+ const allowed = await Promise.all(+ scopes.map(async (scope) => (await managedProjectMembership(scope.scopeId, principalId)) !== false),+ );+ return scopes.filter((_, index) => allowed[index]);+ }+async function sessionForViewer(sessionId: string, principalId: string): Promise<Session | null> {const session = await deps.sessions.getForParticipant(sessionId, principalId);if (!session) return null;@@ -339,20 +348,24 @@ export function createAppHelpers(deps: AppDeps, app: App) {project,});}- for (const s of await sessionsForViewer(principalId)) {- const { kind } = parseScopeId(s.scopeId);- if (s.scopeId !== personal && kind !== "channel" && kind !== "group") continue;- let ctx = byScope.get(s.scopeId);- if (!ctx && kind === "group" && (await deps.directory.groupMember(parseScopeId(s.scopeId).ref, principalId))) {- ctx = { scopeId: s.scopeId, kind: "group", name: s.channelName ?? null, sessionCount: 0, lastActivityAt: null };+ for (const scope of await scopesForViewer(principalId)) {+ const { kind, ref } = parseScopeId(scope.scopeId);+ if (scope.scopeId !== personal && kind !== "channel" && kind !== "group") continue;+ let ctx = byScope.get(scope.scopeId);+ if (!ctx && kind === "group" && (await deps.directory.groupMember(ref, principalId))) {+ ctx = {+ scopeId: scope.scopeId,+ kind: "group",+ name: scope.channelName ?? null,+ sessionCount: 0,+ lastActivityAt: null,+ };}if (!ctx) continue;- if (!ctx.name && s.channelName) ctx.name = s.channelName;- if (s.hasEntries !== false || Boolean(s.title?.trim())) {- ctx.sessionCount++;- ctx.lastActivityAt = Math.max(ctx.lastActivityAt ?? 0, s.lastActivityAt ?? s.createdAt);- }- byScope.set(s.scopeId, ctx);+ if (!ctx.name && scope.channelName) ctx.name = scope.channelName;+ ctx.sessionCount += scope.sessionCount;+ if (scope.lastActivityAt !== null) ctx.lastActivityAt = Math.max(ctx.lastActivityAt ?? 0, scope.lastActivityAt);+ byScope.set(scope.scopeId, ctx);}return [...byScope.values()].sort((a, b) => {if (a.kind === "personal") return -1;@@ -392,13 +405,13 @@ export function createAppHelpers(deps: AppDeps, app: App) {scopeId("org", orgIdOf()),]);try {- const [sessions, channels, groups, projects] = await Promise.all([- deps.sessions ? sessionsForViewer(principalId) : Promise.resolve([]),+ const [sessionScopes, channels, groups, projects] = await Promise.all([+ deps.sessions ? scopesForViewer(principalId) : Promise.resolve([]),deps.directory ? deps.directory.listChannelsFor(principalId) : Promise.resolve([]),deps.directory?.listGroupsFor?.(principalId) ?? Promise.resolve([]),projectsForViewer(principalId),]);- const historical = new Set(sessions.map((session) => session.scopeId));+ const historical = new Set(sessionScopes.map((scope) => scope.scopeId));for (const channel of channels) {const scope = scopeId("channel", channel.channelId);if (channel.isPrivate === true || historical.has(scope)) scopes.add(scope);@@ -429,22 +442,27 @@ export function createAppHelpers(deps: AppDeps, app: App) {async function mayWriteSession(principalId: string,session: Pick<Session, "threadRef" | "scopeId">,- sharedAccess = new Map<ScopeId, Promise<boolean>>(),+ sharedAccess = new Map<string, Promise<boolean>>(),): Promise<boolean> {const actor = deps.identity.classify(principalId);if (!deps.identity.isInternal(actor)) return false;const { kind, ref } = parseScopeId(session.scopeId);if (kind === "personal") return session.scopeId === scopeId("personal", actor.id);if (kind !== "channel" && kind !== "group") return false;- if (isSubagentThreadRef(session.threadRef)) return principalCanWriteScope(actor.id, session.scopeId);- if (!sharedAccess.has(session.scopeId)) sharedAccess.set(session.scopeId, mayUseSharedScope(kind, ref, actor));- return sharedAccess.get(session.scopeId)!;+ const subagent = isSubagentThreadRef(session.threadRef);+ const key = subagent ? `subagent ${session.scopeId}` : session.scopeId;+ if (!sharedAccess.has(key))+ sharedAccess.set(+ key,+ subagent ? principalCanWriteScope(actor.id, session.scopeId) : mayUseSharedScope(kind, ref, actor),+ );+ return sharedAccess.get(key)!;}async function canContinueOnWeb(principalId: string,session: Pick<Session, "threadRef" | "scopeId">,- sharedAccess?: Map<ScopeId, Promise<boolean>>,+ sharedAccess?: Map<string, Promise<boolean>>,): Promise<boolean> {if (!session.threadRef.startsWith("web:") && !isSubagentThreadRef(session.threadRef)) return false;return mayWriteSession(principalId, session, sharedAccess);diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.tsindex 7a54ac91a..2a28d4979 100644--- a/src/api/app-sessions.ts+++ b/src/api/app-sessions.ts@@ -5,7 +5,7 @@ import { deploymentShareScope } from "../deploy/email-access.ts";import { workingSessionThreadRefs } from "../sessions/session-syscalls.ts";import type { PendingApprovalRecord } from "../types.ts";import { orgId as orgIdOf } from "../config.ts";-import { parseScopeId, scopeId, type ScopeId } from "../types.ts";+import { parseScopeId, scopeId } from "../types.ts";import { fileArtifactId, artifactPath } from "../files/file-artifact-store.ts";import { acquireLeaseWithin, entryWithinTenure, windowedTranscript } from "../sessions/session-store.ts";import { createTranscriptSource } from "../sessions/transcript-source.ts";@@ -455,7 +455,7 @@ export function createSessionMethods(}const waiting = new Set(approvalRows.filter((r) => r.blocksInput !== false).map((r) => r.sessionId));const workingThreadRefs = await workingSessionThreadRefs(deps.sessions, deps.runs, waiting);- const sharedAccess = new Map<ScopeId, Promise<boolean>>(+ const sharedAccess = new Map<string, Promise<boolean>>(all.filter((s) => {const { kind, ref } = parseScopeId(s.scopeId);@@ -472,7 +472,10 @@ export function createSessionMethods(workingThreadRefs.has(s.threadRef) ||waiting.has(s.id),)- .map(async (s) => ({ ...s, canContinue: await canContinueOnWeb(principalId, s, sharedAccess) })),+ .map(async ({ hasEntries: _hasEntries, ...s }) => ({+ ...s,+ canContinue: await canContinueOnWeb(principalId, s, sharedAccess),+ })),);const now = Date.now();const jobCounts = new Map<string, number>();diff --git a/src/resolution/scope-membership.ts b/src/resolution/scope-membership.tsindex d37dfb8ba..6a7fadc29 100644--- a/src/resolution/scope-membership.ts+++ b/src/resolution/scope-membership.ts@@ -31,7 +31,7 @@ export interface ScopeMembershipDeps {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 }[]> };+ sessions?: { participantScopes(principalId: string): Promise<readonly { scopeId: ScopeId }[]> };}async function teamMember(deps: ScopeMembershipDeps, principalId: string, teamId: string): Promise<boolean> {@@ -117,7 +117,7 @@ async function memberOfSharedScope(if (current !== undefined) return current;return ((- await deps.sessions?.listByParticipant(principalId).catch(swallowAs("scope membership: session lookup", []))+ await deps.sessions?.participantScopes(principalId).catch(swallowAs("scope membership: session lookup", [])))?.some((s) => s.scopeId === fullScope) === true);}diff --git a/src/sessions/memory-session-store.ts b/src/sessions/memory-session-store.tsindex b3c2aaefc..f13700fab 100644--- a/src/sessions/memory-session-store.ts+++ b/src/sessions/memory-session-store.ts@@ -15,6 +15,7 @@ import type {NewLlmRequest,NewSearchEntry,NewSessionPin,+ ParticipantScope,ParticipantWindow,SessionPage,SessionStore,@@ -494,7 +495,9 @@ export function createMemorySessionStore(opts: StoreOptions = {}): SessionStoreconst out: Session[] = [];for (const id of ids) {const row = participantSession(id, principalId);- if (row) out.push(row);+ if (!row) continue;+ const { spawnMeta: _spawnMeta, clientTools: _clientTools, ...listed } = row;+ out.push(listed);}return opts? out@@ -503,6 +506,22 @@ export function createMemorySessionStore(opts: StoreOptions = {}): SessionStore: out;},+ async participantScopes(principalId) {+ const byScope = new Map<ScopeId, ParticipantScope>();+ for (const id of participants.get(principalId) ?? []) {+ const row = participantSession(id, principalId);+ if (!row) continue;+ const scope = byScope.get(row.scopeId) ?? { scopeId: row.scopeId, sessionCount: 0, lastActivityAt: null };+ if (!scope.channelName && row.channelName) scope.channelName = row.channelName;+ if (row.hasEntries !== false || Boolean(row.title?.trim())) {+ scope.sessionCount++;+ scope.lastActivityAt = Math.max(scope.lastActivityAt ?? 0, row.lastActivityAt ?? row.createdAt);+ }+ byScope.set(row.scopeId, scope);+ }+ return [...byScope.values()];+ },+async getForParticipant(sessionId, principalId) {if (!participants.get(principalId)?.has(sessionId)) return null;return participantSession(sessionId, principalId);diff --git a/src/sessions/postgres-session-store.ts b/src/sessions/postgres-session-store.tsindex 9bd86510e..8f1e1d7b5 100644--- a/src/sessions/postgres-session-store.ts+++ b/src/sessions/postgres-session-store.ts@@ -13,6 +13,7 @@ import type {EntrySearchHit,ScopeActivity,DistinctScope,+ ParticipantScope,GetEntriesOptions,Lease,LeaseAttempt,@@ -198,6 +199,8 @@ function rowToEntry(r: Record<string, unknown>): SessionEntry {const ITEM_FIELDS = `i.session_id, i.seq, ${ITEM_COLUMNS.map(([column, key]) => `${column === "blob_sha" ? "encode(i.blob_sha, 'hex')" : `i.${column}`} AS "${key}"`).join(",")}, ts.scope_id AS scope_label, ${msOf("i.created_at")} AS created_at`;const ITEM_FROM = "items i JOIN sessions ts ON ts.id = i.session_id";const TENANT = "qm_tenant_id()";+const LIST_COLUMNS = `s.id, s.type, s.scope_id, s.thread_ref, s.surface, s.created_at, s.title, s.channel_name,+ s.forked_from_session_id, s.forked_from_title, s.fork_boundary_seq, s.parent_session_id`;const tsOf = (ms: string): string => `to_timestamp((${ms})::double precision / 1000)`;function rowToSpendRow(r: Record<string, unknown>): SpendRow {@@ -273,26 +276,52 @@ export function createPostgresSessionStore(connectionString: string, opts: Store),).join(" UNION ALL ");- const participantSessionsSql = (extraWhere: string): string =>- `SELECT s.*, p.title AS p_title, p.archived AS p_archived, p.pinned AS p_pinned, p.color AS p_color,+ const SEES_ITEMS = `CASE WHEN p.valid_to IS NULL AND p.valid_to_seq IS NULL AND p.valid_from_seq IS NOT NULL+ THEN COALESCE(s.messages, 0) > p.valid_from_seq+ ELSE EXISTS (${participantPresenceSql}) END`;+ const HAS_CONTENT = `(NULLIF(btrim(COALESCE(p.title, s.title)), '') IS NOT NULL OR ${SEES_ITEMS})`;+ const latestUserItem = (kind: string): string =>+ `(SELECT ${msOf("e.created_at")} FROM items e WHERE e.tenant_id = ${TENANT} AND e.session_id = s.id+ AND e.kind = '${kind}' ORDER BY e.created_at DESC LIMIT 1)`;+ const USER_ACTIVITY = `GREATEST(s.created_at, ${latestUserItem("UserMessage")}, ${latestUserItem("SteeringMessage")})`;+ const participantSessionsSql = (extraWhere: string, columns = "s.*"): string =>+ `SELECT ${columns}, p.title AS p_title, p.archived AS p_archived, p.pinned AS p_pinned, p.color AS p_color,p.read_at AS p_read_at,(SELECT ${msOf("MAX(e.created_at)")} FROM items eWHERE e.tenant_id = ${TENANT} AND e.session_id = s.id AND ${AGENT_REPLY_ITEM("e")}) AS agent_last_reply,COALESCE((SELECT ${msOf("MAX(e.created_at)")} FROM items eWHERE e.tenant_id = ${TENANT} AND e.session_id = s.id AND e.kind IN ${USER_KINDS}), s.created_at) AS user_last_activity,- EXISTS (${participantPresenceSql}) AS has_entries+ ${SEES_ITEMS} AS has_entriesFROM sessions sJOIN participants p ON p.session_id = s.idWHERE p.principal_id = $1${extraWhere}`;const participantSessions = async (principalId: string, opts?: { limit: number }): Promise<Session[]> => {const limit = opts ? Math.max(0, Math.floor(opts.limit)) : undefined;const rows = await q(- participantSessionsSql("") ++ participantSessionsSql("", LIST_COLUMNS) +(limit === undefined ? "" : " ORDER BY COALESCE(s.last_activity, s.created_at) DESC, s.id LIMIT $2"),limit === undefined ? [principalId] : [principalId, limit],);return rows.map(rowToParticipantSession);};+ const participantScopes = async (principalId: string): Promise<ParticipantScope[]> => {+ const rows = await q(+ `SELECT s.scope_id, MAX(s.channel_name) AS channel_name,+ COUNT(*) FILTER (WHERE ${HAS_CONTENT}) AS session_count,+ MAX(${USER_ACTIVITY}) FILTER (WHERE ${HAS_CONTENT}) AS last_activity+ FROM sessions s+ JOIN participants p ON p.session_id = s.id+ WHERE p.principal_id = $1+ GROUP BY s.scope_id`,+ [principalId],+ );+ return rows.map((r) => ({+ scopeId: r.scope_id as ScopeId,+ ...(r.channel_name != null ? { channelName: r.channel_name as string } : {}),+ sessionCount: Number(r.session_count),+ lastActivityAt: r.last_activity == null ? null : Number(r.last_activity),+ }));+ };const participantSession = async (sessionId: string, principalId: string): Promise<Session | null> => {const rows = await q(participantSessionsSql(" AND s.id = $2"), [principalId, sessionId]);return rows[0] ? rowToParticipantSession(rows[0]) : null;@@ -1430,7 +1459,9 @@ export function createPostgresSessionStore(connectionString: string, opts: Storeconst includeHistory = opts?.includeHistory === true;await q(`WITH boundary AS (- SELECT CASE WHEN $5 THEN 0 ELSE COALESCE(MAX(seq) + 1, 0) END AS seq+ SELECT CASE WHEN $5 THEN 0+ ELSE GREATEST(COALESCE(MAX(seq) + 1, 0),+ COALESCE((SELECT messages FROM sessions WHERE id = $1), 0)) END AS seqFROM items WHERE tenant_id = ${TENANT} AND session_id = $1)INSERT INTO participants(session_id, principal_id, valid_from, valid_to, valid_from_seq, valid_to_seq, title)@@ -1495,6 +1526,10 @@ export function createPostgresSessionStore(connectionString: string, opts: Storereturn participantSessions(principalId, opts);},+ async participantScopes(principalId): Promise<ParticipantScope[]> {+ return participantScopes(principalId);+ },+async getForParticipant(sessionId, principalId): Promise<Session | null> {return participantSession(sessionId, principalId);},diff --git a/src/sessions/session-store.ts b/src/sessions/session-store.tsindex ed8d1ddb5..593902b09 100644--- a/src/sessions/session-store.ts+++ b/src/sessions/session-store.ts@@ -363,6 +363,13 @@ export interface DistinctScope {channelName?: string;}+export interface ParticipantScope {+ scopeId: ScopeId;+ channelName?: string;+ sessionCount: number;+ lastActivityAt: number | null;+}+export interface EntrySearchHit extends Pick<Session, "scopeId" | "title" | "channelName" | "surface" | "archived"> {sessionId: string;seq: number;@@ -577,6 +584,7 @@ export interface SessionStore {addParticipant(sessionId: string, principalId: string, title?: string, opts?: AddParticipantOptions): Promise<void>;removeParticipant(sessionId: string, principalId: string): Promise<void>;listByParticipant(principalId: string, opts?: { limit: number }): Promise<Session[]>;+ participantScopes(principalId: string): Promise<ParticipantScope[]>;getForParticipant(sessionId: string, principalId: string): Promise<Session | null>;deleteSession(sessionId: string): Promise<void>;diff --git a/src/triggers/run-trigger.ts b/src/triggers/run-trigger.tsindex 0030b2d5f..882c61d2d 100644--- a/src/triggers/run-trigger.ts+++ b/src/triggers/run-trigger.ts@@ -11,7 +11,7 @@ import type { DirectoryMember, DirectoryStore, RecipientResolution } from "../diimport { samePerson } from "../directory/person.ts";import type { CurrentScopeMembers } from "../resolution/scope-membership.ts";import { isProjectGroupRef } from "../projects/project-store.ts";-import { reportFailureAs } from "../util/errors.ts";+import { reportFailureAs, swallowAs } from "../util/errors.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 =@@ -29,7 +29,7 @@ export interface TriggerDeps {groupMembership?(groupId: string, principalId: string): Promise<boolean | undefined>;conversationMembers?: DirectoryStore["conversationMembers"];};- sessions?: { listByParticipant(principalId: string): Promise<readonly { scopeId: ScopeId }[]> };+ sessions?: { participantScopes(principalId: string): Promise<readonly { scopeId: ScopeId }[]> };resolveRecipient?: (query: string) => Promise<RecipientResolution>;}@@ -101,8 +101,8 @@ async function relayAttribution(deps: TriggerDeps, spec: TriggerSpec): Promise<s}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;+ const scopes = await deps.sessions?.participantScopes(actorId).catch(swallowAs("trigger: participant scopes", []));+ return scopes?.some((s) => s.scopeId === scope) === true;}async function actorMayReadScope(diff --git a/test/files-http.test.ts b/test/files-http.test.tsindex fcf6e374b..36959f59b 100644--- a/test/files-http.test.ts+++ b/test/files-http.test.ts@@ -30,7 +30,7 @@ function makeUploadApp(files: FileArtifactStore, acl: ReturnType<typeof createAcchannelMember: async (channelId: string, principalId: string) =>channelId === "C1" && (principalId === "U1" || principalId === "U2"),};- const sessions = { listByParticipant: async (_p: string) => [] };+ const sessions = { listByParticipant: async (_p: string) => [], participantScopes: async (_p: string) => [] };const auditLog = { record: () => undefined };const crons = { list: async () => [] };const webhooks = { list: async () => [] };diff --git a/test/member-edit-authz.test.ts b/test/member-edit-authz.test.tsindex f87f75872..c549cf95d 100644--- a/test/member-edit-authz.test.ts+++ b/test/member-edit-authz.test.ts@@ -56,7 +56,10 @@ function makeDeps(overrides: { config?: ScopedConfigStore; advisoryLock?: Advisoreturn undefined;},};- const sessions = { listByParticipant: async () => [] as { scopeId: string }[] };+ const sessions = {+ listByParticipant: async () => [] as { scopeId: string }[],+ participantScopes: async () => [] as { scopeId: string }[],+ };const skills = createSkillStore();const deployRows: Deployment[] = [];const deploy = { listDeployments: async () => deployRows };diff --git a/test/postgres-store.test.ts b/test/postgres-store.test.tsindex e26a1ef79..e6cf63d40 100644--- a/test/postgres-store.test.ts+++ b/test/postgres-store.test.ts@@ -10,6 +10,7 @@ import { createPostgresRunStore } from "../src/runs/postgres-run-store.ts";import { createPostgresRunSignalStore } from "../src/runs/postgres-run-signal-store.ts";import { scopeId, type Principal, type TurnRequest, type TurnResult } from "../src/types.ts";import type { OrchestratorInput } from "../src/core/orchestrator.ts";+import { assertLateJoinerScopes, assertLeanListing } from "./support/participant-scopes.ts";import { assertParticipantSessionParity } from "./support/participant-session-parity.ts";import { assertSpendRollupParity } from "./support/spend-rollup-parity.ts";@@ -3120,3 +3121,31 @@ test("desktop tool definitions survive a store restart without changing on later]);assert.deepEqual(changed.clientTools, [desktopComputerTool]);});++test("pg session lists leave out spawn metadata and group scopes per participant", { skip }, async () => {+ await assertLeanListing(createPostgresSessionStore(URL!), "pg-lean");+});++test("pg participantScopes leaves out sessions whose content predates the participant", { skip }, async () => {+ await assertLateJoinerScopes(createPostgresSessionStore(URL!), "pg-late");+});++test("pg late joiners start after any stored sequence gap", { skip }, async () => {+ const store = createPostgresSessionStore(URL!);+ const scope = scopeId("channel", "gap-C1");+ const session = await store.getOrCreateByThread("slack:gap-C1:1", "channel", scope, "eng");+ await store.addParticipant(session.id, "gap-early");+ const { lease } = await store.acquireLease(session.id);+ assert.ok(lease);+ await store.append(lease, { type: "user", payload: { text: "before" }, scopeLabel: scope });+ await store.releaseLease(lease);+ const pg = (await import("pg")).default;+ const pool = new pg.Pool({ connectionString: URL });+ await pool.query("UPDATE sessions SET messages = messages + 3 WHERE id = $1", [session.id]);+ await pool.end();+ await store.addParticipant(session.id, "gap-late");+ assert.equal((await store.getForParticipant(session.id, "gap-late"))?.hasEntries, false);+ assert.deepEqual(await store.participantScopes("gap-late"), [+ { scopeId: scope, channelName: "eng", sessionCount: 0, lastActivityAt: null },+ ]);+});diff --git a/test/run-trigger-home-scope.test.ts b/test/run-trigger-home-scope.test.tsindex 3350d7457..84e644f6a 100644--- a/test/run-trigger-home-scope.test.ts+++ b/test/run-trigger-home-scope.test.ts@@ -57,7 +57,7 @@ describe("runTrigger home-scope gate when the directory snapshot dropped the chait("falls back to session participation and runs", async () => {let ranTurn = false;const sessions = {- listByParticipant: async (pid: string): Promise<readonly { scopeId: ScopeId }[]> =>+ participantScopes: async (pid: string): Promise<readonly { scopeId: ScopeId }[]> =>pid === OWNER ? [{ scopeId: SCOPE }] : [],};const d = deps(unknownChannelDirectory(), { sessions, onRun: () => (ranTurn = true) });@@ -69,7 +69,7 @@ describe("runTrigger home-scope gate when the directory snapshot dropped the chait("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 sessions = { participantScopes: async (): Promise<readonly { scopeId: ScopeId }[]> => [] };const d = deps(unknownChannelDirectory(), { sessions, onRun: () => (ranTurn = true) });const out = await runTrigger(d, spec("stranger"));assert.equal(ranTurn, false);@@ -94,7 +94,7 @@ describe("runTrigger home-scope gate when the directory snapshot dropped the cha};let ranTurn = false;const sessions = {- listByParticipant: async (): Promise<readonly { scopeId: ScopeId }[]> => [{ scopeId: SCOPE }],+ participantScopes: async (): Promise<readonly { scopeId: ScopeId }[]> => [{ scopeId: SCOPE }],};const d = deps(dir, { sessions, onRun: () => (ranTurn = true) });const out = await runTrigger(d, spec("kicked"));@@ -122,7 +122,7 @@ describe("runTrigger home-scope gate for group homes", () => {let ranTurn = false;const dir = unknownChannelDirectory();const sessions = {- listByParticipant: async (pid: string): Promise<readonly { scopeId: ScopeId }[]> =>+ participantScopes: async (pid: string): Promise<readonly { scopeId: ScopeId }[]> =>pid === OWNER ? [{ scopeId: GSCOPE }] : [],};const d = deps(dir, { sessions, onRun: () => (ranTurn = true) });@@ -142,7 +142,7 @@ describe("runTrigger home-scope gate for group homes", () => {],};const sessions = {- listByParticipant: async (): Promise<readonly { scopeId: ScopeId }[]> => [{ scopeId: GSCOPE }],+ participantScopes: async (): Promise<readonly { scopeId: ScopeId }[]> => [{ scopeId: GSCOPE }],};const d = deps(dir, { sessions, onRun: () => (ranTurn = true) });const out = await runTrigger(d, groupSpec("kicked"));@@ -157,7 +157,7 @@ describe("runTrigger home-scope gate for group homes", () => {groupMembership: async (): Promise<boolean | undefined> => false,};const sessions = {- listByParticipant: async (): Promise<readonly { scopeId: ScopeId }[]> => [{ scopeId: GSCOPE }],+ participantScopes: async (): Promise<readonly { scopeId: ScopeId }[]> => [{ scopeId: GSCOPE }],};const d: TriggerDeps = {deliveries: createDeliveryStore(),diff --git a/test/scope-resources-authz.test.ts b/test/scope-resources-authz.test.tsindex 2d4ed9fb1..54f52f5a9 100644--- a/test/scope-resources-authz.test.ts+++ b/test/scope-resources-authz.test.ts@@ -31,8 +31,12 @@ function makeDeps() {channelMember: async (channelId: string, principalId: string) => principalId === U1 && channelId === C1,channelPrivacy: async (channelId: string): Promise<boolean | undefined> => (channelId === C1 ? true : undefined),};- const sessions: { listByParticipant: (principalId: string) => Promise<unknown[]> } = {+ const sessions: {+ listByParticipant: (principalId: string) => Promise<unknown[]>;+ participantScopes: (principalId: string) => Promise<unknown[]>;+ } = {listByParticipant: async (_p: string) => [],+ participantScopes: async (_p: string) => [],};const skills = createSkillStore();const deployRows: Deployment[] = [];@@ -218,6 +222,8 @@ test("historical participation grants neither context listing nor current scope},]: [];+ deps.sessions.participantScopes = async (principalId: string) =>+ principalId === "U2" ? [{ scopeId: channelScope, channelName: "general", sessionCount: 1, lastActivityAt: 2 }] : [];await deps.skills.create({scopeId: channelScope,manifest: { name: "private", description: "private", requiredCapabilities: [], body: "# Private" },diff --git a/test/session-list-lean.test.ts b/test/session-list-lean.test.tsnew file mode 100644index 000000000..503709ac2--- /dev/null+++ b/test/session-list-lean.test.ts@@ -0,0 +1,49 @@+import "./support/auto-fake-sprites.ts";++import { test } from "node:test";+import assert from "node:assert/strict";+import { mkdtempSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import type { AddressInfo } from "node:net";+import { createInsecureTestServer } from "../src/api/server.ts";+import { buildApp } from "../src/wiring.ts";+import { createMemorySessionStore } from "../src/sessions/memory-session-store.ts";+import type { SpawnMeta } from "../src/types.ts";+import { assertLateJoinerScopes, assertLeanListing } from "./support/participant-scopes.ts";+import { testConfig } from "./support/test-config.ts";++test("listed sessions leave out spawn metadata; scopes count only sessions with content", async () => {+ await assertLeanListing(createMemorySessionStore(), "mem");+});++test("participantScopes leaves out sessions whose content predates the participant", async () => {+ await assertLateJoinerScopes(createMemorySessionStore(), "mem");+});++test("GET /v1/sessions rows carry no spawn metadata, client tools or entry flag", async () => {+ const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "lean-list-")) }));+ const child = await built.sessions.getOrCreateByThread("subagent:root:2", "dm", "personal:U1", undefined, "web", [+ { name: "screenshot", description: "Take a screenshot", inputSchema: { type: "object" } },+ ]);+ await built.sessions.setSpawnMeta(child.id, {+ surface: "web",+ conversation: { kind: "dm", threadRef: "web:U1:root", audience: [] },+ actor: { id: "U1", type: "internal" },+ } as unknown as SpawnMeta);+ await built.sessions.addParticipant(child.id, "U1", "Research task");+ const server = createInsecureTestServer(built.app);+ server.listen(0);+ try {+ const port = (server.address() as AddressInfo).port;+ const res = await fetch(`http://localhost:${port}/v1/sessions?principalId=U1`);+ assert.equal(res.status, 200);+ const body = (await res.json()) as { sessions: Record<string, unknown>[] };+ const row = body.sessions.find((session) => session.id === child.id);+ assert.ok(row);+ assert.equal(row.title, "Research task");+ for (const field of ["spawnMeta", "clientTools", "hasEntries"]) assert.equal(field in row, false, field);+ } finally {+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+});diff --git a/test/support/participant-scopes.ts b/test/support/participant-scopes.tsnew file mode 100644index 000000000..81d4e8908--- /dev/null+++ b/test/support/participant-scopes.ts@@ -0,0 +1,73 @@+import assert from "node:assert/strict";+import type { ScopeId, SpawnMeta } from "../../src/types.ts";+import type { SessionStore } from "../../src/sessions/session-store.ts";++async function appendUser(store: SessionStore, sessionId: string, scope: ScopeId, text: string): Promise<void> {+ const { lease } = await store.acquireLease(sessionId);+ assert.ok(lease);+ await store.append(lease, { type: "user", payload: { text }, scopeLabel: scope });+ await store.releaseLease(lease);+}++export async function assertLateJoinerScopes(store: SessionStore, prefix: string): Promise<void> {+ const scope = `channel:${prefix}-C1` as ScopeId;+ const session = await store.getOrCreateByThread(`slack:${prefix}-C1:1`, "channel", scope, "eng");+ await store.addParticipant(session.id, `${prefix}-early`);+ await appendUser(store, session.id, scope, "before the late joiner");+ await store.addParticipant(session.id, `${prefix}-late`);++ const [early] = await store.participantScopes(`${prefix}-early`);+ assert.equal(early?.sessionCount, 1);+ assert.equal(+ early?.lastActivityAt,+ (await store.getForParticipant(session.id, `${prefix}-early`))?.lastActivityAt,+ "a scope's recency is its newest session's user activity",+ );+ assert.deepEqual(await store.participantScopes(`${prefix}-late`), [+ { scopeId: scope, channelName: "eng", sessionCount: 0, lastActivityAt: null },+ ]);+ assert.equal((await store.getForParticipant(session.id, `${prefix}-late`))?.hasEntries, false);++ await appendUser(store, session.id, scope, "after the late joiner");+ const [late] = await store.participantScopes(`${prefix}-late`);+ assert.equal(late?.sessionCount, 1, "the late joiner counts the session once it has something they can see");+}++export async function assertLeanListing(store: SessionStore, prefix: string): Promise<void> {+ const me = `${prefix}-U1`;+ const personal = `personal:${me}` as ScopeId;+ const channel = `channel:${prefix}-C1` as ScopeId;+ const spawnMeta = {+ surface: "web",+ conversation: { kind: "dm", threadRef: `web:${me}:root`, audience: [] },+ actor: { id: me, type: "internal" },+ } as unknown as SpawnMeta;+ const child = await store.getOrCreateByThread(`subagent:${prefix}-root:1`, "dm", personal, undefined, "web", [+ { name: "screenshot", description: "Take a screenshot", inputSchema: { type: "object" } },+ ]);+ await store.setSpawnMeta(child.id, spawnMeta);+ await store.addParticipant(child.id, me, "Child task");+ const empty = await store.getOrCreateByThread(`web:${me}:empty`, "dm", personal);+ await store.addParticipant(empty.id, me);+ const shared = await store.getOrCreateByThread(`slack:${prefix}-C1:1`, "channel", channel, "eng");+ await store.addParticipant(shared.id, me);+ const theirs = await store.getOrCreateByThread(`web:${prefix}-U2:a`, "dm", `personal:${prefix}-U2` as ScopeId);+ await store.addParticipant(theirs.id, `${prefix}-U2`, "Theirs");++ const listed = (await store.listByParticipant(me)).find((session) => session.id === child.id);+ assert.equal(listed?.title, "Child task");+ assert.equal(listed?.spawnMeta, undefined);+ assert.equal(listed?.clientTools, undefined);+ assert.ok((await store.getForParticipant(child.id, me))?.spawnMeta, "a single session read keeps spawn metadata");++ const scopes = new Map((await store.participantScopes(me)).map((scope) => [scope.scopeId, scope]));+ assert.deepEqual([...scopes.keys()].sort(), [channel, personal].sort());+ assert.equal(scopes.get(personal)?.sessionCount, 1);+ assert.equal(scopes.get(personal)?.lastActivityAt, (await store.getForParticipant(child.id, me))?.lastActivityAt);+ assert.deepEqual(scopes.get(channel), {+ scopeId: channel,+ channelName: "eng",+ sessionCount: 0,+ lastActivityAt: null,+ });+}