@indigoai-us/hq-cli 5.345.252 → 5.345.254

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 (67) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/contracts/host-canary-release.json +11 -5
  3. package/dist/command-catalog.generated.d.ts +209 -0
  4. package/dist/command-catalog.generated.js +257 -0
  5. package/dist/command-registration-plan.d.ts +6 -0
  6. package/dist/command-registration-plan.js +1 -0
  7. package/dist/commands/ci-intake.d.ts +32 -0
  8. package/dist/commands/ci-intake.js +294 -0
  9. package/dist/commands/ci-metrics.d.ts +8 -0
  10. package/dist/commands/ci-metrics.js +55 -0
  11. package/dist/commands/ci-priorities.d.ts +56 -0
  12. package/dist/commands/ci-priorities.js +144 -0
  13. package/dist/commands/ci.d.ts +13 -0
  14. package/dist/commands/ci.js +11 -0
  15. package/dist/commands/cloud.d.ts +11 -0
  16. package/dist/commands/cloud.js +76 -0
  17. package/dist/commands/files.d.ts +62 -0
  18. package/dist/commands/files.js +249 -8
  19. package/dist/lib/bot/fleet-cron.d.ts +15 -0
  20. package/dist/lib/bot/fleet-cron.js +119 -20
  21. package/dist/lib/daemon/run.js +4 -3
  22. package/dist/lib/daemon/verified-jq.d.ts +6 -0
  23. package/dist/lib/daemon/verified-jq.js +17 -5
  24. package/dist/lib/delivery/migrations.d.ts +32 -1
  25. package/dist/lib/delivery/migrations.js +69 -8
  26. package/dist/lib/hook-engine/adapter-core-pin.d.ts +2 -1
  27. package/dist/lib/hook-engine/adapter-core-pin.js +2 -1
  28. package/dist/lib/hook-engine/coverage.d.ts +15 -0
  29. package/dist/lib/hook-engine/coverage.js +62 -1
  30. package/dist/lib/hook-engine/fleet-registration.d.ts +4 -0
  31. package/dist/lib/hook-engine/fleet-registration.js +25 -3
  32. package/dist/lib/smart-ci/cost.d.ts +72 -0
  33. package/dist/lib/smart-ci/cost.js +120 -0
  34. package/dist/lib/smart-ci/github.d.ts +112 -0
  35. package/dist/lib/smart-ci/github.js +267 -0
  36. package/dist/lib/smart-ci/intake.d.ts +288 -0
  37. package/dist/lib/smart-ci/intake.js +1078 -0
  38. package/dist/lib/smart-ci/ledger.d.ts +218 -0
  39. package/dist/lib/smart-ci/ledger.js +527 -0
  40. package/dist/lib/smart-ci/metrics.d.ts +137 -0
  41. package/dist/lib/smart-ci/metrics.js +249 -0
  42. package/dist/lib/smart-ci/priorities.d.ts +331 -0
  43. package/dist/lib/smart-ci/priorities.js +964 -0
  44. package/dist/lib/smart-ci/priority-refresh.d.ts +192 -0
  45. package/dist/lib/smart-ci/priority-refresh.js +366 -0
  46. package/dist/lib/smart-ci/priority-snapshots.d.ts +88 -0
  47. package/dist/lib/smart-ci/priority-snapshots.js +233 -0
  48. package/dist/lib/smart-ci/records.d.ts +265 -0
  49. package/dist/lib/smart-ci/records.js +281 -0
  50. package/dist/lib/smart-ci/reducer.d.ts +67 -0
  51. package/dist/lib/smart-ci/reducer.js +261 -0
  52. package/dist/lib/smart-ci/sources.d.ts +294 -0
  53. package/dist/lib/smart-ci/sources.js +659 -0
  54. package/dist/lib/smart-ci/text.d.ts +24 -0
  55. package/dist/lib/smart-ci/text.js +83 -0
  56. package/dist/lib/smart-ci/work-in-flight.d.ts +68 -0
  57. package/dist/lib/smart-ci/work-in-flight.js +154 -0
  58. package/dist/lib/sync/cli-manifest-reconcile.d.ts +20 -0
  59. package/dist/lib/sync/cli-manifest-reconcile.js +170 -0
  60. package/dist/lib/sync-core/engine-holds.d.ts +14 -0
  61. package/dist/lib/sync-core/engine-holds.js +78 -11
  62. package/dist/lib/sync-core/hand-back.d.ts +1 -0
  63. package/dist/lib/sync-core/hand-back.js +7 -2
  64. package/dist/lib/sync-core/reconcile.js +10 -2
  65. package/dist/utils/host-registration.d.ts +1 -0
  66. package/dist/utils/host-registration.js +1 -1
  67. package/package.json +9 -7
@@ -0,0 +1,249 @@
1
+ /**
2
+ * Smart CI metrics (smart-ci US-001): what the ledger says about waits, waste
3
+ * and cost for one repo over one window.
4
+ *
5
+ * Definitions, so the numbers can be checked by hand:
6
+ *
7
+ * - The window is [since, until). A job is in it by its queue time, a pull
8
+ * request by its merge time, a runner sample by its sample time.
9
+ * - A job "ran" when a runner picked it up (it has a runner name and a start
10
+ * time). Skipped jobs and jobs cancelled while still queued never ran and
11
+ * are left out of wait and run times.
12
+ * - Queue wait = start - queued. Run time = finish - start (finished jobs only).
13
+ * - Median and p90 use the nearest-rank method: the value at position
14
+ * ceil(p x n) of the sorted list. No interpolation.
15
+ * - A replaced-head job is one whose branch got a newer push at or after the
16
+ * job was queued and before it finished.
17
+ * - A cold start is a job that ran on the runner launched for it: the runner's
18
+ * name is ec2-<this job's id>-<n>, which is how hq-github-runners names a
19
+ * runner it launches for a queued job. Its queue wait is the cold-start
20
+ * time. A job that landed on a warm runner (ec2-warm-...), on a runner
21
+ * launched for another job, or on another pool did not wait for a launch.
22
+ * - Idle runner minutes come from runner pool samples: idle runners at a
23
+ * sample, times the gap to the next sample (capped at 5 minutes so a pause in
24
+ * sampling is not counted as idle time). A pool serves several repos, so the
25
+ * repo is given its share of each pool's idle minutes: its run minutes on
26
+ * the pool over the run minutes of every recorded repo on that pool in the
27
+ * window. The shares of the recorded repos add up to the pool's idle
28
+ * minutes, so summing across repos does not count a pool twice. Where
29
+ * samples are missing (gaps over 5 minutes) the figure covers only part of
30
+ * the window and is reported as an estimate with its coverage.
31
+ * - Merge to production = completion of the first successful deploy workflow
32
+ * run created at or after the merge on the base branch, minus the merge time.
33
+ * The run is matched by time, never by its head sha, which for hq-pro is not
34
+ * the commit it deploys. For hq-pro this is a lower bound: a green Deploy
35
+ * Prod run means the deploy was queued, and the deploy itself finishes
36
+ * minutes later in CodeBuild, which GitHub does not report and the ledger
37
+ * does not record.
38
+ */
39
+ import { DEFAULT_RATES, classifyPool, costPerMerge } from "./cost.js";
40
+ import { KIND, isHosted } from "./records.js";
41
+ /** Repos whose merge to the base branch deploys to production, and the workflow that does it. */
42
+ export const DEPLOY_ON_MERGE = { "indigoai-us/hq-pro": "Deploy Prod" };
43
+ export const COLD_START_RUNNER = /^ec2-(\d+)-\d+$/;
44
+ const MAX_SAMPLE_GAP_MS = 300_000;
45
+ /** Idle minutes are called measured only when samples cover at least this share of the sampled span. */
46
+ export const IDLE_MEASURED_COVERAGE = 0.95;
47
+ /** Nearest-rank percentile of a list of numbers; null for an empty list. */
48
+ export function percentile(values, p) {
49
+ if (values.length === 0)
50
+ return null;
51
+ const sorted = [...values].sort((a, b) => a - b);
52
+ const rank = Math.min(sorted.length, Math.max(1, Math.ceil(p * sorted.length)));
53
+ return sorted[rank - 1];
54
+ }
55
+ function distribution(seconds) {
56
+ return { count: seconds.length, medianSeconds: percentile(seconds, 0.5), p90Seconds: percentile(seconds, 0.9) };
57
+ }
58
+ /** A date (2026-11-21) means the start of that UTC day. Throws on anything that is not a time. */
59
+ export function parseWhen(value, name) {
60
+ const text = /^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}T00:00:00Z` : value;
61
+ const ms = Date.parse(text);
62
+ if (Number.isNaN(ms))
63
+ throw new Error(`${name} is not a date or time: ${JSON.stringify(value)}. Use 2026-11-21 or 2026-11-21T00:00:00Z.`);
64
+ return ms;
65
+ }
66
+ const secondsBetween = (a, b) => Math.max(0, (Date.parse(b) - Date.parse(a)) / 1000);
67
+ const round1 = (n) => Math.round(n * 10) / 10;
68
+ export function computeMetrics(view, opts) {
69
+ const since = parseWhen(opts.since, "--since");
70
+ const until = opts.until === undefined ? Number.POSITIVE_INFINITY : parseWhen(opts.until, "--until");
71
+ const inWindow = (t) => t !== null && Date.parse(t) >= since && Date.parse(t) < until;
72
+ const rates = opts.rates ?? DEFAULT_RATES;
73
+ const allJobs = view.list(KIND.job).filter((j) => inWindow(j.queuedAt));
74
+ const jobs = allJobs.filter((j) => j.repo === opts.repo);
75
+ const ran = jobs.filter((j) => j.runnerName !== null && j.startedAt !== null);
76
+ const finished = ran.filter((j) => j.finishedAt !== null);
77
+ const queueWaits = ran.map((j) => secondsBetween(j.queuedAt, j.startedAt));
78
+ const runTimes = finished.map((j) => secondsBetween(j.startedAt, j.finishedAt));
79
+ const replaced = ran.filter((j) => j.replaced !== null);
80
+ const replacedFinished = replaced.filter((j) => j.finishedAt !== null);
81
+ const runMinutes = (list) => list.reduce((s, j) => s + secondsBetween(j.startedAt, j.finishedAt), 0) / 60;
82
+ const onPr = (j) => j.event !== null && j.event.startsWith("pull_request");
83
+ const minutesAfter = replacedFinished.reduce((s, j) => {
84
+ const from = Math.max(Date.parse(j.startedAt), Date.parse(j.replaced.at));
85
+ return s + Math.max(0, Date.parse(j.finishedAt) - from) / 1000;
86
+ }, 0) / 60;
87
+ const cold = ran.filter((j) => !isHosted(j) && COLD_START_RUNNER.exec(j.runnerName)?.[1] === String(j.jobId));
88
+ // Pool minutes for the cost.
89
+ const pools = new Map();
90
+ for (const j of finished) {
91
+ const seconds = secondsBetween(j.startedAt, j.finishedAt);
92
+ const p = pools.get(j.pool) ?? { pool: j.pool, poolClass: classifyPool(j.pool, isHosted(j), j.labels, rates), jobs: 0, runMinutes: 0, billedMinutes: 0 };
93
+ p.jobs += 1;
94
+ p.runMinutes += seconds / 60;
95
+ p.billedMinutes += Math.max(1, Math.ceil(seconds / 60));
96
+ pools.set(j.pool, p);
97
+ }
98
+ const poolMinutes = [...pools.values()].sort((a, b) => b.runMinutes - a.runMinutes || a.pool.localeCompare(b.pool));
99
+ // Idle runner minutes, for the pools this repo's jobs used.
100
+ const repoPools = new Set(jobs.map((j) => j.pool));
101
+ const samples = view
102
+ .list(KIND.runnerSample)
103
+ .filter((s) => inWindow(s.sampledAt))
104
+ .sort((a, b) => Date.parse(a.sampledAt) - Date.parse(b.sampledAt));
105
+ let idleRunners = null;
106
+ if (samples.length >= 2) {
107
+ const pool = {};
108
+ let coveredMs = 0;
109
+ for (let i = 0; i + 1 < samples.length; i++) {
110
+ const gapMs = Math.min(MAX_SAMPLE_GAP_MS, Date.parse(samples[i + 1].sampledAt) - Date.parse(samples[i].sampledAt));
111
+ coveredMs += gapMs;
112
+ for (const p of samples[i].pools) {
113
+ if (!repoPools.has(p.pool) || p.idle === 0)
114
+ continue;
115
+ pool[p.pool] = (pool[p.pool] ?? 0) + (p.idle * gapMs) / 60_000;
116
+ }
117
+ }
118
+ const spanMs = Date.parse(samples[samples.length - 1].sampledAt) - Date.parse(samples[0].sampledAt);
119
+ // Run minutes on each pool: this repo's and every recorded repo's.
120
+ const mine = {};
121
+ const everyone = {};
122
+ for (const j of allJobs) {
123
+ if (j.runnerName === null || j.startedAt === null || j.finishedAt === null)
124
+ continue;
125
+ const minutes = secondsBetween(j.startedAt, j.finishedAt) / 60;
126
+ everyone[j.pool] = (everyone[j.pool] ?? 0) + minutes;
127
+ if (j.repo === opts.repo)
128
+ mine[j.pool] = (mine[j.pool] ?? 0) + minutes;
129
+ }
130
+ const byPool = {};
131
+ const poolMinutes = {};
132
+ const share = {};
133
+ for (const k of Object.keys(pool)) {
134
+ const s = (everyone[k] ?? 0) > 0 ? (mine[k] ?? 0) / everyone[k] : 0;
135
+ share[k] = Math.round(s * 1000) / 1000;
136
+ poolMinutes[k] = round1(pool[k]);
137
+ byPool[k] = round1(pool[k] * s);
138
+ }
139
+ idleRunners = {
140
+ minutes: round1(Object.keys(pool).reduce((s, k) => s + pool[k] * ((everyone[k] ?? 0) > 0 ? (mine[k] ?? 0) / everyone[k] : 0), 0)),
141
+ samples: samples.length,
142
+ byPool,
143
+ poolMinutes,
144
+ share,
145
+ coverage: spanMs > 0 ? Math.round((coveredMs / spanMs) * 1000) / 1000 : 1,
146
+ };
147
+ }
148
+ const merged = view.list(KIND.pullRequest).filter((p) => p.repo === opts.repo && inWindow(p.mergedAt));
149
+ const openToMerge = merged.map((p) => secondsBetween(p.createdAt, p.mergedAt));
150
+ const workflow = opts.deployWorkflow === undefined ? (DEPLOY_ON_MERGE[opts.repo] ?? null) : opts.deployWorkflow;
151
+ let mergeToProduction = { applicable: false };
152
+ if (workflow !== null) {
153
+ const deploys = view
154
+ .list(KIND.run)
155
+ .filter((r) => r.repo === opts.repo && r.name === workflow && r.status === "completed" && r.conclusion === "success" && r.updatedAt !== null)
156
+ .sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt));
157
+ const times = [];
158
+ for (const p of merged) {
159
+ const first = deploys.find((r) => Date.parse(r.createdAt) >= Date.parse(p.mergedAt) && (r.headBranch === null || r.headBranch === p.baseRef));
160
+ if (first)
161
+ times.push(secondsBetween(p.mergedAt, first.updatedAt));
162
+ }
163
+ mergeToProduction = { applicable: true, workflow, deployed: times.length, notYetDeployed: merged.length - times.length, distribution: distribution(times) };
164
+ }
165
+ const cost = costPerMerge({
166
+ merges: merged.length,
167
+ pools: poolMinutes,
168
+ idleMinutesByPool: idleRunners === null ? null : idleRunners.byPool,
169
+ idleCoverage: idleRunners === null ? null : idleRunners.coverage,
170
+ rates,
171
+ githubBilledUsd: opts.githubBilledUsd,
172
+ awsFleetUsd: opts.awsFleetUsd,
173
+ });
174
+ return {
175
+ repo: opts.repo,
176
+ since: new Date(since).toISOString(),
177
+ until: Number.isFinite(until) ? new Date(until).toISOString() : null,
178
+ jobs: { recorded: jobs.length, ran: ran.length, finished: finished.length, neverRan: jobs.length - ran.length },
179
+ queueWait: distribution(queueWaits),
180
+ runTime: distribution(runTimes),
181
+ replacedHead: {
182
+ runs: new Set(replaced.map((j) => j.runId)).size,
183
+ jobs: replaced.length,
184
+ minutes: round1(runMinutes(replacedFinished)),
185
+ minutesAfterReplacement: round1(minutesAfter),
186
+ onPullRequests: {
187
+ runs: new Set(replaced.filter(onPr).map((j) => j.runId)).size,
188
+ jobs: replaced.filter(onPr).length,
189
+ minutes: round1(runMinutes(replacedFinished.filter(onPr))),
190
+ },
191
+ },
192
+ coldStart: { jobs: cold.length, minutes: round1(cold.reduce((s, j) => s + secondsBetween(j.queuedAt, j.startedAt), 0) / 60) },
193
+ idleRunners,
194
+ pullRequests: { merged: merged.length, openToMerge: distribution(openToMerge) },
195
+ mergeToProduction,
196
+ cost,
197
+ poolMinutes: poolMinutes.map((p) => ({ ...p, runMinutes: round1(p.runMinutes) })),
198
+ };
199
+ }
200
+ /** 95 -> "1m 35s"; 4000 -> "1h 6m 40s". */
201
+ export function formatDuration(seconds) {
202
+ if (seconds === null)
203
+ return "no data";
204
+ const s = Math.round(seconds);
205
+ const h = Math.floor(s / 3600);
206
+ const m = Math.floor((s % 3600) / 60);
207
+ const rest = s % 60;
208
+ if (h > 0)
209
+ return `${h}h ${m}m ${rest}s`;
210
+ if (m > 0)
211
+ return `${m}m ${rest}s`;
212
+ return `${rest}s`;
213
+ }
214
+ const money = (n) => `$${n.toFixed(2)}`;
215
+ /** The plain-text report `hq ci metrics` prints. */
216
+ export function renderMetrics(m) {
217
+ const lines = [];
218
+ const dist = (d) => (d.count === 0 ? "no data" : `median ${formatDuration(d.medianSeconds)}, p90 ${formatDuration(d.p90Seconds)} (${d.count})`);
219
+ lines.push(`Smart CI metrics for ${m.repo}`);
220
+ lines.push(`Window: ${m.since} to ${m.until ?? "now"}`);
221
+ lines.push("");
222
+ lines.push(`Jobs recorded: ${m.jobs.recorded} (${m.jobs.ran} ran, ${m.jobs.finished} finished, ${m.jobs.neverRan} skipped or never started)`);
223
+ lines.push(`Queue wait: ${dist(m.queueWait)}`);
224
+ lines.push(`Run time: ${dist(m.runTime)}`);
225
+ const r = m.replacedHead;
226
+ lines.push(`Replaced-head runs: ${r.runs} runs (${r.jobs} jobs), ${r.minutes} runner minutes, ${r.minutesAfterReplacement} of them after the newer push. On pull requests: ${r.onPullRequests.runs} runs (${r.onPullRequests.jobs} jobs), ${r.onPullRequests.minutes} minutes.`);
227
+ lines.push(`Cold-start runner minutes: ${m.coldStart.minutes} across ${m.coldStart.jobs} jobs that ran on the runner launched for them`);
228
+ lines.push(m.idleRunners === null
229
+ ? "Idle runner minutes: not measured (the window has fewer than two runner pool samples)"
230
+ : `Idle runner minutes: ${m.idleRunners.minutes} from ${m.idleRunners.samples} samples${Object.keys(m.idleRunners.byPool).length > 0 ? ` (${Object.entries(m.idleRunners.byPool).map(([p, v]) => `${p} ${v} of the pool's ${m.idleRunners?.poolMinutes[p]}`).join(", ")})` : ""}. This is the repo's share of each pool it used, by its share of the recorded run minutes on that pool.${m.idleRunners.coverage < IDLE_MEASURED_COVERAGE ? ` Samples cover ${Math.round(m.idleRunners.coverage * 100)}% of the time between the first and the last one, so the real figure is higher.` : ""}`);
231
+ lines.push(`PR open to merge: ${m.pullRequests.merged === 0 ? "no pull requests merged in the window" : dist(m.pullRequests.openToMerge)}`);
232
+ if (!m.mergeToProduction.applicable)
233
+ lines.push("Merge to production: not applicable (this repo does not deploy on merge)");
234
+ else {
235
+ const p = m.mergeToProduction;
236
+ lines.push(`Merge to production (${p.workflow}): ${p.deployed === 0 ? "no deploy recorded for the merges in the window" : dist(p.distribution)}${p.notYetDeployed > 0 ? `; ${p.notYetDeployed} merges with no deploy recorded yet` : ""}`);
237
+ lines.push(` Measured to the end of the first successful ${p.workflow} run after each merge. Where that run only queues the deploy, production is live some minutes later, so read this as a lower bound.`);
238
+ }
239
+ lines.push(m.cost.usdPerMerge === null
240
+ ? `Cost per merge: no merges in the window (total ${money(m.cost.totalUsd)}: GitHub-hosted ${money(m.cost.githubHostedUsd)}, AWS ${money(m.cost.awsUsd)})`
241
+ : `Cost per merge: ${money(m.cost.usdPerMerge)} (${money(m.cost.totalUsd)} over ${m.cost.merges} merges: GitHub-hosted ${money(m.cost.githubHostedUsd)}, AWS ${money(m.cost.awsUsd)})`);
242
+ lines.push(" This is one repo's cost over its own merges. The 2026-11-22 study's figure is for the whole org per pull request, so the two are not the same measure.");
243
+ lines.push("");
244
+ lines.push("Cost inputs (method of the 2026-11-22 CI cost study: GitHub-hosted spend plus AWS runner fleet spend, divided by merges):");
245
+ for (const i of m.cost.inputs)
246
+ lines.push(` ${i.basis.padEnd(11)} ${i.input}: ${i.value} (${i.how})`);
247
+ return `${lines.join("\n")}\n`;
248
+ }
249
+ //# sourceMappingURL=metrics.js.map
@@ -0,0 +1,331 @@
1
+ /**
2
+ * The Smart CI priority map (smart-ci US-002).
3
+ *
4
+ * buildPriorityMap turns four inputs into one ranked list of what the company
5
+ * is working on: standup transcripts, Work Mesh threads and projects, open HQ
6
+ * sessions, and the ontology. It is pure: the readers in sources.ts fetch the
7
+ * inputs and this module only combines them, so the same inputs always give
8
+ * the same map.
9
+ *
10
+ * Method. A priority is a topic term that names real tracked work: it comes
11
+ * from the ids and names of the company's own Work Mesh projects, ontology
12
+ * projects and session repos. No topic is written into this code.
13
+ *
14
+ * Names and fragments. A word of a project slug is kept as a term only when
15
+ * the company uses it as a name: it is the whole name of a project or repo,
16
+ * or it names two or more of them, or it is said in the standups at least
17
+ * twice and more often than in the company's other meetings. Any other slug
18
+ * word is a fragment of one project's name ("first" in "first-run-tour") and
19
+ * is dropped. A project left with no term is listed under its own project id,
20
+ * so no tracked work disappears. A word carried by more than a fifth of the
21
+ * work items (a product prefix) is dropped as well, and so is a word for a
22
+ * word of the company's own name, and a word for a
23
+ * kind of record the sources themselves are made of (RECORD_KIND_WORDS: the
24
+ * word for a session or a thread is in every source whatever the work is, and
25
+ * its score follows whatever happens to be open).
26
+ *
27
+ * Each term gets a score per source:
28
+ *
29
+ * - standups: utterances that say the term, weighted by how recent the
30
+ * standup is and doubled when the utterance uses priority wording, times
31
+ * how much more often the term is said in standups than in the company's
32
+ * other meetings (so ordinary words score near zero);
33
+ * - Work Mesh: threads active in the window, stories in progress and recent
34
+ * board updates on the projects the term names;
35
+ * - sessions: people and agents with an open session on a repo, branch or
36
+ * bound project the term names;
37
+ * - ontology: how high the term's projects stand in the brief's list of most
38
+ * recently active projects.
39
+ *
40
+ * A word of talk counts for a term when it is the term, or an -ing or -ed form
41
+ * of it ("syncing", "synced" for "sync"; see inflectionBases), in standups and
42
+ * in the background alike. Words of the names of the repos the company works
43
+ * in ("cli" of hq-cli) score on standup and Work Mesh evidence only: a
44
+ * session or an ontology entry says where work is for them, not what it is.
45
+ *
46
+ * Each source score is divided by the highest score in that source, then the
47
+ * four are added with fixed weights (standups 0.4, Work Mesh 0.25, sessions
48
+ * 0.2, ontology 0.15). A term needs standup or Work Mesh evidence to be
49
+ * listed. Every priority carries its sources, the date of its latest evidence
50
+ * and an owner, and says where the owner came from.
51
+ *
52
+ * Merging. Two terms whose evidence overlaps are one priority, not two (see
53
+ * mergeReason): they merge when they share at least half of the smaller
54
+ * term's work (projects, repos, sessions), or when at least half of the rarer
55
+ * term's standup utterances, and at least three, also say the other term.
56
+ * Terms are taken strongest first and compared with each priority's lead term
57
+ * only, never with terms already merged in or with the work they brought, so
58
+ * merges do not chain. A merged priority keeps every member term
59
+ * with its evidence, dates and owner, and scores per source as its strongest
60
+ * member does, so shared evidence is not counted twice.
61
+ *
62
+ * Company isolation: the builder sees only what the readers pass in, and the
63
+ * readers read one company (see sources.ts).
64
+ */
65
+ import type { LiveSession, OntologyRead, ProjectPlan, PullRequest, SessionsRead, SourceName, StandupRead, WorkMeshRead } from "./sources.js";
66
+ import { type RepoWorkInFlight } from "./work-in-flight.js";
67
+ export declare const PRIORITY_MAP_SCHEMA = "hq-smart-ci.priority-map.v1";
68
+ export type PrioritySourceKind = "standup" | "work-mesh" | "session" | "ontology";
69
+ export interface PriorityEvidence {
70
+ source: PrioritySourceKind;
71
+ /** Calendar day of the evidence (YYYY-MM-DD). */
72
+ date: string;
73
+ owner: string;
74
+ /** Where to find it: a transcript path, a project id, a session id or an entity id. */
75
+ ref: string;
76
+ detail: string;
77
+ /** The member term of the priority this evidence is for. */
78
+ term: string;
79
+ }
80
+ /** Why a term was merged into a priority. */
81
+ export interface PriorityMerge {
82
+ term: string;
83
+ /** "shared-work": the two terms name the same projects, repos or sessions. "same-sentences": they are said in the same standup utterances. */
84
+ rule: "shared-work" | "same-sentences";
85
+ /** How many work items or utterances the two share. */
86
+ shared: number;
87
+ /** `shared` as a share of the smaller of the two sets. At least MERGE_THRESHOLD. */
88
+ share: number;
89
+ }
90
+ export interface PriorityOwner {
91
+ term: string;
92
+ name: string;
93
+ basis: string;
94
+ }
95
+ export interface Priority {
96
+ /** The lead topic term. Stable across refreshes while the work keeps its name. */
97
+ id: string;
98
+ rank: number;
99
+ /** "top" priorities order CI; "active" ones are listed for context. */
100
+ tier: "top" | "active";
101
+ score: number;
102
+ sourceScores: Record<PrioritySourceKind, number>;
103
+ /** Every term of the priority: the lead term first, then the terms merged into it. */
104
+ terms: string[];
105
+ /** The merged terms, without the lead term. */
106
+ alsoSaid: string[];
107
+ /**
108
+ * The terms a pull request or a branch can name this priority by: the lead
109
+ * term, and a member term that is the whole name of a project or repo. The
110
+ * other member terms describe the priority but are not its name.
111
+ */
112
+ names: string[];
113
+ /** One entry per merged term, saying which rule merged it and by how much. */
114
+ merged: PriorityMerge[];
115
+ projects: string[];
116
+ repos: string[];
117
+ /** The lead term's owner. */
118
+ owner: string;
119
+ ownerBasis: string;
120
+ /** The owner each member term has, lead term first. */
121
+ owners: PriorityOwner[];
122
+ /** Calendar day of the latest evidence. */
123
+ date: string;
124
+ sources: PrioritySourceKind[];
125
+ evidence: PriorityEvidence[];
126
+ }
127
+ export type PullRequestCategory = "priority" | "customer-fix" | "ci-speedup" | "routine";
128
+ export interface MatchEvidence {
129
+ kind: "branch" | "title" | "work-mesh-link" | "session" | "label" | "paths" | "reference";
130
+ detail: string;
131
+ }
132
+ export interface PullRequestMatch {
133
+ repo: string;
134
+ number: number;
135
+ title: string;
136
+ branch: string;
137
+ author: string;
138
+ draft: boolean;
139
+ url: string;
140
+ category: PullRequestCategory;
141
+ /** Set when category is "priority". */
142
+ priorityId: string;
143
+ evidence: MatchEvidence[];
144
+ /** Commit at the head of the branch when the pull request was read. */
145
+ headSha: string;
146
+ /** The changed paths, when they were read. Kept so the next refresh does not ask again while the head is the same. */
147
+ paths?: string[];
148
+ }
149
+ export interface SourceStatus {
150
+ source: SourceName;
151
+ status: "ok" | "down";
152
+ /** When the source was read. */
153
+ readAt: string;
154
+ detail: string;
155
+ }
156
+ export interface PriorityMap {
157
+ schema: typeof PRIORITY_MAP_SCHEMA;
158
+ company: string;
159
+ builtAt: string;
160
+ window: {
161
+ from: string;
162
+ to: string;
163
+ };
164
+ /** True when the map was built while a source was down and no earlier map existed. */
165
+ degraded: boolean;
166
+ priorities: Priority[];
167
+ pullRequests: PullRequestMatch[];
168
+ workInFlight: RepoWorkInFlight[];
169
+ sources: SourceStatus[];
170
+ gaps: string[];
171
+ /** Standup transcripts the map was built from. */
172
+ standupIds: string[];
173
+ method: {
174
+ weights: Record<PrioritySourceKind, number>;
175
+ topCount: number;
176
+ };
177
+ }
178
+ export interface PriorityInputs {
179
+ company: string;
180
+ /** Build time, ISO. Read from the clock by the caller. */
181
+ now: string;
182
+ window: {
183
+ from: string;
184
+ to: string;
185
+ };
186
+ standups: StandupRead | null;
187
+ mesh: WorkMeshRead | null;
188
+ sessions: SessionsRead | null;
189
+ ontology: OntologyRead | null;
190
+ pullRequests: PullRequest[] | null;
191
+ /** Plans of the company's projects, keyed by project id (readProjectPlans). Optional supporting evidence. */
192
+ projectPlans?: Record<string, ProjectPlan>;
193
+ sources: SourceStatus[];
194
+ }
195
+ export interface BuildOptions {
196
+ /** How many priorities are "top". Default 5. */
197
+ topCount?: number;
198
+ /** How many priorities the map keeps. Default 15. */
199
+ keep?: number;
200
+ weights?: Partial<Record<PrioritySourceKind, number>>;
201
+ }
202
+ export declare const DEFAULT_WEIGHTS: Record<PrioritySourceKind, number>;
203
+ /** Two terms are one priority when they share at least this much of the smaller one's evidence. */
204
+ export declare const MERGE_THRESHOLD = 0.5;
205
+ /** The same-sentences rule also needs this many shared utterances, so two terms said once together do not merge. */
206
+ export declare const MERGE_MIN_SHARED_SENTENCES = 3;
207
+ /** What the merge rule compares: the work a term names and the standup utterances that say it. */
208
+ export interface MergeEvidence {
209
+ /** Project ids, `repo:<name>` and `session:<id>`. */
210
+ work: ReadonlySet<string>;
211
+ sentences: ReadonlySet<string>;
212
+ }
213
+ /**
214
+ * The merge rule. Two terms are the same priority when their evidence
215
+ * overlaps:
216
+ *
217
+ * - shared work: the projects, repos and sessions both terms name are at
218
+ * least MERGE_THRESHOLD (half) of the smaller term's work; or
219
+ * - same sentences: the standup utterances that say both terms are at least
220
+ * MERGE_THRESHOLD (half) of the utterances of the term said less often, and
221
+ * there are at least MERGE_MIN_SHARED_SENTENCES of them.
222
+ *
223
+ * Returns which rule holds and by how much, or null when the terms stay
224
+ * apart. The rule knows no topic: it only counts overlap.
225
+ */
226
+ export declare function mergeReason(a: MergeEvidence, b: MergeEvidence): Omit<PriorityMerge, "term"> | null;
227
+ /**
228
+ * The base forms an -ing or -ed word may come from: "syncing" and "synced"
229
+ * from "sync", "shipping" from "ship", "rolled" from "roll", "based" from
230
+ * "base". The candidates are only looked up in the work vocabulary, so a word
231
+ * is folded onto a base only when the base is itself a term that names work.
232
+ */
233
+ export declare function inflectionBases(word: string): string[];
234
+ /** Build the map. See the file header for the method. */
235
+ export declare function buildPriorityMap(input: PriorityInputs, opts?: BuildOptions): PriorityMap;
236
+ export interface MatchContext {
237
+ /** The priorities a pull request can be matched to (the top tier). */
238
+ priorities: Priority[];
239
+ sessions: LiveSession[];
240
+ /** Session id to the project it is bound to. */
241
+ projectOfSession: Map<string, string>;
242
+ /** Customer names, for the customer-facing fix rule. */
243
+ customers: string[];
244
+ /** Per priority id: where its projects' plans say the work lands (see projectPaths). */
245
+ projectPaths?: Map<string, PriorityPaths>;
246
+ }
247
+ /** Where a priority's work lands, from its projects' own plans. */
248
+ export interface PriorityPaths {
249
+ /** Per repo (name without owner): folders and files only this priority's projects list. */
250
+ byRepo: Map<string, {
251
+ folders: string[];
252
+ files: Set<string>;
253
+ project: Map<string, string>;
254
+ }>;
255
+ /** Branches the plans name, with the project that names each. */
256
+ branches: Map<string, string>;
257
+ }
258
+ /** A folder is one of a plan's own when at least this share of the plan's listed files, and at least PLAN_FOLDER_MIN_FILES, are under it. */
259
+ export declare const PLAN_FOLDER_SHARE = 0.1;
260
+ export declare const PLAN_FOLDER_MIN_FILES = 3;
261
+ /** A path listed by more than one priority counts for the one whose plans list at least this many times as many files under it as any other. */
262
+ export declare const PLAN_CLAIM_LEAD = 2;
263
+ /**
264
+ * Turn project plans into path evidence per priority. A project's plan lists
265
+ * the files its stories change. Those files, and the folders (two or more
266
+ * levels deep) they concentrate in (see planClaims), count for a priority
267
+ * when no other priority's projects claim them, or when its plans list at
268
+ * least PLAN_CLAIM_LEAD (twice) as many files under the path as any other
269
+ * priority's do (a project held by two priorities counts for the higher
270
+ * ranked one). A folder that several priorities work in about equally, such
271
+ * as a repo's main source folder, says nothing about which one a change
272
+ * belongs to; a single file listed by two priorities counts for neither.
273
+ */
274
+ export declare function projectPaths(priorities: Priority[], plans: Record<string, ProjectPlan>): Map<string, PriorityPaths>;
275
+ /**
276
+ * True when a description refers to the project as tracked work: a line
277
+ * names the project id together with a story id ("usage-next US-030"), or the
278
+ * text gives the project's folder ("projects/<id>/"). A bare mention in prose
279
+ * or inside a file path is not a reference: project ids are often repo names.
280
+ */
281
+ export declare function refersToProject(description: string, projectId: string): boolean;
282
+ /** The type and scopes of a conventional-commit title ("fix(ci, sync)!: ..."), or null when the title is not one. */
283
+ export declare function conventionalTitle(title: string): {
284
+ type: string;
285
+ scopes: string[];
286
+ } | null;
287
+ /** A file that is part of CI itself: under .github/workflows or .github/actions, or inside a folder named ci. */
288
+ export declare function isCiPath(path: string): boolean;
289
+ /**
290
+ * Match one open pull request. Order: a company priority first, then a
291
+ * customer-facing fix, then a change to CI itself; anything else is routine.
292
+ *
293
+ * Priority evidence, strongest first:
294
+ * - strong: the branch or title carries the id of one of the priority's
295
+ * projects (a multi-word id, matched as a whole), the description refers to
296
+ * one (see refersToProject), or a session on the pull request's branch is
297
+ * bound to one of its projects;
298
+ * - scope: the title's conventional-commit type or scope is the priority's name;
299
+ * - name: the priority's name is in both the branch and the title;
300
+ * - paths: at least half of the changed files are in folders or files that
301
+ * only this priority's projects list in their plans, in the plan's repo.
302
+ * This is the weakest kind, so reading the changed paths never changes a
303
+ * match the cheaper evidence already made; the refresh reads paths only for
304
+ * pull requests nothing else matched.
305
+ * A branch that a project's plan names (or a branch under it) is strong
306
+ * evidence as well.
307
+ * The strongest kind wins. Within a kind, a priority whose own name is part of
308
+ * the project id found wins over one that holds the project through a merged
309
+ * term; then more evidence wins, then the higher ranked priority.
310
+ *
311
+ * A customer-facing fix is a fix (by conventional-commit type, branch prefix
312
+ * or label) with a customer label, the name of a customer the ontology lists,
313
+ * or a reference to a feedback record. A CI change has the conventional-commit
314
+ * type or scope "ci", a ci/ branch, the label "ci", or changes mostly CI files
315
+ * when the changed paths are given. Words in a title are not evidence: a pull
316
+ * request with none of the above is routine.
317
+ *
318
+ * The "ci-speedup" group holds every change to CI itself. Nothing in a pull
319
+ * request's metadata says whether a CI change makes CI faster, so the map does
320
+ * not claim that it does.
321
+ */
322
+ export declare function matchPullRequest(pr: PullRequest, ctx: MatchContext): PullRequestMatch;
323
+ export interface RenderOptions {
324
+ /** Most pull requests listed per group. Default 15. */
325
+ pullRequestLimit?: number;
326
+ /** Most work-in-flight items listed per repo. Default 8. */
327
+ workLimit?: number;
328
+ }
329
+ /** The map in plain language, with the source of every line that states a fact. */
330
+ export declare function renderPriorityMap(map: PriorityMap, opts?: RenderOptions): string;
331
+ //# sourceMappingURL=priorities.d.ts.map