import { readFileSync } from "node:fs"; import { dirname, isAbsolute, resolve } from "node:path"; import type { Command } from "commander"; import type { EmitContext } from "../commander.ts"; import { adapterProofInputs, createBuiltinAdapterRegistry, probeBinaryVersion, readAttestation, } from "../core/adapters/index.ts"; import { resolveCoordRoot } from "../core/agents/coord-client.ts"; import { workflowSubscriptionOnly } from "../core/config.ts"; import { inspectAdapterSpread } from "../core/governor/adapter-spread.ts"; import { approveGovernorPlan, type CreateGovernorMissionInput, type CreateGovernorReplanningInput, configureGovernorService, createGovernor, type GovernorPlanOutcome, type GovernorPlanRecord, type GovernorRecord, type GovernorRunReport, type GovernorServiceConfig, type GovernorServiceStatus, listGovernorsWithWarnings, readGovernor, readGovernorPlan, readGovernorServiceConfig, readGovernorServiceStatus, rejectGovernorPlan, requestGovernorServiceStop, retryGovernorPlan, runGovernor, runGovernorServiceDaemon, spawnGovernorService, } from "../core/governor/index.ts"; import { readGovernorServiceLogs } from "../core/governor/service-read.ts"; import type { PolicyIsolation } from "../core/policy/index.ts"; import { loadPolicyFile } from "../core/policy/index.ts"; import type { WorkflowSpecialistProfile } from "../core/workflow/index.ts"; interface CreateOpts { allowSingleAdapter?: boolean; team: string; id?: string; title?: string; maxCycles?: string; maxRuntimeMs?: string; maxParallelWork?: string; maxTotalAttempts?: string; maxAgentsPerWork?: string; agentConcurrency?: string; acceptPassingProof?: boolean; resumeApproved?: boolean; retryBlocked?: boolean; replanning?: string; mission?: string; json?: boolean; } interface RunOpts { adapter?: string; cwd?: string; observePressure?: boolean; subscriptionOnly?: boolean; allowApiBilling?: boolean; policy?: string; isolation?: PolicyIsolation; approvalTo?: string; actor?: string; json?: boolean; } interface ServiceOpts extends RunOpts { wakeIntervalMs?: string; heartbeatIntervalMs?: string; errorBackoffBaseMs?: string; errorBackoffMaxMs?: string; } export function registerGovernorCommand(program: Command, emit: EmitContext): void { const registry = createBuiltinAdapterRegistry(); const governor = program .command("governor") .description("Run a bounded specialist team over a durable-work dependency graph."); governor .command("create [root-work-id]") .description("Freeze an existing-root goal or an objective-first bounded mission.") .requiredOption("--team ", "JSON object mapping specialist ids to profiles") .option("--id ", "Stable goal id (generated by default)") .option("--title ", "Goal title (defaults to root work title)") .option("--max-cycles ", "Foreground cycle ceiling (default 50)") .option("--max-runtime-ms ", "Foreground wall-time ceiling (default 14400000)") .option("--max-parallel-work ", "Concurrent work-item ceiling (default 1)") .option("--max-total-attempts ", "Graph-wide attempt ceiling (default 100)") .option("--max-agents-per-work ", "Child-agent ceiling per work item (default 20)") .option("--agent-concurrency ", "Child concurrency per work item (default 4)") .option("--accept-passing-proof", "Allow the governor to explicitly accept passing proof") .option("--no-resume-approved", "Stop after an approval instead of resuming its parked run") .option("--retry-blocked", "Allow bounded retry of blocked work") .option( "--allow-single-adapter", "Freeze a team even though every specialist lands on one adapter under subscription auth", ) .option("--replanning ", "Frozen planner policy and allowed workflow-template catalog") .option("--mission ", "Frozen objective, acceptance criteria, and milestone bound") .option("--json", "Emit the complete governor record as JSON") .action((rootWorkId: string | undefined, opts: CreateOpts) => { withGovernorRoot(emit, (coordRoot) => { const specialists = readTeamFile(opts.team); for (const [id, profile] of Object.entries(specialists)) { if (profile.adapter && !registry.get(profile.adapter)) { throw new Error( `specialist ${id} names unknown adapter ${JSON.stringify(profile.adapter)}`, ); } } if (!opts.allowSingleAdapter) { // Refuse a team that would put every child on one subscription seat // while other adapters sit attested and idle. Checked here rather than // at run time because the intent freezes on create with no amend path: // catching it later means recreating the goal. const spread = inspectAdapterSpread({ specialists, defaultAdapter: "claude-code", reachable: registry.ids().filter((id) => readAttestation(id) !== null), subscriptionOnly: workflowSubscriptionOnly(coordRoot), }); if (spread.concentrated) { throw new Error(`refusing to freeze a single-adapter team: ${spread.reason}`); } } emitGovernor( createGovernor({ coordRoot, rootWorkId, specialists, id: opts.id, title: opts.title, limits: { max_cycles: integer(opts.maxCycles), max_runtime_ms: integer(opts.maxRuntimeMs), max_parallel_work: integer(opts.maxParallelWork), max_total_attempts: integer(opts.maxTotalAttempts), max_agents_per_work: integer(opts.maxAgentsPerWork), agent_concurrency: integer(opts.agentConcurrency), }, automation: { accept_passing_proof: opts.acceptPassingProof, resume_approved: opts.resumeApproved, retry_blocked: opts.retryBlocked, }, mission: opts.mission ? readMissionFile(opts.mission) : undefined, replanning: opts.replanning ? readReplanningFile(opts.replanning) : undefined, }), opts.json, emit, true, ); }); }); governor .command("list") .description("List durable goals and their derived next action.") .option("--json", "Emit complete governor records as JSON") .action((opts: { json?: boolean }) => { withGovernorRoot(emit, (coordRoot) => { const { records, warnings } = listGovernorsWithWarnings(coordRoot); if (opts.json) { emit.config({ format: "json" }); emit.data(records); for (const warning of warnings) { emit.log(renderGovernorListWarning(warning.goal_id, warning.reason), "warn"); } } else if (records.length === 0 && warnings.length === 0) { emit.text("no durable governors\n"); } else { emit.text( `${[ ...records.map(renderGovernorRow), ...warnings.map((warning) => renderGovernorListWarning(warning.goal_id, warning.reason), ), ].join("\n")}\n`, ); } }); }); governor .command("show ") .description("Show one goal, frozen team, bounds, graph state, and next action.") .option("--json", "Emit the complete governor record as JSON") .action((goalId: string, opts: { json?: boolean }) => { withGovernorRoot(emit, (coordRoot) => { emitGovernor(readGovernor(coordRoot, goalId), opts.json, emit, true); }); }); registerPlanCommand(governor, emit); registerServiceCommand(governor, registry, emit); registerRunCommand(governor, "tick", registry, emit); registerRunCommand(governor, "run", registry, emit); } function registerPlanCommand(governor: Command, emit: EmitContext): void { const plan = governor .command("plan") .description("Inspect and resolve bounded planner proposals for a durable goal."); plan .command("list ") .description("List append-only replanning attempts for one goal.") .option("--json", "Emit complete plan records as JSON") .action((goalId: string, opts: { json?: boolean }) => { withGovernorRoot(emit, (coordRoot) => { const plans = readGovernor(coordRoot, goalId).plans; if (opts.json) { emit.config({ format: "json" }); emit.data(plans); } else if (plans.length === 0) { emit.text(`governor ${goalId} has no replanning attempts\n`); } else { emit.text(`${plans.map(renderPlanRow).join("\n")}\n`); } }); }); plan .command("show ") .description("Show one planner request, schema-gated proposal, and audit events.") .option("--json", "Emit the complete plan record as JSON") .action((goalId: string, planId: string, opts: { json?: boolean }) => { withGovernorRoot(emit, (coordRoot) => { emitPlan(readGovernorPlan(coordRoot, goalId, planId), opts.json, emit); }); }); plan .command("approve ") .description("Materialize a reviewed proposal and advance the active immutable root.") .option("--actor ", "Actor recorded on the plan decision") .option("--reason ", "Reason for approval") .option("--json", "Emit the plan outcome as JSON") .action( ( goalId: string, planId: string, opts: { actor?: string; reason?: string; json?: boolean }, ) => { withGovernorRoot(emit, (coordRoot) => { emitPlanOutcome( approveGovernorPlan({ coordRoot, goalId, planId, actor: opts.actor, reason: opts.reason, }), opts.json, emit, ); }); }, ); plan .command("reject ") .description("Reject a pending proposal without mutating durable work.") .requiredOption("--reason ", "Reason the proposal is rejected") .option("--actor ", "Actor recorded on the plan decision") .option("--json", "Emit the plan outcome as JSON") .action( ( goalId: string, planId: string, opts: { actor?: string; reason: string; json?: boolean }, ) => { withGovernorRoot(emit, (coordRoot) => { emitPlanOutcome( rejectGovernorPlan({ coordRoot, goalId, planId, actor: opts.actor, reason: opts.reason, }), opts.json, emit, ); }); }, ); plan .command("retry ") .description("Attach bounded guidance and authorize a new attempt after plan attention.") .requiredOption("--reason ", "Guidance for the next planner attempt") .option("--actor ", "Actor recorded on the retry request") .option("--json", "Emit the plan outcome as JSON") .action( ( goalId: string, planId: string, opts: { actor?: string; reason: string; json?: boolean }, ) => { withGovernorRoot(emit, (coordRoot) => { emitPlanOutcome( retryGovernorPlan({ coordRoot, goalId, planId, actor: opts.actor, reason: opts.reason, }), opts.json, emit, ); }); }, ); } function registerServiceCommand( governor: Command, registry: ReturnType, emit: EmitContext, ): void { const service = governor .command("service") .description("Run explicitly enrolled durable goals in a restartable background service."); addServiceOptions( service .command("start [goal-ids...]") .description("Configure and start the detached per-repository governor service."), ) .option("--json", "Emit complete service status as JSON") .action(async (goalIds: string[], opts: ServiceOpts) => { await withGovernorRootAsync(emit, async (coordRoot) => { prepareServiceConfig(coordRoot, goalIds, opts, registry); const status = await spawnGovernorService(coordRoot); emitServiceStatus(status, opts.json, emit); }); }); addServiceOptions( service .command("run [goal-ids...]") .description("Run the persistent service loop in the foreground for a process manager."), ) .option("--json", "Emit terminal service status as JSON") .action(async (goalIds: string[], opts: ServiceOpts) => { await withGovernorRootAsync(emit, async (coordRoot) => { const config = prepareServiceConfig(coordRoot, goalIds, opts, registry); const status = await runGovernorServiceDaemon({ coordRoot, engine: serviceEngine(config, registry), onLog: opts.json ? undefined : (line) => emit.text(`${line}\n`), }); if (opts.json) { emit.config({ format: "json" }); emit.data(status); } }); }); service .command("status") .description("Show service liveness, heartbeat, enrolled goals, and durable wake state.") .option("--json", "Emit complete service status as JSON") .action((opts: { json?: boolean }) => { withGovernorRoot(emit, (coordRoot) => { emitServiceStatus(readGovernorServiceStatus(coordRoot), opts.json, emit); }); }); service .command("stop") .description("Request a graceful stop; an active goal tick is allowed to finish safely.") .option("--json", "Emit complete service status as JSON") .action(async (opts: { json?: boolean }) => { await withGovernorRootAsync(emit, async (coordRoot) => { let status = requestGovernorServiceStop(coordRoot); const deadline = Date.now() + 5_000; while (status.running && Date.now() < deadline) { await delay(50); status = readGovernorServiceStatus(coordRoot); } emitServiceStatus(status, opts.json, emit); }); }); service .command("logs") .description("Show the tail of the private background-service log.") .option("--lines ", "Number of lines to show (default 50)", "50") .action((opts: { lines: string }) => { withGovernorRoot(emit, (coordRoot) => { const lines = integer(opts.lines) ?? 50; if (lines > 10_000) throw new Error("service log lines must not exceed 10000"); const result = readGovernorServiceLogs(coordRoot, { max_bytes: 512 * 1024, max_records: 10_000, }); if (result.lines.length === 0) { emit.text("no governor service log\n"); return; } emit.text(`${result.lines.slice(-lines).join("\n")}\n`); if (result.truncated) emit.log("governor service log read stopped at its bounded budget", "warn"); }); }); service .command("daemon", { hidden: true }) .description("Internal detached service entrypoint.") .action(async () => { await withGovernorRootAsync(emit, async (coordRoot) => { const config = readGovernorServiceConfig(coordRoot); await runGovernorServiceDaemon({ coordRoot, engine: serviceEngine(config, registry), onLog: (line) => emit.text(`${line}\n`), }); }); }); } function addServiceOptions(command: Command): Command { return command .option("--wake-interval-ms ", "State-change poll interval (default 5000)") .option("--heartbeat-interval-ms ", "Heartbeat interval (default 2000)") .option("--error-backoff-base-ms ", "Initial service-error backoff (default 2000)") .option("--error-backoff-max-ms ", "Maximum service-error backoff (default 300000)") .option("--adapter ", "Fallback adapter for agent calls without a specialist") .option("--cwd ", "Working directory for child agents") .option( "--observe-pressure", "Record observer-only local pressure before each workflow's first real child dispatch", ) .option("--subscription-only", "Require stored adapter-login billing") .option("--allow-api-billing", "Permit API-key override billing") .option("--policy ", "Host policy JSON/JSONC") .option("--isolation ", "shared | worktree | sandbox | remote") .option("--approval-to
", "Address durable ASK requests"); } function prepareServiceConfig( coordRoot: string, goalIds: string[], opts: ServiceOpts, registry: ReturnType, ): GovernorServiceConfig { if (goalIds.length === 0) { if (hasServiceConfigOverrides(opts)) { throw new Error("goal ids are required when changing governor service options"); } return readGovernorServiceConfig(coordRoot); } if (opts.adapter && !registry.get(opts.adapter)) { throw new Error(`unknown adapter ${JSON.stringify(opts.adapter)}`); } const policy = opts.policy ? loadPolicyFile(opts.policy) : undefined; return configureGovernorService({ coordRoot, goalIds, wakeIntervalMs: integer(opts.wakeIntervalMs), heartbeatIntervalMs: integer(opts.heartbeatIntervalMs), errorBackoffBaseMs: integer(opts.errorBackoffBaseMs), errorBackoffMaxMs: integer(opts.errorBackoffMaxMs), engine: { default_adapter: opts.adapter, cwd: opts.cwd, subscription_only: opts.subscriptionOnly === true ? true : workflowSubscriptionOnly(coordRoot), allow_api_billing: opts.allowApiBilling, policy, isolation: opts.isolation, approval_addressee: opts.approvalTo, }, }); } function hasServiceConfigOverrides(opts: ServiceOpts): boolean { return Boolean( opts.wakeIntervalMs || opts.heartbeatIntervalMs || opts.errorBackoffBaseMs || opts.errorBackoffMaxMs || opts.adapter || opts.cwd || opts.subscriptionOnly || opts.allowApiBilling || opts.policy || opts.isolation || opts.approvalTo, ); } function serviceEngine( config: GovernorServiceConfig, registry: ReturnType, ) { return { spawners: registry.spawners(), defaultAdapter: config.engine.default_adapter, cwd: config.engine.cwd, subscriptionOnly: config.engine.subscription_only, allowApiBilling: config.engine.allow_api_billing, ...adapterProofInputs( registry.list().map((adapter) => adapter.profile), { versionProbe: probeBinaryVersion }, ), policy: config.engine.policy, approvalMode: "park" as const, approvalAddressee: config.engine.approval_addressee, isolation: config.engine.isolation, networkAccess: "enabled" as const, }; } function emitServiceStatus( status: GovernorServiceStatus, json: boolean | undefined, emit: EmitContext, ): void { if (json) { emit.config({ format: "json" }); emit.data(status); return; } if (!status.config && !status.record) { emit.text("governor service: unconfigured\n"); return; } const state = status.running ? (status.record?.state ?? "running") : status.stale ? "stale" : "stopped"; const lines = [ `governor service: ${state}`, `goals: ${status.config?.goal_ids.join(", ") || "none"}`, ]; if (status.record) { lines.push(`pid: ${status.record.pid} on ${status.record.host}`); lines.push(`heartbeat: ${status.record.heartbeat_at}`); lines.push(`sweeps: ${status.record.sweep_count}`); if (status.record.active_goal_id) lines.push(`active: ${status.record.active_goal_id}`); if (status.record.next_wake_at) lines.push(`next wake: ${status.record.next_wake_at}`); if (status.record.last_error) lines.push(`error: ${status.record.last_error}`); } const backingOff = Object.entries(status.runtime?.goals ?? {}).filter( ([, runtime]) => runtime.state === "backoff", ); if (backingOff.length) { lines.push(`backoff: ${backingOff.map(([goalId]) => goalId).join(", ")}`); } emit.text(`${lines.join("\n")}\n`); } function registerRunCommand( governor: Command, mode: "tick" | "run", registry: ReturnType, emit: EmitContext, ): void { governor .command(`${mode} `) .description( mode === "tick" ? "Perform at most one bounded scheduling cycle." : "Run bounded cycles until success, attention, no progress, or budget exhaustion.", ) .option("--adapter ", "Fallback adapter for agent calls without a specialist") .option("--cwd ", "Working directory for child agents") .option("--subscription-only", "Require stored adapter-login billing") .option("--allow-api-billing", "Permit API-key override billing") .option("--policy ", "Host policy JSON/JSONC") .option("--isolation ", "shared | worktree | sandbox | remote") .option("--approval-to
", "Address durable ASK requests") .option("--actor ", "Actor recorded on governor work decisions") .option("--json", "Emit the complete run report as JSON") .action(async (goalId: string, opts: RunOpts) => { await withGovernorRootAsync(emit, async (coordRoot) => { if (opts.adapter && !registry.get(opts.adapter)) { throw new Error(`unknown adapter ${JSON.stringify(opts.adapter)}`); } const report = await runGovernor({ coordRoot, goalId, mode, actor: opts.actor, onLog: opts.json ? undefined : (line) => emit.text(`${line}\n`), engine: { spawners: registry.spawners(), defaultAdapter: opts.adapter, cwd: opts.cwd, diagnosticAdmission: opts.observePressure ? { schema_version: 1, mode: "shadow" } : undefined, subscriptionOnly: opts.subscriptionOnly === true ? true : workflowSubscriptionOnly(coordRoot), allowApiBilling: opts.allowApiBilling, ...adapterProofInputs( registry.list().map((adapter) => adapter.profile), { versionProbe: probeBinaryVersion }, ), policy: opts.policy ? loadPolicyFile(opts.policy) : undefined, approvalMode: "park", approvalAddressee: opts.approvalTo, isolation: opts.isolation, networkAccess: "enabled", }, }); emitGovernorReport(report, opts.json, emit); }); }); } function readTeamFile(path: string): Record { const absolute = resolve(path); let value: unknown; try { value = JSON.parse(readFileSync(absolute, "utf8")); } catch (error) { throw new Error(`cannot read governor team at ${absolute}: ${(error as Error).message}`); } if (!value || typeof value !== "object" || Array.isArray(value)) { throw new Error("governor team must be a JSON object keyed by specialist id"); } return value as Record; } function readReplanningFile(path: string): CreateGovernorReplanningInput { const absolute = resolve(path); let value: unknown; try { value = JSON.parse(readFileSync(absolute, "utf8")); } catch (error) { throw new Error( `cannot read governor replanning policy at ${absolute}: ${(error as Error).message}`, ); } if (!value || typeof value !== "object" || Array.isArray(value)) { throw new Error("governor replanning policy must be a JSON object"); } const config = value as Record; if (typeof config.planner_specialist !== "string") { throw new Error("governor replanning planner_specialist must be a string"); } if ( !config.templates || typeof config.templates !== "object" || Array.isArray(config.templates) ) { throw new Error("governor replanning templates must be an object"); } const base = dirname(absolute); const templates = Object.fromEntries( Object.entries(config.templates as Record).map(([id, raw]) => { if (!raw || typeof raw !== "object" || Array.isArray(raw)) { throw new Error(`governor replanning template ${id} must be an object`); } const template = raw as Record; if (typeof template.workflow !== "string") { throw new Error(`governor replanning template ${id} workflow must be a string`); } return [ id, { workflowPath: isAbsolute(template.workflow) ? template.workflow : resolve(base, template.workflow), maxAttempts: jsonInteger(template.max_attempts, `template ${id} max_attempts`), root: jsonBoolean(template.root, `template ${id} root`), }, ]; }), ); const review = readReplanningReview(config.review); return { plannerSpecialist: config.planner_specialist, autoApply: jsonBoolean(config.auto_apply, "replanning auto_apply"), maxReplans: jsonInteger(config.max_replans, "replanning max_replans"), maxWorkItemsPerPlan: jsonInteger( config.max_work_items_per_plan, "replanning max_work_items_per_plan", ), maxTotalWorkItems: jsonInteger(config.max_total_work_items, "replanning max_total_work_items"), templates, ...(review ? { review } : {}), }; } function readReplanningReview(raw: unknown): CreateGovernorReplanningInput["review"] | undefined { if (raw === undefined) return undefined; if (!raw || typeof raw !== "object" || Array.isArray(raw)) { throw new Error("governor replanning review must be a JSON object"); } const review = raw as Record; if ( !Array.isArray(review.reviewer_specialists) || review.reviewer_specialists.some((item) => typeof item !== "string") ) { throw new Error("governor replanning review reviewer_specialists must be an array of strings"); } return { reviewerSpecialists: review.reviewer_specialists as string[], maxRevisionRounds: jsonNonNegativeInteger(review.max_revision_rounds, "replanning review max_revision_rounds") ?? 0, }; } function readMissionFile(path: string): CreateGovernorMissionInput { const absolute = resolve(path); let value: unknown; try { value = JSON.parse(readFileSync(absolute, "utf8")); } catch (error) { throw new Error(`cannot read governor mission at ${absolute}: ${(error as Error).message}`); } if (!value || typeof value !== "object" || Array.isArray(value)) { throw new Error("governor mission must be a JSON object"); } const config = value as Record; if (typeof config.objective !== "string") { throw new Error("governor mission objective must be a string"); } if ( !Array.isArray(config.acceptance) || config.acceptance.some((item) => typeof item !== "string") ) { throw new Error("governor mission acceptance must be an array of strings"); } return { objective: config.objective, acceptance: config.acceptance as string[], maxMilestones: jsonInteger(config.max_milestones, "mission max_milestones"), }; } function emitGovernor( record: GovernorRecord, json: boolean | undefined, emit: EmitContext, detail = false, ): void { if (json) { emit.config({ format: "json" }); emit.data(record); return; } if (!detail) { emit.text(`${renderGovernorRow(record)}\n`); return; } const projection = record.projection; const lines = [ `${record.intent.id}: ${record.intent.title}`, `state: ${projection.state}`, `root: ${projection.root_materialized ? projection.root_work_id : "pending initial plan"}`, `reason: ${projection.reason}`, `next: ${projection.next_action}`, `work: ${projection.work_ids.length}`, `attempts: ${projection.attempts_used}/${record.intent.limits.max_total_attempts}`, `specialists: ${projection.specialists.join(", ") || "none"}`, `automation: accept=${record.intent.automation.accept_passing_proof}, ` + `resume=${record.intent.automation.resume_approved}, retry=${record.intent.automation.retry_blocked}`, ]; if (record.intent.replanning) { lines.push( `replanning: generation=${projection.plan_generation}, used=${projection.replans_used}/${record.intent.replanning.max_replans}, auto_apply=${record.intent.replanning.auto_apply}`, ); if (record.intent.replanning.review) { lines.push( `plan review: reviewers=${record.intent.replanning.review.reviewer_specialists.join(", ")}, max_revision_rounds=${record.intent.replanning.review.max_revision_rounds}`, ); } if (projection.root_work_id !== record.intent.root_work_id) { lines.push(`original root: ${record.intent.root_work_id}`); } if (projection.pending_plan_id) lines.push(`pending plan: ${projection.pending_plan_id}`); if (projection.attention_plan_id) { lines.push(`attention plan: ${projection.attention_plan_id}`); } if (projection.replan_consumption && projection.replan_consumption.planner_no_proposal > 0) { lines.push( `replan consumption: planner no-proposal=${projection.replan_consumption.planner_no_proposal}, reviewer rejection=${projection.replan_consumption.reviewer_rejection}`, ); } } if (record.intent.mission) { lines.push(`mission: ${record.intent.mission.objective}`); lines.push( `milestones: ${projection.milestones_completed}/${record.intent.mission.max_milestones}`, ); lines.push(`mission acceptance: ${record.intent.mission.acceptance.length}`); } if (projection.attention_work.length) { lines.push(`attention: ${projection.attention_work.join(", ")}`); } emit.text(`${lines.join("\n")}\n`); } function emitGovernorReport( report: GovernorRunReport, json: boolean | undefined, emit: EmitContext, ): void { if (json) { emit.config({ format: "json" }); emit.data(report); return; } emit.text( `governor ${report.goal_id}: ${report.stop_reason}\n` + `reason: ${report.reason}\n` + `cycles: ${report.cycles}; dispatches: ${report.dispatches}; acceptances: ${report.acceptances}\n` + `replans: ${report.replans}\n` + `state: ${report.projection.state}; next: ${report.projection.next_action}\n`, ); } function renderGovernorRow(record: GovernorRecord): string { const projection = record.projection; const row = `${record.intent.id} ${projection.state.padEnd(20)} ${projection.attempts_used}/${record.intent.limits.max_total_attempts} ${projection.next_action.padEnd(18)} ${record.intent.title}`; const consumption = projection.replan_consumption; if (consumption && consumption.planner_no_proposal > 0) { return `${row} [planner no-proposal x${consumption.planner_no_proposal}]`; } return row; } function integer(value: string | undefined): number | undefined { if (value === undefined) return undefined; if (!/^\d+$/.test(value)) throw new Error(`expected a positive integer, got ${JSON.stringify(value)}`); return Number.parseInt(value, 10); } function jsonInteger(value: unknown, field: string): number | undefined { if (value === undefined) return undefined; if (!Number.isSafeInteger(value) || (value as number) < 1) { throw new Error(`${field} must be a positive integer`); } return value as number; } function jsonNonNegativeInteger(value: unknown, field: string): number | undefined { if (value === undefined) return undefined; if (!Number.isSafeInteger(value) || (value as number) < 0) { throw new Error(`${field} must be a non-negative integer`); } return value as number; } function jsonBoolean(value: unknown, field: string): boolean | undefined { if (value === undefined) return undefined; if (typeof value !== "boolean") throw new Error(`${field} must be boolean`); return value; } function emitPlan(plan: GovernorPlanRecord, json: boolean | undefined, emit: EmitContext): void { if (json) { emit.config({ format: "json" }); emit.data(plan); return; } const lines = [ `${plan.request.id}: ${plan.status}`, `goal: ${plan.request.goal_id}`, `sequence: ${plan.request.sequence}`, `trigger: ${plan.request.trigger ?? "recovery"}`, `prior root: ${plan.request.prior_root_work_id}`, `planner run: ${plan.request.workflow_run_id}`, ]; if (plan.proposal) { lines.push(`decision: ${plan.proposal.decision}`); lines.push(`rationale: ${plan.proposal.rationale}`); lines.push(`proposed work: ${plan.proposal.work.length}`); if (plan.proposal.milestone) { lines.push(`milestone: ${plan.proposal.milestone.sequence} ${plan.proposal.milestone.title}`); } } if (plan.review) { lines.push( `review: ${plan.review.status}, rounds=${plan.review.rounds}, blocking=${plan.review.blocking_findings}, advisory=${plan.review.advisory_findings}`, ); lines.push(`review candidate: ${plan.review.candidate_sha256}`); } if (plan.root_work_id) lines.push(`applied root: ${plan.root_work_id}`); if (plan.approval_id) lines.push(`approval: ${plan.approval_id}`); emit.text(`${lines.join("\n")}\n`); } function emitPlanOutcome( outcome: GovernorPlanOutcome, json: boolean | undefined, emit: EmitContext, ): void { if (json) { emit.config({ format: "json" }); emit.data(outcome); return; } emit.text( `governor plan ${outcome.plan_id}: ${outcome.status}\n` + `${outcome.reason ? `reason: ${outcome.reason}\n` : ""}` + `${outcome.root_work_id ? `root: ${outcome.root_work_id}\n` : ""}`, ); } function renderPlanRow(plan: GovernorPlanRecord): string { const review = plan.review ? ` review:${plan.review.status}` : ""; return `${plan.request.id} ${plan.status.padEnd(18)} ${plan.request.prior_root_work_id}${review}`; } function renderGovernorListWarning(goalId: string, reason: string): string { return `warning ${goalId} unreadable: ${reason}`; } function delay(ms: number): Promise { return new Promise((resolveDelay) => setTimeout(resolveDelay, ms)); } function withGovernorRoot(emit: EmitContext, fn: (coordRoot: string) => void): void { const coordRoot = resolveCoordRoot(); if (!coordRoot) { emit.error({ code: "no_coord_root", message: "no .harnery/ coordination root found; run `init` first", }); emit.setExitCode(1); return; } try { fn(coordRoot); } catch (error) { emit.error({ code: "governor_failed", message: (error as Error).message }); emit.setExitCode(1); } } async function withGovernorRootAsync( emit: EmitContext, fn: (coordRoot: string) => Promise, ): Promise { const coordRoot = resolveCoordRoot(); if (!coordRoot) { emit.error({ code: "no_coord_root", message: "no .harnery/ coordination root found; run `init` first", }); emit.setExitCode(1); return; } try { await fn(coordRoot); } catch (error) { emit.error({ code: "governor_failed", message: (error as Error).message }); emit.setExitCode(1); } }