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
fix(daemon): validate downlink HostCommand with zod (convergence #6)
Claudette#9873b9f61c9c48d5
diff --git a/src/daemon/src/server/contract.ts b/src/daemon/src/server/contract.tsindex 72b52bbf9..72872b3ad 100644--- a/src/daemon/src/server/contract.ts+++ b/src/daemon/src/server/contract.ts@@ -79,4 +79,5 @@ export {formatRef,parseSeq,formatSeq,+ HostCommandSchema,} from "@alook/shared/community-cli-contract";diff --git a/src/daemon/src/server/wsControlChannel.test.ts b/src/daemon/src/server/wsControlChannel.test.tsindex 957edc08f..d85b8321f 100644--- a/src/daemon/src/server/wsControlChannel.test.ts+++ b/src/daemon/src/server/wsControlChannel.test.ts@@ -1,6 +1,6 @@import { describe, it, expect } from "vitest";import { WsControlChannel } from "./wsControlChannel";-import type { WebSocketLike, HostReady, AgentSessionReport } from "./contract";+import type { WebSocketLike, HostReady, AgentSessionReport, HostCommand } from "./contract";import type { Logger } from "../logger";/**@@ -413,6 +413,152 @@ describe("WsControlChannel — reconnect timer keeps the event loop alive", () =});});+describe("WsControlChannel — downlink HostCommand validation (convergence #6)", () => {+ // A REAL `agent:wake` frame as `buildUnreadWakeCommand` (wake-dispatch.ts)+ // constructs it: type/agentId/config/launchId/unreadNotice, with the optional+ // load-bearing `sessionId` present. `config`/`unreadNotice` are opaque blobs+ // (validated as `z.unknown()`), so their interiors must survive untouched.+ const realWake: HostCommand = {+ type: "agent:wake",+ agentId: "bot_1",+ config: { runtime: "claude", model: { kind: "default" }, agentName: "Melisa" } as never,+ sessionId: "sess_abc",+ launchId: "launch_1",+ unreadNotice: {+ kind: "unread_notice",+ channel: "/demo/general",+ latestSeq: 42,+ channelId: "chan_xyz",+ },+ };+ // Real reset/nap/model_switch frames as ws-do (`index.ts`) serializes them.+ const realReset: HostCommand = {+ type: "agent:reset",+ agentId: "bot_1",+ config: { runtime: "claude" } as never,+ launchId: "launch_r",+ };+ const realNap: HostCommand = {+ type: "agent:nap",+ agentId: "bot_1",+ config: { runtime: "claude" } as never,+ launchId: "launch_n",+ handoff: "note to my reborn self",+ };+ const realModelSwitch: HostCommand = {+ type: "agent:model_switch",+ agentId: "bot_1",+ config: { runtime: "claude", model: { kind: "named", id: "opus" } } as never,+ launchId: "launch_m",+ };+ const realStop: HostCommand = { type: "agent:stop", agentId: "bot_1" };++ function driven() {+ const { ch, sockets } = makeChannel();+ const received: HostCommand[] = [];+ ch.onCommand((c) => {+ received.push(c);+ });+ ch.onResync(() => ({ ready: { runtimeReport: [], runningAgents: [] }, sessions: [], activities: [] }));+ ch.connect();+ sockets[0].emit("open");+ return { sockets, received };+ }++ it("dispatches each valid arm unchanged (happy path — the transparent gate)", () => {+ for (const frame of [realWake, realReset, realNap, realModelSwitch, realStop]) {+ const { sockets, received } = driven();+ sockets[0].emit("message", JSON.stringify(frame));+ expect(received).toHaveLength(1);+ expect(received[0].type).toBe(frame.type);+ }+ });++ it("Z5 — a real producer frame round-trips field-for-field at the top level (default-strip drops nothing real)", () => {+ // The strip risk: zod rebuilds `parsed.data`, so any top-level field the+ // schema forgot to enumerate is silently dropped. Assert every real frame's+ // top-level keys AND values survive — including optional load-bearing ones+ // (`wake.sessionId`) and the opaque blobs' interiors (`config`,+ // `unreadNotice.channelId`).+ for (const frame of [realWake, realReset, realNap, realModelSwitch, realStop]) {+ const { sockets, received } = driven();+ sockets[0].emit("message", JSON.stringify(frame));+ expect(received).toHaveLength(1);+ // Deep-equal against the exact producer shape — nothing added, nothing lost.+ expect(received[0]).toEqual(frame);+ // Explicit belt-and-suspenders on the fields strip loves to eat.+ if (frame.type === "agent:wake") {+ expect(received[0]).toHaveProperty("sessionId", "sess_abc");+ expect((received[0] as typeof realWake).unreadNotice).toEqual(realWake.unreadNotice);+ }+ }+ });++ it("drops + logs a malformed frame instead of dispatching it", () => {+ const malformed: unknown[] = [+ { type: "agent:wake", config: {}, launchId: "l", unreadNotice: {} }, // missing agentId+ { type: "agent:wake", agentId: "b", config: {}, unreadNotice: {} }, // missing launchId+ { type: "agent:nap", agentId: "b", config: {}, launchId: "l" }, // missing handoff+ { type: "agent:nap", agentId: "b", config: {}, launchId: "l", handoff: "" }, // empty handoff+ { type: "agent:reset", agentId: "", config: {}, launchId: "l" }, // empty agentId+ { type: "agent:unknown", agentId: "b" }, // unknown discriminant+ ];+ for (const frame of malformed) {+ const logger = stubLogger();+ const { ch, sockets } = makeChannel({ logger });+ const received: HostCommand[] = [];+ ch.onCommand((c) => received.push(c));+ ch.onResync(() => ({ ready: { runtimeReport: [], runningAgents: [] }, sessions: [], activities: [] }));+ ch.connect();+ sockets[0].emit("open");+ sockets[0].emit("message", JSON.stringify(frame));+ expect(received).toHaveLength(0);+ expect(logger.calls.warn.some(([m]) => m === "dropped malformed HostCommand frame")).toBe(true);+ }+ });++ it("keeps AUTH_REJECTED ahead of the schema gate — it is not a HostCommand", () => {+ // The `{type:"error", code:"AUTH_REJECTED"}` frame is NOT a HostCommand and+ // must short-circuit BEFORE `HostCommandSchema.safeParse`, still firing+ // onAuthRejected and never reaching a command listener.+ let authRejected = false;+ const received: HostCommand[] = [];+ const sockets: FakeSocket[] = [];+ const ch = new WsControlChannel({+ url: "ws://test",+ webSocketFactory: () => {+ const s = new FakeSocket();+ sockets.push(s);+ return s;+ },+ reconnect: { baseMs: 1, maxMs: 1 },+ onAuthRejected: () => {+ authRejected = true;+ },+ });+ ch.onCommand((c) => received.push(c));+ ch.onResync(() => ({ ready: { runtimeReport: [], runningAgents: [] }, sessions: [], activities: [] }));+ ch.connect();+ sockets[0].emit("open");+ sockets[0].emit("message", JSON.stringify({ type: "error", code: "AUTH_REJECTED" }));+ expect(authRejected).toBe(true);+ expect(received).toHaveLength(0);+ });++ it("config forward-compat — an unrecognized-but-well-formed config field still parses (no hard drop)", () => {+ // Scope (a): `config` is `z.unknown()` opaque passthrough, so a newer server+ // field on config must NOT hard-drop the frame on an older daemon.+ const frame: HostCommand = {+ ...realReset,+ config: { runtime: "claude", someBrandNewFieldFromANewerServer: true } as never,+ };+ const { sockets, received } = driven();+ sockets[0].emit("message", JSON.stringify(frame));+ expect(received).toHaveLength(1);+ expect((received[0] as typeof realReset).config).toEqual(frame.config);+ });+});+describe("WsControlChannel — logging", () => {it("logs info on open, and info on resync with runtime/session counts", async () => {const logger = stubLogger();diff --git a/src/daemon/src/server/wsControlChannel.ts b/src/daemon/src/server/wsControlChannel.tsindex c43fa9ad7..203cbbac0 100644--- a/src/daemon/src/server/wsControlChannel.ts+++ b/src/daemon/src/server/wsControlChannel.ts@@ -34,6 +34,7 @@ import type {AgentActivityState,HostBotAuditEventFrame,} from "./contract.js";+import { HostCommandSchema } from "./contract.js";import { createLogger, type Logger } from "../logger.js";// Re-export so existing importers of these from this module keep working.export type { WebSocketLike, WebSocketFactory } from "./contract.js";@@ -374,9 +375,24 @@ export class WsControlChannel implements HostControlChannel {return;}- // Valid server frame — reset backoff (server accepted us).+ // Valid server frame — reset backoff (server accepted us). AUTH_REJECTED+ // (above) is an `error` frame, NOT a HostCommand, so it stays ahead of the+ // schema gate and short-circuits regardless of command validity.this.attempt = 0;- const cmd = frame as unknown as HostCommand;++ // Validate the downlink shape before dispatch — the mirror of ws-do's+ // per-frame `safeParse` on the uplink. A malformed/half-written frame (or a+ // producer bug) must be DROPPED + logged here, never handed to the router's+ // arms as a lie. Valid frames dispatch exactly as before (transparent gate).+ const parsed = HostCommandSchema.safeParse(frame);+ if (!parsed.success) {+ this.log.warn("dropped malformed HostCommand frame", {+ type: frame.type,+ issues: parsed.error.issues.map((i) => ({ path: i.path.join("."), code: i.code })),+ });+ return;+ }+ const cmd = parsed.data as HostCommand;for (const cb of this.commandCbs) {// Each listener is fire-and-forget; failures in one must not skip the// next. Catch rejections explicitly — a bare `void cb(cmd)` on an asyncdiff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.tsindex d82cb423e..7ac10d0bb 100644--- a/src/shared/src/community-cli-contract.ts+++ b/src/shared/src/community-cli-contract.ts@@ -22,6 +22,7 @@* IDs are **nanoid** strings (not UUIDs).*/+import { z } from "zod";import type { RuntimeConfig } from "./runtime-config";import type { ChannelType } from "./utils/community-roles";@@ -1113,3 +1114,112 @@ export function parseSeq(s: string): Seq {export function formatSeq(seq: Seq): string {return `#${seq}`;}++// ---------------------------------------------------------------------------+// Downlink (server → daemon) command validation+// ---------------------------------------------------------------------------+//+// The mirror of the uplink (daemon → server) frame `safeParse`s in `src/ws-do`+// (`HostReadyMessageSchema`, `SessionErrorFrameSchema`, `AgentActivityMessageSchema`,+// … in ws-durable.ts). Before this, the daemon's `WsControlChannel.onMessage`+// trusted the frame's SHAPE blindly (`typeof frame.type === "string"` then+// `frame as HostCommand`), so a malformed/half-written frame or a producer bug+// reached the router's arms as a lie. `HostCommandSchema` closes exactly that+// asymmetry — the uplink was validated, the downlink was not.+//+// Colocated with the `HostCommand` TYPE (above) rather than in `schemas.ts`+// on purpose: the daemon reaches this file via the `@alook/shared/community-cli-contract`+// subpath (see `src/daemon/src/server/contract.ts`) and deliberately never+// imports the main `@alook/shared` barrel, which would drag the server/DB code+// (drizzle, queries) into the daemon bundle. The lockstep guard below also only+// compiles here, where the `HostCommand` type is in scope.+//+// SHALLOW by design (CTO ruling — plans/daemon-downlink-zod.md): validate the+// discriminant `type` + each arm's REQUIRED top-level scalars, and enumerate+// EVERY top-level field per arm (including optional load-bearing ones like+// `wake.sessionId`) so zod's default strip drops nothing real. The nested typed+// blobs — `config: RuntimeConfig` and `unreadNotice: UnreadNotice` — stay+// `z.unknown()` opaque passthrough: their interiors carry optional load-bearing+// fields (`unreadNotice.channelId?`, resume `sessionId?`) that a hand-listed+// object schema would most easily strip by accident, and the #6 failure surface+// is the TOP LEVEL (missing `type`/`agentId`/`launchId`, a half-written frame),+// not a blob's interior. `resolveLaunchFieldsOrDefault` re-parses `config`+// downstream with its own defaulting, so deep-validating it here would only turn+// a forward-compatible server field into a hard drop on an older daemon.+export const HostCommandSchema = z.discriminatedUnion("type", [+ z.object({+ type: z.literal("agent:wake"),+ agentId: z.string().min(1),+ config: z.unknown(),+ sessionId: z.string().optional(),+ launchId: z.string().min(1),+ unreadNotice: z.unknown(),+ }),+ z.object({+ type: z.literal("agent:stop"),+ agentId: z.string().min(1),+ }),+ z.object({+ type: z.literal("agent:reset"),+ agentId: z.string().min(1),+ config: z.unknown(),+ launchId: z.string().min(1),+ }),+ z.object({+ type: z.literal("agent:nap"),+ agentId: z.string().min(1),+ config: z.unknown(),+ launchId: z.string().min(1),+ handoff: z.string().min(1),+ }),+ z.object({+ type: z.literal("agent:model_switch"),+ agentId: z.string().min(1),+ config: z.unknown(),+ launchId: z.string().min(1),+ }),+ // The `bot:*` arms are NOT what #6 targets — the daemon acts on `agent:*`;+ // `bot:*` merely mutate/evict the `botsById` cache at the createDaemon layer.+ // Per the CTO scope ("bot:* covered for union-completeness, no bespoke+ // checks"), validate only the discriminant + the load-bearing `botId` (the+ // key the cache is keyed on / removed by) and keep the descriptive fields+ // OPTIONAL. Requiring `ownerName`/`discriminator` here would be a bespoke+ // check AND a behavior change — the daemon today processes a partial bot+ // frame (updating whatever fields it carries) rather than dropping it, and a+ // dropped bot frame would silently stale the cache (wrong `agentHandle`),+ // which is worse than the shallow-shape lie #6 is fixing on the command path.+ z.object({+ type: z.literal("bot:added"),+ botId: z.string().min(1),+ name: z.string().optional(),+ discriminator: z.string().optional(),+ description: z.string().optional(),+ ownerName: z.string().optional(),+ ownerDiscriminator: z.string().optional(),+ }),+ z.object({+ type: z.literal("bot:updated"),+ botId: z.string().min(1),+ name: z.string().optional(),+ discriminator: z.string().optional(),+ description: z.string().optional(),+ ownerName: z.string().optional(),+ ownerDiscriminator: z.string().optional(),+ }),+ z.object({+ type: z.literal("bot:removed"),+ botId: z.string().min(1),+ }),+]);++// Z2 — type↔schema lockstep. The `[T] extends [U]` tuple-wrap defeats union+// distribution so the WHOLE `HostCommand` union must be assignable to the+// schema's inferred type in one shot: a future `HostCommand` arm not added to+// the union above fails to compile (the mirror of #4's capability-completeness+// guard). Direction is `HostCommand extends infer` (not the reverse) because+// the `z.unknown()` blobs make `infer` strictly WIDER than `HostCommand` —+// `RuntimeConfig`/`UnreadNotice` are assignable to `unknown`, never the reverse.+type _HostCommandSchemaCoversType =+ [HostCommand] extends [z.infer<typeof HostCommandSchema>] ? true : never;+const _hostCommandSchemaCoversType: _HostCommandSchemaCoversType = true;+void _hostCommandSchemaCoversType;