Multiplayer agent harness for work.
Projects: link a web project to its Slack home channel (#451)
Regan Bell7dd741802b3d
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.tsindex 59e59eb78..d81374377 100644--- a/plugins/web-ui/server/index.ts+++ b/plugins/web-ui/server/index.ts@@ -892,6 +892,35 @@ const routeRequest = async (req: IncomingMessage, res: ServerResponse) => {return relay(res, r);}+ const projectSlackChannel = path.match(/^\/api\/projects\/([^/]+)\/slack-channel$/);+ if (method === "PUT" && projectSlackChannel) {+ const id = decodeURIComponent(projectSlackChannel[1]!);+ let channel = "";+ try {+ const p = JSON.parse((await readBody(req)) || "{}") as { channel?: unknown };+ if (typeof p.channel === "string") channel = p.channel.trim().slice(0, 200);+ } catch (e) {+ if (e instanceof PayloadTooLargeError) throw e;+ return json(res, 400, { error: "bad_request" });+ }+ if (!channel) return json(res, 400, { error: "bad_request", message: "channel required" });+ const r = await coreFetch(+ "PUT",+ `/v1/projects/${encodeURIComponent(id)}/slack-channel`,+ JSON.stringify({ principalId: user, channel }),+ );+ return relay(res, r);+ }+ if (method === "DELETE" && projectSlackChannel) {+ const id = decodeURIComponent(projectSlackChannel[1]!);+ const r = await coreFetch(+ "DELETE",+ `/v1/projects/${encodeURIComponent(id)}/slack-channel`,+ JSON.stringify({ principalId: user }),+ );+ return relay(res, r);+ }+const removeProjectMember = path.match(/^\/api\/projects\/([^/]+)\/members\/([^/]+)$/);if (method === "DELETE" && removeProjectMember) {const id = decodeURIComponent(removeProjectMember[1]!);diff --git a/plugins/web-ui/src/contexts.ts b/plugins/web-ui/src/contexts.tsindex e99b52d04..bc504bcdb 100644--- a/plugins/web-ui/src/contexts.ts+++ b/plugins/web-ui/src/contexts.ts@@ -95,6 +95,10 @@ export const contextsState = {memberBusy: false,memberError: "",memberSearchedQuery: "",+ slackEditing: false,+ slackValue: "",+ slackBusy: false,+ slackError: "",};let contextsLoading = false;@@ -149,6 +153,10 @@ export function resetContextsState(): void {contextsState.memberBusy = false;contextsState.memberError = "";contextsState.memberSearchedQuery = "";+ contextsState.slackEditing = false;+ contextsState.slackValue = "";+ contextsState.slackBusy = false;+ contextsState.slackError = "";cancelMemberSearchTimer();contextsNotice = "";memberSearchSeq++;@@ -497,8 +505,8 @@ function detailTpl(c: CoreContext): TemplateResult {}</div><aside class="context-settings" aria-label=${c.project ? "Project settings" : "Context settings"}>- ${c.project ? projectMembersSection(c) : nothing} ${contextModelSection(c.scopeId)}- ${ambientPolicySection(c.scopeId)}+ ${c.project ? projectMembersSection(c) : nothing} ${c.project ? projectSlackSection(c) : nothing}+ ${contextModelSection(c.scopeId)} ${ambientPolicySection(c.scopeId)}</aside></div></div>@@ -526,6 +534,182 @@ function memberLabel(context: CoreContext, principalId: string): string {return context.project?.members.find((member) => member.principalId === principalId)?.displayName || principalId;}+function channelNameOptions(): string[] {+ return [+ ...new Set(+ contextsState.list+ .filter((c) => c.kind === "channel" && c.name)+ .map((c) => c.name!.replace(/^#/, ""))+ .sort(),+ ),+ ];+}++async function linkProjectSlackChannel(context: CoreContext): Promise<void> {+ const channel = contextsState.slackValue.trim().replace(/^#/, "");+ if (!context.project || contextsState.slackBusy || !channel) return;+ const resetSeq = contextsResetSeq;+ contextsState.slackBusy = true;+ contextsState.slackError = "";+ drawContexts();+ try {+ const response = await api(`/api/projects/${encodeURIComponent(context.project.id)}/slack-channel`, {+ method: "PUT",+ body: JSON.stringify({ channel }),+ });+ if (resetSeq !== contextsResetSeq) return;+ const project = projectFromResponse(response);+ if (!project) throw new Error("Core returned an invalid project");+ upsertProject(project);+ contextsState.slackEditing = false;+ contextsState.slackValue = "";+ } catch (error) {+ if (resetSeq !== contextsResetSeq) return;+ contextsState.slackError = errMessage(error, "Couldn't link that channel — you must be a member of it.");+ } finally {+ if (resetSeq === contextsResetSeq) {+ contextsState.slackBusy = false;+ drawContexts();+ }+ }+}++async function unlinkProjectSlackChannel(context: CoreContext): Promise<void> {+ const linked = context.project?.slackChannel;+ if (!context.project || !linked || contextsState.slackBusy) return;+ if (!window.confirm(`Unlink #${linked.channelName} from ${context.name || "this project"}?`)) return;+ const resetSeq = contextsResetSeq;+ contextsState.slackBusy = true;+ contextsState.slackError = "";+ drawContexts();+ try {+ const response = await api(`/api/projects/${encodeURIComponent(context.project.id)}/slack-channel`, {+ method: "DELETE",+ });+ if (resetSeq !== contextsResetSeq) return;+ const project = projectFromResponse(response);+ if (!project) throw new Error("Core returned an invalid project");+ upsertProject(project);+ } catch (error) {+ if (resetSeq !== contextsResetSeq) return;+ contextsState.slackError = errMessage(error, "Couldn't unlink the channel.");+ } finally {+ if (resetSeq === contextsResetSeq) {+ contextsState.slackBusy = false;+ drawContexts();+ }+ }+}++function projectSlackLinked(context: CoreContext): TemplateResult {+ const linked = context.project!.slackChannel!;+ return html`+ <div class="project-member-row">+ <span class="context-glyph" aria-hidden="true">${icon(Hash, 15)}</span>+ <span class="project-member-name">${linked.channelName}</span>+ <button+ class="project-icon-button danger"+ type="button"+ aria-label=${`Unlink #${linked.channelName}`}+ title=${`Unlink #${linked.channelName}`}+ ?disabled=${contextsState.slackBusy}+ @click=${() => void unlinkProjectSlackChannel(context)}+ >+ ${icon(X, 15)}+ </button>+ </div>+ <p class="context-hint">+ The agent posts this project's updates to #${linked.channelName}, and everyone in the channel is in the project.+ </p>+ `;+}++function projectSlackEditor(context: CoreContext): TemplateResult {+ const options = channelNameOptions();+ return html`+ <form+ class="project-slack-form"+ @submit=${(e: Event) => {+ e.preventDefault();+ void linkProjectSlackChannel(context);+ }}+ >+ <div class="project-member-search-row">+ ${icon(Hash, 16)}+ <input+ type="text"+ data-focus-key="project-slack-channel"+ autocomplete="off"+ maxlength="200"+ placeholder="channel name"+ list="project-slack-channels"+ aria-label="Slack channel to link"+ .value=${contextsState.slackValue}+ ?disabled=${contextsState.slackBusy}+ @input=${(e: Event) => {+ contextsState.slackValue = (e.target as HTMLInputElement).value;+ }}+ />+ </div>+ <datalist id="project-slack-channels">${options.map((name) => html`<option value=${name}></option>`)}</datalist>+ <div class="project-slack-actions">+ <button class="btn primary" type="submit" ?disabled=${contextsState.slackBusy}>Link</button>+ <button+ class="btn"+ type="button"+ ?disabled=${contextsState.slackBusy}+ @click=${() => {+ contextsState.slackEditing = false;+ contextsState.slackValue = "";+ contextsState.slackError = "";+ drawContexts();+ }}+ >+ Cancel+ </button>+ </div>+ </form>+ `;+}++function projectSlackIdle(): TemplateResult {+ return html`+ <button+ class="btn project-slack-link"+ type="button"+ ?disabled=${contextsState.slackBusy}+ @click=${() => {+ contextsState.slackEditing = true;+ contextsState.slackError = "";+ drawContexts();+ }}+ >+ ${icon(Hash, 15)}<span>Link a channel</span>+ </button>+ <p class="context-hint">+ Give this project a home channel on Slack — the agent will post updates there, and everyone in the channel joins+ the project.+ </p>+ `;+}++function projectSlackSection(context: CoreContext): TemplateResult {+ const project = context.project!;+ let body: TemplateResult;+ if (project.slackChannel) body = projectSlackLinked(context);+ else if (contextsState.slackEditing) body = projectSlackEditor(context);+ else body = projectSlackIdle();+ return html`+ <section class="context-panel project-slack" aria-labelledby="project-slack-title">+ <div class="context-panel-heading">+ <h2 class="context-panel-title" id="project-slack-title">Slack channel</h2>+ </div>+ ${body}+ ${contextsState.slackError ? html`<div class="project-member-status error" aria-live="polite">${contextsState.slackError}</div>` : nothing}+ </section>+ `;+}+function projectMembersSection(context: CoreContext): TemplateResult {const project = context.project!;const pickerOpen = contextsState.memberProjectId === project.id;@@ -538,13 +722,21 @@ function projectMembersSection(context: CoreContext): TemplateResult {<div class="project-member-list">${projectPeople(context).map((principalId) => {const label = memberLabel(context, principalId);+ const viaChannel = Boolean(project.members.find((member) => member.principalId === principalId)?.viaChannel);return html`<div class="project-member-row"><span class="project-member-avatar" aria-hidden="true">${initials(label)}</span><span class="project-member-name">${label}</span>${principalId === project.ownerId ? html`<span class="badge">Owner</span>` : nothing}${- isProjectOwner(context) && principalId !== project.ownerId+ viaChannel && project.slackChannel+ ? html`<span class="badge" title="Joined via the linked Slack channel"+ >#${project.slackChannel.channelName}</span+ >`+ : nothing+ }+ ${+ isProjectOwner(context) && principalId !== project.ownerId && !viaChannel? html`<buttonclass="project-icon-button danger"type="button"@@ -1015,6 +1207,10 @@ function toggleMemberPicker(context: CoreContext): void {contextsState.memberSearching = false;contextsState.memberError = "";contextsState.memberSearchedQuery = "";+ contextsState.slackEditing = false;+ contextsState.slackValue = "";+ contextsState.slackBusy = false;+ contextsState.slackError = "";drawContexts();if (contextsState.memberProjectId)queueMicrotask(() => document.querySelector<HTMLInputElement>("#project-member-search")?.focus());@@ -1029,6 +1225,10 @@ function closeMemberPicker(): void {contextsState.memberSearching = false;contextsState.memberError = "";contextsState.memberSearchedQuery = "";+ contextsState.slackEditing = false;+ contextsState.slackValue = "";+ contextsState.slackBusy = false;+ contextsState.slackError = "";drawContexts();}@@ -1040,6 +1240,10 @@ function scheduleMemberSearch(context: CoreContext): void {contextsState.memberSearching = false;contextsState.memberError = "";contextsState.memberSearchedQuery = "";+ contextsState.slackEditing = false;+ contextsState.slackValue = "";+ contextsState.slackBusy = false;+ contextsState.slackError = "";const query = contextsState.memberQuery.trim();if (query.length < 2) {if (hadVisibleState || contextsState.memberMatches.length) {@@ -1214,6 +1418,10 @@ function selectContext(scopeId: string | null): void {contextsState.memberSearching = false;contextsState.memberError = "";contextsState.memberSearchedQuery = "";+ contextsState.slackEditing = false;+ contextsState.slackValue = "";+ contextsState.slackBusy = false;+ contextsState.slackError = "";contextsState.selected = scopeId;contextsState.resources = null;contextsState.resourcesScope = null;diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.tsindex 4e04c5f78..bfee77f88 100644--- a/plugins/web-ui/src/core-bridge.ts+++ b/plugins/web-ui/src/core-bridge.ts@@ -161,8 +161,10 @@ export interface CoreProject {name: string;ownerId: string;memberIds: string[];+ channelMemberIds?: string[];scopeId: string;- members: Array<{ principalId: string; displayName: string }>;+ members: Array<{ principalId: string; displayName: string; viaChannel?: boolean }>;+ slackChannel?: { channelId: string; channelName: string; linkedBy?: string; linkedAt?: number };createdAt?: number;updatedAt?: number;}diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.cssindex 46e636b9f..557218850 100644--- a/plugins/web-ui/src/shell.css+++ b/plugins/web-ui/src/shell.css@@ -6222,6 +6222,24 @@ a.chat-row-open {flex-direction: column;gap: 10px;}+.project-slack-form {+ display: flex;+ flex-direction: column;+ gap: 8px;+}+.project-slack-actions {+ display: flex;+ gap: 8px;+}+.project-slack .project-slack-link {+ align-self: flex-start;+}+.context-hint {+ margin: 8px 0 0;+ color: var(--muted-foreground);+ font-size: 12px;+ line-height: 1.45;+}.context-model-select {align-self: flex-start;min-width: min(260px, 100%);diff --git a/plugins/web-ui/test/project-slack-channel-source.test.ts b/plugins/web-ui/test/project-slack-channel-source.test.tsnew file mode 100644index 000000000..7aa8ea8ba--- /dev/null+++ b/plugins/web-ui/test/project-slack-channel-source.test.ts@@ -0,0 +1,58 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++const source = readFileSync(new URL("../src/contexts.ts", import.meta.url), "utf8");+const server = readFileSync(new URL("../server/index.ts", import.meta.url), "utf8");+const bridge = readFileSync(new URL("../src/core-bridge.ts", import.meta.url), "utf8");++test("project detail offers a Slack home-channel section", () => {+ assert.match(source, /function projectSlackSection\(/);+ assert.match(source, /c\.project \? projectSlackSection\(c\) : nothing/);+ assert.match(source, /Link a channel/);+});++test("the slack-channel input keeps focus across redraws and commits to state", () => {+ const input = source.match(/<input\s+type="text"\s+data-focus-key="project-slack-channel"[^]*?\/>/)?.[0] ?? "";+ assert.match(input, /\.value=\$\{contextsState\.slackValue\}/);+ assert.match(input, /contextsState\.slackValue = \(e\.target as HTMLInputElement\)\.value/);+});++test("link and unlink go through the project slack-channel API and refresh the project view", () => {+ assert.match(source, /\/slack-channel`, \{\s*method: "PUT"/);+ assert.match(source, /\/slack-channel`, \{\s*method: "DELETE"/);+ const link = source.match(/async function linkProjectSlackChannel[^]*?\n\}/)?.[0] ?? "";+ const unlink = source.match(/async function unlinkProjectSlackChannel[^]*?\n\}/)?.[0] ?? "";+ for (const fn of [link, unlink]) {+ assert.match(fn, /projectFromResponse\(/);+ assert.match(fn, /upsertProject\(/);+ }+ assert.match(unlink, /window\.confirm/);+});++test("the web-ui server proxies slack-channel link routes to core with the signed-in principal", () => {+ assert.match(server, /\/api\\\/projects\\\/\(\[\^/);+ assert.match(server, /slack-channel\$\//);+ const proxy = server.match(/const projectSlackChannel[^]*?const removeProjectMember/)?.[0] ?? "";+ assert.match(proxy, /"PUT",\s*`\/v1\/projects\/\$\{encodeURIComponent\(id\)\}\/slack-channel`/);+ assert.match(proxy, /"DELETE",\s*`\/v1\/projects\/\$\{encodeURIComponent\(id\)\}\/slack-channel`/);+ assert.match(proxy, /JSON\.stringify\(\{ principalId: user, channel \}\)/);+});++test("CoreProject carries the linked slack channel", () => {+ assert.match(+ bridge,+ /slackChannel\?: \{ channelId: string; channelName: string; linkedBy\?: string; linkedAt\?: number \}/,+ );+});++test("channel-derived members are badged and not removable", () => {+ assert.match(source, /viaChannel = Boolean\(/);+ assert.match(source, /principalId !== project\.ownerId && !viaChannel/);+ assert.match(source, /Joined via the linked Slack channel/);+});++test("hint copy says the agent posts there and membership follows the channel", () => {+ assert.match(source, /everyone in the channel joins\s+the project/);+ assert.match(source, /everyone in the channel is in the project/);+});diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.tsindex c13acda84..a1f1f8505 100644--- a/src/api/agent-api-catalog.ts+++ b/src/api/agent-api-catalog.ts@@ -55,7 +55,8 @@ const FAMILIES: AgentApiFamily[] = [(p === "/v1/projects" && (m === "GET" || m === "POST")) ||(/^\/v1\/projects\/[^/]+$/.test(p) && m === "PATCH") ||(/^\/v1\/projects\/[^/]+\/members$/.test(p) && m === "POST") ||- (/^\/v1\/projects\/[^/]+\/members\/[^/]+$/.test(p) && m === "DELETE"),+ (/^\/v1\/projects\/[^/]+\/members\/[^/]+$/.test(p) && m === "DELETE") ||+ (/^\/v1\/projects\/[^/]+\/slack-channel$/.test(p) && (m === "PUT" || m === "DELETE")),guidance:"These act as the ASKING PERSON across every project they belong to, matching the web UI. Do not send principalId; the capability token always determines the person, and inaccessible projects return 404.",routes: [@@ -80,6 +81,17 @@ const FAMILIES: AgentApiFamily[] = [path: "/v1/projects/:id/members/:memberId",summary: "remove a member from a project the asking person owns",},+ {+ method: "PUT",+ path: "/v1/projects/:id/slack-channel",+ summary:+ "link a project to its Slack home channel — body {channel} (name or id; the asking person must be in the project and able to see the channel — public, or a private one they belong to; a channel that already has its own agent workspace is rejected with 409). Everyone in the channel joins the project, and the roster follows the channel from then on; the channel becomes the project's default delivery audience for crons and report-outs.",+ },+ {+ method: "DELETE",+ path: "/v1/projects/:id/slack-channel",+ summary: "unlink a project's Slack home channel — members who joined via the channel leave the project",+ },],},{diff --git a/src/api/app-helpers.ts b/src/api/app-helpers.tsindex 21ba292a0..670681dc1 100644--- a/src/api/app-helpers.ts+++ b/src/api/app-helpers.ts@@ -216,10 +216,15 @@ export function createAppHelpers(deps: AppDeps, app: App) {async function projectView(project: Project): Promise<ProjectView> {const memberIds = (await deps.projects?.members(projectGroupRef(project.id))) ?? project.memberIds;+ const manual = new Set([project.ownerId, ...project.memberIds]);const members = await Promise.all(memberIds.map(async (principalId) => {const member = await deps.directory.get(principalId).catch(() => null);- return { principalId, displayName: member?.displayName?.trim() || principalId };+ return {+ principalId,+ displayName: member?.displayName?.trim() || principalId,+ ...(manual.has(principalId) ? {} : { viaChannel: true }),+ };}),);return { ...project, memberIds, scopeId: projectScopeId(project.id), members };@@ -470,6 +475,53 @@ export function createAppHelpers(deps: AppDeps, app: App) {return (await principalCanAccessCurrentScope(principalId, d.ownerScopeId)) ? "read" : null;}+ async function syncProjectChannelRoster(project: Project, actorId: string): Promise<void> {+ const link = project.slackChannel;+ if (!link || !deps.projects) return;+ const roster = await deps.directory.channelMemberIds(link.channelId).catch(() => undefined);+ if (roster === undefined) return;+ const derived = roster.filter((m) => deps.identity.isInternal(deps.identity.classify(m)));+ const channel = (await deps.directory.listChannels().catch(() => [])).find((c) => c.channelId === link.channelId);+ const prev = project.channelMemberIds ?? [];+ const manual = new Set([project.ownerId, ...project.memberIds]);+ const prevSet = new Set(prev);+ const nextSet = new Set(derived);+ await deps.projects.syncChannelMembers(project.id, derived, channel?.name, async ({ project: p, changed }) => {+ if (!changed) return;+ for (const m of derived) {+ if (prevSet.has(m) || manual.has(m)) continue;+ deps.auditLog.record({+ at: Date.now(),+ principalId: actorId,+ action: "project.member.add",+ resource: m,+ scopeLabel: projectScopeId(p.id),+ });+ await reconcileProjectMember(p, m, true);+ }+ for (const m of prev) {+ if (nextSet.has(m) || manual.has(m)) continue;+ deps.auditLog.record({+ at: Date.now(),+ principalId: actorId,+ action: "project.member.remove",+ resource: m,+ scopeLabel: projectScopeId(p.id),+ });+ await reconcileProjectMember(p, m, false);+ }+ });+ }++ async function syncLinkedProjectRosters(): Promise<void> {+ if (!deps.projects) return;+ for (const project of await deps.projects.listLinked().catch(() => [])) {+ await syncProjectChannelRoster(project, "directory-sync").catch((err) =>+ swallow(`projects: channel roster sync for ${project.id}`, err),+ );+ }+ }+async function reconcileProjectMember(project: Project, memberId: string, add: boolean): Promise<void> {const sessions = (await deps.sessions.listAll()).filter((session) => session.scopeId === projectScopeId(project.id),@@ -552,6 +604,8 @@ export function createAppHelpers(deps: AppDeps, app: App) {principalCanReadDeployment,principalGitPermission,reconcileProjectMember,+ syncProjectChannelRoster,+ syncLinkedProjectRosters,replayOrphanedRunSignals,};}diff --git a/src/api/app-messaging.ts b/src/api/app-messaging.tsindex 766f01241..9ffc01f53 100644--- a/src/api/app-messaging.ts+++ b/src/api/app-messaging.ts@@ -338,6 +338,7 @@ export function createMessagingMethods(},async upsertChannels(channels, channelMembers, syncedAt) {await deps.directory.replaceChannels(channels, channelMembers, syncedAt);+ await h.syncLinkedProjectRosters();},async upsertGroups(groupMembers, syncedAt) {await deps.directory.replaceGroups(groupMembers, syncedAt);diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.tsindex 4bf62a7f9..c756796fb 100644--- a/src/api/app-sessions.ts+++ b/src/api/app-sessions.ts@@ -37,6 +37,7 @@ export function createSessionMethods(| "addProjectMember"| "removeProjectMember"| "renameProject"+ | "setProjectSlackChannel"| "listScopeResources"| "managesScope"| "membershipControlsScope"@@ -65,6 +66,7 @@ export function createSessionMethods(projectsForViewer,projectView,reconcileProjectMember,+ syncProjectChannelRoster,managedProjectMembership,approvalRecordIsCurrent,principalCanAccessCurrentScope,@@ -313,6 +315,56 @@ export function createSessionMethods(return result;},+ async setProjectSlackChannel(id, principalId, channel) {+ if (!deps.projects) return { status: "not_found" };+ if (!deps.identity.isInternal(deps.identity.classify(principalId))) return { status: "forbidden" };+ const existing = await deps.projects.get(id);+ if (!existing || existing.orgId !== orgIdOf()) return { status: "not_found" };+ let link: { channelId: string; channelName: string } | null = null;+ if (channel !== null) {+ const wanted = channel.trim().replace(/^#/, "");+ if (!wanted) return { status: "invalid_channel" };+ const reachable = await deps.directory.listChannelsFor(principalId).catch(() => []);+ const match =+ reachable.find((c) => c.channelId === wanted) ??+ reachable.find((c) => c.name.toLowerCase() === wanted.toLowerCase());+ if (!match) return { status: "invalid_channel" };+ const channelScope = scopeId("channel", match.channelId);+ const inUse = (await deps.sessions.listAll()).some((session) => session.scopeId === channelScope);+ if (inUse) return { status: "channel_in_use" };+ link = { channelId: match.channelId, channelName: match.name };+ }+ const prevDerived = existing.channelMemberIds ?? [];+ const manual = new Set([existing.ownerId, ...existing.memberIds]);+ const result = await deps.projects.setSlackChannel(id, principalId, link, async ({ project, changed }) => {+ if (changed)+ deps.auditLog.record({+ at: Date.now(),+ principalId,+ action: link ? "project.slack_channel.link" : "project.slack_channel.unlink",+ resource: link?.channelId ?? existing.slackChannel?.channelId ?? "",+ scopeLabel: projectScopeId(project.id),+ });+ if (!link) {+ for (const m of prevDerived) {+ if (manual.has(m)) continue;+ deps.auditLog.record({+ at: Date.now(),+ principalId,+ action: "project.member.remove",+ resource: m,+ scopeLabel: projectScopeId(project.id),+ });+ await reconcileProjectMember(project, m, false);+ }+ }+ });+ if (result.status !== "ok") return result;+ if (link) await syncProjectChannelRoster(result.project, principalId);+ const fresh = (await deps.projects.get(id)) ?? result.project;+ return { ...result, project: await projectView(fresh) };+ },+async renameProject(id, principalId, name) {if (!deps.projects) return { status: "not_found" };if (!deps.identity.isInternal(deps.identity.classify(principalId))) return { status: "forbidden" };diff --git a/src/api/app-types.ts b/src/api/app-types.tsindex ae62386f3..f89e39461 100644--- a/src/api/app-types.ts+++ b/src/api/app-types.ts@@ -175,12 +175,12 @@ export type VisibleCron = Cron & { scopeName?: string };export type ProjectView = Project & {scopeId: ScopeId;- members: Array<{ principalId: string; displayName: string }>;+ members: Array<{ principalId: string; displayName: string; viaChannel?: boolean }>;};type ProjectViewMutation =| { status: "ok"; project: ProjectView; changed: boolean }- | { status: "not_found" | "forbidden" | "invalid_member" | "invalid_name" };+ | { status: "not_found" | "forbidden" | "invalid_member" | "invalid_name" | "invalid_channel" | "channel_in_use" };interface DeploymentGitUrl {url: string;@@ -273,6 +273,7 @@ export interface App {createProject(principalId: string, name: string): Promise<ProjectView | null>;addProjectMember(id: string, principalId: string, memberId: string): Promise<ProjectViewMutation>;removeProjectMember(id: string, principalId: string, memberId: string): Promise<ProjectViewMutation>;+ setProjectSlackChannel(id: string, principalId: string, channel: string | null): Promise<ProjectViewMutation>;renameProject(id: string, principalId: string, name: string): Promise<ProjectViewMutation>;updateSession(sessionId: string,diff --git a/src/api/routes/projects.ts b/src/api/routes/projects.tsindex 7f5157825..4847b52b3 100644--- a/src/api/routes/projects.ts+++ b/src/api/routes/projects.ts@@ -38,6 +38,16 @@ function mutationResponse(ctx: ApiCtx, result: Awaited<ReturnType<ApiCtx["app"][return sendJson(ctx.res, ctx.capability ? 404 : 403, { error: ctx.capability ? "not_found" : "forbidden" });if (result.status === "invalid_name")return sendJson(ctx.res, 400, { error: "invalid_name", message: "project name required" });+ if (result.status === "invalid_channel")+ return sendJson(ctx.res, 400, {+ error: "invalid_channel",+ message: "channel not found among the channels you can see",+ });+ if (result.status === "channel_in_use")+ return sendJson(ctx.res, 409, {+ error: "channel_in_use",+ message: "that channel already has its own workspace — it can't also be a project's home channel",+ });return sendJson(ctx.res, 400, {error: "invalid_member",message: "member must be an internal directory member and cannot be the project owner",@@ -77,10 +87,32 @@ async function removeProjectMember(ctx: ApiCtx): Promise<void> {return mutationResponse(ctx, await ctx.app.removeProjectMember(ctx.params.id!, principalId, memberId));}+async function setProjectSlackChannel(ctx: ApiCtx): Promise<void> {+ const body = isObj(ctx.body) ? ctx.body : {};+ const requested = typeof body.principalId === "string" ? body.principalId.trim() : "";+ const principalId = capabilityPrincipal(ctx, requested);+ if (principalId === null) return;+ const channel = typeof body.channel === "string" ? body.channel.trim() : "";+ if (!principalId || !channel)+ return sendJson(ctx.res, 400, { error: "bad_request", message: "principalId and channel required" });+ return mutationResponse(ctx, await ctx.app.setProjectSlackChannel(ctx.params.id!, principalId, channel));+}++async function clearProjectSlackChannel(ctx: ApiCtx): Promise<void> {+ const body = isObj(ctx.body) ? ctx.body : {};+ const requested = typeof body.principalId === "string" ? body.principalId.trim() : "";+ const principalId = capabilityPrincipal(ctx, requested);+ if (principalId === null) return;+ if (!principalId) return sendJson(ctx.res, 400, { error: "bad_request", message: "principalId required" });+ return mutationResponse(ctx, await ctx.app.setProjectSlackChannel(ctx.params.id!, principalId, null));+}+export const projectRoutes: ReadonlyArray<Route<ApiCtx>> = [{ method: "GET", path: "/v1/projects", auth: "either", handle: listProjects },{ method: "POST", path: "/v1/projects", auth: "either", handle: createProject },{ method: "PATCH", path: "/v1/projects/:id", auth: "either", handle: renameProject },{ method: "POST", path: "/v1/projects/:id/members", auth: "either", handle: addProjectMember },{ method: "DELETE", path: "/v1/projects/:id/members/:memberId", auth: "either", handle: removeProjectMember },+ { method: "PUT", path: "/v1/projects/:id/slack-channel", auth: "either", handle: setProjectSlackChannel },+ { method: "DELETE", path: "/v1/projects/:id/slack-channel", auth: "either", handle: clearProjectSlackChannel },];diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.tsindex fdb800127..e81af3c63 100644--- a/src/core/orchestrator.ts+++ b/src/core/orchestrator.ts@@ -150,6 +150,7 @@ import {currentTimeBlock,deliveryMenu,renderConversationRoster,+ renderProjectHomeChannel,renderReachRoster,renderStandingObligations,} from "./orchestrator/prompt-blocks.ts";@@ -861,6 +862,13 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {if (visibleSkills.length) systemPrompt += `\n\n${skillsIndex(visibleSkills)}`;const gatewayBlock = renderGatewayContext(input.surface, input.gatewayContext);if (gatewayBlock) systemPrompt += `\n\n${gatewayBlock}`;+ const homeChannel =+ conversation.kind === "group" && conversation.channelRef+ ? await deps.managedGroups+ ?.slackChannel?.(conversation.channelRef)+ .catch(swallowAs("orchestrator: project home channel read", undefined))+ : undefined;+ if (homeChannel) systemPrompt += `\n\n${renderProjectHomeChannel(homeChannel.channelName)}`;systemPrompt += cronBlock;const sharedFilesBlock = sharedFilesSystemSection(resolution.grantedHandles);if (sharedFilesBlock) systemPrompt += `\n\n${sharedFilesBlock}`;diff --git a/src/core/orchestrator/prompt-blocks.ts b/src/core/orchestrator/prompt-blocks.tsindex 75855ca49..c4b4e93a7 100644--- a/src/core/orchestrator/prompt-blocks.ts+++ b/src/core/orchestrator/prompt-blocks.ts@@ -17,6 +17,16 @@ export function deliveryMenu(candidates: CandidateDestination[], defaultKey: str].join("\n");}+export function renderProjectHomeChannel(channelName: string): string {+ const name = channelName.replace(/^#/, "");+ return [+ "## Project home channel",+ `This project is linked to the Slack channel #${name} — that channel is where the project's people follow the work.`,+ `Treat it as the default external audience: schedule deliveries there (the \`cron\` tool's \`channel: "${name}"\`), and when asked to report out or notify the team, post there with \`reach\` (\`channel: "${name}"\`).`,+ "Project membership follows the channel: everyone in the channel is a member of this project, and people joining or leaving the channel join or leave the project with it.",+ ].join("\n");+}+const OBLIGATIONS_CAP = 10;function cronSchedulePromptLabel(c: Cron): string {const schedule = c.schedule;diff --git a/src/core/orchestrator/types.ts b/src/core/orchestrator/types.tsindex 5801c6db4..bc20a610f 100644--- a/src/core/orchestrator/types.ts+++ b/src/core/orchestrator/types.ts@@ -154,7 +154,7 @@ export interface OrchestratorDeps {serviceCreds?: ServiceCredentialStore;deliveries?: DeliveryStore;directory?: DirectoryStore;- managedGroups?: Pick<ManagedGroupDirectory, "recognizes" | "members" | "version" | "withVersion">;+ managedGroups?: Pick<ManagedGroupDirectory, "recognizes" | "members" | "version" | "withVersion" | "slackChannel">;reachExec?: boolean;eagerProvision?: boolean;environments?: EnvironmentStore;diff --git a/src/directory/directory-store.ts b/src/directory/directory-store.tsindex b3f09fbfe..007f8bd3d 100644--- a/src/directory/directory-store.ts+++ b/src/directory/directory-store.ts@@ -54,6 +54,7 @@ export interface DirectoryStore {resolveChannel(query: string): Promise<ChannelResolution>;channelMember(channelId: string, principalId: string): Promise<boolean>;channelMembership(channelId: string, principalId: string): Promise<boolean | undefined>;+ channelMemberIds(channelId: string): Promise<string[] | undefined>;channelPrivacy(channelId: string): Promise<boolean | undefined>;replaceGroups(groupMembers: GroupMembership[], syncedAt?: number): Promise<boolean>;upsertGroup(groupId: string, principalIds: readonly string[]): Promise<void>;@@ -137,6 +138,10 @@ export function createDirectoryStore(): DirectoryStore {async channelMember(channelId, principalId) {return channelMembers?.get(channelId)?.has(principalId) ?? false;},+ async channelMemberIds(channelId) {+ if (!channelMembers) return undefined;+ return [...(channelMembers.get(channelId) ?? [])];+ },async channelMembership(channelId, principalId) {const memberships = channelMembers;const channel = channels.find((candidate) => candidate.channelId === channelId);diff --git a/src/directory/postgres-directory-store.ts b/src/directory/postgres-directory-store.tsindex 9aae41882..975e12a10 100644--- a/src/directory/postgres-directory-store.ts+++ b/src/directory/postgres-directory-store.ts@@ -315,6 +315,16 @@ export function createPostgresDirectoryStore(connectionString: string): Directorreturn rows.length > 0;},+ async channelMemberIds(channelId) {+ const synced = await q("SELECT channel_members_synced FROM directory_sync WHERE org_id = $1", [orgId]);+ if (synced[0]?.channel_members_synced !== true) return undefined;+ const rows = await q(+ "SELECT principal_id FROM directory_channel_members WHERE org_id = $1 AND channel_id = $2 ORDER BY principal_id",+ [orgId, channelId],+ );+ return rows.map((row) => row.principal_id as string);+ },+async channelMembership(channelId, principalId) {const rows = await q(`SELECT EXISTS (diff --git a/src/projects/project-store.ts b/src/projects/project-store.tsindex 68a53ddfe..3f39aa892 100644--- a/src/projects/project-store.ts+++ b/src/projects/project-store.ts@@ -8,12 +8,21 @@ import { createKeyedQueue } from "../util/async.ts";const PROJECT_GROUP_PREFIX = "web-project-";+interface ProjectSlackChannel {+ channelId: string;+ channelName: string;+ linkedBy: string;+ linkedAt: number;+}+export interface Project {id: string;orgId: string;name: string;ownerId: string;memberIds: string[];+ channelMemberIds?: string[];+ slackChannel?: ProjectSlackChannel;createdAt: number;updatedAt: number;}@@ -31,6 +40,20 @@ export interface ProjectStore {addMember(id: string, actorId: string, memberId: string, effect?: ProjectMutationEffect): Promise<ProjectMutation>;removeMember(id: string, actorId: string, memberId: string, effect?: ProjectMutationEffect): Promise<ProjectMutation>;rename(id: string, ownerId: string, name: string, effect?: ProjectMutationEffect): Promise<ProjectMutation>;+ setSlackChannel(+ id: string,+ actorId: string,+ link: { channelId: string; channelName: string } | null,+ effect?: ProjectMutationEffect,+ ): Promise<ProjectMutation>;+ syncChannelMembers(+ id: string,+ memberIds: readonly string[],+ channelName?: string,+ effect?: ProjectMutationEffect,+ ): Promise<ProjectMutation>;+ listLinked(): Promise<Project[]>;+ slackChannel(groupRef: string): Promise<ProjectSlackChannel | undefined>;recognizes(groupRef: string): boolean;membership(groupRef: string, principalId: string): Promise<boolean | undefined>;members(groupRef: string): Promise<string[] | undefined>;@@ -63,7 +86,12 @@ function cleanName(name: string): string {}function visible(project: Project): Project {- return { ...project, memberIds: [...project.memberIds] };+ return {+ ...project,+ memberIds: [...project.memberIds],+ ...(project.channelMemberIds ? { channelMemberIds: [...project.channelMemberIds] } : {}),+ ...(project.slackChannel ? { slackChannel: { ...project.slackChannel } } : {}),+ };}export function createProjectStore(@@ -90,6 +118,10 @@ export function createProjectStore(return project?.orgId === configOrgId() ? project : undefined;}+ function effectiveMemberIds(project: Project): string[] {+ return [...new Set([...project.memberIds, ...(project.channelMemberIds ?? [])])];+ }+async function mutate(id: string,actorId: string,@@ -164,7 +196,7 @@ export function createProjectStore(project.orgId === configOrgId() &&isActiveMember(project.ownerId) &&isActiveMember(principalId) &&- project.memberIds.includes(principalId),+ effectiveMemberIds(project).includes(principalId),).sort((a, b) => b.updatedAt - a.updatedAt).map(visible);@@ -195,18 +227,101 @@ export function createProjectStore(return result;});},+ async setSlackChannel(id, actorId, link, effect) {+ return withLock(id, async () => {+ if (!backing.update) throw new Error("project store requires DurableMap.update");+ const outcome: { status: ProjectMutation["status"] } = { status: "not_found" };+ let changed = false;+ const updated = await backing.update(id, (project) => {+ const isMember = project.memberIds.some((member) => samePerson(member, actorId));+ if (!isMember || !isActiveMember(project.ownerId) || !isActiveMember(actorId)) {+ outcome.status = "forbidden";+ return project;+ }+ outcome.status = "ok";+ const current = project.slackChannel;+ if (!link) {+ if (!current) return project;+ changed = true;+ const { slackChannel: _dropped, channelMemberIds: _members, ...rest } = project;+ return rest;+ }+ if (current && current.channelId === link.channelId && current.channelName === link.channelName)+ return project;+ changed = true;+ return {+ ...project,+ slackChannel: {+ channelId: link.channelId,+ channelName: link.channelName,+ linkedBy: actorId,+ linkedAt: now(),+ },+ };+ });+ if (!updated) return { status: "not_found" };+ if (outcome.status !== "ok") return { status: outcome.status };+ const result = { status: "ok" as const, project: visible(updated), changed };+ await effect?.(result);+ return result;+ });+ },+ async syncChannelMembers(id, memberIds, channelName, effect) {+ return withLock(id, async () => {+ if (!backing.update) throw new Error("project store requires DurableMap.update");+ const outcome: { status: ProjectMutation["status"] } = { status: "not_found" };+ let changed = false;+ const next = [...new Set(memberIds)].sort();+ const updated = await backing.update(id, (project) => {+ if (!project.slackChannel || !isActiveMember(project.ownerId)) {+ outcome.status = "forbidden";+ return project;+ }+ outcome.status = "ok";+ const current = [...(project.channelMemberIds ?? [])].sort();+ const sameMembers = current.length === next.length && current.every((m, i) => m === next[i]);+ const nextName = channelName ?? project.slackChannel.channelName;+ const sameName = nextName === project.slackChannel.channelName;+ if (sameMembers && sameName) return project;+ changed = true;+ return {+ ...project,+ channelMemberIds: next,+ slackChannel: { ...project.slackChannel, channelName: nextName },+ ...(sameMembers ? {} : { updatedAt: Math.max(now(), project.updatedAt + 1) }),+ };+ });+ if (!updated) return { status: "not_found" };+ if (outcome.status !== "ok") return { status: outcome.status };+ const result = { status: "ok" as const, project: visible(updated), changed };+ await effect?.(result);+ return result;+ });+ },+ async listLinked() {+ return (await backing.all())+ .filter((project) => project.orgId === configOrgId() && project.slackChannel && isActiveMember(project.ownerId))+ .map(visible);+ },+ async slackChannel(groupRef) {+ const project = await projectForGroup(groupRef);+ if (!project || !isActiveMember(project.ownerId) || !project.slackChannel) return undefined;+ return { ...project.slackChannel };+ },recognizes: isProjectGroupRef,async membership(groupRef, principalId) {const project = await projectForGroup(groupRef);return project- ? isActiveMember(project.ownerId) && isActiveMember(principalId) && project.memberIds.includes(principalId)+ ? isActiveMember(project.ownerId) &&+ isActiveMember(principalId) &&+ effectiveMemberIds(project).includes(principalId): undefined;},async members(groupRef) {const project = await projectForGroup(groupRef);if (!project) return undefined;return isActiveMember(project.ownerId)- ? project.memberIds.filter((principalId) => isActiveMember(principalId))+ ? effectiveMemberIds(project).filter((principalId) => isActiveMember(principalId)): [];},async version(groupRef) {diff --git a/src/resolution/scope-membership.ts b/src/resolution/scope-membership.tsindex 05593afe9..17aa0a81c 100644--- a/src/resolution/scope-membership.ts+++ b/src/resolution/scope-membership.ts@@ -8,6 +8,7 @@ export interface ManagedGroupDirectory {members(groupId: string): Promise<string[] | undefined>;version(groupId: string): Promise<string | undefined>;withVersion<T>(groupId: string, version: string | undefined, fn: () => Promise<T>): Promise<T | undefined>;+ slackChannel?(groupId: string): Promise<{ channelId: string; channelName: string } | undefined>;}export interface ScopeMembershipDeps {diff --git a/test/projects.test.ts b/test/projects.test.tsindex 1a876a061..5f394ba17 100644--- a/test/projects.test.ts+++ b/test/projects.test.ts@@ -65,6 +65,87 @@ test("ProjectStore rename is owner-only and cleans the name", async () => {assert.ok(same.status === "ok" && !same.changed);});+test("ProjectStore slack-channel link is member-managed and not a roster change", async () => {+ let at = 500;+ const projects = createProjectStore(undefined, { id: () => "sl", now: () => at++ });+ const project = await projects.create({ name: "Linked", ownerId: "owner" });+ await projects.addMember(project.id, "owner", "member");+ const groupRef = projectGroupRef(project.id);+ const versionBefore = await projects.version(groupRef);++ assert.equal(+ (await projects.setSlackChannel(project.id, "outsider", { channelId: "C1", channelName: "eng" })).status,+ "forbidden",+ );+ assert.equal(await projects.slackChannel(groupRef), undefined);++ const linked = await projects.setSlackChannel(project.id, "member", { channelId: "C1", channelName: "eng" });+ assert.ok(linked.status === "ok" && linked.changed);+ const link = await projects.slackChannel(groupRef);+ assert.equal(link?.channelId, "C1");+ assert.equal(link?.channelName, "eng");+ assert.equal(link?.linkedBy, "member");+ assert.equal((await projects.get(project.id))?.slackChannel?.channelId, "C1");++ const same = await projects.setSlackChannel(project.id, "owner", { channelId: "C1", channelName: "eng" });+ assert.ok(same.status === "ok" && !same.changed);+ assert.equal(+ await projects.version(groupRef),+ versionBefore,+ "linking is not a roster change: in-flight turns and approvals stay current",+ );++ const relinked = await projects.setSlackChannel(project.id, "owner", { channelId: "C2", channelName: "ops" });+ assert.ok(relinked.status === "ok" && relinked.changed);+ assert.equal((await projects.slackChannel(groupRef))?.linkedBy, "owner");++ assert.equal((await projects.setSlackChannel(project.id, "outsider", null)).status, "forbidden");+ const unlinked = await projects.setSlackChannel(project.id, "member", null);+ assert.ok(unlinked.status === "ok" && unlinked.changed);+ assert.equal(await projects.slackChannel(groupRef), undefined);+ const noop = await projects.setSlackChannel(project.id, "member", null);+ assert.ok(noop.status === "ok" && !noop.changed);+ assert.equal((await projects.setSlackChannel("missing", "owner", null)).status, "not_found");+});++test("ProjectStore derives membership from the linked channel roster", async () => {+ let at = 900;+ const projects = createProjectStore(undefined, { id: () => "dr", now: () => at++ });+ const project = await projects.create({ name: "Derived", ownerId: "owner" });+ const groupRef = projectGroupRef(project.id);++ // no link yet: sync is refused+ assert.equal((await projects.syncChannelMembers(project.id, ["chan-pal"])).status, "forbidden");++ await projects.setSlackChannel(project.id, "owner", { channelId: "C1", channelName: "eng" });+ const versionLinked = await projects.version(groupRef);+ const synced = await projects.syncChannelMembers(project.id, ["chan-pal", "owner"]);+ assert.ok(synced.status === "ok" && synced.changed);+ assert.notEqual(await projects.version(groupRef), versionLinked, "derived roster change bumps the scope version");++ // union semantics: manual + derived, deduped+ assert.deepEqual(await projects.members(groupRef), ["owner", "chan-pal"]);+ assert.equal(await projects.membership(groupRef, "chan-pal"), true);+ assert.ok((await projects.listForMember("chan-pal")).some((candidate) => candidate.id === project.id));++ // idempotent re-sync: no version churn+ const versionAfter = await projects.version(groupRef);+ const again = await projects.syncChannelMembers(project.id, ["owner", "chan-pal"]);+ assert.ok(again.status === "ok" && !again.changed);+ assert.equal(await projects.version(groupRef), versionAfter);++ // channel rename flows through without a roster-version bump+ const renamed = await projects.syncChannelMembers(project.id, ["owner", "chan-pal"], "eng-renamed");+ assert.ok(renamed.status === "ok" && renamed.changed);+ assert.equal((await projects.slackChannel(groupRef))?.channelName, "eng-renamed");+ assert.equal(await projects.version(groupRef), versionAfter);++ // unlink drops the derived members with the link+ await projects.setSlackChannel(project.id, "owner", null);+ assert.deepEqual(await projects.members(groupRef), ["owner"]);+ assert.equal(await projects.membership(groupRef, "chan-pal"), false);+});+test("managed groups override Slack membership and historical sessions grant no access", async () => {const projects = createProjectStore(undefined, { id: () => "managed" });const project = await projects.create({ name: "Managed", ownerId: "owner" });@@ -756,3 +837,128 @@ test("leaving a Project still cuts off everything after the member left", asyncassert.equal(await built.app.getSessionForViewer(session.id, "member"), null);assert.deepEqual(await built.app.listSessions("member"), []);});+test("Project slack-channel routes gate on visibility and workspace use, and sync the channel roster", async (t) => {+ const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "projects-slack-")) }));+ const server = createInsecureTestServer(built.app, {});+ const base = await listen(server);+ t.after(() => new Promise<void>((resolve) => server.close(() => resolve())));++ await built.app.upsertDirectory([+ { principalId: "owner", displayName: "Owner", type: "internal" },+ { principalId: "member", displayName: "Member", type: "internal" },+ { principalId: "outsider", displayName: "Outsider", type: "internal" },+ { principalId: "chan-pal", displayName: "Channel Pal", type: "internal" },+ ]);+ const channels = [+ { channelId: "C-ENG", name: "eng", isPrivate: false },+ { channelId: "C-SECRET", name: "war-room", isPrivate: true },+ { channelId: "C-BUSY", name: "busy", isPrivate: false },+ ];+ await built.app.upsertChannels(channels, [+ { channelId: "C-SECRET", principalId: "member" },+ { channelId: "C-ENG", principalId: "owner" },+ { channelId: "C-ENG", principalId: "chan-pal" },+ ]);++ const put = (id: string, principalId: string, channel: string) =>+ fetch(`${base}/v1/projects/${id}/slack-channel`, {+ method: "PUT",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ principalId, channel }),+ });++ const create = await fetch(`${base}/v1/projects`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ principalId: "owner", name: "Linked" }),+ });+ assert.equal(create.status, 201);+ const project = ((await create.json()) as { project: { id: string } }).project;+ const groupRef = projectGroupRef(project.id);+ const scope = projectScopeId(project.id);+ await fetch(`${base}/v1/projects/${project.id}/members`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ principalId: "owner", memberId: "member" }),+ });++ // a session predating the link, so channel-derived members should inherit it+ await built.app.turn({+ surface: "web",+ actor: { externalId: "owner" },+ conversation: { kind: "group", channelRef: groupRef, threadRef: "web:owner:pre", audience: [] },+ text: "before the link",+ });++ // a non-member of the project can't link even a channel they can see+ assert.equal((await put(project.id, "outsider", "eng")).status, 403);+ // a private channel the actor can't see reads as invalid+ assert.equal((await put(project.id, "owner", "war-room")).status, 400);+ assert.equal((await put(project.id, "owner", "no-such-channel")).status, 400);+ assert.equal((await put("missing", "owner", "eng")).status, 404);++ // a channel that already has its own workspace can't become a home channel+ await built.sessions.getOrCreateByThread("ch:C-BUSY:1", "channel", "channel:C-BUSY", "busy", "slack");+ const busy = await put(project.id, "owner", "busy");+ assert.equal(busy.status, 409);+ assert.equal(((await busy.json()) as { error: string }).error, "channel_in_use");++ // linking by #name resolves through the directory and pulls in the channel roster+ const linked = await put(project.id, "owner", "#eng");+ assert.equal(linked.status, 200);+ const linkedProject = (+ (await linked.json()) as {+ project: {+ memberIds: string[];+ slackChannel?: { channelId: string; channelName: string; linkedBy: string };+ members: Array<{ principalId: string; viaChannel?: boolean }>;+ };+ }+ ).project;+ assert.equal(linkedProject.slackChannel?.channelId, "C-ENG");+ assert.equal(linkedProject.slackChannel?.linkedBy, "owner");+ assert.ok(linkedProject.memberIds.includes("chan-pal"), "channel roster joins the project");+ assert.equal(linkedProject.members.find((m) => m.principalId === "chan-pal")?.viaChannel, true);+ assert.equal(linkedProject.members.find((m) => m.principalId === "member")?.viaChannel, undefined);+ assert.equal(await built.projects.membership(groupRef, "chan-pal"), true);+ // ...including the conversations that predate the link+ assert.ok((await built.app.listSessions("chan-pal")).some((s) => s.scopeId === scope));++ // the roster keeps following the channel through directory syncs+ await built.app.upsertChannels(channels, [+ { channelId: "C-SECRET", principalId: "member" },+ { channelId: "C-ENG", principalId: "owner" },+ ]);+ assert.equal(await built.projects.membership(groupRef, "chan-pal"), false, "leaving the channel leaves the project");+ await built.app.upsertChannels(channels, [+ { channelId: "C-SECRET", principalId: "member" },+ { channelId: "C-ENG", principalId: "owner" },+ { channelId: "C-ENG", principalId: "chan-pal" },+ ]);+ assert.equal(+ await built.projects.membership(groupRef, "chan-pal"),+ true,+ "rejoining the channel rejoins the project",+ );++ // manual members never ride the channel roster+ assert.equal(await built.projects.membership(groupRef, "member"), true);++ // unlink: project members only; derived members leave with the link+ const outsiderUnlink = await fetch(`${base}/v1/projects/${project.id}/slack-channel`, {+ method: "DELETE",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ principalId: "outsider" }),+ });+ assert.equal(outsiderUnlink.status, 403);+ const unlink = await fetch(`${base}/v1/projects/${project.id}/slack-channel`, {+ method: "DELETE",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ principalId: "member" }),+ });+ assert.equal(unlink.status, 200);+ assert.equal(await built.projects.slackChannel(groupRef), undefined);+ assert.equal(await built.projects.membership(groupRef, "chan-pal"), false);+ assert.equal(await built.projects.membership(groupRef, "member"), true);+ assert.ok(!(await built.app.listSessions("chan-pal")).some((s) => s.scopeId === scope));+});diff --git a/test/system-prompt-order.test.ts b/test/system-prompt-order.test.tsindex 6eabbf37d..4cedd9b4b 100644--- a/test/system-prompt-order.test.ts+++ b/test/system-prompt-order.test.ts@@ -27,6 +27,7 @@ import type { ConnectorStatusCache } from "../src/credentials/connector-status.timport type { ConnectorTokenStore } from "../src/credentials/keychain.ts";import type { SkillStore } from "../src/skills/skill-store.ts";import { scopeId, type Conversation, type Principal } from "../src/types.ts";+import type { ManagedGroupDirectory } from "../src/resolution/scope-membership.ts";const ORG = "default-org";const actor: Principal = { id: "U1", type: "internal" };@@ -74,7 +75,14 @@ const skills = {visibleFor: async () => [{ skill: { manifest: { name: "deploy", description: "Deploy the app" } }, shadowed: [] }],} as unknown as SkillStore;-function buildOrchestrator(extra: { crons?: CronStore; sandbox?: Sandbox; skills?: SkillStore } = {}) {+function buildOrchestrator(+ extra: {+ crons?: CronStore;+ sandbox?: Sandbox;+ skills?: SkillStore;+ managedGroups?: Pick<ManagedGroupDirectory, "recognizes" | "members" | "version" | "withVersion" | "slackChannel">;+ } = {},+) {const config = createMemoryConfigStore(ORG);const acl = createAclStore();const auditLog = createAuditLog();@@ -308,3 +316,42 @@ test("Slack turns get the terse-response style instruction; other surfaces do noassert.doesNotMatch(nonSlack.reply ?? "", /## Talking on Slack/);assert.doesNotMatch(nonSlack.reply ?? "", /a couple of sentences/);});+test("a project session names its linked Slack home channel; unlinked projects get no block", async () => {+ const managedGroups = {+ recognizes: (ref: string) => ref.startsWith("web-project-"),+ membership: async () => true,+ members: async () => [actor.id],+ version: async () => "1",+ withVersion: async <T>(_ref: string, _version: string | undefined, fn: () => Promise<T>) => fn(),+ slackChannel: async (ref: string) =>+ ref === "web-project-linked" ? { channelId: "C-ENG", channelName: "eng" } : undefined,+ };+ const { orchestrator: orch } = buildOrchestrator({ managedGroups });++ const group = (ref: string, thread: string): OrchestratorInput => ({+ surface: "test",+ actor,+ conversation: {+ kind: "group",+ threadRef: thread,+ channelRef: ref,+ channelName: "Proj",+ audience: [actor],+ } as Conversation,+ text: "!sysprompt",+ scopeVersion: "1",+ sessionParticipantIds: [actor.id],+ origin: { kind: "direct" },+ });++ const linked = await orch.handleTurn(group("web-project-linked", "grp:linked:1"));+ assert.equal(linked.status, "ok", `refused: ${(linked as { reason?: string }).reason}`);+ const prompt = linked.reply ?? "";+ assert.match(prompt, /## Project home channel/);+ assert.match(prompt, /#eng/);+ assert.match(prompt, /channel: "eng"/);++ const unlinked = await orch.handleTurn(group("web-project-bare", "grp:bare:1"));+ assert.equal(unlinked.status, "ok");+ assert.ok(!(unlinked.reply ?? "").includes("## Project home channel"));+});