@staix/agent-hub 0.52.0 → 0.54.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.
- package/CHANGELOG.md +37 -0
- package/README.md +4 -3
- package/docs/addons/open-code-review.md +3 -6
- package/docs/agent-notes/README.md +1 -1
- package/docs/agent-notes/adapters.md +5 -4
- package/docs/agent-notes/budget.md +2 -2
- package/docs/agent-notes/bus.md +1 -0
- package/docs/agent-notes/daemon.md +6 -5
- package/docs/agent-notes/models.md +1 -1
- package/docs/agent-notes/tasks.md +3 -3
- package/docs/agent-notes/tests.md +4 -4
- package/docs/contracts/companion-cli-v2.json +90 -0
- package/docs/contracts/companion-cli-v3.json +348 -0
- package/docs/design/adapters.md +1 -1
- package/docs/design/agent-hub-architecture.md +8 -5
- package/docs/design/bus.md +1 -1
- package/docs/design/cli-output-inventory.md +4 -2
- package/docs/design/execution-reference.md +1 -1
- package/docs/design/guidance-experiments.md +1 -0
- package/docs/design/guidance-probes.md +1 -0
- package/docs/design/model-routes.md +20 -5
- package/docs/design/roadmap.md +6 -4
- package/docs/design/task-board.md +21 -2
- package/docs/dogfood.md +13 -6
- package/docs/events.md +1 -1
- package/docs/memory.md +2 -2
- package/docs/operations.md +158 -50
- package/docs/quickstart.md +14 -2
- package/docs/security.md +17 -9
- package/docs/specs/2026-09-19-agent-hub-design.md +5 -3
- package/docs/specs/2026-09-19-multi-project-design.md +1 -1
- package/docs/specs/2026-09-20-upgrade-recovery-design.md +24 -0
- package/docs/specs/2026-12-04-arev-adoption-design.md +84 -0
- package/docs/specs/mcp-endpoint.md +15 -4
- package/docs/specs/relay-contract.md +38 -0
- package/docs/verification/2026-12-04-host-shared-receipts.md +43 -0
- package/docs/verification/2026-12-05-0.53.0.md +101 -0
- package/docs/verification/2026-12-05-agy-1.5.24.md +55 -0
- package/docs/verification/2026-12-05-claude-implementer-2.1.337.md +43 -0
- package/docs/verification/2026-12-06-0.54.0.md +76 -0
- package/docs/verification/2026-12-06-codex-0174-reviewer-isolation.md +43 -0
- package/docs/verification/2026-12-06-codex-0174-reviewer-tool-call.md +34 -0
- package/docs/verification/2026-12-06-compat-codex-capabilities-0.174.0.md +25 -0
- package/docs/verification/2026-12-06-compat-pi-1.8.0.md +23 -0
- package/docs/verified.json +38 -29
- package/package.json +9 -3
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/.mcp.json +1 -1
- package/plugins/agent-hub/compat.json +9 -5
- package/plugins/agent-hub/kimi-hook.js +892 -874
- package/plugins/agent-hub/relay-launcher.js +24 -0
- package/plugins/agent-hub/server.js +27271 -25146
- package/src/adapters/acp-session-model.ts +1 -1
- package/src/adapters/acp.ts +5 -4
- package/src/adapters/agy/definition.ts +1 -1
- package/src/adapters/agy/hooks.ts +1 -1
- package/src/adapters/channel-peer.ts +3 -1
- package/src/adapters/claude-channel-evidence.ts +26 -1
- package/src/adapters/claude-channel.ts +27 -30
- package/src/adapters/claude-connection-policy.ts +62 -0
- package/src/adapters/claude-relay.ts +255 -0
- package/src/adapters/codex-review-isolation.ts +1 -2
- package/src/adapters/compat.ts +28 -18
- package/src/adapters/definitions/native-cli-preview-pi.ts +2 -1
- package/src/adapters/definitions/native-config-defaults.ts +1 -1
- package/src/adapters/definitions/native-context.ts +1 -2
- package/src/adapters/definitions/native-factories.ts +4 -1
- package/src/adapters/definitions/native-quota.ts +1 -1
- package/src/adapters/definitions/native-recovery.ts +3 -1
- package/src/adapters/external-modules.ts +2 -2
- package/src/adapters/kimi-review.ts +1 -1
- package/src/adapters/kimi-tui-facts.ts +1 -1
- package/src/adapters/local-worker.ts +3 -3
- package/src/adapters/native-capabilities.ts +1 -1
- package/src/adapters/pi.ts +26 -7
- package/src/adapters/registry-types.ts +2 -0
- package/src/adapters/relay-launcher.ts +27 -0
- package/src/adapters/reviewer-mcp.ts +1 -1
- package/src/cli/agents.ts +20 -8
- package/src/cli/agy-mcp.ts +1 -1
- package/src/cli/claude-profile-hook.ts +1 -1
- package/src/cli/command-table.ts +1 -0
- package/src/cli/commands/agents.ts +18 -1
- package/src/cli/commands/doctor.ts +18 -4
- package/src/cli/commands/launch-line.ts +32 -0
- package/src/cli/commands/status.ts +14 -3
- package/src/cli/help.ts +7 -4
- package/src/cli/identity.ts +1 -1
- package/src/cli/init-roles.ts +1 -1
- package/src/cli/init-settings.ts +1 -1
- package/src/cli/launch-line-plan.ts +82 -0
- package/src/cli/launch-line-project.ts +13 -0
- package/src/cli/main.ts +10 -9
- package/src/cli/pi-steps-warning.ts +14 -0
- package/src/cli/recovery-package.ts +60 -6
- package/src/cli/reset.ts +1 -1
- package/src/cli/shell-quote.ts +1 -3
- package/src/cli/upgrade-interactive.ts +7 -2
- package/src/cli/upgrade-keep-plan.ts +47 -0
- package/src/cli/upgrade-restore-state.ts +1 -1
- package/src/cli/upgrade-runtime.ts +119 -18
- package/src/cli/upgrade.ts +17 -2
- package/src/hub/accounts.ts +8 -4
- package/src/hub/action-class.ts +1 -3
- package/src/hub/adec-triage.ts +105 -0
- package/src/hub/autonomy.ts +1 -1
- package/src/hub/board.ts +3 -27
- package/src/hub/bus.ts +39 -6
- package/src/hub/capabilities.ts +1 -1
- package/src/hub/channel-project-base.ts +46 -0
- package/src/hub/channel-project.ts +21 -46
- package/src/hub/config-apply.ts +1 -1
- package/src/hub/config-edit.ts +1 -1
- package/src/hub/config-tier.ts +1 -1
- package/src/hub/config.ts +2 -2
- package/src/hub/confirmation-matrix.ts +1 -1
- package/src/hub/control/board-messages.ts +415 -0
- package/src/hub/control/dashboard-messages.ts +221 -0
- package/src/hub/control/delivery-messages.ts +356 -0
- package/src/hub/control/dispatch.ts +114 -0
- package/src/hub/control/hub-tool-helpers.ts +243 -0
- package/src/hub/control/hub-tools.ts +147 -0
- package/src/hub/control/native-messages.ts +665 -0
- package/src/hub/control/operations-messages.ts +269 -0
- package/src/hub/control/peer-messages.ts +126 -0
- package/src/hub/control/recovery-messages.ts +391 -0
- package/src/hub/control/recovery-operation.ts +480 -0
- package/src/hub/control/scope.ts +460 -0
- package/src/hub/control/sdlc-messages.ts +373 -0
- package/src/hub/control/task-ops-more.ts +245 -0
- package/src/hub/control/task-ops.ts +553 -0
- package/src/hub/control/ui-actions.ts +241 -0
- package/src/hub/control-write-trace.ts +1 -4
- package/src/hub/daemon.ts +485 -4324
- package/src/hub/delivery-hints.ts +2 -0
- package/src/hub/delivery-journal.ts +17 -6
- package/src/hub/events.ts +2 -1
- package/src/hub/execution-reference.ts +1 -1
- package/src/hub/host.ts +41 -9
- package/src/hub/hub-tools.ts +3 -4
- package/src/hub/invocations.ts +1 -1
- package/src/hub/lifecycle.ts +4 -3
- package/src/hub/mcp-endpoint-serve.ts +4 -3
- package/src/hub/mcp-endpoint.ts +15 -6
- package/src/hub/memory-profile-check.ts +1 -1
- package/src/hub/no-writes.ts +1 -1
- package/src/hub/peers.ts +2 -0
- package/src/hub/pi-exit-policy.ts +27 -0
- package/src/hub/progress.ts +1 -1
- package/src/hub/project-runtime-state.ts +17 -4
- package/src/hub/project-runtime.ts +3 -1
- package/src/hub/protocol-window.ts +1 -1
- package/src/hub/recovery-continuity.ts +3 -3
- package/src/hub/recovery-kept-roster.ts +50 -0
- package/src/hub/review-anchor.ts +13 -181
- package/src/hub/review-brief.ts +78 -28
- package/src/hub/review-findings.ts +15 -193
- package/src/hub/review-ledger.ts +162 -0
- package/src/hub/review-material.ts +3 -3
- package/src/hub/reviewer-pool.ts +4 -2
- package/src/hub/roadmap-issue-states.ts +65 -14
- package/src/hub/roadmap-sync.ts +39 -14
- package/src/hub/routing.ts +9 -0
- package/src/hub/runtime-capture-prune.ts +8 -2
- package/src/hub/runtime-package-assets.ts +3 -0
- package/src/hub/sdlc-release-policy.ts +1 -2
- package/src/hub/settings.ts +1 -1
- package/src/hub/spec-ack-tool.ts +4 -0
- package/src/hub/spec-report-history.ts +36 -0
- package/src/hub/specs.ts +1 -4
- package/src/hub/supervision.ts +33 -6
- package/src/hub/tasks-audit.ts +390 -0
- package/src/hub/tasks-backlog.ts +522 -0
- package/src/hub/tasks-handoff.ts +208 -0
- package/src/hub/tasks-release.ts +257 -0
- package/src/hub/tasks-roadmap.ts +17 -3
- package/src/hub/tasks-specs.ts +672 -0
- package/src/hub/tasks-types.ts +334 -0
- package/src/hub/tasks.ts +286 -1961
- package/src/hub/upgrade-session-contract.ts +11 -0
- package/src/local/probe-sandbox.ts +1 -2
- package/src/local/probe-workspace.ts +1 -1
- package/src/models/route/config.ts +4 -4
- package/src/models/route/decision.ts +18 -10
- package/src/models/route/observation-signals.ts +1 -2
- package/src/models/route/runtime.ts +8 -5
- package/src/npm-artifact.ts +76 -0
- package/src/omniroute/client.ts +6 -0
- package/src/pi/extension.ts +5 -2
- package/src/pi/install.ts +77 -0
- package/src/pi/pin.ts +49 -0
- package/src/primitives.ts +14 -0
- package/src/version.ts +2 -0
- package/templates/adec/README.md +10 -6
- package/templates/config.json +1 -1
- package/templates/specs.block.md +1 -0
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
// #1830 S2d: moved onMessage bodies and their private helpers. The daemon owns all state.
|
|
2
|
+
import { isWsPeer } from "../../adapters/channel-peer.ts";
|
|
3
|
+
import { SESSION_CONTRACT } from "../../version.ts";
|
|
4
|
+
import { configSourceTexts } from "../config-reload.ts";
|
|
5
|
+
import { CONFIG_FILES } from "../config.ts";
|
|
6
|
+
import { RecoveryAuthorityError } from "../recovery-authority.ts";
|
|
7
|
+
import { assertKeptRosterCurrent, readKeptRoster } from "../recovery-kept-roster.ts";
|
|
8
|
+
import { readOperation } from "../recovery-store.ts";
|
|
9
|
+
import { archiveRestartSnapshot, compactRestartBus, removeRestartSnapshot, writeRestartSnapshot } from "../restart.ts";
|
|
10
|
+
import { DEFAULT_REVIEW_GATE, DEFAULT_REVIEW_MAX_MINUTES, DEFAULT_REVIEW_UNKNOWN_QUOTA, reviewerAccountingIntegrity } from "../review-budget.ts";
|
|
11
|
+
import { createHash } from "node:crypto";
|
|
12
|
+
import type { Envelope, PeerId } from "../envelope.ts";
|
|
13
|
+
import type { ConductorRecoveryBinding } from "../recovery-authority.ts";
|
|
14
|
+
import type { RestartSnapshot } from "../restart.ts";
|
|
15
|
+
import type { DaemonScope } from "./scope.ts";
|
|
16
|
+
|
|
17
|
+
export async function recoveryOp(scope: DaemonScope, msg: any, checkCurrent: () => void = () => {}, approvedPrepare?: ConductorRecoveryBinding): Promise<Record<string, unknown>> {
|
|
18
|
+
checkCurrent();
|
|
19
|
+
if (typeof msg.op !== "string" || !["inspect", "prepare", "commit", "abort", "release"].includes(msg.op)) return recoveryError("unknown recovery operation");
|
|
20
|
+
if (typeof msg.expectedInstanceId !== "string" || msg.expectedInstanceId !== scope.instanceId) return recoveryError("expected daemon instance does not match");
|
|
21
|
+
const incompatibleCancellationTarget = () => {
|
|
22
|
+
const ids = scope.board.list().filter(task => task.state === "cancelled").map(task => task.id);
|
|
23
|
+
return ids.length && (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("task_cancel"))
|
|
24
|
+
? `target lacks task_cancel; cancelled tasks: ${ids.map(id => `#${id}`).join(", ")}` : undefined;
|
|
25
|
+
};
|
|
26
|
+
const incompatibleRecoveryTarget = () => {
|
|
27
|
+
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("roadmap")) {
|
|
28
|
+
try { if (scope.board.hasMilestoneState()) return "target lacks roadmap; retained milestones require a supporting daemon; choose a target advertising roadmap"; }
|
|
29
|
+
catch { return "roadmap compatibility is unknown; inspect retained milestone state or choose a supporting target"; }
|
|
30
|
+
}
|
|
31
|
+
// #1622 family 4: a milestone history row that carries instructed provenance throws in a daemon that predates it, so the floor holds only while such a row exists.
|
|
32
|
+
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("roadmap_instructed")) {
|
|
33
|
+
try { if (scope.board.hasInstructedMilestoneHistory()) return "target lacks roadmap_instructed; retained instructed milestone verdicts require a supporting daemon; choose a target advertising roadmap_instructed"; }
|
|
34
|
+
catch { return "roadmap instructed compatibility is unknown; inspect retained milestone history or choose a supporting target"; }
|
|
35
|
+
}
|
|
36
|
+
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("reviewer_quota")) {
|
|
37
|
+
const proof = reviewerQuotaIntegrity(scope);
|
|
38
|
+
let explicit = scope.config.review.gate !== undefined && scope.config.review.gate !== DEFAULT_REVIEW_GATE || scope.config.review.max_minutes !== undefined && scope.config.review.max_minutes !== DEFAULT_REVIEW_MAX_MINUTES || scope.config.review.unknown_quota !== undefined && scope.config.review.unknown_quota !== DEFAULT_REVIEW_UNKNOWN_QUOTA;
|
|
39
|
+
try {
|
|
40
|
+
const texts = configSourceTexts(scope.opts.cwd);
|
|
41
|
+
explicit ||= CONFIG_FILES.some(name => {
|
|
42
|
+
if (texts[name] === null) return false;
|
|
43
|
+
const review = JSON.parse(texts[name]!).review;
|
|
44
|
+
return review && typeof review === "object" && (Object.hasOwn(review, "gate") || Object.hasOwn(review, "max_minutes") || Object.hasOwn(review, "unknown_quota"));
|
|
45
|
+
});
|
|
46
|
+
} catch { return "reviewer quota compatibility is unknown; configuration could not be read"; }
|
|
47
|
+
if (proof.rows || !proof.complete || proof.waits || explicit)
|
|
48
|
+
return "target lacks reviewer_quota; retained accounting, wait deadlines or explicit reviewer quota policy require a supporting daemon";
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("instructed_exact")) {
|
|
52
|
+
try { if (scope.instructionReceipts.mode() === "off") return "target lacks instructed_exact; the retained person-disabled mode requires a supporting daemon"; }
|
|
53
|
+
catch { return "instructed mode compatibility is unknown; choose a supporting daemon"; }
|
|
54
|
+
}
|
|
55
|
+
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("instructed_intent")) {
|
|
56
|
+
try {
|
|
57
|
+
const texts = configSourceTexts(scope.opts.cwd);
|
|
58
|
+
const rawIntent = CONFIG_FILES.some(name => texts[name] !== null && JSON.parse(texts[name]!).instructed?.mode === "intent");
|
|
59
|
+
if (scope.instructionReceipts.hasIntentWitness() || rawIntent) return "target lacks instructed_intent; the retained or configured intent mode requires a supporting daemon";
|
|
60
|
+
}
|
|
61
|
+
catch { return "instructed mode compatibility is unknown; choose a supporting daemon"; }
|
|
62
|
+
}
|
|
63
|
+
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("guidance_probe_live")) {
|
|
64
|
+
try { if (scope.guidanceProbeStore.hasLiveRecords()) return "target lacks guidance_probe_live; retained live guidance probe state requires a supporting daemon"; }
|
|
65
|
+
catch { return "live guidance probe compatibility is unknown; inspect retained probe state or choose a supporting target"; }
|
|
66
|
+
}
|
|
67
|
+
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("guidance_probes")) {
|
|
68
|
+
try { if (scope.guidanceProbeStore.hasRecords()) return "target lacks guidance_probes; retained probe declarations or held work require a supporting daemon; choose a target advertising guidance_probes"; }
|
|
69
|
+
catch { return "guidance probe compatibility is unknown; inspect retained probe state or choose a supporting target"; }
|
|
70
|
+
}
|
|
71
|
+
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("guidance_variants")) {
|
|
72
|
+
try { if (scope.board.hasGuidanceVariants()) return "target lacks guidance_variants; retained immutable variants require a supporting daemon; choose a target advertising guidance_variants"; }
|
|
73
|
+
catch { return "guidance variant compatibility is unknown; inspect retained storage or choose a supporting target"; }
|
|
74
|
+
}
|
|
75
|
+
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("execution_lineage")) {
|
|
76
|
+
try { if (scope.board.hasExecutionReferences()) return "target lacks execution_lineage; retained declared references require a supporting daemon; choose a target advertising execution_lineage"; }
|
|
77
|
+
catch { return "execution reference compatibility is unknown; inspect the retained store or choose a supporting target"; }
|
|
78
|
+
}
|
|
79
|
+
if ((!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("model_overrides")) && scope.modelOverrides.hasRecords()) return "target lacks model_overrides; retained runtime model choices require a supporting daemon; clear them with ahub model clear or choose a supporting target";
|
|
80
|
+
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("visuals")) {
|
|
81
|
+
try {
|
|
82
|
+
if (scope.visuals.hasRecords()) return "target lacks visuals; retained visual records require a supporting daemon; choose a target with visuals";
|
|
83
|
+
if (scope.rawVisualsPresent(scope.opts.cwd)) return "target lacks visuals; explicit visuals configuration requires a supporting daemon; choose a target with visuals or remove the explicit configuration";
|
|
84
|
+
} catch { return "visuals compatibility is unknown; the store or configuration could not be read; inspect them or choose a target with visuals"; }
|
|
85
|
+
}
|
|
86
|
+
if (scope.config.specs.enabled && scope.config.specs.review === "require" && (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("design_specs"))) return "target lacks design_specs; specs.enabled is on and specs.review is require; use a supporting release or explicitly change specs.enabled/specs.review";
|
|
87
|
+
if (scope.board.hasConductorManualState() && (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("conductor_recovery"))) return "target lacks conductor_recovery; open conductor manual-assignment intent cannot be preserved";
|
|
88
|
+
if (scope.allExternalInstanceIds().length && (!Array.isArray(msg.targetFeatures) || !["external_adapter_instances", "external_adapter_modules", "peer_instances"].every(feature => msg.targetFeatures.includes(feature)))) return "target lacks external_adapter_instances or its module/instance prerequisites";
|
|
89
|
+
if (!(msg.op === "inspect" && scope.recoveryPhase === "restored")) for (const id of scope.allExternalInstanceIds()) if (!scope.retainedExternalBinding(id, true)) return "external instance retained binding changed or unavailable";
|
|
90
|
+
const cancelled = incompatibleCancellationTarget();
|
|
91
|
+
if (cancelled) return cancelled;
|
|
92
|
+
if (scope.invocations.countOpen() && (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("invocation"))) return `target lacks invocation; open invocations: ${scope.invocations.countOpen()}`;
|
|
93
|
+
// #1053: an older daemon ignores the `questions` table, so an open question or an answer still owed would be lost silently.
|
|
94
|
+
if (scope.questionStore.hasPending() && (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("questions"))) return "target lacks questions; open questions or owed answers cannot be kept by that daemon; answer or cancel them (ahub status), or use a target release that has the questions feature";
|
|
95
|
+
// #1054: an older daemon ignores the completion tables, so an open run or a completion nobody has seen would be lost silently.
|
|
96
|
+
if (scope.completionStore.hasPending() && (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("completions"))) return `target lacks completions; ${scope.completionStore.openRuns().length ? "open runs cannot be kept by that daemon: let them settle (ahub status), then retry; " : ""}unread results cannot be kept by that daemon: read them (ahub results --read-all), or use a supporting release`;
|
|
97
|
+
if (scope.externalIds.size && (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("external_adapter_modules"))) return "target lacks external_adapter_modules; verified external definitions cannot be preserved by that daemon";
|
|
98
|
+
if (scope.configuredIds.some(id => scope.definitionOf(id)?.start.daemonPort === "configured-print") && (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("configured_print"))) return "target lacks configured_print; print adapter declarations cannot be preserved by that daemon";
|
|
99
|
+
if (scope.configuredIds.length && (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("configured_acp"))) return "target lacks configured_acp; project adapter definitions cannot be preserved by that daemon";
|
|
100
|
+
if (scope.extraIds.length && (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("peer_instances"))) return "target lacks peer_instances; declared instance identities cannot be restored by that daemon";
|
|
101
|
+
if (scope.extraIds.some(id => scope.adapterCatalog.definitionOf(scope.declarations[id]!.kind)?.transport === "claude-channel" && scope.declarations[id]!.roles?.includes("implementer")) && (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("role_stages"))) return "target lacks role_stages; declared Claude implementer authority cannot be restored by that daemon";
|
|
102
|
+
if ((Array.isArray(scope.config.planner) || typeof scope.config.planner === "string" && scope.extraIds.includes(scope.config.planner) || scope.extraIds.some(id => scope.declarations[id]!.roles?.includes("planner")) || scope.board.hasPlannerState())
|
|
103
|
+
&& (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("task_planners"))) return "target lacks task_planners; configured or persisted planner authority cannot be restored by that daemon";
|
|
104
|
+
if (scope.board.releases().some(release => release.train && ["active", "frozen"].includes(release.state)) && (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("release_trains"))) return "target lacks release_trains; active or frozen train safeguards cannot be preserved";
|
|
105
|
+
if ((scope.extraIds.some(id => !!scope.definitionOf(id)?.reviewer) || scope.config.review.pool !== undefined) && (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("reviewer_pool"))) return "target lacks reviewer_pool; fresh review-only variants and pool policy cannot be preserved";
|
|
106
|
+
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("research_records")) {
|
|
107
|
+
if (scope.board.hasResearchState()) return "target lacks research_records; persisted research campaign records require a supporting daemon";
|
|
108
|
+
let namesRunners = false;
|
|
109
|
+
try {
|
|
110
|
+
const texts = configSourceTexts(scope.opts.cwd);
|
|
111
|
+
for (const name of CONFIG_FILES) {
|
|
112
|
+
if (texts[name] === null) continue;
|
|
113
|
+
const raw: unknown = JSON.parse(texts[name]!);
|
|
114
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("invalid configuration");
|
|
115
|
+
const research = (raw as Record<string, unknown>).research;
|
|
116
|
+
if (research !== undefined && (!research || typeof research !== "object" || Array.isArray(research))) throw new Error("invalid research configuration");
|
|
117
|
+
namesRunners ||= research !== undefined && Object.hasOwn(research, "runners");
|
|
118
|
+
}
|
|
119
|
+
} catch { return "research_records compatibility is unknown; configuration could not be read"; }
|
|
120
|
+
// Raw presence matters even for a disabled or ignored shared declaration: an older target parses the unknown key first.
|
|
121
|
+
if (namesRunners) return "target lacks research_records; the project's research.runners cannot be loaded by that daemon";
|
|
122
|
+
}
|
|
123
|
+
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("research_runners")) {
|
|
124
|
+
if (scope.board.hasRunnerReceipts()) return "target lacks research_runners; persisted runner attestations require a supporting daemon";
|
|
125
|
+
try {
|
|
126
|
+
if (scope.config.research.runners !== undefined || scope.rawResearchRunnersPresent(scope.opts.cwd)) return "target lacks research_runners; the project's research.runners requires a supporting daemon";
|
|
127
|
+
} catch { return "research_runners compatibility is unknown; configuration could not be read"; }
|
|
128
|
+
}
|
|
129
|
+
if ((!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("research_dispatch")) && scope.board.hasResearchDispatchState())
|
|
130
|
+
return "target lacks research_dispatch; persisted campaign stop policies and handoffs require a supporting daemon";
|
|
131
|
+
if ((!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("research_dropped_offers")) && scope.board.hasResearchDroppedOffers())
|
|
132
|
+
return "target lacks research_dropped_offers; persisted study re-offers require a supporting daemon";
|
|
133
|
+
// agent-hub#1036: an unsettled delivery that holds a distinct session's message is an envelope with `session: true` and a minted `<peer>~<id>` sender. A target without the feature
|
|
134
|
+
// would read that sender as a peer it does not know and queue a reply to it; this is its own label, so a daemon that has the older floors but not this one is still refused.
|
|
135
|
+
if ((!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("session_identity")) && scope.bus.queueList(undefined, true).some(row => (row.originals as Envelope[]).some(env => env.session === true)))
|
|
136
|
+
return "target lacks session_identity; unsettled deliveries hold messages from distinct sessions that require a supporting daemon";
|
|
137
|
+
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("accepted_delivery_settlement")) {
|
|
138
|
+
let hasTimeoutHolds: boolean;
|
|
139
|
+
try { hasTimeoutHolds = scope.bus.hasAcceptedTimeoutHolds(); }
|
|
140
|
+
catch { return "accepted_delivery_settlement compatibility is unknown; inspect and resolve held rows with ahub queue list/resolve, or choose a target with accepted_delivery_settlement"; }
|
|
141
|
+
if (hasTimeoutHolds) return "target lacks accepted_delivery_settlement; inspect and resolve held rows with ahub queue list/resolve, or choose a target with accepted_delivery_settlement";
|
|
142
|
+
}
|
|
143
|
+
// #604: a handoff row in either direction (a task another project handed us, or one we handed over) needs a target that knows `task_handoff`; without it the origin is silently lost.
|
|
144
|
+
if ((!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("task_handoff")) && scope.board.hasHandoffState())
|
|
145
|
+
return "target lacks task_handoff; stored handoffs require a supporting daemon";
|
|
146
|
+
if ((!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("review_comments")) && scope.board.hasReviewCommentsState())
|
|
147
|
+
return "target lacks review_comments; stored anchored comments require a supporting daemon";
|
|
148
|
+
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("review_observer_input_state")) {
|
|
149
|
+
let heldReviewInput = false;
|
|
150
|
+
try { heldReviewInput = scope.journal.hasReviewInputState(); } catch { return "review observer input compatibility is unknown; retained privacy state could not be read"; }
|
|
151
|
+
const readReviewInputState = (id: PeerId): "clean" | "held" | "unknown" => {
|
|
152
|
+
scope.resetReviewObserverSessionIfChanged(id);
|
|
153
|
+
const current = scope.currentReviewObserverInputs.get(id), pending = scope.pendingReviewObserverInputs.get(id);
|
|
154
|
+
if (current?.held || current?.reviewInputScoped || pending?.held || pending?.reviewInputScoped) return "held";
|
|
155
|
+
try { return scope.journal.reviewInputState(id, scope.reviewObserverStableSessionHash(id)).state; }
|
|
156
|
+
catch { return "unknown"; }
|
|
157
|
+
};
|
|
158
|
+
const relevantPeers = new Set<PeerId>([
|
|
159
|
+
...[...scope.bus.peers].filter(([id, peer]) => !id.includes("@") && peer.state !== "offline" && !!scope.definitionOf(id)).map(([id]) => id),
|
|
160
|
+
...(scope.recoveryPeerSnapshot?.filter(saved => saved.state !== "offline" && !!scope.definitionOf(saved.id)).map(saved => saved.id) ?? []),
|
|
161
|
+
]);
|
|
162
|
+
const states = [...relevantPeers].map(readReviewInputState);
|
|
163
|
+
if (states.includes("unknown")) return "target lacks review_observer_input_state; review input compatibility is unknown and retained privacy state could not be confirmed";
|
|
164
|
+
if (heldReviewInput || states.includes("held")) return "target lacks review_observer_input_state; held review input requires a supporting daemon";
|
|
165
|
+
}
|
|
166
|
+
if ((!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("research_experiments")) && scope.board.hasResearchExperimentState())
|
|
167
|
+
return "target lacks research_experiments; persisted experiment records require a supporting daemon";
|
|
168
|
+
if ((!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("research_comparisons")) && scope.board.hasResearchComparisonState())
|
|
169
|
+
return "target lacks research_comparisons; persisted comparison plans, approvals or protocol context require a supporting daemon";
|
|
170
|
+
if ((!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("research_evidence")) && scope.board.hasResearchEvidenceState())
|
|
171
|
+
return "target lacks research_evidence; choose a daemon advertising research_evidence to preserve persisted links and revisions";
|
|
172
|
+
if ((!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("research_evidence_withdrawal")) && scope.board.hasWithdrawnEvidenceState())
|
|
173
|
+
return "target lacks research_evidence_withdrawal; choose a supporting daemon to preserve withdrawal revisions";
|
|
174
|
+
if ((!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("advisor_surveys")) && scope.board.hasSurveyState())
|
|
175
|
+
return "target lacks advisor_surveys; persisted survey candidates and considered-finding history require a supporting daemon";
|
|
176
|
+
if ((!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("spec_readbacks")) && scope.board.hasSpecReadbacksState())
|
|
177
|
+
return "target lacks spec_readbacks; stored spec read-back requests and reports require a supporting daemon";
|
|
178
|
+
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("project_autonomy")) {
|
|
179
|
+
let needsAutonomy = scope.autonomyConfirmed.size > 0;
|
|
180
|
+
try {
|
|
181
|
+
const texts = configSourceTexts(scope.opts.cwd);
|
|
182
|
+
needsAutonomy ||= CONFIG_FILES.some(name => texts[name] !== null && Object.hasOwn(JSON.parse(texts[name]!), "_autonomy"));
|
|
183
|
+
} catch { return "project autonomy compatibility is unknown; configuration could not be read"; }
|
|
184
|
+
if (needsAutonomy) return "target lacks project_autonomy; project preset metadata and retained mode consent require a supporting daemon";
|
|
185
|
+
}
|
|
186
|
+
// #999 T3: a target without the floor key rejects `action_policy.floor` as an unknown key, so the project would fail to load there. The check is the key's presence in the project's file, true or false:
|
|
187
|
+
// `floor: false` is just as unknown to an older target, and a disabled policy still names it.
|
|
188
|
+
// The raw files decide, not the effective config: a shared `config.json` that names `action_policy.floor` is ignored (the key is machine-local) but an older target's parser rejects it
|
|
189
|
+
// before that rule runs, and a `floor: false` is normalized away. Unreadable files are unknown, never absent.
|
|
190
|
+
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("action_policy_floor")) {
|
|
191
|
+
let namesFloor = scope.config.action_policy?.floor !== undefined;
|
|
192
|
+
try {
|
|
193
|
+
const texts = configSourceTexts(scope.opts.cwd);
|
|
194
|
+
namesFloor ||= CONFIG_FILES.some(name => {
|
|
195
|
+
const policy = texts[name] === null ? undefined : (JSON.parse(texts[name]!) as Record<string, unknown>).action_policy;
|
|
196
|
+
return !!policy && typeof policy === "object" && Object.hasOwn(policy, "floor");
|
|
197
|
+
});
|
|
198
|
+
} catch { return "action_policy_floor compatibility is unknown; configuration could not be read"; }
|
|
199
|
+
if (namesFloor) return "target lacks action_policy_floor; the project's action_policy.floor cannot be loaded by that daemon";
|
|
200
|
+
}
|
|
201
|
+
// #1017: an older target refuses a `cron` or `tz` key in a `schedules` entry ("cron not supported yet"), so the project would not load there. The raw files decide, as for the floor: a calendar
|
|
202
|
+
// entry in either file, even one an ordinary reload would reject, names the key; unreadable files are unknown, never absent.
|
|
203
|
+
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("calendar_schedules")) {
|
|
204
|
+
let namesCalendar = scope.config.schedules.some(entry => entry.cron !== undefined || entry.tz !== undefined);
|
|
205
|
+
try {
|
|
206
|
+
const texts = configSourceTexts(scope.opts.cwd);
|
|
207
|
+
namesCalendar ||= CONFIG_FILES.some(name => {
|
|
208
|
+
const list = texts[name] === null ? undefined : (JSON.parse(texts[name]!) as Record<string, unknown>).schedules;
|
|
209
|
+
return Array.isArray(list) && list.some(entry => !!entry && typeof entry === "object" && (Object.hasOwn(entry, "cron") || Object.hasOwn(entry, "tz")));
|
|
210
|
+
});
|
|
211
|
+
} catch { return "calendar_schedules compatibility is unknown; configuration could not be read"; }
|
|
212
|
+
if (namesCalendar) return "target lacks calendar_schedules; the project's schedules use cron or tz, which that daemon cannot load";
|
|
213
|
+
}
|
|
214
|
+
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("schema_guard"))
|
|
215
|
+
return "target lacks schema_guard; controlled recovery requires a guard-aware runtime";
|
|
216
|
+
return undefined;
|
|
217
|
+
};
|
|
218
|
+
// Preserve lifecycle fences before capability probes; the prepare branch rechecks them after resume capture awaits.
|
|
219
|
+
if (msg.op === "prepare") {
|
|
220
|
+
if (scope.rosterChanging) return recoveryError("roster change is in progress; wait for ahub status before preparing recovery");
|
|
221
|
+
if (scope.requestedPeerStops.size) return recoveryError("peer stop is in progress; wait for ahub status before preparing recovery");
|
|
222
|
+
if (scope.recoveryCommitted) return recoveryError("recovery commit is already in progress");
|
|
223
|
+
}
|
|
224
|
+
const checkTarget = msg.op === "prepare" || msg.op === "commit" || msg.op === "inspect" && msg.targetFeatures !== undefined;
|
|
225
|
+
if (checkTarget) {
|
|
226
|
+
const error = incompatibleRecoveryTarget(); if (error) return recoveryError(error);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
if (msg.op === "inspect" || msg.op === "prepare" || msg.op === "commit") {
|
|
230
|
+
for (const [id, peer] of scope.bus.peers) if (scope.isExternalInstance(id) && (peer.state !== "offline" || peer.pendingOwnedProcess !== false)) return recoveryError("external module has no verified controlled-recovery driver; stop it explicitly and restart with its recorded native session id");
|
|
231
|
+
for (const peer of scope.bus.peers.values()) if (peer.captureResume && peer.state === "idle") {
|
|
232
|
+
try { await peer.captureResume(); checkCurrent(); } catch (error) { return recoveryError((error as Error).message); }
|
|
233
|
+
if (checkTarget) { const error = incompatibleRecoveryTarget(); if (error) return recoveryError(error); }
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
if (msg.op === "inspect" && msg.operationId === undefined) return { t: "recovery", ok: true, recovery: recoveryView(scope) };
|
|
237
|
+
if (typeof msg.operationId !== "string" || msg.operationId.length < 1 || msg.operationId.length > 128) return recoveryError("operationId is required");
|
|
238
|
+
const op = msg.operationId as string;
|
|
239
|
+
if (msg.op === "prepare") {
|
|
240
|
+
if (scope.rosterChanging) return recoveryError("roster change is in progress; wait for ahub status before preparing recovery");
|
|
241
|
+
if (scope.requestedPeerStops.size) return recoveryError("peer stop is in progress; wait for ahub status before preparing recovery");
|
|
242
|
+
if (scope.recoveryCommitted) return recoveryError("recovery commit is already in progress");
|
|
243
|
+
if (scope.recoveryPhase === "released" && scope.recoveryOperationId !== op) {
|
|
244
|
+
scope.recoveryOperationId = undefined;
|
|
245
|
+
scope.recoveryPhase = undefined;
|
|
246
|
+
scope.recoveryPeerSnapshot = undefined;
|
|
247
|
+
scope.keptRoster = undefined;
|
|
248
|
+
}
|
|
249
|
+
if (scope.recoveryOperationId && scope.recoveryOperationId !== op) return recoveryError("another recovery operation is active");
|
|
250
|
+
{ const error = incompatibleRecoveryTarget(); if (error) return recoveryError(error); }
|
|
251
|
+
try {
|
|
252
|
+
if (approvedPrepare) {
|
|
253
|
+
const operation = readOperation<import("../../cli/upgrade.ts").RecoveryOperation>(op);
|
|
254
|
+
const { fingerprint, ...body } = operation.plan;
|
|
255
|
+
const { planFingerprint } = await import("../../cli/upgrade.ts");
|
|
256
|
+
checkCurrent();
|
|
257
|
+
if (scope.rosterChanging || scope.requestedPeerStops.size || scope.recoveryCommitted || scope.recoveryOperationId && scope.recoveryOperationId !== op)
|
|
258
|
+
throw new RecoveryAuthorityError();
|
|
259
|
+
const row = operation.plan.projects.find(item => item.project.id === scope.projectId);
|
|
260
|
+
if (fingerprint !== approvedPrepare.planFingerprint || planFingerprint(body) !== fingerprint ||
|
|
261
|
+
!row || JSON.stringify(row.keptRoster) !== JSON.stringify(msg.keptRoster) ||
|
|
262
|
+
JSON.stringify(operation.plan.targetSessionContract) !== JSON.stringify(msg.targetSessionContract))
|
|
263
|
+
throw new RecoveryAuthorityError();
|
|
264
|
+
}
|
|
265
|
+
const proposed = readKeptRoster(op, msg.keptRoster, msg.targetSessionContract, SESSION_CONTRACT, liveClaudeRecoverySession.bind(undefined, scope));
|
|
266
|
+
if (scope.keptRoster?.operationId === op && (scope.keptRoster.sessions.size !== proposed.sessions.size ||
|
|
267
|
+
[...scope.keptRoster.sessions].some(([id, row]) => proposed.sessions.get(id)?.sessionId !== row.sessionId)))
|
|
268
|
+
return recoveryError("kept Claude roster changed during preparation; abort this operation and run ahub upgrade again");
|
|
269
|
+
scope.keptRoster = proposed;
|
|
270
|
+
} catch (error) { return recoveryError((error as Error).message); }
|
|
271
|
+
scope.recoveryOperationId = op;
|
|
272
|
+
if (!scope.recoveryPhase) scope.recoveryPhase = "preparing";
|
|
273
|
+
armRecoveryLease(scope);
|
|
274
|
+
scope.questionDesk.endWaits(); // #1053: a waiting hub_ask would hold taskOpsInFlight for its whole window; it answers `pending` now and its row stays open for the late path
|
|
275
|
+
scope.recoveryPeerSnapshot ??= Object.values(scope.recoveryPeers());
|
|
276
|
+
scope.budget.setRecoveryHold(true);
|
|
277
|
+
scope.bus.setRecoveryHold(true, Array.isArray(msg.targetFeatures) && msg.targetFeatures.includes("recovery_deferred_hub"));
|
|
278
|
+
await scope.bus.fenceRecovery();
|
|
279
|
+
checkCurrent();
|
|
280
|
+
{ const error = incompatibleRecoveryTarget(); if (error) return recoveryError(error); }
|
|
281
|
+
const blocked = [...scope.bus.peers].filter(([id, peer]) => !id.includes("@") && scope.recoveryBusy(peer)).map(([id]) => id);
|
|
282
|
+
if (!blocked.length && scope.permissions.size === 0 && scope.recoveryReady()) {
|
|
283
|
+
scope.recoveryPeerSnapshot ??= Object.values(scope.recoveryPeers());
|
|
284
|
+
scope.recoveryPhase = "prepared";
|
|
285
|
+
}
|
|
286
|
+
scope.writeStatus();
|
|
287
|
+
return { t: "recovery", ok: true, recovery: { ...recoveryView(scope), ...(blocked.length ? { blockedPeers: blocked } : {}), ...(scope.permissions.size ? { blocked: "pending approvals" } : {}) } };
|
|
288
|
+
}
|
|
289
|
+
if (!scope.recoveryOperationId || scope.recoveryOperationId !== op) return msg.op === "inspect"
|
|
290
|
+
? { t: "recovery", ok: true, recovery: recoveryView(scope) }
|
|
291
|
+
: recoveryError("operation does not match this daemon");
|
|
292
|
+
if (msg.op === "inspect") return { t: "recovery", ok: true, recovery: recoveryView(scope) };
|
|
293
|
+
if (msg.op === "abort") {
|
|
294
|
+
if (scope.recoveryCommitted) return recoveryError("a committed recovery cannot be aborted");
|
|
295
|
+
if (scope.recoveryPhase === "released") return { t: "recovery", ok: true, recovery: recoveryView(scope) };
|
|
296
|
+
scope.bus.setRecoveryHold(false);
|
|
297
|
+
scope.recoveryOperationId = undefined;
|
|
298
|
+
scope.recoveryPhase = undefined;
|
|
299
|
+
scope.recoveryPeerSnapshot = undefined;
|
|
300
|
+
scope.keptRoster = undefined;
|
|
301
|
+
clearTimeout(scope.recoveryLeaseTimer);
|
|
302
|
+
scope.budget.setRecoveryHold(false); scope.tasks.scheduleQueuePressureRecheck(); scope.tasks.refreshReviewerQuotaWaits();
|
|
303
|
+
scope.writeStatus();
|
|
304
|
+
return { t: "recovery", ok: true, aborted: true, recovery: recoveryView(scope) };
|
|
305
|
+
}
|
|
306
|
+
if (msg.op === "commit") {
|
|
307
|
+
try { if (scope.keptRoster?.operationId === op) assertKeptRosterCurrent(scope.keptRoster, liveClaudeRecoverySession.bind(undefined, scope)); }
|
|
308
|
+
catch (error) { return recoveryError((error as Error).message); }
|
|
309
|
+
if ((scope.recoveryPhase !== "prepared" && scope.recoveryPhase !== "preparing") || !scope.recoveryReady()) return recoveryError("recovery is not ready; inspect until peers are idle, approvals are complete and completion checks have finished");
|
|
310
|
+
// Person ruling 2026-10-19: upgrade is excluded from release resource gates; original readiness still binds.
|
|
311
|
+
scope.recoveryPhase = "prepared";
|
|
312
|
+
scope.bus.setRecoveryHold(true, Array.isArray(msg.targetFeatures) && msg.targetFeatures.includes("recovery_deferred_hub"));
|
|
313
|
+
scope.recoveryPeerSnapshot ??= Object.values(scope.recoveryPeers());
|
|
314
|
+
const currentPeers = scope.recoveryPeers();
|
|
315
|
+
const peers = (scope.recoveryPeerSnapshot ?? Object.values(currentPeers)).map((saved) => ({
|
|
316
|
+
...saved,
|
|
317
|
+
queueIds: scope.bus.queueIds(saved.id),
|
|
318
|
+
// Recorded at commit, not prepare: a first turn landing in between flips it (#64).
|
|
319
|
+
...(scope.definitionOf(saved.id)?.session.missingEvidence === "transcript" && saved.sessionId ? { sessionPersisted: scope.claudeTranscriptPersisted(saved.id, saved.sessionId) } : {}),
|
|
320
|
+
}));
|
|
321
|
+
const snapshot: RestartSnapshot = {
|
|
322
|
+
schemaVersion: 1,
|
|
323
|
+
projectRoot: scope.opts.cwd,
|
|
324
|
+
projectId: scope.projectId,
|
|
325
|
+
sourceInstanceId: scope.instanceId,
|
|
326
|
+
operationId: op,
|
|
327
|
+
committedAt: Date.now(),
|
|
328
|
+
bus: compactRestartBus(scope.bus.snapshot()),
|
|
329
|
+
manualPaused: [...scope.manualPaused],
|
|
330
|
+
peers,
|
|
331
|
+
integrity: integrity(scope),
|
|
332
|
+
};
|
|
333
|
+
{ const error = incompatibleRecoveryTarget(); if (error) return recoveryError(error); }
|
|
334
|
+
try { writeRestartSnapshot(scope.opts.stateDir, snapshot); } catch { return recoveryError("could not persist restart state"); }
|
|
335
|
+
scope.recoveryCommitted = true;
|
|
336
|
+
clearTimeout(scope.recoveryLeaseTimer);
|
|
337
|
+
scope.writeStatus();
|
|
338
|
+
// Keep phase prepared in status until the replacement daemon reports restored.
|
|
339
|
+
setTimeout(() => void scope.stop().catch((error) => scope.log(`recovery shutdown incomplete: ${(error as Error).message}`)), 0);
|
|
340
|
+
return { t: "recovery", ok: true, committed: true, recovery: { ...recoveryView(scope), phase: "prepared" } };
|
|
341
|
+
}
|
|
342
|
+
if (msg.op === "release") {
|
|
343
|
+
if (scope.recoveryPhase === "released") {
|
|
344
|
+
scope.bus.setRecoveryHold(false); scope.budget.setRecoveryHold(false); scope.tasks.scheduleQueuePressureRecheck(); scope.tasks.refreshReviewerQuotaWaits();
|
|
345
|
+
return { t: "recovery", ok: true, released: true, recovery: recoveryView(scope) };
|
|
346
|
+
}
|
|
347
|
+
if (scope.recoveryPhase !== "restored") return recoveryError("recovery is not restored");
|
|
348
|
+
await scope.bus.fenceRecovery();
|
|
349
|
+
checkCurrent();
|
|
350
|
+
const current = scope.recoveryPeers();
|
|
351
|
+
const missing = (scope.recoveryPeerSnapshot ?? []).filter((saved) => saved.state !== "offline" && !scope.manualPaused.has(saved.id) && !scope.budget.record(saved.id) && (!current[saved.id] || current[saved.id]!.state === "offline"));
|
|
352
|
+
if (missing.length) return recoveryError(`required peers are not attached: ${missing.map((peer) => peer.id).join(", ")}`);
|
|
353
|
+
if (!scope.recoveryReady()) return recoveryError("required peers or approvals are not ready");
|
|
354
|
+
if (!scope.restored?.integrity || JSON.stringify(scope.restored.integrity) !== JSON.stringify(integrityAs(scope, scope.restored.integrity))) {
|
|
355
|
+
return recoveryError("queue, pause, task board or budget integrity changed during recovery");
|
|
356
|
+
}
|
|
357
|
+
archiveRestartSnapshot(scope.opts.stateDir, op);
|
|
358
|
+
scope.recoveryPhase = "released";
|
|
359
|
+
scope.keptRoster = undefined;
|
|
360
|
+
clearTimeout(scope.recoveryLeaseTimer);
|
|
361
|
+
scope.reconcileGuidanceProbes();
|
|
362
|
+
scope.bus.setRecoveryHold(false);
|
|
363
|
+
scope.budget.setRecoveryHold(false); scope.tasks.scheduleQueuePressureRecheck(); scope.tasks.refreshReviewerQuotaWaits();
|
|
364
|
+
scope.writeStatus();
|
|
365
|
+
return { t: "recovery", ok: true, released: true, recovery: recoveryView(scope) };
|
|
366
|
+
}
|
|
367
|
+
return recoveryError("unknown recovery operation");
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
export const recoveryError = (error: string) => ({ t: "recovery", ok: false, error });
|
|
371
|
+
|
|
372
|
+
const recoveryView = (scope: DaemonScope) => ({
|
|
373
|
+
operationId: scope.recoveryOperationId,
|
|
374
|
+
phase: scope.recoveryPhase,
|
|
375
|
+
ready: scope.recoveryReady(),
|
|
376
|
+
pendingApprovals: scope.permissions.size,
|
|
377
|
+
capabilities: { controlledRestart: true, snapshotSchemaVersion: 1, maxLeaseMs: 10 * 60_000 },
|
|
378
|
+
blockers: [
|
|
379
|
+
...(scope.starting.size ? ["peer startup in progress"] : []),
|
|
380
|
+
...(!scope.budget.recoverySettled ? ["budget transition in progress"] : []),
|
|
381
|
+
...([...scope.bus.peers].filter(([id, peer]) => !id.includes("@") && scope.recoveryBusy(peer)).map(([id]) => `${id} is busy`)),
|
|
382
|
+
...(scope.permissions.size ? ["pending approvals"] : []),
|
|
383
|
+
// #272: the rest of what recoveryReady() waits for, so the upgrade screen can name the wait. Display only.
|
|
384
|
+
...(scope.taskOpsInFlight !== 0 ? ["a task command in flight"] : []),
|
|
385
|
+
...(scope.tasks.checksPending() !== 0 ? ["completion checks queued or running"] : []),
|
|
386
|
+
...(scope.tasks.guidanceProbesPending() !== 0 ? ["guidance probe work in flight"] : []),
|
|
387
|
+
...(scope.mergeReadbackPass ? ["an external merge readback in flight"] : []),
|
|
388
|
+
...(scope.tasks.autoPullsPending() !== 0 ? ["an automatic backlog pull in flight"] : []),
|
|
389
|
+
...(scope.tasks.queuePressureRechecksPending() !== 0 ? ["a queue-pressure assignment recheck in flight"] : []),
|
|
390
|
+
...(scope.tasks.schedulesPending() !== 0 ? ["a scheduled task proposal in flight"] : []),
|
|
391
|
+
...(scope.tasks.studiesPending() !== 0 ? ["a research campaign admission in flight"] : []),
|
|
392
|
+
...(scope.tasks.reviewCommentsPending() !== 0 ? ["a review comment write in flight"] : []),
|
|
393
|
+
...(scope.checkPending.size !== 0 ? ["isolated checks queued or running"] : []),
|
|
394
|
+
...(scope.piCallsInFlight() !== 0 ? ["Pi tool calls in flight"] : []),
|
|
395
|
+
...(scope.releasing ? ["ready tasks being released"] : []),
|
|
396
|
+
...([...scope.bus.peers].filter(([id, peer]) => !id.includes("@") && peer.state !== "busy" && "recoveryReady" in peer && peer.recoveryReady !== true).map(([id, peer]) => !scope.membershipAllowed(id) && peer.form === "tui" ? `${id} is not settled; end the retained ${scope.definitionOf(id)?.displayName ?? id} TUI, then prepare again` : `${id} is not settled`)),
|
|
397
|
+
],
|
|
398
|
+
integrity: { current: integrityAs(scope, scope.restored?.integrity), ...(scope.restored?.integrity ? { expected: scope.restored.integrity } : {}) },
|
|
399
|
+
peers: Object.fromEntries([...(scope.recoveryPeerSnapshot ?? []), ...Object.values(scope.recoveryPeers()).filter((peer) => !(scope.recoveryPeerSnapshot ?? []).some((saved) => saved.id === peer.id))].map((peer) => {
|
|
400
|
+
const now = scope.recoveryPeers()[peer.id];
|
|
401
|
+
const owner = scope.bus.peers.get(peer.id), definition = scope.definitionOf(peer.id);
|
|
402
|
+
const channel = definition?.transport === "claude-channel" && isWsPeer(owner) ? owner : undefined;
|
|
403
|
+
const observation = channel && definition
|
|
404
|
+
? { kind: definition.kind, attached: channel.attached, ...(now?.sessionId === undefined ? {} : { sessionDigest: recoverySessionDigest(now.sessionId) }) } : undefined;
|
|
405
|
+
const visible = scope.recoveryPhase === "restored" || scope.recoveryPhase === "released" ? now ?? { id: peer.id, state: "offline", queueIds: scope.bus.queueIds(peer.id) }
|
|
406
|
+
: now ? { ...peer, ...now, queueIds: now.queueIds } : peer;
|
|
407
|
+
const reported = channel?.reportedClaudeSessionId;
|
|
408
|
+
return [peer.id, { ...visible, ...(observation === undefined ? {} : { observation }),
|
|
409
|
+
...(reported ? { reportedClaudeSessionId: reported } : {}), ...(reported && channel?.claudeRelay ? { claudeRelay: true } : {}) }];
|
|
410
|
+
})),
|
|
411
|
+
});
|
|
412
|
+
|
|
413
|
+
const liveClaudeRecoverySession = (scope: DaemonScope, id: string): string | undefined => scope.claudeLaunchProof.owner(id)?.reportedClaudeSessionId;
|
|
414
|
+
|
|
415
|
+
const armRecoveryLease = (scope: DaemonScope, delayMs = 10 * 60_000, retrying = false): void => {
|
|
416
|
+
if (!retrying) scope.recoveryLeaseRetryLogged = false;
|
|
417
|
+
clearTimeout(scope.recoveryLeaseTimer);
|
|
418
|
+
scope.recoveryLeaseTimer = setTimeout(() => {
|
|
419
|
+
if (!scope.recoveryOperationId || scope.recoveryCommitted || (scope.recoveryPhase !== "preparing" && scope.recoveryPhase !== "prepared")) { scope.recoveryLeaseRetryLogged = false; return; }
|
|
420
|
+
try { scope.bus.setRecoveryHold(false); } catch {
|
|
421
|
+
if (!scope.recoveryLeaseRetryLogged) { scope.recoveryLeaseRetryLogged = true; scope.log("recovery lease release deferred; delivery storage must be restored before abort (retrying every second)"); }
|
|
422
|
+
armRecoveryLease(scope, 1000, true); return;
|
|
423
|
+
}
|
|
424
|
+
scope.recoveryLeaseRetryLogged = false;
|
|
425
|
+
scope.log(`recovery lease expired for ${scope.recoveryOperationId}; hold aborted`);
|
|
426
|
+
scope.recoveryOperationId = undefined;
|
|
427
|
+
scope.recoveryPhase = undefined;
|
|
428
|
+
scope.recoveryPeerSnapshot = undefined;
|
|
429
|
+
scope.keptRoster = undefined;
|
|
430
|
+
scope.budget.setRecoveryHold(false);
|
|
431
|
+
removeRestartSnapshot(scope.opts.stateDir);
|
|
432
|
+
scope.writeStatus();
|
|
433
|
+
}, delayMs);
|
|
434
|
+
scope.recoveryLeaseTimer.unref?.();
|
|
435
|
+
};
|
|
436
|
+
|
|
437
|
+
/** The integrity in the shape `expected` was recorded in: the current one unless only an older shape matches. */
|
|
438
|
+
const integrityAs = (scope: DaemonScope, expected: unknown) => {
|
|
439
|
+
const now = integrity(scope);
|
|
440
|
+
if (!expected || JSON.stringify(expected) === JSON.stringify(now)) return now;
|
|
441
|
+
for (let older = 1; older <= scope.ADDED_COLUMNS.length; older++) {
|
|
442
|
+
const then = integrity(scope, older);
|
|
443
|
+
if (JSON.stringify(expected) === JSON.stringify(then)) return then;
|
|
444
|
+
}
|
|
445
|
+
return now;
|
|
446
|
+
};
|
|
447
|
+
|
|
448
|
+
export const recoverySessionDigest = (id: string | undefined) => id === undefined ? undefined : createHash("sha256").update(id).digest("hex");
|
|
449
|
+
|
|
450
|
+
const integrity = (scope: DaemonScope, older = 0) => {
|
|
451
|
+
const roadmap = scope.board.roadmapIntegrity();
|
|
452
|
+
const queues = Object.fromEntries(Object.keys(scope.bus.snapshot(false).queues).sort().map((id) => [id, scope.bus.queueIds(id)]));
|
|
453
|
+
const boardState = scope.board.list().sort((a, b) => a.id - b.id).map((t) => {
|
|
454
|
+
const row: Record<string, unknown> = { ...t };
|
|
455
|
+
for (const [col, empty] of scope.ADDED_COLUMNS.slice(0, older)) if (JSON.stringify(row[col]) === empty) delete row[col];
|
|
456
|
+
return row;
|
|
457
|
+
});
|
|
458
|
+
const budgetState = scope.budget.persistedPauseDigestRows().sort((a, b) => a.peer.localeCompare(b.peer));
|
|
459
|
+
const research = scope.board.researchIntegrity();
|
|
460
|
+
const researchDispatch = scope.board.researchDispatchIntegrity();
|
|
461
|
+
const researchExperiments = scope.board.researchExperimentsIntegrity();
|
|
462
|
+
const researchComparisons = scope.board.researchComparisonIntegrity();
|
|
463
|
+
const researchRunners = scope.board.runnerReceiptIntegrity();
|
|
464
|
+
const researchEvidence = scope.board.researchEvidenceIntegrity();
|
|
465
|
+
const reviewerQuota = reviewerQuotaIntegrity(scope);
|
|
466
|
+
const advisorSurveys = scope.board.surveyIntegrity();
|
|
467
|
+
const specReadbacks = scope.board.specReadbackIntegrity();
|
|
468
|
+
const guidanceVariants = scope.board.guidanceVariantsIntegrity();
|
|
469
|
+
const guidanceProbes = scope.guidanceProbeStore.integrity();
|
|
470
|
+
const executionReferences = scope.board.executionReferencesIntegrity();
|
|
471
|
+
const reviewComments = scope.board.reviewCommentsIntegrity();
|
|
472
|
+
const modelState = scope.modelOverrides.integrity();
|
|
473
|
+
const visualIntegrity = scope.visuals.integrity();
|
|
474
|
+
if (!Number.isSafeInteger(visualIntegrity.count) || visualIntegrity.count < 0 || !/^[a-f0-9]{64}$/.test(visualIntegrity.digest))
|
|
475
|
+
throw new Error("visual recovery integrity unavailable; inspect the retained store before recovery");
|
|
476
|
+
return { ...(roadmap.milestones || roadmap.links ? { roadmap } : {}), ...(reviewerQuota.rows || !reviewerQuota.complete || reviewerQuota.waits ? { reviewerQuota } : {}), queues, manualPaused: [...scope.manualPaused].sort(), boardDigest: scope.digest(boardState), budgetDigest: scope.digest(budgetState), ...(modelState.count ? { modelOverrides: modelState } : {}), ...(research.campaigns || research.units ? { research } : {}), ...(researchDispatch.activations || researchDispatch.handoffs ? { researchDispatch } : {}), ...(researchExperiments.protocols || researchExperiments.attempts || researchExperiments.events || researchExperiments.observations ? { researchExperiments } : {}), ...(researchComparisons.plans || researchComparisons.approvals || researchComparisons.contexts ? { researchComparisons } : {}), ...(researchRunners.count ? { researchRunners } : {}), ...(researchEvidence.links || researchEvidence.revisions ? { researchEvidence } : {}), ...(advisorSurveys.surveys || advisorSurveys.findings || advisorSurveys.considered ? { advisorSurveys } : {}), ...(specReadbacks.readbacks ? { specReadbacks } : {}), ...(guidanceVariants.experiments || guidanceVariants.variants ? { guidanceVariants } : {}), ...(guidanceProbes.experiments || guidanceProbes.sessions ? { guidanceProbes } : {}), ...(executionReferences.count ? { executionReferences } : {}), ...(reviewComments.comments || reviewComments.packages ? { reviewComments } : {}), ...(visualIntegrity.count ? { visuals: visualIntegrity } : {}), ...(scope.allExternalInstanceIds().length ? { externalBindingsDigest: scope.digest(scope.allExternalInstanceIds().sort().map(id => [id, (scope.externalRefusedRows.has(id) ? scope.externalBindings.get(id) : scope.retainedExternalBinding(id)) ?? null])) } : {}) };
|
|
477
|
+
};
|
|
478
|
+
|
|
479
|
+
const reviewerQuotaIntegrity = (scope: DaemonScope) => ({ ...reviewerAccountingIntegrity(scope.reviewerJournalRows, scope.reviewerJournalComplete),
|
|
480
|
+
waits: scope.board.list().filter(task => task.history.some(row => row.reviewerQuotaWait !== undefined)).length });
|