import { parseGuidanceListQuery, parseGuidanceIdQuery, parseGuidancePageResult, parseGuidanceDiffResult } from "./guidance-variants.ts"; import { parseGuidanceProbeReceiptExport, probeSha256 } from "./guidance-probes.ts"; import type { ActionMeta, InboxAnswers } from "@staix/agent-console/contract"; import { assertExecutableRuntimeRoot } from "./project-runtime-state.ts"; import { BACKLOG_SPLIT_SCREEN_TIMEOUT_MS } from "./planning.ts"; import { HUB_DB_BUSY_TIMEOUT_MS } from "./db-timeout.ts"; import { Database } from "bun:sqlite"; import { randomBytes, randomUUID } from "node:crypto"; import { chmodSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { spawn } from "node:child_process"; import { ControlClient, PROTOCOL, PROTOCOL_MIN, RECOVERY_SOURCE_PROTOCOLS, controlProtocolWindow } from "./control-client.ts"; import { Registry, type Project } from "./registry.ts"; import { hubHome, realPath } from "./project.ts"; import { startDashboard, dashboardView } from "./ui.ts"; import { projectChain } from "@staix/agent-mem"; import type { ProjectInspection } from "./lifecycle.ts"; import { MAX_COMMAND_MS } from "../cli/terminal-recovery.ts"; import { processLiveness, processSignature } from "../pi/process-signature.ts"; const MANAGER_OWNER_DB_BUSY_TIMEOUT_MS = 5000; export type ProjectRecord = Project; export type Lifecycle = { inspectProject(project: Project): Promise; startProject(project: Project, options?: { unattended?: boolean; env?: NodeJS.ProcessEnv }): Promise; stopProject(project: Project, expectedInstance?: string): Promise; }; export type ManagerOptions = { registry?: Registry; lifecycle?: Lifecycle; home?: string; cli?: string; orphanWatchMs?: number; liveTest?: boolean; /** #608: runs after the dashboard's "start" has the hub ready, as the person's `ahub up` would, never for a live-test session. Its returned lines and any failure go to manager.log, one line each. Never part of a dashboard request. */ afterStart?: (project: Project) => Promise; /** Test clock seam: maps nominal forwarding deadlines, never comes from dashboard input. */ forwardTimeoutMs?: (action: string, nominalMs: number) => number }; type ManagerHandle = { stop(): Promise; stopped: Promise }; type Manifest = { port: number; protocol: number; protocolMin?: number; protocolMax?: number; instanceId: string; pid: number; pidSignature?: string; runtimeRoot?: string }; const active = new Map(); const CONTROL_TIMEOUT = 3000; // A current CLI may authenticate the previous protocol-9 manager while // refreshing it, then launch the current manager implementation. const SUPPORTED_MANAGER_PROTOCOLS = new Set(RECOVERY_SOURCE_PROTOCOLS); const safeError = (error: unknown) => error instanceof Error ? error.message.slice(0, 300) : "operation failed"; function files(home: string) { const dir = join(home, "manager"); return { dir, token: join(dir, "control-token"), status: join(dir, "status.json"), owner: join(dir, "owner.db") }; } function scrubEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { const out = { ...env }; for (const key of ["AGENTHUB_STATE_DIR", "AGENTHUB_PROJECT_DIR", "AGENTHUB_UNATTENDED", "AGENTHUB_OMNIROUTE_URL", "OMNIROUTE_API_KEY"]) delete out[key]; return out; } async function bounded(promise: Promise, ms: number): Promise { let timer: ReturnType | undefined; try { return await Promise.race([promise, new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("completion was not confirmed; refresh before retrying")), ms); })]); } finally { clearTimeout(timer); } } function claimOwner(path: string, instanceId: string, signature: string | undefined): Database { const db = new Database(path, { create: true }); try { db.run(`PRAGMA busy_timeout = ${MANAGER_OWNER_DB_BUSY_TIMEOUT_MS}`); db.run("CREATE TABLE IF NOT EXISTS owner (slot INTEGER PRIMARY KEY CHECK (slot = 1), instance_id TEXT NOT NULL, pid INTEGER NOT NULL, signature TEXT)"); if (!(db.query("PRAGMA table_info(owner)").all() as { name: string }[]).some((c) => c.name === "signature")) { try { db.run("ALTER TABLE owner ADD COLUMN signature TEXT"); } catch (error) { if (!/duplicate column/i.test((error as Error).message)) throw error; } } db.transaction(() => { // #226: an older manager's INSERT OR REPLACE leaves the signature NULL, so its row is judged by the pid alone. const row = db.query("SELECT pid, signature FROM owner WHERE slot = 1").get() as { pid: number; signature: string | null } | null; if (row && processLiveness(row.pid, row.signature) !== "gone") throw new Error("manager has a live or uncertain owner"); db.query("INSERT OR REPLACE INTO owner (slot, instance_id, pid, signature) VALUES (1, ?, ?, ?)").run(instanceId, process.pid, signature ?? null); }).immediate(); return db; } catch (error) { db.close(); throw error; } } function readManifest(home: string): Manifest | undefined { try { const status = JSON.parse(readFileSync(files(home).status, "utf8")); if (!Number.isInteger(status.port) || status.port < 1 || status.port > 65535 || typeof status.instanceId !== "string") return undefined; return status; } catch { return undefined; } } function removeManifest(home: string, instanceId: string) { if (readManifest(home)?.instanceId !== instanceId) return; rmSync(files(home).status, { force: true }); rmSync(files(home).token, { force: true }); } /** #1483 R5: one project's public roadmap summary for `ahub ui --all`. `partial` means the hub could not answer, so the counts are a floor, not a zero. */ export interface ProjectRoadmapSummary { total: number; byHorizon: Record; byState: Record; drift: number; partial: boolean } /** Lanes and states come from the milestone rows' own fields, so an unknown value is counted under its own name instead of dropped. */ export function roadmapSummary(milestones: readonly Record[], drift = 0): ProjectRoadmapSummary { const byHorizon: Record = {}, byState: Record = {}; for (const milestone of milestones) { const horizon = String(milestone.horizon ?? "later"), state = String(milestone.state ?? "proposed"); byHorizon[horizon] = (byHorizon[horizon] ?? 0) + 1; byState[state] = (byState[state] ?? 0) + 1; } return { total: milestones.length, byHorizon, byState, drift, partial: false }; } /** The manager's project listing and forwarding (#935): shared by `ahub ui --all` and the acon plugin, never widened for either. */ export function projectConsole(options: { registry: Registry; lifecycle: Lifecycle; home: string; stopping?: () => boolean; forwardTimeoutMs?: ManagerOptions["forwardTimeoutMs"]; afterStart?: ManagerOptions["afterStart"]; roadmap?: boolean }) { const { registry, lifecycle, home } = options; const aliases = new Map(); // #1483 R5: a project's roadmap is read once a minute, because the manager's page polls this listing every three seconds. // It is opt-in, so the acon plugin's listing pays nothing for a field it does not show, and the whole read is bounded. const roadmaps = new Map(); const roadmap = async (project: { id: string; root: string; stateDir: string }, instanceId: string | null): Promise => { const cached = roadmaps.get(project.id); if (cached && cached.instanceId === instanceId && Date.now() - cached.at < 60_000) return cached.summary; const unavailable: ProjectRoadmapSummary = { total: 0, byHorizon: {}, byState: {}, drift: 0, partial: true }; let summary = unavailable, client: ControlClient | undefined; try { client = await bounded(ControlClient.connect(project.stateDir, { role: "console", projectId: project.id, projectRoot: project.root }, 3000), 4000); const listed = await bounded(client.request({ t: "task", op: "hub_roadmap_list", args: {} }, 5000), 6000); if (listed && listed.ok !== false) { let report: any; try { report = JSON.parse(String(listed.text ?? "")); } catch { report = undefined; } if (Array.isArray(report?.milestones)) { // The drift read is the hub's own findings count; a refusal only drops the count, never the milestones. const checked = await bounded(client.request({ t: "task", op: "hub_roadmap_check", args: {} }, 15_000), 16_000).catch(() => undefined); let drift = 0; if (checked && checked.ok !== false) { try { const findings = JSON.parse(String(checked.text ?? ""))?.findings; drift = Array.isArray(findings) ? findings.length : 0; } catch { drift = 0; } } summary = roadmapSummary(report.milestones, drift); } } } catch { summary = unavailable; } finally { client?.close(); } roadmaps.set(project.id, { at: Date.now(), instanceId, summary }); return summary; }; const list = async () => { const projects = registry.list(); for (const p of projects) if (!aliases.has(p.id) || Date.now() - aliases.get(p.id)!.at > 60_000) { aliases.set(p.id, { at: Date.now(), names: existsSync(p.root) ? projectChain(p.root) : [] }); } const rows = await Promise.all(projects.map(async (project) => { let result: ProjectInspection; try { result = await bounded(lifecycle.inspectProject(project), 7000); } catch (error) { result = { state: "unavailable", error: safeError(error) }; } const names = aliases.get(project.id)!.names; const shared = projects.some((other) => other.id !== project.id && aliases.get(other.id)!.names.some((name) => names.includes(name))); const instanceId = result.state === "running" ? result.status?.instanceId ?? null : null; return { id: project.id, root: project.root, state: result.state, instanceId, peers: result.status?.peers ?? {}, tasks: result.status?.tasks ?? {}, // #1483 R5: a running project answers with its own public roadmap summary; a stopped one has none to read. ...(instanceId && options.roadmap ? { roadmap: await roadmap(project, instanceId) } : {}), ...(shared ? { warning: "Native memory aliases are shared with another registered project." } : {}), ...(result.error ? { error: result.error } : {}) }; })); return { ok: true, mode: "all", projects: rows }; }; const act = async (input: Record, session?: { liveTest?: true }) => { if (options.stopping?.()) return { ok: false, error: "manager is stopping" }; const project = typeof input.projectId === "string" ? registry.get(input.projectId) : undefined; if (!project) return { ok: false, error: "unknown project" }; let client: ControlClient | undefined; try { if (input.action === "start") { const status = await bounded(lifecycle.startProject(project, { unattended: false, env: { ...scrubEnv(process.env), AGENTHUB_HOME: home } }), 20_000); // The agents start in the background: the dashboard's answer is the hub's readiness, and a terminal that is slow to open must not hold it. // A live-test dashboard session is an agent borrowing the person's console: it never opens the person's default agents. The session, not this process, carries that flag. if (options.afterStart && session?.liveTest !== true) { const stamp = (line: string) => `${new Date().toISOString()} default agents for ${project.id}: ${line.replace(/[\x00-\x1f\x7f]+/g, " ").slice(0, 600)}`; void options.afterStart(project).then( lines => { for (const line of lines) console.error(stamp(line)); }, error => { console.error(stamp(`not started: ${safeError(error)}`)); }); } return { ok: true, projectId: project.id, instanceId: status.instanceId }; } if (typeof input.instanceId !== "string" || !input.instanceId) return { ok: false, error: "expected daemon instance is required" }; if (input.action === "stop") { await bounded(lifecycle.stopProject(project, input.instanceId), 20_000); return { ok: true }; } // #1057: the worktree shelf's person actions. The refresh is the one that reads GitHub, so it gets the delivery reads' deadline in its own branch below. const worktreeAction = ["worktree_override_set", "worktree_override_clear", "worktrees_refresh_prs"].includes(String(input.action)); // The settings actions (#269) reach the project hub as an ordinary session's: this dashboard opens no settings session. if (!["snapshot", "send", "pause", "resume", "permit", "supervision", "propose", "intake", "assign", "backlog_pull", "backlog_return", "planning", "planning_undo", "planner_pull", "backlog_split", "release_new", "release_change", "setting", "setting_undo", "setting_preview", "setting_reload", "model_preview", "model_confirm", "config_edit_preview", "config_edit_apply", "start_peer", "sdlc_queue", "sdlc_release", "result_seen", "results_read_all", "results_unread_last"].includes(String(input.action)) && !worktreeAction) return { ok: false, error: "invalid dashboard action" }; const visualSelector = input.action === "snapshot" ? visualSnapshotSelector(input) : {}; client = await ControlClient.connect(project.stateDir, { role: "console", projectId: project.id, projectRoot: project.root, instanceId: input.instanceId }); const deliveryRead = input.action === "sdlc_queue" || input.action === "sdlc_release"; let nominalMs = 10_000; if (input.action === "start_peer") nominalMs = MAX_COMMAND_MS + 5_000; else if (input.action === "backlog_split") nominalMs = BACKLOG_SPLIT_SCREEN_TIMEOUT_MS + HUB_DB_BUSY_TIMEOUT_MS + 5_000; else if (input.action === "intake") nominalMs = 90_000; // the CLI intake cap, including the hub model's bounded split else if (deliveryRead) nominalMs = 30_000; else if (input.action === "worktrees_refresh_prs") nominalMs = 40_000; // up to 25 s of bounded gh reads plus two git passes const timeoutMs = options.forwardTimeoutMs?.(String(input.action), nominalMs) ?? nominalMs; const result = await client.request(input.action === "snapshot" ? { t: "ui_snapshot", after: input.after ?? 0, ...visualSelector, ...(input.reviewRefresh === true && input.reviewTask !== undefined ? { reviewTask: input.reviewTask, reviewRefresh: true } : {}), ...(input.memory !== undefined ? { memory: input.memory } : {}), ...(dashboardView(input.view) ? { view: input.view } : {}) } : { t: "ui_action", action: input, instanceId: input.instanceId }, timeoutMs); // ControlClient resolves its deadline as this exact sentinel; a hub refusal stays a known failure. if (input.action === "intake" && result.ok === false && result.error === `no answer from the hub within ${Math.round(timeoutMs / 1000)} s`) { const text = "Intake result is unconfirmed. Check Backlog before retrying; the hub may still create its drafts."; return { ok: false, unconfirmed: true, text, error: text }; } if (["start_peer", "backlog_split"].includes(String(input.action)) && result.ok === false && result.error === `no answer from the hub within ${Math.round(timeoutMs / 1000)} s`) { const text = input.action === "backlog_split" ? "Split result is unconfirmed. Reload the task before retrying; the hub may still commit its children." : "Start result is unconfirmed. Check the Peers panel before retrying; the hub may still be starting the peer."; return { ok: false, unconfirmed: true, text, error: text }; } if (deliveryRead) { const { rid: _transportId, ...report } = result; return report; } return result; } catch (error) { return { ok: false, error: safeError(error) }; } finally { client?.close(); } }; // #1053 T5: the acon plugin's answer to a question a peer asked. A port of its own, never an `act` action: `act` is also what the `ahub ui --all` dashboard page reaches, and an answer needs // the console's verified person meta, which only the server-side provider holds (it checks it before calling this). The hub re-validates every answer against the stored row. const answer = async (target: { projectId: unknown; instanceId: unknown }, payload: { questionSet: string; answers: InboxAnswers; person: string }) => { if (options.stopping?.()) return { ok: false, error: "manager is stopping" }; const project = typeof target.projectId === "string" ? registry.get(target.projectId) : undefined; if (!project) return { ok: false, error: "unknown project" }; if (typeof target.instanceId !== "string" || !target.instanceId) return { ok: false, error: "expected daemon instance is required" }; let client: ControlClient | undefined; try { client = await ControlClient.connect(project.stateDir, { role: "console", projectId: project.id, projectRoot: project.root, instanceId: target.instanceId }); const result = await client.request({ t: "answer", surface: "acon", questionSet: payload.questionSet, answers: payload.answers, person: payload.person }, 10_000); const { rid: _rid, t: _t, ...reply } = result as Record; return reply; } catch (error) { return { ok: false, error: safeError(error) }; } finally { client?.close(); } }; // #1054 T6: the acon plugin's receipt for a result: marking one read, all read, or the last read unread again. A port of its own like `answer`, never an `act` action from the plugin: // the provider checks the console's verified person meta first. The hub's console-role `result_seen` and `results` control messages do the write, on the `acon` surface, and name a // stale or unknown result in their refusal. (The page of `ahub ui` and `ahub ui --all` reaches the same writes as dashboard actions, which is the person's own browser session.) const receipt = async (target: { projectId: unknown; instanceId: unknown }, payload: { op: "result_seen"; id: string } | { op: "results"; action: "read-all" | "unread-last" }) => { if (options.stopping?.()) return { ok: false, error: "manager is stopping" }; const project = typeof target.projectId === "string" ? registry.get(target.projectId) : undefined; if (!project) return { ok: false, error: "unknown project" }; if (typeof target.instanceId !== "string" || !target.instanceId) return { ok: false, error: "expected daemon instance is required" }; let client: ControlClient | undefined; try { client = await ControlClient.connect(project.stateDir, { role: "console", projectId: project.id, projectRoot: project.root, instanceId: target.instanceId }); const message = payload.op === "result_seen" ? { t: "result_seen", id: payload.id, surface: "acon" } : { t: "results", action: payload.action, surface: "acon" }; const result = await client.request(message, 10_000); const { rid: _rid, t: _t, ...reply } = result as Record; return reply; } catch (error) { return { ok: false, error: safeError(error) }; } finally { client?.close(); } }; // #1056: only the server-side acon provider calls this port. Dashboard action bodies // cannot select a control operation or manufacture verified person metadata. const consoleControl = async (target: { projectId: unknown; instanceId: unknown }, op: "review_comment_put" | "review_comment_delete" | "review_comment_send" | "review_comments" | "review_blob", payload: Record, personMeta?: ActionMeta) => { if (options.stopping?.()) return { ok: false, error: "manager is stopping" }; if (!["review_comment_put", "review_comment_delete", "review_comment_send", "review_comments", "review_blob"].includes(op)) return { ok: false, error: "invalid review operation" }; const project = typeof target.projectId === "string" ? registry.get(target.projectId) : undefined; if (!project) return { ok: false, error: "unknown project" }; if (typeof target.instanceId !== "string" || !target.instanceId) return { ok: false, error: "expected daemon instance is required" }; let client: ControlClient | undefined; try { client = await ControlClient.connect(project.stateDir, { role: "console", projectId: project.id, projectRoot: project.root, instanceId: target.instanceId }); const timeoutMs = options.forwardTimeoutMs?.(op, 10_000) ?? 10_000; const result = await client.request({ ...payload, t: op, instanceId: target.instanceId, personMeta }, timeoutMs); if (result.ok === false && result.error === `no answer from the hub within ${Math.round(timeoutMs / 1000)} s`) return { ok: false, unconfirmed: true as const, text: "Review result is unconfirmed. Refresh and check the task before retrying.", error: "Review result is unconfirmed. Refresh and check the task before retrying." }; const { rid: _transportId, ...reply } = result; return reply; } catch { return { ok: false, unconfirmed: true as const, text: "Review result is unconfirmed. Refresh and check the task before retrying.", error: "Review result is unconfirmed. Refresh and check the task before retrying." }; } finally { client?.close(); } }; // #1220 T3: the acon provider's execution-lineage read. A port of its own like `answer`, never an `act` action: the // dashboard's action list does not grow, so nothing here can link, probe, replay or execute. It sends the control // message the console role already owns, answered in-stack by the same Tasks projection the CLI and MCP read. const lineageQueryKeys = ["taskId", "attemptId", "root", "task", "cursor", "nodes", "edges", "bytes"] as const; const lineage = async (target: { projectId: unknown; instanceId: unknown }, query: Record) => { if (options.stopping?.()) return { ok: false, error: "manager is stopping" }; const project = typeof target.projectId === "string" ? registry.get(target.projectId) : undefined; if (!project) return { ok: false, error: "unknown project" }; if (typeof target.instanceId !== "string" || !target.instanceId) return { ok: false, error: "expected daemon instance is required" }; // The hub parses a closed query: an unknown field would refuse every read, so name it here instead. if (!query || typeof query !== "object" || Array.isArray(query) || Object.keys(query).some(key => !(lineageQueryKeys as readonly string[]).includes(key))) return { ok: false, error: "invalid lineage query" }; let client: ControlClient | undefined; try { client = await ControlClient.connect(project.stateDir, { role: "console", projectId: project.id, projectRoot: project.root, instanceId: target.instanceId }); const timeoutMs = options.forwardTimeoutMs?.("lineage_show", 10_000) ?? 10_000; const result = await client.request({ t: "lineage_show", ...query }, timeoutMs); // A read has no effect to confirm: a missed deadline is a read that did not happen. if (result.ok === false && result.error === `no answer from the hub within ${Math.round(timeoutMs / 1000)} s`) return { ok: false, error: "the hub did not answer the lineage read in time; refresh and retry" }; const { rid: _transportId, ...reply } = result; return reply; } catch (error) { return { ok: false, error: safeError(error) }; } finally { client?.close(); } }; /** Producer-only read port; never forwards an action, actor or person-metadata claim. */ const guidance = async (target: { projectId: unknown; instanceId: unknown }, op: "list" | "show", input: unknown) => { if (options.stopping?.()) return { ok: false, error: "guidance read is unavailable while the manager stops; reconnect before retrying" }; if (op !== "list" && op !== "show") return { ok: false, error: "guidance console is read-only; use the authorized CLI/MCP for mutations" }; const project = typeof target.projectId === "string" ? registry.get(target.projectId) : undefined; if (!project || typeof target.instanceId !== "string" || !target.instanceId) return { ok: false, error: "select a running project and current instance before reading guidance" }; let query; try { query = op === "list" ? parseGuidanceListQuery(input) : parseGuidanceIdQuery(input); } catch { return { ok: false, error: "invalid guidance query; select the task epoch and existing variant id or cursor" }; } let client: ControlClient | undefined; try { client = await ControlClient.connect(project.stateDir, { role: "console", projectId: project.id, projectRoot: project.root, instanceId: target.instanceId }); if (!client.features.includes("guidance_views")) return { ok: false, error: "running hub lacks guidance_views; upgrade and restart the hub before reading guidance" }; const result = await client.request({ t: op === "list" ? "guidance_list" : "guidance_show", ...query }, options.forwardTimeoutMs?.(`guidance_${op}`, 10_000) ?? 10_000); if (result.ok !== true) return { ok: false, error: "guidance read is unavailable; refresh the task scope and current daemon before retrying" }; return { ok: true, guidance: op === "list" ? parseGuidancePageResult(result.guidance, query) : parseGuidanceDiffResult(result.guidance, query) }; } catch { return { ok: false, error: "guidance read is unavailable; refresh the task scope or upgrade the hub before retrying" }; } finally { client?.close(); } }; /** Producer-only read port for one probe experiment; never forwards an action, an actor or a person-metadata claim, and writes nothing in the hub. */ const guidanceProbe = async (target: { projectId: unknown; instanceId: unknown }, input: unknown) => { if (options.stopping?.()) return { ok: false, error: "guidance probe status is unavailable while the manager stops; reconnect before retrying" }; const project = typeof target.projectId === "string" ? registry.get(target.projectId) : undefined; if (!project || typeof target.instanceId !== "string" || !target.instanceId) return { ok: false, error: "select a running project and current instance before reading a guidance probe" }; // A closed query: exactly one exact registered content id. Any other field is refused here rather than forwarded. if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => key !== "id") || !probeSha256((input as { id?: unknown }).id)) return { ok: false, error: "invalid guidance probe query; use the exact 64-character probe id" }; const id = (input as { id: string }).id; let client: ControlClient | undefined; try { client = await ControlClient.connect(project.stateDir, { role: "console", projectId: project.id, projectRoot: project.root, instanceId: target.instanceId }); if (!client.features.includes("guidance_probe_receipts")) return { ok: false, error: "running hub lacks guidance_probe_receipts; upgrade and restart the hub before reading a guidance probe" }; const result = await client.request({ t: "guidance_probe_receipts", id }, options.forwardTimeoutMs?.("guidance_probe_receipts", 10_000) ?? 10_000); if (result.ok !== true) return { ok: false, error: typeof result.error === "string" ? result.error.slice(0, 512) : "guidance probe status is unavailable; refresh the probe id and the current daemon before retrying" }; const receipts = parseGuidanceProbeReceiptExport(result.receipts); // The reply must be the experiment that was asked for: a well-formed export of another probe never satisfies this selection. if (!receipts || receipts.status.id !== id) return { ok: false, error: "guidance probe receipts are malformed, fail their digest check or name another probe; do not rely on them" }; return { ok: true, receipts }; } catch { return { ok: false, error: "guidance probe status is unavailable; refresh the probe id or upgrade the hub before retrying" }; } finally { client?.close(); } }; return { list, act, answer, receipt, consoleControl, lineage, guidance, guidanceProbe }; } export async function startManager(options: ManagerOptions = {}): Promise { const home = options.home ?? hubHome(); const existing = active.get(home); if (existing) return existing.handle; if (!options.lifecycle) throw new Error("manager lifecycle is not configured"); const lifecycle = options.lifecycle; const registry = options.registry ?? new Registry(join(home, "registry.db")); const ownsRegistry = !options.registry; const f = files(home); mkdirSync(f.dir, { recursive: true, mode: 0o700 }); const token = randomBytes(32).toString("hex"), instanceId = randomUUID(); const pidSignature = processSignature(process.pid); // #226: the owner row and manifest say which process holds this pid let owner: Database | undefined; let server: ReturnType | undefined; let dashboard: ReturnType | undefined; let stopping = false; let orphanWatch: ReturnType | undefined; let resolveStopped!: () => void; const stopped = new Promise((resolve) => { resolveStopped = resolve; }); const cleanup = () => { if (orphanWatch) clearInterval(orphanWatch); dashboard?.stop(); server?.stop(true); active.delete(home); removeManifest(home, instanceId); if (owner) { // The state dir may already be gone (the orphan watchdog path, issue #56): a DELETE on an // unlinked database fails with SQLITE_IOERR_VNODE on macOS, and the claim went with the file. try { owner.query("DELETE FROM owner WHERE slot = 1 AND instance_id = ? AND pid = ?").run(instanceId, process.pid); } catch { /* claim file already gone */ } try { owner.close(); } catch { /* already unlinked */ } owner = undefined; } if (ownsRegistry) registry.close(); }; const stop = async () => { if (stopping) return; stopping = true; cleanup(); resolveStopped(); }; try { const publicationRegistry = typeof registry.runtimeCaptureLocked === "function" && typeof registry.path === "string" && resolve(registry.path) === resolve(join(home, "registry.db")) ? registry : new Registry(join(home, "registry.db")); try { publicationRegistry.runtimeCaptureLocked(() => { assertExecutableRuntimeRoot(realPath(resolve(import.meta.dir, "../.."))); owner = claimOwner(f.owner, instanceId, pidSignature); const { list, act } = projectConsole({ registry, lifecycle, home, roadmap: true, stopping: () => stopping, forwardTimeoutMs: options.forwardTimeoutMs, ...(options.afterStart && !options.liveTest ? { afterStart: options.afterStart } : {}) }); dashboard = startDashboard({ projects: list, snapshot: (after, input = {}) => act({ ...input, action: "snapshot", after }), action: act }); server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 1024, async fetch(req) { if (req.headers.has("origin")) return new Response("forbidden", { status: 403 }); if (req.headers.get("authorization") !== `Bearer ${token}`) return new Response("unauthorized", { status: 401 }); if (req.method !== "POST") return new Response("POST required", { status: 405 }); const expected = req.headers.get("x-agenthub-instance"); if (expected && expected !== instanceId) return Response.json({ ok: false, error: "manager instance changed" }, { status: 409 }); if (stopping) return Response.json({ ok: false, error: "manager is stopping" }, { status: 409 }); const path = new URL(req.url).pathname; if (path === "/open") { const input = await req.json().catch(() => ({})) as { liveTest?: boolean }; return Response.json({ ok: true, instanceId, protocol: PROTOCOL_MIN, protocolMin: PROTOCOL_MIN, protocolMax: PROTOCOL, url: dashboard!.issue(false, input.liveTest === true), ...(input.liveTest === true ? { liveTest: true } : {}) }); } if (path === "/stop") { setTimeout(() => void stop(), 0); return Response.json({ ok: true, instanceId }); } return new Response("not found", { status: 404 }); }, }); writeFileSync(f.token, token, { mode: 0o600 }); chmodSync(f.token, 0o600); const temp = `${f.status}.${instanceId}.tmp`; writeFileSync(temp, JSON.stringify({ port: server.port, protocol: PROTOCOL_MIN, protocolMin: PROTOCOL_MIN, protocolMax: PROTOCOL, instanceId, pid: process.pid, ...(pidSignature ? { pidSignature } : {}), runtimeRoot: realPath(resolve(import.meta.dir, "../..")) }), { mode: 0o600 }); renameSync(temp, f.status); }); } finally { if (publicationRegistry !== registry) publicationRegistry.close(); } // The manager outlives whoever opened it; a deleted AGENTHUB_HOME (a test suite's temp // home, issue #56) must not leave it serving a registry that no longer exists. orphanWatch = setInterval(() => { if (stopping || existsSync(f.dir)) return; void stop(); }, options.orphanWatchMs ?? 10_000); orphanWatch.unref?.(); const handle = { stop, stopped }; active.set(home, { handle, issue: (liveTest) => dashboard!.issue(false, liveTest) }); return handle; } catch (error) { cleanup(); throw error; } } async function managerRequest(home: string, path: "/open" | "/stop", liveTest = false): Promise<{ status: Manifest; body: any }> { const status = readManifest(home); if (!status) throw new Error("manager manifest is unavailable"); if (!SUPPORTED_MANAGER_PROTOCOLS.has(status.protocol) || !controlProtocolWindow(status)) throw new Error("manager protocol is incompatible; use its matching CLI to stop it"); const token = readFileSync(files(home).token, "utf8").trim(); if (!token) throw new Error("manager token is unavailable"); const response = await fetch(`http://127.0.0.1:${status.port}${path}`, { method: "POST", headers: { authorization: `Bearer ${token}`, "x-agenthub-instance": status.instanceId }, ...(liveTest ? { body: JSON.stringify({ liveTest: true }) } : {}), signal: AbortSignal.timeout(CONTROL_TIMEOUT), }); if (!response.ok) throw new Error(`manager refused request (${response.status}); ownership was not verified`); const body = await response.json() as { ok?: boolean; instanceId?: string; url?: string }; if (!body.ok || body.instanceId !== status.instanceId) throw new Error("manager identity changed; refresh before retrying"); if (liveTest && (body as { liveTest?: boolean }).liveTest !== true) throw new Error("manager cannot restrict delegated dashboard content; use a live-test-capable manager"); return { status, body }; } export async function openManager(options: ManagerOptions = {}): Promise { const home = options.home ?? hubHome(); const local = active.get(home); if (local) return local.issue(options.liveTest); try { return (await managerRequest(home, "/open", options.liveTest)).body.url; } catch (error) { const old = readManifest(home); if (old && processLiveness(old.pid, old.pidSignature) !== "gone") throw error; // A definitely dead manager can be recovered by its ownership claim. } const f = files(home); mkdirSync(f.dir, { recursive: true, mode: 0o700 }); const log = openSync(join(f.dir, "manager.log"), "a"); let proc: ReturnType; try { proc = spawn(process.execPath, [options.cli ?? join(import.meta.dir, "../cli/main.ts"), "manager"], { cwd: home, detached: true, stdio: ["ignore", log, log], env: { ...scrubEnv(process.env), AGENTHUB_HOME: home }, }); proc.on("error", () => {}); proc.unref(); } finally { closeSync(log); } const deadline = Date.now() + 8000; let error: unknown; while (Date.now() < deadline) { try { const answered = await managerRequest(home, "/open", options.liveTest); // #584: concurrent opens each spawn a manager and one wins the owner claim. A spawn that lost, or is still booting when // another manager answers, would claim the owner row once that manager is stopped and then run with nobody to stop it. // Only the manager that answered is wanted; stop the process this open started if it is a different one. if (answered.status.pid !== proc.pid) proc.kill("SIGTERM"); return answered.body.url; } catch (caught) { error = caught; await Bun.sleep(100); } } throw new Error(`manager readiness not confirmed: ${safeError(error)}; see ${join(f.dir, "manager.log")}`); } /** Refresh a supported older manager onto the current CLI after upgrade. */ export async function refreshManager(options: ManagerOptions = {}): Promise { const home = options.home ?? hubHome(); const manifest = readManifest(home); if (manifest && (controlProtocolWindow(manifest)?.v ?? Infinity) < PROTOCOL && RECOVERY_SOURCE_PROTOCOLS.includes(manifest.protocol as (typeof RECOVERY_SOURCE_PROTOCOLS)[number])) { await managerRequest(home, "/stop"); const deadline = Date.now() + CONTROL_TIMEOUT; while (Date.now() < deadline && readManifest(home)) await Bun.sleep(25); if (readManifest(home)) throw new Error("legacy manager shutdown is still pending; refresh was not confirmed"); } return openManager(options); } export async function stopManager(options: ManagerOptions = {}): Promise { const home = options.home ?? hubHome(); const local = active.get(home); if (local) return local.handle.stop(); if (!existsSync(files(home).status)) return; const { status } = await managerRequest(home, "/stop"); const deadline = Date.now() + CONTROL_TIMEOUT; while (Date.now() < deadline) { const current = readManifest(home); if (!current) return; if (current.instanceId !== status.instanceId) throw new Error("a new manager instance started; it was not stopped"); await Bun.sleep(25); } throw new Error("manager shutdown is still pending; project hubs were not changed"); } /** Closed read selectors only; no caller path, policy or arbitrary control fields are forwarded. */ export function visualSnapshotSelector(input: Record): Record { const keys = ["visual", "visualTask", "visualAsset"].filter(key => Object.hasOwn(input, key)); if (!keys.length) return {}; if (keys.length !== 1) throw new Error("visual selector is ambiguous; select one visual or task and retry"); const key = keys[0]!, value = input[key]; const id = "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}"; if (key === "visualTask" ? Number.isSafeInteger(value) && Number(value) > 0 : typeof value === "string" && new RegExp(key === "visualAsset" ? `^${id}:(before|after)$` : `^${id}$`).test(value)) return { [key]: value as string | number }; throw new Error("visual selector is invalid; select a current visual or task and retry"); }