@indigoai-us/hq-cli 5.345.253 → 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 (32) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/contracts/host-canary-release.json +11 -5
  3. package/dist/command-catalog.generated.d.ts +61 -0
  4. package/dist/command-catalog.generated.js +75 -0
  5. package/dist/commands/ci-intake.d.ts +17 -0
  6. package/dist/commands/ci-intake.js +43 -1
  7. package/dist/commands/ci-priorities.d.ts +56 -0
  8. package/dist/commands/ci-priorities.js +144 -0
  9. package/dist/commands/ci.js +2 -1
  10. package/dist/commands/cloud.d.ts +11 -0
  11. package/dist/commands/cloud.js +76 -0
  12. package/dist/lib/daemon/verified-jq.d.ts +6 -0
  13. package/dist/lib/daemon/verified-jq.js +17 -5
  14. package/dist/lib/hook-engine/fleet-registration.d.ts +4 -0
  15. package/dist/lib/hook-engine/fleet-registration.js +25 -3
  16. package/dist/lib/smart-ci/priorities.d.ts +331 -0
  17. package/dist/lib/smart-ci/priorities.js +964 -0
  18. package/dist/lib/smart-ci/priority-refresh.d.ts +192 -0
  19. package/dist/lib/smart-ci/priority-refresh.js +366 -0
  20. package/dist/lib/smart-ci/priority-snapshots.d.ts +88 -0
  21. package/dist/lib/smart-ci/priority-snapshots.js +233 -0
  22. package/dist/lib/smart-ci/sources.d.ts +294 -0
  23. package/dist/lib/smart-ci/sources.js +659 -0
  24. package/dist/lib/smart-ci/text.d.ts +24 -0
  25. package/dist/lib/smart-ci/text.js +83 -0
  26. package/dist/lib/smart-ci/work-in-flight.d.ts +68 -0
  27. package/dist/lib/smart-ci/work-in-flight.js +154 -0
  28. package/dist/lib/sync/cli-manifest-reconcile.d.ts +20 -0
  29. package/dist/lib/sync/cli-manifest-reconcile.js +170 -0
  30. package/dist/utils/host-registration.d.ts +1 -0
  31. package/dist/utils/host-registration.js +1 -1
  32. package/package.json +7 -7
@@ -0,0 +1,659 @@
1
+ /**
2
+ * Readers for the Smart CI priority map inputs (smart-ci US-002).
3
+ *
4
+ * Company isolation: every reader takes the company slug as an argument and
5
+ * reads only that company's data. There is no default company. Files are read
6
+ * only under `companies/<slug>/sources/meetings` and under the Work Mesh
7
+ * project cache folder of the company uid that Work Mesh itself returned for
8
+ * that slug. Every `hq` call carries `--company <slug>`. A transcript whose
9
+ * frontmatter names another company uid is skipped and counted.
10
+ *
11
+ * Read only: nothing here writes to Work Mesh, the ontology, the vault or
12
+ * GitHub. Pull requests are read with `gh api --method GET` on the machine's
13
+ * own gh login; GH_TOKEN and GITHUB_TOKEN are removed from the child's
14
+ * environment so a shared token is never used.
15
+ */
16
+ import { execFile } from "node:child_process";
17
+ import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync } from "node:fs";
18
+ import { homedir } from "node:os";
19
+ import { join } from "node:path";
20
+ import * as yaml from "js-yaml";
21
+ import { matchFrontmatter } from "../../utils/frontmatter.js";
22
+ import { isoDay, textTerms } from "./text.js";
23
+ export const PRIORITY_SOURCES = ["standups", "work-mesh", "sessions", "ontology"];
24
+ /**
25
+ * The kinds of record these readers return: a standup or meeting, a Work Mesh
26
+ * thread, project, lane and story, and a session. Every source is full of
27
+ * these words whatever the company works on (thread ids, session ids, "the
28
+ * lane", "this project"), so they describe the tooling the map reads from and
29
+ * never a piece of the company's work. The map does not take them as topic
30
+ * terms. A project whose name is made of them is still listed, under its id.
31
+ */
32
+ export const RECORD_KIND_WORDS = new Set(["standup", "meeting", "thread", "project", "lane", "story", "session"]);
33
+ /** Thrown by a reader when its source cannot be read. The refresh logs it and keeps the last good map. */
34
+ export class SourceUnavailableError extends Error {
35
+ source;
36
+ constructor(source, message) {
37
+ super(`${source}: ${message}`);
38
+ this.name = "SourceUnavailableError";
39
+ this.source = source;
40
+ }
41
+ }
42
+ const COMPANY_SLUG = /^[a-z0-9][a-z0-9-]{0,62}$/;
43
+ const COMPANY_UID = /^cmp_[A-Za-z0-9]+$/;
44
+ const REPO_NAME = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
45
+ /** True for owner/name with no "." or ".." segment, so it cannot climb out of `repos/` in an API path. */
46
+ function isRepoName(repo) {
47
+ return REPO_NAME.test(repo) && repo.split("/").every((part) => !/^\.+$/.test(part));
48
+ }
49
+ /** Refuse anything that is not a plain company slug before it reaches a path or a command. */
50
+ export function assertCompanySlug(company) {
51
+ if (typeof company !== "string" || !COMPANY_SLUG.test(company)) {
52
+ throw new Error(`company must be a company slug (lower-case letters, digits, dashes); got ${JSON.stringify(company)}`);
53
+ }
54
+ }
55
+ export const execRunner = (file, args, opts) => new Promise((resolve, reject) => {
56
+ execFile(file, args, { timeout: opts.timeoutMs, maxBuffer: 64 * 1024 * 1024, env: opts.env ?? process.env }, (err, stdout) => {
57
+ const code = err?.code;
58
+ if (err && typeof code !== "number")
59
+ reject(new Error(`${file} ${args.slice(0, 3).join(" ")} failed: ${err.message.split("\n")[0]}`));
60
+ else
61
+ resolve({ stdout: String(stdout), exitCode: typeof code === "number" ? code : 0 });
62
+ });
63
+ });
64
+ /** The running CLI itself, so the readers use the same build and login as the caller. */
65
+ export function defaultHqCommand() {
66
+ return { file: process.execPath, prefix: [process.argv[1] ?? "hq"] };
67
+ }
68
+ function parseJson(source, text, what) {
69
+ try {
70
+ return JSON.parse(text);
71
+ }
72
+ catch {
73
+ throw new SourceUnavailableError(source, `${what} did not return JSON`);
74
+ }
75
+ }
76
+ function isObject(v) {
77
+ return typeof v === "object" && v !== null && !Array.isArray(v);
78
+ }
79
+ function str(v) {
80
+ return typeof v === "string" ? v : "";
81
+ }
82
+ function arr(v) {
83
+ return Array.isArray(v) ? v : [];
84
+ }
85
+ function headerValue(v) {
86
+ if (typeof v === "string")
87
+ return v.trim();
88
+ return typeof v === "number" ? String(v) : "";
89
+ }
90
+ /**
91
+ * The fields the map needs from a transcript's header. The fence is split by
92
+ * the shared helper and the YAML is parsed as YAML (timestamps stay text).
93
+ * Null when the text has no header or the header is not a YAML mapping.
94
+ */
95
+ export function readMeetingHeader(text) {
96
+ const fenced = matchFrontmatter(text);
97
+ if (!fenced)
98
+ return null;
99
+ let parsed;
100
+ try {
101
+ parsed = yaml.load(fenced[1], { schema: yaml.CORE_SCHEMA });
102
+ }
103
+ catch {
104
+ return null;
105
+ }
106
+ if (!isObject(parsed))
107
+ return null;
108
+ return {
109
+ title: headerValue(parsed.title),
110
+ scheduledStart: headerValue(parsed.scheduled_start_time),
111
+ createdAt: headerValue(parsed.created_at),
112
+ companyId: headerValue(parsed.company_id),
113
+ };
114
+ }
115
+ /**
116
+ * The company's own cloud uid, from its company.yaml. Used to skip
117
+ * transcripts of another company when Work Mesh is not there to say the uid.
118
+ * "" when the file is missing or names no uid.
119
+ */
120
+ export function companyUidFromFile(hqRoot, company) {
121
+ assertCompanySlug(company);
122
+ try {
123
+ const parsed = yaml.load(readFileSync(join(hqRoot, "companies", company, "company.yaml"), "utf8"), { schema: yaml.CORE_SCHEMA });
124
+ const uid = isObject(parsed) ? str(parsed.cloudCompanyUid) : "";
125
+ return COMPANY_UID.test(uid) ? uid : "";
126
+ }
127
+ catch {
128
+ return "";
129
+ }
130
+ }
131
+ /** Speaker name without a trailing "(id)" and without surrounding space. */
132
+ function speakerName(raw) {
133
+ return raw.replace(/\s*\([^)]*\)\s*$/, "").trim();
134
+ }
135
+ function isNotetaker(name) {
136
+ return /notetaker|\bbot\b|recorder/i.test(name);
137
+ }
138
+ export function parseUtterances(text) {
139
+ const body = text.includes("## Transcript") ? text.slice(text.indexOf("## Transcript")) : text;
140
+ const out = [];
141
+ const pattern = /\*\*(.+?)\*\* · `\[(.+?)\]`\r?\n\r?\n([\s\S]*?)(?=\r?\n\r?\n\*\*[^\n]+?\*\* · `\[|$)/g;
142
+ for (let m = pattern.exec(body); m !== null; m = pattern.exec(body)) {
143
+ const speaker = speakerName(m[1]);
144
+ const said = m[3].trim();
145
+ if (speaker === "" || said === "" || isNotetaker(speaker))
146
+ continue;
147
+ out.push({ speaker, at: m[2], text: said });
148
+ }
149
+ return out;
150
+ }
151
+ /** A title the meeting pipeline writes when it has no calendar title. */
152
+ function isUntitled(title) {
153
+ return title === "" || /^meeting [0-9a-f-]{8,}$/i.test(title);
154
+ }
155
+ function readHead(path, bytes) {
156
+ const fd = openSync(path, "r");
157
+ try {
158
+ const buf = Buffer.alloc(bytes);
159
+ const n = readSync(fd, buf, 0, bytes, 0);
160
+ return buf.subarray(0, n).toString("utf8");
161
+ }
162
+ finally {
163
+ closeSync(fd);
164
+ }
165
+ }
166
+ const DAY_MS = 24 * 60 * 60 * 1000;
167
+ /** The meetings folder of one company. The slug is checked before it is put in a path. */
168
+ export function meetingsDir(hqRoot, company) {
169
+ assertCompanySlug(company);
170
+ return join(hqRoot, "companies", company, "sources", "meetings");
171
+ }
172
+ /**
173
+ * Read the standup transcripts in the window, plus term counts from the same
174
+ * company's other meetings (the background that tells a standup topic from
175
+ * ordinary talk). Standups are found by title and start time in the
176
+ * frontmatter. A meeting stored without a title is taken as a standup when
177
+ * most of its speakers also speak in the titled standups, and is reported as
178
+ * a gap.
179
+ */
180
+ export function readStandups(opts) {
181
+ const dir = meetingsDir(opts.hqRoot, opts.company);
182
+ if (!existsSync(dir))
183
+ throw new SourceUnavailableError("standups", `no meetings folder for company ${opts.company}`);
184
+ let names;
185
+ try {
186
+ names = readdirSync(dir).filter((n) => n.endsWith(".md")).sort();
187
+ }
188
+ catch (err) {
189
+ throw new SourceUnavailableError("standups", `cannot list the meetings folder: ${err.message}`);
190
+ }
191
+ const backgroundFrom = opts.toMs - (opts.backgroundDays ?? 30) * DAY_MS;
192
+ const backgroundLimit = opts.backgroundLimit ?? 400;
193
+ const overlapNeeded = opts.speakerOverlap ?? 0.6;
194
+ const companyUid = opts.companyUid || companyUidFromFile(opts.hqRoot, opts.company);
195
+ const titled = [];
196
+ const untitled = [];
197
+ const others = [];
198
+ let skippedOtherCompany = 0;
199
+ for (const name of names) {
200
+ let fm;
201
+ try {
202
+ fm = readMeetingHeader(readHead(join(dir, name), 4096));
203
+ }
204
+ catch {
205
+ continue;
206
+ }
207
+ if (!fm)
208
+ continue;
209
+ if (companyUid !== "" && fm.companyId !== "" && fm.companyId !== companyUid) {
210
+ skippedOtherCompany += 1;
211
+ continue;
212
+ }
213
+ const startMs = Date.parse(fm.scheduledStart || fm.createdAt);
214
+ if (Number.isNaN(startMs) || startMs < backgroundFrom || startMs >= opts.toMs)
215
+ continue;
216
+ const inWindow = startMs >= opts.fromMs;
217
+ const candidate = { name, fm, startMs };
218
+ if (/stand-?up/i.test(fm.title)) {
219
+ if (inWindow)
220
+ titled.push(candidate);
221
+ }
222
+ else if (isUntitled(fm.title) && inWindow)
223
+ untitled.push(candidate);
224
+ else
225
+ others.push(candidate);
226
+ }
227
+ const load = (c, titleInferred) => {
228
+ const text = readFileSync(join(dir, c.name), "utf8");
229
+ const startedAt = new Date(c.startMs).toISOString();
230
+ return {
231
+ id: c.name.replace(/\.md$/, ""),
232
+ file: join("companies", opts.company, "sources", "meetings", c.name),
233
+ title: c.fm.title,
234
+ date: isoDay(startedAt),
235
+ startedAt,
236
+ titleInferred,
237
+ utterances: parseUtterances(text),
238
+ };
239
+ };
240
+ const standups = titled.map((c) => load(c, false));
241
+ const gaps = [];
242
+ const standupSpeakers = new Set(standups.flatMap((s) => s.utterances.map((u) => u.speaker)));
243
+ for (const c of untitled) {
244
+ const t = load(c, true);
245
+ const speakers = new Set(t.utterances.map((u) => u.speaker));
246
+ if (speakers.size < 2 || standupSpeakers.size === 0) {
247
+ others.push(c);
248
+ continue;
249
+ }
250
+ const shared = [...speakers].filter((s) => standupSpeakers.has(s)).length;
251
+ if (shared / speakers.size >= overlapNeeded) {
252
+ standups.push(t);
253
+ gaps.push(`Meeting ${t.id} on ${t.date} is stored without a title; it was read as a standup because ${shared} of its ${speakers.size} speakers also speak in the titled standups.`);
254
+ }
255
+ else {
256
+ others.push(c);
257
+ }
258
+ }
259
+ standups.sort((a, b) => a.startedAt.localeCompare(b.startedAt));
260
+ const termUtterances = {};
261
+ let utterances = 0;
262
+ let transcripts = 0;
263
+ for (const c of others.sort((a, b) => b.startMs - a.startMs).slice(0, backgroundLimit)) {
264
+ let text;
265
+ try {
266
+ text = readFileSync(join(dir, c.name), "utf8");
267
+ }
268
+ catch {
269
+ continue;
270
+ }
271
+ transcripts += 1;
272
+ for (const u of parseUtterances(text)) {
273
+ utterances += 1;
274
+ for (const term of textTerms(u.text))
275
+ termUtterances[term] = (termUtterances[term] ?? 0) + 1;
276
+ }
277
+ }
278
+ return { standups, background: { utterances, termUtterances, transcripts }, skippedOtherCompany, gaps };
279
+ }
280
+ /** Ids of standup-titled transcripts that started at or after `sinceMs`, read from frontmatter only. */
281
+ export function listStandupIdsSince(hqRoot, company, sinceMs) {
282
+ const dir = meetingsDir(hqRoot, company);
283
+ if (!existsSync(dir))
284
+ return [];
285
+ const out = [];
286
+ for (const name of readdirSync(dir)) {
287
+ if (!name.endsWith(".md"))
288
+ continue;
289
+ let fm;
290
+ try {
291
+ fm = readMeetingHeader(readHead(join(dir, name), 4096));
292
+ }
293
+ catch {
294
+ continue;
295
+ }
296
+ if (!fm || !/stand-?up/i.test(fm.title))
297
+ continue;
298
+ const startMs = Date.parse(fm.scheduledStart || fm.createdAt);
299
+ if (!Number.isNaN(startMs) && startMs >= sinceMs)
300
+ out.push(name.replace(/\.md$/, ""));
301
+ }
302
+ return out.sort();
303
+ }
304
+ const DEFAULT_TIMEOUT_MS = 60_000;
305
+ /** `positional` values come from data (names, ids): they go after `--`, so one that starts with a dash is never read as an option. */
306
+ async function hqJson(source, opts, args, anyExit = false, positional = []) {
307
+ assertCompanySlug(opts.company);
308
+ const hq = opts.hq ?? defaultHqCommand();
309
+ const run = opts.run ?? execRunner;
310
+ const what = `hq ${args.slice(0, 2).join(" ")}`;
311
+ let result;
312
+ try {
313
+ result = await run(hq.file, [...hq.prefix, ...args, "--company", opts.company, ...(positional.length > 0 ? ["--", ...positional] : [])], { timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS });
314
+ }
315
+ catch (err) {
316
+ throw new SourceUnavailableError(source, err.message);
317
+ }
318
+ // A lookup that finds nothing exits non-zero and still prints its JSON answer: an answer, not an outage.
319
+ if (result.exitCode !== 0 && !anyExit)
320
+ throw new SourceUnavailableError(source, `${what} exited with code ${result.exitCode}`);
321
+ return parseJson(source, result.stdout, what);
322
+ }
323
+ function threadKind(raw) {
324
+ if (raw.kind === "lane")
325
+ return "lane";
326
+ if (raw.kind === "work-session")
327
+ return "work-session";
328
+ return str(raw.projectId) !== "" ? "project" : "other";
329
+ }
330
+ export function normalizeThread(raw) {
331
+ if (!isObject(raw) || str(raw.threadId) === "")
332
+ return null;
333
+ const session = isObject(raw.workSession) ? raw.workSession : {};
334
+ const classification = isObject(session.classification) ? session.classification : {};
335
+ const lane = isObject(raw.lane) ? raw.lane : {};
336
+ const senior = isObject(lane.senior) ? lane.senior : {};
337
+ const routing = isObject(raw.routing) ? raw.routing : {};
338
+ return {
339
+ threadId: str(raw.threadId),
340
+ kind: threadKind(raw),
341
+ projectId: str(raw.projectId) || str(classification.projectId),
342
+ status: str(raw.threadStatus),
343
+ ownerUid: str(raw.ownerUid),
344
+ priority: str(routing.priority) || "normal",
345
+ createdAt: str(raw.createdAt),
346
+ lastActivityAt: str(raw.lastActivityAt) || str(raw.createdAt),
347
+ sessionId: str(session.sessionId) || (senior.kind === "session" ? str(senior.id) : ""),
348
+ summary: str(raw.progressSummary) || str(raw.blockedReason) || str(classification.intentSummary),
349
+ };
350
+ }
351
+ export function normalizeProject(raw, names) {
352
+ if (!isObject(raw) || str(raw.projectId) === "")
353
+ return null;
354
+ const stories = [];
355
+ for (const s of arr(raw.stories)) {
356
+ if (!isObject(s) || str(s.id) === "")
357
+ continue;
358
+ const assignee = isObject(s.assignee) ? s.assignee : {};
359
+ const uid = str(s.assigneeUid);
360
+ const name = str(assignee.displayName) || str(assignee.name);
361
+ if (uid !== "" && name !== "")
362
+ names[uid] = name;
363
+ stories.push({ id: str(s.id), title: str(s.title), status: str(s.status), assignee: name || uid, updatedAt: str(s.lastActorAt) || str(s.assignedAt) });
364
+ }
365
+ return {
366
+ projectId: str(raw.projectId),
367
+ name: str(raw.name) || str(raw.projectId),
368
+ description: str(raw.description),
369
+ repos: arr(raw.repos)
370
+ .map((r) => (isObject(r) ? str(r.name) || str(r.repo) : str(r)))
371
+ .filter((r) => r !== ""),
372
+ updatedAt: str(raw.updatedAt),
373
+ stories,
374
+ };
375
+ }
376
+ /** Threads from `hq mesh check`, and project detail from the cache folder of the uid Work Mesh returned. */
377
+ export async function readWorkMesh(opts) {
378
+ const raw = await hqJson("work-mesh", opts, ["mesh", "check", "--json"]);
379
+ if (!isObject(raw) || raw.ok !== true || !Array.isArray(raw.threads)) {
380
+ throw new SourceUnavailableError("work-mesh", "hq mesh check did not return threads");
381
+ }
382
+ const company = isObject(raw.company) ? raw.company : {};
383
+ // The answer has to say which company it is for. One that names no company is not trusted.
384
+ if (str(company.companySlug) !== opts.company) {
385
+ throw new SourceUnavailableError("work-mesh", `hq mesh check answered for company ${str(company.companySlug) || "(none named)"}, not ${opts.company}`);
386
+ }
387
+ const companyUid = str(company.companyUid);
388
+ const threads = raw.threads.map(normalizeThread).filter((t) => t !== null);
389
+ const names = {};
390
+ const projects = [];
391
+ if (COMPANY_UID.test(companyUid)) {
392
+ const dir = join(opts.cacheDir ?? join(homedir(), ".hq", "work-mesh", "cache"), "projects", companyUid);
393
+ if (existsSync(dir)) {
394
+ for (const name of readdirSync(dir).sort()) {
395
+ if (!name.endsWith(".json"))
396
+ continue;
397
+ try {
398
+ const parsed = JSON.parse(readFileSync(join(dir, name), "utf8"));
399
+ // A cache file copied in from another company is ignored.
400
+ if (isObject(parsed) && str(parsed.companyUid) !== "" && str(parsed.companyUid) !== companyUid)
401
+ continue;
402
+ const project = normalizeProject(parsed, names);
403
+ if (project)
404
+ projects.push(project);
405
+ }
406
+ catch {
407
+ // An unreadable cache file is not a reason to lose the threads.
408
+ }
409
+ }
410
+ }
411
+ }
412
+ return { companyUid, threads, projects, names };
413
+ }
414
+ /** Open HQ sessions for the company, from the company-wide live read. */
415
+ export async function readSessions(opts) {
416
+ const raw = await hqJson("sessions", opts, ["mesh", "session", "status", "--json"]);
417
+ const live = isObject(raw) && isObject(raw.live) ? raw.live : null;
418
+ if (!isObject(raw) || raw.ok !== true || !live || !Array.isArray(live.participants)) {
419
+ throw new SourceUnavailableError("sessions", "hq mesh session status did not return participants");
420
+ }
421
+ const company = isObject(raw.company) ? raw.company : {};
422
+ if (str(company.companySlug) !== opts.company) {
423
+ throw new SourceUnavailableError("sessions", `hq mesh session status answered for company ${str(company.companySlug) || "(none named)"}, not ${opts.company}`);
424
+ }
425
+ const sessions = [];
426
+ const names = {};
427
+ for (const p of live.participants) {
428
+ if (!isObject(p))
429
+ continue;
430
+ const uid = str(p.actorUid);
431
+ const owner = str(p.displayName) || uid;
432
+ if (uid !== "" && str(p.displayName) !== "")
433
+ names[uid] = str(p.displayName);
434
+ for (const s of arr(p.sessions)) {
435
+ if (!isObject(s) || str(s.sessionId) === "")
436
+ continue;
437
+ sessions.push({
438
+ sessionId: str(s.sessionId),
439
+ owner,
440
+ ownerType: str(p.actorType),
441
+ status: str(s.status),
442
+ repo: str(s.repo),
443
+ branch: str(s.branch),
444
+ folder: str(s.folder),
445
+ startedAt: str(s.startedAt),
446
+ lastTurnAt: str(s.lastTurnAt) || str(s.startedAt),
447
+ });
448
+ }
449
+ }
450
+ return { generatedAt: str(live.generatedAt), sessions, names };
451
+ }
452
+ function briefList(brief, label) {
453
+ const line = brief.split("\n").find((l) => l.trim().toLowerCase().startsWith(`- ${label.toLowerCase()}`));
454
+ if (!line)
455
+ return [];
456
+ const at = line.indexOf(":");
457
+ if (at < 0)
458
+ return [];
459
+ return line
460
+ .slice(at + 1)
461
+ .split(";")
462
+ .map((s) => s.trim())
463
+ .filter((s) => s !== "");
464
+ }
465
+ function edgesOf(raw) {
466
+ return arr(raw)
467
+ .filter(isObject)
468
+ .map((e) => ({ verb: str(e.verb), target: str(e.target), name: str(e.name), src: str(e.src), date: str(e.valid_from) }))
469
+ .filter((e) => e.verb !== "" && e.target !== "");
470
+ }
471
+ /** The ontology brief, then lookup and neighbors for each name asked for. */
472
+ export async function readOntology(opts) {
473
+ const limit = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
474
+ const left = () => (opts.deadlineMs === undefined ? limit : Math.min(limit, opts.deadlineMs - Date.now()));
475
+ const raw = await hqJson("ontology", { ...opts, timeoutMs: Math.max(1, left()) }, ["ontology", "brief", "--stdout", "--json"]);
476
+ if (!isObject(raw) || typeof raw.brief !== "string")
477
+ throw new SourceUnavailableError("ontology", "hq ontology brief did not return a brief");
478
+ const out = {
479
+ activeProjects: briefList(raw.brief, "Active projects"),
480
+ customers: briefList(raw.brief, "Customers"),
481
+ entities: {},
482
+ gaps: [],
483
+ };
484
+ for (const name of opts.lookups ?? []) {
485
+ if (left() <= 0) {
486
+ out.gaps.push(`${name}: not looked up; the ontology read ran out of time`);
487
+ continue;
488
+ }
489
+ // The brief answered, so the ontology is up. A lookup that runs out of the shared time is a gap, not an outage.
490
+ let found;
491
+ let near = null;
492
+ try {
493
+ found = await hqJson("ontology", { ...opts, timeoutMs: left() }, ["ontology", "lookup", "--json"], true, [name]);
494
+ if (isObject(found) && found.status === "resolved" && isObject(found.entity)) {
495
+ near = await hqJson("ontology", { ...opts, timeoutMs: Math.max(1, left()) }, ["ontology", "neighbors", "--json"], true, [str(found.entity.id)]);
496
+ }
497
+ }
498
+ catch (err) {
499
+ if (opts.deadlineMs === undefined || left() > 0)
500
+ throw err;
501
+ out.gaps.push(`${name}: not looked up; the ontology read ran out of time`);
502
+ continue;
503
+ }
504
+ if (!isObject(found) || found.status !== "resolved" || !isObject(found.entity)) {
505
+ out.gaps.push(`${name}: the ontology has no entity by this name`);
506
+ continue;
507
+ }
508
+ const id = str(found.entity.id);
509
+ const facts = arr(found.facts).filter(isObject);
510
+ const fact = (f) => str(facts.find((x) => x.field === f)?.value);
511
+ const edges = edgesOf(isObject(near) ? near.edges : []);
512
+ const ownerEdge = edges.find((e) => e.verb === "owned_by") ?? edges.find((e) => e.verb === "led_by");
513
+ const dates = [...facts.map((f) => str(f.valid_from)), ...edges.map((e) => e.date)].filter((d) => d !== "").sort();
514
+ out.entities[name] = {
515
+ id,
516
+ name: str(found.entity.name),
517
+ aliases: arr(found.entity.aliases).map(str).filter((a) => a !== ""),
518
+ repo: fact("repo"),
519
+ status: fact("status"),
520
+ summary: fact("summary"),
521
+ owner: ownerEdge?.name ?? "",
522
+ ownerSource: ownerEdge?.src ?? "",
523
+ date: dates.at(-1) ?? "",
524
+ edges,
525
+ };
526
+ if (edges.length === 0)
527
+ out.gaps.push(`${name}: ${id} has no relationships in the ontology`);
528
+ }
529
+ return out;
530
+ }
531
+ /** The caller's environment without the shared GitHub token variables. */
532
+ export function ghEnvironment(env = process.env) {
533
+ const clean = { ...env };
534
+ delete clean.GH_TOKEN;
535
+ delete clean.GITHUB_TOKEN;
536
+ return clean;
537
+ }
538
+ /** The exact arguments of the one GitHub call this module makes per repo. A GET; it changes nothing. */
539
+ export function pullRequestArgs(repo) {
540
+ if (!isRepoName(repo))
541
+ throw new Error(`repo must be owner/name; got ${JSON.stringify(repo)}`);
542
+ return ["api", "--method", "GET", "--paginate", `repos/${repo}/pulls?state=open&per_page=100`];
543
+ }
544
+ /** Open pull requests of each repo, read with one paginated GET per repo. */
545
+ export async function readPullRequests(opts) {
546
+ const run = opts.run ?? execRunner;
547
+ const out = [];
548
+ for (const repo of opts.repos) {
549
+ let result;
550
+ try {
551
+ result = await run(opts.gh ?? "gh", pullRequestArgs(repo), { timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS, env: ghEnvironment() });
552
+ }
553
+ catch (err) {
554
+ throw new SourceUnavailableError("pull-requests", err.message);
555
+ }
556
+ if (result.exitCode !== 0)
557
+ throw new SourceUnavailableError("pull-requests", `gh api pulls for ${repo} exited with code ${result.exitCode}`);
558
+ const parsed = parseJson("pull-requests", result.stdout, `gh api pulls for ${repo}`);
559
+ for (const raw of arr(parsed).flat()) {
560
+ if (!isObject(raw) || typeof raw.number !== "number")
561
+ continue;
562
+ const head = isObject(raw.head) ? raw.head : {};
563
+ const user = isObject(raw.user) ? raw.user : {};
564
+ out.push({
565
+ repo,
566
+ number: raw.number,
567
+ title: str(raw.title),
568
+ branch: str(head.ref),
569
+ headSha: str(head.sha),
570
+ labels: arr(raw.labels)
571
+ .map((l) => (isObject(l) ? str(l.name) : ""))
572
+ .filter((l) => l !== ""),
573
+ author: str(user.login),
574
+ draft: raw.draft === true,
575
+ createdAt: str(raw.created_at),
576
+ updatedAt: str(raw.updated_at),
577
+ url: str(raw.html_url),
578
+ body: str(raw.body).slice(0, 4000),
579
+ });
580
+ }
581
+ }
582
+ return out;
583
+ }
584
+ /** The exact arguments of the one GitHub call made per pull request for its changed files. A GET; it changes nothing. */
585
+ export function pullRequestFilesArgs(repo, number) {
586
+ if (!isRepoName(repo))
587
+ throw new Error(`repo must be owner/name; got ${JSON.stringify(repo)}`);
588
+ if (!Number.isInteger(number) || number < 1)
589
+ throw new Error(`pull request number must be a positive whole number; got ${String(number)}`);
590
+ return ["api", "--method", "GET", `repos/${repo}/pulls/${number}/files?per_page=100`];
591
+ }
592
+ /**
593
+ * The paths of the files one pull request changes: its first 100, in one GET.
594
+ * Null when they could not be read; the pull request is then matched without
595
+ * them.
596
+ */
597
+ export async function readPullRequestPaths(opts) {
598
+ const run = opts.run ?? execRunner;
599
+ try {
600
+ const result = await run(opts.gh ?? "gh", pullRequestFilesArgs(opts.repo, opts.number), { timeoutMs: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS, env: ghEnvironment() });
601
+ if (result.exitCode !== 0)
602
+ return null;
603
+ const parsed = JSON.parse(result.stdout);
604
+ if (!Array.isArray(parsed))
605
+ return null;
606
+ return parsed.map((f) => (isObject(f) ? str(f.filename) : "")).filter((f) => f !== "");
607
+ }
608
+ catch {
609
+ return null;
610
+ }
611
+ }
612
+ const PROJECT_ID = /^[a-z0-9][a-z0-9._-]{0,120}$/;
613
+ /** A repo-relative path with no climbing and no other repo in front ("../x", "other-repo:path", "repos/..."). */
614
+ function planPath(raw) {
615
+ const path = str(raw).trim().replace(/\/+$/, "");
616
+ if (path === "" || path.startsWith("/") || path.startsWith(".") || path.includes(":") || path.includes("..") || /\s/.test(path))
617
+ return "";
618
+ if (/^(repos|companies|personal|core|workspace)\//.test(path))
619
+ return "";
620
+ return path;
621
+ }
622
+ /**
623
+ * Read the plans (prd.json) of the named projects from the company's own
624
+ * projects folder. A project with no plan, or an unreadable one, is left out:
625
+ * the plan is supporting evidence, not a source the map depends on.
626
+ */
627
+ export function readProjectPlans(opts) {
628
+ assertCompanySlug(opts.company);
629
+ const out = {};
630
+ for (const projectId of opts.projectIds) {
631
+ if (!PROJECT_ID.test(projectId) || projectId.includes(".."))
632
+ continue;
633
+ let parsed;
634
+ try {
635
+ parsed = JSON.parse(readFileSync(join(opts.hqRoot, "companies", opts.company, "projects", projectId, "prd.json"), "utf8"));
636
+ }
637
+ catch {
638
+ continue;
639
+ }
640
+ if (!isObject(parsed))
641
+ continue;
642
+ const metadata = isObject(parsed.metadata) ? parsed.metadata : {};
643
+ const repoPath = str(metadata.repoPath).replace(/\/+$/, "");
644
+ const repo = repoPath === "" ? "" : repoPath.slice(repoPath.lastIndexOf("/") + 1).toLowerCase();
645
+ const files = new Set();
646
+ for (const story of arr(parsed.userStories)) {
647
+ if (!isObject(story))
648
+ continue;
649
+ for (const f of arr(story.files)) {
650
+ const path = planPath(f);
651
+ if (path !== "")
652
+ files.add(path);
653
+ }
654
+ }
655
+ out[projectId] = { projectId, repo, branch: str(parsed.branchName).trim(), files: [...files].sort() };
656
+ }
657
+ return out;
658
+ }
659
+ //# sourceMappingURL=sources.js.map
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Text helpers for the Smart CI priority map (smart-ci US-002).
3
+ *
4
+ * Nothing here names a company, a project or a topic. The priority map gets
5
+ * its topic vocabulary from the company's own work (Work Mesh project ids,
6
+ * ontology project names, session repos); these helpers only split text into
7
+ * comparable terms and spot generic priority wording.
8
+ */
9
+ /** Lower-case word tokens. Keeps inner dots, plus and hash ("node.js", "c++"); drops punctuation. */
10
+ export declare function tokenize(text: string): string[];
11
+ /** Fold a plural onto its singular ("runners" and "runner" are one term). */
12
+ export declare function stem(word: string): string;
13
+ /** True for a term that can name a topic: not a stopword, not a number, not a hash. */
14
+ export declare function isTopicTerm(term: string): boolean;
15
+ /** Topic terms of a slug, repo or branch name, split on anything that is not a letter or digit. */
16
+ export declare function slugTerms(slug: string): string[];
17
+ /** Distinct stemmed terms of free text (an utterance, a title). */
18
+ export declare function textTerms(text: string): Set<string>;
19
+ export declare function hasPriorityCue(text: string): boolean;
20
+ /** One line, trimmed to `max` characters with an ellipsis. */
21
+ export declare function clip(text: string, max: number): string;
22
+ /** The calendar day (YYYY-MM-DD, UTC) of an ISO timestamp, or "" when it does not parse. */
23
+ export declare function isoDay(timestamp: string | null | undefined): string;
24
+ //# sourceMappingURL=text.d.ts.map