@indigoai-us/hq-cli 5.345.253 → 5.345.255

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 (34) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +8 -0
  3. package/contracts/host-canary-release.json +11 -5
  4. package/dist/command-catalog.generated.d.ts +61 -0
  5. package/dist/command-catalog.generated.js +75 -0
  6. package/dist/commands/ci-intake.d.ts +17 -0
  7. package/dist/commands/ci-intake.js +43 -1
  8. package/dist/commands/ci-priorities.d.ts +56 -0
  9. package/dist/commands/ci-priorities.js +144 -0
  10. package/dist/commands/ci.js +2 -1
  11. package/dist/commands/cloud.d.ts +11 -0
  12. package/dist/commands/cloud.js +76 -0
  13. package/dist/lib/daemon/verified-jq.d.ts +6 -0
  14. package/dist/lib/daemon/verified-jq.js +17 -5
  15. package/dist/lib/hook-engine/coverage.js +1 -0
  16. package/dist/lib/hook-engine/fleet-registration.d.ts +4 -0
  17. package/dist/lib/hook-engine/fleet-registration.js +25 -3
  18. package/dist/lib/smart-ci/priorities.d.ts +331 -0
  19. package/dist/lib/smart-ci/priorities.js +964 -0
  20. package/dist/lib/smart-ci/priority-refresh.d.ts +192 -0
  21. package/dist/lib/smart-ci/priority-refresh.js +366 -0
  22. package/dist/lib/smart-ci/priority-snapshots.d.ts +88 -0
  23. package/dist/lib/smart-ci/priority-snapshots.js +233 -0
  24. package/dist/lib/smart-ci/sources.d.ts +294 -0
  25. package/dist/lib/smart-ci/sources.js +659 -0
  26. package/dist/lib/smart-ci/text.d.ts +24 -0
  27. package/dist/lib/smart-ci/text.js +83 -0
  28. package/dist/lib/smart-ci/work-in-flight.d.ts +68 -0
  29. package/dist/lib/smart-ci/work-in-flight.js +154 -0
  30. package/dist/lib/sync/cli-manifest-reconcile.d.ts +20 -0
  31. package/dist/lib/sync/cli-manifest-reconcile.js +170 -0
  32. package/dist/utils/host-registration.d.ts +1 -0
  33. package/dist/utils/host-registration.js +1 -1
  34. package/package.json +7 -7
@@ -16,6 +16,7 @@
16
16
  import { isAccessDeniedError, accessDeniedKeyOf, formatAccessDenied, } from "../utils/access-denied-hint.js";
17
17
  import { describeSyncError, formatRemoteListNotConverging, } from "../utils/remote-list-not-converging.js";
18
18
  import { findReadOnlyLocalOnly, isGrantEnforced, readVaultAccessManifest, } from "../lib/sync/read-only-local-only.js";
19
+ import { reconcileCliPullManifest, } from "../lib/sync/cli-manifest-reconcile.js";
19
20
  import { SERVER_OWNED_FOLDERS, findServerOwnedLocalOnly, } from "../lib/sync/server-owned-local-only.js";
20
21
  import chalk from "chalk";
21
22
  import * as fs from "fs";
@@ -883,10 +884,16 @@ export async function pullAll(options, deps) {
883
884
  const plan = [];
884
885
  for (const m of memberships) {
885
886
  let slug = m.companyUid;
887
+ let name;
888
+ let bucketName;
886
889
  try {
887
890
  const info = await deps.vaultClient.getEntity(m.companyUid);
888
891
  if (info?.slug)
889
892
  slug = info.slug;
893
+ if (info?.name)
894
+ name = info.name;
895
+ if (info?.bucketName)
896
+ bucketName = info.bucketName;
890
897
  }
891
898
  catch {
892
899
  // Best-effort — keep UID as the row label rather than aborting the run.
@@ -897,6 +904,8 @@ export async function pullAll(options, deps) {
897
904
  slug,
898
905
  companyUid: m.companyUid,
899
906
  ...(m.membershipKey ? { membershipKey: m.membershipKey } : {}),
907
+ ...(name ? { name } : {}),
908
+ ...(bucketName ? { bucketName } : {}),
900
909
  syncOptions: {
901
910
  company: m.companyUid,
902
911
  hqRoot: options.hqRoot,
@@ -1029,6 +1038,37 @@ export async function pullAll(options, deps) {
1029
1038
  result.perCompany.push({ slug: entry.slug, error: message });
1030
1039
  }
1031
1040
  }
1041
+ // The menubar runner reconciles companies/manifest.yaml after a companies
1042
+ // fanout. CLI pull never did, so joiners pulled files into companies/<slug>
1043
+ // and still could not bind (feedback_cff52592).
1044
+ if (deps.reconcileManifest) {
1045
+ const completed = result.perCompany.filter((row) => !row.error);
1046
+ const targets = [];
1047
+ for (const entry of plan) {
1048
+ if (!entry.companyUid)
1049
+ continue;
1050
+ if (entry.syncOptions.personalMode === true || entry.slug === "personal") {
1051
+ continue;
1052
+ }
1053
+ if (!completed.some((row) => row.slug === entry.slug))
1054
+ continue;
1055
+ targets.push({
1056
+ slug: entry.slug,
1057
+ uid: entry.companyUid,
1058
+ ...(entry.name ? { name: entry.name } : {}),
1059
+ ...(entry.bucketName ? { bucketName: entry.bucketName } : {}),
1060
+ });
1061
+ }
1062
+ if (targets.length > 0) {
1063
+ try {
1064
+ await deps.reconcileManifest({ hqRoot: options.hqRoot, targets });
1065
+ }
1066
+ catch {
1067
+ // Same as the runner: a reconcile write failure is diagnostic, not a
1068
+ // failed pull. The files are already on disk.
1069
+ }
1070
+ }
1071
+ }
1032
1072
  return result;
1033
1073
  }
1034
1074
  /**
@@ -1976,6 +2016,39 @@ export function registerCloudCommands(program) {
1976
2016
  aborted: result.aborted,
1977
2017
  });
1978
2018
  console.log(chalk.green(`\n✓ Pulled ${result.filesDownloaded} file(s) (${formatBytes(result.bytesDownloaded)}, ${result.filesSkipped} skipped, ${result.conflicts} conflicts)`));
2019
+ // Same post-pull restore the --all path does (feedback_cff52592).
2020
+ if (resolvedCompanyUid) {
2021
+ try {
2022
+ let slug = options.company ?? readActiveCompany(options.hqRoot);
2023
+ let name;
2024
+ let bucketName;
2025
+ try {
2026
+ const entity = await pullClient.entity.get(resolvedCompanyUid);
2027
+ if (typeof entity.slug === "string" && entity.slug.length > 0) {
2028
+ slug = entity.slug;
2029
+ }
2030
+ name = typeof entity.name === "string" ? entity.name : undefined;
2031
+ bucketName =
2032
+ typeof entity.bucketName === "string" ? entity.bucketName : undefined;
2033
+ }
2034
+ catch {
2035
+ // cloud_uid alone is enough to bind.
2036
+ }
2037
+ if (slug) {
2038
+ reconcileCliPullManifest(options.hqRoot, [
2039
+ {
2040
+ slug,
2041
+ uid: resolvedCompanyUid,
2042
+ ...(name ? { name } : {}),
2043
+ ...(bucketName ? { bucketName } : {}),
2044
+ },
2045
+ ]);
2046
+ }
2047
+ }
2048
+ catch {
2049
+ // Diagnostic only — files are already on disk.
2050
+ }
2051
+ }
1979
2052
  // Emit the hint banner after success so it appears alongside the
1980
2053
  // summary line. Mirrors the wiring in runPullAll and runNowSingle.
1981
2054
  // Size-gated: only a large local folder is nudged.
@@ -2205,6 +2278,9 @@ async function runPullAll(hqRoot, onConflict, modeAllOverride, skipPersonal, for
2205
2278
  // via the shared resolver, so the actual pull is scoped — the CLI no
2206
2279
  // longer seeds an all-mode PullRecord that wedges the menubar runner.
2207
2280
  resolveScope: (companyUid, slug) => resolvePullScope(realClient, companyUid, slug, hqRoot),
2281
+ reconcileManifest: ({ hqRoot: root, targets }) => {
2282
+ reconcileCliPullManifest(root, targets);
2283
+ },
2208
2284
  sync: (opts) => syncLeg({
2209
2285
  company: opts.company,
2210
2286
  hqRoot: opts.hqRoot,
@@ -27,6 +27,12 @@ export declare const JQ_BEHAVIOR_PROBE: {
27
27
  readonly filter: "(if .a == null then \"\" else .a end) + \"|\" + (.b | ascii_upcase) + \"|\" + (.c | map(. * 2 | tostring) | join(\",\")) + \"|\" + (.d | to_entries | map(.key + \"=\" + .value) | join(\";\"))";
28
28
  readonly expected: "|X|2,4|e=f";
29
29
  };
30
+ /**
31
+ * Per probe step; real jq answers in milliseconds when idle, but spawning it
32
+ * under heavy CPU load can take several seconds. Ten seconds avoids false
33
+ * timeouts during load spikes while still failing closed on a hung stand-in.
34
+ */
35
+ export declare const PROBE_TIMEOUT_MS = 10000;
30
36
  export interface JqProbe {
31
37
  ok: boolean;
32
38
  version: string | null;
@@ -31,8 +31,12 @@ export const JQ_BEHAVIOR_PROBE = {
31
31
  filter: '(if .a == null then "" else .a end) + "|" + (.b | ascii_upcase) + "|" + (.c | map(. * 2 | tostring) | join(",")) + "|" + (.d | to_entries | map(.key + "=" + .value) | join(";"))',
32
32
  expected: "|X|2,4|e=f",
33
33
  };
34
- /** Per probe step; real jq answers in milliseconds. Keeps a cold check well under the client's timeout. */
35
- const PROBE_TIMEOUT_MS = 2_000;
34
+ /**
35
+ * Per probe step; real jq answers in milliseconds when idle, but spawning it
36
+ * under heavy CPU load can take several seconds. Ten seconds avoids false
37
+ * timeouts during load spikes while still failing closed on a hung stand-in.
38
+ */
39
+ export const PROBE_TIMEOUT_MS = 10_000;
36
40
  export class JqUnavailableError extends Error {
37
41
  rejected;
38
42
  note;
@@ -136,7 +140,7 @@ export function jqCandidates(env, platform = process.platform, vettedPaths = VET
136
140
  }
137
141
  return [...new Set([...vetted, ...fromPath])];
138
142
  }
139
- /** Probe results by real path, valid while the file's stat stamp is unchanged. */
143
+ /** Passing probe results by real path, valid while the file's stat stamp is unchanged. */
140
144
  const probeCache = new Map();
141
145
  /** For tests. */
142
146
  export function clearJqProbeCache() {
@@ -266,14 +270,22 @@ export async function resolveVerifiedJq(deps) {
266
270
  continue;
267
271
  let probe = probeCache.get(realPath);
268
272
  if (!probe || probe.stamp !== stamp) {
269
- probe = { stamp, probe: await probeJq(realPath, run, deps.timeoutMs) };
273
+ const result = await probeJq(realPath, run, deps.timeoutMs);
270
274
  // A verdict about replaced bytes must neither be cached nor used.
271
275
  if (stampOf(realPath) !== stamp) {
272
276
  probeCache.delete(realPath);
273
277
  rejected.push({ path: candidate, reason: "jq changed while it was being checked" });
274
278
  continue;
275
279
  }
276
- probeCache.set(realPath, probe);
280
+ probe = { stamp, probe: result };
281
+ // Only cache passing probes: a transient timeout under load must not
282
+ // lock out a working jq until the daemon restarts or the file changes.
283
+ if (result.ok) {
284
+ probeCache.set(realPath, probe);
285
+ }
286
+ else {
287
+ probeCache.delete(realPath);
288
+ }
277
289
  }
278
290
  if (!probe.probe.ok) {
279
291
  rejected.push({ path: candidate, reason: probe.probe.reason });
@@ -2258,6 +2258,7 @@ export function promptCompanyBindHold(root) {
2258
2258
  * (crates/hq-hook/src/gate/facts.rs `accepted_hook_lib_sha256`).
2259
2259
  */
2260
2260
  export const POLICY_GATE_REVISIONS = [
2261
+ { revision: 'Core16_0_52', gate: 'ecdbab7c2e0a1d94eb9c98f15e760390f215bc7115a217ded24b4275322722d2', hookLibs: ['436493e3325fb0cbcad651ae8ef42d89f4adf43fe38abd938ed6a39c0b6d17c1'] },
2261
2262
  { revision: 'Core16_0_51', gate: 'ca58a94859eae0a345c11c8d9c59303eb76350dc1cf223391037d21979c28718', hookLibs: ['9133295e5ce523bf8355a093bbea5a1c19682ec42b59ab6b626dffbc33544f3f'] },
2262
2263
  { revision: 'Staging2018', gate: '1bc4df8eaabded175804d2effba704c93b439df05c0867f85bb27f5dcfbc7914', hookLibs: ['9133295e5ce523bf8355a093bbea5a1c19682ec42b59ab6b626dffbc33544f3f'] },
2263
2264
  { revision: 'Core16_0_48Beta90', gate: 'a2879dfe692233f5953bac86672947bbd82f3c5247292f3efcb80f16c3d2c6b1', hookLibs: ['9133295e5ce523bf8355a093bbea5a1c19682ec42b59ab6b626dffbc33544f3f', '49c337ceccf0a2d7c2a64f6b1de8c3c4d1da507bc5d7afcd01ed292e1f25abf7', 'be7ca74b2524afba56fefd530bf46cbd1dd39a4c181b6a64c87e124b29bdebe7'] },
@@ -18,6 +18,9 @@ export type FleetEngineLookup = CoreNextEngineLookup;
18
18
  /** Self-check, then probe, then the host claim. */
19
19
  export declare function fleetEngineCapabilities(engine: string, probe?: typeof probeEngine, verify?: typeof verifyHookEngine, host?: FleetHost): EngineCapabilities;
20
20
  export declare function inspectFleetEngine(engine: string, home: string, probe?: typeof probeEngine, verify?: typeof verifyHookEngine, lookup?: FleetEngineLookup, host?: FleetHost): EngineCapabilities;
21
+ export declare const HAND_BACK_SCHEMA = "hq-hook.hand-back.v1";
22
+ export type HandBackQuery = (engine: string, args: string[], env: NodeJS.ProcessEnv) => string;
23
+ export declare function engineHandBack(caps: EngineCapabilities, argv: string[], env: NodeJS.ProcessEnv, query?: HandBackQuery): string | null;
21
24
  export interface FleetPlanOptions {
22
25
  home: string;
23
26
  env?: NodeJS.ProcessEnv;
@@ -27,6 +30,7 @@ export interface FleetPlanOptions {
27
30
  inspect?: (engine: string) => EngineCapabilities;
28
31
  /** Test injection. Production passes nothing and uses the desktop lookup. */
29
32
  lookup?: FleetEngineLookup;
33
+ handBackQuery?: HandBackQuery;
30
34
  }
31
35
  export interface FleetPlanEntry {
32
36
  mode: 'native' | 'shell';
@@ -8,6 +8,7 @@
8
8
  * else the host's shell adapter command, which is also the native entry's
9
9
  * `--fleet-fallback` argv, verbatim.
10
10
  */
11
+ import { execFileSync } from 'node:child_process';
11
12
  import * as fs from 'node:fs';
12
13
  import * as path from 'node:path';
13
14
  import { checkStableEngine, coreNextOffReason, capableEvents, probeEngine, missingEvaluators, resolveCoreNextEngine } from '../../utils/host-registration.js';
@@ -128,6 +129,24 @@ export function inspectFleetEngine(engine, home, probe = probeEngine, verify = v
128
129
  checkStableEngine(engine, resolved.pinned);
129
130
  return resolved.caps;
130
131
  }
132
+ export const HAND_BACK_SCHEMA = 'hq-hook.hand-back.v1';
133
+ function runHandBackQuery(engine, args, env) {
134
+ return execFileSync(engine, args, { encoding: 'utf8', timeout: 5000, env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
135
+ }
136
+ export function engineHandBack(caps, argv, env, query = runHandBackQuery) {
137
+ if (caps.handBackQuery !== HAND_BACK_SCHEMA)
138
+ return null;
139
+ let doc;
140
+ try {
141
+ doc = JSON.parse(query(argv[0], ['hand-back', '--json', ...argv.slice(1)], env));
142
+ }
143
+ catch (error) {
144
+ return `the engine's hand-back check failed: ${error.message.split('\n')[0]}`;
145
+ }
146
+ if (doc?.schema !== HAND_BACK_SCHEMA || !(doc.hand_back === null || typeof doc.hand_back === 'string'))
147
+ return `the engine's hand-back check did not print a ${HAND_BACK_SCHEMA} document`;
148
+ return doc.hand_back === null ? null : `the engine hands every call back to the adapter: ${doc.hand_back}`;
149
+ }
131
150
  export function fleetRegistrationPlan(root, fallbacks, options) {
132
151
  const host = options.host ?? 'fleet-local';
133
152
  if (!isFleetHost(host))
@@ -158,9 +177,12 @@ export function fleetRegistrationPlan(root, fallbacks, options) {
158
177
  if (!Array.isArray(fallback) || !fallback.every(arg => typeof arg === 'string'))
159
178
  throw new Error(`${event}: fallback must be an argv vector`);
160
179
  const problem = fallbackProblem(fallback, host, event);
161
- const native = !reason && !problem && target?.events.includes(canonical);
162
- const argv = native ? [engine, 'run', '--host', host, event, '--hq-root', root, '--fleet-fallback', JSON.stringify(fallback)] : fallback;
163
- const why = native ? 'complete evaluator and hook coverage' : reason ?? problem ?? (caps && missingEvaluators(caps, canonical)?.length ? 'required evaluators are missing' : `uncovered hooks: ${uncoveredHooks(root, host, canonical, caps?.covers, env).join(', ')}`);
180
+ const covered = !reason && !problem && target?.events.includes(canonical);
181
+ const nativeArgv = [engine, 'run', '--host', host, event, '--hq-root', root, '--fleet-fallback', JSON.stringify(fallback)];
182
+ const handBack = covered && caps ? engineHandBack(caps, nativeArgv, env, options.handBackQuery) : null;
183
+ const native = covered && !handBack;
184
+ const argv = native ? nativeArgv : fallback;
185
+ const why = native ? 'complete evaluator and hook coverage' : handBack ?? reason ?? problem ?? (caps && missingEvaluators(caps, canonical)?.length ? 'required evaluators are missing' : `uncovered hooks: ${uncoveredHooks(root, host, canonical, caps?.covers, env).join(', ')}`);
164
186
  events[event] = { mode: native ? 'native' : 'shell', argv, command: argv.map(quotePosix).join(' '), reason: why };
165
187
  }
166
188
  return { schema: 'hq.hook-registration-plan.v1', host, events };
@@ -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