@staix/agent-hub 0.42.0 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +2 -1
  3. package/docs/adding-an-ai-tool.md +2 -0
  4. package/docs/agent-notes/tasks.md +1 -1
  5. package/docs/agent-notes/tests.md +1 -1
  6. package/docs/design/adapters.md +3 -0
  7. package/docs/design/bus.md +2 -0
  8. package/docs/design/task-board.md +6 -0
  9. package/docs/dogfood.md +5 -1
  10. package/docs/memory.md +5 -3
  11. package/docs/operations.md +64 -4
  12. package/docs/quickstart.md +12 -2
  13. package/docs/sdlc.md +1 -1
  14. package/docs/security.md +1 -1
  15. package/docs/verification/2026-11-18-0.43.0.md +56 -0
  16. package/docs/verified.json +23 -23
  17. package/package.json +2 -2
  18. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  19. package/plugins/agent-hub/kimi-hook.js +307 -117
  20. package/plugins/agent-hub/server.js +307 -117
  21. package/src/adapters/claude-implementer.ts +11 -1
  22. package/src/adapters/claude-print-child.ts +4 -1
  23. package/src/adapters/conformance/fakes/acp-server.ts +2 -1
  24. package/src/adapters/conformance/fakes/app-server.ts +1 -1
  25. package/src/adapters/local-worker.ts +7 -3
  26. package/src/adapters/reviewer-print.ts +3 -1
  27. package/src/cli/help.ts +3 -3
  28. package/src/cli/identity.ts +2 -0
  29. package/src/cli/main.ts +56 -4
  30. package/src/cli/upgrade-output.ts +43 -2
  31. package/src/cli/upgrade-stopped.ts +162 -0
  32. package/src/cli/upgrade-wait.ts +37 -0
  33. package/src/hub/board.ts +4 -2
  34. package/src/hub/config-apply.ts +1 -0
  35. package/src/hub/daemon.ts +75 -13
  36. package/src/hub/envelope.ts +1 -0
  37. package/src/hub/handoff.ts +14 -0
  38. package/src/hub/questions.ts +7 -0
  39. package/src/hub/recovery-store.ts +39 -0
  40. package/src/hub/research-record.ts +2 -1
  41. package/src/hub/runtime-capture-prune.ts +114 -3
  42. package/src/hub/runtime-prune-health.ts +6 -2
  43. package/src/hub/sdlc-metrics.ts +2 -2
  44. package/src/hub/settings.ts +2 -0
  45. package/src/hub/task-sweep.ts +6 -2
  46. package/src/hub/tasks.ts +8 -3
  47. package/src/hub/turn-attribution.ts +46 -0
  48. package/templates/AGENTS.block.md +1 -1
@@ -13,6 +13,7 @@ import { claudeStateFile } from "../hub/claude-state.ts";
13
13
  import { sessionSettings } from "../cli/launch.ts";
14
14
  import { assessVersion, COMPAT } from "./compat.ts";
15
15
  import { OwnedPrintChild, PrintChildCleanupError, type OwnedInputContext, type OwnedInputObserver, type OwnedPrintChildOptions } from "./claude-print-child.ts";
16
+ import { turnAttribution } from "../hub/turn-attribution.ts";
16
17
  import { ClaudeTaskSessions } from "./claude-task-sessions.ts";
17
18
  import { formatClaudeFailure, type ClaudeFailureTrace } from "../hub/claude-failure-stage.ts";
18
19
  import type { PermissionMode } from "../hub/permission-mode.ts";
@@ -52,6 +53,10 @@ export interface ClaudeImplementerOptions {
52
53
  /** Host-owned policy and board reads, never native or model-selected authority. */
53
54
  admit(env: Envelope): boolean;
54
55
  chatTask(): number | undefined;
56
+ /** Host-only schedule provenance; unknown is not an assignment trigger. */
57
+ scheduledTask?(task: number): boolean | undefined;
58
+ /** Host-only privacy and current-owner check for the task-id hint; absent or unknown withholds it. */
59
+ taskHintAllowed?(task: number): boolean;
55
60
  onUsage?(usage: ReviewerPrintUsage, task?: number): void;
56
61
  notify?(message: string): void;
57
62
  /** Test/embedding-only proof port; project configuration cannot select it. */
@@ -243,8 +248,13 @@ export class ClaudeImplementerPeer extends BasePeer {
243
248
  AGENTHUB_INSTANCE_ID: this.options.instanceId, AGENTHUB_LAUNCH_ID: launchId, AGENTHUB_HOOK_PURPOSE: "permission", AGENTHUB_PERMISSION_TOOL: "1" };
244
249
  const mcp = JSON.stringify({ mcpServers: { "agent-hub": { command: process.execPath, args: ["run", this.options.server], env } } });
245
250
  let result = false, failed = false;
251
+ if (!current() || !this.binding?.() || group.envs.some(env => env.private || !this.options.admit(env))) throw new Error("Claude implementer admission changed before child start");
252
+ let taskPrivate = group.task !== undefined;
253
+ try { if (group.task !== undefined) taskPrivate = this.options.taskHintAllowed?.(group.task) !== true; } catch { /* Unknown is private. */ }
254
+ const attribution = turnAttribution(group.envs, { task: group.task, cloud: true, scheduled: this.options.scheduledTask });
255
+ if (taskPrivate) attribution.private = true;
246
256
  const child = new OwnedPrintChild({ peer: this.id, command: this.command!, args: claudeImplementerArgs(turn, mcp, settings, this.options.systemPrompt, model), cwd: this.options.cwd,
247
- input: group.envs.map(frame).join("\n\n"), env, current, stop: this.options.stopChild,
257
+ input: group.envs.map(frame).join("\n\n"), env, attribution, current, stop: this.options.stopChild,
248
258
  onSpawn: () => {
249
259
  try {
250
260
  if (!this.binding?.() || group.envs.some(env => env.private || !this.options.admit(env))) throw new Error("Claude implementer admission changed before child start");
@@ -1,6 +1,7 @@
1
1
  import { spawn, type ChildProcess } from "node:child_process";
2
2
  import { peerChildEnv, stopOwnedProcess, trackGroup } from "../hub/child-process.ts";
3
3
  import type { Envelope } from "../hub/envelope.ts";
4
+ import { applyTurnAttribution, type TurnAttribution } from "../hub/turn-attribution.ts";
4
5
 
5
6
  export interface OwnedInputContext { readonly sessionId: string; readonly inputId: string }
6
7
  export type OwnedInputObserver = (context: OwnedInputContext, envs: readonly Envelope[]) => void;
@@ -12,6 +13,8 @@ export interface OwnedPrintChildOptions {
12
13
  args: readonly string[];
13
14
  cwd: string;
14
15
  env?: NodeJS.ProcessEnv;
16
+ /** Host-derived hints for this child; never native or project configuration authority. */
17
+ attribution?: TurnAttribution;
15
18
  envMode?: "replace";
16
19
  input: string;
17
20
  /** Metadata only: fires after stdin has flushed successfully while the owning generation is current. */
@@ -58,7 +61,7 @@ export class OwnedPrintChild {
58
61
  if (!command) throw new Error("print child command is missing");
59
62
  const child = this.process = spawn(command, [...prefix, ...options.args], {
60
63
  cwd: options.cwd, detached: true,
61
- env: peerChildEnv(options.peer, options.envMode === "replace" ? options.env : { ...process.env, ...options.env }),
64
+ env: applyTurnAttribution(peerChildEnv(options.peer, options.envMode === "replace" ? options.env : { ...process.env, ...options.env }), options.attribution),
62
65
  stdio: ["pipe", "pipe", options.captureStderr ? "pipe" : "ignore"],
63
66
  });
64
67
  // ponytail: 256 KiB per NDJSON frame and 4 MiB stdout by default; raise only with native receipts.
@@ -196,7 +196,8 @@ async function prompt(id: number, text: string) {
196
196
  await sleep(delay);
197
197
  const items = text.split('[agent-hub message from "').length - 1;
198
198
  const memo = text.includes("Shared project memory") ? " +memory" : "";
199
- for (const part of ["echo: ", text.split("\n").at(-1)! + verdict + (items > 1 ? ` (${items} items)` : "") + memo]) {
199
+ const parts = text.includes("FINAL_FYI_TEST_ONLY") ? ["[FYI]"] : ["echo: ", text.split("\n").at(-1)! + verdict + (items > 1 ? ` (${items} items)` : "") + memo];
200
+ for (const part of parts) {
200
201
  send({
201
202
  jsonrpc: "2.0",
202
203
  method: "session/update",
@@ -108,7 +108,7 @@ export function startFakeAppServer(
108
108
  const item = (id: string, phase: string, t: string) =>
109
109
  note("item/completed", { threadId, turnId: turn.id, completedAtMs: Date.now(), item: { type: "agentMessage", id, phase, text: t } });
110
110
  item("m1", "commentary", "thinking out loud");
111
- item("m2", "final_answer", `echo: ${text}${steered.map((s) => ` +steered: ${s}`).join("")}`);
111
+ item("m2", "final_answer", text.includes("FINAL_FYI_TEST_ONLY") ? "[FYI]" : `echo: ${text}${steered.map((s) => ` +steered: ${s}`).join("")}`);
112
112
  // As Codex 0.156 reports it: the thread's running total and what this update added, 100 tokens per turn.
113
113
  threadTotal += 100;
114
114
  note("thread/tokenUsage/updated", { threadId, turnId: turn.id, tokenUsage: { total: usage(threadTotal), last: usage(100) } });
@@ -23,6 +23,7 @@ import { safeModelLabel } from "../omniroute/usage.ts";
23
23
  import { effectiveLocalRoute } from "../hub/routing.ts";
24
24
  import type { ExecutionBudgetDecision } from "../hub/execution-budget.ts";
25
25
  import type { OwnedInputContext, OwnedInputObserver } from "./claude-print-child.ts";
26
+ import { applyTurnAttribution, turnAttribution } from "../hub/turn-attribution.ts";
26
27
  import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
27
28
  import { GUIDANCE_PROBE_MODEL, GUIDANCE_PROBE_SESSION_BYTES, guidanceProbeCanonical, probeHash, probeInteger,
28
29
  type ProbeResourceCharges, type ProbeSlot, type ProbeStoredState } from "../hub/guidance-probes.ts";
@@ -83,6 +84,8 @@ export interface LocalOptions {
83
84
  admitBudget?: (envs: Envelope[], unit: "model_calls" | "tool_calls") => Promise<ExecutionBudgetDecision[]>;
84
85
  /** Per-turn policy from the task the delivery carries: the class's route, and whether it is a PII task. */
85
86
  turnPolicy?: (envs: Envelope[]) => { route?: string; fixedModel?: string; pii: boolean; task?: string } | undefined;
87
+ /** Host-only schedule provenance for a task associated with this turn. */
88
+ scheduledTask?: (task: number) => boolean | undefined;
86
89
  /** Role contract, appended to the system prompt. */
87
90
  preamble?: string;
88
91
  watchdogMs?: number;
@@ -483,7 +486,7 @@ export class LocalPeer extends BasePeer {
483
486
  const fixedPrompt = this.probeConfinement
484
487
  ? this.probeSession?.prepared.request.messages[0]?.content ?? (() => { throw new ProbeLocalError("invalid"); })()
485
488
  : this.turnRecordPrompt(system(this.opts.cwd, this.opts.preamble));
486
- const ctx = this.toolContext(envs, turnSignal, !!policy?.pii, reply);
489
+ const ctx = this.toolContext(envs, turnSignal, !!policy?.pii, reply, policy?.task);
487
490
  let usedTools = false;
488
491
  let captureInvocation = 0;
489
492
  for (let step = 0; step < maxSteps; step++) {
@@ -556,7 +559,7 @@ export class LocalPeer extends BasePeer {
556
559
  /** The base tools, plus `doc_read` and `web_fetch` only when the project opted in (`local.doc_read`, `local.web_fetch.allow`; both off by default). */
557
560
  private toolSchemas() { if (this.probeConfinement) return probeSchemas(); const extra = [...(this.opts.tools.docRead ? [DOC_READ_SCHEMA] : []), ...(this.opts.tools.webFetch ? [WEB_FETCH_SCHEMA] : [])]; return extra.length ? [...TOOL_SCHEMAS, ...extra] : TOOL_SCHEMAS; }
558
561
 
559
- private toolContext(envs: Envelope[], turnSignal: AbortSignal, pii: boolean, reply: EnvelopeOpts): ToolContext {
562
+ private toolContext(envs: Envelope[], turnSignal: AbortSignal, pii: boolean, reply: EnvelopeOpts, task?: string): ToolContext {
560
563
  const executionGeneration=this.turn;
561
564
  const probe = this.probeSession;
562
565
  const context: ToolContext = {
@@ -608,7 +611,8 @@ export class LocalPeer extends BasePeer {
608
611
  },
609
612
  shellExecutionCheck: input=>turnSignal.aborted||executionGeneration!==this.turn?"aborted":this.opts.tools.shellExecutionCheck?.(input)??"valid",
610
613
  sandboxProfile: this.sandboxProfile,
611
- sandboxEnv: this.probeConfinement ? { ...this.probeConfinement.env } : { ...proxyEnv(this.opts.tools.bashNetwork ?? false), AGENTHUB_PEER_ID: this.id },
614
+ sandboxEnv: applyTurnAttribution(this.probeConfinement ? { ...this.probeConfinement.env } : { ...proxyEnv(this.opts.tools.bashNetwork ?? false), AGENTHUB_PEER_ID: this.id },
615
+ this.probeConfinement ? undefined : turnAttribution(envs, { task: task === undefined ? undefined : Number(task), scheduled: this.opts.scheduledTask })) as Record<string, string>,
612
616
  signal: turnSignal,
613
617
  send: (text, to) => {
614
618
  if (this.probeConfinement) return "error: messaging unavailable in guidance probe";
@@ -2,6 +2,7 @@ import type { ModelOverrideSelection } from "./registry-types.ts";
2
2
  import { isNativeModelToken } from "./model-token.ts";
3
3
  import type { ChildProcess } from "node:child_process";
4
4
  import { OwnedPrintChild, PrintChildCleanupError, type OwnedInputContext, type OwnedInputObserver, type OwnedStderrReceipt } from "./claude-print-child.ts";
5
+ import { turnAttribution } from "../hub/turn-attribution.ts";
5
6
  import { randomUUID } from "node:crypto";
6
7
  import { HUB, frame, sanitize } from "../hub/envelope.ts";
7
8
  import { BasePeer } from "../hub/peers.ts";
@@ -555,8 +556,9 @@ export class ReviewerPrintPeer extends BasePeer {
555
556
  // The journal intent precedes spawn: the native agent-file already contains the review facts.
556
557
  this.assertAdmission(env, task, binding);
557
558
  }
559
+ this.assertAdmission(env, task, binding);
558
560
  const child = new OwnedPrintChild({ peer: this.id, command: launch.command, args: launch.args,
559
- cwd: launch.cwd ?? this.opts.cwd, env: launch.env, envMode: launch.envMode, input,
561
+ cwd: launch.cwd ?? this.opts.cwd, env: launch.env, envMode: launch.envMode, input, attribution: turnAttribution([env], { task, cloud: true }),
560
562
  ...(this.opts.backend.failureOnExit ? { captureStderr: true as const } : {}),
561
563
  current: () => generation === this.generation, stop: launch.stop,
562
564
  onInputReleased: () => { inputReleased = true; this.opts.inputReleased?.(inputContext, [env]); },
package/src/cli/help.ts CHANGED
@@ -75,7 +75,7 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
75
75
  ["ahub down", "stop this project's hub, the counterpart of ahub up (same as ahub kill)"],
76
76
  ["ahub reset [--all] [--yes]", "list, then with --yes stop the hub and discard every queued and needs_review delivery, clear holds and pauses and drop session pointers; --all moves the state directory to .agenthub/archive instead"],
77
77
  ["ahub restart [--dry-run] [--yes] [--json] [--verbose] [--color=auto|always|never]", "recover this project's runtime; a configured conductor's --yes requires a same-project, source-issued continuation proof, otherwise run it as the person"],
78
- ["ahub upgrade [--project <path|id>] [--to <version>] [--dry-run] [--yes] [--json] [--verbose] [--color=auto|always|never]", "review and upgrade this selected project (default: current directory; --project selects another); global CLI/plugin updates are separate; --to defaults to latest for interactive review or dry-run, while --yes requires --to <exact-version>; conductor apply needs the same project's supported proof, and a newer-coordinator handoff is person-only"],
78
+ ["ahub upgrade [--project <path|id> | --all-stopped] [--to <version>] [--dry-run] [--yes] [--json] [--verbose] [--color=auto|always|never]", "review and upgrade this selected project (default: current directory; --project selects another); a project whose hub is stopped has only its runtime selection retargeted: no hub, terminal, peer or recovery operation is started; --all-stopped does that for every registered stopped project, each independently (rows: retarget, already at <v>, skipped: running with its per-project command, refused: <cause> with its next step), exits nonzero when a planned retarget fails, and conflicts with --project; global CLI/plugin updates are separate; --to defaults to latest for interactive review or dry-run, while --yes requires --to <exact-version>, and for a running hub waits through a pipe until its recovery operation ends and exits nonzero unless it completed; conductor apply needs the same project's supported proof (a stopped-project retarget is person-only), and a newer-coordinator handoff is person-only"],
79
79
  ["ahub recovery [status|resume|abort] [<operation-id>] [--json] [--color=auto|always|never]", "inspect a preflight; without an id, resume/abort select this project's hold or a retained legacy machine hold; a bare terminal opens the person's screen; only its initiating conductor may continue its own supported restart/upgrade with fresh proof"],
80
80
  ["ahub recovery reattach <operation-id> codex|claude|pi", "person only: repair that blocked peer with its recorded session; leaves the rest for recovery resume"],
81
81
  ["ahub recovery dispose [<operation-id>] --fresh-session codex|claude --reason <text>", "end a partial operation by starting that peer as a new session, recording the lost conversation"],
@@ -106,7 +106,7 @@ const SECTIONS: [string, [usage: string, description: string][]][] = [
106
106
  ["ahub autonomy on [--all-projects] [--yes] | off [--all-projects] | status [--json]", "person only: apply the autonomy preset and machine default with one confirmation, optionally to every registered project; off removes fixed preset keys (manual edits included); status reports modes, floor enforcement and Claude homes; settings undo restores a live-hub project write"],
107
107
  ["ahub model set <peer> <model> | clear <peer> | list [--json]", "person only: select a runtime model at the next turn, clear its override, or inspect effective models and pending changes; unsupported peers need a restart"],
108
108
  ["ahub settings [list] [--json] | get <key> [--json]", "the settings the dashboard can change, each with its value, the file it comes from and when it applies; get sdlc.mode or sdlc.required_checks reads running and file values without adding writable keys"],
109
- ["ahub settings set <key> <value|inherit> [--yes] [--preview] [--now] | undo | reload", "validated settings: conductor set is limited to exact live operational keys; undo/reload and other keys are person only; --preview saves nothing; conductor writes keep the person undo record"],
109
+ ["ahub settings set <key> <value|inherit> [--yes] [--preview] [--now] | undo | reload", "validated settings: memory.sync_interval_min applies live (0 disables sync); conductor set is limited to exact live operational keys; undo/reload and other keys are person only; --preview saves nothing; conductor writes keep the person undo record"],
110
110
  ["ahub settings edit <config.local.json|sdlc.toml> (set <path> <json> | remove <path>)... [--reason <text>] [--preview] [--yes] | backups [--json]", "human only: structural config (instances, review, snapshots, approvals, context.gate, research.runners, sdlc.toml mode and required_checks) validated by the hub's own loaders, previewed as a diff and written with a backup; a key that runs code or locates secrets needs its name typed, never --yes"],
111
111
  ["ahub pause|resume <peer>", "hold a peer's deliveries in its queue / release them"],
112
112
  ["ahub title <peer> <text...>", "person only: replace a Pi or local-worker session title; native-title peers rename in their own UI"],
@@ -385,7 +385,7 @@ export const FLAG_DESCRIPTIONS: Readonly<Record<string, string>> = {
385
385
  "--specs": "turn design specs on", "--no-specs": "turn design specs off", "--spec-review": "how covering specs are reviewed", "--conductor": "the peer that conducts, or none", "--planner": "peers that plan",
386
386
  "--reviewer": "peers that review, or person", "--track-config": "share config.json through git", "--no-track-config": "keep config.json out of git", "--autonomy": "inherit the machine preset, or not",
387
387
  "--shadow": "hub-owned snapshots for a non-git folder", "--release-guard": "install the tag pre-push hook", "--focus": "area the survey looks at", "--review": "review scope: full, delta or none",
388
- "--reviewers": "number of reviewers", "--ci": "CI scope: full, focused or reuse", "--reserved": "reserve the card for this peer", "--unreserve": "clear the card's reservation", "--to": "version to upgrade to",
388
+ "--reviewers": "number of reviewers", "--ci": "CI scope: full, focused or reuse", "--reserved": "reserve the card for this peer", "--unreserve": "clear the card's reservation", "--to": "version to upgrade to", "--all-stopped": "retarget every stopped project's runtime",
389
389
  "--version": "print the installed version",
390
390
  // daemon, agents and recovery
391
391
  "--unattended": "no permission prompts; the agent acts alone", "--no-console": "do not enter the console", "--no-agents": "do not start the default agents", "--panels": "start in panels mode",
@@ -18,6 +18,8 @@ export function liveTestRefusal(command: string, args: readonly string[], contex
18
18
  if (command === "roadmap" && ![undefined, "list", "show", "--json"].includes(args[0])) return true;
19
19
  if (command === "roadmap" && args[0] === "--json" && ![undefined, "list", "show"].includes(args[1])) return true;
20
20
  if (command === "sdlc" && args[0] === "configure") return true;
21
+ // #1540: retargeting a stopped project's runtime or every stopped one is the person's choice of which code runs next; an agent shell must not reach it through `--live-test`.
22
+ if (command === "upgrade" && args.includes("--all-stopped")) return true;
21
23
  if (command === "lineage" && args[0] === "link") return true;
22
24
  if (command === "guidance" && ["create", "withdraw"].includes(args[0] ?? "")) return true;
23
25
  if (command === "sdlc" && args[0] === "survey" && args[1] !== "show") return true;
package/src/cli/main.ts CHANGED
@@ -100,11 +100,13 @@ import { childEnv, personEnv } from "../hub/child-process.ts";
100
100
  import { abortRecovery, createOperation, disposeRecovery, recordRecoveryDelegation, repairedFreshSession, reattachRecovery, liveProjects, nextChoices, nextActionsText, publicOperation, recoveryCommand, registeredProjects, runRecovery, type RecoveryOperation, type Inspection } from "./upgrade.ts";
101
101
  import { endPlannedPeer, makeRecoveryDriver, makeUpgradePlan, preserveSource, reattachPlannedTerminals } from "./upgrade-runtime.ts";
102
102
  import { exactVersion, latestRelease, newerVersion } from "./recovery-package.ts";
103
+ import { applyStoppedRetargets, planStoppedRetargets } from "./upgrade-stopped.ts";
104
+ import { awaitOperationEnd } from "./upgrade-wait.ts";
103
105
  import { globalUpdateAdvice, runtimeVersionWarnings } from "./runtime-version-warning.ts";
104
106
  import { operationScreen, planScreen, type ScreenIO, type UpgradeHost } from "./upgrade-interactive.ts";
105
107
  import { readRecoveryPresentationFlags } from "./upgrade-presentation-flags.ts";
106
108
  import { renderOperation, renderBlocked, renderSummary, type RecoveryPresentationOptions } from "./upgrade-presentation.ts";
107
- import { renderBudgetResult, renderRecoveryStatus, renderUpgradePlan } from "./upgrade-output.ts";
109
+ import { renderBudgetResult, renderRecoveryStatus, renderStoppedPlan, renderStoppedResults, renderUpgradePlan } from "./upgrade-output.ts";
108
110
  import { recordTerminalLaunch, prepareTerminalLaunch, registerTerminalLaunch, type TerminalPeer } from "./terminal-recovery.ts";
109
111
  import { effectiveStartAgents, inheritMachineStart, setupStartAgents, startProjectAgents } from "./start-agents-run.ts";
110
112
  import { ensureMlx, inspectMlx, stopMlx } from "../models/mlx.ts";
@@ -771,11 +773,53 @@ function globalUpdateLines(target: string): string[] {
771
773
  probe: () => spawnSync(DOCTOR_PLUGIN_PROBE.command, [...DOCTOR_PLUGIN_PROBE.argv], { encoding: "utf8", timeout: 10_000 }) });
772
774
  }
773
775
 
776
+ /**
777
+ * #1540: `ahub upgrade` for a project whose hub is stopped (this one, or every registered one with `--all-stopped`): the runtime selection is rewritten and nothing else is started or recorded.
778
+ * True when it handled the command. A single project whose hub is running, or that is not registered, is left to the ordinary recovery plan.
779
+ */
780
+ async function stoppedUpgrade(to: string, all: boolean, display: ReturnType<typeof recoveryDisplay>, yes: boolean, dry: boolean): Promise<boolean> {
781
+ let plan: Awaited<ReturnType<typeof planStoppedRetargets>>;
782
+ try { plan = await planStoppedRetargets(to, all ? "all" : { root: cwd }); } catch (error) { return fail((error as Error).message); }
783
+ // One project whose hub is not positively stopped (or missing) keeps the ordinary plan, with its own blockers; "unknown" is never read as stopped.
784
+ if (!all && !plan.rows.some((row) => row.inspected === "stopped" || row.inspected === "missing")) return false;
785
+ if (display.json) {
786
+ if (!yes || dry) console.log(JSON.stringify(plan, null, 2));
787
+ for (const blocker of plan.blockers) console.error(`ahub: blocker: ${blocker}`);
788
+ } else printRecovery(renderStoppedPlan(plan, VERSION, display.options, yes && !dry));
789
+ if (dry) return true;
790
+ if (plan.blockers.length) fail("plan has blockers; no runtime was changed");
791
+ const retargets = plan.rows.filter((row) => row.outcome === "retarget");
792
+ // Nothing to retarget is still an outcome: a JSON consumer of an idempotent `--yes` run gets the same results document the apply path prints, with no results.
793
+ if (!retargets.length) { if (display.json && yes) console.log(JSON.stringify({ version: plan.version, results: [] }, null, 2)); return true; }
794
+ // The runtime selection decides which code runs a project next: that is the person's choice, as the plan of a running hub is for a conductor only with its source-issued proof.
795
+ if (conductorPeer || delegatedPeer) fail("retargeting a stopped project's runtime is the person's: run it in ahub console or a terminal; no runtime was changed");
796
+ if (!yes) {
797
+ if (!process.stdin.isTTY) fail("review --dry-run and use --yes in non-interactive sessions");
798
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
799
+ try {
800
+ if (!/^(y|yes)$/i.test((await rl.question(`Retarget ${retargets.length} stopped project${retargets.length === 1 ? "" : "s"} without starting ${retargets.length === 1 ? "its hub" : "their hubs"}? [y/N] `)).trim())) return true;
801
+ } finally { rl.close(); }
802
+ const current = await planStoppedRetargets(to, all ? "all" : { root: cwd });
803
+ if (current.fingerprint !== plan.fingerprint) fail("plan changed during review; run the command again");
804
+ }
805
+ const results = await applyStoppedRetargets(plan);
806
+ const failed = results.filter((result) => result.outcome === "failed");
807
+ if (display.json) console.log(JSON.stringify({ version: plan.version, results }, null, 2));
808
+ else {
809
+ printRecovery(renderStoppedResults(results, display.options));
810
+ if (!failed.length) printRecovery(globalUpdateLines(plan.version));
811
+ }
812
+ if (failed.length) fail(`${failed.length} of ${results.length} planned retarget${results.length === 1 ? "" : "s"} failed (${failed.map((result) => result.id).join(", ")}); the others stay retargeted`);
813
+ return true;
814
+ }
815
+
774
816
  async function upgrade(kind: "restart" | "upgrade"): Promise<void> {
775
817
  const display = recoveryDisplay();
776
818
  const { one, rest } = takeFlags(display.args, ["--to"], []);
777
- if (rest.some((a) => !["--dry-run", "--yes"].includes(a)) || (kind === "restart" && one["--to"])) fail("usage: ahub upgrade [--project <path|id>] [--to <version>] [--dry-run] [--yes] | ahub restart [--dry-run] [--yes]");
819
+ if (rest.some((a) => !["--dry-run", "--yes", ...(kind === "upgrade" ? ["--all-stopped"] : [])].includes(a)) || (kind === "restart" && one["--to"])) fail("usage: ahub upgrade [--project <path|id> | --all-stopped] [--to <version>] [--dry-run] [--yes] | ahub restart [--dry-run] [--yes]");
778
820
  const yes = rest.includes("--yes"), dry = rest.includes("--dry-run") || (display.json && !yes);
821
+ const allStopped = rest.includes("--all-stopped");
822
+ if (allStopped && selector !== undefined) fail("--all-stopped and --project are conflicting selectors: --all-stopped covers every registered stopped project");
779
823
  // #272: on a terminal, with neither flag, the plan is reviewed, applied and followed in one session.
780
824
  const interactive = !dry && !yes && humanRecovery(display.json);
781
825
  let to = one["--to"];
@@ -789,7 +833,7 @@ async function upgrade(kind: "restart" | "upgrade"): Promise<void> {
789
833
  // An older CLI must not coordinate a newer target (docs/operations.md): the target's own coordinator takes over.
790
834
  if (conductorPeer && kind === "upgrade" && newerVersion(to!, VERSION)) fail("a supporting target coordinator is required; the person runs it in ahub console or a terminal");
791
835
  if (kind === "upgrade" && newerVersion(to!, VERSION) && process.env.AGENTHUB_UPGRADE_HANDOVER !== "1") {
792
- const argv = ["x", "--package", `@staix/agent-hub@${to}`, "ahub", "--project", cwd, ...liveTestArgs, "upgrade", "--to", to!, ...rest, ...display.flags, ...(dry && !rest.includes("--dry-run") ? ["--dry-run"] : [])];
836
+ const argv = ["x", "--package", `@staix/agent-hub@${to}`, "ahub", ...(allStopped ? [] : ["--project", cwd]), ...liveTestArgs, "upgrade", "--to", to!, ...rest, ...display.flags, ...(dry && !rest.includes("--dry-run") ? ["--dry-run"] : [])];
793
837
  console.error(`ahub: ${to} is newer than this CLI (${VERSION}), so its own coordinator runs the upgrade: bun ${argv.join(" ")}`);
794
838
  if (interactive) {
795
839
  const rl = createInterface({ input: process.stdin, output: process.stdout });
@@ -805,6 +849,7 @@ async function upgrade(kind: "restart" | "upgrade"): Promise<void> {
805
849
  });
806
850
  process.exit(code);
807
851
  }
852
+ if (kind === "upgrade" && await stoppedUpgrade(to!, allStopped, display, yes, dry)) return;
808
853
  if (kind === "upgrade") console.error("ahub: Kimi now defaults to its own TUI (pull-only) in projects without peers.kimi.start_mode. To keep ACP: ahub settings set peers.kimi.start_mode headless");
809
854
  if (interactive) return onTerminal((io) => planScreen(upgradeHost(kind, to ?? VERSION), io), display.options);
810
855
  const plan = await makeUpgradePlan(kind, to ?? VERSION, cwd, undefined, conductorPeer);
@@ -816,7 +861,7 @@ async function upgrade(kind: "restart" | "upgrade"): Promise<void> {
816
861
  if (!jsonApply) console.log(JSON.stringify(plan, null, 2));
817
862
  for (const p of plan.projects) for (const peer of p.reconnectOnly ?? []) console.error(`ahub: ${p.project.id}: ${peer} is reconnect-only (unmanaged session): its plugin reattaches to the new hub; no terminal is closed or relaunched`);
818
863
  for (const p of plan.projects) for (const peer of p.freshStart ?? []) console.error(`ahub: ${p.project.id}: ${peer} restarts as a new session: its thread has no rollout and the hub recorded no turn on it, so nothing is lost`);
819
- } else printRecovery(renderUpgradePlan(plan, VERSION, display.options));
864
+ } else printRecovery(renderUpgradePlan(plan, VERSION, display.options, yes && !dry));
820
865
  const blockers = [...plan.blockers, ...plan.projects.flatMap((p) => p.blockers.map((b) => `${p.project.id}: ${b}`))];
821
866
  if (display.json) for (const blocker of blockers) console.error(`ahub: blocker: ${blocker}`);
822
867
  if (dry) return;
@@ -850,6 +895,13 @@ async function upgrade(kind: "restart" | "upgrade"): Promise<void> {
850
895
  // #718: the upgrade is only scheduled here, but the step is already known: the CLI and the plugin are compared with the daemon this upgrade installs. Never in --json, which stays the raw document.
851
896
  if (kind === "upgrade") printRecovery(globalUpdateLines(plan.version));
852
897
  }
898
+ if (kind === "upgrade" && yes && !process.stdout.isTTY) {
899
+ const ended = await awaitOperationEnd(operation, { read: (id) => readOperation<RecoveryOperation>(id), runner: (id) => recoveryRunner(id), now: Date.now, sleep: Bun.sleep });
900
+ if (ended.phase === "completed") { if (!display.json) console.log(`${kind} to ${plan.version} completed`); return; }
901
+ fail(ended.phase === "blocked" || ended.phase === "cancelled"
902
+ ? `${kind} operation ${operation.id} is ${ended.phase}${ended.error ? `: ${ended.error.split("; next actions: ")[0]}` : ""}; ${nextActionsText(ended)}`
903
+ : `operation ${operation.id} did not finish (its runner stopped, or is still working after the wait limit); ${recoveryCommand(operation, "status")}`);
904
+ }
853
905
  }
854
906
 
855
907
  /** Strict person command: recorded identity only, no session or terminal overrides. */
@@ -9,6 +9,7 @@ import { choiceInstruction, renderBlocked, renderOperation, renderPlan, type Rec
9
9
  import { paint, terminalText, wrap, type Span, type Tone } from "./console-state.ts";
10
10
  import { renderExecutionBudgetStatus } from "./output.ts";
11
11
  import type { NextChoice, RecoveryOperation, UpgradePlan } from "./upgrade.ts";
12
+ import type { StoppedPlan, StoppedResult, StoppedRow } from "./upgrade-stopped.ts";
12
13
 
13
14
  const columnsOf = (options: RecoveryPresentationOptions) => Number.isFinite(options.columns) ? Math.max(2, Math.floor(options.columns)) : 80;
14
15
  const text = (value: string, tone: Tone, options: RecoveryPresentationOptions): string[] =>
@@ -18,19 +19,59 @@ const text = (value: string, tone: Tone, options: RecoveryPresentationOptions):
18
19
  * The plan `restart` or `upgrade` would apply, for a person reading a pipe or a `--dry-run`: the same rows the plan
19
20
  * screen shows (a peer per line with how it runs and what happens to it), every blocker, and what the plan will not do.
20
21
  * Blockers, reconnect-only sessions and fresh starts are part of the rows, so none of them is stderr-only any more.
22
+ * `applying` (#1540 AC9): under `--yes` the plan is the first part of an apply, so the closing line that says nothing was changed and offers `--yes` is left out.
21
23
  */
22
- export function renderUpgradePlan(plan: UpgradePlan, current: string, options: RecoveryPresentationOptions): string[] {
24
+ export function renderUpgradePlan(plan: UpgradePlan, current: string, options: RecoveryPresentationOptions, applying = false): string[] {
23
25
  const out = renderPlan(plan, current, options, planLines(plan, current));
24
26
  const blocked = plan.blockers.length > 0 || plan.projects.some(project => project.blockers.length > 0);
25
27
  if (!plan.projects.length) out.push(...text(plan.kind === "upgrade"
26
28
  ? `No hub is running, so nothing is carried over: ${globalCliUpdateStep(plan.version)}, then \`ahub setup\`.`
27
29
  : "This project's hub is not running: `ahub up` starts it.", "muted", options));
28
- out.push(...text(blocked
30
+ if (blocked || !applying) out.push(...text(blocked
29
31
  ? "Blocked: take the next action each blocker names, then run this again. Nothing was changed."
30
32
  : "Nothing was changed. Apply with `--yes`.", blocked ? "failure" : "muted", options));
31
33
  return out;
32
34
  }
33
35
 
36
+ const stoppedRowText = (plan: StoppedPlan, row: StoppedRow): { text: string; tone: Tone; next?: string } => {
37
+ const single = plan.scope === "project";
38
+ switch (row.outcome) {
39
+ case "retarget": return { text: `${single ? "stopped" : "retarget"}: runtime selection only (${row.from ? `${row.from} to ` : ""}${plan.version})`, tone: "info" };
40
+ case "current": return { text: `already at ${row.from ?? plan.version}`, tone: "muted" };
41
+ case "running": return { text: `skipped: running; its own plan is \`${row.command}\``, tone: "attention" };
42
+ case "refused": return { text: `refused: ${row.cause}`, tone: "failure", ...(row.next ? { next: row.next } : {}) };
43
+ }
44
+ };
45
+
46
+ /**
47
+ * #1540: the plan of `ahub upgrade` for stopped projects (one, or `--all-stopped`): a row per project with its outcome, never a peer. It changes nothing and says what applying does:
48
+ * a runtime selection is written, and no hub, terminal or recovery operation is started.
49
+ */
50
+ export function renderStoppedPlan(plan: StoppedPlan, current: string, options: RecoveryPresentationOptions, applying = false): string[] {
51
+ const out = [...text(`upgrade to ${plan.version}: runtime selection of ${plan.scope === "all-stopped" ? "stopped projects" : "a stopped project"}`, "strong", options), ...text(`Coordinator version ${current}`, "muted", options)];
52
+ if (!plan.rows.length) out.push(...text(plan.scope === "all-stopped" ? "No project is registered." : "This project is not registered.", "muted", options));
53
+ for (const row of plan.rows) {
54
+ const view = stoppedRowText(plan, row);
55
+ out.push(...text(`${row.project.id} ${row.project.root}`, "info", options), ...text(` ${view.text}`, view.tone, options));
56
+ if (view.next) out.push(...text(` next: ${view.next}`, "attention", options));
57
+ }
58
+ const retargets = plan.rows.filter(row => row.outcome === "retarget").length;
59
+ if (retargets) out.push(...text(`Applying writes ${retargets === 1 ? "one runtime selection" : `${retargets} runtime selections`}: no hub is started, no terminal or peer is touched and no recovery operation is recorded.`, "muted", options));
60
+ else if (plan.scope === "all-stopped") out.push(...text("Nothing to retarget.", "muted", options));
61
+ const blocked = plan.blockers.length > 0;
62
+ if (blocked || !applying) out.push(...text(blocked ? "Blocked: take the next action it names, then run this again. Nothing was changed." : retargets ? "Nothing was changed. Apply with `--yes`." : "Nothing was changed.", blocked ? "failure" : "muted", options));
63
+ return out;
64
+ }
65
+
66
+ /** #1540: one line per project of an applied stopped retarget, with the cause of each failure. */
67
+ export function renderStoppedResults(results: readonly StoppedResult[], options: RecoveryPresentationOptions): string[] {
68
+ const out: string[] = [];
69
+ for (const result of results) out.push(...text(result.outcome === "retargeted"
70
+ ? `${result.id}: runtime selection set to ${result.to}${result.from ? ` (was ${result.from})` : ""}; it stays stopped`
71
+ : `${result.id}: not retargeted (${result.cause})`, result.outcome === "retargeted" ? "success" : "failure", options));
72
+ return out;
73
+ }
74
+
34
75
  /**
35
76
  * `ahub recovery status [<id>]`: the receipt's step and projects, then what the person can do about it. A blocked
36
77
  * operation also says what happened, why and what to do, exactly as the coordinator's screen does; the wait and
@@ -0,0 +1,162 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { readControl } from "../hub/control-client.ts";
5
+ import { RecoveryDeferredHubError } from "../hub/deferred-hub.ts";
6
+ import { inspectProject, type ProjectInspection } from "../hub/lifecycle.ts";
7
+ import { canonicalPath, hubHome } from "../hub/project.ts";
8
+ import { recordProjectRuntime } from "../hub/project-runtime.ts";
9
+ import { createProjectRuntimeAccess, projectRuntimeFile, type ProjectRuntimeIdentity, type ProjectRuntimeSelection } from "../hub/project-runtime-state.ts";
10
+ import { recoveryLock } from "../hub/recovery-store.ts";
11
+ import { Registry, type Project } from "../hub/registry.ts";
12
+ import { readRestartSnapshot, restartPath } from "../hub/restart.ts";
13
+ import { processLiveness } from "../pi/process-signature.ts";
14
+ import { exactVersion, newerVersion, registryRelease, runCommand, stageCurrentRuntime, stageRelease, verifyRecoveryTarget, type RunCommand } from "./recovery-package.ts";
15
+ import { registeredProjects } from "./upgrade.ts";
16
+
17
+ /**
18
+ * #1540: `ahub upgrade` for a project whose hub is stopped. It rewrites that project's `runtime.json` to the target and nothing else: no daemon, no terminal, no peer and no recovery
19
+ * operation. The write is `recordProjectRuntime`, the verified-write path every startup uses, under the registry's runtime-capture lock.
20
+ */
21
+ export type StoppedOutcome = "retarget" | "current" | "running" | "refused";
22
+ export interface StoppedRow {
23
+ project: Project;
24
+ outcome: StoppedOutcome;
25
+ /** What inspection read: only `stopped` and `missing` are this module's to plan alone; any other reading belongs to the ordinary recovery plan. */
26
+ inspected: string;
27
+ /** The recorded version, for `retarget` and `current`; absent when the project records no runtime yet. */
28
+ from?: string;
29
+ /** Identity of the recorded selection the plan read, so the apply refuses a record that changed meanwhile. */
30
+ before?: string;
31
+ cause?: string;
32
+ next?: string;
33
+ command?: string;
34
+ }
35
+ export interface StoppedPlan {
36
+ schema: 1;
37
+ kind: "upgrade";
38
+ mode: "runtime-selection";
39
+ scope: "project" | "all-stopped";
40
+ version: string;
41
+ integrity?: string;
42
+ rows: StoppedRow[];
43
+ blockers: string[];
44
+ fingerprint: string;
45
+ }
46
+ export interface StoppedResult { id: string; root: string; outcome: "retargeted" | "failed"; from?: string; to: string; cause?: string }
47
+ export interface StoppedDeps {
48
+ home?: string;
49
+ inspect?: (project: Project) => Promise<ProjectInspection>;
50
+ /** Stage and verify the target once; the default is the same staging a scoped recovery uses. */
51
+ stage?: (version: string, integrity: string, run: RunCommand) => Promise<{ root: string; digest: string }>;
52
+ }
53
+
54
+ const message = (error: unknown): string => (error instanceof Error ? error.message : String(error)).split("\n")[0]!.slice(0, 300);
55
+ const selectionKey = (runtime: ProjectRuntimeIdentity | undefined): string => runtime
56
+ ? JSON.stringify([runtime.version, runtime.root, runtime.digest, runtime.kind, runtime.instanceId]) : "none";
57
+ const fingerprintOf = (plan: Omit<StoppedPlan, "fingerprint">): string => createHash("sha256").update(JSON.stringify({
58
+ scope: plan.scope, version: plan.version, integrity: plan.integrity, blockers: plan.blockers,
59
+ rows: plan.rows.map(row => [row.project.id, row.project.root, row.outcome, row.inspected, row.from, row.before, row.cause]),
60
+ })).digest("hex");
61
+
62
+ async function classify(project: Project, version: string, inspect: NonNullable<StoppedDeps["inspect"]>, home: string): Promise<StoppedRow> {
63
+ let inspected = "unknown";
64
+ const refuse = (cause: string, next: string): StoppedRow => ({ project, outcome: "refused", inspected, cause, next });
65
+ let state: ProjectInspection;
66
+ try { state = await inspect(project); }
67
+ catch (error) { return refuse(`inspection failed: ${message(error)}`, `check \`ahub doctor\`, then run this again`); }
68
+ inspected = state.state;
69
+ if (state.state === "running") return { project, outcome: "running", inspected, command: `ahub --project ${project.id} upgrade --to ${version}` };
70
+ if (state.state === "missing") return refuse("project directory is missing", `restore ${project.root}, or forget the registration with \`ahub projects remove ${project.id}\``);
71
+ // Only a positive reading of "stopped" qualifies: unknown, unavailable, starting, stopping and incompatible are never read as stopped.
72
+ if (state.state !== "stopped") return refuse(`its hub is not verifiably stopped (${state.state}${state.error ? `: ${message(state.error)}` : ""})`, `wait for it to settle or run \`ahub --project ${project.id} status\`, then run this again`);
73
+ if (!existsSync(join(project.root, ".agenthub", "config.json"))) return refuse("project is not initialized", `run \`ahub init\` in ${project.root} first, or forget it with \`ahub projects remove ${project.id}\``);
74
+ // restart.json exists only while a restart snapshot is unreleased (a released one is renamed away); a corrupt one counts too.
75
+ if (existsSync(restartPath(project.stateDir))) {
76
+ let held = "";
77
+ try { held = readRestartSnapshot(project.stateDir, { projectRoot: project.root, projectId: project.id })?.operationId ?? ""; }
78
+ catch (error) { if (!(error instanceof RecoveryDeferredHubError)) throw error; }
79
+ return refuse(held ? `it holds the unreleased restart snapshot of recovery operation ${held}` : "it holds a restart snapshot that cannot be read",
80
+ `start it with \`ahub --project ${project.id} up\` and finish or abort that operation with \`ahub recovery status\`, then run this again`);
81
+ }
82
+ try {
83
+ const owner = recoveryLock(home, project.root);
84
+ if (owner) return refuse(`recovery operation ${owner} holds this project`, `finish it with \`ahub recovery status ${owner}\`, then run this again`);
85
+ } catch (error) { return refuse(`the recovery lock cannot be read: ${message(error)}`, "check `ahub doctor`, then run this again"); }
86
+ let retained: ProjectRuntimeIdentity | undefined;
87
+ try { retained = createProjectRuntimeAccess(project).read(); }
88
+ catch (error) { return refuse(message(error), `inspect ${projectRuntimeFile(project)} (keep it out of git, or remove it), then run this again`); }
89
+ const before = selectionKey(retained);
90
+ if (retained && (retained.version === version || newerVersion(retained.version, version))) return { project, outcome: "current", inspected, from: retained.version, before };
91
+ return { project, outcome: "retarget", inspected, ...(retained ? { from: retained.version } : {}), before };
92
+ }
93
+
94
+ /**
95
+ * Plan the runtime-selection-only retarget of one project (`selection.root`) or of every registered project (`"all"`). Each project is read independently, so one refusal never blocks another.
96
+ * A single project that is not stopped is the caller's business (the ordinary recovery plan); here it reads as `running` or `refused`.
97
+ */
98
+ export async function planStoppedRetargets(version: string, selection: { root: string } | "all", run: RunCommand = runCommand, deps: StoppedDeps = {}): Promise<StoppedPlan> {
99
+ exactVersion(version);
100
+ const home = deps.home ?? hubHome(), inspect = deps.inspect ?? ((project: Project) => inspectProject(project));
101
+ const all = selection === "all";
102
+ const wanted = all ? undefined : canonicalPath(selection.root);
103
+ const projects = registeredProjects(home).filter(project => wanted === undefined || project.root === wanted);
104
+ const rows: StoppedRow[] = [];
105
+ for (const project of projects) rows.push(await classify(project, version, inspect, home));
106
+ const blockers: string[] = [];
107
+ if (!all) {
108
+ if (!rows.length) blockers.push(`project is not registered: ${wanted}`);
109
+ for (const row of rows) if (row.outcome === "refused") blockers.push(`${row.project.id}: ${row.cause}; ${row.next}`);
110
+ }
111
+ const release = rows.some(row => row.outcome === "retarget") ? await registryRelease(version, run) : undefined;
112
+ const body: Omit<StoppedPlan, "fingerprint"> = { schema: 1, kind: "upgrade", mode: "runtime-selection", scope: all ? "all-stopped" : "project", version,
113
+ ...(release ? { integrity: release.integrity } : {}), rows, blockers };
114
+ return { ...body, fingerprint: fingerprintOf(body) };
115
+ }
116
+
117
+ async function defaultStage(version: string, integrity: string, run: RunCommand): Promise<{ root: string; digest: string }> {
118
+ const staged = await stageRelease(version, integrity, run, hubHome(), true);
119
+ return stageCurrentRuntime(staged.root, version);
120
+ }
121
+
122
+ /** The write itself, atomic with its own checks under the registry's runtime-capture lock: a hub that started after planning, a new snapshot, a hold or a changed record refuses. */
123
+ function retargetOne(row: StoppedRow, selection: ProjectRuntimeSelection, home: string): void {
124
+ const access = createProjectRuntimeAccess(row.project); // Git-trust check; callers create it before taking the registry lock
125
+ const registry = new Registry(join(home, "registry.db"));
126
+ try {
127
+ registry.runtimeCaptureLocked(() => {
128
+ const current = registry.get(row.project.id);
129
+ if (!current || current.root !== row.project.root || current.stateDir !== row.project.stateDir) throw new Error("project registration changed; plan again");
130
+ const started = "a hub started for this project after planning; nothing was written";
131
+ if (current.instanceId && processLiveness(current.pid, current.pidSignature) !== "gone") throw new Error(started);
132
+ const control = readControl(current.stateDir);
133
+ if (control && processLiveness(control.pid, control.pidSignature) !== "gone") throw new Error(started);
134
+ if (existsSync(restartPath(current.stateDir))) throw new Error("a restart snapshot appeared after planning; nothing was written");
135
+ const owner = recoveryLock(home, current.root);
136
+ if (owner) throw new Error(`recovery operation ${owner} holds this project; nothing was written`);
137
+ if (selectionKey(access.read()) !== row.before) throw new Error("the recorded runtime changed after planning; plan again");
138
+ // ponytail: a starter that published its pending selection (instance null) but whose daemon has not claimed the registry yet is seen only as an unchanged record; a start marker under the lock would close that window.
139
+ recordProjectRuntime(current, selection, null, registry, access);
140
+ });
141
+ } finally { registry.close(); }
142
+ }
143
+
144
+ /** Apply the `retarget` rows of a plan: stage and verify the target once, then write each project independently. A failed project never stops the others. */
145
+ export async function applyStoppedRetargets(plan: StoppedPlan, run: RunCommand = runCommand, deps: StoppedDeps = {}): Promise<StoppedResult[]> {
146
+ const home = deps.home ?? hubHome();
147
+ const rows = plan.rows.filter(row => row.outcome === "retarget");
148
+ if (!rows.length) return [];
149
+ const failed = (row: StoppedRow, cause: string): StoppedResult => ({ id: row.project.id, root: row.project.root, outcome: "failed", ...(row.from ? { from: row.from } : {}), to: plan.version, cause });
150
+ let selection: ProjectRuntimeSelection;
151
+ try {
152
+ if (!plan.integrity) throw new Error("the plan carries no release identity");
153
+ const target = await (deps.stage ?? defaultStage)(plan.version, plan.integrity, run);
154
+ if (verifyRecoveryTarget("upgrade", target.root, plan.version) !== target.digest) throw new Error("the staged package changed after verification");
155
+ selection = { version: plan.version, root: target.root, digest: target.digest, kind: "upgrade" };
156
+ } catch (error) { return rows.map(row => failed(row, `staging the target failed: ${message(error)}; no runtime was changed`)); }
157
+ return rows.map(row => {
158
+ try { retargetOne(row, selection, home); }
159
+ catch (error) { return failed(row, message(error)); }
160
+ return { id: row.project.id, root: row.project.root, outcome: "retargeted" as const, ...(row.from ? { from: row.from } : {}), to: plan.version };
161
+ });
162
+ }
@@ -0,0 +1,37 @@
1
+ import type { RecoveryOperation } from "./upgrade.ts";
2
+
3
+ export interface OperationWaitPorts {
4
+ read(id: string): RecoveryOperation;
5
+ /** The claimed runner: a pid, "unknown" when it cannot be told, undefined when none holds the claim. */
6
+ runner(id: string): number | "unknown" | undefined;
7
+ now(): number;
8
+ sleep(ms: number): Promise<void>;
9
+ }
10
+
11
+ /** A runner claims and writes within a moment of being spawned; this long without either reads as gone. */
12
+ export const RUNNER_APPEARS_MS = 10_000;
13
+ /**
14
+ * The longest `upgrade --yes` waits for an operation that is still running. A restart waits up to 10 minutes for a quiet hub and each peer restore can wait as long (docs/operations.md), so this is
15
+ * several of those; past it the command fails and names the status command, leaving the operation to its runner.
16
+ * ponytail: a fixed cap; read it from a recovery setting if a longer upgrade needs it.
17
+ */
18
+ export const OPERATION_WAIT_MS = 2 * 60 * 60 * 1000;
19
+
20
+ /**
21
+ * #1540 AC10: wait until a scheduled recovery operation is terminal (completed, cancelled or blocked), so `ahub upgrade --yes; ahub down` no longer races "recovery operation <id> is active".
22
+ * A runner that never shows, or is gone with the receipt still open, returns that open receipt: the caller reads it as a failure, never as success. The receipt is read once more after the runner
23
+ * lets go of its claim, because a runner writes its end state first.
24
+ */
25
+ export async function awaitOperationEnd(operation: Pick<RecoveryOperation, "id" | "updatedAt">, ports: OperationWaitPorts): Promise<RecoveryOperation> {
26
+ const started = ports.now();
27
+ let seen = false;
28
+ for (;;) {
29
+ const op = ports.read(operation.id);
30
+ if (op.phase === "completed" || op.phase === "cancelled" || op.phase === "blocked") return op;
31
+ const runner = ports.runner(operation.id);
32
+ if (runner !== undefined || op.updatedAt !== operation.updatedAt) seen = true;
33
+ if (runner === undefined && (seen || ports.now() - started > RUNNER_APPEARS_MS)) return ports.read(operation.id);
34
+ if (ports.now() - started > OPERATION_WAIT_MS) return op;
35
+ await ports.sleep(250);
36
+ }
37
+ }