Buckets:
| const assert = require("node:assert/strict"); | |
| const { | |
| chmodSync, | |
| existsSync, | |
| lstatSync, | |
| mkdtempSync, | |
| mkdirSync, | |
| readdirSync, | |
| readFileSync, | |
| rmSync, | |
| symlinkSync, | |
| writeFileSync, | |
| } = require("node:fs"); | |
| const { tmpdir } = require("node:os"); | |
| const { join, resolve } = require("node:path"); | |
| const { spawn, spawnSync } = require("node:child_process"); | |
| const { randomBytes } = require("node:crypto"); | |
| const { test } = require("node:test"); | |
| const root = resolve(__dirname, ".."); | |
| const crew = join(root, "dist", "crew.js"); | |
| function baseMsg(extra) { | |
| return { | |
| ts: new Date().toISOString(), | |
| from: "sender-session-id", | |
| fromShort: "sender01", | |
| fromCwd: "/tmp/sender", | |
| text: "coordinate first", | |
| expiresAt: new Date(Date.now() + 3_600_000).toISOString(), | |
| ...extra, | |
| }; | |
| } | |
| function inboxDir(env, sid) { | |
| return join(env.CREW_INBOX_ROOT, sid); | |
| } | |
| /** Inboxes written by crew <= 0.3.x, still drained during migration. */ | |
| function legacyInboxDir(env, sid, era) { | |
| return era === "0.2" | |
| ? join(env.CLAUDE_HOME, "crew", "inbox", sid) | |
| : join(env.CREW_HOME, "inbox", sid); | |
| } | |
| function dropMessage(dir, msg) { | |
| mkdirSync(dir, { recursive: true }); | |
| const name = `${Date.now()}-${Math.random().toString(16).slice(2, 10)}.json`; | |
| writeFileSync(join(dir, name), JSON.stringify(msg)); | |
| } | |
| function writeInbox(env, sid, msg) { | |
| dropMessage(inboxDir(env, sid), msg); | |
| } | |
| function pendingFiles(dir) { | |
| try { | |
| return readdirSync(dir).filter((f) => f.endsWith(".json")); | |
| } catch { | |
| return []; | |
| } | |
| } | |
| /** A live session record, as the hooks would have registered it. */ | |
| function registerSession(env, sid, pid, extra) { | |
| mkdirSync(join(env.CREW_HOME, "sessions"), { recursive: true }); | |
| writeFileSync( | |
| join(env.CREW_HOME, "sessions", `${sid}.json`), | |
| JSON.stringify({ | |
| pid, | |
| sessionId: sid, | |
| agent: "claude", | |
| status: "idle", | |
| cwd: "/tmp/work", | |
| startedAt: new Date().toISOString(), | |
| lastSeen: new Date().toISOString(), | |
| transcript: null, | |
| ...extra, | |
| }), | |
| ); | |
| } | |
| /** A process that stays alive so liveness pruning keeps the record. */ | |
| function sleeper(t) { | |
| const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1e9)"], { | |
| stdio: "ignore", | |
| }); | |
| t.after(() => child.kill()); | |
| return child; | |
| } | |
| function runAsync(args, env, input) { | |
| return new Promise((done) => { | |
| const child = spawn(process.execPath, [crew, ...args], { | |
| cwd: root, | |
| env, | |
| stdio: ["pipe", "pipe", "pipe"], | |
| }); | |
| let stdout = ""; | |
| let stderr = ""; | |
| child.stdout.on("data", (c) => (stdout += c)); | |
| child.stderr.on("data", (c) => (stderr += c)); | |
| child.on("close", (status) => done({ status, stdout, stderr })); | |
| child.stdin.end(input); | |
| }); | |
| } | |
| function stopHook(env, sid, event = "Stop") { | |
| return run( | |
| ["--hook"], | |
| env, | |
| JSON.stringify({ | |
| session_id: sid, | |
| hook_event_name: event, | |
| transcript_path: null, | |
| cwd: root, | |
| }), | |
| ); | |
| } | |
| function homes() { | |
| const root = mkdtempSync(join(tmpdir(), "crew-test-")); | |
| const env = { | |
| ...process.env, | |
| CLAUDE_HOME: join(root, "claude"), | |
| CODEX_HOME: join(root, "codex"), | |
| CREW_HOME: join(root, "crew"), | |
| CREW_INBOX_ROOT: join(root, "inbox"), // never the real /tmp/crew-<uid> | |
| XDG_CONFIG_HOME: join(root, "xdg-config"), // OpenCode plugin location | |
| XDG_DATA_HOME: join(root, "xdg-data"), // OpenCode sqlite location | |
| }; | |
| // The OpenCode plugin's own env identification must not leak between tests. | |
| delete env.CREW_AGENT; | |
| delete env.CREW_PID; | |
| delete env.CREW_SESSION_ID; | |
| return { root, env }; | |
| } | |
| function run(args, env, input) { | |
| return spawnSync(process.execPath, [crew, ...args], { | |
| cwd: root, | |
| env, | |
| input, | |
| encoding: "utf8", | |
| }); | |
| } | |
| test("install-hook merges all products and uninstall preserves other settings", () => { | |
| const h = homes(); | |
| mkdirSync(h.env.CLAUDE_HOME, { recursive: true }); | |
| writeFileSync( | |
| join(h.env.CLAUDE_HOME, "settings.json"), | |
| JSON.stringify({ theme: "dark" }), | |
| ); | |
| assert.equal(run(["install-hook"], h.env).status, 0); | |
| for (const path of [ | |
| join(h.env.CLAUDE_HOME, "settings.json"), | |
| join(h.env.CODEX_HOME, "hooks.json"), | |
| ]) { | |
| const config = JSON.parse(readFileSync(path, "utf8")); | |
| for (const event of ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"]) { | |
| assert.equal(config.hooks[event][0].hooks[0].command, "crew --hook"); | |
| } | |
| } | |
| assert.equal( | |
| JSON.parse(readFileSync(join(h.env.CLAUDE_HOME, "settings.json"), "utf8")).theme, | |
| "dark", | |
| ); | |
| const plugin = join(h.env.XDG_CONFIG_HOME, "opencode", "plugins", "crew.js"); | |
| const source = readFileSync(plugin, "utf8"); | |
| assert.match(source, /generated by @0xmmo\/crew/); | |
| assert.ok(source.includes(JSON.stringify(join(root, "dist", "crew.js")))); | |
| assert.equal(run(["uninstall-hook"], h.env).status, 0); | |
| const remaining = JSON.parse( | |
| readFileSync(join(h.env.CLAUDE_HOME, "settings.json"), "utf8"), | |
| ); | |
| assert.deepEqual(remaining, { theme: "dark" }); | |
| assert.equal(existsSync(plugin), false); | |
| // A plugin file crew didn't generate is never overwritten or removed. | |
| writeFileSync(plugin, "export const Mine = async () => ({})"); | |
| const refused = run(["install-hook"], h.env); | |
| assert.equal(refused.status, 1); | |
| assert.match(refused.stderr, /refusing to overwrite/); | |
| assert.equal(run(["uninstall-hook"], h.env).status, 0); | |
| assert.equal(existsSync(plugin), true); | |
| }); | |
| test("Codex hooks register, parse, receive mail, and drain on Stop", async (t) => { | |
| const h = homes(); | |
| const sid = "019f-test-codex-session"; | |
| const codexSessions = join(h.env.CODEX_HOME, "sessions", "2026", "07", "14"); | |
| mkdirSync(codexSessions, { recursive: true }); | |
| const transcript = join(codexSessions, `rollout-test-${sid}.jsonl`); | |
| const records = [ | |
| { | |
| timestamp: "2026-07-14T07:00:00.000Z", | |
| type: "session_meta", | |
| payload: { id: sid, cwd: root, source: "cli" }, | |
| }, | |
| { | |
| timestamp: "2026-07-14T07:00:01.000Z", | |
| type: "event_msg", | |
| payload: { type: "user_message", message: "fix the parser" }, | |
| }, | |
| { | |
| timestamp: "2026-07-14T07:00:02.000Z", | |
| type: "response_item", | |
| payload: { | |
| type: "function_call", | |
| name: "exec_command", | |
| arguments: JSON.stringify({ cmd: "npm test" }), | |
| }, | |
| }, | |
| { | |
| timestamp: "2026-07-14T07:00:03.000Z", | |
| type: "response_item", | |
| payload: { type: "function_call_output", output: "all tests pass" }, | |
| }, | |
| { | |
| timestamp: "2026-07-14T07:00:04.000Z", | |
| type: "event_msg", | |
| payload: { type: "agent_message", message: "Parser fixed." }, | |
| }, | |
| { | |
| timestamp: "2026-07-14T07:00:05.000Z", | |
| type: "event_msg", | |
| payload: { type: "task_complete", last_agent_message: "Parser fixed." }, | |
| }, | |
| ]; | |
| writeFileSync(transcript, records.map(JSON.stringify).join("\n") + "\n"); | |
| const fake = spawn( | |
| process.execPath, | |
| [join(root, "test", "fake-codex.cjs"), crew, transcript, root, sid, "codex"], | |
| { cwd: root, env: h.env, stdio: ["pipe", "pipe", "pipe"] }, | |
| ); | |
| t.after(() => fake.kill()); | |
| let output = ""; | |
| fake.stdout.setEncoding("utf8"); | |
| fake.stdout.on("data", (chunk) => (output += chunk)); | |
| await new Promise((resolvePromise, reject) => { | |
| const timer = setTimeout(() => reject(new Error("fake Codex did not start")), 3000); | |
| fake.stdout.on("data", () => { | |
| if (output.includes("ready\n")) { | |
| clearTimeout(timer); | |
| resolvePromise(); | |
| } | |
| }); | |
| }); | |
| const listed = run(["--json", "10"], h.env); | |
| assert.equal(listed.status, 0, listed.stderr); | |
| const session = JSON.parse(listed.stdout.trim()); | |
| assert.equal(session.sessionId, sid); | |
| assert.equal(session.agent, "codex"); | |
| assert.equal(session.recap, "Parser fixed."); | |
| assert.deepEqual( | |
| session.tail.map((entry) => entry.kind), | |
| ["text", "tool_use", "tool_result", "text"], | |
| ); | |
| assert.equal(session.tail[1].summary, "npm test"); | |
| const sent = run(["send", sid.slice(0, 8), "coordinate first"], h.env); | |
| assert.equal(sent.status, 0, sent.stderr); | |
| fake.stdin.write("stop\n"); | |
| await new Promise((resolvePromise, reject) => { | |
| const timer = setTimeout(() => reject(new Error("Stop hook did not return")), 3000); | |
| fake.stdout.on("data", () => { | |
| if (output.includes("hook:")) { | |
| clearTimeout(timer); | |
| resolvePromise(); | |
| } | |
| }); | |
| }); | |
| const hookLine = output.split("\n").find((line) => line.startsWith("hook:")); | |
| const result = JSON.parse(hookLine.slice(5)); | |
| assert.equal(result.decision, "block"); | |
| assert.match(result.reason, /coordinate first/); | |
| const after = JSON.parse(run(["--json"], h.env).stdout.trim()); | |
| assert.equal(after.pendingMessages, 0); | |
| assert.equal(after.status, "idle"); | |
| }); | |
| test("kickstart force-continues on Stop; plain mail only injects context", () => { | |
| const h = homes(); | |
| const sid = "claude-kickstart-session"; | |
| writeInbox(h.env, sid, baseMsg({ text: "plain hello" })); | |
| const plain = stopHook(h.env, sid); | |
| assert.equal(plain.status, 0, plain.stderr); | |
| const plainOut = JSON.parse(plain.stdout.trim()); | |
| assert.equal(plainOut.decision, undefined); | |
| assert.match(plainOut.hookSpecificOutput.additionalContext, /plain hello/); | |
| writeInbox(h.env, sid, baseMsg({ text: "go fix the build", kickstart: true })); | |
| const kick = stopHook(h.env, sid); | |
| assert.equal(kick.status, 0, kick.stderr); | |
| const kickOut = JSON.parse(kick.stdout.trim()); | |
| assert.equal(kickOut.decision, "block"); | |
| assert.match(kickOut.reason, /go fix the build/); | |
| assert.match(kickOut.reason, /Act on it now/); | |
| // Mid-turn (PostToolUse) the agent is already active, so kickstart mail is | |
| // delivered as context, not a forced continuation. | |
| writeInbox(h.env, sid, baseMsg({ text: "mid turn", kickstart: true })); | |
| const mid = stopHook(h.env, sid, "PostToolUse"); | |
| assert.equal(mid.status, 0, mid.stderr); | |
| const midOut = JSON.parse(mid.stdout.trim()); | |
| assert.equal(midOut.decision, undefined); | |
| assert.match(midOut.hookSpecificOutput.additionalContext, /mid turn/); | |
| }); | |
| const hasSqlite3 = | |
| spawnSync("sqlite3", ["--version"], { encoding: "utf8" }).status === 0; | |
| test( | |
| "OpenCode sessions register, read sqlite history, and gate Stop on kickstart", | |
| { skip: !hasSqlite3 && "sqlite3 CLI not available" }, | |
| async (t) => { | |
| const h = homes(); | |
| const sid = "ses_crewtestopencode"; | |
| // Fixture: OpenCode's message/part tables, one user + one assistant turn. | |
| const dbDir = join(h.env.XDG_DATA_HOME, "opencode"); | |
| mkdirSync(dbDir, { recursive: true }); | |
| const sql = (value) => `'${JSON.stringify(value).replace(/'/g, "''")}'`; | |
| const rows = [ | |
| `CREATE TABLE message (id text PRIMARY KEY, session_id text, time_created integer, time_updated integer, data text);`, | |
| `CREATE TABLE part (id text PRIMARY KEY, message_id text, session_id text, time_created integer, time_updated integer, data text);`, | |
| `INSERT INTO message VALUES ('msg_1', '${sid}', 1000, 1000, ${sql({ role: "user", time: { created: 1000 } })});`, | |
| `INSERT INTO part VALUES ('prt_1', 'msg_1', '${sid}', 1000, 1000, ${sql({ type: "text", text: "scan the repo" })});`, | |
| `INSERT INTO message VALUES ('msg_2', '${sid}', 2000, 2000, ${sql({ role: "assistant", time: { created: 2000 } })});`, | |
| `INSERT INTO part VALUES ('prt_2', 'msg_2', '${sid}', 2000, 2000, ${sql({ type: "reasoning", text: "thinking..." })});`, | |
| `INSERT INTO part VALUES ('prt_3', 'msg_2', '${sid}', 2000, 2000, ${sql({ type: "tool", tool: "bash", callID: "c1", state: { status: "completed", input: { description: "List files" }, output: "file1 file2" } })});`, | |
| `INSERT INTO part VALUES ('prt_4', 'msg_2', '${sid}', 2000, 2000, ${sql({ type: "text", text: "Two files found." })});`, | |
| `INSERT INTO part VALUES ('prt_5', 'msg_2', '${sid}', 2000, 2000, ${sql({ type: "text", text: "injected crew context", synthetic: true })});`, | |
| ]; | |
| const seeded = spawnSync("sqlite3", [join(dbDir, "opencode.db")], { | |
| input: rows.join("\n"), | |
| encoding: "utf8", | |
| }); | |
| assert.equal(seeded.status, 0, seeded.stderr); | |
| // The generated plugin identifies its sessions via env, not ancestry. | |
| const sleeper = spawn(process.execPath, ["-e", "setInterval(() => {}, 1e9)"], { | |
| stdio: "ignore", | |
| }); | |
| t.after(() => sleeper.kill()); | |
| const env = { ...h.env, CREW_AGENT: "opencode", CREW_PID: String(sleeper.pid) }; | |
| const prompt = stopHook(env, sid, "UserPromptSubmit"); | |
| assert.equal(prompt.status, 0, prompt.stderr); | |
| const listed = run(["--json", "10"], h.env); | |
| assert.equal(listed.status, 0, listed.stderr); | |
| const session = JSON.parse(listed.stdout.trim()); | |
| assert.equal(session.sessionId, sid); | |
| assert.equal(session.agent, "opencode"); | |
| assert.equal(session.status, "busy"); | |
| assert.deepEqual( | |
| session.tail.map((entry) => entry.kind), | |
| ["text", "tool_use", "tool_result", "text"], // reasoning + synthetic skipped | |
| ); | |
| assert.equal(session.tail[1].summary, "List files"); | |
| assert.equal(session.tail[3].text, "Two files found."); | |
| // Plain mail must not be drained at Stop: an idle OpenCode session would | |
| // never see it. It stays queued for the next turn. | |
| writeInbox(h.env, sid, baseMsg({ text: "plain hello" })); | |
| const plain = stopHook(env, sid); | |
| assert.equal(plain.status, 0, plain.stderr); | |
| assert.equal(plain.stdout.trim(), ""); | |
| assert.equal(pendingFiles(inboxDir(h.env, sid)).length, 1); | |
| // Kickstart mail wakes the session: Stop returns a forced continuation | |
| // carrying everything pending, and the inbox drains. | |
| writeInbox(h.env, sid, baseMsg({ text: "go fix the build", kickstart: true })); | |
| const kick = stopHook(env, sid); | |
| assert.equal(kick.status, 0, kick.stderr); | |
| const kickOut = JSON.parse(kick.stdout.trim()); | |
| assert.equal(kickOut.decision, "block"); | |
| assert.match(kickOut.reason, /plain hello/); | |
| assert.match(kickOut.reason, /go fix the build/); | |
| assert.equal(pendingFiles(inboxDir(h.env, sid)).length, 0); | |
| // SessionEnd (OpenCode reports deleted sessions) drops the registry record. | |
| const ended = stopHook(env, sid, "SessionEnd"); | |
| assert.equal(ended.status, 0, ended.stderr); | |
| assert.equal(ended.stdout.trim(), ""); | |
| assert.equal(run(["--json"], h.env).stdout.trim(), ""); | |
| }, | |
| ); | |
| test("send --kickstart flags the message and warns when the target is idle", async (t) => { | |
| const h = homes(); | |
| const sid = "claude-idle-target-session"; | |
| registerSession(h.env, sid, sleeper(t).pid); | |
| const sent = run( | |
| ["send", sid.slice(0, 8), "deploy is unblocked, go", "--kickstart"], | |
| h.env, | |
| ); | |
| assert.equal(sent.status, 0, sent.stderr); | |
| assert.match(sent.stdout, /kickstart queued/); | |
| assert.match(sent.stderr, /idle/); | |
| const dir = inboxDir(h.env, sid); | |
| const [file] = pendingFiles(dir); | |
| const msg = JSON.parse(readFileSync(join(dir, file), "utf8")); | |
| assert.equal(msg.kickstart, true); | |
| assert.equal(msg.text, "deploy is unblocked, go"); | |
| // Mail no longer lands under the crew home, which sandboxes may deny. | |
| assert.equal(existsSync(join(h.env.CREW_HOME, "inbox")), false); | |
| }); | |
| test( | |
| "cross-session send works when the crew home is read-only (sandboxed agent)", | |
| { skip: process.getuid() === 0 && "root ignores mode bits" }, | |
| async (t) => { | |
| const h = homes(); | |
| const target = "target-sandboxed-session"; | |
| const sender = "sender-sandboxed-session"; | |
| registerSession(h.env, target, sleeper(t).pid); | |
| registerSession(h.env, sender, sleeper(t).pid, { status: "busy" }); | |
| // The reported failure: an agent sandbox denies writes anywhere under | |
| // $HOME, so the old ~/.crew/inbox could not even be created. Reads and | |
| // the existing registry still work, which is why crew looked healthy. | |
| chmodSync(h.env.CREW_HOME, 0o500); | |
| t.after(() => chmodSync(h.env.CREW_HOME, 0o700)); | |
| assert.throws( | |
| () => mkdirSync(join(h.env.CREW_HOME, "inbox")), | |
| /EACCES|EPERM/, | |
| "the sandbox this test simulates must actually deny the legacy inbox", | |
| ); | |
| const sent = run(["send", target.slice(0, 8), "sandboxed hello"], { | |
| ...h.env, | |
| CREW_SESSION_ID: sender, // attribute the send to the sender session | |
| }); | |
| assert.equal(sent.status, 0, sent.stderr); | |
| assert.match(sent.stdout, /queued for/); | |
| assert.equal(pendingFiles(inboxDir(h.env, target)).length, 1); | |
| const delivered = stopHook(h.env, target); | |
| assert.equal(delivered.status, 0, delivered.stderr); | |
| const context = JSON.parse(delivered.stdout.trim()).hookSpecificOutput | |
| .additionalContext; | |
| assert.match(context, /sandboxed hello/); | |
| assert.match(context, new RegExp(sender.slice(0, 8))); | |
| assert.deepEqual(pendingFiles(inboxDir(h.env, target)), []); | |
| }, | |
| ); | |
| test("mail left in legacy inboxes is still delivered, and still expires", () => { | |
| const h = homes(); | |
| const sid = "claude-legacy-inbox-session"; | |
| const roots = { | |
| current: inboxDir(h.env, sid), | |
| "0.3": legacyInboxDir(h.env, sid, "0.3"), | |
| "0.2": legacyInboxDir(h.env, sid, "0.2"), | |
| }; | |
| dropMessage(roots.current, baseMsg({ text: "from the current mailbox" })); | |
| dropMessage(roots["0.3"], baseMsg({ text: "from the 0.3 crew home" })); | |
| dropMessage(roots["0.2"], baseMsg({ text: "from the 0.2 claude home" })); | |
| // Expiry has to reach legacy roots too, or stale mail sits there forever. | |
| dropMessage( | |
| roots["0.3"], | |
| baseMsg({ | |
| text: "stale legacy message", | |
| expiresAt: new Date(Date.now() - 60_000).toISOString(), | |
| }), | |
| ); | |
| const delivered = stopHook(h.env, sid); | |
| assert.equal(delivered.status, 0, delivered.stderr); | |
| const context = JSON.parse(delivered.stdout.trim()).hookSpecificOutput | |
| .additionalContext; | |
| assert.match(context, /from the current mailbox/); | |
| assert.match(context, /from the 0.3 crew home/); | |
| assert.match(context, /from the 0.2 claude home/); | |
| assert.doesNotMatch(context, /stale legacy message/); | |
| for (const [era, dir] of Object.entries(roots)) { | |
| assert.deepEqual(pendingFiles(dir), [], `${era} inbox should be drained`); | |
| } | |
| }); | |
| test("concurrent drains deliver each message exactly once", async () => { | |
| const h = homes(); | |
| const sid = "claude-concurrent-drain-session"; | |
| const count = 300; // enough mail that the drainers genuinely overlap | |
| for (let i = 0; i < count; i++) { | |
| dropMessage(inboxDir(h.env, sid), baseMsg({ text: `concurrent-${i}-marker` })); | |
| } | |
| // Spawning is not simultaneous: process startup jitter alone lets the first | |
| // drainer finish before the last one starts, and then nothing is contended | |
| // and the test proves nothing. A wall-clock deadline is no better, because a | |
| // loaded machine blows through it. So the drainers announce themselves and | |
| // then spin on a gate file the parent opens once every one of them is ready. | |
| const drainers = 6; | |
| const ready = join(h.root, "ready"); | |
| const gate = join(h.root, "gate"); | |
| mkdirSync(ready, { recursive: true }); | |
| const drainer = ` | |
| const { writeFileSync, existsSync } = require("node:fs"); | |
| const { drainInbox } = require(${JSON.stringify(join(root, "dist", "mailbox.js"))}); | |
| writeFileSync(${JSON.stringify(ready)} + "/" + process.pid, ""); | |
| while (!existsSync(${JSON.stringify(gate)})) {} // spin: all six leave together | |
| const claimed = drainInbox(${JSON.stringify(sid)}); | |
| process.stdout.write(JSON.stringify(claimed.map((m) => m.text))); | |
| `; | |
| const drains = Array.from( | |
| { length: drainers }, | |
| () => | |
| new Promise((done) => { | |
| const child = spawn(process.execPath, ["-e", drainer], { | |
| env: h.env, | |
| stdio: ["ignore", "pipe", "pipe"], | |
| }); | |
| let stdout = ""; | |
| let stderr = ""; | |
| child.stdout.on("data", (c) => (stdout += c)); | |
| child.stderr.on("data", (c) => (stderr += c)); | |
| child.on("close", (status) => done({ status, stdout, stderr })); | |
| }), | |
| ); | |
| const deadline = Date.now() + 30_000; | |
| while (readdirSync(ready).length < drainers) { | |
| assert.ok(Date.now() < deadline, "drainers never reached the gate"); | |
| await new Promise((tick) => setTimeout(tick, 20)); | |
| } | |
| writeFileSync(gate, ""); // open it: every drainer enters drainInbox at once | |
| const results = await Promise.all(drains); | |
| const seen = []; | |
| for (const drain of results) { | |
| assert.equal(drain.status, 0, drain.stderr); | |
| seen.push(...JSON.parse(drain.stdout)); | |
| } | |
| // Claiming renames before reading, so racing drainers split the inbox | |
| // between them: nothing delivered twice, and nothing dropped on the floor. | |
| assert.equal(new Set(seen).size, seen.length, "a message was delivered twice"); | |
| assert.equal(seen.length, count, `lost mail: only ${seen.length}/${count}`); | |
| assert.deepEqual(pendingFiles(inboxDir(h.env, sid)), []); | |
| // The race must have actually happened, or this proves nothing. | |
| const winners = results.filter((d) => JSON.parse(d.stdout).length > 0).length; | |
| assert.ok(winners > 1, `only ${winners} drainer claimed anything; not contended`); | |
| }); | |
| test( | |
| "the default mailbox is a 0700 per-uid directory under /tmp", | |
| { skip: process.platform === "win32" && "POSIX layout only" }, | |
| (t) => { | |
| // The real mailbox is shared with every other crew on this machine, | |
| // including a second copy of this suite: never use a fixed id in it. | |
| const sid = `crew-selftest-${process.pid}-${randomBytes(4).toString("hex")}`; | |
| const env = { ...process.env }; | |
| delete env.CREW_INBOX_ROOT; // exercise the real default resolution | |
| const probe = spawnSync( | |
| process.execPath, | |
| [ | |
| "-e", | |
| `const { sendMessage } = require(${JSON.stringify(join(root, "dist", "mailbox.js"))}); | |
| const { inboxLocation } = require(${JSON.stringify(join(root, "dist", "home.js"))}); | |
| sendMessage(${JSON.stringify(sid)}, ${JSON.stringify(baseMsg())}); | |
| process.stdout.write(JSON.stringify(inboxLocation()));`, | |
| ], | |
| { env, encoding: "utf8" }, | |
| ); | |
| assert.equal(probe.status, 0, probe.stderr); | |
| const location = JSON.parse(probe.stdout); | |
| t.after(() => rmSync(join(location.root, sid), { recursive: true, force: true })); | |
| assert.equal(location.base, `/tmp/crew-${process.getuid()}`); | |
| assert.equal(location.root, join(location.base, "inbox")); | |
| assert.equal(pendingFiles(join(location.root, sid)).length, 1); | |
| const st = lstatSync(location.base); | |
| assert.equal(st.isSymbolicLink(), false); | |
| assert.equal(st.uid, process.getuid()); | |
| assert.equal(st.mode & 0o777, 0o700, "the per-user mailbox must be private"); | |
| }, | |
| ); | |
| test("a mailbox root crew does not own is refused, and nothing is queued", async (t) => { | |
| const h = homes(); | |
| const sid = "claude-refused-root-session"; | |
| registerSession(h.env, sid, sleeper(t).pid); | |
| const elsewhere = join(h.root, "elsewhere"); | |
| mkdirSync(elsewhere, { recursive: true }); | |
| symlinkSync(elsewhere, join(h.root, "linked-inbox")); | |
| const sent = run(["send", sid.slice(0, 8), "should never be queued"], { | |
| ...h.env, | |
| CREW_INBOX_ROOT: join(h.root, "linked-inbox"), | |
| }); | |
| assert.equal(sent.status, 1); | |
| assert.match(sent.stderr, /symlink/); | |
| assert.match(sent.stderr, /NOT queued/); | |
| assert.doesNotMatch(sent.stdout, /queued for/); | |
| assert.deepEqual(pendingFiles(join(elsewhere, sid)), []); | |
| }); | |
| test("doctor reports unwired hooks, --json is structured, and --fix repairs them", () => { | |
| const h = homes(); | |
| const before = run(["doctor"], h.env); | |
| assert.equal(before.status, 1, before.stdout + before.stderr); | |
| assert.match(before.stdout, /✗ Claude Code hook\s+not wired/); | |
| assert.match(before.stdout, /✗ Codex hook\s+not wired/); | |
| assert.match(before.stdout, /✗ OpenCode hook\s+not wired/); | |
| assert.match(before.stdout, /→ crew install-hook/); | |
| assert.match(before.stdout, /3 failing/); | |
| // Nothing was written in report-only mode. | |
| assert.equal(existsSync(join(h.env.CLAUDE_HOME, "settings.json")), false); | |
| assert.equal(existsSync(h.env.CREW_INBOX_ROOT), false); | |
| const json = run(["doctor", "--json"], h.env); | |
| assert.equal(json.status, 1); | |
| const report = JSON.parse(json.stdout); | |
| assert.equal(report.schema, 1); | |
| assert.equal(report.ok, false); | |
| assert.equal(report.version, require("../package.json").version); | |
| const byId = Object.fromEntries(report.checks.map((c) => [c.id, c])); | |
| for (const agent of ["claude", "codex", "opencode"]) { | |
| assert.equal(byId[`hook:${agent}`].status, "fail"); | |
| assert.equal(byId[`hook:${agent}`].fix, "crew install-hook"); | |
| } | |
| assert.equal(byId.mailbox.status, "ok"); | |
| assert.equal(byId.registry.status, "ok"); | |
| assert.equal(byId["opencode:sqlite"].status, "ok"); // skipped: no plugin | |
| const fixed = run(["doctor", "--fix"], h.env); | |
| assert.equal(fixed.status, 0, fixed.stdout + fixed.stderr); | |
| assert.match(fixed.stdout, /✓ Claude Code hook .*\(fixed\)/); | |
| assert.match(fixed.stdout, /3 fixed/); | |
| assert.equal(existsSync(join(h.env.CLAUDE_HOME, "settings.json")), true); | |
| assert.equal(existsSync(join(h.env.CODEX_HOME, "hooks.json")), true); | |
| const plugin = join(h.env.XDG_CONFIG_HOME, "opencode", "plugins", "crew.js"); | |
| assert.match( | |
| readFileSync(plugin, "utf8"), | |
| new RegExp(`^// crew ${require("../package.json").version.replace(/\\./g, "\\\\.")} — generated by`, "m"), | |
| ); | |
| const after = run(["doctor", "--json"], h.env); | |
| assert.equal(after.status, 0); | |
| const again = Object.fromEntries(JSON.parse(after.stdout).checks.map((c) => [c.id, c])); | |
| for (const agent of ["claude", "codex", "opencode"]) { | |
| assert.equal(again[`hook:${agent}`].status, "ok"); | |
| } | |
| assert.equal(run(["doctor", "--bogus"], h.env).status, 2); | |
| }); | |
| test("doctor flags a stale OpenCode plugin, a foreign one, and unreadable settings", () => { | |
| const h = homes(); | |
| assert.equal(run(["install-hook"], h.env).status, 0); | |
| // An older crew stamped a different version (or none at all). | |
| const plugin = join(h.env.XDG_CONFIG_HOME, "opencode", "plugins", "crew.js"); | |
| const source = readFileSync(plugin, "utf8"); | |
| writeFileSync(plugin, source.replace(/^\/\/ crew \S+ — /, "// crew 0.3.0 — ")); | |
| let r = JSON.parse(run(["doctor", "--json"], h.env).stdout); | |
| let oc = r.checks.find((c) => c.id === "hook:opencode"); | |
| assert.equal(oc.status, "warn"); | |
| assert.match(oc.detail, /older crew/); | |
| // --fix re-renders it; a plugin crew didn't write is left alone. | |
| assert.equal(run(["doctor", "--fix"], h.env).status, 0); | |
| assert.equal(readFileSync(plugin, "utf8"), source); | |
| writeFileSync(plugin, "export const Mine = async () => ({})"); | |
| r = JSON.parse(run(["doctor", "--fix", "--json"], h.env).stdout); | |
| oc = r.checks.find((c) => c.id === "hook:opencode"); | |
| assert.equal(oc.status, "fail"); | |
| assert.match(oc.detail, /crew didn't generate it/); | |
| assert.equal(readFileSync(plugin, "utf8"), "export const Mine = async () => ({})"); | |
| // Broken JSON is reported, never overwritten, even under --fix. | |
| const settings = join(h.env.CLAUDE_HOME, "settings.json"); | |
| writeFileSync(settings, "{ not json"); | |
| r = JSON.parse(run(["doctor", "--fix", "--json"], h.env).stdout); | |
| const claude = r.checks.find((c) => c.id === "hook:claude"); | |
| assert.equal(claude.status, "fail"); | |
| assert.match(claude.detail, /isn't valid JSON/); | |
| assert.equal(readFileSync(settings, "utf8"), "{ not json"); | |
| }); | |
| test("doctor refuses a mailbox it doesn't own and counts stale registry entries", async (t) => { | |
| const h = homes(); | |
| // A symlink where the mailbox root should be: fail, and --fix must not follow it. | |
| const elsewhere = mkdtempSync(join(tmpdir(), "crew-elsewhere-")); | |
| symlinkSync(elsewhere, h.env.CREW_INBOX_ROOT); | |
| let r = JSON.parse(run(["doctor", "--fix", "--json"], h.env).stdout); | |
| const mailbox = r.checks.find((c) => c.id === "mailbox"); | |
| assert.equal(mailbox.status, "fail"); | |
| assert.match(mailbox.detail, /symlink/); | |
| assert.equal(lstatSync(h.env.CREW_INBOX_ROOT).isSymbolicLink(), true); | |
| rmSync(h.env.CREW_INBOX_ROOT); | |
| // Too-open perms are a warning that --fix tightens. | |
| mkdirSync(h.env.CREW_INBOX_ROOT, { recursive: true, mode: 0o755 }); | |
| r = JSON.parse(run(["doctor", "--json"], h.env).stdout); | |
| assert.equal(r.checks.find((c) => c.id === "mailbox").status, "warn"); | |
| r = JSON.parse(run(["doctor", "--fix", "--json"], h.env).stdout); | |
| assert.equal(r.checks.find((c) => c.id === "mailbox").status, "fixed"); | |
| assert.equal(lstatSync(h.env.CREW_INBOX_ROOT).mode & 0o077, 0); | |
| // One live session, one whose process is gone. | |
| const alive = sleeper(t); | |
| registerSession(h.env, "live-session", alive.pid); | |
| registerSession(h.env, "dead-session", 2 ** 22 - 1); | |
| r = JSON.parse(run(["doctor", "--json"], h.env).stdout); | |
| let registry = r.checks.find((c) => c.id === "registry"); | |
| assert.equal(registry.status, "warn"); | |
| assert.match(registry.detail, /1 live, 1 stale/); | |
| r = JSON.parse(run(["doctor", "--fix", "--json"], h.env).stdout); | |
| registry = r.checks.find((c) => c.id === "registry"); | |
| assert.equal(registry.status, "fixed"); | |
| assert.equal(existsSync(join(h.env.CREW_HOME, "sessions", "dead-session.json")), false); | |
| assert.equal(existsSync(join(h.env.CREW_HOME, "sessions", "live-session.json")), true); | |
| }); | |
Xet Storage Details
- Size:
- 29.2 kB
- Xet hash:
- e367d556f62478ad81e781274d70b8457fe52d9ada7d2ccd88b28de047b6b1b4
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.