@prestyj/cli 5.35.1 → 5.36.0

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 (49) hide show
  1. package/dist/cli/command-routing.d.ts +1 -1
  2. package/dist/cli/command-routing.js +2 -1
  3. package/dist/cli/command-routing.js.map +1 -1
  4. package/dist/cli/validate.d.ts +4 -0
  5. package/dist/cli/validate.js +243 -0
  6. package/dist/cli/validate.js.map +1 -0
  7. package/dist/cli.js +3 -0
  8. package/dist/cli.js.map +1 -1
  9. package/dist/core/agent-notifications.d.ts +1 -1
  10. package/dist/core/agent-session.d.ts +2 -0
  11. package/dist/core/agent-session.js +7 -0
  12. package/dist/core/agent-session.js.map +1 -1
  13. package/dist/core/validation/backends.d.ts +20 -0
  14. package/dist/core/validation/backends.js +54 -0
  15. package/dist/core/validation/backends.js.map +1 -0
  16. package/dist/core/validation/config.d.ts +22 -0
  17. package/dist/core/validation/config.js +220 -0
  18. package/dist/core/validation/config.js.map +1 -0
  19. package/dist/core/validation/exec.d.ts +3 -0
  20. package/dist/core/validation/exec.js +17 -0
  21. package/dist/core/validation/exec.js.map +1 -0
  22. package/dist/core/validation/github-actions-backend.d.ts +35 -0
  23. package/dist/core/validation/github-actions-backend.js +181 -0
  24. package/dist/core/validation/github-actions-backend.js.map +1 -0
  25. package/dist/core/validation/local-backend.d.ts +18 -0
  26. package/dist/core/validation/local-backend.js +101 -0
  27. package/dist/core/validation/local-backend.js.map +1 -0
  28. package/dist/core/validation/service.d.ts +125 -0
  29. package/dist/core/validation/service.js +689 -0
  30. package/dist/core/validation/service.js.map +1 -0
  31. package/dist/core/validation/session-hook.d.ts +3 -0
  32. package/dist/core/validation/session-hook.js +25 -0
  33. package/dist/core/validation/session-hook.js.map +1 -0
  34. package/dist/core/validation/store.d.ts +10 -0
  35. package/dist/core/validation/store.js +48 -0
  36. package/dist/core/validation/store.js.map +1 -0
  37. package/dist/core/validation/types.d.ts +127 -0
  38. package/dist/core/validation/types.js +14 -0
  39. package/dist/core/validation/types.js.map +1 -0
  40. package/dist/tools/index.js +2 -0
  41. package/dist/tools/index.js.map +1 -1
  42. package/dist/tools/prompt-hints.js +2 -0
  43. package/dist/tools/prompt-hints.js.map +1 -1
  44. package/dist/tools/tool-tiers.js +1 -0
  45. package/dist/tools/tool-tiers.js.map +1 -1
  46. package/dist/tools/validate.d.ts +21 -0
  47. package/dist/tools/validate.js +107 -0
  48. package/dist/tools/validate.js.map +1 -0
  49. package/package.json +5 -5
@@ -0,0 +1,689 @@
1
+ // The validation orchestrator. Sessions enqueue jobs and return immediately;
2
+ // one leader process (a session host or `ezcoder validate daemon`) dispatches
3
+ // them to backends with bounded concurrency, polls them, posts commit statuses
4
+ // and records results. Every process watches the shared store and tells its
5
+ // own sessions when a job for their project changes.
6
+ import { EventEmitter } from "node:events";
7
+ import { randomBytes } from "node:crypto";
8
+ import fs from "node:fs/promises";
9
+ import os from "node:os";
10
+ import path from "node:path";
11
+ import { withFileLock } from "@prestyj/core";
12
+ import { fits, loadBackends } from "./backends.js";
13
+ import { buildStageCommand, loadProjectConfig, parseGitHubRepo } from "./config.js";
14
+ import { defaultExec } from "./exec.js";
15
+ import { JobStore, defaultValidationDir } from "./store.js";
16
+ import { isTerminal, } from "./types.js";
17
+ const ACTIVE = new Set(["queued", "waiting", "running"]);
18
+ function nowIso() {
19
+ return new Date().toISOString();
20
+ }
21
+ function newJobId() {
22
+ return `v${Date.now().toString(36)}${randomBytes(3).toString("hex")}`;
23
+ }
24
+ function pidAlive(pid) {
25
+ try {
26
+ process.kill(pid, 0);
27
+ return true;
28
+ }
29
+ catch (e) {
30
+ return e.code === "EPERM";
31
+ }
32
+ }
33
+ export function short(sha) {
34
+ return sha.slice(0, 8);
35
+ }
36
+ let shared;
37
+ export class ValidationService {
38
+ dir;
39
+ store;
40
+ exec;
41
+ pollMs;
42
+ offlineWarnMs;
43
+ backends;
44
+ maxConcurrent;
45
+ injected;
46
+ events = new EventEmitter();
47
+ seen = new Map();
48
+ seeded = false;
49
+ timer;
50
+ ticking;
51
+ keepAlive = false;
52
+ /** Backend problems found while loading the registry. */
53
+ problems = [];
54
+ /** Start the poll loop when work is queued; short-lived commands turn this off. */
55
+ autoStart;
56
+ constructor(opts = {}) {
57
+ this.dir = opts.dir ?? defaultValidationDir();
58
+ this.store = new JobStore(this.dir);
59
+ this.exec = opts.exec ?? defaultExec;
60
+ this.pollMs = opts.pollMs ?? 20_000;
61
+ this.offlineWarnMs = (opts.offlineWarnMinutes ?? 10) * 60_000;
62
+ this.injected = !!opts.backends;
63
+ this.backends = opts.backends ?? [];
64
+ this.maxConcurrent = opts.maxConcurrent ?? 4;
65
+ this.autoStart = opts.autoStart ?? true;
66
+ if (!opts.backends)
67
+ this.reloadBackends();
68
+ this.events.setMaxListeners(100);
69
+ }
70
+ /** One service per process. */
71
+ static shared() {
72
+ shared ??= new ValidationService();
73
+ return shared;
74
+ }
75
+ reloadBackends() {
76
+ if (this.injected)
77
+ return;
78
+ const loaded = loadBackends(this.dir, this.exec);
79
+ this.backends = loaded.backends;
80
+ this.maxConcurrent = loaded.maxConcurrent;
81
+ this.problems = loaded.problems;
82
+ }
83
+ getBackends() {
84
+ return this.backends;
85
+ }
86
+ backend(id) {
87
+ return this.backends.find((b) => b.id === id);
88
+ }
89
+ // ── events ───────────────────────────────────────────────
90
+ onJob(listener) {
91
+ this.events.on("job", listener);
92
+ return () => this.events.off("job", listener);
93
+ }
94
+ observe(jobs) {
95
+ const changed = [];
96
+ for (const job of jobs) {
97
+ const prev = this.seen.get(job.id);
98
+ const key = `${job.state}|${job.offlineWarned ? 1 : 0}`;
99
+ if (prev === key)
100
+ continue;
101
+ this.seen.set(job.id, key);
102
+ // First look after start: only report finished jobs nobody was told about.
103
+ if (!this.seeded && (!isTerminal(job.state) || job.notifiedState === job.state))
104
+ continue;
105
+ changed.push(job);
106
+ this.events.emit("job", job, prev ? prev.split("|")[0] : undefined);
107
+ }
108
+ this.seeded = true;
109
+ return changed;
110
+ }
111
+ // ── git ──────────────────────────────────────────────────
112
+ async git(cwd, args) {
113
+ const r = await this.exec("git", args, { cwd, timeoutMs: 15_000 });
114
+ return r.code === 0 ? r.stdout.trim() : undefined;
115
+ }
116
+ async gitState(cwd, ref) {
117
+ const sha = await this.git(cwd, ["rev-parse", "--verify", `${ref}^{commit}`]);
118
+ const branchRaw = await this.git(cwd, ["rev-parse", "--abbrev-ref", "HEAD"]);
119
+ const status = await this.git(cwd, ["status", "--porcelain", "--untracked-files=no"]);
120
+ const origin = await this.git(cwd, ["remote", "get-url", "origin"]);
121
+ return {
122
+ sha,
123
+ branch: ref === "HEAD" && branchRaw && branchRaw !== "HEAD" ? branchRaw : undefined,
124
+ dirty: ref === "HEAD" && !!status,
125
+ originRepo: origin ? parseGitHubRepo(origin) : undefined,
126
+ };
127
+ }
128
+ // ── public API ───────────────────────────────────────────
129
+ config(cwd) {
130
+ return loadProjectConfig(cwd);
131
+ }
132
+ async enqueue(cwdIn, opts = {}) {
133
+ const cwd = path.resolve(cwdIn);
134
+ const config = loadProjectConfig(cwd);
135
+ if ("error" in config)
136
+ throw new Error(config.error);
137
+ const ref = opts.ref ?? "HEAD";
138
+ const g = await this.gitState(cwd, ref);
139
+ if (!g.sha)
140
+ throw new Error(`"${ref}" is not a commit in ${cwd} (is this a Git repo with commits?)`);
141
+ const sha = g.sha;
142
+ const repo = config.repo ?? g.originRepo;
143
+ let stages = config.stages;
144
+ if (opts.stages?.length) {
145
+ const unknown = opts.stages.filter((s) => !stages.some((x) => x.name === s));
146
+ if (unknown.length) {
147
+ throw new Error(`unknown stage(s) ${unknown.join(", ")}; this project has: ${stages.map((s) => s.name).join(", ") || "none"}`);
148
+ }
149
+ stages = stages.filter((s) => opts.stages.includes(s.name));
150
+ }
151
+ if (stages.length === 0)
152
+ throw new Error(`no validation stages. ${config.notes.join(" ")}`);
153
+ const messages = [];
154
+ const hasRemote = this.backends.some((b) => b.runs === "remote");
155
+ if (g.dirty && stages.some((s) => s.run === "remote")) {
156
+ messages.push(`Uncommitted changes are not included in remote stages; they test commit ${short(sha)}. Commit first to test them.`);
157
+ }
158
+ const created = [];
159
+ const reused = [];
160
+ await this.store.update((jobs) => {
161
+ for (const stage of stages) {
162
+ let backend = stage.run === "local" ? "local" : (stage.backend ?? "");
163
+ let command = buildStageCommand(stage);
164
+ if (stage.run === "remote" && !stage.backend && (!repo || !hasRemote)) {
165
+ backend = "local";
166
+ command = stage.setup ? `${stage.setup} && ${stage.command}` : stage.command;
167
+ messages.push(`${stage.name}: ${!repo ? "not a GitHub repo" : "no remote worker configured"}, so it runs on this machine.`);
168
+ }
169
+ if (backend && !this.backend(backend)) {
170
+ throw new Error(`stage ${stage.name} names backend "${backend}", which isn't configured`);
171
+ }
172
+ const isLocal = backend === "local";
173
+ const same = jobs
174
+ .filter((j) => j.project === cwd && j.sha === sha && j.stage === stage.name && j.command === command)
175
+ .at(-1);
176
+ if (same &&
177
+ !opts.force &&
178
+ (ACTIVE.has(same.state) ||
179
+ (same.state === "passed" && !same.dirty && !(isLocal && g.dirty)))) {
180
+ reused.push(same);
181
+ continue;
182
+ }
183
+ const at = nowIso();
184
+ const job = {
185
+ id: newJobId(),
186
+ project: cwd,
187
+ ...(repo ? { repo } : {}),
188
+ sha,
189
+ ...(g.branch ? { branch: g.branch } : {}),
190
+ stage: stage.name,
191
+ run: isLocal ? "local" : "remote",
192
+ required: stage.required,
193
+ command,
194
+ timeoutMinutes: stage.timeoutMinutes,
195
+ backend,
196
+ ...(stage.resources ? { resources: stage.resources } : {}),
197
+ ...(config.postCommitStatus && repo && !isLocal
198
+ ? { statusContext: `${config.statusContextPrefix}/${stage.name}` }
199
+ : {}),
200
+ state: "queued",
201
+ createdAt: at,
202
+ updatedAt: at,
203
+ ...(isLocal && g.dirty ? { dirty: true } : {}),
204
+ };
205
+ // A newer commit on the same branch makes older pending runs pointless.
206
+ if (g.branch) {
207
+ for (const old of jobs) {
208
+ if (old.project === cwd &&
209
+ old.branch === g.branch &&
210
+ old.stage === stage.name &&
211
+ old.sha !== sha &&
212
+ ACTIVE.has(old.state) &&
213
+ (old.state === "queued" || config.cancelSuperseded)) {
214
+ old.state = "superseded";
215
+ old.supersededBy = job.id;
216
+ old.summary = `superseded by ${short(sha)}`;
217
+ old.updatedAt = at;
218
+ old.finishedAt = at;
219
+ messages.push(`${old.stage} for ${short(old.sha)} superseded.`);
220
+ }
221
+ }
222
+ }
223
+ jobs.push(job);
224
+ created.push(job);
225
+ }
226
+ });
227
+ if (created.length && this.autoStart)
228
+ this.start();
229
+ return { sha, branch: g.branch, dirty: g.dirty, jobs: created, reused, messages };
230
+ }
231
+ async list(cwd) {
232
+ const jobs = await this.store.read();
233
+ return cwd ? jobs.filter((j) => j.project === path.resolve(cwd)) : jobs;
234
+ }
235
+ async get(id) {
236
+ return (await this.store.read()).find((j) => j.id === id);
237
+ }
238
+ /** Required stages for an exact commit: ok only when every one passed at that SHA. */
239
+ async gate(cwdIn, ref = "HEAD") {
240
+ const cwd = path.resolve(cwdIn);
241
+ const config = loadProjectConfig(cwd);
242
+ if ("error" in config)
243
+ throw new Error(config.error);
244
+ const sha = await this.git(cwd, ["rev-parse", "--verify", `${ref}^{commit}`]);
245
+ if (!sha)
246
+ throw new Error(`"${ref}" is not a commit`);
247
+ const jobs = (await this.store.read()).filter((j) => j.project === cwd && j.sha === sha && j.state !== "superseded");
248
+ const rows = config.stages
249
+ .filter((s) => s.required)
250
+ .map((s) => {
251
+ const mine = jobs.filter((j) => j.stage === s.name);
252
+ const job = [...mine].reverse().find((j) => j.state === "passed" && !j.dirty) ?? mine.at(-1);
253
+ if (!job)
254
+ return { stage: s.name, state: "missing" };
255
+ const note = job.dirty ? "ran on uncommitted changes; doesn't count" : job.summary;
256
+ return {
257
+ stage: s.name,
258
+ state: job.state,
259
+ jobId: job.id,
260
+ url: job.url,
261
+ ...(note ? { note } : {}),
262
+ };
263
+ });
264
+ const ok = rows.every((r) => r.state === "passed" && !r.note?.includes("doesn't count"));
265
+ return { sha, ok, rows };
266
+ }
267
+ async cancel(id) {
268
+ const job = await this.store.update((jobs) => {
269
+ const j = jobs.find((x) => x.id === id);
270
+ if (!j || isTerminal(j.state))
271
+ return j;
272
+ j.state = "cancelled";
273
+ j.summary = "cancelled by request";
274
+ j.updatedAt = j.finishedAt = nowIso();
275
+ return { ...j };
276
+ });
277
+ if (job?.runId)
278
+ await this.backend(job.backend)
279
+ ?.cancel(job)
280
+ .catch(() => { });
281
+ if (job?.statusContext && job.dispatchedAt)
282
+ await this.postStatus(job, "error", "cancelled");
283
+ return job;
284
+ }
285
+ /** Run a finished job again at the same commit. */
286
+ async retry(id) {
287
+ const created = await this.store.update((jobs) => {
288
+ const j = jobs.find((x) => x.id === id);
289
+ if (!j)
290
+ throw new Error(`no job ${id}`);
291
+ if (!isTerminal(j.state))
292
+ throw new Error(`job ${id} is still ${j.state}`);
293
+ const at = nowIso();
294
+ const copy = {
295
+ id: newJobId(),
296
+ project: j.project,
297
+ ...(j.repo ? { repo: j.repo } : {}),
298
+ sha: j.sha,
299
+ ...(j.branch ? { branch: j.branch } : {}),
300
+ stage: j.stage,
301
+ run: j.run,
302
+ required: j.required,
303
+ command: j.command,
304
+ timeoutMinutes: j.timeoutMinutes,
305
+ backend: j.run === "local" ? "local" : "",
306
+ ...(j.resources ? { resources: j.resources } : {}),
307
+ ...(j.statusContext ? { statusContext: j.statusContext } : {}),
308
+ ...(j.dirty ? { dirty: true } : {}),
309
+ state: "queued",
310
+ createdAt: at,
311
+ updatedAt: at,
312
+ retryOf: j.id,
313
+ };
314
+ jobs.push(copy);
315
+ return copy;
316
+ });
317
+ if (this.autoStart)
318
+ this.start();
319
+ return created;
320
+ }
321
+ async logs(id, failedOnly = true) {
322
+ const job = await this.get(id);
323
+ if (!job)
324
+ return `No job ${id}.`;
325
+ const b = this.backend(job.backend);
326
+ if (!b)
327
+ return job.backend
328
+ ? `Backend ${job.backend} is no longer configured.`
329
+ : "Not dispatched yet.";
330
+ return b.logs(job, failedOnly && job.state === "failed");
331
+ }
332
+ async workers() {
333
+ const jobs = await this.store.read();
334
+ const dayAgo = Date.now() - 86_400_000;
335
+ return Promise.all(this.backends.map(async (b) => ({
336
+ id: b.id,
337
+ kind: b.kind,
338
+ maxConcurrent: b.maxConcurrent,
339
+ active: jobs.filter((j) => j.backend === b.id && (j.state === "waiting" || j.state === "running")).length,
340
+ queued: jobs.filter((j) => j.state === "queued" && (j.backend === b.id || (!j.backend && b.runs === "remote"))).length,
341
+ health: await b.health().catch((e) => ({
342
+ online: false,
343
+ detail: e instanceof Error ? e.message : String(e),
344
+ })),
345
+ recentFailures: jobs.filter((j) => j.backend === b.id && j.state === "error" && Date.parse(j.updatedAt) > dayAgo).length,
346
+ })));
347
+ }
348
+ // ── scheduling loop ──────────────────────────────────────
349
+ /** Start (or keep) the poll loop. Cheap when idle: it stops itself. */
350
+ start(opts = {}) {
351
+ if (opts.keepAlive)
352
+ this.keepAlive = true;
353
+ if (this.timer)
354
+ return;
355
+ const loop = () => {
356
+ this.timer = setTimeout(async () => {
357
+ await this.tick().catch(() => { });
358
+ if (this.timer)
359
+ loop();
360
+ }, this.pollMs);
361
+ if (!this.keepAlive)
362
+ this.timer.unref();
363
+ };
364
+ void this.tick().catch(() => { });
365
+ loop();
366
+ }
367
+ stop() {
368
+ if (this.timer)
369
+ clearTimeout(this.timer);
370
+ this.timer = undefined;
371
+ }
372
+ get running() {
373
+ return !!this.timer;
374
+ }
375
+ /** One pass: observe, and if we lead, poll/dispatch. Returns whether work remains. */
376
+ async tick() {
377
+ if (this.ticking) {
378
+ await this.ticking;
379
+ return this.hasActive();
380
+ }
381
+ this.ticking = this.tickInner().finally(() => {
382
+ this.ticking = undefined;
383
+ });
384
+ await this.ticking;
385
+ return this.hasActive();
386
+ }
387
+ lastActive = false;
388
+ hasActive() {
389
+ return this.lastActive;
390
+ }
391
+ async tickInner() {
392
+ let jobs = await this.store.read();
393
+ this.emitAndMark(jobs);
394
+ const active = jobs.filter((j) => ACTIVE.has(j.state));
395
+ const pendingCancels = jobs.filter((j) => j.state === "superseded" && j.runId && !j.stopSent);
396
+ this.lastActive = active.length > 0;
397
+ if (!active.length && !pendingCancels.length) {
398
+ if (!this.keepAlive)
399
+ this.stop();
400
+ return;
401
+ }
402
+ if (!(await this.lead()))
403
+ return;
404
+ // Superseded jobs that were already running: stop them on the worker.
405
+ for (const j of pendingCancels) {
406
+ await this.patch(j.id, { stopSent: true }, undefined, true);
407
+ await this.backend(j.backend)
408
+ ?.cancel(j)
409
+ .catch(() => { });
410
+ await this.postStatus(j, "error", `superseded by a newer commit`);
411
+ }
412
+ // Poll what's in flight.
413
+ for (const j of active.filter((x) => x.state !== "queued")) {
414
+ const b = this.backend(j.backend);
415
+ if (!b) {
416
+ await this.patch(j.id, {
417
+ state: "error",
418
+ summary: `backend ${j.backend} is no longer configured`,
419
+ });
420
+ continue;
421
+ }
422
+ try {
423
+ const r = await b.poll(j);
424
+ const patch = {};
425
+ if (r.url && r.url !== j.url)
426
+ patch.url = r.url;
427
+ if (r.state !== j.state) {
428
+ patch.state = r.state;
429
+ if (r.summary)
430
+ patch.summary = r.summary;
431
+ if (r.state === "running")
432
+ patch.startedAt = nowIso();
433
+ if (isTerminal(r.state)) {
434
+ patch.finishedAt = nowIso();
435
+ if (j.run === "local" && !j.dirty && (await this.movedSince(j)))
436
+ patch.dirty = true;
437
+ if (r.state === "failed" && b.runs === "remote") {
438
+ patch.summary = await this.failureSummary(b, j, r.summary);
439
+ }
440
+ }
441
+ }
442
+ if ((r.state === "waiting" || j.state === "waiting") &&
443
+ !j.offlineWarned &&
444
+ j.dispatchedAt &&
445
+ Date.now() - Date.parse(j.dispatchedAt) > this.offlineWarnMs) {
446
+ const h = await b.health().catch(() => undefined);
447
+ if (h && !h.online) {
448
+ patch.offlineWarned = true;
449
+ patch.summary = `worker offline (${h.detail}); it stays queued on GitHub and runs when the worker is back`;
450
+ }
451
+ }
452
+ if (Object.keys(patch).length) {
453
+ const updated = await this.patch(j.id, patch);
454
+ if (updated && patch.state && isTerminal(patch.state) && updated.statusContext) {
455
+ await this.postFinal(updated);
456
+ }
457
+ }
458
+ }
459
+ catch (e) {
460
+ // Transient (network, rate limit): try again next tick.
461
+ void e;
462
+ }
463
+ }
464
+ // Dispatch queued jobs into free slots, oldest first.
465
+ jobs = await this.store.read();
466
+ let inFlight = jobs.filter((j) => j.state === "waiting" || j.state === "running").length;
467
+ for (const j of jobs.filter((x) => x.state === "queued")) {
468
+ if (inFlight >= this.maxConcurrent)
469
+ break;
470
+ const b = this.chooseBackend(j, jobs);
471
+ if (b === "none") {
472
+ await this.patch(j.id, {
473
+ state: "error",
474
+ summary: "no configured worker fits this stage's resources",
475
+ finishedAt: nowIso(),
476
+ });
477
+ continue;
478
+ }
479
+ if (!b)
480
+ continue; // every fitting backend is full
481
+ const claimed = await this.patch(j.id, { backend: b.id }, "queued");
482
+ if (!claimed)
483
+ continue;
484
+ try {
485
+ if (b.runs === "remote" && j.repo && !(await this.commitOnGitHub(j.repo, j.sha))) {
486
+ await this.patch(j.id, {
487
+ state: "error",
488
+ summary: `commit ${short(j.sha)} isn't on GitHub; push it, then run validation again`,
489
+ finishedAt: nowIso(),
490
+ });
491
+ continue;
492
+ }
493
+ const handle = await b.dispatch({ ...claimed, backend: b.id });
494
+ const at = nowIso();
495
+ const updated = await this.patch(j.id, { state: "waiting", dispatchedAt: at, ...handle }, "queued");
496
+ inFlight++;
497
+ j.backend = b.id;
498
+ j.state = "waiting";
499
+ if (updated?.statusContext)
500
+ await this.postStatus(updated, "pending", `running on ${b.id}`);
501
+ }
502
+ catch (e) {
503
+ await this.patch(j.id, {
504
+ state: "error",
505
+ summary: `dispatch to ${b.id} failed: ${e instanceof Error ? e.message : String(e)}`.slice(0, 400),
506
+ finishedAt: nowIso(),
507
+ });
508
+ }
509
+ }
510
+ this.emitAndMark(await this.store.read());
511
+ }
512
+ chooseBackend(job, jobs) {
513
+ const load = (b) => jobs.filter((j) => j.backend === b.id && (j.state === "waiting" || j.state === "running"))
514
+ .length;
515
+ let candidates;
516
+ if (job.backend) {
517
+ const b = this.backend(job.backend);
518
+ if (!b)
519
+ return "none";
520
+ candidates = [b];
521
+ }
522
+ else {
523
+ candidates = this.backends.filter((b) => b.runs === "remote" && fits(job.resources, b.capacity));
524
+ if (!candidates.length)
525
+ return "none";
526
+ }
527
+ const free = candidates
528
+ .filter((b) => load(b) < b.maxConcurrent)
529
+ .sort((a, b) => load(a) / a.maxConcurrent - load(b) / b.maxConcurrent);
530
+ return free[0];
531
+ }
532
+ async movedSince(job) {
533
+ const head = await this.git(job.project, ["rev-parse", "HEAD"]);
534
+ const status = await this.git(job.project, ["status", "--porcelain", "--untracked-files=no"]);
535
+ return head !== job.sha || !!status;
536
+ }
537
+ async failureSummary(b, j, base) {
538
+ const log = await b.logs(j, true).catch(() => "");
539
+ const lines = log
540
+ .split("\n")
541
+ .map((l) => l.trim())
542
+ .filter(Boolean)
543
+ .filter((l) => /fail|error|expected|assert|✗|×/i.test(l))
544
+ .slice(-4);
545
+ return [base ?? "failed", ...lines].join(" | ").slice(0, 480);
546
+ }
547
+ async commitOnGitHub(repo, sha) {
548
+ const r = await this.exec("gh", ["api", `repos/${repo}/commits/${sha}`, "--jq", ".sha"], {
549
+ timeoutMs: 30_000,
550
+ });
551
+ if (r.code === 0)
552
+ return true;
553
+ // Only a clear "not found" blocks; on network trouble let the worker decide.
554
+ return !/HTTP 4(04|22)|No commit found/i.test(r.stderr + r.stdout);
555
+ }
556
+ async postFinal(job) {
557
+ const state = job.state === "passed" ? "success" : job.state === "failed" ? "failure" : "error";
558
+ await this.postStatus(job, state, (job.summary ?? job.state).slice(0, 130));
559
+ }
560
+ async postStatus(job, state, description) {
561
+ if (!job.repo || !job.statusContext)
562
+ return;
563
+ const args = [
564
+ "api",
565
+ "-X",
566
+ "POST",
567
+ `repos/${job.repo}/statuses/${job.sha}`,
568
+ "-f",
569
+ `state=${state}`,
570
+ "-f",
571
+ `context=${job.statusContext}`,
572
+ "-f",
573
+ `description=${description.slice(0, 139)}`,
574
+ ...(job.url?.startsWith("http") ? ["-f", `target_url=${job.url}`] : []),
575
+ ];
576
+ const r = await this.exec("gh", args, { timeoutMs: 30_000 });
577
+ await this.patch(job.id, { postedStatus: r.code === 0 ? state : `failed:${state}` }, undefined, true);
578
+ }
579
+ /** Merge a patch into one stored job. With `onlyIf`, only when it's still in that state. */
580
+ async patch(id, patch, onlyIf, evenIfTerminal = false) {
581
+ return this.store.update((jobs) => {
582
+ const j = jobs.find((x) => x.id === id);
583
+ if (!j)
584
+ return undefined;
585
+ if (onlyIf && j.state !== onlyIf)
586
+ return undefined;
587
+ // Never resurrect a job someone cancelled or superseded meanwhile.
588
+ if (!evenIfTerminal && isTerminal(j.state) && patch.state && !isTerminal(patch.state))
589
+ return undefined;
590
+ if (!evenIfTerminal && (j.state === "cancelled" || j.state === "superseded") && patch.state) {
591
+ return undefined;
592
+ }
593
+ Object.assign(j, patch, { updatedAt: nowIso() });
594
+ return { ...j };
595
+ });
596
+ }
597
+ emitAndMark(jobs) {
598
+ const changed = this.observe(jobs);
599
+ const done = changed.filter((j) => isTerminal(j.state) && j.notifiedState !== j.state);
600
+ if (done.length && this.events.listenerCount("job") > 0) {
601
+ void this.store
602
+ .update((all) => {
603
+ for (const d of done) {
604
+ const j = all.find((x) => x.id === d.id);
605
+ if (j)
606
+ j.notifiedState = d.state;
607
+ }
608
+ })
609
+ .catch(() => { });
610
+ }
611
+ }
612
+ // ── leadership ───────────────────────────────────────────
613
+ async lead() {
614
+ const file = path.join(this.dir, "leader.json");
615
+ const staleMs = Math.max(90_000, this.pollMs * 4);
616
+ await fs.mkdir(this.dir, { recursive: true });
617
+ return withFileLock(file, async () => {
618
+ try {
619
+ const cur = JSON.parse(await fs.readFile(file, "utf8"));
620
+ const mine = cur.pid === process.pid && cur.host === os.hostname();
621
+ const live = cur.host === os.hostname() ? pidAlive(cur.pid) : true;
622
+ if (!mine && live && Date.now() - cur.at < staleMs)
623
+ return false;
624
+ }
625
+ catch {
626
+ // no leader yet
627
+ }
628
+ await fs.writeFile(file, JSON.stringify({ pid: process.pid, host: os.hostname(), at: Date.now() }));
629
+ return true;
630
+ });
631
+ }
632
+ /** Is some live process leading? (Used to decide whether to start a daemon.) */
633
+ async leaderAlive() {
634
+ try {
635
+ const cur = JSON.parse(await fs.readFile(path.join(this.dir, "leader.json"), "utf8"));
636
+ return (cur.host === os.hostname() &&
637
+ pidAlive(cur.pid) &&
638
+ Date.now() - cur.at < Math.max(90_000, this.pollMs * 4));
639
+ }
640
+ catch {
641
+ return false;
642
+ }
643
+ }
644
+ }
645
+ /** Plain-words one-liner for a job, used by notifications, the tool and the CLI. */
646
+ export function describeJob(j) {
647
+ const where = j.backend ? ` on ${j.backend}` : "";
648
+ const extra = j.summary ? ` — ${j.summary}` : "";
649
+ const dirty = j.dirty ? " (uncommitted changes; advisory only)" : "";
650
+ return `${j.id} ${j.stage} @ ${short(j.sha)}${where}: ${j.state}${dirty}${extra}${j.url ? ` ${j.url}` : ""}`;
651
+ }
652
+ /** The notification a session gets for a job change, or undefined for routine ones. */
653
+ export function notificationFor(j) {
654
+ const at = `${j.stage} at ${short(j.sha)}${j.backend ? ` on ${j.backend}` : ""}`;
655
+ switch (j.state) {
656
+ case "passed":
657
+ return {
658
+ text: `Validation passed: ${at}${j.dirty ? " (on uncommitted changes, advisory only)" : ""}.`,
659
+ terminal: true,
660
+ urgent: false,
661
+ };
662
+ case "failed":
663
+ return {
664
+ text: `Validation FAILED: ${at}${j.summary ? `: ${j.summary}` : ""}. ` +
665
+ `Read the log with validate logs ${j.id}, fix the cause, commit, then validate run again ` +
666
+ `(the new commit supersedes this one).`,
667
+ terminal: true,
668
+ urgent: true,
669
+ };
670
+ case "error":
671
+ return {
672
+ text: `Validation could not run (not a code failure): ${at}: ${j.summary ?? "unknown error"}. ` +
673
+ `Tell the user if it needs them; retry with validate retry ${j.id}.`,
674
+ terminal: true,
675
+ urgent: true,
676
+ };
677
+ case "waiting":
678
+ return j.offlineWarned
679
+ ? {
680
+ text: `Validation waiting: ${at}: ${j.summary}. Not retrying; tell the user.`,
681
+ terminal: false,
682
+ urgent: true,
683
+ }
684
+ : undefined;
685
+ default:
686
+ return undefined;
687
+ }
688
+ }
689
+ //# sourceMappingURL=service.js.map