@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,281 @@
1
+ /**
2
+ * Smart CI records (smart-ci US-001).
3
+ *
4
+ * Two shapes live here. An Observation is what the intake saw: one GitHub
5
+ * workflow run, job, check run, pull request, push, or one sample of the
6
+ * runner pools, reduced to the fields Smart CI uses. A record body is what the
7
+ * ledger keeps: one per run, job, check run, pull request, push and sample,
8
+ * keyed so that the same observation written twice is still one record.
9
+ *
10
+ * Observations carry no actor, author, email or commit message. The fields are
11
+ * picked one by one from the API response, so nothing else can ride along.
12
+ * Every time in a record comes from GitHub, except a runner sample's
13
+ * sampledAt, which is the clock reading when the sample was taken.
14
+ */
15
+ export const SMART_CI_TENANT = "smart-ci";
16
+ export const KIND = {
17
+ run: "ci.run",
18
+ job: "ci.job",
19
+ checkRun: "ci.check_run",
20
+ pullRequest: "ci.pull_request",
21
+ push: "ci.push",
22
+ runnerSample: "ci.runner_sample",
23
+ /** A stretch of a stream the intake did not read (page limit or request budget). Written so a hole is visible. */
24
+ gap: "ci.gap",
25
+ };
26
+ /** The kinds the intake moves to archive files once they are old and closed. */
27
+ export const ROTATED_KINDS = ["ci.run", "ci.job", "ci.check_run", "ci.pull_request", "ci.push", "ci.runner_sample"];
28
+ export const OBSERVATION_TYPES = ["workflow_run", "workflow_job", "check_run", "pull_request", "push", "runner_pool"];
29
+ export const runKey = (repo, runId, attempt) => `${repo}/run/${runId}/${attempt}`;
30
+ export const jobKey = (repo, jobId) => `${repo}/job/${jobId}`;
31
+ export const checkRunKey = (repo, id) => `${repo}/check/${id}`;
32
+ export const pullRequestKey = (repo, number) => `${repo}/pr/${number}`;
33
+ export const pushKey = (repo, id) => `${repo}/push/${id}`;
34
+ export const runnerSampleKey = (org, sampledAt) => `${org}/runners/${sampledAt}`;
35
+ const STATUS_RANK = { queued: 0, in_progress: 1, completed: 2 };
36
+ export const statusRank = (s) => STATUS_RANK[s];
37
+ /** GitHub reports several not-yet-running states; Smart CI records them all as queued. */
38
+ export function normalizeStatus(raw) {
39
+ if (raw === "completed")
40
+ return "completed";
41
+ if (raw === "in_progress")
42
+ return "in_progress";
43
+ return "queued";
44
+ }
45
+ /** runs-on labels that say what kind of machine, not which pool. */
46
+ const GENERIC_LABELS = new Set(["self-hosted", "linux", "windows", "macos", "x64", "arm64", "arm"]);
47
+ /**
48
+ * The pool a job ran on or asked for. A self-hosted job names its pool in
49
+ * runs-on (hq-cli-x64, hq-mac-light); a GitHub-hosted job's label is the image
50
+ * (ubuntu-latest). With no usable label the runner group is the pool.
51
+ */
52
+ export function poolOf(labels, runnerGroup) {
53
+ const specific = labels.find((l) => !GENERIC_LABELS.has(l.toLowerCase()));
54
+ return specific ?? runnerGroup ?? "unknown";
55
+ }
56
+ /** True when the job asked for a GitHub-hosted runner (no self-hosted label, not in a self-hosted group). */
57
+ export function isHosted(job) {
58
+ if (job.labels.some((l) => l.toLowerCase() === "self-hosted"))
59
+ return false;
60
+ return job.runnerGroup === null || job.runnerGroup === "GitHub Actions";
61
+ }
62
+ function str(v) {
63
+ return typeof v === "string" && v !== "" ? v : null;
64
+ }
65
+ function num(v) {
66
+ return typeof v === "number" && Number.isFinite(v) ? v : 0;
67
+ }
68
+ function obj(v) {
69
+ return typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
70
+ }
71
+ function arr(v) {
72
+ return Array.isArray(v) ? v : [];
73
+ }
74
+ /** GitHub REST workflow run to observation. Array and string fields are coerced here, at the parse boundary. */
75
+ export function runFromApi(raw) {
76
+ const r = obj(raw);
77
+ return {
78
+ id: num(r.id),
79
+ attempt: num(r.run_attempt) || 1,
80
+ name: str(r.name) ?? "",
81
+ event: str(r.event) ?? "",
82
+ status: normalizeStatus(r.status),
83
+ conclusion: str(r.conclusion),
84
+ headBranch: str(r.head_branch),
85
+ headSha: str(r.head_sha) ?? "",
86
+ createdAt: str(r.created_at) ?? "",
87
+ startedAt: str(r.run_started_at),
88
+ updatedAt: str(r.updated_at),
89
+ prNumbers: arr(r.pull_requests)
90
+ .map((p) => num(obj(p).number))
91
+ .filter((n) => n > 0),
92
+ };
93
+ }
94
+ export function jobFromApi(raw) {
95
+ const j = obj(raw);
96
+ const status = normalizeStatus(j.status);
97
+ return {
98
+ id: num(j.id),
99
+ runId: num(j.run_id),
100
+ runAttempt: num(j.run_attempt) || 1,
101
+ workflow: str(j.workflow_name) ?? "",
102
+ name: str(j.name) ?? "",
103
+ headBranch: str(j.head_branch),
104
+ headSha: str(j.head_sha) ?? "",
105
+ status,
106
+ conclusion: str(j.conclusion),
107
+ createdAt: str(j.created_at) ?? "",
108
+ // A queued job has no start yet, whatever placeholder the API returns.
109
+ startedAt: status === "queued" ? null : str(j.started_at),
110
+ completedAt: status === "completed" ? str(j.completed_at) : null,
111
+ labels: arr(j.labels).filter((l) => typeof l === "string"),
112
+ runnerName: str(j.runner_name),
113
+ runnerGroup: str(j.runner_group_name),
114
+ };
115
+ }
116
+ export function checkRunFromApi(raw) {
117
+ const c = obj(raw);
118
+ const status = normalizeStatus(c.status);
119
+ return {
120
+ id: num(c.id),
121
+ name: str(c.name) ?? "",
122
+ headSha: str(c.head_sha) ?? "",
123
+ status,
124
+ conclusion: str(c.conclusion),
125
+ startedAt: str(c.started_at),
126
+ completedAt: status === "completed" ? str(c.completed_at) : null,
127
+ app: str(obj(c.app).slug),
128
+ };
129
+ }
130
+ export function pullRequestFromApi(raw) {
131
+ const p = obj(raw);
132
+ const head = obj(p.head);
133
+ return {
134
+ number: num(p.number),
135
+ title: str(p.title) ?? "",
136
+ state: p.state === "closed" ? "closed" : "open",
137
+ draft: p.draft === true,
138
+ createdAt: str(p.created_at) ?? "",
139
+ updatedAt: str(p.updated_at) ?? "",
140
+ closedAt: str(p.closed_at),
141
+ mergedAt: str(p.merged_at),
142
+ mergeCommitSha: str(p.merge_commit_sha),
143
+ headSha: str(head.sha) ?? "",
144
+ headRef: str(head.ref) ?? "",
145
+ baseRef: str(obj(p.base).ref) ?? "",
146
+ labels: arr(p.labels)
147
+ .map((l) => str(obj(l).name))
148
+ .filter((l) => l !== null),
149
+ };
150
+ }
151
+ export function pushFromApi(raw) {
152
+ const a = obj(raw);
153
+ return {
154
+ id: num(a.id),
155
+ ref: str(a.ref) ?? "",
156
+ before: str(a.before) ?? "",
157
+ after: str(a.after) ?? "",
158
+ at: str(a.timestamp) ?? "",
159
+ activityType: str(a.activity_type) ?? "",
160
+ };
161
+ }
162
+ /** Pool of a registered runner: its first label that is not a generic one, else its name with digits removed. */
163
+ export function runnerPool(raw) {
164
+ const r = obj(raw);
165
+ const labels = arr(r.labels)
166
+ .map((l) => str(obj(l).name))
167
+ .filter((l) => l !== null);
168
+ const specific = labels.find((l) => !GENERIC_LABELS.has(l.toLowerCase()));
169
+ return specific ?? (str(r.name) ?? "unknown").replace(/\d+/g, "N");
170
+ }
171
+ /** Reduce a list of registered runners to counts per pool. No runner name is kept. */
172
+ export function runnerSampleFromApi(runners, sampledAt) {
173
+ const pools = new Map();
174
+ for (const raw of runners) {
175
+ const r = obj(raw);
176
+ const pool = runnerPool(r);
177
+ const c = pools.get(pool) ?? { pool, online: 0, busy: 0, idle: 0, offline: 0 };
178
+ if (r.status === "online") {
179
+ c.online += 1;
180
+ if (r.busy === true)
181
+ c.busy += 1;
182
+ else
183
+ c.idle += 1;
184
+ }
185
+ else
186
+ c.offline += 1;
187
+ pools.set(pool, c);
188
+ }
189
+ return { sampledAt, total: runners.length, pools: [...pools.values()].sort((a, b) => a.pool.localeCompare(b.pool)) };
190
+ }
191
+ const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/;
192
+ const isIso = (v) => typeof v === "string" && ISO.test(v) && !Number.isNaN(Date.parse(v));
193
+ const isIsoOrNull = (v) => v === null || isIso(v);
194
+ const isId = (v) => typeof v === "number" && Number.isInteger(v) && v > 0;
195
+ const isRepo = (v) => typeof v === "string" && /^[\w.-]+\/[\w.-]+$/.test(v);
196
+ const isStatus = (v) => v === "queued" || v === "in_progress" || v === "completed";
197
+ const isStrings = (v) => Array.isArray(v) && v.every((s) => typeof s === "string");
198
+ /**
199
+ * Problems with one observation, or [] when it can be recorded. Used on every
200
+ * fixture line and on everything the poller builds, so a malformed input is
201
+ * refused with a reason instead of becoming a half-filled record.
202
+ */
203
+ export function validateObservation(input) {
204
+ const o = obj(input);
205
+ const errors = [];
206
+ const need = (ok, what) => {
207
+ if (!ok)
208
+ errors.push(what);
209
+ };
210
+ switch (o.type) {
211
+ case "workflow_run": {
212
+ const r = obj(o.run);
213
+ need(isRepo(o.repo), "repo: not owner/name");
214
+ need(isId(r.id), "run.id: not a positive integer");
215
+ need(isId(r.attempt), "run.attempt: not a positive integer");
216
+ need(isStatus(r.status), "run.status: unknown");
217
+ need(typeof r.headSha === "string" && r.headSha !== "", "run.headSha: missing");
218
+ need(isIso(r.createdAt), "run.createdAt: not a UTC timestamp");
219
+ need(isIsoOrNull(r.startedAt) && isIsoOrNull(r.updatedAt), "run times: not UTC timestamps");
220
+ need(Array.isArray(r.prNumbers) && r.prNumbers.every(isId), "run.prNumbers: not a list of numbers");
221
+ break;
222
+ }
223
+ case "workflow_job": {
224
+ const j = obj(o.job);
225
+ need(isRepo(o.repo), "repo: not owner/name");
226
+ need(isId(j.id), "job.id: not a positive integer");
227
+ need(isId(j.runId), "job.runId: not a positive integer");
228
+ need(isId(j.runAttempt), "job.runAttempt: not a positive integer");
229
+ need(isStatus(j.status), "job.status: unknown");
230
+ need(typeof j.headSha === "string" && j.headSha !== "", "job.headSha: missing");
231
+ need(isIso(j.createdAt), "job.createdAt: not a UTC timestamp");
232
+ need(isIsoOrNull(j.startedAt) && isIsoOrNull(j.completedAt), "job times: not UTC timestamps");
233
+ need(isStrings(j.labels), "job.labels: not a list of strings");
234
+ break;
235
+ }
236
+ case "check_run": {
237
+ const c = obj(o.checkRun);
238
+ need(isRepo(o.repo), "repo: not owner/name");
239
+ need(isId(c.id), "checkRun.id: not a positive integer");
240
+ need(isStatus(c.status), "checkRun.status: unknown");
241
+ need(typeof c.headSha === "string" && c.headSha !== "", "checkRun.headSha: missing");
242
+ need(isIsoOrNull(c.startedAt) && isIsoOrNull(c.completedAt), "checkRun times: not UTC timestamps");
243
+ break;
244
+ }
245
+ case "pull_request": {
246
+ const p = obj(o.pr);
247
+ need(isRepo(o.repo), "repo: not owner/name");
248
+ need(isId(p.number), "pr.number: not a positive integer");
249
+ need(p.state === "open" || p.state === "closed", "pr.state: unknown");
250
+ need(isIso(p.createdAt) && isIso(p.updatedAt), "pr.createdAt or updatedAt: not a UTC timestamp");
251
+ need(isIsoOrNull(p.closedAt) && isIsoOrNull(p.mergedAt), "pr.closedAt or mergedAt: not a UTC timestamp");
252
+ need(typeof p.headSha === "string" && p.headSha !== "", "pr.headSha: missing");
253
+ need(isStrings(p.labels), "pr.labels: not a list of strings");
254
+ break;
255
+ }
256
+ case "push": {
257
+ const p = obj(o.push);
258
+ need(isRepo(o.repo), "repo: not owner/name");
259
+ need(isId(p.id), "push.id: not a positive integer");
260
+ need(typeof p.ref === "string" && p.ref !== "", "push.ref: missing");
261
+ need(typeof p.before === "string" && typeof p.after === "string", "push.before or after: missing");
262
+ need(isIso(p.at), "push.at: not a UTC timestamp");
263
+ break;
264
+ }
265
+ case "runner_pool": {
266
+ const s = obj(o.sample);
267
+ need(typeof o.org === "string" && o.org !== "", "org: missing");
268
+ need(isIso(s.sampledAt), "sample.sampledAt: not a UTC timestamp");
269
+ need(Array.isArray(s.pools) &&
270
+ s.pools.every((p) => {
271
+ const c = obj(p);
272
+ return typeof c.pool === "string" && [c.online, c.busy, c.idle, c.offline].every((n) => typeof n === "number" && Number.isInteger(n) && n >= 0);
273
+ }), "sample.pools: not a list of pool counts");
274
+ break;
275
+ }
276
+ default:
277
+ errors.push(`type: unknown ${JSON.stringify(o.type)}`);
278
+ }
279
+ return errors;
280
+ }
281
+ //# sourceMappingURL=records.js.map
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Turns observations into ledger records (smart-ci US-001).
3
+ *
4
+ * Every rule here gives the same record whatever order the observations arrive
5
+ * in and however often one is repeated, because a restarted intake reads part
6
+ * of its input again:
7
+ *
8
+ * - A job or run only moves forward: queued, in_progress, completed. An
9
+ * observation of an earlier state than the stored one changes nothing, and
10
+ * one of the same state can only fill in fields that were empty.
11
+ * - A pull request keeps the observation with the newest updatedAt.
12
+ * - Whether a job's head was replaced is worked out from the job and the
13
+ * pushes on its branch, and worked out again when either side changes. A
14
+ * push seen before the job gives the same answer as one seen after it.
15
+ */
16
+ import type { Upsert } from "./ledger.js";
17
+ import { type JobBody, type Observation, type PushBody, type Replacement } from "./records.js";
18
+ /** What the reducer needs to read from the ledger. */
19
+ export interface RecordReader {
20
+ get<T extends Record<string, unknown>>(kind: string, id: string): T | undefined;
21
+ list<T extends Record<string, unknown>>(kind: string): T[];
22
+ }
23
+ /**
24
+ * The first push that moved the job's branch off the job's head, at or after
25
+ * the job was queued and before it finished. null when the job finished first
26
+ * or no such push is known.
27
+ */
28
+ export declare function replacementFor(job: Pick<JobBody, "queuedAt" | "finishedAt">, pushesFromHead: readonly PushBody[]): Replacement | null;
29
+ /**
30
+ * Holds the ledger's current records plus the ones produced so far in a batch,
31
+ * so a batch is reduced against its own earlier lines before anything is
32
+ * committed. Call reduce() for each observation, then take() the upserts and
33
+ * commit them; on a failed commit, drop the Reducer and build a new one.
34
+ */
35
+ export declare class Reducer {
36
+ private readonly ledger;
37
+ private readonly pending;
38
+ /** Pushes by (repo, branch, before sha). */
39
+ private readonly pushesFrom;
40
+ /** Job ids by (repo, branch, head sha). */
41
+ private readonly jobsAt;
42
+ /** The run event by (repo, run id), so a job learns its trigger. */
43
+ private readonly runEvent;
44
+ /** Job ids by (repo, run id). */
45
+ private readonly jobsOfRun;
46
+ constructor(ledger: RecordReader);
47
+ private indexPush;
48
+ private indexJob;
49
+ private read;
50
+ /** A record as it will be after this batch: the pending one, else the ledger's. */
51
+ peek<T extends Record<string, unknown>>(kind: string, id: string): T | undefined;
52
+ /** The ledger's records of a kind with this batch's pending ones laid over them. */
53
+ list<T extends Record<string, unknown>>(kind: string, idOf: (body: T) => string): T[];
54
+ /** Put a record that is not derived from an observation into the batch. */
55
+ put(kind: string, id: string, body: Record<string, unknown>): void;
56
+ private write;
57
+ private replacement;
58
+ reduce(o: Observation): void;
59
+ private reduceJob;
60
+ private reduceRun;
61
+ private reduceCheckRun;
62
+ private reducePullRequest;
63
+ private reducePush;
64
+ /** The records this batch produced, and an empty batch afterwards. */
65
+ take(): Upsert[];
66
+ }
67
+ //# sourceMappingURL=reducer.d.ts.map
@@ -0,0 +1,261 @@
1
+ import { KIND, checkRunKey, jobKey, poolOf, pullRequestKey, pushKey, runKey, runnerSampleKey, statusRank, } from "./records.js";
2
+ const branchOfRef = (ref) => (ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length) : null);
3
+ const headKey = (repo, branch, sha) => `${repo}\u0000${branch}\u0000${sha}`;
4
+ const runIdKey = (repo, runId) => `${repo}\u0000${runId}`;
5
+ /**
6
+ * The first push that moved the job's branch off the job's head, at or after
7
+ * the job was queued and before it finished. null when the job finished first
8
+ * or no such push is known.
9
+ */
10
+ export function replacementFor(job, pushesFromHead) {
11
+ const queued = Date.parse(job.queuedAt);
12
+ const finished = job.finishedAt === null ? Number.POSITIVE_INFINITY : Date.parse(job.finishedAt);
13
+ let best = null;
14
+ for (const p of pushesFromHead) {
15
+ const at = Date.parse(p.at);
16
+ if (at < queued || at >= finished)
17
+ continue;
18
+ if (best === null || at < Date.parse(best.at) || (at === Date.parse(best.at) && p.pushId < best.pushId))
19
+ best = p;
20
+ }
21
+ return best === null ? null : { bySha: best.after, at: best.at, pushId: best.pushId };
22
+ }
23
+ /**
24
+ * Holds the ledger's current records plus the ones produced so far in a batch,
25
+ * so a batch is reduced against its own earlier lines before anything is
26
+ * committed. Call reduce() for each observation, then take() the upserts and
27
+ * commit them; on a failed commit, drop the Reducer and build a new one.
28
+ */
29
+ export class Reducer {
30
+ ledger;
31
+ pending = new Map();
32
+ /** Pushes by (repo, branch, before sha). */
33
+ pushesFrom = new Map();
34
+ /** Job ids by (repo, branch, head sha). */
35
+ jobsAt = new Map();
36
+ /** The run event by (repo, run id), so a job learns its trigger. */
37
+ runEvent = new Map();
38
+ /** Job ids by (repo, run id). */
39
+ jobsOfRun = new Map();
40
+ constructor(ledger) {
41
+ this.ledger = ledger;
42
+ for (const p of ledger.list(KIND.push))
43
+ this.indexPush(p);
44
+ for (const j of ledger.list(KIND.job))
45
+ this.indexJob(j);
46
+ for (const r of ledger.list(KIND.run))
47
+ this.runEvent.set(runIdKey(r.repo, r.runId), r.event);
48
+ }
49
+ indexPush(p) {
50
+ const branch = branchOfRef(p.ref);
51
+ if (branch === null || p.before === "")
52
+ return;
53
+ const key = headKey(p.repo, branch, p.before);
54
+ const list = this.pushesFrom.get(key) ?? [];
55
+ if (!list.some((x) => x.pushId === p.pushId))
56
+ list.push(p);
57
+ this.pushesFrom.set(key, list);
58
+ }
59
+ indexJob(j) {
60
+ if (j.headBranch !== null) {
61
+ const key = headKey(j.repo, j.headBranch, j.headSha);
62
+ const set = this.jobsAt.get(key) ?? new Set();
63
+ set.add(j.jobId);
64
+ this.jobsAt.set(key, set);
65
+ }
66
+ const rk = runIdKey(j.repo, j.runId);
67
+ const ofRun = this.jobsOfRun.get(rk) ?? new Set();
68
+ ofRun.add(j.jobId);
69
+ this.jobsOfRun.set(rk, ofRun);
70
+ }
71
+ read(kind, id) {
72
+ const p = this.pending.get(`${kind}\u0000${id}`);
73
+ return p ? p.body : this.ledger.get(kind, id);
74
+ }
75
+ /** A record as it will be after this batch: the pending one, else the ledger's. */
76
+ peek(kind, id) {
77
+ return this.read(kind, id);
78
+ }
79
+ /** The ledger's records of a kind with this batch's pending ones laid over them. */
80
+ list(kind, idOf) {
81
+ const out = new Map();
82
+ for (const b of this.ledger.list(kind))
83
+ out.set(idOf(b), b);
84
+ for (const p of this.pending.values())
85
+ if (p.kind === kind)
86
+ out.set(p.id, p.body);
87
+ return [...out.values()];
88
+ }
89
+ /** Put a record that is not derived from an observation into the batch. */
90
+ put(kind, id, body) {
91
+ this.write(kind, id, body);
92
+ }
93
+ write(kind, id, body) {
94
+ this.pending.set(`${kind}\u0000${id}`, { kind, id, body });
95
+ }
96
+ replacement(job) {
97
+ if (job.headBranch === null)
98
+ return null;
99
+ return replacementFor(job, this.pushesFrom.get(headKey(job.repo, job.headBranch, job.headSha)) ?? []);
100
+ }
101
+ reduce(o) {
102
+ switch (o.type) {
103
+ case "workflow_job":
104
+ return this.reduceJob(o.repo, o.job);
105
+ case "workflow_run":
106
+ return this.reduceRun(o.repo, o.run);
107
+ case "check_run":
108
+ return this.reduceCheckRun(o.repo, o.checkRun);
109
+ case "pull_request":
110
+ return this.reducePullRequest(o.repo, o.pr);
111
+ case "push":
112
+ return this.reducePush(o.repo, o.push);
113
+ case "runner_pool": {
114
+ const body = { org: o.org, sampledAt: o.sample.sampledAt, total: o.sample.total, pools: o.sample.pools };
115
+ return this.write(KIND.runnerSample, runnerSampleKey(o.org, o.sample.sampledAt), body);
116
+ }
117
+ }
118
+ }
119
+ reduceJob(repo, j) {
120
+ const id = jobKey(repo, j.id);
121
+ const old = this.read(KIND.job, id);
122
+ if (old && statusRank(j.status) < statusRank(old.status))
123
+ return;
124
+ const sameState = old !== undefined && old.status === j.status;
125
+ const labels = j.labels.length > 0 ? j.labels : (old?.labels ?? []);
126
+ const runnerGroup = j.runnerGroup ?? old?.runnerGroup ?? null;
127
+ const next = {
128
+ repo,
129
+ jobId: j.id,
130
+ runId: j.runId,
131
+ runAttempt: j.runAttempt,
132
+ workflow: j.workflow !== "" ? j.workflow : (old?.workflow ?? ""),
133
+ name: j.name,
134
+ event: this.runEvent.get(runIdKey(repo, j.runId)) ?? old?.event ?? null,
135
+ headBranch: j.headBranch ?? old?.headBranch ?? null,
136
+ headSha: j.headSha,
137
+ status: j.status,
138
+ conclusion: j.conclusion ?? (sameState ? old.conclusion : null),
139
+ // The queue time is fixed by the first observation: GitHub never changes created_at.
140
+ queuedAt: old?.queuedAt ?? j.createdAt,
141
+ startedAt: j.startedAt ?? old?.startedAt ?? null,
142
+ finishedAt: j.completedAt ?? (sameState ? old.finishedAt : null),
143
+ labels,
144
+ pool: poolOf(labels, runnerGroup),
145
+ runnerName: j.runnerName ?? old?.runnerName ?? null,
146
+ runnerGroup,
147
+ replaced: null,
148
+ };
149
+ next.replaced = this.replacement(next);
150
+ this.indexJob(next);
151
+ this.write(KIND.job, id, next);
152
+ }
153
+ reduceRun(repo, r) {
154
+ const id = runKey(repo, r.id, r.attempt);
155
+ const old = this.read(KIND.run, id);
156
+ this.runEvent.set(runIdKey(repo, r.id), r.event);
157
+ // Jobs recorded before their run learn the trigger now.
158
+ for (const jobId of this.jobsOfRun.get(runIdKey(repo, r.id)) ?? []) {
159
+ const job = this.read(KIND.job, jobKey(repo, jobId));
160
+ if (job && job.event !== r.event)
161
+ this.write(KIND.job, jobKey(repo, jobId), { ...job, event: r.event });
162
+ }
163
+ if (old && statusRank(r.status) < statusRank(old.status)) {
164
+ if (r.jobsFinal === true && !old.jobsFinal)
165
+ this.write(KIND.run, id, { ...old, jobsFinal: true });
166
+ return;
167
+ }
168
+ const sameState = old !== undefined && old.status === r.status;
169
+ const next = {
170
+ repo,
171
+ runId: r.id,
172
+ attempt: r.attempt,
173
+ name: r.name,
174
+ event: r.event,
175
+ status: r.status,
176
+ conclusion: r.conclusion ?? (sameState ? old.conclusion : null),
177
+ headBranch: r.headBranch ?? old?.headBranch ?? null,
178
+ headSha: r.headSha,
179
+ createdAt: old?.createdAt ?? r.createdAt,
180
+ startedAt: r.startedAt ?? old?.startedAt ?? null,
181
+ // updatedAt only moves forward, so a stale page cannot wind it back.
182
+ updatedAt: later(old?.updatedAt ?? null, r.updatedAt),
183
+ prNumbers: r.prNumbers.length > 0 ? [...r.prNumbers].sort((a, b) => a - b) : (old?.prNumbers ?? []),
184
+ jobsFinal: r.jobsFinal === true || old?.jobsFinal === true,
185
+ };
186
+ this.write(KIND.run, id, next);
187
+ }
188
+ reduceCheckRun(repo, c) {
189
+ const id = checkRunKey(repo, c.id);
190
+ const old = this.read(KIND.checkRun, id);
191
+ if (old && statusRank(c.status) < statusRank(old.status))
192
+ return;
193
+ const sameState = old !== undefined && old.status === c.status;
194
+ const next = {
195
+ repo,
196
+ checkRunId: c.id,
197
+ name: c.name,
198
+ headSha: c.headSha,
199
+ status: c.status,
200
+ conclusion: c.conclusion ?? (sameState ? old.conclusion : null),
201
+ startedAt: c.startedAt ?? old?.startedAt ?? null,
202
+ completedAt: c.completedAt ?? (sameState ? old.completedAt : null),
203
+ app: c.app ?? old?.app ?? null,
204
+ };
205
+ this.write(KIND.checkRun, id, next);
206
+ }
207
+ reducePullRequest(repo, p) {
208
+ const id = pullRequestKey(repo, p.number);
209
+ const old = this.read(KIND.pullRequest, id);
210
+ if (old && Date.parse(p.updatedAt) < Date.parse(old.updatedAt))
211
+ return;
212
+ const next = {
213
+ repo,
214
+ number: p.number,
215
+ title: p.title,
216
+ state: p.state,
217
+ draft: p.draft,
218
+ createdAt: p.createdAt,
219
+ updatedAt: p.updatedAt,
220
+ closedAt: p.closedAt,
221
+ mergedAt: p.mergedAt,
222
+ mergeCommitSha: p.mergeCommitSha,
223
+ headSha: p.headSha,
224
+ headRef: p.headRef,
225
+ baseRef: p.baseRef,
226
+ labels: [...p.labels].sort(),
227
+ };
228
+ this.write(KIND.pullRequest, id, next);
229
+ }
230
+ reducePush(repo, p) {
231
+ const body = { repo, pushId: p.id, ref: p.ref, before: p.before, after: p.after, at: p.at, activityType: p.activityType };
232
+ this.write(KIND.push, pushKey(repo, p.id), body);
233
+ this.indexPush(body);
234
+ const branch = branchOfRef(p.ref);
235
+ if (branch === null || p.before === "")
236
+ return;
237
+ // Jobs already recorded on the head this push replaced are judged again.
238
+ for (const jobId of this.jobsAt.get(headKey(repo, branch, p.before)) ?? []) {
239
+ const job = this.read(KIND.job, jobKey(repo, jobId));
240
+ if (!job)
241
+ continue;
242
+ const replaced = this.replacement(job);
243
+ if (JSON.stringify(replaced) !== JSON.stringify(job.replaced))
244
+ this.write(KIND.job, jobKey(repo, jobId), { ...job, replaced });
245
+ }
246
+ }
247
+ /** The records this batch produced, and an empty batch afterwards. */
248
+ take() {
249
+ const out = [...this.pending.values()];
250
+ this.pending.clear();
251
+ return out;
252
+ }
253
+ }
254
+ function later(a, b) {
255
+ if (a === null)
256
+ return b;
257
+ if (b === null)
258
+ return a;
259
+ return Date.parse(b) >= Date.parse(a) ? b : a;
260
+ }
261
+ //# sourceMappingURL=reducer.js.map
@@ -25,6 +25,21 @@ export declare function writeHandbackKeep(home: string, vault: {
25
25
  /** Test seam: runs after the temp file is written, before the re-read that guards the rename. */
26
26
  beforeRename?: (attempt: number) => void): void;
27
27
  export declare function engineHoldFile(engineHome: string, vaultUid: string): string;
28
+ export declare function readEngineHoldKinds(engineHome: string, vaultUid: string): string[];
29
+ export declare const ENGINE_HOLD_DIRECTIONS: readonly ["delete_local", "delete_remote", "overwrite_local", "overwrite_remote", "merge", "undecided", "not_approvable"];
30
+ export interface EngineHeldLocalBody {
31
+ path: string;
32
+ direction: string;
33
+ }
34
+ export interface EngineHeldLocalBodies {
35
+ holdId?: string;
36
+ count: number;
37
+ paths: EngineHeldLocalBody[];
38
+ directions: string[];
39
+ readFailed?: true;
40
+ }
28
41
  export declare function readEngineHeldDeletes(engineHome: string, vaultUid: string, warn?: (line: string) => void): EngineHeldDeletes | "unreadable" | null;
42
+ export declare function readEngineHeldLocalBodies(engineHome: string, vaultUid: string): EngineHeldLocalBodies | null;
43
+ export declare function heldLocalBodiesHandoverLine(vaultUid: string, held: EngineHeldLocalBodies): string;
29
44
  export declare function heldDeletesHandoverLine(vaultUid: string, held: EngineHeldDeletes | "unreadable", engineHome: string, home: string): string;
30
45
  //# sourceMappingURL=engine-holds.d.ts.map