@staix/agent-hub 0.43.0 → 0.45.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 +61 -0
- package/README.md +3 -8
- package/docs/agent-notes/adapters.md +2 -2
- package/docs/agent-notes/daemon.md +4 -4
- package/docs/agent-notes/local-worker.md +2 -1
- package/docs/agent-notes/security-review.md +1 -1
- package/docs/agent-notes/tasks.md +5 -2
- package/docs/agent-notes/tests.md +4 -3
- package/docs/design/adapters.md +4 -2
- package/docs/design/agent-hub-architecture.md +2 -0
- package/docs/design/agent-hub.md +1 -1
- package/docs/design/roadmap.md +75 -2
- package/docs/design/supervision.md +34 -2
- package/docs/design/task-board.md +36 -2
- package/docs/dogfood.md +20 -5
- package/docs/events.md +9 -3
- package/docs/influences.md +7 -0
- package/docs/memory.md +4 -4
- package/docs/operations.md +84 -31
- package/docs/quickstart.md +14 -2
- package/docs/research.md +18 -0
- package/docs/roadmap.json +4 -0
- package/docs/roadmap.md +9 -0
- package/docs/sdlc.md +19 -4
- package/docs/security.md +4 -4
- package/docs/verification/2026-11-11-supervision-pilot-1221.md +864 -0
- package/docs/verification/2026-11-19-0.44.0.md +60 -0
- package/docs/verification/2026-11-19-claude-implementer-2.1.328.md +49 -0
- package/docs/verification/2026-11-20-claude-implementer-2.1.329.md +49 -0
- package/docs/verification/2026-11-20-sdlc-metrics-diagnosis.md +7 -0
- package/docs/verification/2026-11-21-0.45.0.md +69 -0
- package/docs/verification/2026-11-22-codex-0171-reviewer-isolation.md +47 -0
- package/docs/verified.json +32 -26
- package/package.json +2 -2
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +585 -264
- package/plugins/agent-hub/kimi-review-policy-worker.js +5 -5
- package/plugins/agent-hub/server.js +629 -293
- package/scripts/check-docs.mjs +9 -1
- package/src/adapters/acp.ts +11 -1
- package/src/adapters/compat.ts +3 -3
- package/src/adapters/definitions/builtin-metadata.ts +2 -2
- package/src/adapters/definitions/native-context.ts +10 -0
- package/src/adapters/jcode.ts +10 -0
- package/src/adapters/local-worker.ts +3 -2
- package/src/adapters/pi.ts +15 -4
- package/src/cli/console-state.ts +3 -1
- package/src/cli/help.ts +3 -1
- package/src/cli/identity.ts +2 -1
- package/src/cli/main.ts +12 -6
- package/src/cli/output.ts +2 -2
- package/src/cli/recovery-package.ts +16 -3
- package/src/cli/roadmap-write.ts +59 -0
- package/src/cli/roadmap.ts +81 -4
- package/src/cli/sdlc-output.ts +11 -1
- package/src/cli/upgrade-runtime.ts +10 -6
- package/src/cli/upgrade.ts +9 -3
- package/src/hub/agent-mem-range.ts +43 -0
- package/src/hub/board.ts +116 -2
- package/src/hub/bus.ts +4 -0
- package/src/hub/check-runner.ts +25 -1
- package/src/hub/claude-shell-wrapper.ts +2 -1
- package/src/hub/config-apply.ts +4 -2
- package/src/hub/config-trust.ts +1 -1
- package/src/hub/context-window.ts +1 -1
- package/src/hub/control-write-trace.ts +39 -2
- package/src/hub/cost-governance.ts +11 -7
- package/src/hub/daemon.ts +318 -53
- package/src/hub/dogfood-read.ts +4 -2
- package/src/hub/edit-guard.ts +100 -0
- package/src/hub/events.ts +79 -8
- package/src/hub/facts.ts +85 -2
- package/src/hub/hub-tools.ts +3 -1
- package/src/hub/lifecycle.ts +6 -1
- package/src/hub/log-rotation.ts +130 -0
- package/src/hub/memory-profile.ts +137 -21
- package/src/hub/no-writes.ts +1 -0
- package/src/hub/operational-authority.ts +3 -2
- package/src/hub/operational-settings.ts +2 -2
- package/src/hub/quota-events.ts +40 -0
- package/src/hub/recovery-store.ts +70 -24
- package/src/hub/report.ts +1 -1
- package/src/hub/research-experiments.ts +132 -0
- package/src/hub/research-quality.ts +13 -3
- package/src/hub/research-record.ts +38 -2
- package/src/hub/research.ts +128 -28
- package/src/hub/restart.ts +49 -2
- package/src/hub/roadmap-check.ts +65 -0
- package/src/hub/roadmap-decompose.ts +80 -0
- package/src/hub/roadmap-export.ts +27 -0
- package/src/hub/roadmap-sync.ts +97 -0
- package/src/hub/roadmap.ts +40 -0
- package/src/hub/runtime-capture-prune.ts +9 -1
- package/src/hub/runtime-prune-health.ts +5 -1
- package/src/hub/sdlc-branch-ci.ts +128 -0
- package/src/hub/sdlc-merge.ts +12 -5
- package/src/hub/sdlc-metrics.ts +33 -10
- package/src/hub/sdlc.ts +90 -10
- package/src/hub/settings.ts +1 -0
- package/src/hub/snapshots.ts +56 -1
- package/src/hub/startup-event-seeds.ts +21 -15
- package/src/hub/startup-timing.ts +3 -1
- package/src/hub/supervision-proposals.ts +10 -2
- package/src/hub/supervision-rules.ts +27 -4
- package/src/hub/supervision.ts +7 -0
- package/src/hub/task-pr.ts +47 -0
- package/src/hub/task-shell-command.ts +124 -0
- package/src/hub/task-worktree.ts +18 -11
- package/src/hub/tasks.ts +617 -45
- package/src/hub/usage-rollup.ts +35 -20
- package/src/hub/worktree-shelf.ts +2 -1
- package/src/local/sandbox.ts +2 -1
- package/src/local/shell-environment.ts +6 -0
- package/src/local/tools.ts +13 -1
- package/src/memory/brief.ts +10 -1
- package/src/memory/client.ts +3 -2
- package/src/pi/extension.ts +15 -3
- package/src/pi/tool-receipts.ts +26 -0
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { githubRepo, milestoneId } from "./roadmap.ts";
|
|
3
|
+
import type { SdlcGh } from "./sdlc.ts";
|
|
4
|
+
|
|
5
|
+
export interface MirrorIssue { number: number; milestone: number | null }
|
|
6
|
+
export interface MirrorMilestone { number: number; title: string; state: "open" | "closed" }
|
|
7
|
+
export interface MirrorDesired { title: string; state: "open" | "closed"; issues: number[]; marker: string }
|
|
8
|
+
export interface MirrorPlan { calls: string[][]; fingerprint: string }
|
|
9
|
+
export interface MirrorSnapshot { milestones: (MirrorMilestone & MarkerMilestone)[]; issues: MirrorIssue[] }
|
|
10
|
+
|
|
11
|
+
/** Complete bounded metadata-only pages. A failed or full last page refuses every write plan. */
|
|
12
|
+
export async function readMirrorSnapshot(repoInput: string, run: SdlcGh): Promise<MirrorSnapshot> {
|
|
13
|
+
const repo = githubRepo(repoInput), deadline = performance.now() + 20_000;
|
|
14
|
+
const pages = async (kind: "milestones" | "issues"): Promise<Record<string, unknown>[]> => {
|
|
15
|
+
const rows: Record<string, unknown>[] = [], seen = new Set<number>();
|
|
16
|
+
// ponytail: this all-state inventory has a 1000-row ceiling including pull requests; page milestone members and desired issues separately to remove it.
|
|
17
|
+
for (let page = 1; page <= 10; page++) {
|
|
18
|
+
const left = deadline - performance.now();
|
|
19
|
+
if (left <= 0) throw new Error("roadmap mirror inventory timed out");
|
|
20
|
+
const projection = kind === "milestones" ? "[.[]|{number,title,state,description,html_url}]" : "[.[]|{number,html_url,milestone:(.milestone|if . == null then null else {number} end),pull_request:(.pull_request!=null)}]";
|
|
21
|
+
const result = await run(["api", `repos/${repo}/${kind}?state=all&per_page=100&page=${page}`, "--hostname", "github.com", "--jq", projection], Math.min(left, 10_000), undefined, 2 * 1024 * 1024);
|
|
22
|
+
if (performance.now() > deadline || result.code !== 0 || Buffer.byteLength(result.stdout) > 2 * 1024 * 1024) throw new Error("roadmap mirror inventory unavailable");
|
|
23
|
+
const raw: unknown = JSON.parse(result.stdout);
|
|
24
|
+
if (!Array.isArray(raw) || raw.length > 100) throw new Error("roadmap mirror inventory malformed");
|
|
25
|
+
for (const item of raw) {
|
|
26
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) throw new Error("roadmap mirror inventory malformed");
|
|
27
|
+
const row = item as Record<string, unknown>, id = milestoneId(row.number);
|
|
28
|
+
if (seen.has(id)) throw new Error("roadmap mirror inventory duplicated");
|
|
29
|
+
seen.add(id); rows.push(row);
|
|
30
|
+
}
|
|
31
|
+
if (raw.length < 100) return rows;
|
|
32
|
+
}
|
|
33
|
+
throw new Error("roadmap mirror inventory incomplete");
|
|
34
|
+
};
|
|
35
|
+
const milestones = (await pages("milestones")).map(row => {
|
|
36
|
+
if (typeof row.title !== "string" || row.title.length > 300 || row.state !== "open" && row.state !== "closed" || row.description !== null && typeof row.description !== "string" || typeof row.html_url !== "string" || row.html_url.toLowerCase() !== `https://github.com/${repo}/milestone/${milestoneId(row.number)}`) throw new Error("roadmap mirror milestone malformed");
|
|
37
|
+
return { number: milestoneId(row.number), title: row.title, state: row.state, description: row.description } as MirrorMilestone & MarkerMilestone;
|
|
38
|
+
});
|
|
39
|
+
const issueRows = await pages("issues");
|
|
40
|
+
if (issueRows.some(row => typeof row.pull_request !== "boolean")) throw new Error("roadmap mirror issue malformed");
|
|
41
|
+
const issues = issueRows.filter(row => row.pull_request === false).map(row => {
|
|
42
|
+
const value = row.milestone;
|
|
43
|
+
if (value !== null && (!value || typeof value !== "object" || Array.isArray(value)) || typeof row.html_url !== "string" || row.html_url.toLowerCase() !== `https://github.com/${repo}/issues/${milestoneId(row.number)}`) throw new Error("roadmap mirror issue malformed");
|
|
44
|
+
return { number: milestoneId(row.number), milestone: value === null ? null : milestoneId((value as Record<string, unknown>).number) };
|
|
45
|
+
});
|
|
46
|
+
return { milestones, issues };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface MarkerMilestone { number: number; title: string; description: string | null }
|
|
50
|
+
export type MirrorRecovery = (
|
|
51
|
+
| { kind: "create" }
|
|
52
|
+
| { kind: "bind"; number: number }
|
|
53
|
+
| { kind: "ambiguous"; numbers: number[] }
|
|
54
|
+
) & { titleConflicts: number[] };
|
|
55
|
+
|
|
56
|
+
/** Resolve a lost create response without ever inferring identity from a title. */
|
|
57
|
+
export function recoverMirrorBinding(marker: string, title: string, remote: readonly MarkerMilestone[]): MirrorRecovery {
|
|
58
|
+
if (!/^<!-- ahub-roadmap:[A-Za-z0-9._-]+:[1-9][0-9]* -->$/.test(marker)) throw new Error("invalid roadmap marker");
|
|
59
|
+
const marked = remote.filter(row => row.description?.includes(marker)).map(row => milestoneId(row.number)).sort((a, b) => a - b);
|
|
60
|
+
const titleConflicts = remote.filter(row => row.title === title && !row.description?.includes(marker)).map(row => milestoneId(row.number)).sort((a, b) => a - b);
|
|
61
|
+
if (marked.length > 1) return { kind: "ambiguous", numbers: marked, titleConflicts };
|
|
62
|
+
if (marked.length === 1) return { kind: "bind", number: marked[0]!, titleConflicts };
|
|
63
|
+
return { kind: "create", titleConflicts };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Plan one public milestone against a complete, host-validated snapshot. Never applies it. */
|
|
67
|
+
export function planRoadmapMirror(repoInput: string, desired: MirrorDesired, remote: MirrorMilestone | null, issues: readonly MirrorIssue[]): MirrorPlan {
|
|
68
|
+
const repo = githubRepo(repoInput);
|
|
69
|
+
if (!/^<!-- ahub-roadmap:[A-Za-z0-9._-]+:[1-9][0-9]* -->$/.test(desired.marker)) throw new Error("invalid roadmap marker");
|
|
70
|
+
if (typeof desired.title !== "string" || !desired.title.trim() || desired.title.length > 300 || /[\p{Cc}\p{Cf}]/u.test(desired.title)
|
|
71
|
+
|| !["open", "closed"].includes(desired.state)) throw new Error("invalid public milestone");
|
|
72
|
+
const desiredIds = new Set(desired.issues.map(milestoneId));
|
|
73
|
+
if (desiredIds.size !== desired.issues.length) throw new Error("duplicate issue membership");
|
|
74
|
+
const calls: string[][] = [];
|
|
75
|
+
if (remote === null) {
|
|
76
|
+
// The server assigns the number. A later preview plans membership separately.
|
|
77
|
+
calls.push(["api", `repos/${repo}/milestones`, "--hostname", "github.com", "--method", "POST", "-f", `title=${desired.title}`, "-f", `state=${desired.state}`, "-f", `description=${desired.marker}`]);
|
|
78
|
+
} else {
|
|
79
|
+
const number = milestoneId(remote.number);
|
|
80
|
+
if (remote.state !== "open" && remote.state !== "closed") throw new Error("invalid remote milestone state");
|
|
81
|
+
if (remote.title !== desired.title || remote.state !== desired.state)
|
|
82
|
+
calls.push(["api", `repos/${repo}/milestones/${number}`, "--hostname", "github.com", "--method", "PATCH", "-f", `title=${desired.title}`, "-f", `state=${desired.state}`]);
|
|
83
|
+
const seen = new Set<number>();
|
|
84
|
+
for (const issue of [...issues].sort((a, b) => a.number - b.number)) {
|
|
85
|
+
const id = milestoneId(issue.number);
|
|
86
|
+
if (seen.has(id)) throw new Error("duplicate remote issue");
|
|
87
|
+
seen.add(id);
|
|
88
|
+
if (issue.milestone !== null) milestoneId(issue.milestone);
|
|
89
|
+
if (desiredIds.has(id) && issue.milestone !== number)
|
|
90
|
+
calls.push(["api", `repos/${repo}/issues/${id}`, "--hostname", "github.com", "--method", "PATCH", "-F", `milestone=${number}`]);
|
|
91
|
+
else if (!desiredIds.has(id) && issue.milestone === number)
|
|
92
|
+
calls.push(["api", `repos/${repo}/issues/${id}`, "--hostname", "github.com", "--method", "PATCH", "-F", "milestone=null"]);
|
|
93
|
+
}
|
|
94
|
+
if ([...desiredIds].some(id => !seen.has(id))) throw new Error("issue membership snapshot is incomplete");
|
|
95
|
+
}
|
|
96
|
+
return { calls, fingerprint: createHash("sha256").update(JSON.stringify(calls)).digest("hex") };
|
|
97
|
+
}
|
package/src/hub/roadmap.ts
CHANGED
|
@@ -3,6 +3,13 @@ export const MILESTONE_STATES = ["proposed", "planned", "active", "done", "dropp
|
|
|
3
3
|
export const MILESTONE_HORIZONS = ["now", "next", "later"] as const;
|
|
4
4
|
export const MILESTONE_LINK_KINDS = ["spec", "issue", "task", "release"] as const;
|
|
5
5
|
export const MILESTONE_HISTORY_LIMIT = 256;
|
|
6
|
+
export interface RoadmapConfig { github_mirror: boolean; github_write: "off" | "conductor" }
|
|
7
|
+
export function roadmapConfig(raw: unknown): RoadmapConfig {
|
|
8
|
+
if (raw === undefined) return { github_mirror: false, github_write: "off" };
|
|
9
|
+
const row = object(raw);
|
|
10
|
+
if (Object.keys(row).some(key => key !== "github_mirror" && key !== "github_write") || row.github_mirror !== undefined && typeof row.github_mirror !== "boolean" || row.github_write !== undefined && row.github_write !== "off" && row.github_write !== "conductor") throw new Error("roadmap config requires github_mirror boolean and github_write off or conductor");
|
|
11
|
+
return { github_mirror: row.github_mirror === true, github_write: row.github_write === "conductor" ? "conductor" : "off" };
|
|
12
|
+
}
|
|
6
13
|
export const MILESTONE_LIMITS = Object.freeze({ title: 300, outcome: 4000, spec: 160, issue: 300, actor: 64 });
|
|
7
14
|
export type MilestoneState = typeof MILESTONE_STATES[number];
|
|
8
15
|
export type MilestoneHorizon = typeof MILESTONE_HORIZONS[number];
|
|
@@ -125,3 +132,36 @@ export interface MilestoneSuggestion {
|
|
|
125
132
|
citeMilestone: string | null; citeItem: string;
|
|
126
133
|
state: SuggestionState; by: string; created: number; settled: number | null; settledBy: string | null;
|
|
127
134
|
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* R2 (#1480): a model-written decomposition of one milestone. Advisory data like a suggestion: it is stored apart from the
|
|
138
|
+
* roadmap, no accept path links anything from part 1, and a later intake reads it by id.
|
|
139
|
+
*/
|
|
140
|
+
export const DECOMPOSE_INTAKES = ["spec", "task"] as const;
|
|
141
|
+
export const DECOMPOSITION_STATES = ["pending", "accepted", "rejected", "superseded"] as const;
|
|
142
|
+
export const DECOMPOSE_LIMITS = Object.freeze({ parts: 8, title: 300, detail: 1200, cites: 16 });
|
|
143
|
+
export type DecomposeIntake = typeof DECOMPOSE_INTAKES[number];
|
|
144
|
+
export type DecompositionState = typeof DECOMPOSITION_STATES[number];
|
|
145
|
+
export interface DecomposePart {
|
|
146
|
+
title: string;
|
|
147
|
+
/** What the part changes and how it is verified. */
|
|
148
|
+
detail: string;
|
|
149
|
+
/** A hub task class, named `class` as a `hub_backlog_split` part names it. */
|
|
150
|
+
class: string;
|
|
151
|
+
/** `spec`: the part changes behaviour and needs its own spec issue; `task`: a mechanical chore that goes straight to a task. */
|
|
152
|
+
intake: DecomposeIntake;
|
|
153
|
+
/** Ids copied from what the model was shown: linked spec ids and issue refs. */
|
|
154
|
+
cites: string[];
|
|
155
|
+
}
|
|
156
|
+
export interface MilestoneDecomposition {
|
|
157
|
+
id: number; milestone: number; parts: DecomposePart[]; state: DecompositionState;
|
|
158
|
+
by: string; created: number; settled: number | null; settledBy: string | null;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* R2 part 2 (#1480): one proposed part accepted as a held intake draft. Keyed by the pending row it came from and the part's
|
|
163
|
+
* 1-based position, so a second accept of the same part finds this row instead of making a second draft.
|
|
164
|
+
*/
|
|
165
|
+
export interface DecompositionAccept {
|
|
166
|
+
decomposition: number; milestone: number; part: number; task: number; intake: DecomposeIntake; by: string; at: number;
|
|
167
|
+
}
|
|
@@ -474,14 +474,20 @@ function admissionRow(db: Database): Admission | undefined {
|
|
|
474
474
|
|| row.signature !== null && (typeof row.signature !== "string" || !row.signature.trim() || Buffer.byteLength(row.signature) > 1024))) fail("runtime maintenance admission state is invalid");
|
|
475
475
|
return rows[0];
|
|
476
476
|
}
|
|
477
|
+
/** A prune that only found recovery coordination present did nothing: it is not a completed pass (#1546). */
|
|
478
|
+
export const RECOVERY_DEFERRAL = /recovery coordination is present/;
|
|
477
479
|
function admitSchedule(home: string): string | undefined {
|
|
478
480
|
const db = startupAdmissionDatabase(home);
|
|
479
481
|
try {
|
|
480
482
|
return db.transaction(() => {
|
|
481
483
|
const previous = admissionRow(db), now = Date.now();
|
|
484
|
+
// A pass deferred only by recovery coordination starts no cooldown: the next schedule (after the lock is released) may run at once.
|
|
485
|
+
const recoveryOnly = previous?.phase === "complete" && (() => {
|
|
486
|
+
try { const o = db.query("SELECT outcome FROM admission WHERE slot=1").get() as { outcome: string | null } | null; return typeof JSON.parse(o?.outcome ?? "{}").deferred === "string" && RECOVERY_DEFERRAL.test(JSON.parse(o!.outcome!).deferred); } catch { return false; }
|
|
487
|
+
})();
|
|
482
488
|
const dead = previous?.phase === "running" && previous.pid !== null && previous.signature !== null
|
|
483
489
|
&& processLiveness(previous.pid, previous.signature) === "gone";
|
|
484
|
-
if (previous && (previous.phase === "running" && !dead || !dead && now - previous.admitted_at < RUNTIME_PRUNE_INTERVAL_MS)) return undefined;
|
|
490
|
+
if (previous && (previous.phase === "running" && !dead || !dead && !recoveryOnly && now - previous.admitted_at < RUNTIME_PRUNE_INTERVAL_MS)) return undefined;
|
|
485
491
|
const id = randomUUID();
|
|
486
492
|
db.query("INSERT OR REPLACE INTO admission(slot,id,admitted_at,phase,pid,outcome,signature) VALUES(1,?,?,'scheduled',NULL,NULL,NULL)").run(id, now);
|
|
487
493
|
return id;
|
|
@@ -497,6 +503,8 @@ export function scheduleRuntimeCapturePrune(home?: string): void {
|
|
|
497
503
|
setImmediate(() => {
|
|
498
504
|
try {
|
|
499
505
|
const targetHome = home ?? hubHome({ AGENTHUB_HOME: inheritedHome });
|
|
506
|
+
// Never schedule a pass that is bound to defer: while any recovery hold exists (or it cannot be read) the runner schedules one after its release.
|
|
507
|
+
if (anyRecoveryHold(targetHome, true)) return; // non-blocking: a locked project-locks.db is a hold, never a wait on the startup loop
|
|
500
508
|
const id = admitSchedule(targetHome); if (!id) return;
|
|
501
509
|
const env = childEnv(process.env);
|
|
502
510
|
for (const key of Object.keys(env)) if (key.startsWith("ORCA_") || ["AGENTHUB_STATE_DIR", "AGENTHUB_PROJECT_DIR", "AGENTHUB_PEER_ID", "AGENTHUB_CHANNEL", "CLAUDECODE", "CODEX_THREAD_ID"].includes(key)) delete env[key];
|
|
@@ -4,7 +4,7 @@ import { isAbsolute, join, normalize } from "node:path";
|
|
|
4
4
|
import { processLiveness } from "../pi/process-signature.ts";
|
|
5
5
|
import { hubHome } from "./project.ts";
|
|
6
6
|
import { REGISTRY_DB_BUSY_TIMEOUT_MS } from "./registry.ts";
|
|
7
|
-
import { RETAINED_SELECTED_RECEIPTS, RETAINED_TERMINAL_RECEIPTS, RUNTIME_PRUNE_INTERVAL_MS } from "./runtime-capture-prune.ts";
|
|
7
|
+
import { RECOVERY_DEFERRAL, RETAINED_SELECTED_RECEIPTS, RETAINED_TERMINAL_RECEIPTS, RUNTIME_PRUNE_INTERVAL_MS } from "./runtime-capture-prune.ts";
|
|
8
8
|
|
|
9
9
|
export interface RuntimePruneHealthCheck { ok: boolean | undefined; name: string; detail: string }
|
|
10
10
|
const MAX_LEDGER_BYTES = 1024 * 1024, MAX_OUTCOME_BYTES = 16 * 1024;
|
|
@@ -64,6 +64,10 @@ function admissionHealth(file: string): LedgerHealth {
|
|
|
64
64
|
|| !Number.isSafeInteger(outcome.removed) || (outcome.removed as number) < 0 || !Array.isArray(outcome.quarantined) || outcome.quarantined.length > MAX_QUARANTINES
|
|
65
65
|
|| outcome.quarantined.some(value => typeof value !== "string" || value.length > 4096 || isAbsolute(value) || normalize(value) !== value || value.split(/[\\/]/).some(part => part === ".."))
|
|
66
66
|
|| outcome.deferred !== undefined && (typeof outcome.deferred !== "string" || Buffer.byteLength(outcome.deferred) > 512)) throw new Error("invalid completed outcome");
|
|
67
|
+
if (typeof outcome.deferred === "string" && RECOVERY_DEFERRAL.test(outcome.deferred) && !outcome.quarantined.length) {
|
|
68
|
+
// #1546: a pass that only found recovery coordination present did nothing and is retried after the lock is released: not a failure.
|
|
69
|
+
return { checks: [issue("maintenance was deferred while recovery coordination was present; it is scheduled again after the recovery lock is released", true)], active: false };
|
|
70
|
+
}
|
|
67
71
|
if (outcome.deferred !== undefined || outcome.quarantined.length) {
|
|
68
72
|
// #1541: a deferral that already names a supported command (the receipt ceiling, an open operation) is not sent to the ledger.
|
|
69
73
|
const text = typeof outcome.deferred === "string" ? outcome.deferred.replace(/[\x00-\x1f\x7f]/g, " ") : undefined;
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import type { SdlcGh } from "./sdlc.ts";
|
|
2
|
+
|
|
3
|
+
/** Bounded GitHub evidence; missing or ambiguous coverage never becomes a count. */
|
|
4
|
+
export interface BranchCi {
|
|
5
|
+
runs: { id: number; attempt: number }[];
|
|
6
|
+
fullGateRuns: number;
|
|
7
|
+
successfulGateRuns: number;
|
|
8
|
+
failedGateRuns: number;
|
|
9
|
+
cancelledGateRuns: number;
|
|
10
|
+
otherGateRuns: number;
|
|
11
|
+
macosShardRuns: number;
|
|
12
|
+
firstPass: 0 | 1 | null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
type Row = Record<string, any>;
|
|
16
|
+
const PAGE_SIZE = 100;
|
|
17
|
+
const PAGE_LIMIT = 10;
|
|
18
|
+
const TIMEOUT = 10_000;
|
|
19
|
+
const CAP = 256 * 1024;
|
|
20
|
+
const integer = (v: unknown): v is number => Number.isSafeInteger(v) && (v as number) > 0;
|
|
21
|
+
const timestamp = (v: unknown): number => typeof v === "string" ? Date.parse(v) : NaN;
|
|
22
|
+
|
|
23
|
+
/** Read all pages, failing closed on an error, malformed page, changed total or a bounded overflow. */
|
|
24
|
+
async function pages(run: SdlcGh, endpoint: string, fields: string[], projection: string, key?: string): Promise<Row[] | undefined> {
|
|
25
|
+
const all: Row[] = []; let total: number | undefined;
|
|
26
|
+
for (let page = 1; page <= PAGE_LIMIT; page++) {
|
|
27
|
+
const reply = await run(["api", "-X", "GET", endpoint, ...fields, "-F", `per_page=${PAGE_SIZE}`, "-F", `page=${page}`, "--jq", projection], TIMEOUT, undefined, CAP);
|
|
28
|
+
if (reply.code !== 0) return;
|
|
29
|
+
const parsed = JSON.parse(reply.stdout), rows = key ? parsed?.[key] : parsed;
|
|
30
|
+
if (!Array.isArray(rows) || rows.length > PAGE_SIZE || rows.some(row => !row || typeof row !== "object")) return;
|
|
31
|
+
if (key) {
|
|
32
|
+
if (!Number.isSafeInteger(parsed.total_count) || parsed.total_count < 0 || (total !== undefined && total !== parsed.total_count)) return;
|
|
33
|
+
total = parsed.total_count;
|
|
34
|
+
}
|
|
35
|
+
all.push(...rows);
|
|
36
|
+
if (total !== undefined ? all.length === total : rows.length < PAGE_SIZE) return all;
|
|
37
|
+
if (total !== undefined && (all.length > total || rows.length < PAGE_SIZE)) return;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Associate PR workflow runs by verified same-repository branch and lifetime, not pull_requests (often empty). */
|
|
42
|
+
export async function readBranchCi(repo: string, number: number, firstHead: string | undefined, run: SdlcGh): Promise<BranchCi | undefined> {
|
|
43
|
+
try {
|
|
44
|
+
const response = await run(["api", `repos/${repo}/pulls/${number}`, "--jq", "{number,state,created_at,merged_at,head:{ref:.head.ref,repo:{full_name:.head.repo.full_name}},base:{repo:{full_name:.base.repo.full_name}}}"], TIMEOUT, undefined, CAP);
|
|
45
|
+
if (response.code !== 0) return;
|
|
46
|
+
const pr = JSON.parse(response.stdout), branch = pr?.head?.ref, start = timestamp(pr?.created_at), end = timestamp(pr?.merged_at);
|
|
47
|
+
if (pr.number !== number || pr.state !== "closed" || typeof branch !== "string" || !branch || !Number.isFinite(start) || !Number.isFinite(end) || end < start
|
|
48
|
+
|| pr.head?.repo?.full_name?.toLowerCase() !== repo.toLowerCase() || pr.base?.repo?.full_name?.toLowerCase() !== repo.toLowerCase()) return;
|
|
49
|
+
const owner = repo.split("/")[0];
|
|
50
|
+
const prs = await pages(run, `repos/${repo}/pulls`, ["-f", "state=all", "-f", `head=${owner}:${branch}`], "[.[]|{number,created_at,closed_at}]");
|
|
51
|
+
if (!prs || !prs.some(row => row.number === number)) return;
|
|
52
|
+
for (const other of prs) {
|
|
53
|
+
if (other.number === number) continue;
|
|
54
|
+
const created = timestamp(other.created_at), closed = other.closed_at === null ? Infinity : timestamp(other.closed_at);
|
|
55
|
+
if (!Number.isFinite(created) || !(Number.isFinite(closed) || closed === Infinity)) return;
|
|
56
|
+
if (created <= end && closed >= start) return;
|
|
57
|
+
}
|
|
58
|
+
const rows = await pages(run, `repos/${repo}/actions/runs`, ["-f", `branch=${branch}`, "-f", "event=pull_request"], "{total_count,workflow_runs:[.workflow_runs[]|{id,path,created_at,head_sha,status,conclusion,run_attempt,pull_requests:[.pull_requests[].number]}]}", "workflow_runs");
|
|
59
|
+
if (!rows) return;
|
|
60
|
+
if (rows.some(row => typeof row.path !== "string" || !Number.isFinite(timestamp(row.created_at)) || !Array.isArray(row.pull_requests) || row.pull_requests.some((value: unknown) => !integer(value)))) return;
|
|
61
|
+
const checks = rows.filter(row => row.path === ".github/workflows/check.yml" && timestamp(row.created_at) >= start && timestamp(row.created_at) <= end && (row.pull_requests.length === 0 || row.pull_requests.includes(number)));
|
|
62
|
+
if (checks.some(row => row.pull_requests.some((value: number) => value !== number))) return;
|
|
63
|
+
// ponytail: inspect at most one page of check runs and ten attempts each; raise the bounds with a provider-side summary.
|
|
64
|
+
if (checks.length > PAGE_SIZE || checks.some(row => !integer(row.id) || !integer(row.run_attempt) || row.run_attempt > PAGE_LIMIT || !/^[a-f0-9]{40}$/.test(row.head_sha) || typeof row.status !== "string")) return;
|
|
65
|
+
if (new Set(checks.map(row => row.id)).size !== checks.length) return;
|
|
66
|
+
const timeline = await pages(run, `repos/${repo}/issues/${number}/timeline`, [], "[.[]|{event,created_at}]");
|
|
67
|
+
if (!timeline) return;
|
|
68
|
+
const changes = timeline.filter(row => row.event === "ready_for_review" || row.event === "converted_to_draft").map(row => ({ event: row.event, at: timestamp(row.created_at) })).sort((a, b) => a.at - b.at);
|
|
69
|
+
if (changes.some(change => !Number.isFinite(change.at))) return;
|
|
70
|
+
const initialDraft = changes.length > 0 && changes[0]!.event === "ready_for_review";
|
|
71
|
+
let finalDraft = initialDraft;
|
|
72
|
+
for (const change of changes) {
|
|
73
|
+
if ((change.event === "ready_for_review") !== finalDraft) return;
|
|
74
|
+
finalDraft = change.event === "converted_to_draft";
|
|
75
|
+
}
|
|
76
|
+
if (finalDraft) return;
|
|
77
|
+
const draftAt = (at: number): boolean | undefined => {
|
|
78
|
+
let draft = initialDraft;
|
|
79
|
+
for (const change of changes) {
|
|
80
|
+
if (change.at === at) return;
|
|
81
|
+
if (change.at > at) break;
|
|
82
|
+
if ((change.event === "ready_for_review") !== draft) return;
|
|
83
|
+
draft = change.event === "converted_to_draft";
|
|
84
|
+
}
|
|
85
|
+
return draft;
|
|
86
|
+
};
|
|
87
|
+
let macosShardRuns = 0, firstPass: 0 | 1 | null = null, firstDecided = false;
|
|
88
|
+
const observedRuns: { id: number; attempt: number; conclusion: string }[] = [];
|
|
89
|
+
const ordered = checks.sort((a, b) => timestamp(a.created_at) - timestamp(b.created_at) || a.id - b.id);
|
|
90
|
+
const firstHeadTimes = ordered.filter(row => firstHead && row.head_sha === firstHead).map(row => timestamp(row.created_at));
|
|
91
|
+
const firstOrderAmbiguous = new Set(firstHeadTimes).size !== firstHeadTimes.length;
|
|
92
|
+
for (const check of ordered) {
|
|
93
|
+
let atMerge: { id: number; attempt: number; conclusion: string } | undefined;
|
|
94
|
+
let previousStarted = -Infinity;
|
|
95
|
+
for (let attempt = 1; attempt <= check.run_attempt; attempt++) {
|
|
96
|
+
const attemptReply = await run(["api", `repos/${repo}/actions/runs/${check.id}/attempts/${attempt}`, "--jq", "{id,run_attempt,status,conclusion,run_started_at,updated_at}"], TIMEOUT, undefined, CAP);
|
|
97
|
+
if (attemptReply.code !== 0) return;
|
|
98
|
+
const observed = JSON.parse(attemptReply.stdout), started = timestamp(observed.run_started_at), updated = timestamp(observed.updated_at);
|
|
99
|
+
if (observed.id !== check.id || observed.run_attempt !== attempt || !Number.isFinite(started) || !Number.isFinite(updated) || started < previousStarted || updated < started || started === end || updated === end) return;
|
|
100
|
+
previousStarted = started;
|
|
101
|
+
if (started > end) continue;
|
|
102
|
+
if (observed.status !== "completed" || typeof observed.conclusion !== "string" || updated > end) return;
|
|
103
|
+
atMerge = { id: check.id, attempt, conclusion: observed.conclusion };
|
|
104
|
+
const jobs = await pages(run, `repos/${repo}/actions/runs/${check.id}/attempts/${attempt}/jobs`, [], "{total_count,jobs:[.jobs[]|{name,status,conclusion,runner_id}]}", "jobs");
|
|
105
|
+
if (!jobs || jobs.some(job => typeof job.name !== "string")) return;
|
|
106
|
+
const shards = jobs.filter(job => /^check \(macos-latest\) shard [1-4]\/4$/.test(job.name));
|
|
107
|
+
if (shards.some(job => job.status !== "completed" || typeof job.conclusion !== "string" || !(job.runner_id === null || job.runner_id === 0 || integer(job.runner_id)) || (job.runner_id === null || job.runner_id === 0) && job.conclusion !== "skipped" && job.conclusion !== "cancelled")) return;
|
|
108
|
+
const ran = shards.filter(job => job.conclusion !== "skipped" && integer(job.runner_id));
|
|
109
|
+
macosShardRuns += ran.length;
|
|
110
|
+
if (attempt !== 1 || firstDecided || !firstHead || check.head_sha !== firstHead) continue;
|
|
111
|
+
const draft = draftAt(timestamp(check.created_at));
|
|
112
|
+
if (draft === undefined) return;
|
|
113
|
+
if (draft || ran.length === 0 || observed.status !== "completed" || observed.conclusion === "cancelled") continue;
|
|
114
|
+
if (observed.conclusion === "success") firstPass = 1;
|
|
115
|
+
else if (observed.conclusion === "failure" || observed.conclusion === "timed_out") firstPass = 0;
|
|
116
|
+
else return;
|
|
117
|
+
firstDecided = true;
|
|
118
|
+
}
|
|
119
|
+
if (!atMerge) return;
|
|
120
|
+
observedRuns.push(atMerge);
|
|
121
|
+
}
|
|
122
|
+
const successfulGateRuns = observedRuns.filter(row => row.conclusion === "success").length;
|
|
123
|
+
const failedGateRuns = observedRuns.filter(row => row.conclusion === "failure" || row.conclusion === "timed_out").length;
|
|
124
|
+
const cancelledGateRuns = observedRuns.filter(row => row.conclusion === "cancelled").length;
|
|
125
|
+
return { runs: observedRuns.map(row => ({ id: row.id, attempt: row.attempt })), fullGateRuns: observedRuns.length,
|
|
126
|
+
successfulGateRuns, failedGateRuns, cancelledGateRuns, otherGateRuns: observedRuns.length - successfulGateRuns - failedGateRuns - cancelledGateRuns, macosShardRuns, firstPass: firstOrderAmbiguous ? null : firstPass };
|
|
127
|
+
} catch { return; }
|
|
128
|
+
}
|
package/src/hub/sdlc-merge.ts
CHANGED
|
@@ -27,6 +27,7 @@ export interface MergeInput {
|
|
|
27
27
|
tasks: DeliveryTask[];
|
|
28
28
|
run: SdlcGh;
|
|
29
29
|
readableMetadata?: (path: string) => boolean;
|
|
30
|
+
firstSubmittedHead?: string;
|
|
30
31
|
/** Final synchronous authority and queue-input fence, after fresh gates and immediately before the gh call. */
|
|
31
32
|
beforeMerge?: (queue: MergeQueue | undefined) => string | undefined;
|
|
32
33
|
/** Post-run host fence and durable progress record. False or a throw withholds cleanup. No remote text is supplied. */
|
|
@@ -50,6 +51,10 @@ export interface MergeOutcome {
|
|
|
50
51
|
result?: { exit: number; state: "merged" | "not_merged" | "unknown"; mergeCommit?: string; cleanup?: MergeRecord["cleanup"]; reason?: MergeRecord["reason"] };
|
|
51
52
|
}
|
|
52
53
|
|
|
54
|
+
export const MERGE_READBACK_INTERVAL_MS = 5 * 60_000;
|
|
55
|
+
// ponytail: 60 s bounds paged branch and job readbacks; lower it once a single bounded provider read supplies the same evidence.
|
|
56
|
+
export const MERGE_READBACK_DEADLINE_MS = 60_000;
|
|
57
|
+
export const INLINE_MERGE_READBACK_DEADLINE_MS = 8_000;
|
|
53
58
|
const SHA = /^[0-9a-f]{40}$/;
|
|
54
59
|
const REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
|
|
55
60
|
/**
|
|
@@ -92,10 +97,10 @@ function checkGates(evidence: PrEvidence, required: readonly string[], extra: re
|
|
|
92
97
|
}
|
|
93
98
|
|
|
94
99
|
/** 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> {
|
|
100
|
+
export async function readAdoptMergeEvidence(receipt: SdlcReceipt, run: SdlcGh): Promise<(PrEvidence & { costSnapshot?: unknown }) | undefined> {
|
|
96
101
|
if (!REPO.test(receipt.repo ?? "") || receipt.repo!.startsWith("-") || !Number.isSafeInteger(receipt.pr) || receipt.pr! <= 0) return undefined;
|
|
97
102
|
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 startedAt checkSuite{workflowRun{workflow{resourcePath}}}} ... on StatusContext{context state}} pageInfo{hasNextPage}}}}}}}}}";
|
|
103
|
+
const query = "query($owner:String!,$name:String!,$number:Int!){repository(owner:$owner,name:$name){pullRequest(number:$number){number headRefOid state mergedAt reviews(first:100){nodes{databaseId commit{oid}} pageInfo{hasNextPage}} costCommits:commits(first:100){nodes{commit{oid}} pageInfo{hasNextPage}} 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 startedAt checkSuite{workflowRun{workflow{resourcePath}}}} ... on StatusContext{context state}} pageInfo{hasNextPage}}}}}}}}}";
|
|
99
104
|
try {
|
|
100
105
|
const result = await run(["api", "graphql", "-f", `query=${query}`, "-f", `owner=${owner}`, "-f", `name=${name}`, "-F", `number=${receipt.pr}`]);
|
|
101
106
|
if (result.code !== 0) return undefined;
|
|
@@ -113,7 +118,9 @@ export async function readAdoptMergeEvidence(receipt: SdlcReceipt, run: SdlcGh):
|
|
|
113
118
|
return check.state === "passed" && !green ? { ...check, state: "unknown" } : check;
|
|
114
119
|
});
|
|
115
120
|
// Files are outside adoption's decision. Keep their coverage explicitly unknown in the shared evidence shape.
|
|
116
|
-
|
|
121
|
+
const costSnapshot = pr.number === receipt.pr && typeof pr.mergedAt === "string" && pr.costCommits && pr.reviews
|
|
122
|
+
? { ...pr, commits: pr.costCommits } : undefined;
|
|
123
|
+
return { ...evidence, pathsComplete: false, typesComplete: false, ...(costSnapshot ? { costSnapshot } : {}) };
|
|
117
124
|
} catch { return undefined; }
|
|
118
125
|
}
|
|
119
126
|
|
|
@@ -301,11 +308,11 @@ export async function guardedMerge(input: MergeInput & { mode: AutoMergeMode }):
|
|
|
301
308
|
if (input.recordMerge) {
|
|
302
309
|
// #481 S7: the merged PR's review and CI figures, read once now that the merge is observed. After the merge there is nothing left to race, so this await is fine;
|
|
303
310
|
// its own bound keeps a slow GitHub from holding the record, and a failed read records no cost (unknown), never a zero.
|
|
304
|
-
const costDeadline = performance.now() +
|
|
311
|
+
const costDeadline = performance.now() + INLINE_MERGE_READBACK_DEADLINE_MS;
|
|
305
312
|
const cost = result.state === "merged" ? await readPrCostHistory(decision.repo, decision.pr, (args, timeout, cwd, cap) => {
|
|
306
313
|
const left = costDeadline - performance.now();
|
|
307
314
|
return left > 0 ? input.run(args, Math.min(timeout ?? 10_000, left), cwd, cap) : Promise.resolve({ code: 1, stdout: "" });
|
|
308
|
-
}).then(mergeCostFrom, () => undefined) : undefined;
|
|
315
|
+
}, undefined, undefined, input.firstSubmittedHead).then(mergeCostFrom, () => undefined) : undefined;
|
|
309
316
|
let record: MergeRecord={repo:decision.repo,pr:decision.pr,head:decision.head,at:Date.now(),...result,...(cost?{cost}:{}),cleanup:"not_started",ownerNotice:"not_started"};
|
|
310
317
|
const save = () => {try {return input.recordMerge!({...record});}catch{return false;}};
|
|
311
318
|
if (!save()) {record={...record,cleanup:"skipped",reason:"authority_changed"};save();}
|
package/src/hub/sdlc-metrics.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// #481 S7: SDLC metrics and deterministic control bands. Pure: board history in, numbers out. No I/O, no clock, no model.
|
|
2
2
|
// A metric that cannot be derived is `unknown` and counted as such, never 0.
|
|
3
|
-
// `first_pass_check`
|
|
3
|
+
// `first_pass_check` prefers the completion check, then the latest isolated run before the first done at the same head.
|
|
4
4
|
|
|
5
5
|
export const BAND_METRICS = ["acceptance_to_plan_ms", "acceptance_to_first_review_ms", "first_pass_approval", "rework_rounds", "first_pass_check", "stale_head_re_reviews", "hotfix_rate", "security_open_alerts"] as const;
|
|
6
6
|
export type BandMetric = typeof BAND_METRICS[number];
|
|
@@ -26,6 +26,7 @@ export interface TaskSample {
|
|
|
26
26
|
/** When the task was approved, else null: `rework_rounds` and `stale_head_re_reviews` are final only then, and sit at this time in their series. */
|
|
27
27
|
approved_at: number | null;
|
|
28
28
|
acceptance_to_plan_ms: number | null;
|
|
29
|
+
accepted_to_plan_ms: number | null;
|
|
29
30
|
acceptance_to_first_review_ms: number | null;
|
|
30
31
|
acceptance_to_merge_ms: number | null;
|
|
31
32
|
first_pass_approval: 0 | 1 | null;
|
|
@@ -37,6 +38,12 @@ export interface TaskSample {
|
|
|
37
38
|
review_rounds_at_merge: number | null;
|
|
38
39
|
ci_runs_at_merge: number | null;
|
|
39
40
|
github_reviews_at_merge: number | null;
|
|
41
|
+
full_gate_runs: number | null;
|
|
42
|
+
successful_gate_runs: number | null;
|
|
43
|
+
failed_gate_runs: number | null;
|
|
44
|
+
cancelled_gate_runs: number | null;
|
|
45
|
+
other_gate_runs: number | null;
|
|
46
|
+
macos_shard_runs: number | null;
|
|
40
47
|
}
|
|
41
48
|
|
|
42
49
|
export interface Summary { n: number; unknown: number; mean: number | null; median: number | null; p90: number | null; max: number | null }
|
|
@@ -101,34 +108,48 @@ function staleHeadRounds(history: MetricTask["history"]): number | null {
|
|
|
101
108
|
}
|
|
102
109
|
|
|
103
110
|
/** One task's values from its own history. A private task never reaches here. */
|
|
104
|
-
export function taskSample(task: MetricTask, extra: { mergedAt?: number; ciReruns?: number | null; ciRuns?: number | null; reviews?: number | null } = {}): TaskSample {
|
|
111
|
+
export function taskSample(task: MetricTask, extra: { mergedAt?: number; ciReruns?: number | null; ciRuns?: number | null; reviews?: number | null; firstPass?: 0 | 1 | null; fullGateRuns?: number | null; successfulGateRuns?: number | null; failedGateRuns?: number | null; cancelledGateRuns?: number | null; otherGateRuns?: number | null; macosShardRuns?: number | null } = {}): TaskSample {
|
|
105
112
|
const history = [...task.history].filter(entry => Number.isFinite(entry.at) && entry.at >= 0).sort((a, b) => a.at - b.at);
|
|
106
113
|
const view: MetricTask = { id: task.id, history };
|
|
107
114
|
const accepted = first(view, ["accepted"]);
|
|
108
|
-
const spec = first(view, ["spec accepted"]);
|
|
115
|
+
const spec = first(view, ["spec accepted", "spec acceptance carried"]);
|
|
109
116
|
const plan = spec ? first(view, ["plan reviewed"], spec.at) : undefined;
|
|
117
|
+
const acceptedPlan = !spec && accepted ? first(view, ["plan reviewed"], accepted.at) : undefined;
|
|
110
118
|
const verdict = accepted ? first(view, VERDICTS, accepted.at) : first(view, VERDICTS);
|
|
111
119
|
// Evidence-only still ends the actual wait for a first review, but says nothing about whether the work passed.
|
|
112
120
|
const substantiveVerdict = history.find(entry => entry.at >= (accepted?.at ?? -Infinity) && VERDICTS.includes(entry.event) && entry.evidenceOnly !== true);
|
|
113
121
|
const dones = history.filter(entry => entry.event === "done");
|
|
114
|
-
const
|
|
122
|
+
const completionCheck = first(view, ["check passed", "check failed"]);
|
|
123
|
+
const firstDone = history.findIndex(entry => entry.event === "done");
|
|
124
|
+
const doneHead = firstDone >= 0 ? history[firstDone]?.requestHead : undefined;
|
|
125
|
+
const latestRun = doneHead ? history.slice(0, firstDone).findLast(entry => entry.event === "check run passed" || entry.event === "check run failed") : undefined;
|
|
126
|
+
const isolatedCheck = latestRun?.requestHead === doneHead ? latestRun : undefined;
|
|
127
|
+
const ci = completionCheck ?? isolatedCheck;
|
|
128
|
+
const hasHubCheck = history.some(entry => ["check passed", "check failed", "check run passed", "check run failed"].includes(entry.event));
|
|
115
129
|
const approvedAt = history.find(entry => entry.event === "approved")?.at ?? null;
|
|
116
130
|
return {
|
|
117
131
|
id: task.id,
|
|
118
132
|
at: verdict?.at ?? accepted?.at ?? history[0]?.at ?? 0,
|
|
119
133
|
approved_at: approvedAt,
|
|
120
134
|
acceptance_to_plan_ms: spec && plan ? plan.at - spec.at : null,
|
|
135
|
+
accepted_to_plan_ms: accepted && acceptedPlan ? acceptedPlan.at - accepted.at : null,
|
|
121
136
|
acceptance_to_first_review_ms: accepted && verdict ? verdict.at - accepted.at : null,
|
|
122
137
|
acceptance_to_merge_ms: accepted && extra.mergedAt !== undefined && Number.isFinite(extra.mergedAt) && extra.mergedAt >= accepted.at ? extra.mergedAt - accepted.at : null,
|
|
123
138
|
first_pass_approval: substantiveVerdict ? (substantiveVerdict.event === "approved" ? 1 : 0) : null,
|
|
124
139
|
// Rework grows with every round, so it is a value only once the task is approved: a task still in flight has no final one, and a
|
|
125
140
|
// provisional point would move at each verdict and could start a second breach episode inside one shift.
|
|
126
141
|
rework_rounds: dones.length && approvedAt !== null ? history.filter(entry => entry.event === "changes_requested" && entry.evidenceOnly !== true).length : null,
|
|
127
|
-
first_pass_check: ci ? (ci.event === "check passed" ? 1 : 0) : null,
|
|
142
|
+
first_pass_check: ci ? (ci.event === "check passed" || ci.event === "check run passed" ? 1 : 0) : hasHubCheck ? null : extra.firstPass ?? null,
|
|
128
143
|
same_head_ci_reruns: extra.ciReruns === undefined ? null : extra.ciReruns,
|
|
129
144
|
// Counted only for a merged PR whose figures were read: a done before the merge is one review round.
|
|
130
145
|
review_rounds_at_merge: extra.mergedAt !== undefined && Number.isFinite(extra.mergedAt) ? dones.filter(entry => entry.at <= extra.mergedAt!).length : null,
|
|
131
146
|
ci_runs_at_merge: extra.ciRuns === undefined ? null : extra.ciRuns,
|
|
147
|
+
full_gate_runs: extra.fullGateRuns ?? null,
|
|
148
|
+
successful_gate_runs: extra.successfulGateRuns ?? null,
|
|
149
|
+
failed_gate_runs: extra.failedGateRuns ?? null,
|
|
150
|
+
cancelled_gate_runs: extra.cancelledGateRuns ?? null,
|
|
151
|
+
other_gate_runs: extra.otherGateRuns ?? null,
|
|
152
|
+
macos_shard_runs: extra.macosShardRuns ?? null,
|
|
132
153
|
github_reviews_at_merge: extra.reviews === undefined ? null : extra.reviews,
|
|
133
154
|
stale_head_re_reviews: approvedAt !== null ? staleHeadRounds(history) : null,
|
|
134
155
|
};
|
|
@@ -202,14 +223,15 @@ export interface MetricsReport {
|
|
|
202
223
|
since: number | null;
|
|
203
224
|
tasks: number;
|
|
204
225
|
withheldPrivate: number;
|
|
226
|
+
securityScan?: Record<string, number | null>;
|
|
205
227
|
metrics: {
|
|
206
|
-
acceptance_to_plan_ms: Summary; acceptance_to_first_review_ms: Summary; acceptance_to_merge_ms: Summary;
|
|
228
|
+
acceptance_to_plan_ms: Summary; accepted_to_plan_ms: Summary; acceptance_to_first_review_ms: Summary; acceptance_to_merge_ms: Summary;
|
|
207
229
|
first_pass_approval: { n: number; unknown: number; rate: number | null };
|
|
208
230
|
rework_rounds: Summary;
|
|
209
231
|
first_pass_check: { n: number; unknown: number; rate: number | null };
|
|
210
232
|
same_head_ci_reruns: Summary;
|
|
211
233
|
stale_head_re_reviews: Summary;
|
|
212
|
-
review_rounds_at_merge: Summary; ci_runs_at_merge: Summary; github_reviews_at_merge: Summary;
|
|
234
|
+
review_rounds_at_merge: Summary; ci_runs_at_merge: Summary; github_reviews_at_merge: Summary; full_gate_runs: Summary; successful_gate_runs: Summary; failed_gate_runs: Summary; cancelled_gate_runs: Summary; other_gate_runs: Summary; macos_shard_runs: Summary;
|
|
213
235
|
};
|
|
214
236
|
/** Merged PRs whose review and CI figures were read at merge, and how many of the counted tasks have none (unknown, never 0). */
|
|
215
237
|
merged: { read: number; unknown: number };
|
|
@@ -226,9 +248,9 @@ const rate = (values: readonly (number | null)[]) => {
|
|
|
226
248
|
* The whole report from board tasks. `since` keeps samples that count at or after it; `mergedAt` and `ciReruns` come from bounded
|
|
227
249
|
* PR readbacks keyed by task id and are optional. Private tasks are counted as withheld and read for nothing else.
|
|
228
250
|
*/
|
|
229
|
-
export function sdlcMetrics(tasks: readonly MetricTask[], opts: { since?: number; bands?: BandsConfig; stalls?: StallCounts; mergedAt?: Readonly<Record<number, number>>; ciReruns?: Readonly<Record<number, number | null>>; ciRuns?: Readonly<Record<number, number | null>>; reviews?: Readonly<Record<number, number | null>>; external?: Partial<Record<BandMetric, readonly SeriesPoint[]>> } = {}): MetricsReport {
|
|
251
|
+
export function sdlcMetrics(tasks: readonly MetricTask[], opts: { since?: number; bands?: BandsConfig; stalls?: StallCounts; mergedAt?: Readonly<Record<number, number>>; ciReruns?: Readonly<Record<number, number | null>>; ciRuns?: Readonly<Record<number, number | null>>; reviews?: Readonly<Record<number, number | null>>; firstPass?: Readonly<Record<number, 0 | 1 | null>>; fullGateRuns?: Readonly<Record<number, number | null>>; successfulGateRuns?: Readonly<Record<number, number | null>>; failedGateRuns?: Readonly<Record<number, number | null>>; cancelledGateRuns?: Readonly<Record<number, number | null>>; otherGateRuns?: Readonly<Record<number, number | null>>; macosShardRuns?: Readonly<Record<number, number | null>>; external?: Partial<Record<BandMetric, readonly SeriesPoint[]>> } = {}): MetricsReport {
|
|
230
252
|
const visible = tasks.filter(task => !task.private);
|
|
231
|
-
const all = visible.map(task => taskSample(task, { mergedAt: opts.mergedAt?.[task.id], ciReruns: opts.ciReruns?.[task.id], ciRuns: opts.ciRuns?.[task.id], reviews: opts.reviews?.[task.id] }));
|
|
253
|
+
const all = visible.map(task => taskSample(task, { mergedAt: opts.mergedAt?.[task.id], ciReruns: opts.ciReruns?.[task.id], ciRuns: opts.ciRuns?.[task.id], reviews: opts.reviews?.[task.id], firstPass: opts.firstPass?.[task.id], fullGateRuns: opts.fullGateRuns?.[task.id], successfulGateRuns: opts.successfulGateRuns?.[task.id], failedGateRuns: opts.failedGateRuns?.[task.id], cancelledGateRuns: opts.cancelledGateRuns?.[task.id], otherGateRuns: opts.otherGateRuns?.[task.id], macosShardRuns: opts.macosShardRuns?.[task.id] }));
|
|
232
254
|
const samples = opts.since === undefined ? all : all.filter(sample => sample.at >= opts.since!);
|
|
233
255
|
const bands: BandResult[] | "off" = opts.bands && Object.keys(opts.bands).length
|
|
234
256
|
? BAND_METRICS.flatMap(metric => opts.bands![metric] ? [controlEpisode(EXTERNAL_METRICS.includes(metric) ? [...(opts.external?.[metric] ?? [])] : series(samples, metric as TaskMetric), metric, opts.bands![metric]!)] : [])
|
|
@@ -236,13 +258,14 @@ export function sdlcMetrics(tasks: readonly MetricTask[], opts: { since?: number
|
|
|
236
258
|
return {
|
|
237
259
|
since: opts.since ?? null, tasks: samples.length, withheldPrivate: tasks.length - visible.length,
|
|
238
260
|
metrics: {
|
|
239
|
-
acceptance_to_plan_ms: summarize(samples.map(s => s.acceptance_to_plan_ms)), acceptance_to_first_review_ms: summarize(samples.map(s => s.acceptance_to_first_review_ms)),
|
|
261
|
+
acceptance_to_plan_ms: summarize(samples.map(s => s.acceptance_to_plan_ms)), accepted_to_plan_ms: summarize(samples.map(s => s.accepted_to_plan_ms)), acceptance_to_first_review_ms: summarize(samples.map(s => s.acceptance_to_first_review_ms)),
|
|
240
262
|
acceptance_to_merge_ms: summarize(samples.map(s => s.acceptance_to_merge_ms)),
|
|
241
263
|
first_pass_approval: rate(samples.map(s => s.first_pass_approval)), rework_rounds: summarize(samples.map(s => s.rework_rounds)),
|
|
242
264
|
first_pass_check: rate(samples.map(s => s.first_pass_check)), same_head_ci_reruns: summarize(samples.map(s => s.same_head_ci_reruns)),
|
|
243
265
|
stale_head_re_reviews: summarize(samples.map(s => s.stale_head_re_reviews)),
|
|
244
266
|
review_rounds_at_merge: summarize(samples.map(s => s.review_rounds_at_merge)), ci_runs_at_merge: summarize(samples.map(s => s.ci_runs_at_merge)),
|
|
245
267
|
github_reviews_at_merge: summarize(samples.map(s => s.github_reviews_at_merge)),
|
|
268
|
+
full_gate_runs: summarize(samples.map(s => s.full_gate_runs)), successful_gate_runs: summarize(samples.map(s => s.successful_gate_runs)), failed_gate_runs: summarize(samples.map(s => s.failed_gate_runs)), cancelled_gate_runs: summarize(samples.map(s => s.cancelled_gate_runs)), other_gate_runs: summarize(samples.map(s => s.other_gate_runs)), macos_shard_runs: summarize(samples.map(s => s.macos_shard_runs)),
|
|
246
269
|
},
|
|
247
270
|
merged: { read: samples.filter(s => s.ci_runs_at_merge !== null || s.github_reviews_at_merge !== null).length, unknown: samples.filter(s => s.ci_runs_at_merge === null && s.github_reviews_at_merge === null).length },
|
|
248
271
|
stalls: opts.stalls ?? { open: 0, byKind: {}, doneWithoutWrites: 0 }, bands,
|