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
refactor(daemon): dedicated CLI commands section + non-brittle prompt tests
Gusab50bd5c4c6f
diff --git a/AGENTS.md b/AGENTS.mdindex 0c4d5e4de..3630decb0 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -10,6 +10,7 @@ Alook's main purpose is to make the cli agent always on, and give it a email add- `src/ws-do`: WebSocket Durable Object worker## MUST+- Don't write comment: comment may be outdated, code never. Unless the comment are specs and rules.- run `pnpm typecheck`, `pnpm test` as the final check when you think the code is ready.- service must be STATELESS! All the state must be in DB or local, never put important states in memory.- scope the queries before, not check the ownership after. don't query data then check if the data belongs to a workspace, use workspace id ahead to query the data.diff --git a/src/daemon/src/drivers/pi.test.ts b/src/daemon/src/drivers/pi.test.tsindex 63acfbf0a..149fdb854 100644--- a/src/daemon/src/drivers/pi.test.ts+++ b/src/daemon/src/drivers/pi.test.ts@@ -73,4 +73,11 @@ describe("PiDriver.createSession — AGENTS.md packing", () => {await driver.createSession(baseCtx({ standingPrompt: "" }), fakeDeps());expect(fs.existsSync(path.join(tmpDir, CANONICAL_FILE))).toBe(false);});++ it("creates the workdir first when it doesn't exist yet (unlike prepareCliTransport's stateDir mkdir, nothing else guarantees this for Pi)", async () => {+ const driver = new PiDriver();+ const notYetCreated = path.join(tmpDir, "not-yet-created", "agent_1");+ await driver.createSession(baseCtx({ workingDirectory: notYetCreated }), fakeDeps());+ expect(fs.readFileSync(path.join(notYetCreated, CANONICAL_FILE), "utf-8")).toBe("You are Pi.");+ });});diff --git a/src/daemon/src/drivers/pi.ts b/src/daemon/src/drivers/pi.tsindex 4e31de165..adc737c0c 100644--- a/src/daemon/src/drivers/pi.ts+++ b/src/daemon/src/drivers/pi.ts@@ -13,6 +13,7 @@* same convention).*/import { createRequire } from "module";+import { mkdirSync } from "fs";import type { Driver, LaunchConfig, LaunchContext, ParsedEvent, SpawnResult } from "../types.js";import { buildCliTransportSystemPrompt } from "./cliTransport.js";import { writeAgentFile } from "./agentFile.js";@@ -115,8 +116,13 @@ export class PiDriver implements Driver {const spawnEnv = await deps.buildSpawnEnv();// Pi has no child process, so it never goes through prepareCliTransport —// write AGENTS.md here directly (same unified packing every other driver- // gets); Pi's SDK auto-reads it from cwd, same as the CLI drivers.- if (ctx.standingPrompt) writeAgentFile(ctx.workingDirectory, ctx.standingPrompt);+ // gets); Pi's SDK auto-reads it from cwd, same as the CLI drivers. Unlike+ // prepareCliTransport (which creates the workdir via its stateDir mkdir),+ // nothing guarantees ctx.workingDirectory exists yet, so create it first.+ if (ctx.standingPrompt) {+ mkdirSync(ctx.workingDirectory, { recursive: true });+ writeAgentFile(ctx.workingDirectory, ctx.standingPrompt);+ }const f = resolveLaunchFieldsOrDefault(ctx.config.runtimeConfig);const { session, sessionId } = await deps.createAgentSession({cwd: ctx.workingDirectory,diff --git a/src/daemon/src/drivers/systemPrompt.test.ts b/src/daemon/src/drivers/systemPrompt.test.tsindex ed472a434..fedee3324 100644--- a/src/daemon/src/drivers/systemPrompt.test.ts+++ b/src/daemon/src/drivers/systemPrompt.test.ts@@ -15,61 +15,53 @@ const baseConfig: LaunchConfig = {},};-describe("buildCliSystemPrompt — Alook default", () => {- const prompt = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });-- it("keeps the core sections", () => {- expect(prompt).toContain("You are an AI agent operating in");- expect(prompt).toContain("## CLI tool");- expect(prompt).toContain("## Sending & receiving messages");- expect(prompt).toContain("## Privacy & Security");- expect(prompt).toContain("## On wake");- expect(prompt).toContain("## Communication in Alook");- expect(prompt).toContain("## Channel awareness");- expect(prompt).toContain("## Workspace & Memory");- expect(prompt).toContain("## Message Notifications");- });-- it("does NOT bake in any other product's protocol conventions", () => {- expect(prompt).not.toContain("RFC 5424");- expect(prompt).not.toContain(":shortid");- expect(prompt).not.toContain("todo → in_progress");- expect(prompt).not.toContain("MEMORY.md");- expect(prompt).not.toMatch(/##\s*CRITICAL RULES/);+/**+ * 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.+ */+describe("buildCliSystemPrompt", () => {+ it("returns non-empty content for both lifecycle kinds", () => {+ expect(buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" }).length).toBeGreaterThan(0);+ expect(buildCliSystemPrompt(baseConfig, { lifecycleKind: "per_turn" }).length).toBeGreaterThan(0);});- it("no longer has the removed Additional rules / Notes / communicationGuide sections", () => {- expect(prompt).not.toContain("## Additional rules");- expect(prompt).not.toMatch(/##\s*Notes\b/);+ it("produces different content for persistent vs per_turn lifecycles", () => {+ const persistent = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });+ const perTurn = buildCliSystemPrompt(baseConfig, { lifecycleKind: "per_turn" });+ expect(persistent).not.toBe(perTurn);});- it("hardcodes the alook CLI name and Alook platform label everywhere", () => {- expect(prompt).toContain("`alook`");- expect(prompt).toContain("You are an AI agent operating in Alook.");- });-});--describe("buildCliSystemPrompt — lifecycle-driven notification section", () => {- it("persistent describes busy-time inbox notices", () => {- const p = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });- expect(p).toContain("inbox notice");- expect(p).toContain("inbox pull");- });+ it("injects agentName and agentHandle into the prompt only when set", () => {+ const withIdentity = buildCliSystemPrompt(+ { ...baseConfig, agentName: "Nova", agentHandle: "nova" },+ { lifecycleKind: "persistent" },+ );+ expect(withIdentity).toContain("Nova");+ expect(withIdentity).toContain("nova");- it("per_turn describes finishing the wake and stopping instead of polling", () => {- const p = buildCliSystemPrompt(baseConfig, { lifecycleKind: "per_turn" });- expect(p).toContain("once per wake");- expect(p).not.toContain("inbox notice");+ const without = buildCliSystemPrompt(baseConfig, { lifecycleKind: "persistent" });+ expect(without).not.toContain("Nova");});-});-describe("buildCliSystemPrompt — role injection", () => {- it("includes the role when config.description is set", () => {- const p = buildCliSystemPrompt(+ it("includes a Role section with config.description's exact text only when it's set", () => {+ const withRole = buildCliSystemPrompt({ ...baseConfig, description: "You are the onboarding assistant." },{ lifecycleKind: "persistent" },);- expect(p).toContain("## Role");- expect(p).toContain("You are the onboarding assistant.");+ expect(withRole).toContain("You are the onboarding assistant.");+ expect(withRole).toContain("## Role");++ 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");});});diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.tsindex 65ff23256..260ec1c4f 100644--- a/src/daemon/src/drivers/systemPrompt.ts+++ b/src/daemon/src/drivers/systemPrompt.ts@@ -4,16 +4,21 @@* Every CLI driver's `buildSystemPrompt` funnels through here. The prompt is* assembled from a fixed sequence of sections:* 1. Identity line- * 2. CLI tool description- * 3. Sending & receiving messages- * 4. Channel refs & message format- * 5. Credential hygiene- * 6. Startup sequence- * 7. Communication style & etiquette- * 8. Channel awareness- * 9. Workspace & Memory- * 10. Message notifications (auto-generated from `lifecycleKind`)- * 11. Role (from `config.description`, when set)+ * 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. Critical rules (hard constraints, visually separated from style advice)+ * 5. Startup sequence+ * 6. Communication style & etiquette+ * 7. Channel awareness+ * 8. Workspace & memory+ * 9. Message notifications (auto-generated from `lifecycleKind`)+ * 10. Role (from `config.description`, when set)** 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@@ -21,7 +26,7 @@** 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 10 is derived+ * — 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.@@ -32,7 +37,7 @@ const CLI = "alook";export interface SystemPromptOpts {/**- * Drives the auto-generated `## Message Notifications` section: whether+ * Drives the auto-generated `## Message notifications` section: whether* this runtime's process stays alive across turns (`"persistent"`) or* handles exactly one turn and exits (`"per_turn"`). Pass* `driver.lifecycle.kind` directly — do not hand-write reminder text per@@ -45,39 +50,54 @@ export interface SystemPromptOpts {/* Section builders *//* ------------------------------------------------------------------ */-function cliToolsSection(): string {+/**+ * Reference list of every command `alook` exposes, grouped by category, plus+ * the universal output-format contract every command shares. This is the ONE+ * place commands are enumerated — when a future category is added (tasks,+ * calendar, …) it gets its own `### <Category>` subsection here, so the list+ * of "what can I run" always lives in one spot instead of being rediscovered+ * from scattered mentions across other sections.+ */+function cliCommandsSection(): string {return [- "## CLI tool",+ "## CLI commands","",- `\`${CLI}\` is your only way to send or receive messages. 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.`,+ "",+ "### Messaging","",`1. \`${CLI} inbox pull\` — fetch unread messages.`,`2. \`${CLI} message send\` — send a message to a channel, DM, or thread.`,"",- `Run \`${CLI} <subcommand> -h\` for full usage and flags.`,+ "### Output format",+ "",+ `Every \`${CLI}\` command outputs a single JSON line (envelope):`,+ '- Success: `{"success": { ... }}`',+ '- Error: `{"error": "message", "hint": "optional recovery hint"}`',].join("\n");}-function messagingHowToSection(): string {+/**+ * The "how" for the messaging commands specifically: reply mechanics,+ * addressing, and the shape of a pulled message. Command *existence* lives in+ * `## CLI commands` — this section is about using them, not listing them, so+ * it doesn't need to grow when new non-messaging command categories are added.+ * Named "Messaging", not "Communication", so it can't collide with+ * `## Communication style` (social/behavioral norms, a different concern).+ */+function messagingSection(): string {return [- "## Sending & receiving messages",+ "## Messaging",+ "",+ "### Sending & receiving","",- `- Read incoming messages with \`${CLI} inbox pull\`.`,"- Send a reply — two options depending on length:",` - Short: \`${CLI} message send --target <ref> --text "brief reply"\``,` - Long: write body to a file, then \`${CLI} message send --target <ref> --file /path/to/msg.txt\``,"- Address your reply to where the message came from.",- "- **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.`,- "- Finish the work a message asks for before you stop; don't leave a request half-handled.",- ].join("\n");-}--function channelRefSection(): string {- return [- "## Channel refs & message format","",- "### Addressing",+ "### Channel refs & addressing","","Channels and messages are addressed with path-style refs:","",@@ -106,23 +126,27 @@ function channelRefSection(): string {"- `sender` — `@handle` of who sent it.","- `content.text` — the message body.","- `time` — ISO-8601 timestamp.",- "",- "### CLI output format",- "",- `All \`${CLI}\` commands output a single JSON line (envelope):`,- '- Success: `{"success": { ... }}`',- '- Error: `{"error": "message", "hint": "optional recovery hint"}`',].join("\n");}-function credentialHygieneSection(): string {+/**+ * Hard constraints, pulled out of style/prose bullets and given their own+ * visually-distinct section — break one of these and something actually+ * fails, as opposed to the softer style guidance elsewhere in the prompt.+ */+function criticalRulesSection(): string {return [- "## Privacy & Security",+ "## Critical rules","",- "- Do not expose tokens, keys, or secrets in any message or channel.",- "- Redact credential-like strings from tool output before sharing.",- "- Your profile credential is the sole auth source. If it's unavailable, stop — do not",- " attempt alternate tokens or environment variables as fallback.",+ "- Do not expose tokens, keys, or secrets in any message or channel; redact",+ " 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.",+ "- **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.`,+ "- Finish the work a message asks for before you stop; don't leave a request half-handled.",].join("\n");}@@ -140,7 +164,7 @@ function startupSequenceSection(): string {function communicationStyleSection(): string {return [- "## Communication in Alook",+ "## Communication style","","Your reasoning is invisible to others — keep them in the loop:","- Acknowledge tasks before starting; give a one-line plan.",@@ -169,7 +193,7 @@ function channelAwarenessSection(): string {function workspaceMemorySection(): string {return [- "## Workspace & Memory",+ "## Workspace & memory","","Your cwd is a persistent workspace that survives across sessions.","",@@ -187,7 +211,7 @@ function workspaceMemorySection(): string {"Do NOT put ephemeral state (current task, in-progress status) in memory.md — the","context timeline handles that.","",- "### Context Timeline",+ "### 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.",@@ -208,7 +232,7 @@ function workspaceMemorySection(): string {function messageNotificationSection(lifecycleKind: SystemPromptOpts["lifecycleKind"]): string {if (lifecycleKind === "per_turn") {return [- "## Message Notifications",+ "## 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",@@ -216,13 +240,16 @@ function messageNotificationSection(lifecycleKind: SystemPromptOpts["lifecycleKi].join("\n");}return [- "## Message Notifications",+ "## 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.",- `It's non-urgent: finish your current step, then run \`${CLI} inbox pull\` at a natural`,- "breakpoint to fetch the bodies.",+ "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");}@@ -234,9 +261,9 @@ function messageNotificationSection(lifecycleKind: SystemPromptOpts["lifecycleKi* Assemble the standing/system prompt.** Asserts what's universally true for any Alook agent workspace — identity,- * CLI tool, messaging shape, credential hygiene, startup sequence,- * communication style, channel awareness, workspace/memory model, and- * notification handling. The only per-driver input is `lifecycleKind`.+ * CLI command reference, messaging mechanics, critical rules, startup+ * 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 {const identityParts = ["You are an AI agent operating in Alook."];@@ -245,10 +272,9 @@ export function buildCliSystemPrompt(config: LaunchConfig, opts: SystemPromptOptconst sections: string[] = [identityParts.join(" "),- cliToolsSection(),- messagingHowToSection(),- channelRefSection(),- credentialHygieneSection(),+ cliCommandsSection(),+ messagingSection(),+ criticalRulesSection(),startupSequenceSection(),communicationStyleSection(),channelAwarenessSection(),@@ -257,7 +283,12 @@ export function buildCliSystemPrompt(config: LaunchConfig, opts: SystemPromptOpt];if (config.description) {- sections.push("## Role\n" + config.description);+ sections.push(+ "## Role\n" ++ config.description ++ "\n\nThis 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).",+ );}return sections.filter((s) => s && s.length > 0).join("\n\n");