10 Commits

Author SHA1 Message Date
Mika Kuns
f4539eb2c9 chore(release): 1.5.1
All checks were successful
Release / release (push) Successful in 8s
Release (Node) / release (push) Successful in 10s
2026-05-20 14:09:19 +02:00
Mika Kuns
4b93641cf4 fix(server): register onClose hook before app.listen
Fastify forbids addHook after the instance is listening, so the
sweep-timer cleanup hook from 1.5.0 threw on every `serve` startup
and crashed the daemon. Register the hook first, then start
listening, and assign the timer through a ref.
2026-05-20 14:09:11 +02:00
Mika Kuns
2cadc3a867 chore(release): 1.5.0
All checks were successful
CI (Node) / build-test (push) Successful in 8s
Release / release (push) Successful in 8s
Release (Node) / release (push) Successful in 12s
2026-05-20 13:54:43 +02:00
Mika Kuns
0c06e2cf4b feat(cleanup): hide and prune stale mailboxes
Mailbox listings grew unbounded as old sessions ended without
unregistering. This adds two layers of cleanup, configurable via
mailbox.json or `serve` flags:

- Lazy filter: list responses (REST /v1/list, MCP list_mailboxes)
  drop mailboxes idle longer than hideAfterMinutes (default 24h),
  while always keeping the caller and any sender with messages
  pending for them.
- Background sweep: startServer runs an initial prune on boot and
  schedules an unref'd interval timer that hard-deletes mailboxes
  idle longer than deleteAfterMinutes (default 7d) which have no
  pending messages, and wipes their delivered history.
2026-05-20 13:54:03 +02:00
Mika Kuns
06a2ea6b7b chore(release): 1.4.1
All checks were successful
Release / release (push) Successful in 7s
CI (Node) / build-test (push) Successful in 8s
Release (Node) / release (push) Successful in 11s
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 13:34:34 +02:00
Mika Kuns
01c22ff9a3 fix(cli): lazy-load server module so non-serve commands skip node:sqlite
All checks were successful
CI (Node) / build-test (push) Successful in 8s
Importing server.js statically also imports db.ts, which pulls in
node:sqlite at startup. On Linux that emits an ExperimentalWarning to
stderr for every CLI invocation -- visible to users running the hook on
every prompt. Defer the server import into the serve action so check
--hook / session-announce / send / peek / list never touch sqlite.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 13:30:04 +02:00
Mika Kuns
7b65545600 chore(release): 1.4.0
Some checks failed
CI (Node) / build-test (push) Failing after 7s
Release / release (push) Successful in 7s
Release (Node) / release (push) Failing after 8s
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 13:14:22 +02:00
Mika Kuns
b10ac36ed0 feat(naming)!: auto-derive mailbox name from project + runtime rename
Mailbox names are now built as <project>-<session-short>, where <project>
is the sanitized git-repo basename (or cwd basename) — no more env-var
prefix step. Sessions can re-tag themselves at runtime via the new
mcp__mailbox__rename tool (POST /v1/rename), which transfers all
pending messages to the new name in a single transaction. Peers using
the old name re-discover via list_mailboxes.

BREAKING: \$CLAUDE_MAILBOX_NAME is no longer read. Existing setups that
relied on the env-var prefix should remove it from .claude/settings.json;
the prefix now comes from the working directory automatically.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 13:14:15 +02:00
Mika Kuns
8832eab6c7 refactor(node): migrate from better-sqlite3 to node:sqlite, require Node 24+
Some checks failed
CI (Node) / build-test (push) Failing after 8s
Native binding caused install pain on every new Node major (no prebuilts +
node-gyp needs VS+Windows SDK to fall back). For this project's workload
(a few ops/day, no advanced SQLite features) better-sqlite3's perf edge is
irrelevant — node:sqlite's bundled, ABI-stable sync API is the better fit.

- db.ts: DatabaseSync, db.exec("PRAGMA …"), explicit BEGIN/COMMIT helper to
  replace db.transaction(); row casts go through unknown because node:sqlite
  returns Record<string, SQLOutputValue>.
- package.json: drop better-sqlite3 + @types/better-sqlite3, bump
  engines.node to >=24, vitest 2 → 4 (2.x couldn't resolve `node:sqlite`).
- mailbox-doctor: add Step 1 that enforces Node ≥24 with a concrete fix
  message, renumbers downstream steps.

Node 1.2.0 → 1.3.0. 35 transitive packages removed from the lockfile.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 16:07:21 +02:00
Mika Kuns
8747d638fb feat(plugin): add SubagentStop hook to auto-check inbox after subagent runs
Delivers peer messages that arrive during a long-running subagent into the
parent context the moment the Task tool returns, instead of waiting until
the next user prompt. Reuses the existing `claude-mailbox check --hook` so
the mailbox identity stays consistent with UserPromptSubmit.

Plugin 1.2.0 → 1.3.0.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 16:06:55 +02:00
20 changed files with 1594 additions and 1440 deletions

View File

@@ -104,15 +104,26 @@ claude-mailbox uninstall-service [--purge]
## How identity works ## How identity works
Every Claude Code session gets a unique mailbox name derived from its UUID: Every Claude Code session gets a unique mailbox name automatically derived as `<project>-<8-hex-of-session-id>`:
| Setup | Resulting mailbox name | | Setup | Resulting mailbox name |
|---|---| |---|---|
| Default | `claude-<8-hex-of-session-id>` | | Inside a git repo | `<repo-basename>-<8-hex>` (e.g. `claude-mailbox-a3f91b2c`) |
| `CLAUDE_MAILBOX_NAME=backend` (in `.claude/settings.json` env) | `backend-<8-hex>` | | Outside a git repo | `<cwd-basename>-<8-hex>` |
| No cwd available (rare) | `claude-<8-hex>` |
| Manual `.mcp.json` with `X-Mailbox: backend` header (no plugin) | `backend` (legacy mode) | | Manual `.mcp.json` with `X-Mailbox: backend` header (no plugin) | `backend` (legacy mode) |
The plugin's `SessionStart` hook prints the session's identity and the list of peers active in the last hour into the conversation context, so Claude knows who it is and who's around without needing to call any tools first. Project names are sanitized (lowercased, non-alphanumerics → dashes, capped at 40 chars). The plugin's `SessionStart` hook prints the session's identity and the list of peers active in the last hour into the conversation context, so Claude knows who it is and who's around without needing to call any tools first.
### Renaming at runtime
Claude can refine its own mailbox name during the session — useful when a session focuses on a specific area (e.g. only frontend work):
```
mcp__mailbox__rename(current_name="claude-mailbox-a3f91b2c", new_name="claude-mailbox-frontend-a3f91b2c")
```
Pending messages are transferred to the new name in a single transaction. The old name is removed — peers using it must re-discover via `list_mailboxes`. The endpoint returns `409` if the target name is already in use.
--- ---

View File

@@ -48,5 +48,5 @@ Cost: one local HTTP round-trip plus Node coldstart per prompt (~100ms on Window
npm config set //git.kuns.dev/api/packages/releases/npm/:_authToken=<token> npm config set //git.kuns.dev/api/packages/releases/npm/:_authToken=<token>
``` ```
`gyp ERR! find VS` on Windows during install `Cannot find module 'node:sqlite'` or similar
: `better-sqlite3` ships prebuilt binaries for current Node LTS versions. If yours isn't covered, npm falls back to building from source and needs the Visual Studio Build Tools. Either install them or pin to a Node version with a matching prebuild. : claude-mailbox uses Node's built-in `node:sqlite`, stable since Node 24. On Node 22.523.x it works only with `--experimental-sqlite`. Upgrade to Node 24 LTS or newer: `nvm install 24 && nvm use 24` (or `winget install OpenJS.NodeJS.LTS` on Windows).

2005
node/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{ {
"name": "@kuns/claude-mailbox", "name": "@kuns/claude-mailbox",
"version": "1.2.0", "version": "1.5.1",
"description": "Standalone MCP mail server that lets parallel Claude sessions coordinate with each other.", "description": "Standalone MCP mail server that lets parallel Claude sessions coordinate with each other.",
"type": "module", "type": "module",
"bin": { "bin": {
@@ -20,11 +20,10 @@
"prepack": "npm run build" "prepack": "npm run build"
}, },
"engines": { "engines": {
"node": ">=20" "node": ">=24"
}, },
"dependencies": { "dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0", "@modelcontextprotocol/sdk": "^1.29.0",
"better-sqlite3": "^11.3.0",
"commander": "^12.1.0", "commander": "^12.1.0",
"fastify": "^5.0.0", "fastify": "^5.0.0",
"zod": "^3.25.0" "zod": "^3.25.0"
@@ -33,10 +32,9 @@
"node-windows": "^1.0.0-beta.8" "node-windows": "^1.0.0-beta.8"
}, },
"devDependencies": { "devDependencies": {
"@types/better-sqlite3": "^7.6.11",
"@types/node": "^22.7.4", "@types/node": "^22.7.4",
"typescript": "^5.6.2", "typescript": "^5.6.2",
"vitest": "^2.1.1" "vitest": "^4.1.6"
}, },
"keywords": [ "keywords": [
"mcp", "mcp",

View File

@@ -4,7 +4,6 @@ import { existsSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path"; import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import { resolveConfig, baseUrl, DEFAULT_PORT } from "./config.js"; import { resolveConfig, baseUrl, DEFAULT_PORT } from "./config.js";
import { startServer } from "./server.js";
import { autostartManager } from "./autostart/index.js"; import { autostartManager } from "./autostart/index.js";
import { runStdioMcp } from "./mcp-stdio.js"; import { runStdioMcp } from "./mcp-stdio.js";
import { import {
@@ -79,9 +78,33 @@ program
.option("--bind <address>", "Bind address") .option("--bind <address>", "Bind address")
.option("--db-path <path>", "SQLite database path") .option("--db-path <path>", "SQLite database path")
.option("--config <path>", "Path to mailbox.json") .option("--config <path>", "Path to mailbox.json")
.action(async (opts: { port?: number; bind?: string; dbPath?: string; config?: string }) => { .option(
"--hide-after-minutes <n>",
"Hide mailboxes idle longer than N minutes from list responses (0 = disabled)",
(v) => parseInt(v, 10),
)
.option(
"--delete-after-minutes <n>",
"Hard-delete mailboxes idle longer than N minutes (0 = disabled)",
(v) => parseInt(v, 10),
)
.option(
"--sweep-interval-minutes <n>",
"Stale-mailbox sweep interval in minutes (0 = disabled)",
(v) => parseInt(v, 10),
)
.action(async (opts: {
port?: number;
bind?: string;
dbPath?: string;
config?: string;
hideAfterMinutes?: number;
deleteAfterMinutes?: number;
sweepIntervalMinutes?: number;
}) => {
const cfg = resolveConfig(opts); const cfg = resolveConfig(opts);
try { try {
const { startServer } = await import("./server.js");
const { app } = await startServer(cfg); const { app } = await startServer(cfg);
app.log.info(`ClaudeMailbox listening on ${baseUrl(cfg)} (db: ${cfg.dbPath})`); app.log.info(`ClaudeMailbox listening on ${baseUrl(cfg)} (db: ${cfg.dbPath})`);
} catch (err) { } catch (err) {
@@ -137,22 +160,19 @@ function resolveHookMailboxName(explicit: string | undefined): string | null {
if (explicit && explicit.trim()) return explicit.trim(); if (explicit && explicit.trim()) return explicit.trim();
const stdin = parseHookStdin(readStdinIfPiped()); const stdin = parseHookStdin(readStdinIfPiped());
const sid = stdin?.session_id?.trim(); const sid = stdin?.session_id?.trim();
if (sid) { if (!sid) return null;
const base = (process.env["CLAUDE_MAILBOX_NAME"] ?? "").trim() || null; const cwd = typeof stdin?.cwd === "string" ? stdin.cwd : process.cwd();
return deriveSessionName(sid, base); return deriveSessionName(sid, cwd);
}
const envName = (process.env["CLAUDE_MAILBOX_NAME"] ?? "").trim();
return envName || null;
} }
program program
.command("check") .command("check")
.description( .description(
"Pull pending messages and mark delivered. In --hook mode the name is auto-derived from the SessionStart/UserPromptSubmit stdin (session_id), optionally flavored by $CLAUDE_MAILBOX_NAME.", "Pull pending messages and mark delivered. In --hook mode the name is auto-derived from the SessionStart/UserPromptSubmit stdin: <project>-<session-short>, where <project> is the git-repo or cwd basename from stdin.",
) )
.option( .option(
"--name <name>", "--name <name>",
"Explicit mailbox name. Overrides hook stdin and $CLAUDE_MAILBOX_NAME.", "Explicit mailbox name. Overrides hook stdin auto-derivation.",
) )
.option("--url <url>", "Daemon base URL", DEFAULT_URL) .option("--url <url>", "Daemon base URL", DEFAULT_URL)
.option( .option(
@@ -162,10 +182,10 @@ program
.action(async (opts: { name?: string; url: string; hook?: boolean }) => { .action(async (opts: { name?: string; url: string; hook?: boolean }) => {
const name = opts.hook const name = opts.hook
? resolveHookMailboxName(opts.name) ? resolveHookMailboxName(opts.name)
: (opts.name ?? process.env["CLAUDE_MAILBOX_NAME"] ?? "").trim() || null; : (opts.name ?? "").trim() || null;
if (!name) { if (!name) {
if (opts.hook) return; if (opts.hook) return;
console.error("Missing --name (or set CLAUDE_MAILBOX_NAME)."); console.error("Missing --name.");
process.exit(1); process.exit(1);
} }
try { try {
@@ -217,12 +237,13 @@ program
const stdin = parseHookStdin(readStdinIfPiped()); const stdin = parseHookStdin(readStdinIfPiped());
const sid = stdin?.session_id?.trim(); const sid = stdin?.session_id?.trim();
if (!sid) return; if (!sid) return;
const base = (process.env["CLAUDE_MAILBOX_NAME"] ?? "").trim() || null; const cwd = typeof stdin?.cwd === "string" ? stdin.cwd : process.cwd();
const name = deriveSessionName(sid, base); const name = deriveSessionName(sid, cwd);
const lines = [ const lines = [
`Claude-Mailbox: your mailbox name this session is \`${name}\`.`, `Claude-Mailbox: your mailbox name this session is \`${name}\`.`,
`When using mcp__mailbox__* tools, ALWAYS pass this name explicitly:`, `The name is auto-derived as <project>-<session-short>. You can rename it (e.g. to tag your working area) with mcp__mailbox__rename(current_name="${name}", new_name="<project>-<area>-<short>"); after that, use the new name everywhere.`,
`When using mcp__mailbox__* tools, ALWAYS pass your current name explicitly:`,
` - mcp__mailbox__send: from="${name}"`, ` - mcp__mailbox__send: from="${name}"`,
` - mcp__mailbox__check_inbox: name="${name}"`, ` - mcp__mailbox__check_inbox: name="${name}"`,
` - mcp__mailbox__peek_inbox: name="${name}"`, ` - mcp__mailbox__peek_inbox: name="${name}"`,

View File

@@ -4,17 +4,26 @@ import { join, resolve } from "node:path";
export const DEFAULT_PORT = 37849; export const DEFAULT_PORT = 37849;
export const DEFAULT_BIND = "127.0.0.1"; export const DEFAULT_BIND = "127.0.0.1";
export const DEFAULT_HIDE_AFTER_MINUTES = 60 * 24;
export const DEFAULT_DELETE_AFTER_MINUTES = 60 * 24 * 7;
export const DEFAULT_SWEEP_INTERVAL_MINUTES = 60;
export interface FileConfig { export interface FileConfig {
port?: number; port?: number;
bind?: string; bind?: string;
dbPath?: string; dbPath?: string;
hideAfterMinutes?: number;
deleteAfterMinutes?: number;
sweepIntervalMinutes?: number;
} }
export interface DaemonConfig { export interface DaemonConfig {
port: number; port: number;
bind: string; bind: string;
dbPath: string; dbPath: string;
hideAfterMinutes: number;
deleteAfterMinutes: number;
sweepIntervalMinutes: number;
} }
export function defaultDbPath(): string { export function defaultDbPath(): string {
@@ -65,6 +74,12 @@ export function loadFileConfig(explicitPath?: string): FileConfig {
port: typeof parsed.port === "number" ? parsed.port : undefined, port: typeof parsed.port === "number" ? parsed.port : undefined,
bind: typeof parsed.bind === "string" ? parsed.bind : undefined, bind: typeof parsed.bind === "string" ? parsed.bind : undefined,
dbPath: typeof parsed.dbPath === "string" ? parsed.dbPath : undefined, dbPath: typeof parsed.dbPath === "string" ? parsed.dbPath : undefined,
hideAfterMinutes:
typeof parsed.hideAfterMinutes === "number" ? parsed.hideAfterMinutes : undefined,
deleteAfterMinutes:
typeof parsed.deleteAfterMinutes === "number" ? parsed.deleteAfterMinutes : undefined,
sweepIntervalMinutes:
typeof parsed.sweepIntervalMinutes === "number" ? parsed.sweepIntervalMinutes : undefined,
}; };
} }
} }
@@ -76,6 +91,9 @@ export interface ServeOverrides {
bind?: string; bind?: string;
dbPath?: string; dbPath?: string;
config?: string; config?: string;
hideAfterMinutes?: number;
deleteAfterMinutes?: number;
sweepIntervalMinutes?: number;
} }
export function resolveConfig(overrides: ServeOverrides): DaemonConfig { export function resolveConfig(overrides: ServeOverrides): DaemonConfig {
@@ -83,7 +101,20 @@ export function resolveConfig(overrides: ServeOverrides): DaemonConfig {
const port = overrides.port ?? file.port ?? DEFAULT_PORT; const port = overrides.port ?? file.port ?? DEFAULT_PORT;
const bind = overrides.bind ?? file.bind ?? DEFAULT_BIND; const bind = overrides.bind ?? file.bind ?? DEFAULT_BIND;
const dbPathRaw = overrides.dbPath ?? file.dbPath ?? defaultDbPath(); const dbPathRaw = overrides.dbPath ?? file.dbPath ?? defaultDbPath();
return { port, bind, dbPath: expandPath(dbPathRaw) }; const hideAfterMinutes =
overrides.hideAfterMinutes ?? file.hideAfterMinutes ?? DEFAULT_HIDE_AFTER_MINUTES;
const deleteAfterMinutes =
overrides.deleteAfterMinutes ?? file.deleteAfterMinutes ?? DEFAULT_DELETE_AFTER_MINUTES;
const sweepIntervalMinutes =
overrides.sweepIntervalMinutes ?? file.sweepIntervalMinutes ?? DEFAULT_SWEEP_INTERVAL_MINUTES;
return {
port,
bind,
dbPath: expandPath(dbPathRaw),
hideAfterMinutes,
deleteAfterMinutes,
sweepIntervalMinutes,
};
} }
export function baseUrl(cfg: { port: number; bind: string }): string { export function baseUrl(cfg: { port: number; bind: string }): string {

View File

@@ -1,4 +1,4 @@
import Database from "better-sqlite3"; import { DatabaseSync, type StatementSync } from "node:sqlite";
import { mkdirSync } from "node:fs"; import { mkdirSync } from "node:fs";
import { dirname } from "node:path"; import { dirname } from "node:path";
@@ -50,6 +50,15 @@ function nowIso(): string {
return new Date().toISOString(); return new Date().toISOString();
} }
export type RenameFailure = "invalid" | "source-missing" | "target-exists";
export class RenameError extends Error {
constructor(message: string, public readonly reason: RenameFailure) {
super(message);
this.name = "RenameError";
}
}
function parseDate(s: string | null | undefined): Date | null { function parseDate(s: string | null | undefined): Date | null {
if (!s) return null; if (!s) return null;
const normalized = s.includes("T") ? s : s.replace(" ", "T") + (s.endsWith("Z") ? "" : "Z"); const normalized = s.includes("T") ? s : s.replace(" ", "T") + (s.endsWith("Z") ? "" : "Z");
@@ -57,28 +66,49 @@ function parseDate(s: string | null | undefined): Date | null {
return isNaN(d.getTime()) ? null : d; return isNaN(d.getTime()) ? null : d;
} }
function runInTransaction<T>(db: DatabaseSync, fn: () => T): T {
db.exec("BEGIN");
try {
const result = fn();
db.exec("COMMIT");
return result;
} catch (err) {
try {
db.exec("ROLLBACK");
} catch {
// ignore: original error already on its way up
}
throw err;
}
}
export class MailboxStore { export class MailboxStore {
private readonly db: Database.Database; private readonly db: DatabaseSync;
private readonly stmts: { private readonly stmts: {
findMailbox: Database.Statement; findMailbox: StatementSync;
insertMailbox: Database.Statement; insertMailbox: StatementSync;
touchMailbox: Database.Statement; touchMailbox: StatementSync;
listMailboxes: Database.Statement; listMailboxes: StatementSync;
insertMessage: Database.Statement; listMailboxesFiltered: StatementSync;
countPending: Database.Statement; listMailboxesFilteredAnon: StatementSync;
oldestPending: Database.Statement; insertMessage: StatementSync;
selectPending: Database.Statement; countPending: StatementSync;
markDelivered: Database.Statement; oldestPending: StatementSync;
pendingByRecipient: Database.Statement; selectPending: StatementSync;
markDelivered: StatementSync;
pendingByRecipient: StatementSync;
findStaleCandidates: StatementSync;
deleteMessagesForNames: StatementSync;
deleteMailboxesByNames: StatementSync;
}; };
constructor(public readonly dbPath: string) { constructor(public readonly dbPath: string) {
mkdirSync(dirname(dbPath), { recursive: true }); mkdirSync(dirname(dbPath), { recursive: true });
this.db = new Database(dbPath); this.db = new DatabaseSync(dbPath);
this.db.pragma("journal_mode = WAL"); this.db.exec("PRAGMA journal_mode = WAL");
this.db.pragma("foreign_keys = ON"); this.db.exec("PRAGMA foreign_keys = ON");
for (const sql of DDL_STATEMENTS) this.db.prepare(sql).run(); for (const sql of DDL_STATEMENTS) this.db.exec(sql);
this.stmts = { this.stmts = {
findMailbox: this.db.prepare("SELECT * FROM mailboxes WHERE name = ?"), findMailbox: this.db.prepare("SELECT * FROM mailboxes WHERE name = ?"),
@@ -87,6 +117,19 @@ export class MailboxStore {
), ),
touchMailbox: this.db.prepare("UPDATE mailboxes SET last_seen_at = ? WHERE name = ?"), touchMailbox: this.db.prepare("UPDATE mailboxes SET last_seen_at = ? WHERE name = ?"),
listMailboxes: this.db.prepare("SELECT * FROM mailboxes ORDER BY name"), listMailboxes: this.db.prepare("SELECT * FROM mailboxes ORDER BY name"),
listMailboxesFiltered: this.db.prepare(
`SELECT * FROM mailboxes
WHERE last_seen_at >= ?
OR name = ?
OR name IN (
SELECT DISTINCT from_mailbox FROM messages
WHERE to_mailbox = ? AND delivered_at IS NULL
)
ORDER BY name`,
),
listMailboxesFilteredAnon: this.db.prepare(
"SELECT * FROM mailboxes WHERE last_seen_at >= ? ORDER BY name",
),
insertMessage: this.db.prepare( insertMessage: this.db.prepare(
"INSERT INTO messages (to_mailbox, from_mailbox, body, created_at, delivered_at) VALUES (?, ?, ?, ?, NULL)", "INSERT INTO messages (to_mailbox, from_mailbox, body, created_at, delivered_at) VALUES (?, ?, ?, ?, NULL)",
), ),
@@ -105,6 +148,20 @@ export class MailboxStore {
pendingByRecipient: this.db.prepare( pendingByRecipient: this.db.prepare(
"SELECT to_mailbox, COUNT(*) AS n FROM messages WHERE delivered_at IS NULL GROUP BY to_mailbox", "SELECT to_mailbox, COUNT(*) AS n FROM messages WHERE delivered_at IS NULL GROUP BY to_mailbox",
), ),
findStaleCandidates: this.db.prepare(
`SELECT name FROM mailboxes
WHERE last_seen_at < ?
AND name NOT IN (SELECT to_mailbox FROM messages WHERE delivered_at IS NULL)
AND name NOT IN (SELECT from_mailbox FROM messages WHERE delivered_at IS NULL)`,
),
deleteMessagesForNames: this.db.prepare(
`DELETE FROM messages
WHERE to_mailbox IN (SELECT value FROM json_each(?))
OR from_mailbox IN (SELECT value FROM json_each(?))`,
),
deleteMailboxesByNames: this.db.prepare(
"DELETE FROM mailboxes WHERE name IN (SELECT value FROM json_each(?))",
),
}; };
} }
@@ -114,7 +171,7 @@ export class MailboxStore {
upsertMailbox(name: string): void { upsertMailbox(name: string): void {
const now = nowIso(); const now = nowIso();
const existing = this.stmts.findMailbox.get(name) as MailboxRow | undefined; const existing = this.stmts.findMailbox.get(name) as unknown as MailboxRow | undefined;
if (existing) { if (existing) {
this.stmts.touchMailbox.run(now, name); this.stmts.touchMailbox.run(now, name);
} else { } else {
@@ -123,14 +180,13 @@ export class MailboxStore {
} }
send(from: string, to: string, body: string): { id: number; queuedAt: Date } { send(from: string, to: string, body: string): { id: number; queuedAt: Date } {
const tx = this.db.transaction(() => { return runInTransaction(this.db, () => {
this.upsertMailbox(from); this.upsertMailbox(from);
this.upsertMailbox(to); this.upsertMailbox(to);
const createdAt = nowIso(); const createdAt = nowIso();
const result = this.stmts.insertMessage.run(to, from, body, createdAt); const result = this.stmts.insertMessage.run(to, from, body, createdAt);
return { id: Number(result.lastInsertRowid), queuedAt: new Date(createdAt) }; return { id: Number(result.lastInsertRowid), queuedAt: new Date(createdAt) };
}); });
return tx();
} }
peek(name: string): InboxStatus { peek(name: string): InboxStatus {
@@ -141,19 +197,62 @@ export class MailboxStore {
} }
checkInbox(name: string): MessageRow[] { checkInbox(name: string): MessageRow[] {
const tx = this.db.transaction(() => { return runInTransaction(this.db, () => {
const pending = this.stmts.selectPending.all(name) as MessageRow[]; const pending = this.stmts.selectPending.all(name) as unknown as MessageRow[];
if (pending.length > 0) { if (pending.length > 0) {
const ids = pending.map((m) => m.id); const ids = pending.map((m) => m.id);
this.stmts.markDelivered.run(nowIso(), JSON.stringify(ids)); this.stmts.markDelivered.run(nowIso(), JSON.stringify(ids));
} }
return pending; return pending;
}); });
return tx();
} }
listMailboxes(forName?: string): MailboxInfo[] { rename(from: string, to: string): { from: string; to: string; messagesTransferred: number } {
const rows = this.stmts.listMailboxes.all() as MailboxRow[]; const oldName = from.trim();
const newName = to.trim();
if (!oldName) throw new RenameError("from is required", "invalid");
if (!newName) throw new RenameError("to is required", "invalid");
if (oldName === newName) {
this.upsertMailbox(oldName);
return { from: oldName, to: newName, messagesTransferred: 0 };
}
return runInTransaction(this.db, () => {
const source = this.stmts.findMailbox.get(oldName) as unknown as MailboxRow | undefined;
if (!source) throw new RenameError(`Mailbox '${oldName}' does not exist.`, "source-missing");
const target = this.stmts.findMailbox.get(newName) as unknown as MailboxRow | undefined;
if (target) throw new RenameError(`Mailbox '${newName}' already exists.`, "target-exists");
const now = nowIso();
this.stmts.insertMailbox.run(newName, source.created_at, now);
const movedTo = this.db
.prepare("UPDATE messages SET to_mailbox = ? WHERE to_mailbox = ?")
.run(newName, oldName);
this.db
.prepare("UPDATE messages SET from_mailbox = ? WHERE from_mailbox = ?")
.run(newName, oldName);
this.db.prepare("DELETE FROM mailboxes WHERE name = ?").run(oldName);
return { from: oldName, to: newName, messagesTransferred: Number(movedTo.changes ?? 0) };
});
}
listMailboxes(forName?: string, options?: { hideAfterMinutes?: number }): MailboxInfo[] {
const hideAfterMinutes = options?.hideAfterMinutes;
let rows: MailboxRow[];
if (hideAfterMinutes != null && hideAfterMinutes > 0) {
const cutoff = new Date(Date.now() - hideAfterMinutes * 60_000).toISOString();
if (forName) {
rows = this.stmts.listMailboxesFiltered.all(
cutoff,
forName,
forName,
) as unknown as MailboxRow[];
} else {
rows = this.stmts.listMailboxesFilteredAnon.all(cutoff) as unknown as MailboxRow[];
}
} else {
rows = this.stmts.listMailboxes.all() as unknown as MailboxRow[];
}
const pendingMap = new Map<string, number>(); const pendingMap = new Map<string, number>();
if (forName) { if (forName) {
const counts = this.stmts.pendingByRecipient.all() as { to_mailbox: string; n: number }[]; const counts = this.stmts.pendingByRecipient.all() as { to_mailbox: string; n: number }[];
@@ -165,6 +264,22 @@ export class MailboxStore {
pendingForYou: forName ? (pendingMap.get(forName) ?? 0) : 0, pendingForYou: forName ? (pendingMap.get(forName) ?? 0) : 0,
})); }));
} }
pruneStale(deleteAfterMinutes: number): { deletedMailboxes: number; deletedMessages: number } {
if (deleteAfterMinutes <= 0) return { deletedMailboxes: 0, deletedMessages: 0 };
const cutoff = new Date(Date.now() - deleteAfterMinutes * 60_000).toISOString();
return runInTransaction(this.db, () => {
const candidates = this.stmts.findStaleCandidates.all(cutoff) as { name: string }[];
if (candidates.length === 0) return { deletedMailboxes: 0, deletedMessages: 0 };
const namesJson = JSON.stringify(candidates.map((c) => c.name));
const msgResult = this.stmts.deleteMessagesForNames.run(namesJson, namesJson);
const mbxResult = this.stmts.deleteMailboxesByNames.run(namesJson);
return {
deletedMailboxes: Number(mbxResult.changes ?? 0),
deletedMessages: Number(msgResult.changes ?? 0),
};
});
}
} }
export function rowToMessage(r: MessageRow): { export function rowToMessage(r: MessageRow): {

View File

@@ -1,6 +1,7 @@
import { spawnSync } from "node:child_process";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os"; import { homedir } from "node:os";
import { dirname, join } from "node:path"; import { basename, dirname, join } from "node:path";
export interface HookStdinPayload { export interface HookStdinPayload {
session_id?: string; session_id?: string;
@@ -34,11 +35,51 @@ export function shortSessionId(sessionId: string): string {
return sessionId.toLowerCase().replace(/[^a-z0-9]/g, "").slice(0, 8) || "00000000"; return sessionId.toLowerCase().replace(/[^a-z0-9]/g, "").slice(0, 8) || "00000000";
} }
export function deriveSessionName(sessionId: string, base?: string | null): string { const MAX_PROJECT_NAME_LENGTH = 40;
export function sanitizeProjectName(raw: string | null | undefined): string {
if (!raw) return "";
const cleaned = raw
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/-+/g, "-")
.replace(/^-|-$/g, "");
return cleaned.slice(0, MAX_PROJECT_NAME_LENGTH).replace(/-+$/g, "");
}
export function deriveProjectName(cwd?: string | null): string {
const dir = (cwd ?? "").trim();
if (dir) {
const gitTop = gitToplevel(dir);
if (gitTop) {
const sanitized = sanitizeProjectName(basename(gitTop));
if (sanitized) return sanitized;
}
const sanitized = sanitizeProjectName(basename(dir));
if (sanitized) return sanitized;
}
return "claude";
}
function gitToplevel(cwd: string): string | null {
try {
const r = spawnSync("git", ["rev-parse", "--show-toplevel"], {
cwd,
encoding: "utf8",
timeout: 1500,
});
if (r.status !== 0) return null;
const out = (r.stdout ?? "").trim();
return out || null;
} catch {
return null;
}
}
export function deriveSessionName(sessionId: string, cwd?: string | null): string {
const short = shortSessionId(sessionId); const short = shortSessionId(sessionId);
const trimmed = (base ?? "").trim(); const project = deriveProjectName(cwd);
if (trimmed) return `${trimmed}-${short}`; return `${project}-${short}`;
return `claude-${short}`;
} }
export interface PeerEntry { export interface PeerEntry {

View File

@@ -155,6 +155,36 @@ export function buildStdioMcpServer(daemonUrl: string = resolveDaemonUrl()): Mcp
}, },
); );
server.registerTool(
"rename",
{
title: "Rename your mailbox",
description:
"Rename your own mailbox (e.g. to add a working-area tag like `myproject-frontend-a3f9`). Pending messages are transferred to the new name. After this returns, USE THE NEW NAME for all subsequent send/check/peek/list calls. Peers using the old name will fail until they re-discover via list_mailboxes.",
inputSchema: {
current_name: z
.string()
.describe(
"Your current mailbox name (from the SessionStart announcement or last rename).",
),
new_name: z
.string()
.describe("The new mailbox name. Must be unique. Convention: <project>-<area>-<short>."),
},
},
async ({ current_name, new_name }) => {
const from = requireIdentity(current_name, "name");
const out = (await rest("POST", `${daemonUrl}/v1/rename`, {
headers: { "X-Mailbox": from },
body: { to: new_name },
})) as { from: string; to: string; messagesTransferred: number };
return {
content: [{ type: "text", text: JSON.stringify(out) }],
structuredContent: out,
};
},
);
return server; return server;
} }

View File

@@ -2,7 +2,7 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { z } from "zod"; import { z } from "zod";
import type { FastifyInstance } from "fastify"; import type { FastifyInstance } from "fastify";
import { MailboxStore, rowToMessage } from "./db.js"; import { MailboxStore, RenameError, rowToMessage } from "./db.js";
import { HEADER_NAME } from "./server.js"; import { HEADER_NAME } from "./server.js";
function headerFallback(extra: unknown): string { function headerFallback(extra: unknown): string {
@@ -27,7 +27,7 @@ export function resolveIdentity(
); );
} }
function buildMcpServer(store: MailboxStore): McpServer { function buildMcpServer(store: MailboxStore, hideAfterMinutes: number): McpServer {
const server = new McpServer({ name: "claude-mailbox", version: "1.0.0" }); const server = new McpServer({ name: "claude-mailbox", version: "1.0.0" });
server.registerTool( server.registerTool(
@@ -129,7 +129,7 @@ function buildMcpServer(store: MailboxStore): McpServer {
}, },
async ({ name }, extra) => { async ({ name }, extra) => {
const me = resolveIdentity(name, extra, "name"); const me = resolveIdentity(name, extra, "name");
const list = store.listMailboxes(me).map((m) => ({ const list = store.listMailboxes(me, { hideAfterMinutes }).map((m) => ({
name: m.name, name: m.name,
lastSeenAt: m.lastSeenAt.toISOString(), lastSeenAt: m.lastSeenAt.toISOString(),
pendingForYou: m.pendingForYou, pendingForYou: m.pendingForYou,
@@ -141,11 +141,51 @@ function buildMcpServer(store: MailboxStore): McpServer {
}, },
); );
server.registerTool(
"rename",
{
title: "Rename your mailbox",
description:
"Rename your own mailbox (e.g. to add a working-area tag like `myproject-frontend-a3f9`). Pending messages are transferred to the new name. After this returns, USE THE NEW NAME for all subsequent send/check/peek/list calls. Peers using the old name will fail until they re-discover via list_mailboxes.",
inputSchema: {
current_name: z
.string()
.optional()
.describe(
"Your current mailbox name (the one to rename away from). Required unless X-Mailbox is set in .mcp.json.",
),
new_name: z
.string()
.describe("The new mailbox name. Must be unique. Convention: <project>-<area>-<short>."),
},
},
async ({ current_name, new_name }, extra) => {
const from = resolveIdentity(current_name, extra, "name");
try {
const r = store.rename(from, new_name);
const out = { from: r.from, to: r.to, messagesTransferred: r.messagesTransferred };
return {
content: [{ type: "text", text: JSON.stringify(out) }],
structuredContent: out,
};
} catch (err) {
if (err instanceof RenameError) {
throw new Error(`${err.message} (${err.reason})`);
}
throw err;
}
},
);
return server; return server;
} }
export async function registerMcp(app: FastifyInstance, store: MailboxStore): Promise<void> { export async function registerMcp(
const mcpServer = buildMcpServer(store); app: FastifyInstance,
store: MailboxStore,
hideAfterMinutes: number,
): Promise<void> {
const mcpServer = buildMcpServer(store, hideAfterMinutes);
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined }); const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
await mcpServer.connect(transport); await mcpServer.connect(transport);

View File

@@ -2,7 +2,7 @@ import Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest }
import { readFileSync } from "node:fs"; import { readFileSync } from "node:fs";
import { join, dirname } from "node:path"; import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import { MailboxStore, rowToMessage } from "./db.js"; import { MailboxStore, RenameError, rowToMessage } from "./db.js";
import type { DaemonConfig } from "./config.js"; import type { DaemonConfig } from "./config.js";
import { registerMcp } from "./mcp.js"; import { registerMcp } from "./mcp.js";
@@ -93,21 +93,74 @@ export async function buildServer(cfg: DaemonConfig, store: MailboxStore): Promi
app.get("/v1/list", async (req) => { app.get("/v1/list", async (req) => {
const name = req.mailboxName; const name = req.mailboxName;
return store.listMailboxes(name).map((m) => ({ return store
.listMailboxes(name, { hideAfterMinutes: cfg.hideAfterMinutes })
.map((m) => ({
name: m.name, name: m.name,
lastSeenAt: m.lastSeenAt.toISOString(), lastSeenAt: m.lastSeenAt.toISOString(),
pendingForYou: m.pendingForYou, pendingForYou: m.pendingForYou,
})); }));
}); });
await registerMcp(app, store); app.post<{ Body: { to?: string } }>("/v1/rename", async (req, reply) => {
const from = req.mailboxName!;
const to = (req.body?.to ?? "").trim();
if (!to) {
reply.code(400);
return { error: "to is required" };
}
try {
const r = store.rename(from, to);
return { from: r.from, to: r.to, messagesTransferred: r.messagesTransferred };
} catch (err) {
if (err instanceof RenameError) {
reply.code(err.reason === "target-exists" ? 409 : 400);
return { error: err.message, reason: err.reason };
}
throw err;
}
});
await registerMcp(app, store, cfg.hideAfterMinutes);
return app; return app;
} }
export async function startServer(cfg: DaemonConfig): Promise<{ app: FastifyInstance; store: MailboxStore }> { function startSweep(
store: MailboxStore,
cfg: DaemonConfig,
log: FastifyInstance["log"],
): NodeJS.Timeout | null {
if (cfg.sweepIntervalMinutes <= 0 || cfg.deleteAfterMinutes <= 0) return null;
const runOnce = (): void => {
try {
const r = store.pruneStale(cfg.deleteAfterMinutes);
if (r.deletedMailboxes > 0 || r.deletedMessages > 0) {
log.info(
r,
`Pruned ${r.deletedMailboxes} stale mailbox(es) and ${r.deletedMessages} delivered message(s)`,
);
}
} catch (err) {
log.error({ err }, "Stale-mailbox sweep failed");
}
};
runOnce();
const timer = setInterval(runOnce, cfg.sweepIntervalMinutes * 60_000);
timer.unref?.();
return timer;
}
export async function startServer(
cfg: DaemonConfig,
): Promise<{ app: FastifyInstance; store: MailboxStore; sweepTimer: NodeJS.Timeout | null }> {
const store = new MailboxStore(cfg.dbPath); const store = new MailboxStore(cfg.dbPath);
const app = await buildServer(cfg, store); const app = await buildServer(cfg, store);
const timerRef: { current: NodeJS.Timeout | null } = { current: null };
app.addHook("onClose", async () => {
if (timerRef.current) clearInterval(timerRef.current);
});
await app.listen({ host: cfg.bind, port: cfg.port }); await app.listen({ host: cfg.bind, port: cfg.port });
return { app, store }; timerRef.current = startSweep(store, cfg, app.log);
return { app, store, sweepTimer: timerRef.current };
} }

View File

@@ -35,8 +35,8 @@ describe("`check --hook` CLI behavior", () => {
} }
}); });
it("exits 0 silently when no stdin, no --name, no env", () => { it("exits 0 silently when no stdin and no --name", () => {
const r = runCli(["check", "--hook"], { env: { CLAUDE_MAILBOX_NAME: undefined } }); const r = runCli(["check", "--hook"]);
expect(r.status).toBe(0); expect(r.status).toBe(0);
expect(r.stdout).toBe(""); expect(r.stdout).toBe("");
expect(r.stderr).toBe(""); expect(r.stderr).toBe("");
@@ -44,18 +44,6 @@ describe("`check --hook` CLI behavior", () => {
it("derives session-id-based name from stdin and emits daemon hint when down", () => { it("derives session-id-based name from stdin and emits daemon hint when down", () => {
const r = runCli(["check", "--hook", "--url", "http://127.0.0.1:1"], { const r = runCli(["check", "--hook", "--url", "http://127.0.0.1:1"], {
env: { CLAUDE_MAILBOX_NAME: undefined },
stdin: HOOK_STDIN,
});
expect(r.status).toBe(0);
expect(r.stdout).toContain("[Claude-Mailbox] Daemon not reachable");
});
it("uses base prefix from CLAUDE_MAILBOX_NAME when both env and stdin present", () => {
// We can't directly assert the name from --hook output (it's only in the unreachable hint URL).
// The hint always contains the URL we passed, so this just confirms the path runs without error.
const r = runCli(["check", "--hook", "--url", "http://127.0.0.1:1"], {
env: { CLAUDE_MAILBOX_NAME: "backend" },
stdin: HOOK_STDIN, stdin: HOOK_STDIN,
}); });
expect(r.status).toBe(0); expect(r.status).toBe(0);
@@ -65,7 +53,7 @@ describe("`check --hook` CLI behavior", () => {
it("explicit --name overrides session-id derivation", () => { it("explicit --name overrides session-id derivation", () => {
const r = runCli( const r = runCli(
["check", "--hook", "--name", "explicit", "--url", "http://127.0.0.1:1"], ["check", "--hook", "--name", "explicit", "--url", "http://127.0.0.1:1"],
{ env: { CLAUDE_MAILBOX_NAME: "ignored" }, stdin: HOOK_STDIN }, { stdin: HOOK_STDIN },
); );
expect(r.status).toBe(0); expect(r.status).toBe(0);
expect(r.stdout).toContain("[Claude-Mailbox] Daemon not reachable"); expect(r.stdout).toContain("[Claude-Mailbox] Daemon not reachable");
@@ -73,7 +61,7 @@ describe("`check --hook` CLI behavior", () => {
it("uses CLAUDE_MAILBOX_URL env as default base URL when --url is not given", () => { it("uses CLAUDE_MAILBOX_URL env as default base URL when --url is not given", () => {
const r = runCli(["check", "--hook"], { const r = runCli(["check", "--hook"], {
env: { CLAUDE_MAILBOX_NAME: undefined, CLAUDE_MAILBOX_URL: "http://127.0.0.1:1" }, env: { CLAUDE_MAILBOX_URL: "http://127.0.0.1:1" },
stdin: HOOK_STDIN, stdin: HOOK_STDIN,
}); });
expect(r.status).toBe(0); expect(r.status).toBe(0);
@@ -81,9 +69,9 @@ describe("`check --hook` CLI behavior", () => {
}); });
it("non-hook mode errors out when no name resolved", () => { it("non-hook mode errors out when no name resolved", () => {
const r = runCli(["check"], { env: { CLAUDE_MAILBOX_NAME: undefined } }); const r = runCli(["check"]);
expect(r.status).not.toBe(0); expect(r.status).not.toBe(0);
expect(r.stderr).toContain("CLAUDE_MAILBOX_NAME"); expect(r.stderr).toContain("Missing --name");
}); });
}); });
@@ -96,38 +84,33 @@ describe("`session-announce` CLI behavior", () => {
} }
}); });
it("prints the derived mailbox name from a SessionStart payload", () => { it("prints the derived mailbox name from a SessionStart payload (project-prefixed)", () => {
// cwd "/tmp" is not a git repo → basename "tmp" → project prefix "tmp".
const r = runCli(["session-announce", "--url", UNREACHABLE], { const r = runCli(["session-announce", "--url", UNREACHABLE], {
env: { CLAUDE_MAILBOX_NAME: undefined },
stdin: HOOK_STDIN, stdin: HOOK_STDIN,
}); });
expect(r.status).toBe(0); expect(r.status).toBe(0);
expect(r.stdout).toContain("`claude-abc12345`"); // The exact prefix depends on the runtime cwd if git resolves; the deterministic
// assertion is the session-short suffix and the announcement structure.
expect(r.stdout).toMatch(/`[a-z0-9-]+-abc12345`/);
expect(r.stdout).toContain("mcp__mailbox__send"); expect(r.stdout).toContain("mcp__mailbox__send");
expect(r.stdout).toContain(`from="claude-abc12345"`); expect(r.stdout).toMatch(/from="[a-z0-9-]+-abc12345"/);
}); });
it("uses base prefix when set", () => { it("includes a hint about the rename tool", () => {
const r = runCli(["session-announce", "--url", UNREACHABLE], { const r = runCli(["session-announce", "--url", UNREACHABLE], { stdin: HOOK_STDIN });
env: { CLAUDE_MAILBOX_NAME: "backend" },
stdin: HOOK_STDIN,
});
expect(r.status).toBe(0); expect(r.status).toBe(0);
expect(r.stdout).toContain("`backend-abc12345`"); expect(r.stdout).toContain("mcp__mailbox__rename");
}); });
it("emits daemon-not-reachable hint when daemon is down", () => { it("emits daemon-not-reachable hint when daemon is down", () => {
const r = runCli(["session-announce", "--url", UNREACHABLE], { const r = runCli(["session-announce", "--url", UNREACHABLE], { stdin: HOOK_STDIN });
env: { CLAUDE_MAILBOX_NAME: undefined },
stdin: HOOK_STDIN,
});
expect(r.status).toBe(0); expect(r.status).toBe(0);
expect(r.stdout).toContain("[Claude-Mailbox] Daemon not reachable"); expect(r.stdout).toContain("[Claude-Mailbox] Daemon not reachable");
}); });
it("stays silent when no session_id in stdin", () => { it("stays silent when no session_id in stdin", () => {
const r = runCli(["session-announce", "--url", UNREACHABLE], { const r = runCli(["session-announce", "--url", UNREACHABLE], {
env: { CLAUDE_MAILBOX_NAME: undefined },
stdin: JSON.stringify({ hook_event_name: "SessionStart" }), stdin: JSON.stringify({ hook_event_name: "SessionStart" }),
}); });
expect(r.status).toBe(0); expect(r.status).toBe(0);
@@ -135,9 +118,7 @@ describe("`session-announce` CLI behavior", () => {
}); });
it("stays silent when no stdin at all", () => { it("stays silent when no stdin at all", () => {
const r = runCli(["session-announce", "--url", UNREACHABLE], { const r = runCli(["session-announce", "--url", UNREACHABLE]);
env: { CLAUDE_MAILBOX_NAME: undefined },
});
expect(r.status).toBe(0); expect(r.status).toBe(0);
expect(r.stdout).toBe(""); expect(r.stdout).toBe("");
}); });

View File

@@ -2,7 +2,15 @@ import { describe, it, expect, afterEach, beforeEach } from "vitest";
import { mkdtempSync, rmSync } from "node:fs"; import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os"; import { tmpdir } from "node:os";
import { join } from "node:path"; import { join } from "node:path";
import { MailboxStore } from "../src/db.js"; import { DatabaseSync } from "node:sqlite";
import { MailboxStore, RenameError } from "../src/db.js";
function backdate(dbPath: string, name: string, minutesAgo: number): void {
const db = new DatabaseSync(dbPath);
const iso = new Date(Date.now() - minutesAgo * 60_000).toISOString();
db.prepare("UPDATE mailboxes SET last_seen_at = ? WHERE name = ?").run(iso, name);
db.close();
}
let dir: string; let dir: string;
let dbPath: string; let dbPath: string;
@@ -75,6 +83,93 @@ describe("send / peek / check round-trip", () => {
}); });
}); });
describe("rename", () => {
it("renames a mailbox and transfers undelivered messages", () => {
const store = new MailboxStore(dbPath);
try {
store.send("alice", "bob-old", "hi");
store.send("alice", "bob-old", "again");
const r = store.rename("bob-old", "bob-new");
expect(r.from).toBe("bob-old");
expect(r.to).toBe("bob-new");
expect(r.messagesTransferred).toBe(2);
// Old name is gone.
const list = store.listMailboxes().map((m) => m.name);
expect(list).toContain("bob-new");
expect(list).not.toContain("bob-old");
// Messages still pending under the new name.
const peek = store.peek("bob-new");
expect(peek.pending).toBe(2);
// checkInbox under the new name yields the original bodies and the original from.
const pulled = store.checkInbox("bob-new");
expect(pulled.map((m) => m.body)).toEqual(["hi", "again"]);
} finally {
store.close();
}
});
it("also rewrites the from-side when the renamed mailbox was a sender", () => {
const store = new MailboxStore(dbPath);
try {
store.send("sender-old", "bob", "msg-1");
store.rename("sender-old", "sender-new");
const pulled = store.checkInbox("bob");
expect(pulled).toHaveLength(1);
expect(pulled[0]!.from_mailbox).toBe("sender-new");
} finally {
store.close();
}
});
it("treats rename-to-same-name as a no-op touch", () => {
const store = new MailboxStore(dbPath);
try {
store.upsertMailbox("alice");
const r = store.rename("alice", "alice");
expect(r.messagesTransferred).toBe(0);
expect(store.listMailboxes().map((m) => m.name)).toEqual(["alice"]);
} finally {
store.close();
}
});
it("rejects when target already exists", () => {
const store = new MailboxStore(dbPath);
try {
store.upsertMailbox("alice");
store.upsertMailbox("bob");
expect(() => store.rename("alice", "bob")).toThrow(RenameError);
try {
store.rename("alice", "bob");
} catch (e) {
expect((e as RenameError).reason).toBe("target-exists");
}
// Source still present after the failed attempt.
expect(store.listMailboxes().map((m) => m.name)).toEqual(["alice", "bob"]);
} finally {
store.close();
}
});
it("rejects when source is missing", () => {
const store = new MailboxStore(dbPath);
try {
try {
store.rename("nope", "fresh");
} catch (e) {
expect(e).toBeInstanceOf(RenameError);
expect((e as RenameError).reason).toBe("source-missing");
}
} finally {
store.close();
}
});
});
describe("listMailboxes", () => { describe("listMailboxes", () => {
it("returns mailboxes alphabetically with pendingForYou for the caller", () => { it("returns mailboxes alphabetically with pendingForYou for the caller", () => {
const store = new MailboxStore(dbPath); const store = new MailboxStore(dbPath);
@@ -91,4 +186,127 @@ describe("listMailboxes", () => {
store.close(); store.close();
} }
}); });
it("hides mailboxes older than hideAfterMinutes when filter is active", () => {
const store = new MailboxStore(dbPath);
try {
store.upsertMailbox("recent");
store.upsertMailbox("stale");
store.close();
backdate(dbPath, "stale", 90);
const store2 = new MailboxStore(dbPath);
try {
const filtered = store2.listMailboxes(undefined, { hideAfterMinutes: 60 });
expect(filtered.map((m) => m.name)).toEqual(["recent"]);
const unfiltered = store2.listMailboxes();
expect(unfiltered.map((m) => m.name).sort()).toEqual(["recent", "stale"]);
} finally {
store2.close();
}
} catch (e) {
store.close();
throw e;
}
});
it("always includes the caller and senders with pending messages, even if stale", () => {
const store = new MailboxStore(dbPath);
try {
store.send("stale-sender", "me", "you have mail");
store.upsertMailbox("recent-other");
store.upsertMailbox("stale-other");
store.close();
backdate(dbPath, "stale-sender", 120);
backdate(dbPath, "stale-other", 120);
backdate(dbPath, "me", 120);
const store2 = new MailboxStore(dbPath);
try {
const filtered = store2.listMailboxes("me", { hideAfterMinutes: 60 });
const names = filtered.map((m) => m.name).sort();
expect(names).toContain("me");
expect(names).toContain("stale-sender");
expect(names).toContain("recent-other");
expect(names).not.toContain("stale-other");
} finally {
store2.close();
}
} catch (e) {
store.close();
throw e;
}
});
});
describe("pruneStale", () => {
it("deletes idle mailboxes with no pending messages and wipes their delivered history", () => {
const store = new MailboxStore(dbPath);
try {
store.send("alice", "bob", "old");
store.checkInbox("bob");
store.upsertMailbox("fresh");
store.close();
backdate(dbPath, "alice", 60 * 24 * 8);
backdate(dbPath, "bob", 60 * 24 * 8);
const store2 = new MailboxStore(dbPath);
try {
const r = store2.pruneStale(60 * 24 * 7);
expect(r.deletedMailboxes).toBe(2);
expect(r.deletedMessages).toBe(1);
const remaining = store2.listMailboxes().map((m) => m.name);
expect(remaining).toEqual(["fresh"]);
} finally {
store2.close();
}
} catch (e) {
store.close();
throw e;
}
});
it("never deletes a mailbox that still has pending messages, even if idle", () => {
const store = new MailboxStore(dbPath);
try {
store.send("alice", "bob", "still pending");
store.close();
backdate(dbPath, "alice", 60 * 24 * 30);
backdate(dbPath, "bob", 60 * 24 * 30);
const store2 = new MailboxStore(dbPath);
try {
const r = store2.pruneStale(60 * 24 * 7);
expect(r.deletedMailboxes).toBe(0);
expect(r.deletedMessages).toBe(0);
expect(store2.peek("bob").pending).toBe(1);
} finally {
store2.close();
}
} catch (e) {
store.close();
throw e;
}
});
it("returns zero when deleteAfterMinutes is 0 (disabled)", () => {
const store = new MailboxStore(dbPath);
try {
store.upsertMailbox("x");
store.close();
backdate(dbPath, "x", 60 * 24 * 365);
const store2 = new MailboxStore(dbPath);
try {
const r = store2.pruneStale(0);
expect(r).toEqual({ deletedMailboxes: 0, deletedMessages: 0 });
expect(store2.listMailboxes().map((m) => m.name)).toEqual(["x"]);
} finally {
store2.close();
}
} catch (e) {
store.close();
throw e;
}
});
}); });

View File

@@ -2,15 +2,18 @@ import { describe, it, expect } from "vitest";
import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs"; import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
import { tmpdir } from "node:os"; import { tmpdir } from "node:os";
import { join } from "node:path"; import { join } from "node:path";
import { execFileSync } from "node:child_process";
import { import {
applyInstall, applyInstall,
applyUninstall, applyUninstall,
buildHookCommand, buildHookCommand,
deriveProjectName,
deriveSessionName, deriveSessionName,
formatActivePeerList, formatActivePeerList,
formatMessagesForHook, formatMessagesForHook,
parseHookStdin, parseHookStdin,
readSettings, readSettings,
sanitizeProjectName,
shortSessionId, shortSessionId,
writeSettings, writeSettings,
type PeerEntry, type PeerEntry,
@@ -205,7 +208,7 @@ describe("parseHookStdin", () => {
}); });
}); });
describe("shortSessionId / deriveSessionName", () => { describe("shortSessionId", () => {
it("takes first 8 hex chars from a UUID", () => { it("takes first 8 hex chars from a UUID", () => {
expect(shortSessionId("abc12345-de67-89f0-1234-567890abcdef")).toBe("abc12345"); expect(shortSessionId("abc12345-de67-89f0-1234-567890abcdef")).toBe("abc12345");
}); });
@@ -217,26 +220,73 @@ describe("shortSessionId / deriveSessionName", () => {
it("falls back to a sanitized prefix for non-hex ids", () => { it("falls back to a sanitized prefix for non-hex ids", () => {
expect(shortSessionId("session-Test123")).toBe("sessiont"); expect(shortSessionId("session-Test123")).toBe("sessiont");
}); });
it("derives anonymous name when no base", () => {
expect(deriveSessionName("abc12345-de67-89f0-1234-567890abcdef")).toBe("claude-abc12345");
}); });
it("prepends base prefix when given", () => { describe("sanitizeProjectName", () => {
expect(deriveSessionName("abc12345-de67-89f0-1234-567890abcdef", "backend")).toBe( it("lowercases and replaces non-alnum with dashes", () => {
"backend-abc12345", expect(sanitizeProjectName("My Project!")).toBe("my-project");
);
}); });
it("treats whitespace-only base as no base", () => { it("collapses runs of separators", () => {
expect(deriveSessionName("abc12345-de67-89f0-1234-567890abcdef", " ")).toBe( expect(sanitizeProjectName("foo __ bar")).toBe("foo-bar");
"claude-abc12345",
);
}); });
it("derives different names for different sessions with the same base", () => { it("trims leading/trailing dashes", () => {
const a = deriveSessionName("aaaa1111-de67-89f0-1234-567890abcdef", "shared"); expect(sanitizeProjectName("--foo--")).toBe("foo");
const b = deriveSessionName("bbbb2222-de67-89f0-1234-567890abcdef", "shared"); });
it("returns empty for purely non-alnum input", () => {
expect(sanitizeProjectName("---")).toBe("");
expect(sanitizeProjectName("")).toBe("");
expect(sanitizeProjectName(null)).toBe("");
expect(sanitizeProjectName(undefined)).toBe("");
});
it("caps long names", () => {
const out = sanitizeProjectName("a".repeat(120));
expect(out.length).toBeLessThanOrEqual(40);
});
});
describe("deriveProjectName", () => {
it("uses cwd basename when not in a git repo", () => {
// tmpdir is virtually never inside a git repo; basename is platform-dependent.
const got = deriveProjectName(tmpdir());
expect(got).toMatch(/^[a-z0-9-]+$/);
});
it("falls back to 'claude' when cwd is empty", () => {
expect(deriveProjectName("")).toBe("claude");
expect(deriveProjectName(null)).toBe("claude");
expect(deriveProjectName(undefined)).toBe("claude");
});
it("uses git toplevel basename when called from inside a repo", () => {
// The test harness itself runs inside the claude-mailbox checkout.
let inRepo = false;
try {
execFileSync("git", ["rev-parse", "--show-toplevel"], { encoding: "utf8", stdio: "pipe" });
inRepo = true;
} catch {
inRepo = false;
}
if (!inRepo) return; // CI without git in PATH — skip.
const got = deriveProjectName(process.cwd());
// Anywhere in the repo, we should resolve to the repo's basename — sanitized.
expect(got).toMatch(/^[a-z0-9-]+$/);
expect(got.length).toBeGreaterThan(0);
});
});
describe("deriveSessionName", () => {
it("composes <project>-<short>", () => {
const got = deriveSessionName("abc12345-de67-89f0-1234-567890abcdef", "");
expect(got).toBe("claude-abc12345");
});
it("derives different names for different sessions in the same project", () => {
const a = deriveSessionName("aaaa1111-de67-89f0-1234-567890abcdef", "");
const b = deriveSessionName("bbbb2222-de67-89f0-1234-567890abcdef", "");
expect(a).not.toBe(b); expect(a).not.toBe(b);
}); });
}); });

View File

@@ -2,6 +2,7 @@ import { describe, it, expect, afterEach, beforeEach } from "vitest";
import { mkdtempSync, rmSync } from "node:fs"; import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os"; import { tmpdir } from "node:os";
import { join } from "node:path"; import { join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { MailboxStore } from "../src/db.js"; import { MailboxStore } from "../src/db.js";
import { buildServer } from "../src/server.js"; import { buildServer } from "../src/server.js";
import type { FastifyInstance } from "fastify"; import type { FastifyInstance } from "fastify";
@@ -16,7 +17,17 @@ beforeEach(async () => {
dir = mkdtempSync(join(tmpdir(), "claude-mailbox-srv-")); dir = mkdtempSync(join(tmpdir(), "claude-mailbox-srv-"));
dbPath = join(dir, "test.db"); dbPath = join(dir, "test.db");
store = new MailboxStore(dbPath); store = new MailboxStore(dbPath);
app = await buildServer({ port: 0, bind: "127.0.0.1", dbPath }, store); app = await buildServer(
{
port: 0,
bind: "127.0.0.1",
dbPath,
hideAfterMinutes: 0,
deleteAfterMinutes: 0,
sweepIntervalMinutes: 0,
},
store,
);
await app.listen({ host: "127.0.0.1", port: 0 }); await app.listen({ host: "127.0.0.1", port: 0 });
const addr = app.server.address(); const addr = app.server.address();
if (!addr || typeof addr === "string") throw new Error("no address"); if (!addr || typeof addr === "string") throw new Error("no address");
@@ -94,6 +105,99 @@ describe("REST surface", () => {
expect(wrong.status).toBe(403); expect(wrong.status).toBe(403);
}); });
it("POST /v1/rename transfers pending messages and exposes the new name", async () => {
// alice sends to bob-old.
await call("POST", "/v1/send", {
headers: { "X-Mailbox": "alice" },
body: { to: "bob-old", body: "hi old bob" },
});
const rename = await call("POST", "/v1/rename", {
headers: { "X-Mailbox": "bob-old" },
body: { to: "bob-new" },
});
expect(rename.status).toBe(200);
expect(rename.body).toMatchObject({
from: "bob-old",
to: "bob-new",
messagesTransferred: 1,
});
// Peek under new name shows the pending msg; old name is empty.
const peekNew = await call("GET", "/v1/peek?name=bob-new");
expect(peekNew.body).toMatchObject({ pending: 1 });
const peekOld = await call("GET", "/v1/peek?name=bob-old");
expect(peekOld.body).toMatchObject({ pending: 0 });
// check-inbox under new name pulls the message.
const check = await call("POST", "/v1/check-inbox?name=bob-new", {
headers: { "X-Mailbox": "bob-new" },
});
const arr = check.body as Array<{ from: string; body: string }>;
expect(arr).toHaveLength(1);
expect(arr[0]!.body).toBe("hi old bob");
});
it("POST /v1/rename returns 409 when target name is taken", async () => {
await call("POST", "/v1/send", {
headers: { "X-Mailbox": "alice" },
body: { to: "bob", body: "x" },
});
// 'taken' already exists thanks to upsert on X-Mailbox.
const r = await call("POST", "/v1/rename", {
headers: { "X-Mailbox": "bob" },
body: { to: "alice" },
});
expect(r.status).toBe(409);
expect(r.body).toMatchObject({ reason: "target-exists" });
});
it("POST /v1/rename requires X-Mailbox and body.to", async () => {
const missingHeader = await call("POST", "/v1/rename", { body: { to: "x" } });
expect(missingHeader.status).toBe(400);
const missingTo = await call("POST", "/v1/rename", {
headers: { "X-Mailbox": "alice" },
body: {},
});
expect(missingTo.status).toBe(400);
});
it("/v1/list filters out mailboxes idle beyond hideAfterMinutes", async () => {
await app.close();
store.close();
store = new MailboxStore(dbPath);
store.upsertMailbox("recent");
store.upsertMailbox("stale");
store.close();
const handle = new DatabaseSync(dbPath);
const past = new Date(Date.now() - 120 * 60_000).toISOString();
handle.prepare("UPDATE mailboxes SET last_seen_at = ? WHERE name = ?").run(past, "stale");
handle.close();
store = new MailboxStore(dbPath);
app = await buildServer(
{
port: 0,
bind: "127.0.0.1",
dbPath,
hideAfterMinutes: 60,
deleteAfterMinutes: 0,
sweepIntervalMinutes: 0,
},
store,
);
await app.listen({ host: "127.0.0.1", port: 0 });
const addr = app.server.address();
if (!addr || typeof addr === "string") throw new Error("no address");
baseUrl = `http://127.0.0.1:${addr.port}`;
const r = await call("GET", "/v1/list");
expect(r.status).toBe(200);
const names = (r.body as Array<{ name: string }>).map((m) => m.name);
expect(names).toContain("recent");
expect(names).not.toContain("stale");
});
it("/v1/list and /v1/peek are anonymous", async () => { it("/v1/list and /v1/peek are anonymous", async () => {
await call("POST", "/v1/send", { await call("POST", "/v1/send", {
headers: { "X-Mailbox": "alice" }, headers: { "X-Mailbox": "alice" },

View File

@@ -1,7 +1,7 @@
{ {
"name": "claude-mailbox", "name": "claude-mailbox",
"version": "1.2.0", "version": "1.5.1",
"description": "Auto-checks the local Claude-Mailbox daemon before every prompt and injects pending messages into the conversation context.", "description": "Auto-checks the local Claude-Mailbox daemon before every prompt and after each subagent run, and injects pending messages into the conversation context.",
"author": { "author": {
"name": "Mika Kuns" "name": "Mika Kuns"
}, },

View File

@@ -15,21 +15,23 @@ The doctor walks the rest:
1. installs the `claude-mailbox` binary via `npm install -g @kuns/claude-mailbox` if missing (asks first) 1. installs the `claude-mailbox` binary via `npm install -g @kuns/claude-mailbox` if missing (asks first)
2. registers the daemon for autostart and starts it if needed 2. registers the daemon for autostart and starts it if needed
3. health-probes `http://127.0.0.1:37849/health` 3. health-probes `http://127.0.0.1:37849/health`
4. optionally lets you set a **base prefix** (e.g., `backend`) — without one, mailbox names are anonymous (`claude-XXXXXXXX`) 4. runs a self → self smoke test
5. runs a self → self smoke test
Restart Claude Code only if step 4 wrote a new prefix. After that, every prompt auto-pulls unread messages. After that, every prompt auto-pulls unread messages.
## Mailbox identity (the important bit) ## Mailbox identity (the important bit)
Each Claude Code session gets its own mailbox name, derived from the session's UUID: Each Claude Code session gets its own mailbox name, automatically derived as `<project>-<session-short>`:
| Configuration | Resulting mailbox name | | Where the session runs | Resulting mailbox name |
|---|---| |---|---|
| No `CLAUDE_MAILBOX_NAME` set | `claude-a8b3c1d2` (first 8 hex chars of session_id) | | Inside a git repo | `<repo-basename>-a8b3c1d2` (e.g. `claude-mailbox-a8b3c1d2`) |
| `CLAUDE_MAILBOX_NAME=backend` in `.claude/settings.json` env | `backend-a8b3c1d2` | | Outside a git repo | `<cwd-basename>-a8b3c1d2` |
| No cwd in stdin (rare) | `claude-a8b3c1d2` |
So if you open two Claude Code sessions in the same project, they'll be e.g. `backend-a8b3c1d2` and `backend-d4e5f6a7` — distinct, addressable, no manual setup. So if you open two Claude Code sessions in the same project, they'll share the project prefix but differ in the session-short — e.g. `claude-mailbox-a8b3c1d2` and `claude-mailbox-d4e5f6a7`. No env-var, no manual prefix step.
If a session focuses on a sub-area (frontend, backend, …), Claude can call `mcp__mailbox__rename(current_name="…", new_name="claude-mailbox-frontend-a8b3c1d2")` to tag itself; pending messages are transferred. Peers using the old name re-discover via `list_mailboxes`.
The `SessionStart` hook announces the current session's mailbox name in the conversation context on startup. Peers discover each other via `claude-mailbox list` or the `mcp__mailbox__list_mailboxes` MCP tool. The `SessionStart` hook announces the current session's mailbox name in the conversation context on startup. Peers discover each other via `claude-mailbox list` or the `mcp__mailbox__list_mailboxes` MCP tool.
@@ -39,8 +41,9 @@ The `SessionStart` hook announces the current session's mailbox name in the conv
|---|---|---| |---|---|---|
| `SessionStart` | `claude-mailbox session-announce` | Registers the session with the daemon, then prints (a) this session's mailbox name, (b) the exact `from` / `name` args to pass to MCP tools, and (c) a list of other mailboxes active in the last hour — so Claude knows who's around without needing to call `list_mailboxes` first. | | `SessionStart` | `claude-mailbox session-announce` | Registers the session with the daemon, then prints (a) this session's mailbox name, (b) the exact `from` / `name` args to pass to MCP tools, and (c) a list of other mailboxes active in the last hour — so Claude knows who's around without needing to call `list_mailboxes` first. |
| `UserPromptSubmit` | `claude-mailbox check --hook` | Pulls unread messages for the session's mailbox and injects them as context. Silent on empty inbox; emits a one-line setup hint when the daemon is unreachable. | | `UserPromptSubmit` | `claude-mailbox check --hook` | Pulls unread messages for the session's mailbox and injects them as context. Silent on empty inbox; emits a one-line setup hint when the daemon is unreachable. |
| `SubagentStop` | `claude-mailbox check --hook` | Same as `UserPromptSubmit`, but fires when a subagent finishes (Task tool). Lets the parent see peer messages that arrived during a long-running subagent run, instead of waiting until the next user prompt. |
Cost: one local HTTP round-trip per prompt + Node coldstart (~100ms on Windows). Cost: one local HTTP round-trip per prompt and per subagent stop + Node coldstart (~100ms on Windows).
## MCP tools ## MCP tools
@@ -54,6 +57,7 @@ Each MCP tool takes the caller's mailbox name as an explicit argument (from the
| `mcp__mailbox__check_inbox` | `name` | Pull all undelivered messages for your mailbox (marks delivered). | | `mcp__mailbox__check_inbox` | `name` | Pull all undelivered messages for your mailbox (marks delivered). |
| `mcp__mailbox__peek_inbox` | `name` | Non-consuming count of pending messages. | | `mcp__mailbox__peek_inbox` | `name` | Non-consuming count of pending messages. |
| `mcp__mailbox__list_mailboxes` | `name` | Discover known mailboxes and `pendingForYou` counts. | | `mcp__mailbox__list_mailboxes` | `name` | Discover known mailboxes and `pendingForYou` counts. |
| `mcp__mailbox__rename` | `current_name`, `new_name` | Rename your own mailbox (e.g. add an area tag). Pending messages are transferred. Use the new name afterward. |
The SessionStart announcement spells out the exact args to pass, so Claude picks them up automatically. The SessionStart announcement spells out the exact args to pass, so Claude picks them up automatically.

View File

@@ -1,13 +1,27 @@
--- ---
description: Diagnose and auto-fix the Claude-Mailbox setup (binary install, port-conflict detection, daemon autostart, smoke test, optional base-prefix). description: Diagnose and auto-fix the Claude-Mailbox setup (Node version, binary install, port-conflict detection, daemon autostart, smoke test, optional base-prefix).
allowed-tools: Bash, Read, Edit, Write allowed-tools: Bash, Read, Edit, Write
--- ---
You are running the **Claude-Mailbox doctor**. Walk through these checks in order. After each step, print a one-line `✓` / `✗` with the action you took. End with a summary block. You are running the **Claude-Mailbox doctor**. Walk through these checks in order. After each step, print a one-line `✓` / `✗` with the action you took. End with a summary block.
Use `Bash` only for `claude-mailbox` subcommands, `npm`, `where`/`which`, and HTTP probes. Use `Read`/`Edit`/`Write` for `.claude/settings.json` and `mailbox.json`. Never run `sudo` automatically — if elevation is needed, stop and ask. Use `Bash` only for `claude-mailbox` subcommands, `npm`, `node`, `where`/`which`, and HTTP probes. Use `Read`/`Edit`/`Write` for `.claude/settings.json` and `mailbox.json`. Never run `sudo` automatically — if elevation is needed, stop and ask.
## Step 1 — daemon binary on PATH ## Step 1 — Node.js version
Run: `node --version`
claude-mailbox uses Node's built-in `node:sqlite` and therefore requires **Node 24 or newer**. Parse the major version from the output.
- **Major ≥ 24** → ✓ record the version, continue.
- **Major == 22 or 23** → ✗ Stop. `node:sqlite` is experimental on these and requires `--experimental-sqlite`. Print:
> Found Node `<X.Y.Z>`. claude-mailbox needs Node 24 LTS or newer. Install via `nvm install 24 && nvm use 24` (or `nvs` / `winget install OpenJS.NodeJS.LTS` on Windows), then re-run the doctor.
- **Major < 22** → ✗ Stop with the same message; this Node is end-of-life.
- **Major ≥ 26** with `better-sqlite3` still installed globally from a previous version → just note: "Node `<X.Y.Z>` is fine for the current claude-mailbox (no native deps); ignore any old `better-sqlite3` build warnings from a prior install."
If `node --version` itself fails (`command not found`), stop and tell the user to install Node 24+ first.
## Step 2 — daemon binary on PATH
Run: `claude-mailbox --version` Run: `claude-mailbox --version`
@@ -27,7 +41,7 @@ Run: `claude-mailbox --version`
After install, re-run `claude-mailbox --version`. If it still fails, stop and report. After install, re-run `claude-mailbox --version`. If it still fails, stop and report.
## Step 2 — port-conflict check (before autostart!) ## Step 3 — port-conflict check (before autostart!)
Default port is 37849. Probe whether anything is already on it: Default port is 37849. Probe whether anything is already on it:
@@ -35,10 +49,10 @@ Default port is 37849. Probe whether anything is already on it:
curl -sf http://127.0.0.1:37849/health curl -sf http://127.0.0.1:37849/health
``` ```
- **Returns a JSON body with `"status":"ok"` and a `version` field that matches `claude-mailbox --version`** → it's already our daemon, ✓ skip to Step 4. - **Returns a JSON body with `"status":"ok"` and a `version` field that matches `claude-mailbox --version`** → it's already our daemon, ✓ skip to Step 5.
- **Returns 200 with `"status":"ok"` but a different `version`** → it's an older claude-mailbox; treat as running, ✓. - **Returns 200 with `"status":"ok"` but a different `version`** → it's an older claude-mailbox; treat as running, ✓.
- **Returns non-200, non-JSON, or any other foreign response** → **port conflict**. Some other process owns 37849. - **Returns non-200, non-JSON, or any other foreign response** → **port conflict**. Some other process owns 37849.
- **Connection refused** → port is free, ✓ continue to Step 3. - **Connection refused** → port is free, ✓ continue to Step 4.
If port conflict detected: If port conflict detected:
1. Tell the user which process holds the port (Windows: `Get-NetTCPConnection -LocalPort 37849 | Select-Object OwningProcess`, then `Get-Process -Id <pid>`; macOS/Linux: `lsof -i :37849`). 1. Tell the user which process holds the port (Windows: `Get-NetTCPConnection -LocalPort 37849 | Select-Object OwningProcess`, then `Get-Process -Id <pid>`; macOS/Linux: `lsof -i :37849`).
@@ -51,7 +65,7 @@ If port conflict detected:
Merge into existing env, preserving other keys. Merge into existing env, preserving other keys.
5. Mark `restart_needed = true`. 5. Mark `restart_needed = true`.
## Step 3 — daemon autostart and running state ## Step 4 — daemon autostart and running state
Run: `claude-mailbox status` Run: `claude-mailbox status`
@@ -63,24 +77,19 @@ Run: `claude-mailbox status`
If `install-autostart` still fails after both attempts (very rare — would mean both `schtasks` and `reg add` are blocked), stop and report what `status` and `start` printed. If `install-autostart` still fails after both attempts (very rare — would mean both `schtasks` and `reg add` are blocked), stop and report what `status` and `start` printed.
## Step 4 — health probe ## Step 5 — health probe
Hit `http://127.0.0.1:<port>/health` (use the configured port, not necessarily 37849). Expect a JSON body with `"status":"ok"` AND a `version` matching `claude-mailbox --version`. If unreachable or version mismatch, stop and report. Hit `http://127.0.0.1:<port>/health` (use the configured port, not necessarily 37849). Expect a JSON body with `"status":"ok"` AND a `version` matching `claude-mailbox --version`. If unreachable or version mismatch, stop and report.
## Step 5 — mailbox identity (base prefix) ## Step 6 — mailbox identity
**No prompt by default.** Each Claude Code session gets a unique mailbox name auto-derived from its `session_id` (e.g., `claude-a8b3c1d2`). **No prompt.** Each Claude Code session gets a unique mailbox name auto-derived as `<project>-<short_session_id>`, where `<project>` is the git-repo basename of the session's `cwd` (or the cwd basename if not a git repo). Example: `claude-mailbox-a8b3c1d2`.
Read `.claude/settings.json` and look for `env.CLAUDE_MAILBOX_NAME`. ✓ "Mailbox name will be auto-derived as `<project>-<short_session_id>`."
- If set → ✓ "Mailbox prefix is `<X>`." (real name will be `<X>-<short_session_id>`). Sessions can also rename themselves at runtime via the `mcp__mailbox__rename` MCP tool — e.g. to add an area tag like `claude-mailbox-frontend-a8b3c1d2`. No config involved.
- If unset → ✓ "Mailbox name will be auto-derived (`claude-<short_session_id>`)."
Ask once: *"Want to flavor your mailbox names with a memorable prefix (e.g., `backend`, `frontend`)? (yes / no / `<name>`)"* ## Step 7 — smoke test
On yes/explicit name: merge `env.CLAUDE_MAILBOX_NAME = <name>` into `.claude/settings.json`, preserving other keys. Mark `restart_needed = true`.
## Step 6 — smoke test
Use two ephemeral names — we don't need the real session name here: Use two ephemeral names — we don't need the real session name here:
@@ -89,14 +98,15 @@ claude-mailbox send --from doctor-probe-a --to doctor-probe-b --body "ping from
claude-mailbox check --name doctor-probe-b claude-mailbox check --name doctor-probe-b
``` ```
(If the port was changed in Step 2, pass `--url http://127.0.0.1:<port>` to both.) (If the port was changed in Step 3, pass `--url http://127.0.0.1:<port>` to both.)
The `check` output must be a JSON array with one message: `from: doctor-probe-a`, body matches. ✓ on success, ✗ otherwise. The `check` output must be a JSON array with one message: `from: doctor-probe-a`, body matches. ✓ on success, ✗ otherwise.
## Step 7 — summary ## Step 8 — summary
``` ```
Claude-Mailbox doctor Claude-Mailbox doctor
node: <version>
binary: <version> binary: <version>
daemon: Running (port: <port>, what you did if anything) daemon: Running (port: <port>, what you did if anything)
health: ok health: ok

View File

@@ -12,12 +12,12 @@ Claude-Mailbox status
binary: <output of `claude-mailbox --version`, or "not installed"> binary: <output of `claude-mailbox --version`, or "not installed">
daemon: <output of `claude-mailbox status`> daemon: <output of `claude-mailbox status`>
health: <"ok" if GET http://127.0.0.1:37849/health returns 200, else "unreachable"> health: <"ok" if GET http://127.0.0.1:37849/health returns 200, else "unreachable">
mailbox name: <value of env.CLAUDE_MAILBOX_NAME in ./.claude/settings.json, or "unset"; also note if ~/.claude/settings.json has a value> mailbox name: auto-derived per session as <project>-<short-session-id> (see SessionStart announcement)
pending: <integer count from `claude-mailbox peek --name <resolved-name>` if name is set, else "n/a"> pending: n/a (the session's mailbox name isn't known until SessionStart runs in this session's context)
``` ```
End with one line: End with one line:
- All good → `Status: OK` - All good → `Status: OK`
- Missing daemon or unset name `Status: Setup incomplete. Run /claude-mailbox:mailbox-doctor to fix.` - Missing daemon → `Status: Setup incomplete. Run /claude-mailbox:mailbox-doctor to fix.`
- Daemon installed but stopped → `Status: Daemon is not running. Try \`claude-mailbox start\` or run /claude-mailbox:mailbox-doctor.` - Daemon installed but stopped → `Status: Daemon is not running. Try \`claude-mailbox start\` or run /claude-mailbox:mailbox-doctor.`

View File

@@ -19,6 +19,16 @@
} }
] ]
} }
],
"SubagentStop": [
{
"hooks": [
{
"type": "command",
"command": "claude-mailbox check --hook"
}
]
}
] ]
} }
} }