@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
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Refreshing the Smart CI priority map (smart-ci US-002).
3
+ *
4
+ * A refresh reads the sources, builds a new map and stores it in the ledger.
5
+ * It never stands between the scheduler and a map:
6
+ *
7
+ * - currentPriorityMap reads the last stored map from the ledger and calls no
8
+ * source, so it answers at once whatever state the sources are in.
9
+ * - Each source read has its own time limit.
10
+ * - When any source is down, the previous map is kept whole, the failure is
11
+ * logged through `log` and recorded in the ledger as a failed run naming
12
+ * each source, and the refresh returns the previous map. While the same
13
+ * sources stay down the failed run is recorded once an hour, not on every
14
+ * retry.
15
+ * - Only when there is no full map to keep is a map built from the sources
16
+ * that did answer. It is marked degraded and lists the sources that were
17
+ * down. A degraded map is a stand-in, not a last good map: it is never kept
18
+ * in place of a rebuild, and refreshDue retries at the retry interval until
19
+ * a full map replaces it.
20
+ *
21
+ * Changed paths. Reading the files a pull request changes costs one GitHub
22
+ * request per pull request, so it is done only for pull requests that the
23
+ * cheaper evidence (branch, title, description, session, label) left
24
+ * unmatched, at most `maxPathReads` per refresh, and never twice for the same
25
+ * head commit: the paths are kept in the stored map and reused while the head
26
+ * is unchanged. The count of requests made is in the result and in the map's
27
+ * pull-requests source line.
28
+ *
29
+ * refreshDue says when to refresh: on a schedule, and as soon as a standup
30
+ * transcript appears that the current map was not built from. Every attempt
31
+ * notes its time (in the ledger and in this process), so an attempt whose
32
+ * ledger write was refused still starts the wait for the next one.
33
+ *
34
+ * Where the map is stored: the "priorities" scope of the Smart CI ledger
35
+ * (priority-snapshots.ts). Pass `ledger` when this process already owns it
36
+ * (the intake hosting the refresh, PriorityRefreshHost below); otherwise
37
+ * `ledgerDir`, which is opened only for the length of each write.
38
+ */
39
+ import { type BuildOptions, type PriorityMap } from "./priorities.js";
40
+ import { type LastGood, type RefreshRecord, type SourceFailure } from "./priority-snapshots.js";
41
+ import type { SmartCiLedger } from "./ledger.js";
42
+ import { type CommandRunner, type HqCommand, type OntologyRead, type ProjectPlan, type PullRequest, type SessionsRead, type StandupRead, type WorkMeshRead } from "./sources.js";
43
+ export declare const DEFAULT_REFRESH_INTERVAL_MS: number;
44
+ export declare const DEFAULT_RETRY_INTERVAL_MS: number;
45
+ /** While the same sources stay down, their failed run is written to the ledger this often. */
46
+ export declare const FAILURE_REPEAT_MS: number;
47
+ /** Where the snapshots go, from the options: the ledger this process owns, else the directory. */
48
+ export interface LedgerChoice {
49
+ /** The Smart CI ledger directory. Not needed when `ledger` is given. */
50
+ ledgerDir?: string;
51
+ /** The Smart CI ledger this process already owns (hosted refresh). */
52
+ ledger?: SmartCiLedger;
53
+ }
54
+ /** The source readers, replaceable in tests. Each rejects (or throws) when its source is down. */
55
+ export interface SourceReaders {
56
+ standups: (opts: {
57
+ company: string;
58
+ hqRoot: string;
59
+ fromMs: number;
60
+ toMs: number;
61
+ companyUid?: string;
62
+ }) => StandupRead | Promise<StandupRead>;
63
+ workMesh: (opts: {
64
+ company: string;
65
+ }) => Promise<WorkMeshRead>;
66
+ sessions: (opts: {
67
+ company: string;
68
+ }) => Promise<SessionsRead>;
69
+ ontology: (opts: {
70
+ company: string;
71
+ lookups: string[];
72
+ deadlineMs?: number;
73
+ }) => Promise<OntologyRead>;
74
+ pullRequests: (opts: {
75
+ repos: string[];
76
+ }) => Promise<PullRequest[]>;
77
+ /** The changed paths of one pull request, or null when they cannot be read. One GitHub request. */
78
+ pullRequestPaths: (opts: {
79
+ repo: string;
80
+ number: number;
81
+ }) => Promise<string[] | null>;
82
+ /** The plans of the named projects, from the company's own projects folder. */
83
+ projectPlans: (opts: {
84
+ company: string;
85
+ hqRoot: string;
86
+ projectIds: string[];
87
+ }) => Record<string, ProjectPlan>;
88
+ }
89
+ export interface RefreshOptions extends LedgerChoice {
90
+ company: string;
91
+ hqRoot: string;
92
+ /** Repos whose open pull requests are matched, as owner/name. */
93
+ repos: string[];
94
+ /** Milliseconds since the Unix epoch. Default Date.now. */
95
+ clock?: () => number;
96
+ /** Days of standups and activity to read. Default 7. */
97
+ windowDays?: number;
98
+ /** An explicit window, instead of the last `windowDays` days. */
99
+ window?: {
100
+ from: string;
101
+ to: string;
102
+ };
103
+ /** Receives one line per source failure and per kept or stored map. */
104
+ log?: (line: string) => void;
105
+ readers?: Partial<SourceReaders>;
106
+ run?: CommandRunner;
107
+ hq?: HqCommand;
108
+ /** Folder holding the Work Mesh cache. Default ~/.hq/work-mesh/cache. */
109
+ meshCacheDir?: string;
110
+ /** Time limit of one source read. Default 60 s. */
111
+ sourceTimeoutMs?: number;
112
+ /** Most ontology entities looked up per refresh. Default 12. */
113
+ lookupLimit?: number;
114
+ /** Most pull requests whose changed paths are requested from GitHub in one refresh. Default 150. */
115
+ maxPathReads?: number;
116
+ build?: BuildOptions;
117
+ }
118
+ export interface RefreshResult {
119
+ /** True when a new map was built in this refresh. */
120
+ refreshed: boolean;
121
+ /** True when the previous map was kept because a source was down. */
122
+ kept: boolean;
123
+ /** The map to use now: the new one, the previous one, or null when there is none at all. */
124
+ map: PriorityMap | null;
125
+ failures: SourceFailure[];
126
+ record: RefreshRecord | null;
127
+ /** Set when the ledger could not be written; the map was still built. */
128
+ ledgerError: string;
129
+ /** Changed-path reads in this refresh: GitHub requests made, pull requests served from the stored map, and unmatched pull requests left unread by the limit. */
130
+ pathReads: {
131
+ requested: number;
132
+ cached: number;
133
+ skipped: number;
134
+ };
135
+ }
136
+ /** The last stored map for the company, or null. Calls no source; safe on the scheduling path. */
137
+ export declare function currentPriorityMap(opts: LedgerChoice & {
138
+ company: string;
139
+ }): LastGood | null;
140
+ /** Read the sources, then store a new map or keep the previous one. Never throws for a source that is down. */
141
+ export declare function refreshPriorityMap(opts: RefreshOptions): Promise<RefreshResult>;
142
+ export interface RefreshDue {
143
+ due: boolean;
144
+ reason: string;
145
+ }
146
+ /**
147
+ * Whether to refresh now: there is no map, the schedule interval has passed
148
+ * since the last attempt, or a standup transcript has arrived that the map
149
+ * was not built from. After a failed attempt the next one waits for the retry
150
+ * interval, so a source that stays down is not hammered.
151
+ */
152
+ export declare function refreshDue(opts: LedgerChoice & {
153
+ company: string;
154
+ hqRoot: string;
155
+ clock?: () => number;
156
+ intervalMs?: number;
157
+ retryMs?: number;
158
+ }): RefreshDue;
159
+ /** Forget the attempt times kept in this process. For tests. */
160
+ export declare function forgetAttempts(): void;
161
+ export interface HostOptions extends Omit<RefreshOptions, "ledger" | "ledgerDir"> {
162
+ /** Schedule interval. Default 15 minutes. */
163
+ intervalMs?: number;
164
+ /** Wait after a failed attempt. Default 5 minutes. */
165
+ retryMs?: number;
166
+ }
167
+ /**
168
+ * Runs the priority map refresh inside the process that owns the Smart CI
169
+ * ledger (the intake), so the map is stored while the intake holds the store.
170
+ * `tick()` starts a refresh when one is due and none is running, and returns
171
+ * at once: the refresh runs beside the owner's own work and never delays it.
172
+ * A refresh that throws is logged and counted, never rethrown. `drain()`
173
+ * waits for a running refresh, for a clean close of the ledger.
174
+ */
175
+ export declare class PriorityRefreshHost {
176
+ private readonly ledger;
177
+ private readonly opts;
178
+ private running;
179
+ /** Refreshes started, stored and failed (threw) in this process. */
180
+ readonly counts: {
181
+ started: number;
182
+ stored: number;
183
+ kept: number;
184
+ failed: number;
185
+ };
186
+ constructor(ledger: SmartCiLedger, opts: HostOptions);
187
+ /** Start a refresh if one is due and none is running. Returns the reason it gave. */
188
+ tick(): RefreshDue;
189
+ /** Wait for a running refresh to finish. */
190
+ drain(): Promise<void>;
191
+ }
192
+ //# sourceMappingURL=priority-refresh.d.ts.map
@@ -0,0 +1,366 @@
1
+ /**
2
+ * Refreshing the Smart CI priority map (smart-ci US-002).
3
+ *
4
+ * A refresh reads the sources, builds a new map and stores it in the ledger.
5
+ * It never stands between the scheduler and a map:
6
+ *
7
+ * - currentPriorityMap reads the last stored map from the ledger and calls no
8
+ * source, so it answers at once whatever state the sources are in.
9
+ * - Each source read has its own time limit.
10
+ * - When any source is down, the previous map is kept whole, the failure is
11
+ * logged through `log` and recorded in the ledger as a failed run naming
12
+ * each source, and the refresh returns the previous map. While the same
13
+ * sources stay down the failed run is recorded once an hour, not on every
14
+ * retry.
15
+ * - Only when there is no full map to keep is a map built from the sources
16
+ * that did answer. It is marked degraded and lists the sources that were
17
+ * down. A degraded map is a stand-in, not a last good map: it is never kept
18
+ * in place of a rebuild, and refreshDue retries at the retry interval until
19
+ * a full map replaces it.
20
+ *
21
+ * Changed paths. Reading the files a pull request changes costs one GitHub
22
+ * request per pull request, so it is done only for pull requests that the
23
+ * cheaper evidence (branch, title, description, session, label) left
24
+ * unmatched, at most `maxPathReads` per refresh, and never twice for the same
25
+ * head commit: the paths are kept in the stored map and reused while the head
26
+ * is unchanged. The count of requests made is in the result and in the map's
27
+ * pull-requests source line.
28
+ *
29
+ * refreshDue says when to refresh: on a schedule, and as soon as a standup
30
+ * transcript appears that the current map was not built from. Every attempt
31
+ * notes its time (in the ledger and in this process), so an attempt whose
32
+ * ledger write was refused still starts the wait for the next one.
33
+ *
34
+ * Where the map is stored: the "priorities" scope of the Smart CI ledger
35
+ * (priority-snapshots.ts). Pass `ledger` when this process already owns it
36
+ * (the intake hosting the refresh, PriorityRefreshHost below); otherwise
37
+ * `ledgerDir`, which is opened only for the length of each write.
38
+ */
39
+ import { buildPriorityMap } from "./priorities.js";
40
+ import { enrolledWorkers, lastAttemptMs, noteAttempt, readLastGood, readRefreshLog, recordFailure, recordSnapshot, } from "./priority-snapshots.js";
41
+ import { SourceUnavailableError, assertCompanySlug, listStandupIdsSince, readOntology, readProjectPlans, readPullRequestPaths, readPullRequests, readSessions, readStandups, readWorkMesh, } from "./sources.js";
42
+ const DAY_MS = 24 * 60 * 60 * 1000;
43
+ export const DEFAULT_REFRESH_INTERVAL_MS = 15 * 60 * 1000;
44
+ export const DEFAULT_RETRY_INTERVAL_MS = 5 * 60 * 1000;
45
+ /** While the same sources stay down, their failed run is written to the ledger this often. */
46
+ export const FAILURE_REPEAT_MS = 60 * 60 * 1000;
47
+ /** Attempt times kept in this process, for when the ledger folder cannot be written at all. */
48
+ const attemptsInProcess = new Map();
49
+ const attemptKey = (ledgerDir, company) => `${ledgerDir}\n${company}`;
50
+ function targetOf(opts) {
51
+ if (opts.ledger)
52
+ return { target: { ledger: opts.ledger }, dir: opts.ledger.dir };
53
+ if (!opts.ledgerDir)
54
+ throw new Error("a priority map refresh needs the Smart CI ledger or its directory");
55
+ return { target: { dir: opts.ledgerDir }, dir: opts.ledgerDir };
56
+ }
57
+ function defaultReaders(opts) {
58
+ const cli = { run: opts.run, hq: opts.hq, timeoutMs: opts.sourceTimeoutMs };
59
+ return {
60
+ standups: (o) => readStandups(o),
61
+ workMesh: (o) => readWorkMesh({ ...cli, ...o, cacheDir: opts.meshCacheDir }),
62
+ sessions: (o) => readSessions({ ...cli, ...o }),
63
+ ontology: (o) => readOntology({ ...cli, ...o }),
64
+ pullRequests: (o) => readPullRequests({ run: opts.run, timeoutMs: opts.sourceTimeoutMs, ...o }),
65
+ pullRequestPaths: (o) => readPullRequestPaths({ run: opts.run, timeoutMs: opts.sourceTimeoutMs, ...o }),
66
+ projectPlans: (o) => readProjectPlans(o),
67
+ };
68
+ }
69
+ function withTimeout(source, work, timeoutMs) {
70
+ return new Promise((resolve, reject) => {
71
+ const timer = setTimeout(() => reject(new SourceUnavailableError(source, `no answer within ${timeoutMs} ms`)), timeoutMs);
72
+ work.then((v) => {
73
+ clearTimeout(timer);
74
+ resolve(v);
75
+ }, (err) => {
76
+ clearTimeout(timer);
77
+ reject(err instanceof Error ? err : new Error(String(err)));
78
+ });
79
+ });
80
+ }
81
+ function reason(err) {
82
+ const text = (err instanceof Error ? err.message : String(err)).split("\n")[0];
83
+ // Name the error code too when the message leaves it out (the ledger's STORE_HAS_WORKERS, for example).
84
+ const code = err instanceof Error ? err.code : undefined;
85
+ return typeof code === "string" && !text.startsWith(code) ? `${code}: ${text}` : text;
86
+ }
87
+ /** The last stored map for the company, or null. Calls no source; safe on the scheduling path. */
88
+ export function currentPriorityMap(opts) {
89
+ return readLastGood({ target: targetOf(opts).target, company: opts.company });
90
+ }
91
+ /** Read the sources, then store a new map or keep the previous one. Never throws for a source that is down. */
92
+ export async function refreshPriorityMap(opts) {
93
+ assertCompanySlug(opts.company);
94
+ const clock = opts.clock ?? Date.now;
95
+ const log = opts.log ?? (() => { });
96
+ const timeoutMs = opts.sourceTimeoutMs ?? 60_000;
97
+ const readers = { ...defaultReaders(opts), ...opts.readers };
98
+ const nowMs = clock();
99
+ // Noted first, in this process, so even a refresh that dies half way starts the wait for the next one.
100
+ const { target, dir } = targetOf(opts);
101
+ attemptsInProcess.set(attemptKey(dir, opts.company), nowMs);
102
+ const window = opts.window ?? { from: new Date(nowMs - (opts.windowDays ?? 7) * DAY_MS).toISOString(), to: new Date(nowMs).toISOString() };
103
+ const ledger = { target, company: opts.company, clock, log };
104
+ let previous = null;
105
+ try {
106
+ previous = readLastGood(ledger);
107
+ }
108
+ catch (err) {
109
+ log(`smart-ci priorities: could not read the last map from the ledger: ${reason(err)}`);
110
+ }
111
+ const failures = [];
112
+ const statuses = [];
113
+ const settle = async (source, work, describe) => {
114
+ const readAt = new Date(clock()).toISOString();
115
+ try {
116
+ const value = await withTimeout(source, Promise.resolve().then(work), timeoutMs);
117
+ statuses.push({ source, status: "ok", readAt, detail: describe(value) });
118
+ return value;
119
+ }
120
+ catch (err) {
121
+ const message = reason(err).replace(new RegExp(`^${source}: `), "");
122
+ failures.push({ source, message });
123
+ statuses.push({ source, status: "down", readAt, detail: message });
124
+ log(`smart-ci priorities: source ${source} is down: ${message}`);
125
+ return null;
126
+ }
127
+ };
128
+ const [mesh, sessions, pullRequests] = await Promise.all([
129
+ settle("work-mesh", () => readers.workMesh({ company: opts.company }), (v) => `${v.threads.length} threads, ${v.projects.length} projects.`),
130
+ settle("sessions", () => readers.sessions({ company: opts.company }), (v) => `${v.sessions.length} open sessions.`),
131
+ opts.repos.length === 0
132
+ ? Promise.resolve(null)
133
+ : settle("pull-requests", () => readers.pullRequests({ repos: opts.repos }), (v) => `${v.length} open pull requests in ${opts.repos.join(", ")}.`),
134
+ ]);
135
+ const standups = await settle("standups", () => readers.standups({ company: opts.company, hqRoot: opts.hqRoot, fromMs: Date.parse(window.from), toMs: Date.parse(window.to), companyUid: mesh?.companyUid || undefined }), (v) => `${v.standups.length} standup transcripts, ${v.background.transcripts} other meetings for comparison.`);
136
+ const base = (ontology, sources) => ({
137
+ company: opts.company,
138
+ now: new Date(nowMs).toISOString(),
139
+ window,
140
+ standups,
141
+ mesh,
142
+ sessions,
143
+ ontology,
144
+ pullRequests,
145
+ sources,
146
+ });
147
+ // Two ontology reads: the brief first, then lookup and neighbors for the projects that rank highest.
148
+ // Each read is many `hq` calls that share one time limit, counted from when that read starts; each call is
149
+ // started with what is left of it.
150
+ let ontologyDeadline = Date.now() + timeoutMs;
151
+ const brief = await settle("ontology", () => readers.ontology({ company: opts.company, lookups: [], deadlineMs: ontologyDeadline }), (v) => `${v.activeProjects.length} active projects in the brief.`);
152
+ let ontology = brief;
153
+ if (brief) {
154
+ const firstPass = buildPriorityMap(base(brief, []), opts.build);
155
+ const lookups = [...new Set(firstPass.priorities.flatMap((p) => p.projects.slice(0, 3)))].slice(0, opts.lookupLimit ?? 12);
156
+ if (lookups.length > 0) {
157
+ statuses.pop();
158
+ ontologyDeadline = Date.now() + timeoutMs;
159
+ ontology = await settle("ontology", () => readers.ontology({ company: opts.company, lookups, deadlineMs: ontologyDeadline }), (v) => `${v.activeProjects.length} active projects in the brief, ${Object.keys(v.entities).length} of ${lookups.length} entities resolved.`);
160
+ }
161
+ }
162
+ if (opts.repos.length === 0) {
163
+ statuses.push({ source: "pull-requests", status: "ok", readAt: new Date(clock()).toISOString(), detail: "No repo was named, so no pull request was read." });
164
+ }
165
+ const result = { refreshed: false, kept: false, map: previous?.map ?? null, failures, record: null, ledgerError: "", pathReads: { requested: 0, cached: 0, skipped: 0 } };
166
+ const write = (work) => {
167
+ try {
168
+ result.record = work();
169
+ }
170
+ catch (err) {
171
+ result.ledgerError = reason(err);
172
+ log(`smart-ci priorities: the ledger was not written: ${result.ledgerError}`);
173
+ }
174
+ };
175
+ const recordFailures = () => {
176
+ // The same sources still down: one failed run an hour is enough of a log.
177
+ let repeat = false;
178
+ try {
179
+ const newest = readRefreshLog(ledger).at(-1);
180
+ const same = newest?.status === "failed" && newest.failures.map((f) => f.source).sort().join() === failures.map((f) => f.source).sort().join();
181
+ repeat = same === true && nowMs - Date.parse(newest?.at ?? "") < FAILURE_REPEAT_MS;
182
+ }
183
+ catch {
184
+ // The log cannot be read; try to write.
185
+ }
186
+ if (!repeat)
187
+ write(() => recordFailure(ledger, failures));
188
+ };
189
+ // A degraded map is a stand-in. Only a full map is kept in place of a rebuild.
190
+ if (failures.length > 0 && previous && !previous.map.degraded) {
191
+ result.kept = true;
192
+ recordFailures();
193
+ if (!result.record)
194
+ noteAttempt(ledger);
195
+ log(`smart-ci priorities: kept the map built ${previous.map.builtAt}; down: ${failures.map((f) => f.source).join(", ")}`);
196
+ return result;
197
+ }
198
+ let inputs = base(ontology, statuses);
199
+ let map = buildPriorityMap(inputs, opts.build);
200
+ // The plans of the projects the priorities name: where each project says its work lands.
201
+ try {
202
+ const projectIds = [...new Set(map.priorities.flatMap((p) => p.projects))];
203
+ inputs = { ...inputs, projectPlans: readers.projectPlans({ company: opts.company, hqRoot: opts.hqRoot, projectIds }) };
204
+ map = buildPriorityMap(inputs, opts.build);
205
+ }
206
+ catch (err) {
207
+ log(`smart-ci priorities: project plans were not read: ${reason(err)}`);
208
+ }
209
+ // Changed paths, only for pull requests nothing else matched, and only once per head commit.
210
+ if (pullRequests && pullRequests.length > 0) {
211
+ const known = new Map();
212
+ for (const pr of previous?.map.pullRequests ?? []) {
213
+ if (pr.paths && pr.headSha)
214
+ known.set(`${pr.repo}#${pr.number}@${pr.headSha}`, pr.paths);
215
+ }
216
+ const unmatched = new Set(map.pullRequests.filter((m) => m.category === "routine").map((m) => `${m.repo}#${m.number}`));
217
+ const limit = opts.maxPathReads ?? 150;
218
+ const toRead = [];
219
+ const withPaths = pullRequests.map((pr) => {
220
+ if (!unmatched.has(`${pr.repo}#${pr.number}`))
221
+ return pr;
222
+ const cached = pr.headSha === "" ? undefined : known.get(`${pr.repo}#${pr.number}@${pr.headSha}`);
223
+ if (cached) {
224
+ result.pathReads.cached += 1;
225
+ return { ...pr, paths: cached };
226
+ }
227
+ const copy = { ...pr };
228
+ if (toRead.length < limit)
229
+ toRead.push(copy);
230
+ else
231
+ result.pathReads.skipped += 1;
232
+ return copy;
233
+ });
234
+ // A few at a time, so a refresh does not open a hundred connections at once.
235
+ const workers = Array.from({ length: Math.min(6, toRead.length) }, async () => {
236
+ for (let pr = toRead.shift(); pr !== undefined; pr = toRead.shift()) {
237
+ result.pathReads.requested += 1;
238
+ const paths = await readers.pullRequestPaths({ repo: pr.repo, number: pr.number }).catch(() => null);
239
+ if (paths)
240
+ pr.paths = paths;
241
+ }
242
+ });
243
+ await Promise.all(workers);
244
+ const status = statuses.find((x) => x.source === "pull-requests");
245
+ if (status) {
246
+ status.detail = `${status.detail} Changed files were needed for ${unmatched.size} pull request(s) nothing else matched: ${result.pathReads.requested} read from GitHub (one request each), ${result.pathReads.cached} reused from the stored map${result.pathReads.skipped > 0 ? `, ${result.pathReads.skipped} left for the next refresh` : ""}.`;
247
+ }
248
+ inputs = { ...inputs, pullRequests: withPaths };
249
+ map = buildPriorityMap(inputs, opts.build);
250
+ }
251
+ result.refreshed = true;
252
+ result.map = map;
253
+ if (failures.length > 0)
254
+ recordFailures();
255
+ const failureRecord = result.record;
256
+ result.record = null;
257
+ write(() => recordSnapshot(ledger, map));
258
+ const stored = result.record;
259
+ if (!stored) {
260
+ // The failure record (if any) stays the result; the attempt is noted when nothing at all was written.
261
+ result.record = failureRecord;
262
+ if (!failureRecord)
263
+ noteAttempt(ledger);
264
+ }
265
+ log(`smart-ci priorities: ${stored?.digest ? "stored" : "built"} a ${map.degraded ? "degraded " : ""}map with ${map.priorities.length} priorities`);
266
+ return result;
267
+ }
268
+ /**
269
+ * Whether to refresh now: there is no map, the schedule interval has passed
270
+ * since the last attempt, or a standup transcript has arrived that the map
271
+ * was not built from. After a failed attempt the next one waits for the retry
272
+ * interval, so a source that stays down is not hammered.
273
+ */
274
+ export function refreshDue(opts) {
275
+ const nowMs = (opts.clock ?? Date.now)();
276
+ const retryMs = opts.retryMs ?? DEFAULT_RETRY_INTERVAL_MS;
277
+ const { target, dir } = targetOf(opts);
278
+ const ledger = { target, company: opts.company };
279
+ // A store with delivery workers is never written by Smart CI, so a refresh there could not be stored or backed off.
280
+ if (!opts.ledger && enrolledWorkers(dir) > 0) {
281
+ return { due: false, reason: "the ledger directory is a store with delivery workers; Smart CI does not write there, so nothing would be stored" };
282
+ }
283
+ const records = readRefreshLog(ledger);
284
+ // The last attempt is the newest of: the last run in the ledger, the attempt marker, and this process's own note.
285
+ const attempts = [Date.parse(records.at(-1)?.at ?? ""), lastAttemptMs(ledger), attemptsInProcess.get(attemptKey(dir, opts.company)) ?? Number.NaN].filter((v) => !Number.isNaN(v) && v <= nowMs);
286
+ const sinceAttempt = attempts.length === 0 ? Infinity : nowMs - Math.max(...attempts);
287
+ const last = readLastGood(ledger);
288
+ if (!last) {
289
+ return sinceAttempt < retryMs ? { due: false, reason: "no map yet; the last attempt was moments ago" } : { due: true, reason: "no map yet" };
290
+ }
291
+ if (last.map.degraded) {
292
+ return sinceAttempt < retryMs ? { due: false, reason: "the stored map is degraded; the last attempt was moments ago" } : { due: true, reason: "the stored map was built while a source was down" };
293
+ }
294
+ if (sinceAttempt >= (opts.intervalMs ?? DEFAULT_REFRESH_INTERVAL_MS))
295
+ return { due: true, reason: "the scheduled interval has passed" };
296
+ const known = new Set(last.map.standupIds);
297
+ const fresh = listStandupIdsSince(opts.hqRoot, opts.company, Date.parse(last.map.window.from)).filter((id) => !known.has(id));
298
+ if (fresh.length > 0) {
299
+ return sinceAttempt < retryMs
300
+ ? { due: false, reason: `new standup transcript ${fresh[0]}; the last attempt was moments ago` }
301
+ : { due: true, reason: `new standup transcript ${fresh[0]}` };
302
+ }
303
+ return { due: false, reason: "the map is current" };
304
+ }
305
+ /** Forget the attempt times kept in this process. For tests. */
306
+ export function forgetAttempts() {
307
+ attemptsInProcess.clear();
308
+ }
309
+ /**
310
+ * Runs the priority map refresh inside the process that owns the Smart CI
311
+ * ledger (the intake), so the map is stored while the intake holds the store.
312
+ * `tick()` starts a refresh when one is due and none is running, and returns
313
+ * at once: the refresh runs beside the owner's own work and never delays it.
314
+ * A refresh that throws is logged and counted, never rethrown. `drain()`
315
+ * waits for a running refresh, for a clean close of the ledger.
316
+ */
317
+ export class PriorityRefreshHost {
318
+ ledger;
319
+ opts;
320
+ running = null;
321
+ /** Refreshes started, stored and failed (threw) in this process. */
322
+ counts = { started: 0, stored: 0, kept: 0, failed: 0 };
323
+ constructor(ledger, opts) {
324
+ this.ledger = ledger;
325
+ this.opts = opts;
326
+ assertCompanySlug(opts.company);
327
+ }
328
+ /** Start a refresh if one is due and none is running. Returns the reason it gave. */
329
+ tick() {
330
+ const log = this.opts.log ?? (() => { });
331
+ if (this.running)
332
+ return { due: false, reason: "a refresh is already running" };
333
+ let due;
334
+ try {
335
+ due = refreshDue({ ...this.opts, ledger: this.ledger });
336
+ }
337
+ catch (err) {
338
+ log(`smart-ci priorities: could not tell whether a refresh is due: ${reason(err)}`);
339
+ return { due: false, reason: reason(err) };
340
+ }
341
+ if (!due.due)
342
+ return due;
343
+ this.counts.started += 1;
344
+ this.running = refreshPriorityMap({ ...this.opts, ledger: this.ledger })
345
+ .then((r) => {
346
+ if (r.kept)
347
+ this.counts.kept += 1;
348
+ else if (r.record)
349
+ this.counts.stored += 1;
350
+ })
351
+ .catch((err) => {
352
+ this.counts.failed += 1;
353
+ log(`smart-ci priorities: the hosted refresh failed: ${reason(err)}`);
354
+ })
355
+ .finally(() => {
356
+ this.running = null;
357
+ });
358
+ return due;
359
+ }
360
+ /** Wait for a running refresh to finish. */
361
+ async drain() {
362
+ if (this.running)
363
+ await this.running;
364
+ }
365
+ }
366
+ //# sourceMappingURL=priority-refresh.js.map
@@ -0,0 +1,88 @@
1
+ import { SmartCiLedger } from "./ledger.js";
2
+ import { type PriorityMap } from "./priorities.js";
3
+ import { type SourceName } from "./sources.js";
4
+ export declare const PRIORITIES_NAMESPACE = "priorities";
5
+ export declare const SNAPSHOT_KIND = "map-snapshot";
6
+ export declare const FAILURE_KIND = "refresh-failed";
7
+ export declare const ATTEMPT_KIND = "refresh-attempt";
8
+ export interface SourceFailure {
9
+ source: SourceName;
10
+ message: string;
11
+ }
12
+ /**
13
+ * Where the snapshots go: a ledger directory (opened for each write, read
14
+ * without ownership), or the SmartCiLedger this process already owns.
15
+ */
16
+ export type PriorityLedgerTarget = {
17
+ dir: string;
18
+ ledger?: undefined;
19
+ } | {
20
+ ledger: SmartCiLedger;
21
+ dir?: undefined;
22
+ };
23
+ export interface SnapshotOptions {
24
+ target: PriorityLedgerTarget;
25
+ company: string;
26
+ /** Milliseconds since the Unix epoch, for a ledger this module opens. Default Date.now. */
27
+ clock?: () => number;
28
+ /** Controller id when this module opens the ledger. Default "smart-ci-priorities@<host>". */
29
+ controllerId?: string;
30
+ /** How many snapshots to keep. Default 20. */
31
+ keepSnapshots?: number;
32
+ /** How many failed refreshes to keep. Default 200. */
33
+ keepFailures?: number;
34
+ /** Receives a line for housekeeping that failed (pruning, the attempt note). */
35
+ log?: (line: string) => void;
36
+ }
37
+ export interface RefreshRecord {
38
+ /** Record id in the priorities scope. */
39
+ id: string;
40
+ status: "succeeded" | "failed";
41
+ /** When the ledger wrote the record. */
42
+ at: string;
43
+ /** sha256 of the map, for a succeeded refresh. */
44
+ digest: string;
45
+ failures: SourceFailure[];
46
+ }
47
+ export interface LastGood {
48
+ map: PriorityMap;
49
+ record: RefreshRecord;
50
+ }
51
+ /** Thrown, with nothing written, when another live process owns the ledger. */
52
+ export declare class LedgerHeldError extends Error {
53
+ readonly dir: string;
54
+ readonly code = "LEDGER_HELD";
55
+ constructor(dir: string, detail: string);
56
+ }
57
+ /** How many delivery workers the store in `dir` has on record. 0 when there is no store. Reads without any lock or ownership. */
58
+ export declare function enrolledWorkers(dir: string): number;
59
+ /**
60
+ * Whether this process can write the priority map now: true when it hosts the
61
+ * ledger, or when no other live process owns the directory. Answering costs one
62
+ * open and close of the ledger. Never throws.
63
+ */
64
+ export declare function ledgerWritable(opts: Pick<SnapshotOptions, "target" | "company" | "clock" | "controllerId">): {
65
+ writable: boolean;
66
+ reason: string;
67
+ };
68
+ /** Store a new map as the last good one, and note the attempt, in one commit. Prunes old snapshots after. */
69
+ export declare function recordSnapshot(opts: SnapshotOptions, map: PriorityMap): RefreshRecord;
70
+ /** Log a refresh that kept the previous map: one record naming each source that was down. Also notes the attempt. */
71
+ export declare function recordFailure(opts: SnapshotOptions, failures: SourceFailure[]): RefreshRecord;
72
+ /**
73
+ * Note the time of a refresh attempt, whatever came of it. Best effort:
74
+ * returns false, with nothing written, when the ledger cannot be written
75
+ * (another owner, or a store with delivery workers).
76
+ */
77
+ export declare function noteAttempt(opts: SnapshotOptions): boolean;
78
+ /** When the last refresh attempt was noted (epoch milliseconds), or NaN when none was. */
79
+ export declare function lastAttemptMs(opts: Pick<SnapshotOptions, "target" | "company">): number;
80
+ /** Every stored or failed refresh of the company that is still kept, oldest first. Empty when there is no ledger yet. */
81
+ export declare function readRefreshLog(opts: Pick<SnapshotOptions, "target" | "company">): RefreshRecord[];
82
+ /**
83
+ * The newest map stored for the company, or null. Reads the ledger and one
84
+ * blob; calls no source. A snapshot whose blob is missing, does not match its
85
+ * hash, or is not a map of this company is passed over for the one before it.
86
+ */
87
+ export declare function readLastGood(opts: Pick<SnapshotOptions, "target" | "company">): LastGood | null;
88
+ //# sourceMappingURL=priority-snapshots.d.ts.map