@staix/agent-hub 0.50.0 → 0.51.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 (96) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +1 -1
  3. package/docs/adding-an-ai-tool.md +2 -2
  4. package/docs/agent-notes/README.md +1 -0
  5. package/docs/agent-notes/adapters.md +3 -3
  6. package/docs/agent-notes/daemon.md +1 -1
  7. package/docs/agent-notes/local-worker.md +3 -3
  8. package/docs/agent-notes/tasks.md +5 -1
  9. package/docs/design/adapters.md +17 -0
  10. package/docs/design/cli-output-inventory.md +22 -17
  11. package/docs/design/roadmap.md +1 -1
  12. package/docs/design/task-board.md +34 -0
  13. package/docs/dogfood.md +7 -3
  14. package/docs/operations.md +49 -3
  15. package/docs/quickstart.md +18 -1
  16. package/docs/roadmap.json +20 -20
  17. package/docs/roadmap.md +2 -2
  18. package/docs/sdlc.md +3 -2
  19. package/docs/specs/2026-09-19-agent-hub-design.md +1 -0
  20. package/docs/verification/2026-11-29-agy-1.5.20.md +33 -0
  21. package/docs/verification/2026-11-29-claude-profile-hook.md +12 -0
  22. package/docs/verification/2026-11-29-idle-daemon-footprint.md +75 -0
  23. package/docs/verification/2026-11-29-kimi-281-reviewer-compat.md +38 -0
  24. package/docs/verification/2026-11-29-kimi-tui-281.md +12 -0
  25. package/docs/verification/2026-11-30-0.51.0.md +91 -0
  26. package/docs/verification/2026-11-30-account-switch-1806.md +445 -0
  27. package/docs/verified.json +31 -27
  28. package/package.json +1 -1
  29. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  30. package/plugins/agent-hub/kimi-hook.js +1329 -24654
  31. package/plugins/agent-hub/server.js +612 -413
  32. package/scripts/check-docs.mjs +1 -1
  33. package/src/adapters/acp.ts +13 -13
  34. package/src/adapters/agy/definition.ts +2 -2
  35. package/src/adapters/agy/entry.ts +2 -0
  36. package/src/adapters/claude-channel-evidence.ts +7 -3
  37. package/src/adapters/compat.ts +4 -3
  38. package/src/adapters/definitions/builtin-metadata.ts +2 -2
  39. package/src/adapters/definitions/native-cli-claude-launch.ts +3 -1
  40. package/src/adapters/definitions/native-cli-entry-claude.ts +17 -2
  41. package/src/adapters/definitions/native-cli-entry-codex.ts +2 -0
  42. package/src/adapters/definitions/native-cli-entry-jcode.ts +2 -0
  43. package/src/adapters/definitions/native-cli-entry-kimi.ts +2 -0
  44. package/src/adapters/definitions/native-cli-entry-pi.ts +2 -0
  45. package/src/adapters/definitions/native-cli-entry-qwen.ts +2 -0
  46. package/src/adapters/definitions/native-cli-entry-types.ts +3 -1
  47. package/src/adapters/definitions/native-cli-jcode-home-init.ts +1 -1
  48. package/src/adapters/definitions/native-cli-preview-common.ts +1 -1
  49. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  50. package/src/adapters/jcode.ts +16 -0
  51. package/src/adapters/native-facts-hooks.ts +12 -0
  52. package/src/cli/autonomy-offline.ts +1 -1
  53. package/src/cli/bench.ts +1 -1
  54. package/src/cli/claude-profile-hook.ts +31 -11
  55. package/src/cli/commands/releases.ts +82 -0
  56. package/src/cli/conductor-recovery.ts +1 -1
  57. package/src/cli/facts-hook.ts +11 -4
  58. package/src/cli/help.ts +8 -6
  59. package/src/cli/identity.ts +5 -1
  60. package/src/cli/init-prompt.ts +1 -1
  61. package/src/cli/init-settings.ts +4 -35
  62. package/src/cli/init.ts +1 -1
  63. package/src/cli/json-text-spans.ts +57 -0
  64. package/src/cli/launch-check.ts +157 -0
  65. package/src/cli/launch.ts +19 -1
  66. package/src/cli/main.ts +44 -3
  67. package/src/cli/memory.ts +1 -1
  68. package/src/cli/output.ts +14 -1
  69. package/src/cli/preview.ts +1 -1
  70. package/src/cli/recovery-launch.ts +1 -1
  71. package/src/cli/setup-homes.ts +2 -2
  72. package/src/cli/start-agents-run.ts +85 -7
  73. package/src/cli/start-check.ts +28 -0
  74. package/src/cli/upgrade-runtime.ts +1 -1
  75. package/src/cli/warn-line.ts +1 -1
  76. package/src/hub/ci-watch.ts +311 -79
  77. package/src/hub/config-apply.ts +1 -1
  78. package/src/hub/config.ts +518 -0
  79. package/src/hub/control-client.ts +1 -1
  80. package/src/hub/daemon.ts +76 -513
  81. package/src/hub/delivery-public.ts +11 -0
  82. package/src/hub/hub-check.ts +125 -0
  83. package/src/hub/path-policy.ts +1 -1
  84. package/src/hub/permission-mode.ts +3 -40
  85. package/src/hub/permission-paths.ts +41 -0
  86. package/src/hub/recovery-policy.ts +1 -1
  87. package/src/hub/releases-inventory.ts +198 -0
  88. package/src/hub/runtime-capture-prune.ts +25 -3
  89. package/src/hub/runtime-prune-health.ts +8 -1
  90. package/src/hub/sdlc-release-authorization.ts +42 -21
  91. package/src/hub/sdlc-release-diagnostics.ts +5 -0
  92. package/src/hub/sdlc-release-policy.ts +21 -7
  93. package/src/hub/sdlc-release.ts +80 -20
  94. package/src/hub/sdlc.ts +7 -3
  95. package/src/hub/tasks.ts +138 -36
  96. package/src/ui/plugin.ts +1 -1
@@ -1,24 +1,42 @@
1
1
  import { latestCheckRuns, requiredCheckNames, parsePrEvidence, type SdlcGh } from "./sdlc.ts";
2
2
 
3
- /**
4
- * #785 P1b: one bounded watcher per exact PR head. It starts when `hub_task_done` names a head whose CI was not green,
5
- * ends on a passed CI result or on this deadline (a failed or incomplete one is told and then watched for a rerun), and is cancelled by a newer head or any task move. It is a timer in the
6
- * hub, never a peer turn, and its gh reads (one `gh pr view` per poll) are the only periodic gh calls the hub makes.
7
- * The longest hosted run is about 30 minutes (the job limits in `.github/workflows/check.yml` are 35 and 40 minutes).
8
- */
3
+ /** #1801: a single bounded snapshot per PR head and poll; each task phase gets its own deadline. */
9
4
  export const CI_WATCH_DEADLINE_MS = 45 * 60_000;
10
5
  export const CI_WATCH_POLL_MS = 60_000;
6
+ const CI_MISSING_RUN_MS = 10 * 60_000;
11
7
  const REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
12
8
  /** How many finished heads are remembered, so one head never tells the same outcome twice. */
13
9
  const SETTLED_CAP = 256;
14
10
 
15
11
  /** What one poll found. `incomplete` is every required check finished with none failed and not all passed (skipped, neutral, duplicated). */
16
12
  export type CiPoll = "pending" | "passed" | "failed" | "incomplete" | "superseded" | "closed";
17
- export type CiOutcome = "passed" | "failed" | "incomplete" | "deadline";
13
+ export type CiOutcome = "passed" | "failed" | "incomplete" | "deadline" | "conflicting" | "missing-run";
14
+ type CiPhase = "draft" | "review" | "approved";
15
+
16
+ export interface CiSnapshot {
17
+ result: CiPoll;
18
+ mergeable?: "MERGEABLE" | "CONFLICTING" | "UNKNOWN";
19
+ hasRuns?: boolean;
20
+ failedChecks?: readonly string[];
21
+ /** A failure in the required CI workflow, whether or not it is safe to rerun. */
22
+ retryWorkflowFailure?: true;
23
+ retry?: CiShardRetry;
24
+ retryPending?: CiShardRetry;
25
+ simultaneousShardFailures?: readonly CiShardRetry[];
26
+ }
27
+
28
+ export interface CiShardRetry {
29
+ job: string;
30
+ run: number;
31
+ attempt: number;
32
+ startedAt?: number;
33
+ aggregate?: string;
34
+ aggregateStartedAt?: number;
35
+ aggregateOnly?: true;
36
+ }
18
37
 
19
- export interface CiWatch { id: number; head: string; repo: string; pr: number; deadlineAt: number }
20
- /** `reported`: a result was told, so a deadline ends silently. `renew`: the next pending read may renew the deadline once (set by each new told result). */
21
- type Entry = { watch: CiWatch; timer?: ReturnType<typeof setTimeout>; reported?: boolean; renew?: boolean };
38
+ export interface CiWatch { id: number; head: string; repo: string; pr: number; deadlineAt: number; phase: CiPhase }
39
+ type Entry = { watch: CiWatch; timer?: ReturnType<typeof setTimeout>; reading?: boolean; renew?: boolean; awaitingRetry?: CiShardRetry; conflicts: number };
22
40
 
23
41
  /**
24
42
  * #1490: the required check a draft PR defers. Its aggregate fails with "macOS deferred" until `gh pr ready` (check.yml), which is not a CI failure of the head.
@@ -39,13 +57,34 @@ function awaitingDeferredReplacement(check: Record<string, unknown>, rows: reado
39
57
  && typeof row.startedAt === "string" && Date.parse(row.startedAt) > at);
40
58
  }
41
59
 
42
- /**
43
- * One read of the PR: the head, its state and the required checks of that head. A failed or unreadable read is `pending`; the deadline bounds the retries.
44
- * #1490: a cancelled check (a superseded run, or the draft run that `gh pr ready` replaces) and a draft PR's deferred macOS check are `pending`, never `failed`: nobody has to fix them.
45
- * After a PR becomes ready, a later same-workflow macOS shard also keeps the older aggregate pending until the replacement aggregate appears.
46
- * A cancelled run of an older head never gets here (the head differs: `superseded`).
47
- */
48
- export async function pollCi(target: { repo: string; pr: number }, head: string, required: readonly string[], run: SdlcGh): Promise<CiPoll> {
60
+ /** A ready PR can still contain an aggregate from a workflow run created before it became ready. */
61
+ function readyAggregatePending(check: Record<string, unknown>, readyAt: number | undefined): boolean {
62
+ if (readyAt === undefined || !DEFERRED_ON_DRAFT.includes(String(check.name ?? check.context)) || check.conclusion !== "FAILURE") return false;
63
+ const at = typeof check.runCreatedAt === "string" ? Date.parse(check.runCreatedAt) : NaN;
64
+ return !Number.isFinite(at) || at <= readyAt;
65
+ }
66
+
67
+ function evaluateCi(body: { headRefOid: string; state: string; isDraft?: boolean; statusCheckRollup: Record<string, unknown>[] }, names: readonly string[], draftOnly: boolean, readyAt?: number): CiSnapshot {
68
+ const draft = body.isDraft === true, allRows = body.statusCheckRollup;
69
+ const rollup = latestCheckRuns(allRows).map(check => {
70
+ const native = String(check?.conclusion ?? check?.state ?? "");
71
+ return native === "CANCELLED" || draft && DEFERRED_ON_DRAFT.includes(String(check?.name ?? check?.context)) && native !== "SUCCESS"
72
+ || !draft && readyAggregatePending(check, readyAt) || awaitingDeferredReplacement(check, allRows) ? { ...check, status: "PENDING" } : check;
73
+ });
74
+ const evidence = parsePrEvidence({ ...body, statusCheckRollup: rollup, files: [], changedFiles: 0 });
75
+ const required = draft && draftOnly ? names.filter(name => !DEFERRED_ON_DRAFT.includes(name)) : names;
76
+ const rows = required.map(name => evidence.checks.filter(check => check.name === name));
77
+ const failedChecks = rows.flat().filter(check => check.state === "failed").map(check => check.name);
78
+ if (failedChecks.length) return { result: "failed", failedChecks };
79
+ if (rows.some(row => row.length === 0 || row.some(check => check.state === "pending"))) return { result: "pending" };
80
+ return { result: rows.length && rows.every(row => row.length === 1 && row[0]!.state === "passed") ? "passed" : "incomplete" };
81
+ }
82
+
83
+ /** Legacy PR evidence reader; the lifecycle watcher uses the same evaluator with a fuller snapshot. */
84
+ export function pollCi(target: { repo: string; pr: number }, head: string, required: readonly string[], run: SdlcGh): Promise<CiPoll>;
85
+ export function pollCi(target: CiWatch, head: string, required: readonly string[], run: SdlcGh, lifecycle: true): Promise<CiSnapshot>;
86
+ export async function pollCi(target: { repo: string; pr: number }, head: string, required: readonly string[], run: SdlcGh, lifecycle?: true): Promise<CiPoll | CiSnapshot> {
87
+ if (lifecycle) return pollCiSnapshot(target as CiWatch, required, run);
49
88
  if (!REPO.test(target.repo) || !Number.isSafeInteger(target.pr) || target.pr < 1) return "closed";
50
89
  const names = requiredCheckNames(target.repo, required);
51
90
  if (!names.length) return "incomplete";
@@ -55,81 +94,222 @@ export async function pollCi(target: { repo: string; pr: number }, head: string,
55
94
  const body = JSON.parse(view.stdout);
56
95
  if (body?.headRefOid !== head) return "superseded";
57
96
  if (body.state !== "OPEN") return "closed";
58
- const draft = body.isDraft === true;
59
- const allRows: Record<string, unknown>[] = Array.isArray(body.statusCheckRollup) ? body.statusCheckRollup : [];
60
- const rollup = Array.isArray(body.statusCheckRollup) ? latestCheckRuns(allRows).map((check: Record<string, unknown>) => {
61
- const native = String(check?.conclusion ?? check?.state ?? "");
62
- return native === "CANCELLED" || draft && DEFERRED_ON_DRAFT.includes(String(check?.name ?? check?.context)) && native !== "SUCCESS" || awaitingDeferredReplacement(check, allRows) ? { ...check, status: "PENDING" } : check;
63
- }) : body.statusCheckRollup;
64
- // The same check-state mapping as every other PR read; files are not requested here.
65
- const evidence = parsePrEvidence({ ...body, statusCheckRollup: rollup, files: [], changedFiles: 0 });
66
- const rows = names.map(name => evidence.checks.filter(check => check.name === name));
67
- if (rows.some(row => row.some(check => check.state === "failed"))) return "failed";
68
- if (rows.some(row => row.length === 0 || row.some(check => check.state === "pending"))) return "pending";
69
- return rows.every(row => row.length === 1 && row[0]!.state === "passed") ? "passed" : "incomplete";
97
+ return evaluateCi(body, names, false).result;
70
98
  } catch { return "pending"; }
71
99
  }
72
100
 
101
+ const CI_QUERY = `query($owner:String!,$name:String!,$number:Int!){
102
+ repository(owner:$owner,name:$name){pullRequest(number:$number){
103
+ headRefOid state isDraft mergeable
104
+ timelineItems(last:1,itemTypes:[READY_FOR_REVIEW_EVENT]){nodes{... on ReadyForReviewEvent{createdAt}}}
105
+ commits(last:1){nodes{commit{oid statusCheckRollup{contexts(first:100){nodes{
106
+ ... on CheckRun{name status conclusion startedAt checkSuite{
107
+ status matchingPullRequests(first:2){nodes{number}pageInfo{hasNextPage}}
108
+ workflowRun{databaseId runAttempt event createdAt workflow{resourcePath}}
109
+ }}
110
+ ... on StatusContext{context state}
111
+ }pageInfo{hasNextPage}}}}}}
112
+ reviewThreads(first:100){nodes{isResolved}pageInfo{hasNextPage}}
113
+ }}
114
+ }`;
115
+
116
+ type ShardCheck = { name?: unknown; status?: unknown; conclusion?: unknown; startedAt?: unknown; workflowName?: unknown;
117
+ checkSuite?: { status?: unknown; matchingPullRequests?: { nodes?: { number?: unknown }[]; pageInfo?: { hasNextPage?: unknown } };
118
+ workflowRun?: { databaseId?: unknown; runAttempt?: unknown; event?: unknown; createdAt?: unknown; workflow?: { resourcePath?: unknown } } } };
119
+
120
+ function shardAggregate(name: unknown): string | undefined {
121
+ if (typeof name !== "string") return undefined;
122
+ const shard = /^(check \(ubuntu-latest\)|check \(macos-latest\)) shard ([1-9]\d*)\/([1-9]\d*)$/.exec(name)
123
+ ?? /^(seeded guards) \(([1-9]\d*)\/([1-9]\d*)\)$/.exec(name);
124
+ return shard && Number(shard[2]) <= Number(shard[3]) ? shard[1] : undefined;
125
+ }
126
+
127
+ const failedCheck = (row: ShardCheck) => row.status === "COMPLETED"
128
+ && ["FAILURE", "ERROR", "TIMED_OUT", "ACTION_REQUIRED"].includes(String(row.conclusion));
129
+
130
+ function matchingRetryRun(watch: CiWatch, row: ShardCheck, readyAt?: number) {
131
+ const suite = row.checkSuite, workflow = suite?.workflowRun, prs = suite?.matchingPullRequests;
132
+ const expectedWorkflow = `/${watch.repo}/actions/workflows/check.yml`.toLowerCase();
133
+ if (!suite || !workflow || typeof workflow.workflow?.resourcePath !== "string"
134
+ || workflow.workflow.resourcePath.toLowerCase() !== expectedWorkflow || workflow.event !== "pull_request"
135
+ || prs?.pageInfo?.hasNextPage !== false || !Array.isArray(prs.nodes) || prs.nodes.length !== 1 || prs.nodes[0]?.number !== watch.pr) return;
136
+ const runCreatedAt = typeof workflow.createdAt === "string" ? Date.parse(workflow.createdAt) : NaN;
137
+ if (readyAt !== undefined && (!Number.isFinite(runCreatedAt) || runCreatedAt <= readyAt)) return;
138
+ return workflow;
139
+ }
140
+
141
+ function checkStartTime(value: unknown): number | undefined {
142
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(value)) return;
143
+ const timestamp = Date.parse(value);
144
+ return Number.isSafeInteger(timestamp) && timestamp > 0 && new Date(timestamp).toISOString().slice(0, 19) === value.slice(0, 19)
145
+ ? timestamp : undefined;
146
+ }
147
+
148
+ function retryCandidate(watch: CiWatch, row: ShardCheck, readyAt?: number): CiShardRetry | undefined {
149
+ const workflow = matchingRetryRun(watch, row, readyAt);
150
+ if (!workflow || typeof row.name !== "string") return;
151
+ const { databaseId: run, runAttempt: attempt } = workflow;
152
+ if (typeof run !== "number" || !Number.isSafeInteger(run) || run < 1 || typeof attempt !== "number" || !Number.isSafeInteger(attempt) || attempt < 1) return;
153
+ return { job: row.name, run, attempt, startedAt: checkStartTime(row.startedAt) };
154
+ }
155
+
156
+ function retryWorkflowFailure(watch: CiWatch, names: readonly string[], rows: readonly ShardCheck[], result: CiSnapshot, readyAt?: number): CiSnapshot {
157
+ const current = latestCheckRuns(rows), failed = current.filter(failedCheck);
158
+ if (result.result === "incomplete" && names.length && names.every(name => {
159
+ const required = current.filter(row => row.name === name);
160
+ return required.length === 1 && required[0]?.status === "COMPLETED" && required[0].conclusion === "SKIPPED";
161
+ })) {
162
+ const decision = failed.find(row => row.name === "decision" && matchingRetryRun(watch, row, readyAt));
163
+ if (decision) return { result: "failed", failedChecks: ["decision"], retryWorkflowFailure: true };
164
+ }
165
+ if (result.result !== "failed") return result;
166
+ const failedShards = failed.filter(row => {
167
+ const aggregate = shardAggregate(row.name);
168
+ return aggregate !== undefined && names.includes(aggregate) && result.failedChecks?.includes(aggregate);
169
+ });
170
+ if (!failedShards.length) {
171
+ const aggregates = failed.filter(row => typeof row.name === "string" && names.includes(row.name)
172
+ && result.failedChecks?.includes(row.name) && matchingRetryRun(watch, row, readyAt));
173
+ const aggregate = aggregates.length === 1 && result.failedChecks?.length === 1 ? retryCandidate(watch, aggregates[0]!, readyAt) : undefined;
174
+ return aggregates.length ? { ...result, retryWorkflowFailure: true, ...(aggregate ? { retryPending: { ...aggregate, aggregateOnly: true } } : {}) } : result;
175
+ }
176
+ const shards = failedShards.map(row => row.name as string);
177
+ const dependent = failedShards.map(row => shardAggregate(row.name));
178
+ const local = { ...result, retryWorkflowFailure: true as const, failedChecks: [...shards, ...(result.failedChecks ?? []).filter(name => !dependent.includes(name))] };
179
+ if (failedShards.length !== 1 || result.failedChecks?.length !== 1) {
180
+ const simultaneousShardFailures = failedShards.map(row => retryCandidate(watch, row, readyAt)).filter(row => row !== undefined);
181
+ return { ...local, simultaneousShardFailures };
182
+ }
183
+ const shard = failedShards[0]!, candidate = retryCandidate(watch, shard, readyAt);
184
+ if (!candidate) return local;
185
+ // The failed aggregate is the dependent check for this shard. A second failed job makes --failed too broad.
186
+ const aggregate = shardAggregate(shard.name);
187
+ const related = failed.filter(row => row.checkSuite?.workflowRun?.databaseId === candidate.run
188
+ && row.checkSuite.workflowRun.runAttempt === candidate.attempt);
189
+ if (related.some(row => row !== shard && row.name !== aggregate)) return local;
190
+ candidate.aggregate = aggregate;
191
+ candidate.aggregateStartedAt = checkStartTime(related.find(row => row.name === aggregate)?.startedAt);
192
+ const status = shard.checkSuite?.status;
193
+ if (status === "COMPLETED") return { ...local, retry: candidate };
194
+ if (status === "IN_PROGRESS" || status === "QUEUED" || status === "PENDING") return { ...local, retryPending: candidate };
195
+ return local;
196
+ }
197
+
198
+ /** Read exact-head checks, conflicts and thread resolution in one metadata-only GraphQL call. */
199
+ async function pollCiSnapshot(watch: CiWatch, required: readonly string[], run: SdlcGh): Promise<CiSnapshot> {
200
+ const { repo, pr, head, phase } = watch;
201
+ if (!REPO.test(repo) || !Number.isSafeInteger(pr) || pr < 1) return { result: "closed" };
202
+ const names = requiredCheckNames(repo, required);
203
+ const pending: CiSnapshot = { result: "pending" };
204
+ const [owner, name] = repo.split("/");
205
+ try {
206
+ const reply = await run(["api", "graphql", "-f", `query=${CI_QUERY}`, "-f", `owner=${owner}`, "-f", `name=${name}`, "-F", `number=${pr}`], 10_000, undefined, 512 * 1024);
207
+ if (reply.code !== 0 || Buffer.byteLength(reply.stdout) > 512 * 1024) return pending;
208
+ const parsed = JSON.parse(reply.stdout), body = parsed?.data?.repository?.pullRequest;
209
+ if (parsed.errors || !body || !/^[a-f0-9]{40}$/.test(body.headRefOid ?? "")) return pending;
210
+ if (body.headRefOid !== head) return { result: "superseded" };
211
+ if (body.state === "MERGED" || body.state === "CLOSED") return { result: "closed" };
212
+ if (body.state !== "OPEN" || typeof body.isDraft !== "boolean") return pending;
213
+ const mergeable = ["MERGEABLE", "CONFLICTING", "UNKNOWN"].includes(body.mergeable) ? body.mergeable as CiSnapshot["mergeable"] : undefined;
214
+ const commit = body.commits?.nodes?.[0]?.commit, rollup = commit?.statusCheckRollup, threads = body.reviewThreads;
215
+ if (commit?.oid !== head) return { ...pending, mergeable };
216
+ const rows = rollup === null ? [] : rollup?.contexts?.nodes;
217
+ const hasRuns = Array.isArray(rows) && (rows.length > 0 || rollup?.contexts?.pageInfo?.hasNextPage === true);
218
+ if ((rollup !== null && rollup?.contexts?.pageInfo?.hasNextPage !== false) || !Array.isArray(rows) || rows.length > 100
219
+ || threads?.pageInfo?.hasNextPage !== false || !Array.isArray(threads.nodes) || threads.nodes.length > 100
220
+ || !threads.nodes.every((thread: { isResolved?: unknown } | null) => typeof thread?.isResolved === "boolean")) return { ...pending, mergeable, ...(hasRuns ? { hasRuns } : {}) };
221
+ const timeline = body.timelineItems?.nodes;
222
+ if (!Array.isArray(timeline) || timeline.length > 1) return { ...pending, mergeable, ...(hasRuns ? { hasRuns } : {}) };
223
+ const readyAt = timeline.length ? Date.parse(timeline[0]?.createdAt ?? "") : undefined;
224
+ if (readyAt !== undefined && !Number.isFinite(readyAt)) return { ...pending, mergeable, ...(hasRuns ? { hasRuns } : {}) };
225
+ if (phase === "approved" && body.isDraft) return { ...pending, mergeable, hasRuns };
226
+ const statusCheckRollup = rows.map(row => ({ ...row, workflowName: row?.checkSuite?.workflowRun?.workflow?.resourcePath, runCreatedAt: row?.checkSuite?.workflowRun?.createdAt }));
227
+ let result = evaluateCi({ ...body, statusCheckRollup }, names, phase === "draft", readyAt);
228
+ if (!body.isDraft && phase !== "draft") result = retryWorkflowFailure(watch, names, statusCheckRollup, result, readyAt);
229
+ if (phase === "approved" && result.result === "passed" && (mergeable !== "MERGEABLE" || threads.nodes.some((thread: { isResolved: boolean }) => !thread.isResolved))) {
230
+ return { ...pending, mergeable, hasRuns };
231
+ }
232
+ return { ...result, mergeable, hasRuns };
233
+ } catch { return pending; }
234
+ }
235
+
236
+ export type CiRetryDecision = "waiting" | "reserved" | "confirmed" | "unconfirmed" | "ineligible" | "stale" | "stale-unconfirmed" | "final";
237
+
73
238
  export interface CiWatchersOptions {
74
239
  deadlineMs?: number;
240
+ missingRunMs?: number;
75
241
  pollMs?: number;
76
242
  now?: () => number;
77
- poll: (watch: CiWatch) => Promise<CiPoll>;
78
- /** False once the task moved or its head changed: the watcher ends without a notice. */
243
+ poll: (watch: CiWatch) => Promise<CiPoll | CiSnapshot>;
79
244
  current: (watch: CiWatch) => boolean;
80
- finish: (watch: CiWatch, outcome: CiOutcome) => void | Promise<void>;
245
+ retry?: (watch: CiWatch, attempt: CiShardRetry, completed: boolean, mergeable: boolean) => Promise<CiRetryDecision>;
246
+ finish: (watch: CiWatch, outcome: CiOutcome, snapshot?: CiSnapshot) => void | Promise<void>;
81
247
  }
82
248
 
83
- /**
84
- * At most one watcher per task, and one per exact head. Only `passed` settles a head for good (#540): after `failed` or
85
- * `incomplete` the watcher keeps reading until its deadline, so a rerun of the same head (a new run attempt reads as pending,
86
- * which renews the deadline once per newly told result) is reported too, and a later `start` at that head watches again. Each (head, outcome) is told once. Timers are chained `setTimeout`s (never an interval), unref'd, and cleared
87
- * on every end, so nothing outlives its deadline, a newer head or `stopAll`. Watchers are not restored after a hub restart:
88
- * the next `hub_task_done` starts one (ponytail: persist them only if restarts during CI turn out to be common).
89
- */
249
+ type Reports = { head: string; repo: string; pr: number; keys: Set<string>; missingRunAt: number; sawRuns: boolean; last?: CiOutcome };
250
+
251
+ /** Keep one timer and one in-flight read per task PR head; phase changes renew its deadline, not its head-wide notices. */
90
252
  export class CiWatchers {
91
253
  private readonly active = new Map<number, Entry>();
92
- private readonly settled = new Map<number, { head: string; outcomes: Set<CiOutcome>; last: CiOutcome }>();
254
+ private readonly settled = new Map<number, Reports>();
93
255
  private readonly deadlineMs: number;
256
+ private readonly missingRunMs: number;
94
257
  private readonly pollMs: number;
95
258
  private readonly now: () => number;
96
259
 
97
260
  constructor(private readonly o: CiWatchersOptions) {
98
261
  this.deadlineMs = o.deadlineMs ?? CI_WATCH_DEADLINE_MS;
262
+ this.missingRunMs = o.missingRunMs ?? CI_MISSING_RUN_MS;
99
263
  this.pollMs = o.pollMs ?? CI_WATCH_POLL_MS;
100
264
  this.now = o.now ?? Date.now;
101
265
  }
102
266
 
103
267
  get size(): number { return this.active.size; }
104
268
 
105
- /** Starts a watcher for this exact head; false when this head is already watched or already passed. A different head replaces the old watcher. */
106
- start(target: { id: number; head: string; repo: string; pr: number }): boolean {
107
- const have = this.active.get(target.id), done = this.reported(target.id, target.head);
108
- if (have?.watch.head === target.head || done?.has("passed")) return false;
269
+ start(target: Omit<CiWatch, "deadlineAt" | "phase"> & { phase?: CiPhase }, alreadyPassed = false): boolean {
270
+ const have = this.active.get(target.id), phase = target.phase ?? "review";
271
+ const watch: CiWatch = { ...target, phase, deadlineAt: this.now() + this.deadlineMs };
272
+ const saved = this.reports(watch);
273
+ if (alreadyPassed) saved.keys.add(this.key(watch, "passed"));
274
+ if (have?.watch.head === target.head && have.watch.repo === target.repo && have.watch.pr === target.pr) {
275
+ if (have.watch.phase === phase) return false;
276
+ have.watch = watch;
277
+ have.renew = false;
278
+ have.awaitingRetry = undefined;
279
+ if (!have.reading) { clearTimeout(have.timer); this.schedule(have); }
280
+ return true;
281
+ }
109
282
  if (have) this.cancel(target.id);
110
- const entry: Entry = { watch: { ...target, deadlineAt: this.now() + this.deadlineMs }, reported: !!done?.size };
283
+ const entry: Entry = { watch, conflicts: 0 };
111
284
  this.active.set(target.id, entry);
112
285
  this.schedule(entry);
113
286
  return true;
114
287
  }
115
288
 
116
- /** The latest result reported for this exact head, if any. */
289
+ /** The most recent reported outcome at this head. */
117
290
  outcomeOf(id: number, head: string): CiOutcome | undefined {
118
291
  const done = this.settled.get(id);
119
292
  return done?.head === head ? done.last : undefined;
120
293
  }
121
294
 
122
- private reported(id: number, head: string): Set<CiOutcome> | undefined {
123
- const done = this.settled.get(id);
124
- return done?.head === head ? done.outcomes : undefined;
295
+ private reports(watch: CiWatch): Reports {
296
+ const previous = this.settled.get(watch.id);
297
+ if (previous?.head === watch.head && previous.repo === watch.repo && previous.pr === watch.pr) return previous;
298
+ const next: Reports = { head: watch.head, repo: watch.repo, pr: watch.pr, keys: new Set(), missingRunAt: this.now() + this.missingRunMs, sawRuns: false };
299
+ this.settled.delete(watch.id);
300
+ this.settled.set(watch.id, next);
301
+ while (this.settled.size > SETTLED_CAP) this.settled.delete(this.settled.keys().next().value as number);
302
+ return next;
303
+ }
304
+
305
+ private key(watch: CiWatch, outcome: CiOutcome): string {
306
+ return outcome === "conflicting" || outcome === "missing-run" ? outcome : `${watch.phase}:${outcome}`;
125
307
  }
126
308
 
127
- /** Ends the task's watcher (a given head only when `head` is named). No notice. */
128
309
  cancel(id: number, head?: string): void {
129
310
  const entry = this.active.get(id);
130
311
  if (!entry || head !== undefined && entry.watch.head !== head) return;
131
- clearTimeout(entry.timer);
132
- this.active.delete(id);
312
+ this.end(entry);
133
313
  }
134
314
 
135
315
  stopAll(): void {
@@ -150,43 +330,95 @@ export class CiWatchers {
150
330
  return true;
151
331
  }
152
332
 
153
- private report(entry: Entry, outcome: CiOutcome): void {
154
- if (outcome !== "deadline") {
155
- const outcomes = this.reported(entry.watch.id, entry.watch.head) ?? new Set<CiOutcome>();
156
- outcomes.add(outcome);
157
- entry.reported = true;
158
- entry.renew = true;
159
- this.settled.delete(entry.watch.id);
160
- this.settled.set(entry.watch.id, { head: entry.watch.head, outcomes, last: outcome });
161
- while (this.settled.size > SETTLED_CAP) this.settled.delete(this.settled.keys().next().value as number);
162
- }
163
- void Promise.resolve().then(() => this.o.finish(entry.watch, outcome)).catch(() => { /* the finisher guards its own notices */ });
333
+ private report(watch: CiWatch, outcome: CiOutcome, snapshot?: CiSnapshot, final?: CiShardRetry): boolean {
334
+ const saved = this.reports(watch), phaseKey = this.key(watch, outcome);
335
+ const key = final ? `${phaseKey}:${final.job}:${final.startedAt}` : phaseKey;
336
+ if (saved.keys.has(key)) return false;
337
+ saved.keys.add(key);
338
+ if (final) saved.keys.add(phaseKey);
339
+ if (outcome === "passed" || outcome === "failed" || outcome === "incomplete") saved.last = outcome;
340
+ void Promise.resolve().then(() => this.o.finish(watch, outcome, snapshot)).catch(() => { /* the finisher guards its own notices */ });
341
+ return true;
164
342
  }
165
343
 
166
- /** A watcher never throws out of its timer: a `current` or `finish` that fails (a closed board at shutdown) ends it. */
167
344
  private async tick(entry: Entry): Promise<void> {
168
345
  try { await this.step(entry); } catch { this.end(entry); }
169
346
  }
170
347
 
348
+ private expire(entry: Entry): boolean {
349
+ const { watch } = entry;
350
+ if (this.now() < watch.deadlineAt) return false;
351
+ if (this.end(entry) && (entry.awaitingRetry || !(["passed", "failed", "incomplete"] as const)
352
+ .some(outcome => this.reports(watch).keys.has(this.key(watch, outcome))))) this.report(watch, "deadline");
353
+ return true;
354
+ }
355
+
171
356
  private async step(entry: Entry): Promise<void> {
172
357
  entry.timer = undefined;
173
- if (this.active.get(entry.watch.id) !== entry) return;
174
- if (!this.o.current(entry.watch)) { this.end(entry); return; }
175
- // A deadline after a reported result ends silently: that result was already told.
176
- if (this.now() >= entry.watch.deadlineAt) { if (this.end(entry) && !entry.reported) this.report(entry, "deadline"); return; }
177
- let result: CiPoll;
178
- try { result = await this.o.poll(entry.watch); } catch { result = "pending"; }
179
- if (this.active.get(entry.watch.id) !== entry) return; // cancelled or replaced during the read
180
- if (!this.o.current(entry.watch) || result === "superseded" || result === "closed") { this.end(entry); return; }
358
+ const watch = entry.watch;
359
+ if (this.active.get(watch.id) !== entry) return;
360
+ if (!this.o.current(watch)) { this.end(entry); return; }
361
+ if (this.expire(entry)) return;
362
+ let snapshot: CiSnapshot;
363
+ entry.reading = true;
364
+ try {
365
+ const value = await this.o.poll(watch);
366
+ snapshot = typeof value === "string" ? { result: value } : value;
367
+ } catch { snapshot = { result: "pending" }; }
368
+ finally { entry.reading = false; }
369
+ if (this.active.get(watch.id) !== entry) return;
370
+ if (entry.watch !== watch) { this.schedule(entry); return; }
371
+ const result = snapshot.result;
372
+ if (!this.o.current(watch) || result === "superseded" || result === "closed") { this.end(entry); return; }
373
+ const reports = this.reports(watch);
374
+ if (snapshot.hasRuns) reports.sawRuns = true;
375
+ if (this.expire(entry)) return;
376
+ if (snapshot.mergeable !== "CONFLICTING" && snapshot.hasRuns === false && !reports.sawRuns && this.now() >= reports.missingRunAt) this.report(watch, "missing-run", snapshot);
377
+ entry.conflicts = snapshot.mergeable === "CONFLICTING" ? entry.conflicts + 1 : 0;
378
+ if (entry.conflicts >= 2) this.report(watch, "conflicting", snapshot);
379
+ if (snapshot.simultaneousShardFailures?.length && this.o.retry) {
380
+ const classify = this.o.retry;
381
+ entry.reading = true;
382
+ let stale: Set<string>;
383
+ try {
384
+ const observed = await Promise.all(snapshot.simultaneousShardFailures.map(async shard => ({
385
+ job: shard.job, decision: await classify(watch, shard, false, false),
386
+ })));
387
+ stale = new Set(observed.filter(row => row.decision === "stale" || row.decision === "stale-unconfirmed").map(row => row.job));
388
+ } finally { entry.reading = false; }
389
+ if (this.active.get(watch.id) !== entry) return;
390
+ if (entry.watch !== watch) { this.schedule(entry); return; }
391
+ if (!this.o.current(watch)) { this.end(entry); return; }
392
+ const failedChecks = snapshot.failedChecks?.filter(name => !stale.has(name));
393
+ if (!failedChecks?.length) { this.schedule(entry); return; }
394
+ snapshot = { ...snapshot, failedChecks };
395
+ }
396
+ const candidate = snapshot.retry ?? snapshot.retryPending;
397
+ const awaiting = entry.awaitingRetry;
398
+ let retry: CiRetryDecision = "ineligible";
399
+ if (candidate && this.o.retry) {
400
+ entry.reading = true;
401
+ try { retry = await this.o.retry(watch, candidate, snapshot.retry !== undefined, snapshot.mergeable === "MERGEABLE"); } finally { entry.reading = false; }
402
+ if (this.active.get(watch.id) !== entry) return;
403
+ if (entry.watch !== watch) { this.schedule(entry); return; }
404
+ if (!this.o.current(watch)) { this.end(entry); return; }
405
+ if (retry === "unconfirmed" || retry === "stale-unconfirmed" || retry === "stale") entry.renew = false;
406
+ if (retry === "stale") entry.awaitingRetry = candidate;
407
+ if (retry === "confirmed") {
408
+ watch.deadlineAt = this.now() + this.deadlineMs;
409
+ entry.awaitingRetry = candidate;
410
+ entry.renew = false;
411
+ reports.keys.delete(this.key(watch, "failed"));
412
+ }
413
+ if (retry === "waiting" || retry === "reserved" || retry === "confirmed" || retry === "stale" || retry === "stale-unconfirmed") { this.schedule(entry); return; }
414
+ }
181
415
  if (result === "pending") {
182
- // The first pending read after a newly told result is a new run attempt of this head: it gets one full deadline of its own.
183
- // Later pending reads (an unreadable gh is pending too) and an unchanged failed result keep that deadline, so the watcher always ends.
184
- if (entry.renew) { entry.renew = false; entry.watch.deadlineAt = this.now() + this.deadlineMs; }
185
- this.schedule(entry); return;
416
+ if (entry.renew) { entry.renew = false; watch.deadlineAt = this.now() + this.deadlineMs; }
417
+ } else if (snapshot.mergeable !== "CONFLICTING" || ((awaiting || retry === "final") && result === "failed")) {
418
+ entry.awaitingRetry = undefined;
419
+ const reported = awaiting && result === "failed" ? { ...snapshot, retryWorkflowFailure: true as const } : snapshot;
420
+ if (this.report(watch, result, reported, retry === "final" ? candidate : undefined)) entry.renew = result !== "passed" && retry !== "unconfirmed" && retry !== "final";
186
421
  }
187
- if (result === "passed") { if (this.end(entry)) this.report(entry, result); return; }
188
- // failed or incomplete: told once per outcome, then keep reading for a rerun of the same head.
189
- if (!this.reported(entry.watch.id, entry.watch.head)?.has(result)) this.report(entry, result);
190
422
  this.schedule(entry);
191
423
  }
192
424
  }
@@ -8,7 +8,7 @@ import { actionPolicyConfig } from "./action-policy.ts";
8
8
  import { adapterModuleDeclarations } from "../adapters/external-modules.ts";
9
9
  import { externalMetadataDefinitions, type ExternalAdapterMetadata } from "../adapters/external-metadata.ts";
10
10
  import { reviewerPoolConfig } from "./reviewer-pool-config.ts";
11
- import type { HubConfig } from "./daemon.ts";
11
+ import type { HubConfig } from "./config.ts";
12
12
  import { ALL_MACHINE_LOCAL, configRepositoryPresent, configTracked } from "./config-trust.ts";
13
13
  import { structuralLeaf } from "./config-tier.ts";
14
14
  import { createProjectAdapterCatalog, type ProjectAdapterCatalog, ADAPTERS, DEFAULT_REVIEW_POOL, REVIEW_POOL_KINDS, SUPPORTED_PEERS, PLANNER_PEERS, START_MODE_PEERS } from "../adapters/registry.ts";