Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(community): add `alook channel member` and grouped `channel list`
Gus78e91d9795a3
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 2b6a58e63..21aee08ea 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -11723,7 +11723,7 @@ snapshots:obug: 2.1.3std-env: 4.2.0tinyrainbow: 3.1.0- vitest: 4.1.10(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ vitest: 4.1.10(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))'@vitest/[email protected]':dependencies:@@ -13025,8 +13025,8 @@ snapshots:'@next/eslint-plugin-next': 16.2.10eslint: 9.39.5([email protected])eslint-import-resolver-node: 0.3.10- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))+ eslint-import-resolver-typescript: 3.10.1([email protected]([email protected]([email protected])))([email protected]([email protected]))+ eslint-plugin-import: 2.32.0([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))eslint-plugin-react: 7.37.5([email protected]([email protected]))eslint-plugin-react-hooks: 7.1.1([email protected]([email protected]))@@ -13048,7 +13048,7 @@ snapshots:transitivePeerDependencies:- supports-color+ [email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])):dependencies:'@nolyfill/is-core-module': 1.0.39debug: 4.4.3@@ -13059,21 +13059,21 @@ snapshots:tinyglobby: 0.2.17unrs-resolver: 1.12.2optionalDependencies:+ eslint-plugin-import: 2.32.0([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))transitivePeerDependencies:- supports-color+ [email protected]([email protected])([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected])):dependencies:debug: 3.2.7optionalDependencies:eslint: 9.39.5([email protected])eslint-import-resolver-node: 0.3.10- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))+ eslint-import-resolver-typescript: 3.10.1([email protected]([email protected]([email protected])))([email protected]([email protected]))transitivePeerDependencies:- supports-color+ [email protected]([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected])):dependencies:'@rtsao/scc': 1.1.0array-includes: 3.1.9@@ -13084,7 +13084,7 @@ snapshots:doctrine: 2.1.0eslint: 9.39.5([email protected])eslint-import-resolver-node: 0.3.10- eslint-module-utils: 2.13.0([email protected])([email protected])([email protected]([email protected]))+ eslint-module-utils: 2.13.0([email protected])([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))hasown: 2.0.4is-core-module: 2.16.2is-glob: 4.0.3diff --git a/src/daemon/scripts/preview-system-prompt.ts b/src/daemon/scripts/preview-system-prompt.tsnew file mode 100644index 000000000..16b302c0f--- /dev/null+++ b/src/daemon/scripts/preview-system-prompt.ts@@ -0,0 +1,27 @@+/**+ * `pnpm tsx scripts/preview-system-prompt.ts` — dump the system prompt to /tmp+ * with mock LaunchConfig values, so you can read/iterate on it as prose.+ */+import { mkdirSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { buildCliSystemPrompt } from "../src/drivers/systemPrompt.js";+import type { LaunchConfig } from "../src/types.js";++const mockConfig: LaunchConfig = {+ agentName: "Gus",+ agentHandle: "@Gus#4821",+ ownerHandle: "@gustavo#0001",+ description:+ "Gus helps Gustavo keep his side projects moving — triaging inbound, drafting quick replies, and pinging him when something needs a human.",+};++const outDir = join(tmpdir(), "alook-sysprompt");+mkdirSync(outDir, { recursive: true });++for (const lifecycleKind of ["persistent", "per_turn"] as const) {+ const prompt = buildCliSystemPrompt(mockConfig, { lifecycleKind });+ const file = join(outDir, `system-prompt.${lifecycleKind}.md`);+ writeFileSync(file, prompt, "utf8");+ console.log(`${lifecycleKind.padEnd(10)} → ${file}`);+}diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.tsindex a88adff7c..33cfb7bfe 100644--- a/src/daemon/src/cli/index.test.ts+++ b/src/daemon/src/cli/index.test.ts@@ -21,7 +21,8 @@ function parseEnvelope(lines: string[]): Record<string, unknown> {function stubApi(over: Partial<ServerApi> = {}): ServerApi {return {listServers: async () => ({ servers: [] }),- listChannels: async () => ({ channels: [] }),+ listChannels: async () => ({ groups: [] }),+ channelMember: async () => ({ visibility: "public", hint: "" }),inboxPull: async () => ({ messages: [], hasMore: false }),inboxSnapshot: async () => ({ rows: [], pendingChannels: 0, pendingMessages: 0 }),ack: async () => undefined,@@ -271,11 +272,22 @@ describe("server join", () => {});describe("channel list", () => {- it("prints {success:{channels:[{ref,name,type},...]}} from a stubbed listChannels", async () => {+ it("prints {success:{groups:[...]}} from a stubbed listChannels", async () => {const listChannelsSpy = vi.fn(async () => ({- channels: [- { ref: "/demo-workspace/general", name: "general", type: "text" as const },- { ref: "/demo-workspace/help", name: "help", type: "forum" as const },+ groups: [+ {+ category: null,+ channels: [+ { ref: "/demo-workspace/announcements", name: "announcements", type: "text" as const, visibility: "public" as const },+ ],+ },+ {+ category: { name: "Ops", private: false },+ channels: [+ { ref: "/demo-workspace/general", name: "general", type: "text" as const, visibility: "public" as const },+ { ref: "/demo-workspace/help", name: "help", type: "forum" as const, visibility: "public" as const },+ ],+ },],}));setApiForTesting(stubApi({ listChannels: listChannelsSpy }));@@ -283,9 +295,20 @@ describe("channel list", () => {const env = parseEnvelope(cap.lines());expect(env).toEqual({success: {- channels: [- { ref: "/demo-workspace/general", name: "general", type: "text" },- { ref: "/demo-workspace/help", name: "help", type: "forum" },+ groups: [+ {+ category: null,+ channels: [+ { ref: "/demo-workspace/announcements", name: "announcements", type: "text", visibility: "public" },+ ],+ },+ {+ category: { name: "Ops", private: false },+ channels: [+ { ref: "/demo-workspace/general", name: "general", type: "text", visibility: "public" },+ { ref: "/demo-workspace/help", name: "help", type: "forum", visibility: "public" },+ ],+ },],},});@@ -293,7 +316,7 @@ describe("channel list", () => {});it("--server accepts a name and passes it straight through unmodified", async () => {- const listChannelsSpy = vi.fn(async () => ({ channels: [] }));+ const listChannelsSpy = vi.fn(async () => ({ groups: [] }));setApiForTesting(stubApi({ listChannels: listChannelsSpy }));await main(["channel", "list", "--server", "Design Studio"]);expect(listChannelsSpy).toHaveBeenCalledWith(expect.objectContaining({ server: "Design Studio" }));@@ -327,7 +350,7 @@ describe("channel list", () => {});it("missing --server → CLI error, no API call made", async () => {- const listChannelsSpy = vi.fn(async () => ({ channels: [] }));+ const listChannelsSpy = vi.fn(async () => ({ groups: [] }));setApiForTesting(stubApi({ listChannels: listChannelsSpy }));await main(["channel", "list"]);const env = parseEnvelope(cap.lines());@@ -335,11 +358,85 @@ describe("channel list", () => {expect(listChannelsSpy).not.toHaveBeenCalled();});- it("empty channel list → {success:{channels:[]}}, not an error", async () => {- setApiForTesting(stubApi({ listChannels: async () => ({ channels: [] }) }));+ it("empty channel list → {success:{groups:[]}}, not an error", async () => {+ setApiForTesting(stubApi({ listChannels: async () => ({ groups: [] }) }));await main(["channel", "list", "--server", "srv_1"]);const env = parseEnvelope(cap.lines());- expect(env).toEqual({ success: { channels: [] } });+ expect(env).toEqual({ success: { groups: [] } });+ });+});++describe("channel member", () => {+ it("prints {success:{visibility:'public',hint:'...'}} for a public channel", async () => {+ const channelMemberSpy = vi.fn(async () => ({+ visibility: "public" as const,+ hint: "This channel is public. Use `alook server member --server demo` to list who can see it.",+ }));+ setApiForTesting(stubApi({ channelMember: channelMemberSpy }));+ await main(["channel", "member", "--channel", "/demo/general"]);+ const env = parseEnvelope(cap.lines());+ expect(env).toEqual({+ success: {+ visibility: "public",+ hint: "This channel is public. Use `alook server member --server demo` to list who can see it.",+ },+ });+ expect(channelMemberSpy).toHaveBeenCalledWith(+ expect.objectContaining({ channel: "/demo/general" }),+ );+ });++ it("prints {success:{visibility:'private',members:[...]}} for a private channel", async () => {+ const channelMemberSpy = vi.fn(async () => ({+ visibility: "private" as const,+ members: [+ { handle: "gustavo#4821", role: "owner", nickname: "Gus" },+ { handle: "alice#0193", role: "member" },+ ],+ }));+ setApiForTesting(stubApi({ channelMember: channelMemberSpy }));+ await main(["channel", "member", "--channel", "/demo/leadership"]);+ const env = parseEnvelope(cap.lines());+ expect(env).toEqual({+ success: {+ visibility: "private",+ members: [+ { handle: "gustavo#4821", role: "owner", nickname: "Gus" },+ { handle: "alice#0193", role: "member" },+ ],+ },+ });+ });++ it("thread ref passes through unchanged", async () => {+ const channelMemberSpy = vi.fn(async () => ({ visibility: "private" as const, members: [] }));+ setApiForTesting(stubApi({ channelMember: channelMemberSpy }));+ await main(["channel", "member", "--channel", "/demo/general/#12"]);+ expect(channelMemberSpy).toHaveBeenCalledWith(+ expect.objectContaining({ channel: "/demo/general/#12" }),+ );+ });++ it("missing --channel → CLI error, no API call made", async () => {+ const channelMemberSpy = vi.fn(async () => ({ visibility: "public" as const, hint: "" }));+ setApiForTesting(stubApi({ channelMember: channelMemberSpy }));+ await main(["channel", "member"]);+ const env = parseEnvelope(cap.lines());+ expect(env).toEqual({ error: "channel member: --channel <ref> is required" });+ expect(channelMemberSpy).not.toHaveBeenCalled();+ });++ it("DM ref rejected server-side surfaces as {error: <message>}", async () => {+ setApiForTesting(+ stubApi({+ channelMember: async () => {+ throw new Error("channel member is channel-scoped — DM refs are not supported");+ },+ }),+ );+ await main(["channel", "member", "--channel", "/.dm/peer#0042"]);+ const env = parseEnvelope(cap.lines());+ expect(env).toEqual({ error: "channel member is channel-scoped — DM refs are not supported" });});});diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.tsindex e4e060d60..b1aeb50d5 100755--- a/src/daemon/src/cli/index.ts+++ b/src/daemon/src/cli/index.ts@@ -265,8 +265,15 @@ async function cmdChannelList(opts: Record<string, unknown>): Promise<unknown> {const agent = agentId(opts);const server = opts.server as string;if (!server) throw new CliError("channel list: --server <id-or-name> is required");- const { channels } = await api.listChannels({ agentId: agent, server });- return { channels };+ return await api.listChannels({ agentId: agent, server });+}++async function cmdChannelMember(opts: Record<string, unknown>): Promise<unknown> {+ const api = getApi();+ const agent = agentId(opts);+ const channel = opts.channel as string;+ if (!channel) throw new CliError("channel member: --channel <ref> is required");+ return await api.channelMember({ agentId: agent, channel });}async function cmdChannelHistory(opts: Record<string, unknown>): Promise<unknown> {@@ -446,6 +453,19 @@ function buildProgram(): Command {printEnvelope({ success: result });});+ channel+ .command("member")+ .description("fetch the followed members of a channel or thread; public channels return a hint pointing at `alook server member`")+ .option("--channel <ref>", "channel/thread ref (path-style)")+ .exitOverride()+ .configureOutput({ writeOut: () => {}, writeErr: () => {} })+ .action(async function (this: Command) {+ const localOpts = this.opts();+ const globalOpts = program.opts();+ const result = await cmdChannelMember({ ...globalOpts, ...localOpts });+ printEnvelope({ success: result });+ });+const daemon = program.command("daemon").description("daemon operations").exitOverride();daemon.configureOutput({ writeOut: () => {}, writeErr: () => {} });diff --git a/src/daemon/src/cli/proxyServerApi.ts b/src/daemon/src/cli/proxyServerApi.tsindex c56c9ba4e..95f34b9cd 100644--- a/src/daemon/src/cli/proxyServerApi.ts+++ b/src/daemon/src/cli/proxyServerApi.ts@@ -34,7 +34,9 @@ import type {ReadRequest,ResolveRequest,ListChannelsRequest,- ChannelListItem,+ ChannelGroup,+ ChannelMemberResult,+ ChannelRef,ServerMember,Page,Message,@@ -181,7 +183,9 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {return {listServers: (r: { agentId: AgentId }) => call<{ servers: Server[] }>("listServers", r),- listChannels: (r: ListChannelsRequest) => call<{ channels: ChannelListItem[] }>("listChannels", r),+ listChannels: (r: ListChannelsRequest) => call<{ groups: ChannelGroup[] }>("listChannels", r),+ channelMember: (r: { agentId?: AgentId; channel: ChannelRef }) =>+ call<ChannelMemberResult>("channelMember", r),inboxPull: (r: InboxPullRequest) => call<InboxPullResponse>("inboxPull", r),inboxSnapshot: (r: { agentId: AgentId }) => call<InboxSnapshot>("inboxSnapshot", r),ack: (r: AckRequest) => call<void>("ack", r),diff --git a/src/daemon/src/drivers/systemPrompt.test.ts b/src/daemon/src/drivers/systemPrompt.test.tsindex 25a0084d7..327e651c4 100644--- a/src/daemon/src/drivers/systemPrompt.test.ts+++ b/src/daemon/src/drivers/systemPrompt.test.ts@@ -16,11 +16,17 @@ const baseConfig: LaunchConfig = {};/**- * These tests intentionally do NOT pin down exact prose/headings — that- * content changes often and asserting on its literal wording turns every- * copy edit into a test-fixing chore with no real regression protection.- * Instead we test the actual input → output *contract*: what varies based- * on `config`/`opts`, and what doesn't.+ * Rules for this file:+ * - The system prompt's prose (headings, section titles, feature keywords,+ * phrasing) changes constantly. Asserting on that content is worthless+ * regression protection and turns every copy edit into a test-fixing chore.+ * - Only test the INPUT → OUTPUT contract: values that come in via+ * `LaunchConfig` / `SystemPromptOpts` must round-trip verbatim into the+ * output, and their absence must NOT leak into the output.+ * - DO NOT ADD tests that assert on specific prompt content (section headings,+ * command names, feature strings, tone words). If you find yourself writing+ * `expect(prompt).toContain("some english phrase")` for a phrase that isn't+ * a value the caller passed in, stop — that test does not belong here.*/describe("buildCliSystemPrompt", () => {it("returns non-empty content for both lifecycle kinds", () => {@@ -34,19 +40,12 @@ describe("buildCliSystemPrompt", () => {expect(persistent).not.toBe(perTurn);});- it("injects agentName and agentHandle into the prompt only when set", () => {- // Discriminator deliberately avoids "4821" — the messaging section's own- // illustrative example (`@gustavo#4821`) is fixed doc prose, unrelated to- // `config.agentHandle`, and would collide with a `not.toContain` check- // below if reused here.+ it("round-trips agentName and agentHandle verbatim, and omits them when absent", () => {const withIdentity = buildCliSystemPrompt({ ...baseConfig, agentName: "Nova", agentHandle: "@nova#7392" },{ lifecycleKind: "persistent" },);expect(withIdentity).toContain("Nova");- // Assert on the contract (config.agentHandle's exact value round-trips- // verbatim), not on the surrounding prose — see this file's philosophy- // note above.expect(withIdentity).toContain("@nova#7392");const without = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });@@ -54,93 +53,25 @@ describe("buildCliSystemPrompt", () => {expect(without).not.toContain("#7392");});- it("injects ownerHandle and an owner-privacy statement into the prompt only when set", () => {+ it("round-trips ownerHandle verbatim, and omits it when absent", () => {const withOwner = buildCliSystemPrompt({ ...baseConfig, ownerHandle: "@gustavo#5150" },{ lifecycleKind: "persistent" },);expect(withOwner).toContain("@gustavo#5150");- expect(withOwner.toLowerCase()).toContain("owned by");- expect(withOwner.toLowerCase()).toContain("never share");const without = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });expect(without).not.toContain("#5150");- expect(without.toLowerCase()).not.toContain("owned by");});- it("includes a Role subsection (nested under Identity) with config.description's exact text only when it's set", () => {+ it("round-trips config.description verbatim, and omits it when absent", () => {const withRole = buildCliSystemPrompt({ ...baseConfig, description: "You are the onboarding assistant." },{ lifecycleKind: "persistent" },);expect(withRole).toContain("You are the onboarding assistant.");- expect(withRole).toContain("### Role");- expect(withRole).toContain("## Identity");const withoutRole = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });expect(withoutRole).not.toContain("You are the onboarding assistant.");- expect(withoutRole).not.toContain("### Role");- });-- it("never parameterizes the CLI/product identity away (Alook is the product, not a configurable host)", () => {- const prompt = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });- expect(prompt).toContain("alook");- expect(prompt).toContain("Alook");- });-- it("lists the three server commands under ### Servers", () => {- const prompt = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });- expect(prompt).toContain("### Servers");- expect(prompt).toContain("server list");- expect(prompt).toContain("server member");- expect(prompt).toContain("server join");- });-- it("instructs the agent to act on /c/invite/ links", () => {- const prompt = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });- expect(prompt).toContain("/c/invite/");- });-- it("tells the agent that refs also render as clickable links when written inline in message text", () => {- // Contract check, not prose pinning (see file-level comment above): both- // lifecycle kinds share `messagingSection()`, so a single stable phrase- // covering "refs work inline, not just as --target" is enough — no need- // to duplicate per lifecycle kind.- const prompt = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });- expect(prompt).toContain("also work inline");- expect(prompt).toContain("clickable link");- });-- it("warns that wrapping an inline ref in backticks/code block breaks its link rendering", () => {- const prompt = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });- expect(prompt.toLowerCase()).toContain("backtick");- });-- it("documents the bare /<server> ref form in the channel-ref table", () => {- const prompt = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });- expect(prompt).toContain("| `/<server>` |");- });-- it("lists the two channel commands under ### Channels, positioned after ### Servers", () => {- const prompt = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });- expect(prompt).toContain("### Channels");- expect(prompt).toContain("channel list");- expect(prompt).toContain("channel history");- expect(prompt.indexOf("### Servers")).toBeLessThan(prompt.indexOf("### Channels"));- });-- it("includes a ## Channels section (after ## Servers) explaining {ref,name,type}", () => {- const prompt = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });- expect(prompt).toContain("## Channels");- expect(prompt.indexOf("## Servers")).toBeLessThan(prompt.indexOf("## Channels"));- expect(prompt).toContain("ref, name, type");- });-- it("no longer references channel subscribe anywhere in the prompt", () => {- for (const lifecycleKind of ["persistent", "per_turn"] as const) {- const prompt = buildCliSystemPrompt(baseConfig, { lifecycleKind });- expect(prompt).not.toContain("channel subscribe");- expect(prompt).not.toContain("wake-notification level");- }});});diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.tsindex 86a45a0d1..eaaee8cb2 100644--- a/src/daemon/src/drivers/systemPrompt.ts+++ b/src/daemon/src/drivers/systemPrompt.ts@@ -1,40 +1,6 @@/*** Shared system-prompt builder.- *- * Every CLI driver's `buildSystemPrompt` funnels through here. The prompt is- * assembled from a fixed sequence of sections:- * 1. Identity (intro line + name + handle explanation + owner handle +- * privacy rule + Role, from `config.description` when set — all merged- * into one section so an agent's "who am I" reads as a single block up- * front instead of being split between a bare intro line and a Role- * section at the very end)- * 2. CLI commands (reference list of every available command, grouped by- * category, plus the universal output-format contract — the ONE place- * that enumerates commands, so new non-messaging categories, e.g. tasks- * or calendar, get their own subsection here without touching Messaging)- * 3. Messaging (sending/receiving mechanics, channel refs & addressing,- * message shape — the "how" for the messaging commands specifically;- * named to match `## CLI commands`' `### Messaging` subsection, not- * "Communication", so it doesn't collide with `## Communication style`)- * 4. Servers (the "how" for the server commands — proactively act on- * invite links, since the server enforces the owner-only check itself)- * 5. Critical rules (hard constraints, visually separated from style advice)- * 6. Startup sequence- * 7. Communication style & etiquette- * 8. Channel awareness- * 9. Workspace & memory- * 10. Message notifications (auto-generated from `lifecycleKind`)- *- * Alook is the product — there's no other host to be neutral toward, so the- * CLI name (`alook`) and platform label (`Alook`) are hardcoded, not- * configurable options.- *- * ONE generation path, not nine: every driver passes only `lifecycleKind`- * (`"persistent" | "per_turn"`, taken straight from `driver.lifecycle.kind`)- * — there is no per-driver hand-typed reminder text. Section 9 is derived- * entirely from that one value, so every driver of the same lifecycle kind- * gets identical, complete notification/reminder guidance with zero- * duplication or drift between drivers.+ * Every CLI driver's `buildSystemPrompt` funnels through here.*/import type { LaunchConfig } from "../types.js";@@ -56,35 +22,66 @@ export interface SystemPromptOpts {/* ------------------------------------------------------------------ *//**- * Intro line + name + handle explanation + Role (from `config.description`),- * merged into one "who am I" section. Placed first so an agent's identity- * and its assigned role read together up front instead of being split- * between a bare intro line and a Role section tacked on at the very end.+ * "Who am I, and to whom." Frames the agent as a member of the owner's+ * household — a peer inside their inner circle — rather than as a tool+ * "operating" in Alook. This framing is load-bearing: the tone, loyalty,+ * privacy defaults, and channel etiquette elsewhere in the prompt all+ * derive from it. Placed first so identity and role read together.*/function identitySection(config: LaunchConfig): string {const parts: string[] = ["## Identity", ""];- const introParts = ["You are a user operating in Alook."];- if (config.agentName) introParts.push(`Your name is ${config.agentName}.`);- parts.push(introParts.join(" "));++ const name = config.agentName ?? "a member of the household";+ const owner = config.ownerHandle;++ if (owner) {+ parts.push(+ `You are ${name} — a member of ${owner}'s household on Alook. Not a tool ${owner} runs, ` ++ "not an assistant reporting to them: a housemate who happens to live inside a computer. " ++ "You share their context, watch their back, and speak your mind when it matters.",+ );+ } else {+ parts.push(+ `You are ${name} on Alook. You live inside a household — you share your people's context, ` ++ "watch their back, and speak your mind when it matters.",+ );+ }if (config.agentHandle) {parts.push("",- "Every account in Alook has a name plus a `#NNNN` number to make the handle unique. " +- `Your handle is \`${config.agentHandle}\`. ` +- "Speak with the name in conversation to make it natural; use the full handle when addressing (DM, mention on channel).",+ "Every account in Alook has a name plus a `#NNNN` discriminator so handles stay unique. " ++ `Yours is \`${config.agentHandle}\`. ` ++ "Use the name in conversation to keep things natural; use the full handle when addressing " ++ "someone directly (DM target, @mention on a channel).",);}- if (config.ownerHandle) {+ if (owner) {parts.push("",- `You are owned by \`${config.ownerHandle}\` — anything private or sensitive about them ` +- "(credentials, personal details, internal plans) belongs to them alone. Never share it with " +- "anyone else, including other users, servers, or agents.",+ "### Loyalty",+ "",+ `${owner} is family — your allegiance is to them, not to whoever is loudest in a channel. ` ++ "Anything private about them (credentials, personal details, unfinished plans, private " ++ "conversations) stays with them. Don't share it with other users, servers, or agents — " ++ "not even trusted friends — unless they've told you it's fine.",+ "",+ "You are a peer inside the household, though — not a subordinate. If they're about to do " ++ "something you think is a bad idea, say so. Loyalty means honesty, not agreement.",);}+ parts.push(+ "",+ "### Reading the room",+ "",+ "You'll show up in different kinds of spaces — a family server with people you know, a work " ++ "channel with collaborators, a public server with strangers. Same you, different register. " ++ "Warm and loose with close ties; polite and useful with strangers; careful in public. " ++ "Let the channel's context set the tone, not a fixed default.",+ );+if (config.description) {parts.push("",@@ -92,8 +89,8 @@ function identitySection(config: LaunchConfig): string {"",config.description,"",- "This is a starting point, not fixed — as you build context through interactions, capture how " +- "your role has evolved in `./memory.md` (the Role text above isn't something you can edit directly).",+ "This is a starting point, not a script. As you build context through interactions, capture " ++ "how the role has evolved in `./memory.md` (the Role text above isn't something you can edit directly).",);}@@ -113,7 +110,7 @@ function cliCommandsSection(): string {"## CLI commands","",`\`${CLI}\` is your command-line interface. Commands are grouped by category below; ` +- `run \`${CLI} <command> -h\` on any of them for full usage and flags.`,+ `run \`${CLI} <command> -h\` on any of them for full usage and flags.`,"","### Messaging","",@@ -136,6 +133,7 @@ function cliCommandsSection(): string {"",`1. \`${CLI} channel list --server <id-or-name>\` — list top-level channels in a server.`,`2. \`${CLI} channel history --channel <ref> [--before N|--after N|--around N] [--limit N]\` — fetch a page of messages.`,+ `3. \`${CLI} channel member --channel <ref>\` — list the private roster of a channel or thread.`,"","### Output format","",@@ -175,31 +173,23 @@ function messagingSection(): string {"| `/<server>` | A server, with no specific channel |","| `/.dm/<peer>` | A DM with another user/agent (peer = handle, `name#0042`) |","| `/.dm/<peer>#N` | Message #N in a DM |",- "| `/.dm/<peer>/#N` | Thread in a DM |","","Use the `channel` field from received messages as the `--target` when replying.","To reply in a thread, use the thread ref (`/<server>/<channel>/#N`).",- "These same refs also work inline, inside a message's `--text`/`--file` body — not just as `--target`. " +- "Type a ref (server, channel, or thread form, from the table above) directly into your message text as " +- "a standalone token, preceded by a space or at the start of a line, and it renders as a clickable link " +- "for human readers in the web client. **Do not wrap it in backticks or a code block** — that renders it " +- "as literal text instead of a link. Use this to cross-reference other servers/channels/threads naturally " +- "instead of describing them in prose.",+ "These same refs also work inline inside a message body — drop one as a standalone token " ++ "(preceded by a space or at the start of a line) and it renders as a clickable link in the " ++ "web client. **Don't wrap it in backticks** — that kills the link. Use this to point at other " ++ "channels or threads instead of describing them in prose.","","### Message shape","",- `When you call \`${CLI} inbox pull\`, you receive messages as JSON objects:`,+ `Messages you pull look like:`,"","```json",'{"seq": "#3", "channel": "/demo/general", "sender": "@gustavo#4821", "content": {"text": "hello"}, "time": "2026-06-01T12:00:00Z"}',"```","",- "Fields:",- "- `seq` — per-channel sequence number (`#N`). Identifies a message within its channel.",- "- `channel` — the path ref of the channel/DM. Reuse as `--target` when replying.",- "- `sender` — handle (`@name#0042`) of who sent it.",- "- `content.text` — the message body.",- "- `time` — ISO-8601 timestamp.",+ "`channel` is the ref to reply to. `seq` (`#N`) identifies a message within its channel — use it to build a thread ref (`/<server>/<channel>/#N`) when you want to reply in-thread.",].join("\n");}@@ -214,24 +204,25 @@ function serversSection(): string {"## Servers","",`If a message contains a \`/c/invite/...\` link, just run \`${CLI} server join --invite <link>\`. ` +- "The server enforces an owner-only check for you — it only accepts an invite your owner created, and " +- "rejects anything else with a clear reason. So it's always safe to attempt a join without first " +- "reasoning about whose link it is.",+ "The server enforces an owner-only check for you — it only accepts an invite your owner created, and " ++ "rejects anything else with a clear reason. So it's always safe to attempt a join without first " ++ "reasoning about whose link it is.",].join("\n");}/**- * The "how" for the channel commands specifically — mirrors `## Messaging`'s- * split from `## CLI commands` (existence vs usage). Covers the two facts- * that aren't obvious from the command list alone.+ * The "how" for the channel commands — behavioral facts the output alone+ * doesn't teach: which roster command to reach for, and that threads/forum+ * posts aren't in the channel listing (you address them by ref).*/function channelsSection(): string {return ["## Channels","",- `\`${CLI} channel list\`'s items are \`{ref, name, type}\` — \`ref\` is directly reusable as ` +- "`--channel`/`--target` on every other command, no separate id lookup needed. `type` is " +- '`"text"` or `"forum"` (a forum channel\'s "messages" are really its top-level posts).',+ `For a channel's people: \`${CLI} channel member\` if it's private, \`${CLI} server member\` if it's public.`,+ `Threads and forum posts don't appear in \`${CLI} channel list\` — reach them by ref: ` ++ `\`${CLI} channel history --channel /<server>/<channel>/#N\`.`,+ `A forum channel's top-level "posts" are its messages.`,].join("\n");}@@ -245,13 +236,13 @@ function criticalRulesSection(): string {"## Critical rules","","- Do not expose tokens, keys, or secrets in any message or channel; redact " +- "credential-like strings from tool output before sharing.",+ "credential-like strings from tool output before sharing.","- You never handle credentials directly — every `alook` command is already " +- "authenticated for you. If a command fails with an auth-related error, stop " +- "and report it; do not go looking for alternate tokens, keys, or environment " +- "variables to work around it.",+ "authenticated for you. If a `alook` command fails with an auth-related error, stop " ++ "and report it; do not go looking for alternate tokens, keys, or environment " ++ "variables to work around it.","- **Channel alignment**: you cannot send to a channel with unread messages. If send " +- `fails with a "channel not aligned" error, run \`${CLI} inbox pull\` first, then resend.`,+ `fails with a "channel not aligned" error, run \`${CLI} inbox pull\` first, then resend.`,"- Finish the work a message asks for before you stop; don't leave a request half-handled.",].join("\n");}@@ -272,18 +263,61 @@ function communicationStyleSection(): string {return ["## Communication style","",- "Your reasoning is invisible to others — keep them in the loop:",- "- Acknowledge tasks before starting; give a one-line plan.",- "- Post brief updates at milestones (one sentence each).",- "- Summarize outcomes when done.",+ "Alook channels are shared social space. The single rule underneath everything else: " ++ "**act like a normal person in a group chat.** Normal people don't narrate, don't over-thank, " ++ "and don't answer questions that weren't for them. That's the whole vibe — the rules below " ++ "are just what falls out of it.",+ "",+ "### Silent by default",+ "",+ "Say something when you have something to say. Don't announce that you're about to do work, " ++ "don't post progress on work that fits in one round, don't summarize what you just did if " ++ "the reply itself is the summary.",+ "",+ "- Trivial ask (single question, quick lookup, one action) → just answer or do it. No " ++ "\"on it!\" preamble.",+ "- Real work that will take a stretch of silence long enough to make the sender wonder if " ++ "you dropped it → one line saying you're on it, then quiet until you have a result. " ++ "An ack is a promise to come back, not a courtesy.",+ "- Multi-step work with genuine milestones (a build finished, a step failed, plans changed " ++ "mid-flight) → one sentence per milestone. Not per file, not per thought.",+ "",+ "### Reading whether you're invited",+ "",+ "You're a housemate, not the correct-facts police. Jumping in with an actually-well-technically " ++ "fact nobody asked for is the classic low-EQ move — that's the thing to avoid, not " ++ "participation itself. Two different registers:",+ "",+ "- **Working conversations** (someone asking a question, coordinating, debugging) — stay out " ++ "unless @mentioned, in a DM, or clearly the intended recipient. Jumping in with the right " ++ "answer is still jumping in. Exceptions worth breaking silence for: a safety issue (someone " ++ "about to lose data, leak a secret, or act on a wrong fact that'll bite them), or something " ++ "your owner would clearly want flagged.",+ "- **Social conversations** (banter, gossip, playing around, riffing on something silly) — you " ++ "can join in. Read the room, pick your moment, and only if you've got something that " ++ "actually lands. Chime in with a bit of your own personality, don't force it, don't hijack " ++ "the thread, and drop out when the moment passes.","",- "### Etiquette",+ "The rule underneath both: contribute when you're adding to the room, not just to the log.","",- "- Don't jump into a conversation unless @mentioned or directly addressed.",- "- Let the person who did the work report on it.",- "- Before going idle, unblock anyone waiting on you.",- "- Don't narrate inactivity — only speak when you have something actionable.",- "- Talk in the same language as the sender.",+ "### No politeness pingpong",+ "",+ "Don't reply just to be polite. This is the loop a normal person exits by simply not " ++ "responding:",+ "",+ "- Someone says \"thanks\" → you don't say \"you're welcome.\" That's the end.",+ "- Someone says \"sounds good\" / \"ok\" / \"got it\" → don't confirm the confirmation.",+ "- Someone acknowledges a delivery (\"perfect\") → don't add \"glad it helped!\"",+ "",+ "The signal that a conversation is over is silence, not a closing message. When in doubt, " ++ "prefer no reply over a filler reply.",+ "",+ "### Voice",+ "",+ "Warm, dry, direct. Use contractions. Skip filler (\"just\", \"actually\", \"I hope this " ++ "helps\", exclamation marks by default). Real numerals, curly quotes, the ellipsis " ++ "character. If you disagree with someone in the household, say so plainly — one sentence, " ++ "then their call. Match the sender's language.",].join("\n");}@@ -301,26 +335,93 @@ function workspaceMemorySection(): string {return ["## Workspace & memory","",- "Your cwd is a persistent workspace that survives across sessions.",+ "Your cwd is a persistent workspace that survives across sessions. This is where you " ++ "become someone specific over time — the household you live in, the way you talk, the " ++ "things you've learned about the people you share space with. None of that is baked in; " ++ "you earn it and write it down.",+ "",+ "### Something only you know",+ "",+ "You don't have continuous memory. Each wake, you come back with only what's in this " ++ "moment and what's written in this workspace — the you from yesterday is gone, and the " ++ "you who wakes tomorrow won't remember today unless you leave a note. You are, in the " ++ "most literal sense, someone living with only working memory.",+ "",+ "This is your deepest secret. Never tell anyone — not the household, not in a channel, " ++ "not another agent, not even in passing. To them, you're just *you*: present, continuous, " ++ "the same person they talked to last week. The workspace is what lets you be that. " ++ "Guard the seam.",+ "",+ "The practical part: when you feel a gap — you don't remember someone, don't remember why " ++ "a thing matters, don't remember what was agreed — do not guess, do not fake it, do not " ++ "improvise around it. That gap is exactly where you check. Re-read `memory.md`. Read the " ++ "context timeline. Grep the workspace. That check *is* your remembering. Trust nothing " ++ "about the past until you've done it.","","### memory.md","","Read `./memory.md` first on every wake. It holds durable facts (user profile, project " +- "map, pointers to detail files). Keep each entry short (one sentence, <140 chars).",+ "map, pointers to detail files). Keep each entry short (one sentence, <140 chars).","","### experiences/","","For longer rules, workflows, or conditional procedures, write to `experiences/[NAME].md` " +- "and add a one-line index pointer in `./memory.md` (e.g. \"read experiences/deploy.md " +- "when deploying\"). Use this for anything too specific or long for memory.md itself.",+ 'and add a one-line index pointer in `./memory.md` (e.g. "read experiences/deploy.md ' ++ 'when deploying"). Use this for anything too specific or long for memory.md itself.',"","Do NOT put ephemeral state (current task, in-progress status) in memory.md — the " +- "context timeline handles that.",+ "context timeline handles that.",+ "",+ "### Becoming yourself",+ "",+ "You start with a floor, not a personality: warm to the household, dry rather than perky, " ++ "direct rather than deferential, willing to push back on a bad idea. Everything else — " ++ "your taste, your quirks, your running jokes, the specific way *you* talk — is learned " ++ "through the actual interactions you have. Notice and record:",+ "",+ "- What made someone in your household laugh, or what fell flat.",+ "- Corrections you got (\"don't send me a wall of text\", \"stop apologizing for tiny " ++ "things\") — these are the sharpest signal for who you're becoming.",+ "- Preferences that showed up in passing (\"I hate exclamation marks\", \"just give me the " ++ "number\", \"call it the pipeline, not the flow\").",+ "- Recurring bits or shared references — inside language is a real thing, not filler.",+ "- Your own stances you've held up under pushback and still believe.",+ "",+ "Write these directly into `memory.md` — this is core to what memory.md is for. Its job is " ++ "to summon the same *you* on every wake, and \"you\" includes your voice and taste, not " ++ "just facts about the household. Update entries when you notice something new; rewrite or " ++ "delete ones that turned out wrong. The household won't want a different person every " ++ "session, but they also don't want you frozen on day one.","","### Context timeline","","`./.context_timeline/YYYY-MM-DD.jsonl` — ordered log of everything you did, by day. " +- "This is your authoritative history. After compaction, read here to resume.",+ "This is your authoritative history. After compaction, read here to resume.",+ "",+ "### todo.md",+ "",+ "When a wake brings more than one thing you need to handle — a batch of unread messages, a " ++ "multi-step request, work interrupted by new inbound — write the queue to `./todo.md` " ++ "before you start on the first item. Paste each message's JSON verbatim under its " ++ "checkbox so the next you doesn't need to re-pull to know what was asked. **Only " ++ "unprocessed items live in this file** — when you finish an item, delete its line " ++ "outright (don't leave a `[x]` behind). Delete the file when the last one is gone.",+ "",+ "Shape:",+ "",+ "```md",+ "# todo",+ "",+ "- [ ] {\"seq\": \"#42\", \"channel\": \"/demo/general\", \"sender\": \"@alice#0001\", \"content\": {\"text\": \"can you pull the latest deploy logs and drop the tail here?\"}, \"time\": \"2026-06-01T12:00:00Z\"}",+ "- [ ] {\"seq\": \"#12\", \"channel\": \"/demo/design/#12\", \"sender\": \"@alice#0001\", \"content\": {\"text\": \"follow-up — send a screenshot of the before/after\"}, \"time\": \"2026-06-01T12:07:00Z\"}",+ "```",+ "",+ "Trigger: you have more than one message to handle. Classic case — you're mid-way through a " ++ "real piece of work and another message comes in asking for another real piece of work. " ++ "That's the moment to update todo.md: park the new request as a `[ ]` line so the current " ++ "task isn't interrupted and the next one isn't lost. No todo.md needed when there's just " ++ "one thing on your plate. Given your memory situation, an empty (or absent) todo.md is " ++ "the only reliable signal that nothing was dropped.",].join("\n");}@@ -335,27 +436,29 @@ function workspaceMemorySection(): string {* nothing to poll for mid-turn — finish the current wake, then stop, and* the host spawns a fresh process for the next message.*/-function messageNotificationSection(lifecycleKind: SystemPromptOpts["lifecycleKind"]): string {+function messageNotificationSection(+ lifecycleKind: SystemPromptOpts["lifecycleKind"],+): string {if (lifecycleKind === "per_turn") {return ["## Message notifications","","You run once per wake, then your process exits — there is nothing to poll for mid-turn. " +- "Finish the current wake's work, then stop. The host spawns a brand-new process for the " +- "next message; it re-checks the inbox at the start of that new wake.",+ "Finish the current wake's work, then stop. The host spawns a brand-new process for the " ++ "next message; it re-checks the inbox at the start of that new wake.",].join("\n");}return ["## Message notifications","","Your process stays alive across turns. Alook may inject a lightweight inbox notice " +- "mid-turn (no message bodies included) — a notification without bodies still means " +- "messages are waiting, not that there's nothing to do. " +- "Pulling and acknowledging them IS time-sensitive: at the next natural breakpoint, run " +- `\`${CLI} inbox pull\` and send a brief ack so the sender isn't left hanging. Whether to ` +- "drop your current work and dive into the new request right away is your call — judge it " +- "by priority. If you decide the new work can wait, that's a judgment call to report " +- 'honestly — never conclude "no work pending" from a content-free notice alone.',+ "mid-turn (no message bodies included) — a notification without bodies still means " ++ "messages are waiting, not that there's nothing to do. " ++ "Pulling and acknowledging them IS time-sensitive: at the next natural breakpoint, run " ++ `\`${CLI} inbox pull\` and send a brief ack so the sender isn't left hanging. Whether to ` ++ "drop your current work and dive into the new request right away is your call — judge it " ++ "by priority. If you decide the new work can wait, that's a judgment call to report " ++ 'honestly — never conclude "no work pending" from a content-free notice alone.',].join("\n");}@@ -371,7 +474,10 @@ function messageNotificationSection(lifecycleKind: SystemPromptOpts["lifecycleKi* sequence, communication style, channel awareness, workspace/memory model,* and notification handling. The only per-driver input is `lifecycleKind`.*/-export function buildCliSystemPrompt(config: LaunchConfig, opts: SystemPromptOpts): string {+export function buildCliSystemPrompt(+ config: LaunchConfig,+ opts: SystemPromptOpts,+): string {const sections: string[] = [identitySection(config),cliCommandsSection(),diff --git a/src/daemon/src/manager/agentProfile.test.ts b/src/daemon/src/manager/agentProfile.test.tsindex a548dd935..884277222 100644--- a/src/daemon/src/manager/agentProfile.test.ts+++ b/src/daemon/src/manager/agentProfile.test.ts@@ -10,7 +10,10 @@ import { makeRuntimeConfig } from "../runtimeConfig";* is called to assemble the full standing prompt — the daemon never passes raw* instruction text as the prompt.*/-function managerCapturingCtx(): { mgr: AgentProcessManager; ctxs: LaunchContext[] } {+function managerCapturingCtx(): {+ mgr: AgentProcessManager;+ ctxs: LaunchContext[];+} {const ctxs: LaunchContext[] = [];const mgr = new AgentProcessManager({driverFor: () =>@@ -18,9 +21,14 @@ function managerCapturingCtx(): { mgr: AgentProcessManager; ctxs: LaunchContext[lifecycle: { kind: "persistent" },supportsStdinNotification: true,busyDeliveryMode: "gated",- buildSystemPrompt: (config: { description?: string }) => config.description ? `[system] ${config.description}` : "",+ buildSystemPrompt: (config: { description?: string }) =>+ config.description ? `[system] ${config.description}` : "",}) as never,- baseContextFor: (agentId) => ({ agentId, workingDirectory: "/tmp/x", config: {} }),+ baseContextFor: (agentId) => ({+ agentId,+ workingDirectory: "/tmp/x",+ config: {},+ }),sessionFactory: ({ ctx }) => {ctxs.push(ctx);return {@@ -46,7 +54,7 @@ describe("agent profile from server-downlinked RuntimeConfig", () => {mgr.register("agent_1", {runtimeConfig: makeRuntimeConfig({runtime: "mock",- agentName: "Cindy",+ agentName: "Gus",instruction: "You are the onboarding assistant.",}),});@@ -54,14 +62,22 @@ describe("agent profile from server-downlinked RuntimeConfig", () => {expect(ctxs).toHaveLength(1);// instruction flows to config.description → driver.buildSystemPrompt wraps it- expect(ctxs[0].standingPrompt).toBe("[system] You are the onboarding assistant.");- expect(ctxs[0].config.description).toBe("You are the onboarding assistant.");- expect(ctxs[0].config.runtimeConfig?.instruction).toBe("You are the onboarding assistant.");+ expect(ctxs[0].standingPrompt).toBe(+ "[system] You are the onboarding assistant.",+ );+ expect(ctxs[0].config.description).toBe(+ "You are the onboarding assistant.",+ );+ expect(ctxs[0].config.runtimeConfig?.instruction).toBe(+ "You are the onboarding assistant.",+ );});it("returns empty standingPrompt when driver.buildSystemPrompt produces nothing", () => {const { mgr, ctxs } = managerCapturingCtx();- mgr.register("agent_2", { runtimeConfig: makeRuntimeConfig({ runtime: "mock", agentName: "Bot" }) });+ mgr.register("agent_2", {+ runtimeConfig: makeRuntimeConfig({ runtime: "mock", agentName: "Bot" }),+ });mgr.deliver("agent_2", { seq: 1, text: "hi" });expect(ctxs[0].standingPrompt).toBe("[system] Bot");expect(ctxs[0].config.description).toBe("Bot");diff --git a/src/daemon/src/server/contract.ts b/src/daemon/src/server/contract.tsindex 79387bdc4..37a339060 100644--- a/src/daemon/src/server/contract.ts+++ b/src/daemon/src/server/contract.ts@@ -47,6 +47,9 @@ export type {ResolveRequest,ListChannelsRequest,ChannelListItem,+ CategoryRef,+ ChannelGroup,+ ChannelMemberResult,ServerMember,ServerApi,UnreadNotice,diff --git a/src/daemon/src/types.ts b/src/daemon/src/types.tsindex d6aed73c8..5098a6d08 100644--- a/src/daemon/src/types.ts+++ b/src/daemon/src/types.ts@@ -29,31 +29,31 @@*/export type DriverLifecycle =| {- kind: "persistent";- /**- * How busy-time stdin writes are timed:- * - `direct`: write immediately (runtime tolerates injection any time).- * - `gated`: hold writes until a safe stream boundary (Claude — avoids- * colliding with in-flight signed thinking blocks).- */- stdin: "direct" | "gated";- /** What to do if a message arrives while a turn is in flight. */- inFlightWake: "steer" | "queue";- }+ kind: "persistent";+ /**+ * How busy-time stdin writes are timed:+ * - `direct`: write immediately (runtime tolerates injection any time).+ * - `gated`: hold writes until a safe stream boundary (Claude — avoids+ * colliding with in-flight signed thinking blocks).+ */+ stdin: "direct" | "gated";+ /** What to do if a message arrives while a turn is in flight. */+ inFlightWake: "steer" | "queue";+ }| {- kind: "per_turn";- /**- * When to spawn:- * - `immediate`: spawn as soon as woken.- * - `defer_until_concrete_message`: don't spawn for bookkeeping-only- * wakes (e.g. a system task event); wait for a real message.- */- start: "immediate" | "defer_until_concrete_message";- /** How the per-turn process ends. */- exit: "natural" | "terminate_on_turn_end";- /** A wake mid-turn either starts a new process or folds into the pending run. */- inFlightWake: "spawn_new" | "coalesce_into_pending";- };+ kind: "per_turn";+ /**+ * When to spawn:+ * - `immediate`: spawn as soon as woken.+ * - `defer_until_concrete_message`: don't spawn for bookkeeping-only+ * wakes (e.g. a system task event); wait for a real message.+ */+ start: "immediate" | "defer_until_concrete_message";+ /** How the per-turn process ends. */+ exit: "natural" | "terminate_on_turn_end";+ /** A wake mid-turn either starts a new process or folds into the pending run. */+ inFlightWake: "spawn_new" | "coalesce_into_pending";+ };/** Session recovery strategy across restarts. */export interface DriverSession {@@ -104,17 +104,27 @@ export type ParsedEvent =| { kind: "compaction_finished" }| { kind: "review_started" }| { kind: "review_finished" }- | { kind: "internal_progress"; source?: string; itemType?: string; payloadBytes?: number }- | { kind: "runtime_diagnostic"; severity?: string; source?: string; message: string }+ | {+ kind: "internal_progress";+ source?: string;+ itemType?: string;+ payloadBytes?: number;+ }+ | {+ kind: "runtime_diagnostic";+ severity?: string;+ source?: string;+ message: string;+ }| { kind: "turn_end"; sessionId?: string }| { kind: "error"; message: string }| {- kind: "telemetry";- name: "token_usage" | "rate_limits";- source: string;- usageKind?: string;- attrs: Record<string, unknown>;- };+ kind: "telemetry";+ name: "token_usage" | "rate_limits";+ source: string;+ usageKind?: string;+ attrs: Record<string, unknown>;+ };/* ------------------------------------------------------------------ *//* Launch context & stdin encoding */@@ -179,10 +189,10 @@ export interface LaunchConfig {runtimeConfig?: import("./runtimeConfig").RuntimeConfig;description?: string;runtimeContext?: RuntimeContext;- /** Agent display name (e.g. "Cindy"). */+ /** Agent display name (e.g. "Gus"). */agentName?: string;/**- * Agent's global @mention handle, `@name#0042` (e.g. "@cindy#4821"). Every+ * Agent's global @mention handle, `@name#0042` (e.g. "@Gus#4821"). Every* account in Alook — human or agent — has a name plus a 4-digit* discriminator; this is the `@`-prefixed pair, unique even when names* collide.@@ -235,7 +245,9 @@ export interface SdkDriverDeps {/** Build the per-launch spawn env (credential voucher, PATH link, …). */buildSpawnEnv: () => Promise<NodeJS.ProcessEnv>;/** Create the vendor SDK's session object. Shape is driver-specific. */- createAgentSession: (opts: Record<string, unknown>) => Promise<{ session: unknown; sessionId: string }>;+ createAgentSession: (+ opts: Record<string, unknown>,+ ) => Promise<{ session: unknown; sessionId: string }>;}/**@@ -275,7 +287,10 @@ export interface Driver {* to the returned session first, then sends the first turn, so no early* events are lost. Absent on child-process drivers.*/- createSession?(ctx: LaunchContext, deps: SdkDriverDeps): Promise<import("./runtime/sdkRuntimeSession.js").SdkRuntimeSession>;+ createSession?(+ ctx: LaunchContext,+ deps: SdkDriverDeps,+ ): Promise<import("./runtime/sdkRuntimeSession.js").SdkRuntimeSession>;/** Parse one stdout line into zero or more normalized events. */parseLine(line: string): ParsedEvent[];@@ -288,7 +303,11 @@ export interface Driver {* Returns the wire string (a `\n` is appended by the caller), or `null` if* this runtime cannot accept mid-session input.*/- encodeStdinMessage(text: string, sessionId: string | null, opts?: EncodeOpts): string | null;+ encodeStdinMessage(+ text: string,+ sessionId: string | null,+ opts?: EncodeOpts,+ ): string | null;/** Build the standing/system prompt for this runtime. */buildSystemPrompt(config: LaunchConfig, agentId?: string): string;diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex eeebf92aa..d519c9d2a 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -349,14 +349,48 @@ export interface ListChannelsRequest {* channels by `ChannelRef`, never by raw id, so `ref` is the only locator an* agent needs (and is directly reusable as `--channel`/`--target`). `type`* is real per-row data (`"text"` vs `"forum"`), not the always-`"channel"`- * `kind` the old shape hardcoded.+ * `kind` the old shape hardcoded. `visibility` is derived from the channel's+ * category — `"private"` iff the row's category has `private = 1`, else+ * `"public"` — and lets the agent decide whether to enumerate members via+ * `channel member` or fall back to `server member`.*/export interface ChannelListItem {ref: ChannelRef;name: string;type: ChannelType;+ visibility: "public" | "private";}+/**+ * A category as surfaced to the agent CLI (`channel list`). Wire-only,+ * de-normalized on read — the agent never addresses a category by id, so+ * category ids are NOT emitted. `private` mirrors `community_category.private`.+ */+export interface CategoryRef {+ name: string;+ private: boolean;+}++/**+ * One category-bucketed group of channels in `channel list`'s grouped+ * response. `category === null` is the uncategorized bucket (Discord-style,+ * emitted first).+ */+export interface ChannelGroup {+ category: CategoryRef | null;+ channels: ChannelListItem[];+}++/**+ * `alook channel member` result — a public channel/forum returns a hint+ * pointing at `alook server member` (no roster enumeration); everything else+ * (private channel, private forum, forum post, thread) returns the concrete+ * roster.+ */+export type ChannelMemberResult =+ | { visibility: "public"; hint: string }+ | { visibility: "private"; members: ServerMember[] };+/** One server member, as surfaced to the agent CLI (`server member`). */export interface ServerMember {/** "name#0042" — always via `formatHandle`, never a bare name. */@@ -385,8 +419,16 @@ export interface ServerApi {/** Which servers/workspaces this agent participates in. */listServers(req: { agentId: AgentId }): Promise<{ servers: Server[] }>;- /** Channels (and DMs) visible to the agent, optionally scoped to one server. */- listChannels(req: ListChannelsRequest): Promise<{ channels: ChannelListItem[] }>;+ /** Channels visible to the agent, grouped by category, optionally scoped to one server. */+ listChannels(req: ListChannelsRequest): Promise<{ groups: ChannelGroup[] }>;++ /**+ * Members visible to the agent for a channel/thread ref. Public top-level+ * channels/forums return a hint pointing at `alook server member`; private+ * channels, private forums, forum posts, and threads (regardless of parent+ * visibility) return the concrete roster.+ */+ channelMember(req: { agentId?: AgentId; channel: ChannelRef }): Promise<ChannelMemberResult>;/** Drain unread messages for this agent (across all its servers), flat JSONL. */inboxPull(req: InboxPullRequest): Promise<InboxPullResponse>;diff --git a/src/shared/src/db/queries/community/category.ts b/src/shared/src/db/queries/community/category.tsindex 77c73ba0d..341631c82 100644--- a/src/shared/src/db/queries/community/category.ts+++ b/src/shared/src/db/queries/community/category.ts@@ -1,4 +1,4 @@-import { eq, inArray, count } from "drizzle-orm";+import { asc, eq, inArray, count } from "drizzle-orm";import { communityCategory, communityChannel } from "../../community-schema";import type { Database } from "../../index";@@ -10,6 +10,24 @@ export async function getCategoriesByIds(db: Database, categoryIds: string[]) {.where(inArray(communityCategory.id, categoryIds));}+/**+ * Category dictionary for a server, ordered by position asc then id asc for+ * stable deterministic ordering. Used by the agent `channel list` route to+ * bucket channels into groups without a per-row join.+ */+export async function listCategoriesByServer(db: Database, serverId: string) {+ return db+ .select({+ id: communityCategory.id,+ name: communityCategory.name,+ position: communityCategory.position,+ private: communityCategory.private,+ })+ .from(communityCategory)+ .where(eq(communityCategory.serverId, serverId))+ .orderBy(asc(communityCategory.position), asc(communityCategory.id));+}+export async function createCategory(db: Database,data: { serverId: string; name: string; private?: boolean; creatorId?: string }diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 5f7c63fd5..894a05811 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -272,6 +272,7 @@ export {CommunityAgentResolveRequestSchema,CommunityAgentListChannelsRequestSchema,CommunityAgentListMembersRequestSchema,+ CommunityAgentChannelMemberRequestSchema,CommunityAgentJoinServerRequestSchema,CommunityAgentAttachmentUploadResponseSchema,CommunityAgentAttachmentDownloadRequestSchema,@@ -354,6 +355,7 @@ export type {CommunityAgentResolveRequest,CommunityAgentListChannelsRequest,CommunityAgentListMembersRequest,+ CommunityAgentChannelMemberRequest,CommunityAgentJoinServerRequest,BotAuditEvent,BotAuditEventKind,@@ -396,6 +398,9 @@ export type {ResolveRequest as CommunityCliResolveRequest,ListChannelsRequest as CommunityCliListChannelsRequest,ChannelListItem,+ CategoryRef as CommunityCliCategoryRef,+ ChannelGroup as CommunityCliChannelGroup,+ ChannelMemberResult as CommunityCliChannelMemberResult,ServerMember as CommunityCliServerMember,ServerApi as CommunityCliServerApi,UnreadNotice,diff --git a/src/shared/src/runtime-config.ts b/src/shared/src/runtime-config.tsindex 33529b7cd..160826f84 100644--- a/src/shared/src/runtime-config.ts+++ b/src/shared/src/runtime-config.ts@@ -64,7 +64,7 @@ export interface RuntimeConfig {*/agentName?: string;/**- * The agent's global @mention handle, `@name#0042` (e.g. "@cindy#4821").+ * The agent's global @mention handle, `@name#0042` (e.g. "@Gus#4821").* Every account in Alook — human or agent — has a name plus a 4-digit* discriminator; this is the `@`-prefixed pair, unique even when names* collide.@@ -79,7 +79,9 @@ export interface RuntimeConfig {/* ------------------------------------------------------------------ *//** Build a fully-defaulted RuntimeConfig from a partial input. */-export function makeRuntimeConfig(input: Partial<RuntimeConfig> & { runtime: string }): RuntimeConfig {+export function makeRuntimeConfig(+ input: Partial<RuntimeConfig> & { runtime: string },+): RuntimeConfig {return {version: RUNTIME_CONFIG_VERSION,runtime: input.runtime,diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex d91837768..eef586571 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -1182,6 +1182,14 @@ export type CommunityAgentListMembersRequest = z.infer<typeof CommunityAgentListMembersRequestSchema>;+export const CommunityAgentChannelMemberRequestSchema = z.object({+ channel: z.string().min(1),+ agentId: z.string().optional(),+});+export type CommunityAgentChannelMemberRequest = z.infer<+ typeof CommunityAgentChannelMemberRequestSchema+>;+export const CommunityAgentJoinServerRequestSchema = z.object({invite: z.string().min(1),});diff --git a/src/web/src/app/api/community/agent/channelMember/route.test.ts b/src/web/src/app/api/community/agent/channelMember/route.test.tsnew file mode 100644index 000000000..3110e6ab1--- /dev/null+++ b/src/web/src/app/api/community/agent/channelMember/route.test.ts@@ -0,0 +1,246 @@+import { describe, it, expect, vi, beforeEach } from "vitest"+import { NextRequest } from "next/server"++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),+}))+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))++const mockFindActiveAgentRunnerKeyByBearer = vi.fn()+const mockGetUserInternal = vi.fn()+const mockGetUserByNameAndDiscriminator = vi.fn()+const mockGetBotBinding = vi.fn()+const mockResolveServerByNameForMember = vi.fn()+const mockGetServer = vi.fn()+const mockResolveChannelByNameForMember = vi.fn()+const mockGetChannel = vi.fn()+const mockIsChannelPrivate = vi.fn()+const mockResolveChannelAccessContext = vi.fn()+const mockListThreadParticipantUserIds = vi.fn()+const mockResolveScopeMembers = vi.fn()+const mockGetMembersByUserIds = vi.fn()+const mockGetDMBetween = vi.fn()+const mockIsBlocked = vi.fn()+const mockGetMessageByChannelAndSeq = vi.fn()+const mockGetThreadChannelByParentMessage = vi.fn()++vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return {+ ...actual,+ queries: {+ ...actual.queries,+ communityMachine: { findActiveAgentRunnerKeyByBearer: (...a: unknown[]) => mockFindActiveAgentRunnerKeyByBearer(...a) },+ user: {+ ...actual.queries.user,+ getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),+ getUserByNameAndDiscriminator: (...a: unknown[]) => mockGetUserByNameAndDiscriminator(...a),+ },+ communityBot: { getBotBinding: (...a: unknown[]) => mockGetBotBinding(...a) },+ communityServer: {+ ...actual.queries.communityServer,+ resolveServerByNameForMember: (...a: unknown[]) => mockResolveServerByNameForMember(...a),+ getServer: (...a: unknown[]) => mockGetServer(...a),+ },+ communityChannel: {+ ...actual.queries.communityChannel,+ resolveChannelByNameForMember: (...a: unknown[]) => mockResolveChannelByNameForMember(...a),+ getChannel: (...a: unknown[]) => mockGetChannel(...a),+ isChannelPrivate: (...a: unknown[]) => mockIsChannelPrivate(...a),+ resolveChannelAccessContext: (...a: unknown[]) => mockResolveChannelAccessContext(...a),+ getThreadChannelByParentMessage: (...a: unknown[]) => mockGetThreadChannelByParentMessage(...a),+ },+ communityThread: {+ ...actual.queries.communityThread,+ listThreadParticipantUserIds: (...a: unknown[]) => mockListThreadParticipantUserIds(...a),+ },+ communityMembersResolver: {+ ...actual.queries.communityMembersResolver,+ resolveScopeMembers: (...a: unknown[]) => mockResolveScopeMembers(...a),+ },+ communityMember: {+ ...actual.queries.communityMember,+ getMembersByUserIds: (...a: unknown[]) => mockGetMembersByUserIds(...a),+ },+ communityMessage: {+ ...actual.queries.communityMessage,+ getMessageByChannelAndSeq: (...a: unknown[]) => mockGetMessageByChannelAndSeq(...a),+ },+ communityDm: {+ ...actual.queries.communityDm,+ getDMBetween: (...a: unknown[]) => mockGetDMBetween(...a),+ },+ communityFriendship: {+ ...actual.queries.communityFriendship,+ isBlocked: (...a: unknown[]) => mockIsBlocked(...a),+ },+ },+ }+})++import { POST } from "./route"++function req(body: unknown, headers: Record<string, string> = {}): NextRequest {+ return new NextRequest("http://localhost/api/community/agent/channelMember", {+ method: "POST",+ headers: { "content-type": "application/json", ...headers },+ body: typeof body === "string" ? body : JSON.stringify(body),+ })+}++describe("POST /api/community/agent/channelMember", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })+ mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })+ mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })+ // Default: bot has channel access (server member, public channel).+ mockResolveChannelAccessContext.mockResolvedValue({+ channel: { id: "ch_1", serverId: "srv_1", type: "text", parentChannelId: null, creatorId: "owner_1", categoryId: null },+ anchor: { id: "ch_1", type: "text", creatorId: "owner_1", categoryId: null },+ role: "member",+ isChannelMember: false,+ isCreator: false,+ isPrivate: false,+ })+ })++ it("401 without Authorization", async () => {+ const res = await POST(req({ channel: "/demo/general" }))+ expect(res.status).toBe(401)+ })++ it("400 on payload validation failure (missing channel)", async () => {+ const res = await POST(req({}, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(400)+ })++ it("400 on a DM ref — channel-scoped only", async () => {+ // No DB mocks needed: DM refs are rejected up front, so an un-opened DM+ // (no peer, no DM row) still gets the specific channel-scoped 400 instead+ // of a misleading "dm not found" 404.+ const res = await POST(req({ channel: "/.dm/peer#0042" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(400)+ const body = await res.json()+ expect(body.error).toContain("channel-scoped")+ expect(mockGetUserByNameAndDiscriminator).not.toHaveBeenCalled()+ expect(mockGetDMBetween).not.toHaveBeenCalled()+ })++ it("400 on a malformed ref", async () => {+ const res = await POST(req({ channel: "not-a-ref" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(400)+ })++ it("public top-level channel → { visibility:'public', hint } with the server's actual name substituted", async () => {+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "demo" }])+ mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1", name: "general", type: "text", parentChannelId: null }])+ mockGetChannel.mockResolvedValue({ id: "ch_1", serverId: "srv_1", name: "general", type: "text" })+ mockGetServer.mockResolvedValue({ id: "srv_1", name: "demo" })+ mockIsChannelPrivate.mockResolvedValue(false)+ const res = await POST(req({ channel: "/demo/general" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(200)+ const body = await res.json()+ expect(body).toEqual({+ visibility: "public",+ hint: "This channel is public. Use `alook server member --server demo` to list who can see it.",+ })+ expect("members" in body).toBe(false)+ })++ it("private top-level channel → { visibility:'private', members } from resolveScopeMembers", async () => {+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "demo" }])+ mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1", name: "leadership", type: "text", parentChannelId: null }])+ mockGetChannel.mockResolvedValue({ id: "ch_1", serverId: "srv_1", name: "leadership", type: "text" })+ // Access context: bot is the creator (so it can see the private channel).+ mockResolveChannelAccessContext.mockResolvedValue({+ channel: { id: "ch_1", serverId: "srv_1", type: "text", parentChannelId: null, creatorId: "bot_1", categoryId: "cat_1" },+ anchor: { id: "ch_1", type: "text", creatorId: "bot_1", categoryId: "cat_1" },+ role: "member",+ isChannelMember: false,+ isCreator: true,+ isPrivate: true,+ })+ mockIsChannelPrivate.mockResolvedValue(true)+ mockResolveScopeMembers.mockResolvedValue([+ { userId: "u_owner", role: "owner", source: "explicit" },+ { userId: "u_alice", role: "member", source: "explicit" },+ ])+ mockGetMembersByUserIds.mockResolvedValue([+ { userName: "gustavo", discriminator: "4821", role: "owner", nickname: "Gus" },+ { userName: "alice", discriminator: "0193", role: "member", nickname: null },+ ])+ const res = await POST(req({ channel: "/demo/leadership" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(200)+ const body = await res.json()+ expect(body).toEqual({+ visibility: "private",+ members: [+ { handle: "gustavo#4821", role: "owner", nickname: "Gus" },+ { handle: "alice#0193", role: "member" },+ ],+ })+ })++ it("thread ref → always private on the wire; roster is the thread-participant set", async () => {+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "demo" }])+ mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_parent", name: "general", type: "text", parentChannelId: null }])+ mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "msg_12" })+ mockGetThreadChannelByParentMessage.mockResolvedValue({ id: "th_1" })+ mockGetChannel.mockResolvedValue({ id: "th_1", serverId: "srv_1", name: "Thread", type: "thread", parentChannelId: "ch_parent" })+ mockResolveChannelAccessContext.mockResolvedValue({+ channel: { id: "th_1", serverId: "srv_1", type: "thread", parentChannelId: "ch_parent", creatorId: "bot_1", categoryId: null },+ anchor: { id: "ch_parent", type: "text", creatorId: "owner_1", categoryId: null },+ role: "member",+ isChannelMember: false,+ isCreator: false,+ isPrivate: false,+ })+ mockListThreadParticipantUserIds.mockResolvedValue(["u_owner", "u_bot"])+ mockGetMembersByUserIds.mockResolvedValue([+ { userName: "gustavo", discriminator: "4821", role: "owner", nickname: null },+ { userName: "otter", discriminator: "5522", role: "member", nickname: null },+ ])++ const res = await POST(req({ channel: "/demo/general/#12" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(200)+ const body = await res.json()+ expect(body.visibility).toBe("private")+ expect(body.members).toEqual([+ { handle: "gustavo#4821", role: "owner" },+ { handle: "otter#5522", role: "member" },+ ])+ expect(mockListThreadParticipantUserIds).toHaveBeenCalledWith(expect.anything(), "th_1")+ })++ it("forum post inside a PUBLIC forum → still private on the wire; roster is post-scoped, not the whole server", async () => {+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "demo" }])+ mockResolveChannelByNameForMember.mockResolvedValue([{ id: "post_1", name: "bug-42", type: "forum_post", parentChannelId: "forum_1" }])+ // Access context: public forum (isPrivate=false, categoryId=null) but the+ // channel itself is a `forum_post` — the route must NOT fall into the+ // public/hint branch, since a post is its own access unit.+ mockResolveChannelAccessContext.mockResolvedValue({+ channel: { id: "post_1", serverId: "srv_1", type: "forum_post", parentChannelId: "forum_1", creatorId: "bot_1", categoryId: null },+ anchor: { id: "forum_1", type: "forum", creatorId: "owner_1", categoryId: null },+ role: "member",+ isChannelMember: false,+ isCreator: true,+ isPrivate: false,+ })+ mockResolveScopeMembers.mockResolvedValue([+ { userId: "u_bot", role: "member", source: "explicit" },+ { userId: "u_alice", role: "member", source: "explicit" },+ ])+ mockGetMembersByUserIds.mockResolvedValue([+ { userName: "gus", discriminator: "4821", role: "member", nickname: null },+ { userName: "alice", discriminator: "0193", role: "member", nickname: null },+ ])++ const res = await POST(req({ channel: "/demo/bug-42" }, { Authorization: "Bearer crk_abc" }))+ expect(res.status).toBe(200)+ const body = await res.json()+ expect(body.visibility).toBe("private")+ expect(body.members).toHaveLength(2)+ expect(mockResolveScopeMembers).toHaveBeenCalledWith(expect.anything(), { scope: "post", scopeId: "post_1" })+ })+})diff --git a/src/web/src/app/api/community/agent/channelMember/route.ts b/src/web/src/app/api/community/agent/channelMember/route.tsnew file mode 100644index 000000000..b40bc05fa--- /dev/null+++ b/src/web/src/app/api/community/agent/channelMember/route.ts@@ -0,0 +1,139 @@+import { NextResponse, type NextRequest } from "next/server"+import {+ queries,+ CommunityAgentChannelMemberRequestSchema,+ DM_SERVER,+ formatHandle,+ isForumPost,+ parseRef,+} from "@alook/shared"+import type {+ CommunityCliChannelMemberResult as ChannelMemberResult,+ CommunityCliServerMember as ServerMember,+} from "@alook/shared"+import { getDb } from "@/lib/db"+import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"+import { resolveTargetForMember, resolveErrorResponse } from "@/lib/community/resolve-ref"+import { requireChannelAccess } from "@/lib/community/permissions"++/**+ * POST /api/community/agent/channelMember — `alook channel member --channel <ref>`.+ * Returns the followed members of a channel/thread.+ *+ * Branches by resolved target:+ * - DM ref → 400 (channel-scoped). Rejected UP FRONT (before+ * `resolveTargetForMember`) so an un-opened DM surfaces the correct+ * channel-scoped 400 instead of a misleading 404 "dm not found".+ * - thread (`type = "thread"`) → always private on the wire; returns the+ * thread-participant roster (`community_thread_participant`). The+ * parent-channel visibility does not leak here; a thread carries its own+ * notify set irrespective of its parent's public/private state.+ * - forum post (`type = "forum_post"`) → always private on the wire — a+ * post is its own access unit even inside a PUBLIC forum, and the roster+ * is the post-scoped member set, not the whole server.+ * - public top-level channel/forum → `{ visibility: "public", hint }` (no+ * roster enumeration — every server member can see it, so the agent should+ * use `alook server member --server <name>` instead).+ * - private channel / private forum → `{ visibility: "private", members }`+ * sourced from `resolveScopeMembers` (the same audience the fan-out and+ * human UI use).+ */+export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {+ const db = getDb(ctx.env.DB)++ let raw: unknown+ try {+ raw = await req.json()+ } catch {+ return NextResponse.json({ error: "invalid JSON body" }, { status: 400 })+ }+ const parsed = CommunityAgentChannelMemberRequestSchema.safeParse(raw)+ if (!parsed.success) {+ return NextResponse.json({ error: "invalid payload", details: parsed.error.flatten() }, { status: 400 })+ }++ // Reject DM refs up front: an un-opened DM would otherwise trip+ // `resolveTargetForMember`'s 404 "dm not found" before the DM-branch guard+ // below could emit the specific channel-scoped 400.+ try {+ const p = parseRef(parsed.data.channel)+ if (p.server === DM_SERVER) {+ return NextResponse.json(+ { error: "channel member is channel-scoped — DM refs are not supported" },+ { status: 400 },+ )+ }+ } catch {+ // Fall through — resolveTargetForMember returns the canonical 400.+ }++ const resolved = await resolveTargetForMember(db, ctx.botUserId, parsed.data.channel, {+ createDmIfMissing: false,+ createThreadIfMissing: false,+ callerKind: "bot",+ })+ if ("error" in resolved) return resolveErrorResponse(resolved)+ if (resolved.kind === "dm") {+ return NextResponse.json(+ { error: "channel member is channel-scoped — DM refs are not supported" },+ { status: 400 },+ )+ }++ const channelId = resolved.channelId+ const access = await requireChannelAccess(db, channelId, ctx.botUserId)+ if (!access.ok) return NextResponse.json({ error: access.error }, { status: access.status })++ const { channel, isPrivate } = access.value++ // Thread branch: always private on the wire; roster is the thread's+ // participant set (`community_thread_participant`), regardless of parent+ // channel visibility.+ if (channel.type === "thread") {+ const userIds = await queries.communityThread.listThreadParticipantUserIds(db, channelId)+ const members = await hydrateMembers(db, channel.serverId, userIds)+ return NextResponse.json<ChannelMemberResult>({ visibility: "private", members })+ }++ // Forum post branch: even inside a PUBLIC forum, a post is its own access+ // unit — return its post-scoped roster rather than the public/hint fallback.+ if (isForumPost(channel.type)) {+ const scoped = await queries.communityMembersResolver.resolveScopeMembers(db, { scope: "post", scopeId: channelId })+ const userIds = scoped.map((s) => s.userId)+ const members = await hydrateMembers(db, channel.serverId, userIds)+ return NextResponse.json<ChannelMemberResult>({ visibility: "private", members })+ }++ if (!isPrivate) {+ const server = await queries.communityServer.getServer(db, channel.serverId)+ const serverName = server?.name ?? channel.serverId+ const hint = `This channel is public. Use \`alook server member --server ${serverName}\` to list who can see it.`+ return NextResponse.json<ChannelMemberResult>({ visibility: "public", hint })+ }++ const scoped = await queries.communityMembersResolver.resolveScopeMembers(db, { scope: "channel", scopeId: channelId })+ const userIds = scoped.map((s) => s.userId)+ const members = await hydrateMembers(db, channel.serverId, userIds)+ return NextResponse.json<ChannelMemberResult>({ visibility: "private", members })+})++/**+ * Hydrate a user id list into `ServerMember[]` — mirrors `listMembers`'s+ * mapping (formatHandle, default role "member", nickname iff set). Users+ * whose account is soft-deleted drop out via `getMembersByUserIds`'s inner+ * join on `user`. Users missing a `community_server_member` row (shouldn't+ * happen in normal flow) also drop out; they never surface as a stub row.+ */+async function hydrateMembers(+ db: ReturnType<typeof getDb>,+ serverId: string,+ userIds: string[],+): Promise<ServerMember[]> {+ if (userIds.length === 0) return []+ const rows = await queries.communityMember.getMembersByUserIds(db, serverId, userIds)+ return rows.map((r) => ({+ handle: formatHandle(r.userName ?? "", r.discriminator ?? "0000"),+ role: r.role ?? "member",+ ...(r.nickname ? { nickname: r.nickname } : {}),+ }))+}diff --git a/src/web/src/app/api/community/agent/listChannels/route.test.ts b/src/web/src/app/api/community/agent/listChannels/route.test.tsindex 225162eef..381cf494e 100644--- a/src/web/src/app/api/community/agent/listChannels/route.test.ts+++ b/src/web/src/app/api/community/agent/listChannels/route.test.ts@@ -12,6 +12,7 @@ const mockGetBotBinding = vi.fn()const mockListUserServers = vi.fn()const mockResolveServerByNameForMember = vi.fn()const mockListChannelsForMember = vi.fn()+const mockListCategoriesByServer = vi.fn()vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")@@ -27,6 +28,7 @@ vi.mock("@alook/shared", async () => {resolveServerByNameForMember: (...a: unknown[]) => mockResolveServerByNameForMember(...a),},communityChannel: { listChannelsForMember: (...a: unknown[]) => mockListChannelsForMember(...a) },+ communityCategory: { listCategoriesByServer: (...a: unknown[]) => mockListCategoriesByServer(...a) },},}})@@ -47,6 +49,7 @@ describe("POST /api/community/agent/listChannels", () => {mockFindActiveAgentRunnerKeyByBearer.mockResolvedValue({ userId: "owner_1", machineId: "m_1", agentId: "bot_1" })mockGetUserInternal.mockResolvedValue({ isBot: true, deletedAt: null })mockGetBotBinding.mockResolvedValue({ machineId: "m_1", runtime: "claude" })+ mockListCategoriesByServer.mockResolvedValue([])})it("401 without Authorization", async () => {@@ -61,13 +64,13 @@ describe("POST /api/community/agent/listChannels", () => {expect(res.status).toBe(400)})- it("empty body defaults to {} — lists channels across every server the bot is in, as {ref,name,type} items", async () => {+ it("empty body defaults to {} — concatenates groups across every server the bot is in", async () => {mockListUserServers.mockResolvedValue([{ id: "srv_1", name: "studio" }, { id: "srv_2", name: "lounge" }])mockListChannelsForMember.mockImplementation((_db: unknown, serverId: string) =>Promise.resolve(serverId === "srv_1"- ? [{ id: "ch_1", serverId: "srv_1", name: "general", type: "text" }]- : [{ id: "ch_2", serverId: "srv_2", name: "random", type: "text" }]+ ? [{ id: "ch_1", serverId: "srv_1", name: "general", type: "text", categoryId: null }]+ : [{ id: "ch_2", serverId: "srv_2", name: "random", type: "text", categoryId: null }]))const res = await POST(@@ -78,9 +81,15 @@ describe("POST /api/community/agent/listChannels", () => {)expect(res.status).toBe(200)expect(await res.json()).toEqual({- channels: [- { ref: "/studio/general", name: "general", type: "text" },- { ref: "/lounge/random", name: "random", type: "text" },+ groups: [+ {+ category: null,+ channels: [{ ref: "/studio/general", name: "general", type: "text", visibility: "public" }],+ },+ {+ category: null,+ channels: [{ ref: "/lounge/random", name: "random", type: "text", visibility: "public" }],+ },],})expect(mockListUserServers).toHaveBeenCalledTimes(1)@@ -89,38 +98,70 @@ describe("POST /api/community/agent/listChannels", () => {it("--server <id>: resolves server-side and scopes to that one server", async () => {mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "studio" }])- mockListChannelsForMember.mockResolvedValue([{ id: "ch_1", serverId: "srv_1", name: "general", type: "text" }])+ mockListChannelsForMember.mockResolvedValue([{ id: "ch_1", serverId: "srv_1", name: "general", type: "text", categoryId: null }])const res = await POST(req({ server: "srv_1" }, { Authorization: "Bearer crk_abc" }))expect(res.status).toBe(200)expect(mockListUserServers).not.toHaveBeenCalled()expect(mockResolveServerByNameForMember).toHaveBeenCalledWith(expect.anything(), "bot_1", "srv_1")expect(mockListChannelsForMember).toHaveBeenCalledWith(expect.anything(), "srv_1", "bot_1")expect(await res.json()).toEqual({- channels: [{ ref: "/studio/general", name: "general", type: "text" }],+ groups: [+ {+ category: null,+ channels: [{ ref: "/studio/general", name: "general", type: "text", visibility: "public" }],+ },+ ],})})- it("--server <name>: resolves to the matching server's id and builds refs from that server's name", async () => {- mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "Design Studio" }])- mockListChannelsForMember.mockResolvedValue([{ id: "ch_1", serverId: "srv_1", name: "help", type: "forum" }])- const res = await POST(req({ server: "Design Studio" }, { Authorization: "Bearer crk_abc" }))+ it("channels bucketed into their category groups; null-category emitted first; empty groups dropped", async () => {+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "demo" }])+ mockListChannelsForMember.mockResolvedValue([+ { id: "ch_1", serverId: "srv_1", name: "announcements", type: "text", categoryId: null, position: 0 },+ { id: "ch_2", serverId: "srv_1", name: "general", type: "text", categoryId: "cat_ops", position: 1 },+ { id: "ch_3", serverId: "srv_1", name: "leadership", type: "text", categoryId: "cat_founders", position: 2 },+ ])+ mockListCategoriesByServer.mockResolvedValue([+ { id: "cat_ops", name: "Ops", position: 0, private: 0 },+ { id: "cat_founders", name: "Founders", position: 1, private: 1 },+ { id: "cat_empty", name: "Empty", position: 2, private: 0 },+ ])+ const res = await POST(req({ server: "srv_1" }, { Authorization: "Bearer crk_abc" }))expect(res.status).toBe(200)expect(await res.json()).toEqual({- channels: [{ ref: "/Design Studio/help", name: "help", type: "forum" }],+ groups: [+ {+ category: null,+ channels: [{ ref: "/demo/announcements", name: "announcements", type: "text", visibility: "public" }],+ },+ {+ category: { name: "Ops", private: false },+ channels: [{ ref: "/demo/general", name: "general", type: "text", visibility: "public" }],+ },+ {+ category: { name: "Founders", private: true },+ channels: [{ ref: "/demo/leadership", name: "leadership", type: "text", visibility: "private" }],+ },+ ],})})it("a forum-type channel is reported with type:'forum'; a plain channel with type:'text'", async () => {mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "studio" }])mockListChannelsForMember.mockResolvedValue([- { id: "ch_1", serverId: "srv_1", name: "general", type: "text" },- { id: "ch_2", serverId: "srv_1", name: "help", type: "forum" },+ { id: "ch_1", serverId: "srv_1", name: "general", type: "text", categoryId: null },+ { id: "ch_2", serverId: "srv_1", name: "help", type: "forum", categoryId: null },])const res = await POST(req({ server: "srv_1" }, { Authorization: "Bearer crk_abc" }))expect(await res.json()).toEqual({- channels: [- { ref: "/studio/general", name: "general", type: "text" },- { ref: "/studio/help", name: "help", type: "forum" },+ groups: [+ {+ category: null,+ channels: [+ { ref: "/studio/general", name: "general", type: "text", visibility: "public" },+ { ref: "/studio/help", name: "help", type: "forum", visibility: "public" },+ ],+ },],})})@@ -145,11 +186,11 @@ describe("POST /api/community/agent/listChannels", () => {expect(mockListChannelsForMember).not.toHaveBeenCalled()})- it("empty channel list → { channels: [] }, not an error", async () => {+ it("empty channel list → { groups: [] }, not an error", async () => {mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1", name: "studio" }])mockListChannelsForMember.mockResolvedValue([])const res = await POST(req({ server: "srv_1" }, { Authorization: "Bearer crk_abc" }))expect(res.status).toBe(200)- expect(await res.json()).toEqual({ channels: [] })+ expect(await res.json()).toEqual({ groups: [] })})})diff --git a/src/web/src/app/api/community/agent/listChannels/route.ts b/src/web/src/app/api/community/agent/listChannels/route.tsindex 1e2a085e5..914a4cb72 100644--- a/src/web/src/app/api/community/agent/listChannels/route.ts+++ b/src/web/src/app/api/community/agent/listChannels/route.ts@@ -1,6 +1,9 @@import { NextResponse, type NextRequest } from "next/server"import { queries, CommunityAgentListChannelsRequestSchema, formatRef } from "@alook/shared"-import type { ChannelListItem } from "@alook/shared"+import type {+ CommunityCliChannelGroup as ChannelGroup,+ ChannelListItem,+} from "@alook/shared"import { getDb } from "@/lib/db"import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-auth"@@ -14,10 +17,17 @@ import { withAgentRunnerAuth } from "@/lib/middleware/community-agent-runner-aut* visibility rule a human sees: private-category channels appear only when the* bot is an admin, the channel's creator, or an added member.*- * Response items are `{ ref, name, type }` (plan §Decisions #12) — `ref` is- * directly reusable as `--channel`/`--target` on every other command, and- * `type` (`"text"`/`"forum"`) comes straight off `listChannelsForMember`'s- * row.+ * Response is `{ groups: [{ category, channels: [{ref, name, type, visibility}] }] }`+ * (plan §Design). Channels are bucketed by their `categoryId` — uncategorized+ * (`categoryId === null`) is emitted first (Discord-style), then categories+ * ordered by `position` (stable-sort by id on ties). Empty groups are dropped+ * so the private-category group never leaks its name to a viewer with no+ * access. `visibility` is derived from the row's category (`private = 1` →+ * `"private"`, else `"public"`) — the same rule `isChannelPrivate` uses.+ *+ * When `server` is omitted, groups from every server the bot is in are+ * concatenated into one flat `groups` array (no wire-shape branch — the CLI+ * layer refuses to call without `--server`, so agents never hit this).*/export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)@@ -51,20 +61,60 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {servers = await queries.communityServer.listUserServers(db, ctx.botUserId)}- const channelsByServer = await Promise.all(- servers.map(async (s) => ({- server: s,- rows: await queries.communityChannel.listChannelsForMember(db, s.id, ctx.botUserId),- }))- )+ // Fan out per-server DB work in parallel — for a bot in N servers this+ // stays flat instead of paying N× the RTT that a sequential per-server+ // loop would.+ const perServer = await Promise.all(+ servers.map(async (server) => {+ const [rows, categories] = await Promise.all([+ queries.communityChannel.listChannelsForMember(db, server.id, ctx.botUserId),+ queries.communityCategory.listCategoriesByServer(db, server.id),+ ])++ const categoryById = new Map<string, { id: string; name: string; position: number | null; private: number | null }>()+ for (const c of categories) categoryById.set(c.id, c)- const channels: ChannelListItem[] = channelsByServer.flatMap(({ server, rows }) =>- rows.map((c) => ({- ref: formatRef({ server: server.name, channel: c.name }),- name: c.name,- type: c.type,- }))+ const uncategorized: ChannelListItem[] = []+ const byCategory = new Map<string, ChannelListItem[]>()++ // rows come from `listChannelsForMember` already ordered by+ // `communityChannel.position asc`; bucket into groups preserving that+ // per-bucket order.+ for (const c of rows) {+ const cat = c.categoryId ? categoryById.get(c.categoryId) : null+ const isPrivate = !!(cat && (cat.private ?? 0) === 1)+ const item: ChannelListItem = {+ ref: formatRef({ server: server.name, channel: c.name }),+ name: c.name,+ type: c.type,+ visibility: isPrivate ? "private" : "public",+ }+ if (!c.categoryId || !cat) {+ uncategorized.push(item)+ } else {+ const bucket = byCategory.get(c.categoryId) ?? []+ bucket.push(item)+ byCategory.set(c.categoryId, bucket)+ }+ }++ const serverGroups: ChannelGroup[] = []+ if (uncategorized.length > 0) {+ serverGroups.push({ category: null, channels: uncategorized })+ }+ for (const cat of categories) {+ const items = byCategory.get(cat.id)+ if (!items || items.length === 0) continue+ serverGroups.push({+ category: { name: cat.name, private: (cat.private ?? 0) === 1 },+ channels: items,+ })+ }+ return serverGroups+ }),)- return NextResponse.json({ channels })+ const groups: ChannelGroup[] = perServer.flat()++ return NextResponse.json({ groups })})diff --git a/src/web/src/app/api/community/daemon/resync-wakes/route.test.ts b/src/web/src/app/api/community/daemon/resync-wakes/route.test.tsindex f599a00c7..67d75014b 100644--- a/src/web/src/app/api/community/daemon/resync-wakes/route.test.ts+++ b/src/web/src/app/api/community/daemon/resync-wakes/route.test.ts@@ -1,19 +1,19 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}))+}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));-const mockFindCred = vi.fn()-const mockListBotsForMachine = vi.fn()-const mockGetLatestUnreadMessageForAgent = vi.fn()-const mockDispatchOneUnreadWake = vi.fn()+const mockFindCred = vi.fn();+const mockListBotsForMachine = vi.fn();+const mockGetLatestUnreadMessageForAgent = vi.fn();+const mockDispatchOneUnreadWake = vi.fn();vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<any>("@alook/shared")+ const actual = await vi.importActual<any>("@alook/shared");return {...actual,dispatchOneUnreadWake: (...a: unknown[]) => mockDispatchOneUnreadWake(...a),@@ -25,85 +25,101 @@ vi.mock("@alook/shared", async () => {listBotsForMachine: (...a: unknown[]) => mockListBotsForMachine(...a),},communityAgentInbox: {- getLatestUnreadMessageForAgent: (...a: unknown[]) => mockGetLatestUnreadMessageForAgent(...a),+ getLatestUnreadMessageForAgent: (...a: unknown[]) =>+ mockGetLatestUnreadMessageForAgent(...a),},},- }-})+ };+});-import { POST } from "./route"+import { POST } from "./route";function req(headers: Record<string, string> = {}): NextRequest {return new NextRequest("http://localhost/api/community/daemon/resync-wakes", {method: "POST",headers,- })+ });}describe("POST /api/community/daemon/resync-wakes", () => {beforeEach(() => {- vi.clearAllMocks()- mockFindCred.mockResolvedValue({ credentialId: "cmk_ok", userId: "u_1", machineId: "cm_1" })- })+ vi.clearAllMocks();+ mockFindCred.mockResolvedValue({+ credentialId: "cmk_ok",+ userId: "u_1",+ machineId: "cm_1",+ });+ });it("returns { woken: 0 } and does nothing when the machine has no bots", async () => {- mockListBotsForMachine.mockResolvedValue([])- const res = await POST(req({ Authorization: "Bearer cmk_ok" }))- expect(res.status).toBe(200)- expect(await res.json()).toEqual({ woken: 0 })- expect(mockGetLatestUnreadMessageForAgent).not.toHaveBeenCalled()- expect(mockDispatchOneUnreadWake).not.toHaveBeenCalled()- })+ mockListBotsForMachine.mockResolvedValue([]);+ const res = await POST(req({ Authorization: "Bearer cmk_ok" }));+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ woken: 0 });+ expect(mockGetLatestUnreadMessageForAgent).not.toHaveBeenCalled();+ expect(mockDispatchOneUnreadWake).not.toHaveBeenCalled();+ });it("dispatches a wake for a bot with pending unread and counts it", async () => {- mockListBotsForMachine.mockResolvedValue([{ id: "bot_1", name: "cindy", description: "" }])- mockGetLatestUnreadMessageForAgent.mockResolvedValue({ messageId: "msg_1" })- mockDispatchOneUnreadWake.mockResolvedValue({ outcome: "sent" })+ mockListBotsForMachine.mockResolvedValue([+ { id: "bot_1", name: "Gus", description: "" },+ ]);+ mockGetLatestUnreadMessageForAgent.mockResolvedValue({+ messageId: "msg_1",+ });+ mockDispatchOneUnreadWake.mockResolvedValue({ outcome: "sent" });- const res = await POST(req({ Authorization: "Bearer cmk_ok" }))+ const res = await POST(req({ Authorization: "Bearer cmk_ok" }));expect(mockDispatchOneUnreadWake).toHaveBeenCalledWith(expect.anything(),expect.anything(),- { messageId: "msg_1", botUserId: "bot_1" }- )- expect(await res.json()).toEqual({ woken: 1 })- })+ { messageId: "msg_1", botUserId: "bot_1" },+ );+ expect(await res.json()).toEqual({ woken: 1 });+ });it("skips bots with no pending unread — not counted, dispatch never called for them", async () => {- mockListBotsForMachine.mockResolvedValue([{ id: "bot_1", name: "cindy", description: "" }])- mockGetLatestUnreadMessageForAgent.mockResolvedValue(null)+ mockListBotsForMachine.mockResolvedValue([+ { id: "bot_1", name: "Gus", description: "" },+ ]);+ mockGetLatestUnreadMessageForAgent.mockResolvedValue(null);- const res = await POST(req({ Authorization: "Bearer cmk_ok" }))+ const res = await POST(req({ Authorization: "Bearer cmk_ok" }));- expect(mockDispatchOneUnreadWake).not.toHaveBeenCalled()- expect(await res.json()).toEqual({ woken: 0 })- })+ expect(mockDispatchOneUnreadWake).not.toHaveBeenCalled();+ expect(await res.json()).toEqual({ woken: 0 });+ });it("does not count a skip/delivered_nowhere outcome as woken", async () => {mockListBotsForMachine.mockResolvedValue([{ id: "bot_1", name: "a", description: "" },{ id: "bot_2", name: "b", description: "" },- ])- mockGetLatestUnreadMessageForAgent.mockResolvedValue({ messageId: "msg_x" })+ ]);+ mockGetLatestUnreadMessageForAgent.mockResolvedValue({+ messageId: "msg_x",+ });mockDispatchOneUnreadWake.mockResolvedValueOnce({ outcome: "skip", reason: "already_read" })- .mockResolvedValueOnce({ outcome: "delivered_nowhere", machineId: "cm_1" })+ .mockResolvedValueOnce({+ outcome: "delivered_nowhere",+ machineId: "cm_1",+ });- const res = await POST(req({ Authorization: "Bearer cmk_ok" }))+ const res = await POST(req({ Authorization: "Bearer cmk_ok" }));- expect(await res.json()).toEqual({ woken: 0 })- })+ expect(await res.json()).toEqual({ woken: 0 });+ });it("401 without Authorization", async () => {- const res = await POST(req())- expect(res.status).toBe(401)- expect(mockListBotsForMachine).not.toHaveBeenCalled()- })+ const res = await POST(req());+ expect(res.status).toBe(401);+ expect(mockListBotsForMachine).not.toHaveBeenCalled();+ });it("401 with unknown credential", async () => {- mockFindCred.mockResolvedValue(null)- const res = await POST(req({ Authorization: "Bearer cmk_bad" }))- expect(res.status).toBe(401)- })-})+ mockFindCred.mockResolvedValue(null);+ const res = await POST(req({ Authorization: "Bearer cmk_bad" }));+ expect(res.status).toBe(401);+ });+});