@staix/agent-hub 0.35.0 → 0.36.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 (104) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +21 -4
  3. package/docs/agent-notes/README.md +60 -0
  4. package/docs/agent-notes/adapters.md +5 -2
  5. package/docs/agent-notes/bus.md +1 -0
  6. package/docs/agent-notes/daemon.md +5 -4
  7. package/docs/agent-notes/models.md +4 -3
  8. package/docs/agent-notes/tasks.md +8 -1
  9. package/docs/agent-notes/tests.md +1 -0
  10. package/docs/design/adapters.md +72 -0
  11. package/docs/design/agent-hub-architecture.md +1 -1
  12. package/docs/design/bus.md +8 -0
  13. package/docs/design/execution-reference.md +171 -11
  14. package/docs/design/guidance-experiments.md +438 -0
  15. package/docs/design/model-routes.md +628 -0
  16. package/docs/design/supervision.md +121 -0
  17. package/docs/design/task-board.md +111 -0
  18. package/docs/dogfood.md +15 -4
  19. package/docs/operations.md +291 -22
  20. package/docs/profiles.md +2 -2
  21. package/docs/quickstart.md +106 -1
  22. package/docs/research.md +4 -2
  23. package/docs/sdlc.md +108 -4
  24. package/docs/security.md +67 -5
  25. package/docs/specs/2026-09-19-agent-hub-design.md +5 -4
  26. package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
  27. package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
  28. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +46 -0
  29. package/docs/verification/2026-11-10-0.36.0.md +59 -0
  30. package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
  31. package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
  32. package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
  33. package/docs/verification/claude-shell-wrapper-native.py +1 -1
  34. package/docs/verified.json +27 -27
  35. package/package.json +1 -1
  36. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  37. package/plugins/agent-hub/kimi-hook.js +1201 -368
  38. package/plugins/agent-hub/server.js +1682 -431
  39. package/src/adapters/claude-channel.ts +7 -4
  40. package/src/adapters/compat.ts +10 -10
  41. package/src/adapters/local-worker.ts +1 -1
  42. package/src/adapters/qwen-dual.ts +324 -44
  43. package/src/cli/guidance.ts +67 -0
  44. package/src/cli/help.ts +10 -3
  45. package/src/cli/identity.ts +10 -3
  46. package/src/cli/init-prompt.ts +15 -2
  47. package/src/cli/init-required-checks.ts +122 -0
  48. package/src/cli/init-settings.ts +10 -4
  49. package/src/cli/init.ts +39 -3
  50. package/src/cli/lineage.ts +78 -0
  51. package/src/cli/main.ts +111 -10
  52. package/src/cli/setup-research.ts +10 -0
  53. package/src/hub/autonomy-defaults.ts +20 -9
  54. package/src/hub/board.ts +346 -4
  55. package/src/hub/build-entry.ts +11 -0
  56. package/src/hub/bus.ts +12 -0
  57. package/src/hub/ci-watch.ts +4 -4
  58. package/src/hub/config-apply.ts +2 -1
  59. package/src/hub/config-trust.ts +1 -0
  60. package/src/hub/control-client.ts +1 -1
  61. package/src/hub/daemon.ts +342 -20
  62. package/src/hub/delivery-hints.ts +4 -2
  63. package/src/hub/delivery-journal.ts +50 -2
  64. package/src/hub/delivery-public.ts +51 -0
  65. package/src/hub/dogfood-profile.ts +8 -4
  66. package/src/hub/execution-lineage-owner.ts +272 -0
  67. package/src/hub/execution-lineage.ts +52 -8
  68. package/src/hub/execution-links.ts +85 -0
  69. package/src/hub/guidance-variants.ts +398 -0
  70. package/src/hub/handoff.ts +1 -0
  71. package/src/hub/hub-tools.ts +43 -2
  72. package/src/hub/manager.ts +44 -2
  73. package/src/hub/memory-policy.ts +2 -2
  74. package/src/hub/peers.ts +1 -1
  75. package/src/hub/planning.ts +1 -1
  76. package/src/hub/progress.ts +24 -7
  77. package/src/hub/restart.ts +13 -0
  78. package/src/hub/roles.ts +26 -0
  79. package/src/hub/routing.ts +4 -1
  80. package/src/hub/sdlc-merge.ts +39 -1
  81. package/src/hub/sdlc-release.ts +1 -1
  82. package/src/hub/sdlc.ts +62 -11
  83. package/src/hub/settings.ts +2 -0
  84. package/src/hub/supervision-proposals.ts +405 -0
  85. package/src/hub/supervision-rules.ts +388 -0
  86. package/src/hub/supervision.ts +2 -0
  87. package/src/hub/task-approval.ts +2 -2
  88. package/src/hub/task-repository.ts +5 -0
  89. package/src/hub/tasks.ts +603 -50
  90. package/src/memory/capture.ts +2 -2
  91. package/src/models/relay.ts +9 -2
  92. package/src/models/route/config.ts +27 -0
  93. package/src/models/route/decision.ts +87 -15
  94. package/src/models/route/relay-selector.ts +8 -7
  95. package/src/models/route/runtime.ts +22 -16
  96. package/src/models/route/stage-diagnostics.ts +22 -0
  97. package/src/models/route/stage-evidence.ts +55 -0
  98. package/src/models/route/stage-fallback.ts +58 -0
  99. package/src/models/route/stage-input.ts +155 -0
  100. package/src/models/route/stage.ts +5 -147
  101. package/src/ui/guidance-panel.ts +156 -0
  102. package/src/ui/guidance-view.ts +43 -0
  103. package/src/ui/lineage-view.ts +34 -0
  104. package/src/ui/plugin.ts +71 -7
@@ -1,3 +1,4 @@
1
+ import { parseGuidanceListQuery, parseGuidanceIdQuery, parseGuidancePageResult, parseGuidanceDiffResult } from "./guidance-variants.ts";
1
2
  import type { ActionMeta, InboxAnswers } from "@staix/agent-console/contract";
2
3
  import { assertExecutableRuntimeRoot } from "./project-runtime-state.ts";
3
4
  import { BACKLOG_SPLIT_SCREEN_TIMEOUT_MS } from "./planning.ts";
@@ -132,7 +133,7 @@ export function projectConsole(options: { registry: Registry; lifecycle: Lifecyc
132
133
  // #1057: the worktree shelf's person actions. The refresh is the one that reads GitHub, so it gets the delivery reads' deadline in its own branch below.
133
134
  const worktreeAction = ["worktree_override_set", "worktree_override_clear", "worktrees_refresh_prs"].includes(String(input.action));
134
135
  // The settings actions (#269) reach the project hub as an ordinary session's: this dashboard opens no settings session.
135
- if (!["snapshot", "send", "pause", "resume", "permit", "propose", "intake", "assign", "backlog_pull", "backlog_return", "planning", "planning_undo", "planner_pull", "backlog_split", "release_new", "release_change", "setting", "setting_undo", "setting_preview", "setting_reload", "model_preview", "model_confirm", "config_edit_preview", "config_edit_apply", "start_peer", "sdlc_queue", "sdlc_release", "result_seen", "results_read_all", "results_unread_last"].includes(String(input.action)) && !worktreeAction) return { ok: false, error: "invalid dashboard action" };
136
+ if (!["snapshot", "send", "pause", "resume", "permit", "supervision", "propose", "intake", "assign", "backlog_pull", "backlog_return", "planning", "planning_undo", "planner_pull", "backlog_split", "release_new", "release_change", "setting", "setting_undo", "setting_preview", "setting_reload", "model_preview", "model_confirm", "config_edit_preview", "config_edit_apply", "start_peer", "sdlc_queue", "sdlc_release", "result_seen", "results_read_all", "results_unread_last"].includes(String(input.action)) && !worktreeAction) return { ok: false, error: "invalid dashboard action" };
136
137
  const visualSelector = input.action === "snapshot" ? visualSnapshotSelector(input) : {};
137
138
  client = await ControlClient.connect(project.stateDir, { role: "console", projectId: project.id, projectRoot: project.root, instanceId: input.instanceId });
138
139
  const deliveryRead = input.action === "sdlc_queue" || input.action === "sdlc_release";
@@ -215,7 +216,48 @@ export function projectConsole(options: { registry: Registry; lifecycle: Lifecyc
215
216
  } catch { return { ok: false, unconfirmed: true as const, text: "Review result is unconfirmed. Refresh and check the task before retrying.", error: "Review result is unconfirmed. Refresh and check the task before retrying." }; }
216
217
  finally { client?.close(); }
217
218
  };
218
- return { list, act, answer, receipt, consoleControl };
219
+ // #1220 T3: the acon provider's execution-lineage read. A port of its own like `answer`, never an `act` action: the
220
+ // dashboard's action list does not grow, so nothing here can link, probe, replay or execute. It sends the control
221
+ // message the console role already owns, answered in-stack by the same Tasks projection the CLI and MCP read.
222
+ const lineageQueryKeys = ["taskId", "attemptId", "root", "task", "cursor", "nodes", "edges", "bytes"] as const;
223
+ const lineage = async (target: { projectId: unknown; instanceId: unknown }, query: Record<string, unknown>) => {
224
+ if (options.stopping?.()) return { ok: false, error: "manager is stopping" };
225
+ const project = typeof target.projectId === "string" ? registry.get(target.projectId) : undefined;
226
+ if (!project) return { ok: false, error: "unknown project" };
227
+ if (typeof target.instanceId !== "string" || !target.instanceId) return { ok: false, error: "expected daemon instance is required" };
228
+ // The hub parses a closed query: an unknown field would refuse every read, so name it here instead.
229
+ if (!query || typeof query !== "object" || Array.isArray(query) || Object.keys(query).some(key => !(lineageQueryKeys as readonly string[]).includes(key))) return { ok: false, error: "invalid lineage query" };
230
+ let client: ControlClient | undefined;
231
+ try {
232
+ client = await ControlClient.connect(project.stateDir, { role: "console", projectId: project.id, projectRoot: project.root, instanceId: target.instanceId });
233
+ const timeoutMs = options.forwardTimeoutMs?.("lineage_show", 10_000) ?? 10_000;
234
+ const result = await client.request({ t: "lineage_show", ...query }, timeoutMs);
235
+ // A read has no effect to confirm: a missed deadline is a read that did not happen.
236
+ if (result.ok === false && result.error === `no answer from the hub within ${Math.round(timeoutMs / 1000)} s`) return { ok: false, error: "the hub did not answer the lineage read in time; refresh and retry" };
237
+ const { rid: _transportId, ...reply } = result;
238
+ return reply;
239
+ } catch (error) { return { ok: false, error: safeError(error) }; }
240
+ finally { client?.close(); }
241
+ };
242
+ /** Producer-only read port; never forwards an action, actor or person-metadata claim. */
243
+ const guidance = async (target: { projectId: unknown; instanceId: unknown }, op: "list" | "show", input: unknown) => {
244
+ if (options.stopping?.()) return { ok: false, error: "guidance read is unavailable while the manager stops; reconnect before retrying" };
245
+ if (op !== "list" && op !== "show") return { ok: false, error: "guidance console is read-only; use the authorized CLI/MCP for mutations" };
246
+ const project = typeof target.projectId === "string" ? registry.get(target.projectId) : undefined;
247
+ if (!project || typeof target.instanceId !== "string" || !target.instanceId) return { ok: false, error: "select a running project and current instance before reading guidance" };
248
+ let query; try { query = op === "list" ? parseGuidanceListQuery(input) : parseGuidanceIdQuery(input); }
249
+ catch { return { ok: false, error: "invalid guidance query; select the task epoch and existing variant id or cursor" }; }
250
+ let client: ControlClient | undefined;
251
+ try {
252
+ client = await ControlClient.connect(project.stateDir, { role: "console", projectId: project.id, projectRoot: project.root, instanceId: target.instanceId });
253
+ if (!client.features.includes("guidance_views")) return { ok: false, error: "running hub lacks guidance_views; upgrade and restart the hub before reading guidance" };
254
+ const result = await client.request({ t: op === "list" ? "guidance_list" : "guidance_show", ...query }, options.forwardTimeoutMs?.(`guidance_${op}`, 10_000) ?? 10_000);
255
+ if (result.ok !== true) return { ok: false, error: "guidance read is unavailable; refresh the task scope and current daemon before retrying" };
256
+ return { ok: true, guidance: op === "list" ? parseGuidancePageResult(result.guidance, query) : parseGuidanceDiffResult(result.guidance, query) };
257
+ } catch { return { ok: false, error: "guidance read is unavailable; refresh the task scope or upgrade the hub before retrying" }; }
258
+ finally { client?.close(); }
259
+ };
260
+ return { list, act, answer, receipt, consoleControl, lineage, guidance };
219
261
  }
220
262
 
221
263
  export async function startManager(options: ManagerOptions = {}): Promise<ManagerHandle> {
@@ -60,7 +60,7 @@ export function promotionScreen(
60
60
 
61
61
 
62
62
  /** Host-only review capsules retain bodies for recipients, never observer sinks or capture. */
63
- export function isTrustedReviewPackage(env: Envelope): boolean {
63
+ export function isTrustedReviewPackage(env: Pick<Envelope, "from" | "kind" | "refs">): boolean {
64
64
  return env.from === HUB && env.kind === "review" && typeof env.refs?.reviewPackage === "string"
65
65
  && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(env.refs.reviewPackage);
66
66
  }
@@ -80,7 +80,7 @@ export function reviewCaptureExcluded(tool: string, args: string): boolean {
80
80
 
81
81
 
82
82
  /** reviewResponse is stamped by Bus from delivered-parent provenance, never peer refs. */
83
- export function isReviewObserverExcluded(env: Envelope): boolean {
83
+ export function isReviewObserverExcluded(env: Pick<Envelope, "from" | "kind" | "refs">): boolean {
84
84
  return isTrustedReviewPackage(env) || env.from !== HUB && env.from !== "user" && (env.kind === "chat" || env.kind === "status")
85
85
  && typeof env.refs?.reviewResponse === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(env.refs.reviewResponse);
86
86
  }
package/src/hub/peers.ts CHANGED
@@ -101,7 +101,7 @@ export interface PeerAdapter {
101
101
  /** Fixed-builtin native proof only; present undefined is unknown, not an absent proxy. */
102
102
  readonly frontendProxy?: FrontendProxyPort;
103
103
  /** Fixed operator notices from builtin native adapters, never provider text or native ids. */
104
- readonly statusNotice?: { code: "unidentified-cancellation" | "qwen-detached" | "qwen-stalled" | "jcode-headless-after-recovery"; message: string };
104
+ readonly statusNotice?: { code: "unidentified-cancellation" | "qwen-detached" | "qwen-stalled" | "qwen-deny-quiescence" | "jcode-headless-after-recovery"; message: string };
105
105
  /** Fixed builtins with session.nativeRevert only. Native conversation effects remain in the adapter. */
106
106
  revertTurn?(nativeTurn: string): Promise<void>;
107
107
  /** #445 C1: what this peer's native source lists right now (a probed version only), or an empty manifest. Never throws for an unprobed version; a transport failure rejects. */
@@ -77,7 +77,7 @@ export function planningPatch(input: unknown = {}): PlanningPatch {
77
77
  /** Structured lifecycle events only, including reviewerless approval via done. */
78
78
  export function actualTaskDates(task: Pick<Task, "history" | "state" | "reviewer">) {
79
79
  const first = (events: readonly string[]) => task.history.find(entry => events.includes(entry.event))?.at ?? null;
80
- const approved = first(["approved"]), reviewed = task.reviewer !== null || task.history.some(entry => entry.event === "approved" || entry.event === "changes_requested");
80
+ const approved = first(["approved", "merged outside the hub"]), reviewed = task.reviewer !== null || task.history.some(entry => entry.event === "approved" || entry.event === "changes_requested");
81
81
  const reviewerlessDone = task.state === "approved" && !task.reviewer ? [...task.history].reverse().find(entry => entry.event === "done")?.at ?? null : null;
82
82
  return { startedAt: first(["accepted"]), reviewAt: reviewed ? first(["done"]) : null, doneAt: approved ?? reviewerlessDone };
83
83
  }
@@ -1,5 +1,5 @@
1
1
  import { EscalationState, type EscalationCategory, type EscalationVerdict } from "../models/route/escalation.ts";
2
- import { dimensionsFromSignal } from "../models/route/stage.ts";
2
+ import { diagnoseStageResult } from "../models/route/stage-diagnostics.ts";
3
3
  import { extractToolSignalsFromObservations, fingerprint, type ToolObservation, type ToolSignals } from "../models/route/signals.ts";
4
4
  import type { Conversation } from "../models/route/normalize.ts";
5
5
  import type { HubEvent } from "./events.ts";
@@ -54,9 +54,27 @@ export interface ProgressDimensions {
54
54
  production: number;
55
55
  }
56
56
 
57
- export function progressDimensions(signals: ToolSignals): ProgressDimensions {
58
- const dimensions = dimensionsFromSignal(signals);
59
- return { severity: dimensions.severity, spinning: dimensions.spinning, exploring: dimensions.exploring, production: dimensions.productionIntensity };
57
+ /** Observer calibration is independent of stage risk and never reads commands/arguments. */
58
+ export function progressDimensions(observations: readonly NativeToolObservation[]): ProgressDimensions {
59
+ let severity = 0, reads = 0, mutations = 0, inspected = 0;
60
+ const turns = new Set<string>();
61
+ for (let index = Math.max(0, observations.length - MAX_OBSERVATIONS); index < observations.length; index++) {
62
+ const item = observations[index];
63
+ if (!item) continue;
64
+ inspected++;
65
+ const name = item.name.slice(0, 80).toLowerCase();
66
+ const read = /^(read|read_file|glob|grep|search|list|list_dir)$/.test(name);
67
+ const mutation = /^(filechange|write|write_file|edit|apply_patch|patch|delete|create|replace)$/.test(name);
68
+ if (read) reads++;
69
+ if (mutation) mutations++;
70
+ const diagnostic = diagnoseStageResult({ text: item.resultText?.slice(0, MAX_TEXT) ?? "", error: item.isError === true,
71
+ family: read ? "read" : mutation ? "mutation" : "other", associated: true });
72
+ if (diagnostic.fault !== "none") severity = 0.7;
73
+ const turn = validTurn(item.turn);
74
+ if (turn) turns.add(turn);
75
+ }
76
+ return { severity, spinning: turns.size >= 8 && mutations === 0 ? 1 : 0,
77
+ exploring: reads / Math.max(1, inspected), production: mutations / Math.max(1, inspected) };
60
78
  }
61
79
 
62
80
  export interface ProgressDeps {
@@ -89,8 +107,7 @@ export class ProgressObserver {
89
107
  state.observations.push(boundedObservation(observation));
90
108
  if (state.observations.length > MAX_OBSERVATIONS) state.observations.splice(0, state.observations.length - MAX_OBSERVATIONS);
91
109
  pruneAttemptedTurns(state);
92
- const signals = signalsFor(state.observations);
93
- this.safeEmit({ type: "progress", peer, task: taskId, ...progressDimensions(signals) });
110
+ this.safeEmit({ type: "progress", peer, task: taskId, ...progressDimensions(state.observations) });
94
111
  if (this.judgeEligible(state)) void this.evaluateState(peer, taskId, state);
95
112
  }
96
113
 
@@ -147,7 +164,7 @@ export class ProgressObserver {
147
164
  if (!latestNativeTurn(state.observations) || state.escalation.snapshot().latched) return false;
148
165
  const signals = signalsFor(state.observations);
149
166
  const repeatedAcrossTurns = signals.repeatedFailure && repeatedFailureAcrossTurns(state.observations);
150
- return repeatedAcrossTurns || progressDimensions(signals).spinning > 0;
167
+ return repeatedAcrossTurns || progressDimensions(state.observations).spinning > 0;
151
168
  }
152
169
 
153
170
  private openTask(peer: string, id: number): Task | undefined {
@@ -47,6 +47,8 @@ export interface RestartSnapshot {
47
47
  boardDigest: string;
48
48
  budgetDigest: string;
49
49
  modelOverrides?: { count: number; digest: string };
50
+ guidanceVariants?: { experiments: number; variants: number; digest: string };
51
+ executionReferences?: { count: number; digest: string };
50
52
  /** Whole captured binding set; portable identities are covered alongside queue/board integrity. */
51
53
  externalBindingsDigest?: string;
52
54
  /** Research state remains part of controlled-recovery integrity when present. */
@@ -114,6 +116,17 @@ export function readRestartSnapshot(stateDir: string, expected: RestartReadExpec
114
116
  if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).sort().join(",") !== "count,digest"
115
117
  || !Number.isSafeInteger(value.count) || value.count < 0 || typeof value.digest !== "string" || !/^[a-f0-9]{64}$/.test(value.digest)) return undefined;
116
118
  }
119
+ if (s.integrity && Object.hasOwn(s.integrity, "guidanceVariants")) {
120
+ const value = s.integrity.guidanceVariants;
121
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).sort().join(",") !== "digest,experiments,variants"
122
+ || !Number.isSafeInteger(value.experiments) || value.experiments < 0 || !Number.isSafeInteger(value.variants) || value.variants < value.experiments
123
+ || typeof value.digest !== "string" || value.digest.length !== 64 || !/^[a-f0-9]{64}$/.test(value.digest)) return undefined;
124
+ }
125
+ if (s.integrity && Object.hasOwn(s.integrity, "executionReferences")) {
126
+ const value = s.integrity.executionReferences;
127
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).sort().join(",") !== "count,digest"
128
+ || !Number.isSafeInteger(value.count) || value.count < 0 || typeof value.digest !== "string" || !/^[a-f0-9]{64}$/.test(value.digest)) return undefined;
129
+ }
117
130
  if (s.integrity && Object.hasOwn(s.integrity, "research")) {
118
131
  const research = s.integrity.research;
119
132
  if (!research || typeof research !== "object" || Array.isArray(research)
package/src/hub/roles.ts CHANGED
@@ -14,6 +14,16 @@ export interface CatalogRole {
14
14
  body: string; review: string; layer: "shipped" | "project"; hash: string;
15
15
  }
16
16
  export interface RoleCatalog { roles: Map<string, CatalogRole>; errors: { id: string; reason: string }[] }
17
+ export interface RoleSectionSpan {
18
+ readonly name: typeof ROLE_SECTIONS[number];
19
+ readonly startUtf16: number; readonly endUtf16: number; readonly contentStartUtf16: number;
20
+ readonly headingRaw: string; readonly contentRaw: string; readonly raw: string;
21
+ }
22
+ export interface RoleDocument {
23
+ readonly role: Readonly<CatalogRole>;
24
+ readonly rawHeader: string; readonly bodyPrefix: string;
25
+ readonly sections: readonly RoleSectionSpan[];
26
+ }
17
27
  /** Flat headers are data, never YAML execution or authority configuration. */
18
28
  export function parseRole(text: string, stem: string, layer: CatalogRole["layer"]): CatalogRole {
19
29
  if (Buffer.byteLength(text) > 8192 || text.includes("\r") || !ID.test(stem)) throw new Error("invalid role size, encoding or file id");
@@ -48,6 +58,22 @@ export function parseRole(text: string, stem: string, layer: CatalogRole["layer"
48
58
  const review = body.slice(reviewStart, sections[5]!.index).trim();
49
59
  return { id: stem, name: header.name!, group: header.group!, summary: header.summary!, source: header.source!, base: list("base", BASES), classes: list("classes", CLASSES), body, review, layer, hash: createHash("sha256").update(text).digest("hex") };
50
60
  }
61
+ /** Validate with the existing parser, then retain exact source slices without trim or normalization. */
62
+ export function parseRoleDocument(text: string, stem: string, layer: CatalogRole["layer"]): RoleDocument {
63
+ const role = parseRole(text, stem, layer);
64
+ const rawHeader = /^---\n[\s\S]*?\n---\n/.exec(text)![0];
65
+ const body = text.slice(rawHeader.length), headings = [...body.matchAll(/^## (.+)$/gm)];
66
+ const sections = headings.map((heading, index): RoleSectionSpan => {
67
+ const startUtf16 = rawHeader.length + heading.index!;
68
+ const endUtf16 = rawHeader.length + (headings[index + 1]?.index ?? body.length);
69
+ let contentStartUtf16 = startUtf16 + heading[0].length;
70
+ if (text[contentStartUtf16] === "\n") contentStartUtf16++;
71
+ return Object.freeze({ name: ROLE_SECTIONS[index]!, startUtf16, endUtf16, contentStartUtf16,
72
+ headingRaw: text.slice(startUtf16, contentStartUtf16), contentRaw: text.slice(contentStartUtf16, endUtf16), raw: text.slice(startUtf16, endUtf16) });
73
+ });
74
+ Object.freeze(role.base); Object.freeze(role.classes); Object.freeze(role);
75
+ return Object.freeze({ role, rawHeader, bodyPrefix: body.slice(0, headings[0]!.index), sections: Object.freeze(sections) });
76
+ }
51
77
  function projectRole(file: string): string {
52
78
  const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
53
79
  try {
@@ -11,7 +11,7 @@ export interface PeerCapabilities { tests: boolean; spec: boolean; testsReason?:
11
11
  import type { PeerId, PeerState } from "./envelope.ts";
12
12
 
13
13
  import { parseHubRoutes, type HubRoute } from "../models/route/config.ts";
14
- import { DEFAULT_STAY_SWITCH, type StaySwitchMode } from "../models/route/stage.ts";
14
+ import { DEFAULT_STAY_SWITCH, type StaySwitchMode } from "../models/route/stage-fallback.ts";
15
15
 
16
16
  export interface ClassPolicy {
17
17
  /** preference order among attached, unpaused peers */
@@ -426,6 +426,8 @@ export function assign(
426
426
  states: Record<PeerId, PeerState>,
427
427
  routing: Routing,
428
428
  opts: InstanceRoutingOptions & {
429
+ /** Precomputed snapshot guidance only; it never changes peer eligibility or performs a read. */
430
+ entryDiagnostic?: string;
429
431
  capabilities?: Record<PeerId, PeerCapabilities>;
430
432
  repository?: string;
431
433
  exclude?: PeerId[];
@@ -469,6 +471,7 @@ export function assign(
469
471
  const instanceMode = hasInstances(opts);
470
472
  const policy = routing.classes[task.class];
471
473
  const trace: string[] = [`class ${task.class}${policy ? "" : " (no [classes] entry: only an explicit owner can take it)"}`, `signals: ${task.signals.join(", ") || "none"}`];
474
+ if (opts.entryDiagnostic) trace.push(`build entry: ${opts.entryDiagnostic}`);
472
475
  // Which file each of this class's values comes from (#269), only when the machine-local overlay sets one.
473
476
  const local = Object.keys(routing.sources ?? {}).filter((key) => key.startsWith(`classes.${task.class}.`)).map((key) => key.slice(`classes.${task.class}.`.length));
474
477
  if (local.length) trace.push(`policy source: ${local.join(", ")} from ${OVERLAY_FILE}; the rest from routing.toml`);
@@ -2,7 +2,7 @@ import { findingsForHead, findingHead, findingTally } from "./review-findings.ts
2
2
  import { readMergeQueue, type DeliveryTask, type MergeQueue } from "./sdlc-queue.ts";
3
3
  import { evalGapBlockers, evalGateView, evalReportedGap, evalRequiredChecks, readEvalFor, type EvalResult } from "./eval-gate.ts";
4
4
  import { mergeCostFrom } from "./cost-governance.ts";
5
- import { readPrCostHistory, readSdlcPr, stageDefinition, type AutoMergeMode, type PrEvidence, type SdlcConfig, type SdlcGh, type MergeRecord } from "./sdlc.ts";
5
+ import { parsePrEvidence, readPrCostHistory, readSdlcPr, stageDefinition, type AutoMergeMode, type PrEvidence, type SdlcConfig, type SdlcGh, type MergeRecord, type SdlcReceipt } from "./sdlc.ts";
6
6
 
7
7
  /**
8
8
  * #786 T1/T2: the one guarded merge. Given a task and the head its reviewer approved, it re-reads the PR (`readSdlcPr`) and the merge queue
@@ -91,6 +91,44 @@ function checkGates(evidence: PrEvidence, required: readonly string[], extra: re
91
91
  return gates;
92
92
  }
93
93
 
94
+ /** One bounded GitHub snapshot for adoption: no bodies, no merge or cleanup mutation, and complete head-bound review/check coverage. */
95
+ export async function readAdoptMergeEvidence(receipt: SdlcReceipt, run: SdlcGh): Promise<PrEvidence | undefined> {
96
+ if (!REPO.test(receipt.repo ?? "") || receipt.repo!.startsWith("-") || !Number.isSafeInteger(receipt.pr) || receipt.pr! <= 0) return undefined;
97
+ const [owner, name] = receipt.repo!.split("/");
98
+ const query = "query($owner:String!,$name:String!,$number:Int!){repository(owner:$owner,name:$name){pullRequest(number:$number){headRefOid state reviewDecision isDraft mergeCommit{oid} reviewRequests(first:100){nodes{requestedReviewer{__typename}} pageInfo{hasNextPage}} reviewThreads(first:100){nodes{isResolved} pageInfo{hasNextPage}} commits(last:1){nodes{commit{oid statusCheckRollup{contexts(first:100){nodes{... on CheckRun{name status conclusion} ... on StatusContext{context state}} pageInfo{hasNextPage}}}}}}}}}";
99
+ try {
100
+ const result = await run(["api", "graphql", "-f", `query=${query}`, "-f", `owner=${owner}`, "-f", `name=${name}`, "-F", `number=${receipt.pr}`]);
101
+ if (result.code !== 0) return undefined;
102
+ const response = JSON.parse(result.stdout), pr = response?.data?.repository?.pullRequest;
103
+ const commit = pr?.commits?.nodes?.length === 1 ? pr.commits.nodes[0]?.commit : undefined, checks = commit?.statusCheckRollup?.contexts;
104
+ if (response.errors !== undefined || !pr || commit?.oid !== pr.headRefOid || checks?.pageInfo?.hasNextPage !== false || !Array.isArray(checks.nodes)) return undefined;
105
+ const threads = pr.reviewThreads, requests = pr.reviewRequests;
106
+ const threadComplete = threads?.pageInfo?.hasNextPage === false && Array.isArray(threads.nodes) && threads.nodes.every((node: { isResolved?: unknown } | null) => typeof node?.isResolved === "boolean");
107
+ const requestComplete = requests?.pageInfo?.hasNextPage === false && Array.isArray(requests.nodes) && requests.nodes.every((node: { requestedReviewer?: { __typename?: unknown } } | null) => typeof node?.requestedReviewer?.__typename === "string");
108
+ const evidence = parsePrEvidence({ ...pr, statusCheckRollup: checks.nodes, files: [], ...(threadComplete ? { unresolvedThreads: threads.nodes.filter((node: { isResolved: boolean }) => !node.isResolved).length } : {}), reviewRequests: requestComplete ? requests.nodes : undefined });
109
+ evidence.checks = evidence.checks.map((check, index): PrEvidence["checks"][number] => {
110
+ const raw = checks.nodes[index];
111
+ const green = raw.name ? (raw.status === "COMPLETED" && raw.conclusion === "SUCCESS") : raw.state === "SUCCESS";
112
+ return check.state === "passed" && !green ? { ...check, state: "unknown" } : check;
113
+ });
114
+ // Files are outside adoption's decision. Keep their coverage explicitly unknown in the shared evidence shape.
115
+ return { ...evidence, pathsComplete: false, typesComplete: false };
116
+ } catch { return undefined; }
117
+ }
118
+
119
+ /** #1328 T3: adoption observes a completed merge; it never dispatches a merge or invents a reviewer verdict. */
120
+ export function adoptMergeGates(evidence: PrEvidence | undefined, head: string, required: readonly string[]): string[] {
121
+ if (!evidence) return ["PR evidence unavailable; restore GitHub access and retry ahub sdlc adopt-merge"];
122
+ const gates: string[] = [];
123
+ if (evidence.state !== "MERGED") gates.push("PR is not merged; complete the normal review and guarded merge before adopting it");
124
+ if (evidence.head !== head) gates.push("PR head differs from the task's last recorded full head; record the correct task head before retrying ahub sdlc adopt-merge");
125
+ if (evidence.unresolved === null || evidence.unresolved > 0) gates.push("PR review threads are unresolved or unknown; resolve the threads and restore complete GitHub readback before retrying ahub sdlc adopt-merge");
126
+ if (evidence.pendingReviews === null || evidence.pendingReviews > 0) gates.push("PR review requests are pending or unknown; settle the requests and restore complete GitHub readback before retrying ahub sdlc adopt-merge");
127
+ if (evidence.review === "changes_requested") gates.push("PR has a pending change request; settle the review before retrying ahub sdlc adopt-merge");
128
+ gates.push(...checkGates(evidence, required).map(gate => `${gate}; configure required_checks in .agenthub/sdlc.toml and get every required check green at the recorded head before retrying ahub sdlc adopt-merge`));
129
+ return gates;
130
+ }
131
+
94
132
  function queueGates(queue: MergeQueue | undefined, pr: number): string[] {
95
133
  const row = queue?.rows.find(r => r.pr === pr);
96
134
  if (!queue || !row) return ["merge queue unavailable: this PR is not in the open snapshot"];
@@ -254,7 +254,7 @@ export function releaseMetrics(releases: Release[], tasks: Task[]) {
254
254
  const scope = train.scope ?? [...train.history].reverse().find(row => row.event === "cut")?.scope;
255
255
  if (!scope) { unknown.add(release.id); continue; }
256
256
  for (const id of scope) {
257
- const task = byTask.get(id), approved = task?.history.findLast(row => row.at <= event.at && (row.event === "approved" || row.event === "done" && task.state === "approved" && task.reviewer === null))?.at ?? null;
257
+ const task = byTask.get(id), approved = task?.history.findLast(row => row.at <= event.at && (row.event === "approved" || row.event === "merged outside the hub" || row.event === "done" && task.state === "approved" && task.reviewer === null))?.at ?? null;
258
258
  const ms = approved !== null && approved <= event.at ? event.at - approved : null;
259
259
  if (ms === null) unknown.add(release.id);
260
260
  approvalToReleaseMs.push({ release: release.id, task: id, ms });
package/src/hub/sdlc.ts CHANGED
@@ -350,6 +350,30 @@ export function parsePrEvidence(value: unknown): PrEvidence {
350
350
  /** Issue identity and edit times only; no body is fetched or stored. `lastEditedAt` moves on a body edit, not on comments. */
351
351
  export interface SpecEdit { lastEditedAt: string | null; updatedAt: string }
352
352
  export interface SpecAcceptance extends SpecEdit { repo: string; issue: number; acceptedAt: number }
353
+ /** Consent references are complete local task tokens, never numbers extracted from prose. */
354
+ export function localSupersedingTask(value: unknown): number | undefined {
355
+ if (typeof value !== "string") return undefined;
356
+ const match = /^(?:task #|#)?([1-9][0-9]*)$/.exec(value);
357
+ const task = match?.[0] === value ? Number(match[1]) : NaN;
358
+ return Number.isSafeInteger(task) ? task : undefined;
359
+ }
360
+
361
+ /** Validate host-stored consent without importing any other source receipt fields. */
362
+ export function storedSpecAcceptance(value: unknown): SpecAcceptance | undefined {
363
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
364
+ const record = value as Record<string, unknown>;
365
+ const stamp = (v: unknown): v is string => typeof v === "string" && v.length <= 40 && !Number.isNaN(Date.parse(v));
366
+ if (!repo(record.repo) || !id(record.issue) || !stamp(record.updatedAt) || record.lastEditedAt !== null && !stamp(record.lastEditedAt)
367
+ || typeof record.acceptedAt !== "number" || !Number.isFinite(record.acceptedAt)) return undefined;
368
+ return { repo: record.repo, issue: record.issue, updatedAt: record.updatedAt, lastEditedAt: record.lastEditedAt as string | null, acceptedAt: record.acceptedAt };
369
+ }
370
+
371
+ /** Only a host observation of the same issue/body permits copying existing person consent. */
372
+ export function carriedSpecAcceptance(source: SpecAcceptance, destination: { repo: string; issue: number }, edit: SpecEdit | undefined): SpecAcceptance | undefined {
373
+ if (!edit || source.repo.toLowerCase() !== destination.repo.toLowerCase() || source.issue !== destination.issue || source.lastEditedAt !== edit.lastEditedAt) return undefined;
374
+ return { repo: destination.repo, issue: destination.issue, lastEditedAt: source.lastEditedAt, updatedAt: source.updatedAt, acceptedAt: source.acceptedAt };
375
+ }
376
+
353
377
  export type SpecState = "missing" | "current" | "changed" | "unknown";
354
378
  /** Whether the receipt's spec issue is accepted at its current body. `edit` undefined means the readback failed. */
355
379
  export function specState(receipt: SdlcReceipt | undefined, edit: SpecEdit | undefined): SpecState {
@@ -546,16 +570,34 @@ export async function readPlanIssueMetadata(repository: string, number: number,
546
570
  } catch { return undefined; }
547
571
  }
548
572
 
573
+ /** The native CI floor belongs only to this repository; other projects must name their own checks. */
574
+ export function requiredCheckNames(repository: string | undefined, required: readonly string[]): string[] {
575
+ return required.length ? [...new Set(required)] : repository?.toLowerCase() === "staixbwlb/agent-hub" ? ["check (ubuntu-latest)", "check (macos-latest)", "seeded guards"] : [];
576
+ }
577
+
578
+ /** Names each non-green required check. Incomplete inventories cannot prove either presence or success. */
579
+ export function requiredCiBlocker(required: readonly string[], checks: PrEvidence["checks"], complete = true): string | undefined {
580
+ const problems = required.flatMap(name => {
581
+ const matches = checks.filter(check => check.name === name);
582
+ const state = !complete ? "unknown" : !matches.length ? "missing" : matches.some(check => check.state === "failed") ? "failed"
583
+ : matches.some(check => check.state === "pending") ? "pending" : matches.length !== 1 ? "duplicate" : matches[0]!.state !== "passed" ? "unknown" : undefined;
584
+ return state ? [`${state} ${name}`] : [];
585
+ });
586
+ return problems.length ? `exact-head full CI is not green: ${problems.join("; ")}` : undefined;
587
+ }
588
+
549
589
  /** A complete resolved-thread snapshot already proves there is no pending unanswered bot thread. */
550
- export function reviewReadinessFromEvidence(evidence: PrEvidence | undefined, expected: string | undefined, required: readonly string[]): ReviewReadiness | undefined {
590
+ export function reviewReadinessFromEvidence(evidence: PrEvidence | undefined, expected: string | undefined, required: readonly string[], repository?: string): ReviewReadiness | undefined {
551
591
  if (!evidence || evidence.unresolved !== 0) return undefined;
552
- const checks = required.length ? [...required] : ["check (ubuntu-latest)", "check (macos-latest)", "seeded guards"];
592
+ const checks = requiredCheckNames(repository, required);
593
+ if (!checks.length) return { ready: false, blockers: ["required checks unknown: set required_checks in .agenthub/sdlc.toml"], checks };
553
594
  if (!checks.every(name => evidence.checks.some(check => check.name === name)) || evidence.checks.some(check => check.state === "unknown")) return undefined;
554
595
  const blockers: string[] = [];
555
596
  if (!expected || !sha(expected)) blockers.push("review head missing");
556
597
  else if (evidence.head !== expected) blockers.push("review head changed");
557
598
  if (evidence.state !== "OPEN") blockers.push("review PR is not open");
558
- if (!checks.every(name => { const matched = evidence.checks.filter(check => check.name === name); return matched.length === 1 && matched[0]?.state === "passed"; })) blockers.push("exact-head full CI is not green");
599
+ const ciBlocker = requiredCiBlocker(checks, evidence.checks);
600
+ if (ciBlocker) blockers.push(ciBlocker);
559
601
  return { head: evidence.head, ready: blockers.length === 0, blockers, checks };
560
602
  }
561
603
 
@@ -565,6 +607,8 @@ export interface ReviewReadiness { head?: string; ready: boolean; blockers: stri
565
607
  export async function readReviewReadiness(receipt: SdlcReceipt, expected: string | undefined, run: SdlcGh = sdlcGh, requiredChecks: readonly string[] = []): Promise<ReviewReadiness> {
566
608
  const unknown = (): ReviewReadiness => ({ ready: false, blockers: ["review readiness unavailable"] });
567
609
  if (!repo(receipt.repo) || !id(receipt.pr)) return unknown();
610
+ const full = requiredCheckNames(receipt.repo, requiredChecks);
611
+ if (!full.length) return { ready: false, blockers: ["required checks unknown: set required_checks in .agenthub/sdlc.toml"], checks: full };
568
612
  const [owner, name] = receipt.repo.split("/");
569
613
  const query = "query($owner:String!,$name:String!,$number:Int!){repository(owner:$owner,name:$name){pullRequest(number:$number){headRefOid state commits(last:1){nodes{commit{oid tree{oid} statusCheckRollup{contexts(first:100){nodes{... on CheckRun{name status conclusion} ... on StatusContext{context state}} pageInfo{hasNextPage}}}}}} reviewThreads(first:100){nodes{isResolved comments(first:100){nodes{author{__typename} createdAt} pageInfo{hasNextPage}}} pageInfo{hasNextPage}}}}}";
570
614
  try {
@@ -585,14 +629,21 @@ export async function readReviewReadiness(receipt: SdlcReceipt, expected: string
585
629
  if (!commit || commit.oid !== pr.headRefOid) blockers.push("review head changed");
586
630
  const contexts = commit?.statusCheckRollup?.contexts;
587
631
  const nodes: unknown[] | undefined = contexts?.nodes;
588
- const full = requiredChecks.length ? [...requiredChecks] : ["check (ubuntu-latest)", "check (macos-latest)", "seeded guards"];
589
632
  let reusedRun: number | undefined;
590
- if (contexts?.pageInfo?.hasNextPage !== false || !Array.isArray(nodes) || nodes.length > 100
591
- || !full.every(name => {
592
- const matches = (nodes as { name?: string; context?: string; status?: string; conclusion?: string; state?: string }[]).filter(node => (node?.name ?? node?.context) === name);
593
- return matches.length === 1 && (matches[0]?.name ? matches[0].status === "COMPLETED" && matches[0].conclusion === "SUCCESS" : matches[0]?.state === "SUCCESS");
594
- })) blockers.push("exact-head full CI is not green");
595
- if (blockers.includes("exact-head full CI is not green") && contexts?.pageInfo?.hasNextPage === false && Array.isArray(nodes)
633
+ const completeChecks = !(contexts?.pageInfo?.hasNextPage !== false || !Array.isArray(nodes) || nodes.length > 100);
634
+ const requiredNodes = completeChecks ? nodes!.filter(node => {
635
+ const raw = node as { name?: unknown; context?: unknown } | null | undefined;
636
+ return full.some(name => (raw?.name ?? raw?.context) === name);
637
+ }) : [];
638
+ const checkEvidence = completeChecks ? parsePrEvidence({ headRefOid: pr.headRefOid, state: pr.state, files: [], statusCheckRollup: requiredNodes }).checks.map((check, index) => {
639
+ const raw = requiredNodes[index] as { name?: unknown; status?: unknown; conclusion?: unknown; state?: unknown } | undefined;
640
+ // Fresh GraphQL admission keeps its original success proof, even when common normalization accepts a legacy shape.
641
+ const success = raw?.name ? raw.status === "COMPLETED" && raw.conclusion === "SUCCESS" : raw?.state === "SUCCESS";
642
+ return check.state === "passed" && !success ? { ...check, state: "unknown" as const } : check;
643
+ }) : [];
644
+ const ciBlocker = requiredCiBlocker(full, checkEvidence, completeChecks);
645
+ if (ciBlocker) blockers.push(ciBlocker);
646
+ if (ciBlocker && contexts?.pageInfo?.hasNextPage === false && Array.isArray(nodes)
596
647
  && full.every(name => { const matches = (nodes as { name?: string; conclusion?: string }[]).filter(node => node?.name === name); return matches.length === 1 && matches[0]?.conclusion === "SKIPPED"; }) && sha(commit?.tree?.oid)) {
597
648
  reusedRun = await identicalTreeGate(receipt.repo, commit.tree.oid, bounded, full);
598
649
  if (reusedRun !== undefined) {
@@ -600,7 +651,7 @@ export async function readReviewReadiness(receipt: SdlcReceipt, expected: string
600
651
  const after = await bounded(args, 10_000, undefined, 512 * 1024);
601
652
  try { if (after.code !== 0 || JSON.stringify(JSON.parse(after.stdout)?.data?.repository?.pullRequest) !== JSON.stringify(pr)) reusedRun = undefined; }
602
653
  catch { reusedRun = undefined; }
603
- if (reusedRun !== undefined) blockers.splice(blockers.indexOf("exact-head full CI is not green"), 1);
654
+ if (reusedRun !== undefined) blockers.splice(blockers.indexOf(ciBlocker!), 1);
604
655
  }
605
656
  }
606
657
  const threads = pr.reviewThreads;
@@ -64,6 +64,8 @@ export const SETTINGS: readonly SettingDef[] = [
64
64
  { key: "tasks.escalate_after", group: "Routing", label: "Escalate after N consecutive changes_requested", type: "integer", min: 1, max: 10, store: "config", applies: "live", risk: "raises", path: ["tasks", "escalate_after"] },
65
65
  ...OPERATIONAL_NUMBERS.map(({ defaultValue, unit, inventory, ...def }): SettingDef => def),
66
66
  { key: "tasks.auto_pull", group: "Switches", label: "Auto-pull the top reserved ready card when a planner slot frees", type: "boolean", store: "config", applies: "live", risk: "raises", floor: false, path: ["tasks", "auto_pull"] },
67
+ // #1221 T2: off evaluates nothing, shadow stores bounded proposals with no inbox row or notice, advisory may also show one in the inbox.
68
+ { key: "supervision.mode", group: "Switches", label: "Supervision proposals: off, shadow (stored, zero-effect) or advisory (also shown in the inbox)", type: "enum", values: ["off", "shadow", "advisory"], store: "config", applies: "live", risk: "raises", floor: "off", path: ["supervision", "mode"] },
67
69
  { key: "tasks.queue_backpressure.max_queued", group: "Routing", label: "Automatic offers: max queued envelopes (0 disables)", type: "integer", min: 0, max: QUEUE_BACKPRESSURE_LIMITS.max_queued, store: "config", applies: "live", risk: "raises", path: ["tasks", "queue_backpressure", "max_queued"] },
68
70
  { key: "tasks.queue_backpressure.max_oldest_s", group: "Routing", label: "Automatic offers: max oldest queued age in seconds (0 disables)", type: "integer", min: 0, max: QUEUE_BACKPRESSURE_LIMITS.max_oldest_s, store: "config", applies: "live", risk: "raises", path: ["tasks", "queue_backpressure", "max_oldest_s"] },
69
71
  { key: "planner", group: "Roles", label: "Planners (task-local selection)", type: "peers", values: PLANNER_PEERS, store: "config", applies: "live", risk: "raises", path: ["planner"] },