@indigoai-us/hq-cli 5.345.251 → 5.345.253

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 (188) hide show
  1. package/CHANGELOG.md +153 -0
  2. package/assets/scaffold/core/scripts/hq-session.sh +9 -0
  3. package/contracts/host-canary-release.json +9 -3
  4. package/dist/command-catalog.generated.d.ts +269 -1
  5. package/dist/command-catalog.generated.js +330 -1
  6. package/dist/command-registration-plan.d.ts +6 -0
  7. package/dist/command-registration-plan.js +1 -0
  8. package/dist/commands/bot.js +7 -2
  9. package/dist/commands/ci-intake.d.ts +15 -0
  10. package/dist/commands/ci-intake.js +252 -0
  11. package/dist/commands/ci-metrics.d.ts +8 -0
  12. package/dist/commands/ci-metrics.js +55 -0
  13. package/dist/commands/ci.d.ts +13 -0
  14. package/dist/commands/ci.js +10 -0
  15. package/dist/commands/core-bucket-c-work-mesh-offer-native.js +1 -1
  16. package/dist/commands/core-hq-session-binding.d.ts +140 -0
  17. package/dist/commands/core-hq-session-binding.js +363 -0
  18. package/dist/commands/core-hq-session-native.d.ts +23 -0
  19. package/dist/commands/core-hq-session-native.js +59 -9
  20. package/dist/commands/core-stop-autosave.js +1 -1
  21. package/dist/commands/core.js +10 -0
  22. package/dist/commands/doctor.d.ts +5 -1
  23. package/dist/commands/doctor.js +42 -5
  24. package/dist/commands/files.d.ts +62 -0
  25. package/dist/commands/files.js +250 -9
  26. package/dist/commands/install-global.js +4 -2
  27. package/dist/commands/logout.js +4 -0
  28. package/dist/commands/ontology-graph.d.ts +2 -0
  29. package/dist/commands/ontology-graph.js +33 -0
  30. package/dist/commands/report.js +35 -2
  31. package/dist/commands/storage-gate.js +1 -1
  32. package/dist/commands/vault-retention-flag.js +2 -1
  33. package/dist/commands/whoami.js +1 -1
  34. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +238 -221
  35. package/dist/hq-cloud-sync-runner/package.json +1 -1
  36. package/dist/index.js +3 -1
  37. package/dist/lib/agent-kit/inbox-poll-backoff-flag.js +1 -1
  38. package/dist/lib/agent-kit/mcp/tools.js +48 -0
  39. package/dist/lib/bot/fleet-bots-update-pass.js +1 -1
  40. package/dist/lib/bot/fleet-cron.d.ts +50 -0
  41. package/dist/lib/bot/fleet-cron.js +173 -32
  42. package/dist/lib/bot/fleet-local.d.ts +18 -0
  43. package/dist/lib/bot/fleet-local.js +51 -5
  44. package/dist/lib/bot/inbox-poll-backoff-flag.js +1 -1
  45. package/dist/lib/bot/signals-engine-flag.d.ts +1 -1
  46. package/dist/lib/bot/signals-engine-flag.js +1 -1
  47. package/dist/lib/cli-invite-nudge.js +1 -1
  48. package/dist/lib/client-version.d.ts +2 -0
  49. package/dist/lib/client-version.js +24 -0
  50. package/dist/lib/company-flag-gate.d.ts +30 -0
  51. package/dist/lib/company-flag-gate.js +104 -0
  52. package/dist/lib/core-utils/hook-timeout-debug-context-flag.js +1 -1
  53. package/dist/lib/daemon/flag.js +2 -1
  54. package/dist/lib/daemon/legacy-journal-gate.js +3 -1
  55. package/dist/lib/daemon/run.js +4 -3
  56. package/dist/lib/daemon/shared-flag-reads.js +1 -1
  57. package/dist/lib/delivery/migrations.d.ts +32 -1
  58. package/dist/lib/delivery/migrations.js +69 -8
  59. package/dist/lib/doctor/checks/host-core.js +22 -4
  60. package/dist/lib/doctor/checks/jq.d.ts +27 -6
  61. package/dist/lib/doctor/checks/jq.js +46 -8
  62. package/dist/lib/doctor/client-health-reason-codes-flag.js +1 -1
  63. package/dist/lib/doctor/fix/refresh-sync-handoff.d.ts +1 -1
  64. package/dist/lib/doctor/fix/refresh-sync-handoff.js +1 -1
  65. package/dist/lib/flag-client-gate-headers.d.ts +38 -0
  66. package/dist/lib/flag-client-gate-headers.js +62 -0
  67. package/dist/lib/flag-client-headers.d.ts +15 -0
  68. package/dist/lib/flag-client-headers.js +25 -0
  69. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  70. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  71. package/dist/lib/flag-registry-worker.js +35 -0
  72. package/dist/lib/flag-registry.d.ts +1 -20
  73. package/dist/lib/flag-registry.js +5 -81
  74. package/dist/lib/hook-engine/adapter-core-pin.d.ts +30 -0
  75. package/dist/lib/hook-engine/adapter-core-pin.js +30 -0
  76. package/dist/lib/hook-engine/coverage.d.ts +65 -1
  77. package/dist/lib/hook-engine/coverage.js +173 -8
  78. package/dist/lib/hook-engine/reconcile.js +3 -2
  79. package/dist/lib/hot-channels/prompts/signals-pass.md +20 -0
  80. package/dist/lib/hot-channels/signal-changes.d.ts +228 -0
  81. package/dist/lib/hot-channels/signal-changes.js +683 -0
  82. package/dist/lib/hot-channels/signals-pass.d.ts +24 -0
  83. package/dist/lib/hot-channels/signals-pass.js +232 -12
  84. package/dist/lib/lanes/outpost-worktree-pruner-flag.d.ts +1 -1
  85. package/dist/lib/lanes/outpost-worktree-pruner-flag.js +1 -1
  86. package/dist/lib/lanes/registry-flag.js +2 -1
  87. package/dist/lib/lanes/spawn.js +11 -1
  88. package/dist/lib/mesh/live/binding-intent.d.ts +61 -0
  89. package/dist/lib/mesh/live/binding-intent.js +201 -0
  90. package/dist/lib/mesh/live/binding-receipt.d.ts +157 -0
  91. package/dist/lib/mesh/live/binding-receipt.js +365 -0
  92. package/dist/lib/mesh/live/company-flag-refresh.js +1 -1
  93. package/dist/lib/mesh/live/daemon/doctor-telemetry.d.ts +39 -0
  94. package/dist/lib/mesh/live/daemon/doctor-telemetry.js +58 -0
  95. package/dist/lib/mesh/live/daemon/install.js +2 -1
  96. package/dist/lib/mesh/live/daemon/presence.js +9 -0
  97. package/dist/lib/mesh/live/daemon/run.d.ts +3 -0
  98. package/dist/lib/mesh/live/daemon/run.js +33 -1
  99. package/dist/lib/ontology-graph/lineage/index.d.ts +401 -0
  100. package/dist/lib/ontology-graph/lineage/index.js +1027 -0
  101. package/dist/lib/ontology-graph/model/index.d.ts +54 -0
  102. package/dist/lib/ontology-graph/model/index.js +112 -0
  103. package/dist/lib/ontology-graph/model/pass-tasks.d.ts +75 -0
  104. package/dist/lib/ontology-graph/model/pass-tasks.js +166 -0
  105. package/dist/lib/ontology-graph/model/pass.d.ts +6 -0
  106. package/dist/lib/ontology-graph/model/pass.js +9 -2
  107. package/dist/lib/ontology-graph/model/pending-items.d.ts +8 -0
  108. package/dist/lib/ontology-graph/model/pending-items.js +24 -1
  109. package/dist/lib/ontology-graph/model/step.d.ts +1 -1
  110. package/dist/lib/ontology-graph/model/tasks.d.ts +11 -3
  111. package/dist/lib/ontology-graph/model/tasks.js +20 -7
  112. package/dist/lib/ontology-graph/read/brief.js +41 -6
  113. package/dist/lib/ontology-graph/read/index.d.ts +4 -0
  114. package/dist/lib/ontology-graph/read/index.js +173 -29
  115. package/dist/lib/ontology-graph/read/lineage.d.ts +101 -0
  116. package/dist/lib/ontology-graph/read/lineage.js +262 -0
  117. package/dist/lib/ontology-graph/replay/buffered-store.js +17 -0
  118. package/dist/lib/ontology-graph/replay/engine.d.ts +32 -1
  119. package/dist/lib/ontology-graph/replay/engine.js +213 -8
  120. package/dist/lib/ontology-graph/replay/extractors.d.ts +26 -0
  121. package/dist/lib/ontology-graph/replay/extractors.js +25 -1
  122. package/dist/lib/ontology-graph/replay/index.d.ts +2 -0
  123. package/dist/lib/ontology-graph/replay/index.js +9 -3
  124. package/dist/lib/ontology-graph/replay/signal-changes.d.ts +118 -0
  125. package/dist/lib/ontology-graph/replay/signal-changes.js +687 -0
  126. package/dist/lib/ontology-graph/schema/decision-status.d.ts +18 -0
  127. package/dist/lib/ontology-graph/schema/decision-status.js +20 -0
  128. package/dist/lib/ontology-graph/schema/index.d.ts +1 -0
  129. package/dist/lib/ontology-graph/schema/index.js +1 -0
  130. package/dist/lib/ontology-graph/setup/index.js +13 -3
  131. package/dist/lib/search-index/index.d.ts +33 -1
  132. package/dist/lib/search-index/index.js +180 -25
  133. package/dist/lib/search-index/qmd-exit-diagnostics.d.ts +7 -0
  134. package/dist/lib/search-index/qmd-exit-diagnostics.js +25 -1
  135. package/dist/lib/signals/adapters-catalog.js +1 -1
  136. package/dist/lib/smart-ci/cost.d.ts +72 -0
  137. package/dist/lib/smart-ci/cost.js +120 -0
  138. package/dist/lib/smart-ci/github.d.ts +112 -0
  139. package/dist/lib/smart-ci/github.js +267 -0
  140. package/dist/lib/smart-ci/intake.d.ts +288 -0
  141. package/dist/lib/smart-ci/intake.js +1078 -0
  142. package/dist/lib/smart-ci/ledger.d.ts +218 -0
  143. package/dist/lib/smart-ci/ledger.js +527 -0
  144. package/dist/lib/smart-ci/metrics.d.ts +137 -0
  145. package/dist/lib/smart-ci/metrics.js +249 -0
  146. package/dist/lib/smart-ci/records.d.ts +265 -0
  147. package/dist/lib/smart-ci/records.js +281 -0
  148. package/dist/lib/smart-ci/reducer.d.ts +67 -0
  149. package/dist/lib/smart-ci/reducer.js +261 -0
  150. package/dist/lib/sync-core/engine-holds.d.ts +15 -0
  151. package/dist/lib/sync-core/engine-holds.js +104 -11
  152. package/dist/lib/sync-core/engine-home.d.ts +3 -0
  153. package/dist/lib/sync-core/engine-home.js +41 -1
  154. package/dist/lib/sync-core/flag.js +2 -1
  155. package/dist/lib/sync-core/hand-back.d.ts +1 -0
  156. package/dist/lib/sync-core/hand-back.js +7 -2
  157. package/dist/lib/sync-core/legacy-journal-export-child.js +5 -3
  158. package/dist/lib/sync-core/legacy-journal-export.d.ts +23 -4
  159. package/dist/lib/sync-core/legacy-journal-export.js +120 -55
  160. package/dist/lib/sync-core/reconcile.d.ts +2 -1
  161. package/dist/lib/sync-core/reconcile.js +40 -7
  162. package/dist/lib/sync-invalid-entity-warning.js +2 -1
  163. package/dist/lib/windows/install-followup.d.ts +41 -0
  164. package/dist/lib/windows/install-followup.js +87 -0
  165. package/dist/lib/windows/jq.d.ts +59 -0
  166. package/dist/lib/windows/jq.js +154 -3
  167. package/dist/lib/windows/user-path.d.ts +5 -0
  168. package/dist/lib/windows/user-path.js +1 -1
  169. package/dist/lib/work-context/auto-bind.d.ts +12 -0
  170. package/dist/lib/work-context/auto-bind.js +49 -3
  171. package/dist/lib/work-context/organize.d.ts +4 -2
  172. package/dist/lib/work-context/organize.js +18 -8
  173. package/dist/lib/work-context/reconcile.js +16 -1
  174. package/dist/main.js +12 -1
  175. package/dist/utils/client-health-contract.d.ts +30 -0
  176. package/dist/utils/client-health-contract.js +111 -0
  177. package/dist/utils/client-health.d.ts +5 -2
  178. package/dist/utils/client-health.js +74 -5
  179. package/dist/utils/exclusive-lock.d.ts +5 -1
  180. package/dist/utils/exclusive-lock.js +9 -2
  181. package/dist/utils/host-registration.d.ts +7 -0
  182. package/dist/utils/host-registration.js +10 -1
  183. package/dist/utils/pid.d.ts +31 -0
  184. package/dist/utils/pid.js +65 -0
  185. package/dist/utils/resident-package-preload.js +12 -4
  186. package/dist/utils/sentry-fingerprint.js +3 -0
  187. package/package.json +10 -8
  188. package/scripts/install-hook-engine.mjs +5 -3
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Cost per merge (smart-ci US-001).
3
+ *
4
+ * Same method as the CI cost study of 2026-11-22
5
+ * (workspace/reports/ship-faster-2026-11-20/corey-ci-cost-2026-11-22.md):
6
+ *
7
+ * cost per merge = (GitHub-hosted spend + AWS runner fleet spend) / merged pull requests
8
+ *
9
+ * over one window. The study took GitHub spend from the org billing usage API
10
+ * and AWS spend from Cost Explorer. The ledger holds neither bill, so each
11
+ * input is one of two things and the output says which:
12
+ *
13
+ * - measured: counted from ledger records (merges, job minutes per pool, idle
14
+ * runner minutes), or a billed amount the caller passed in;
15
+ * - estimated: minutes multiplied by a price from the table below.
16
+ *
17
+ * The prices are list prices written down on 2026-11-24 and are estimates.
18
+ * Pass billed amounts to replace them. Runners on hardware Indigo owns (the Mac
19
+ * pool, the Windows boxes) have no price here, as in the study, and count as $0.
20
+ */
21
+ export const DEFAULT_RATES = {
22
+ hostedPerMinute: { linux: 0.006, windows: 0.01, macos: 0.062 },
23
+ awsPerHour: {
24
+ "hq-cli-main-priority": 0.1795,
25
+ "hq-pr-pool-hq-cli": 0.1795,
26
+ "hq-cli-x64": 0.1058,
27
+ "hq-pro-main-ec2": 0.359,
28
+ "hq-pro-main-priority": 0.359,
29
+ "hq-pro-agents-main-ec2": 0.359,
30
+ "hq-cloud-bench-x64": 0.1058,
31
+ "indigo-arm64": 0.0898,
32
+ "indigo-x64": 0.1058,
33
+ "aws-local-ci": 0.319,
34
+ "aws-linux": 0.319,
35
+ },
36
+ awsOverheadPerHour: 0.0094,
37
+ };
38
+ /** Which bill a pool's minutes land on. */
39
+ export function classifyPool(pool, hosted, labels, rates) {
40
+ if (hosted) {
41
+ const all = [pool, ...labels].join(" ").toLowerCase();
42
+ if (all.includes("macos"))
43
+ return "hosted-macos";
44
+ if (all.includes("windows"))
45
+ return "hosted-windows";
46
+ return "hosted-linux";
47
+ }
48
+ return Object.prototype.hasOwnProperty.call(rates.awsPerHour, pool) ? "aws" : "own-hardware";
49
+ }
50
+ const usd = (n) => `$${n.toFixed(2)}`;
51
+ const mins = (n) => `${n.toFixed(1)} min`;
52
+ export function costPerMerge(input) {
53
+ const { rates } = input;
54
+ const inputs = [];
55
+ inputs.push({ input: "Merged pull requests", value: String(input.merges), basis: "measured", how: "pull request records in the ledger with a merge time in the window" });
56
+ const hosted = input.pools.filter((p) => p.poolClass.startsWith("hosted-"));
57
+ const hostedBilledMinutes = hosted.reduce((s, p) => s + p.billedMinutes, 0);
58
+ let githubHostedUsd;
59
+ if (input.githubBilledUsd !== undefined) {
60
+ githubHostedUsd = input.githubBilledUsd;
61
+ inputs.push({ input: "GitHub-hosted spend", value: usd(githubHostedUsd), basis: "measured", how: "billed amount passed in (GitHub billing usage API), as in the 2026-11-22 study" });
62
+ }
63
+ else {
64
+ githubHostedUsd = hosted.reduce((s, p) => {
65
+ const os = p.poolClass === "hosted-macos" ? "macos" : p.poolClass === "hosted-windows" ? "windows" : "linux";
66
+ return s + p.billedMinutes * rates.hostedPerMinute[os];
67
+ }, 0);
68
+ inputs.push({ input: "GitHub-hosted minutes", value: mins(hostedBilledMinutes), basis: "measured", how: "job records on GitHub-hosted runners, each job rounded up to a whole minute" });
69
+ inputs.push({
70
+ input: "GitHub-hosted spend",
71
+ value: usd(githubHostedUsd),
72
+ basis: "estimated",
73
+ how: `minutes x list price (Linux $${rates.hostedPerMinute.linux}, Windows $${rates.hostedPerMinute.windows}, macOS $${rates.hostedPerMinute.macos} a minute); no billed amount was passed in`,
74
+ });
75
+ }
76
+ const aws = input.pools.filter((p) => p.poolClass === "aws");
77
+ const awsRunMinutes = aws.reduce((s, p) => s + p.runMinutes, 0);
78
+ const idle = input.idleMinutesByPool;
79
+ const awsIdleMinutes = idle === null ? 0 : Object.entries(idle).reduce((s, [pool, m]) => s + (Object.prototype.hasOwnProperty.call(rates.awsPerHour, pool) ? m : 0), 0);
80
+ let awsUsd;
81
+ if (input.awsFleetUsd !== undefined) {
82
+ awsUsd = input.awsFleetUsd;
83
+ inputs.push({ input: "AWS runner fleet spend", value: usd(awsUsd), basis: "measured", how: "amount passed in (AWS Cost Explorer for the runner fleet), as in the 2026-11-22 study; pass this repo's share, or read the result as fleet spend over this repo's merges" });
84
+ }
85
+ else {
86
+ const rate = (pool) => (rates.awsPerHour[pool] ?? 0) + rates.awsOverheadPerHour;
87
+ const runUsd = aws.reduce((s, p) => s + (p.runMinutes / 60) * rate(p.pool), 0);
88
+ const idleUsd = idle === null ? 0 : Object.entries(idle).reduce((s, [pool, m]) => s + (Object.prototype.hasOwnProperty.call(rates.awsPerHour, pool) ? (m / 60) * rate(pool) : 0), 0);
89
+ awsUsd = runUsd + idleUsd;
90
+ inputs.push({ input: "AWS runner minutes running jobs", value: mins(awsRunMinutes), basis: "measured", how: "job records on AWS pools" });
91
+ inputs.push(idle === null
92
+ ? { input: "AWS runner minutes idle", value: "none", basis: "not counted", how: "the window has no runner pool samples, so idle and warm-pool time is missing from this cost" }
93
+ : (input.idleCoverage ?? 1) >= 0.95
94
+ ? { input: "AWS runner minutes idle", value: mins(awsIdleMinutes), basis: "measured", how: "runner pool samples: idle runners x time between samples, times this repo's share of the recorded run minutes on each pool" }
95
+ : {
96
+ input: "AWS runner minutes idle",
97
+ value: mins(awsIdleMinutes),
98
+ basis: "estimated",
99
+ how: `runner pool samples cover ${Math.round((input.idleCoverage ?? 0) * 100)}% of the sampled time (samples were skipped), so this is a lower bound; idle runners x time between samples, times this repo's share of the recorded run minutes on each pool`,
100
+ });
101
+ inputs.push({
102
+ input: "AWS runner fleet spend",
103
+ value: usd(awsUsd),
104
+ basis: "estimated",
105
+ how: "minutes x On-Demand list price per pool plus IPv4 and disk; boot time, Spot discounts and data transfer are not in it; no Cost Explorer amount was passed in",
106
+ });
107
+ }
108
+ const own = input.pools.filter((p) => p.poolClass === "own-hardware");
109
+ if (own.length > 0) {
110
+ inputs.push({
111
+ input: "Runners on owned hardware",
112
+ value: mins(own.reduce((s, p) => s + p.runMinutes, 0)),
113
+ basis: "not counted",
114
+ how: `pools ${own.map((p) => p.pool).sort().join(", ")} have no price (the 2026-11-22 study also left the Mac pool out); counted as $0`,
115
+ });
116
+ }
117
+ const totalUsd = githubHostedUsd + awsUsd;
118
+ return { usdPerMerge: input.merges > 0 ? totalUsd / input.merges : null, totalUsd, githubHostedUsd, awsUsd, merges: input.merges, inputs };
119
+ }
120
+ //# sourceMappingURL=cost.js.map
@@ -0,0 +1,112 @@
1
+ export declare const GITHUB_API = "https://api.github.com";
2
+ export declare class GitHubReadError extends Error {
3
+ readonly status: number;
4
+ readonly path: string;
5
+ /** Seconds to wait before another request, when GitHub said so. */
6
+ readonly retryAfterSeconds: number | null;
7
+ constructor(message: string, status: number, path: string,
8
+ /** Seconds to wait before another request, when GitHub said so. */
9
+ retryAfterSeconds?: number | null);
10
+ }
11
+ export interface AuditEntry {
12
+ ts: string;
13
+ method: "GET";
14
+ path: string;
15
+ status: number;
16
+ conditional: boolean;
17
+ rateRemaining: number | null;
18
+ rateUsed: number | null;
19
+ }
20
+ export interface GitHubResponse {
21
+ status: number;
22
+ /** True for 304: nothing changed since the last read of this path. */
23
+ notModified: boolean;
24
+ /** Parsed JSON body, or null on 304. */
25
+ body: unknown;
26
+ /** Query string of the next page from the Link header (GitHub links by repository id, so the caller keeps its own path), or null. */
27
+ nextQuery: string | null;
28
+ }
29
+ export type FetchLike = (url: string, init: {
30
+ method: "GET";
31
+ headers: Record<string, string>;
32
+ }) => Promise<{
33
+ status: number;
34
+ headers: {
35
+ get(name: string): string | null;
36
+ };
37
+ text(): Promise<string>;
38
+ }>;
39
+ export interface GitHubClientOptions {
40
+ token: string;
41
+ /** Default https://api.github.com. Tests point this at a local server. */
42
+ baseUrl?: string;
43
+ fetch?: FetchLike;
44
+ clock?: () => number;
45
+ /** Append one JSON line per request here. */
46
+ auditPath?: string;
47
+ /** Size at which the audit log is rotated to `<auditPath>.1`. Default 16 MB (about 100,000 requests). */
48
+ auditMaxBytes?: number;
49
+ /** Called with each audit entry, after it is written. */
50
+ onRequest?: (entry: AuditEntry) => void;
51
+ userAgent?: string;
52
+ }
53
+ /** How many requests were made, in total and in the last hour. */
54
+ export interface RequestCounts {
55
+ total: number;
56
+ notModified: number;
57
+ errors: number;
58
+ lastHour: number;
59
+ /** Requests in the last hour that were not answered 304: the ones that count against the rate limit. */
60
+ lastHourCounted: number;
61
+ rateRemaining: number | null;
62
+ }
63
+ export declare class GitHubReadClient {
64
+ private readonly token;
65
+ private readonly baseUrl;
66
+ private readonly fetchImpl;
67
+ private readonly clock;
68
+ private readonly auditPath;
69
+ private readonly auditMaxBytes;
70
+ private auditBytes;
71
+ private readonly onRequest;
72
+ private readonly userAgent;
73
+ private readonly etags;
74
+ private readonly recent;
75
+ private total;
76
+ private notModified;
77
+ private errors;
78
+ private rateRemaining;
79
+ private rateResetAt;
80
+ constructor(opts: GitHubClientOptions);
81
+ /**
82
+ * GET one allowed path. With `conditional` (the default) a known ETag is sent
83
+ * and a 304 comes back as notModified. Throws GitHubReadError for any other
84
+ * status than 200 or 304.
85
+ */
86
+ get(path: string, opts?: {
87
+ conditional?: boolean;
88
+ }): Promise<GitHubResponse>;
89
+ /** Forget the ETag of a path, so the next read returns the body again. */
90
+ forget(path: string): void;
91
+ /** Forget every ETag: what was read since the last commit did not reach the ledger. */
92
+ forgetAll(): void;
93
+ /** Charged requests (every answer but a 304) of the last hour, by clock minute, oldest first. */
94
+ chargedByMinute(): Array<[number, number]>;
95
+ private nextQuery;
96
+ private record;
97
+ counts(): RequestCounts;
98
+ /** When GitHub's rate window resets, in clock milliseconds, or null when not yet known. */
99
+ rateResetsAt(): number | null;
100
+ }
101
+ /** Read an audit log and count its requests. Any method other than GET is a write call. */
102
+ export declare function summarizeAudit(lines: readonly string[]): {
103
+ requests: number;
104
+ writes: number;
105
+ notModified: number;
106
+ byStatus: Record<string, number>;
107
+ firstAt: string | null;
108
+ lastAt: string | null;
109
+ perHour: number | null;
110
+ countedPerHour: number | null;
111
+ };
112
+ //# sourceMappingURL=github.d.ts.map
@@ -0,0 +1,267 @@
1
+ /**
2
+ * Read-only GitHub client for the Smart CI intake (smart-ci US-001).
3
+ *
4
+ * This client can only read. It has one request function, and that function
5
+ * sends GET: there is no method argument, so no caller can make it write. It
6
+ * also refuses any path outside the short list of read endpoints the intake
7
+ * uses, so a mistake elsewhere cannot reach, say, a rerun or cancel URL.
8
+ *
9
+ * Every request is written to an audit log (one JSON line: time, method, path,
10
+ * status, whether it was conditional, and the rate-limit numbers GitHub
11
+ * returned). The token is never logged. The audit log is the evidence that the
12
+ * intake made no write call and of how many requests it makes an hour.
13
+ *
14
+ * Conditional requests: the ETag of each response is kept, and the next
15
+ * request for the same path sends If-None-Match. GitHub answers 304 with no
16
+ * body when nothing changed, and a 304 does not count against the rate limit
17
+ * (checked against x-ratelimit-used in the audit log of a live hour: the
18
+ * counter did not move on a 304). So the client counts two things: every
19
+ * request, and the charged ones (every answer but a 304).
20
+ *
21
+ * The audit log is bounded: when it passes auditMaxBytes it is renamed to
22
+ * `<name>.1`, replacing the one before, and a new file is started.
23
+ */
24
+ import { appendFileSync, existsSync, mkdirSync, renameSync, statSync } from "node:fs";
25
+ import { dirname } from "node:path";
26
+ export const GITHUB_API = "https://api.github.com";
27
+ /** The only paths the intake may request. Each is a read endpoint. */
28
+ const ALLOWED_PATHS = [
29
+ /^\/repos\/[\w.-]+\/[\w.-]+\/actions\/runs(\?[^#]*)?$/,
30
+ /^\/repos\/[\w.-]+\/[\w.-]+\/actions\/runs\/\d+$/,
31
+ /^\/repos\/[\w.-]+\/[\w.-]+\/actions\/runs\/\d+\/jobs(\?[^#]*)?$/,
32
+ /^\/repos\/[\w.-]+\/[\w.-]+\/commits\/[0-9a-f]{7,64}\/check-runs(\?[^#]*)?$/,
33
+ /^\/repos\/[\w.-]+\/[\w.-]+\/pulls(\?[^#]*)?$/,
34
+ /^\/repos\/[\w.-]+\/[\w.-]+\/activity(\?[^#]*)?$/,
35
+ /^\/orgs\/[\w.-]+\/actions\/runners(\?[^#]*)?$/,
36
+ /^\/rate_limit$/,
37
+ ];
38
+ export class GitHubReadError extends Error {
39
+ status;
40
+ path;
41
+ retryAfterSeconds;
42
+ constructor(message, status, path,
43
+ /** Seconds to wait before another request, when GitHub said so. */
44
+ retryAfterSeconds = null) {
45
+ super(message);
46
+ this.status = status;
47
+ this.path = path;
48
+ this.retryAfterSeconds = retryAfterSeconds;
49
+ this.name = "GitHubReadError";
50
+ }
51
+ }
52
+ export class GitHubReadClient {
53
+ token;
54
+ baseUrl;
55
+ fetchImpl;
56
+ clock;
57
+ auditPath;
58
+ auditMaxBytes;
59
+ auditBytes = 0;
60
+ onRequest;
61
+ userAgent;
62
+ etags = new Map();
63
+ recent = [];
64
+ total = 0;
65
+ notModified = 0;
66
+ errors = 0;
67
+ rateRemaining = null;
68
+ rateResetAt = null;
69
+ constructor(opts) {
70
+ if (opts.token.trim() === "")
71
+ throw new Error("GitHubReadClient: a token is required");
72
+ this.token = opts.token;
73
+ this.baseUrl = (opts.baseUrl ?? GITHUB_API).replace(/\/+$/, "");
74
+ this.fetchImpl = opts.fetch ?? globalThis.fetch;
75
+ this.clock = opts.clock ?? Date.now;
76
+ this.auditPath = opts.auditPath;
77
+ this.onRequest = opts.onRequest;
78
+ this.userAgent = opts.userAgent ?? "hq-smart-ci-intake";
79
+ this.auditMaxBytes = Math.max(1024, opts.auditMaxBytes ?? 16 * 1024 * 1024);
80
+ if (this.auditPath) {
81
+ mkdirSync(dirname(this.auditPath), { recursive: true });
82
+ this.auditBytes = existsSync(this.auditPath) ? statSync(this.auditPath).size : 0;
83
+ }
84
+ }
85
+ /**
86
+ * GET one allowed path. With `conditional` (the default) a known ETag is sent
87
+ * and a 304 comes back as notModified. Throws GitHubReadError for any other
88
+ * status than 200 or 304.
89
+ */
90
+ async get(path, opts = {}) {
91
+ const segments = path.split("?")[0].split("/");
92
+ if (segments.includes("..") || segments.includes(".") || !ALLOWED_PATHS.some((p) => p.test(path))) {
93
+ throw new GitHubReadError(`refused: ${path.split("?")[0]} is not one of the read endpoints the Smart CI intake may call`, 0, path);
94
+ }
95
+ const etag = opts.conditional === false ? undefined : this.etags.get(path);
96
+ const headers = {
97
+ accept: "application/vnd.github+json",
98
+ authorization: `Bearer ${this.token}`,
99
+ "user-agent": this.userAgent,
100
+ "x-github-api-version": "2022-11-28",
101
+ };
102
+ if (etag)
103
+ headers["if-none-match"] = etag;
104
+ let status = 0;
105
+ let res = null;
106
+ try {
107
+ res = await this.fetchImpl(`${this.baseUrl}${path}`, { method: "GET", headers });
108
+ status = res.status;
109
+ }
110
+ catch (err) {
111
+ // No answer at all (DNS, a reset connection, a sleeping laptop). Reported like any failed read, so a poll cycle skips this stream and tries again.
112
+ throw new GitHubReadError(`could not reach GitHub for GET ${path.split("?")[0]}: ${err instanceof Error ? err.message : String(err)}`, 0, path);
113
+ }
114
+ finally {
115
+ const remaining = res ? intHeader(res.headers.get("x-ratelimit-remaining")) : null;
116
+ const reset = res ? intHeader(res.headers.get("x-ratelimit-reset")) : null;
117
+ if (remaining !== null)
118
+ this.rateRemaining = remaining;
119
+ if (reset !== null)
120
+ this.rateResetAt = reset * 1000;
121
+ this.record({
122
+ ts: new Date(this.clock()).toISOString(),
123
+ method: "GET",
124
+ path,
125
+ status,
126
+ conditional: etag !== undefined,
127
+ rateRemaining: remaining,
128
+ rateUsed: res ? intHeader(res.headers.get("x-ratelimit-used")) : null,
129
+ });
130
+ }
131
+ if (res === null)
132
+ throw new GitHubReadError(`could not reach GitHub for GET ${path.split("?")[0]}`, 0, path);
133
+ if (status === 304)
134
+ return { status, notModified: true, body: null, nextQuery: null };
135
+ let text;
136
+ try {
137
+ text = await res.text();
138
+ }
139
+ catch (err) {
140
+ throw new GitHubReadError(`the answer to GET ${path.split("?")[0]} was cut off: ${err instanceof Error ? err.message : String(err)}`, 0, path);
141
+ }
142
+ if (status !== 200) {
143
+ const retryAfter = intHeader(res.headers.get("retry-after"));
144
+ throw new GitHubReadError(`GitHub answered ${status} for GET ${path.split("?")[0]}`, status, path, retryAfter);
145
+ }
146
+ const newEtag = res.headers.get("etag");
147
+ if (newEtag)
148
+ this.etags.set(path, newEtag);
149
+ let body;
150
+ try {
151
+ body = JSON.parse(text);
152
+ }
153
+ catch {
154
+ throw new GitHubReadError(`GitHub answered 200 for GET ${path.split("?")[0]} with a body that is not JSON`, status, path);
155
+ }
156
+ return { status, notModified: false, body, nextQuery: this.nextQuery(res.headers.get("link")) };
157
+ }
158
+ /** Forget the ETag of a path, so the next read returns the body again. */
159
+ forget(path) {
160
+ this.etags.delete(path);
161
+ }
162
+ /** Forget every ETag: what was read since the last commit did not reach the ledger. */
163
+ forgetAll() {
164
+ this.etags.clear();
165
+ }
166
+ /** Charged requests (every answer but a 304) of the last hour, by clock minute, oldest first. */
167
+ chargedByMinute() {
168
+ this.counts();
169
+ const out = new Map();
170
+ for (const r of this.recent)
171
+ if (r.counted)
172
+ out.set(Math.floor(r.at / 60_000), (out.get(Math.floor(r.at / 60_000)) ?? 0) + 1);
173
+ return [...out].sort((a, b) => a[0] - b[0]);
174
+ }
175
+ nextQuery(link) {
176
+ if (!link)
177
+ return null;
178
+ for (const part of link.split(",")) {
179
+ const m = /<([^>]+)>;\s*rel="next"/.exec(part);
180
+ if (!m)
181
+ continue;
182
+ try {
183
+ return new URL(m[1]).search.replace(/^\?/, "");
184
+ }
185
+ catch {
186
+ return null;
187
+ }
188
+ }
189
+ return null;
190
+ }
191
+ record(entry) {
192
+ this.total += 1;
193
+ if (entry.status === 304)
194
+ this.notModified += 1;
195
+ if (entry.status !== 200 && entry.status !== 304)
196
+ this.errors += 1;
197
+ this.recent.push({ at: this.clock(), counted: entry.status !== 304 });
198
+ if (this.auditPath) {
199
+ const line = `${JSON.stringify(entry)}\n`;
200
+ if (this.auditBytes > 0 && this.auditBytes + line.length > this.auditMaxBytes) {
201
+ renameSync(this.auditPath, `${this.auditPath}.1`);
202
+ this.auditBytes = 0;
203
+ }
204
+ appendFileSync(this.auditPath, line);
205
+ this.auditBytes += line.length;
206
+ }
207
+ this.onRequest?.(entry);
208
+ }
209
+ counts() {
210
+ const cutoff = this.clock() - 3_600_000;
211
+ while (this.recent.length > 0 && this.recent[0].at < cutoff)
212
+ this.recent.shift();
213
+ return {
214
+ total: this.total,
215
+ notModified: this.notModified,
216
+ errors: this.errors,
217
+ lastHour: this.recent.length,
218
+ lastHourCounted: this.recent.filter((r) => r.counted).length,
219
+ rateRemaining: this.rateRemaining,
220
+ };
221
+ }
222
+ /** When GitHub's rate window resets, in clock milliseconds, or null when not yet known. */
223
+ rateResetsAt() {
224
+ return this.rateResetAt;
225
+ }
226
+ }
227
+ function intHeader(v) {
228
+ if (v === null || !/^\d+$/.test(v.trim()))
229
+ return null;
230
+ return Number(v.trim());
231
+ }
232
+ /** Read an audit log and count its requests. Any method other than GET is a write call. */
233
+ export function summarizeAudit(lines) {
234
+ let requests = 0;
235
+ let writes = 0;
236
+ let notModified = 0;
237
+ let firstAt = null;
238
+ let lastAt = null;
239
+ const byStatus = {};
240
+ for (const line of lines) {
241
+ if (line.trim() === "")
242
+ continue;
243
+ const e = JSON.parse(line);
244
+ requests += 1;
245
+ if (e.method !== "GET")
246
+ writes += 1;
247
+ if (e.status === 304)
248
+ notModified += 1;
249
+ byStatus[String(e.status)] = (byStatus[String(e.status)] ?? 0) + 1;
250
+ if (typeof e.ts === "string") {
251
+ firstAt ??= e.ts;
252
+ lastAt = e.ts;
253
+ }
254
+ }
255
+ const hours = firstAt && lastAt ? (Date.parse(lastAt) - Date.parse(firstAt)) / 3_600_000 : 0;
256
+ return {
257
+ requests,
258
+ writes,
259
+ notModified,
260
+ byStatus,
261
+ firstAt,
262
+ lastAt,
263
+ perHour: hours > 0 ? requests / hours : null,
264
+ countedPerHour: hours > 0 ? (requests - notModified) / hours : null,
265
+ };
266
+ }
267
+ //# sourceMappingURL=github.js.map