create-interview-cockpit 0.18.0 → 0.19.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.
@@ -17,8 +17,51 @@ interface GithubActionsLabWorkspace {
17
17
 
18
18
  type OutputKind = "stdout" | "stderr" | "info";
19
19
 
20
+ // Status a job can be in across the lifecycle of one act run.
21
+ // `pending` — declared in the workflow YAML but not yet started
22
+ // `running` — act has emitted its first line for this job
23
+ // `success` — act printed "Job succeeded" (or run finished cleanly while job was running)
24
+ // `failed` — act printed "Job failed" (or run finished non-zero while job was running)
25
+ // `skipped` — act printed a skip line
26
+ export type GhaJobStatus =
27
+ | "pending"
28
+ | "running"
29
+ | "success"
30
+ | "failed"
31
+ | "skipped";
32
+
33
+ export interface GhaStepSnapshot {
34
+ // Step name as printed by act (e.g. "Checkout repo").
35
+ name: string;
36
+ // "Main" for normal steps, "Pre"/"Post" for action lifecycle hooks.
37
+ phase: "Main" | "Pre" | "Post";
38
+ status: GhaJobStatus;
39
+ startedAt?: string;
40
+ endedAt?: string;
41
+ durationMs?: number;
42
+ // Captured raw lines that appeared between this step's start and its
43
+ // terminal marker. Capped per-step so a runaway step can't bloat the
44
+ // metadata file.
45
+ log?: string;
46
+ }
47
+
48
+ export interface GhaJobSnapshot {
49
+ // Job key as `act` prints it inside the [workflow/job] prefix.
50
+ // For matrix jobs this includes the matrix instance suffix.
51
+ name: string;
52
+ // Workflow display name from the prefix (left of the slash).
53
+ workflow?: string;
54
+ status: GhaJobStatus;
55
+ startedAt?: string;
56
+ endedAt?: string;
57
+ durationMs?: number;
58
+ // Per-step lifecycle parsed from act's `⭐ Run` / `✅ Success` markers.
59
+ steps?: GhaStepSnapshot[];
60
+ }
61
+
20
62
  export type GhaStreamMessage =
21
63
  | { type: "output"; kind: OutputKind; text: string }
64
+ | { type: "job"; job: GhaJobSnapshot }
22
65
  | { type: "complete"; runId: string; exitCode: number; durationMs: number }
23
66
  | { type: "error"; error: string };
24
67
 
@@ -362,6 +405,273 @@ export interface GhaRunMetadata {
362
405
  durationMs: number;
363
406
  exitCode: number;
364
407
  error?: string;
408
+ // Parsed live from act's stdout; lets the UI render a job DAG with
409
+ // pending/running/success/failed boxes instead of just raw text.
410
+ jobs?: GhaJobSnapshot[];
411
+ // Captured for the History tab so users can group runs by workflow.
412
+ event?: string;
413
+ workflow?: string;
414
+ }
415
+
416
+ // ─── act output → job snapshot parser ───────────────────────────────────
417
+ //
418
+ // act prints every line for a given job with a `[<workflow>/<job>]` prefix,
419
+ // e.g.:
420
+ // [CI/greet ] 🚀 Start image=catthehacker/ubuntu:act-latest
421
+ // [CI/greet ] ✅ Success - Set up job
422
+ // [CI/greet ] 🏁 Job succeeded
423
+ // [CI/build-1 ] 🏁 Job failed
424
+ // We watch for the first line per job (→ running), and the "Job succeeded /
425
+ // Job failed / Job skipped" markers. Anything still running when act exits
426
+ // is finalised based on the process exit code.
427
+ const JOB_PREFIX_RE = /^\[([^\]/]+)\/([^\]]+)\]\s*(.*)$/;
428
+ // act prints `⭐ Run Main <step name>` to mark a step boundary. The emoji is
429
+ // optional in some act versions / when colour is stripped, so the regex
430
+ // tolerates either form.
431
+ const STEP_START_RE = /(?:⭐\s*)?Run\s+(Main|Pre|Post)\s+(.+?)\s*$/;
432
+ // And one of these for the terminal marker:
433
+ // ✅ Success - Main <name>
434
+ // ❌ Failure - Main <name>
435
+ // ⏭ Skipped - Main <name> (also ⚠)
436
+ const STEP_END_RE =
437
+ /(?:[✅❌⏭⚠]\s*)?(Success|Failure|Skipped)\s*-\s*(Main|Pre|Post)\s+(.+?)\s*$/;
438
+ const MAX_STEP_LOG_CHARS = 8_000;
439
+
440
+ class JobTracker {
441
+ private readonly jobs = new Map<string, GhaJobSnapshot>();
442
+ private leftover = "";
443
+
444
+ constructor(private readonly onUpdate: (job: GhaJobSnapshot) => void) {}
445
+
446
+ feed(text: string): void {
447
+ const combined = this.leftover + text;
448
+ const lines = combined.split(/\r?\n/);
449
+ this.leftover = lines.pop() ?? "";
450
+ for (const line of lines) this.processLine(line);
451
+ }
452
+
453
+ flush(): void {
454
+ if (this.leftover) {
455
+ this.processLine(this.leftover);
456
+ this.leftover = "";
457
+ }
458
+ }
459
+
460
+ finalize(exitCode: number): void {
461
+ const fallback: GhaJobStatus = exitCode === 0 ? "success" : "failed";
462
+ const endedAt = new Date().toISOString();
463
+ for (const job of this.jobs.values()) {
464
+ // Close any still-open step first so the UI doesn't show a stuck
465
+ // "running" spinner inside a finished job.
466
+ if (job.steps) {
467
+ for (const step of job.steps) {
468
+ if (step.status === "running") {
469
+ step.status = fallback;
470
+ step.endedAt = endedAt;
471
+ if (step.startedAt) {
472
+ step.durationMs =
473
+ new Date(endedAt).getTime() -
474
+ new Date(step.startedAt).getTime();
475
+ }
476
+ }
477
+ }
478
+ }
479
+ if (job.status === "running") {
480
+ job.status = fallback;
481
+ job.endedAt = endedAt;
482
+ if (job.startedAt) {
483
+ job.durationMs =
484
+ new Date(endedAt).getTime() - new Date(job.startedAt).getTime();
485
+ }
486
+ this.onUpdate({ ...job });
487
+ }
488
+ }
489
+ }
490
+
491
+ snapshot(): GhaJobSnapshot[] {
492
+ return Array.from(this.jobs.values()).map((job) => ({
493
+ ...job,
494
+ steps: job.steps?.map((s) => ({ ...s })),
495
+ }));
496
+ }
497
+
498
+ private processLine(line: string): void {
499
+ const match = JOB_PREFIX_RE.exec(line);
500
+ if (!match) return;
501
+ const workflow = match[1].trim();
502
+ const jobName = match[2].trim();
503
+ const rest = match[3] ?? "";
504
+ if (!jobName) return;
505
+
506
+ const existing = this.jobs.get(jobName);
507
+ const now = new Date().toISOString();
508
+ const job: GhaJobSnapshot = existing
509
+ ? { ...existing, steps: existing.steps ? [...existing.steps] : [] }
510
+ : {
511
+ name: jobName,
512
+ workflow,
513
+ status: "running",
514
+ startedAt: now,
515
+ steps: [],
516
+ };
517
+
518
+ let touched = !existing; // first sighting always counts as an update
519
+
520
+ // ── Step boundaries ──
521
+ const stepStart = STEP_START_RE.exec(rest);
522
+ const stepEnd = STEP_END_RE.exec(rest);
523
+ if (stepEnd) {
524
+ const phase = stepEnd[2] as "Main" | "Pre" | "Post";
525
+ const name = stepEnd[3];
526
+ const status: GhaJobStatus =
527
+ stepEnd[1] === "Success"
528
+ ? "success"
529
+ : stepEnd[1] === "Failure"
530
+ ? "failed"
531
+ : "skipped";
532
+ const step =
533
+ job.steps?.find((s) => s.phase === phase && s.name === name) ?? null;
534
+ if (step) {
535
+ step.status = status;
536
+ step.endedAt = now;
537
+ if (step.startedAt) {
538
+ step.durationMs =
539
+ new Date(now).getTime() - new Date(step.startedAt).getTime();
540
+ }
541
+ } else {
542
+ // End without a matching start (act sometimes elides start lines
543
+ // for fast steps). Synthesize a zero-duration entry so the UI
544
+ // still shows the step.
545
+ job.steps?.push({ name, phase, status, endedAt: now });
546
+ }
547
+ touched = true;
548
+ } else if (stepStart) {
549
+ const phase = stepStart[1] as "Main" | "Pre" | "Post";
550
+ const name = stepStart[2];
551
+ // De-dupe: if a previous run already opened this same step, just
552
+ // restart it (matrix jobs share the parser instance per name).
553
+ const existingStep = job.steps?.find(
554
+ (s) => s.phase === phase && s.name === name && s.status === "running",
555
+ );
556
+ if (!existingStep) {
557
+ job.steps?.push({
558
+ name,
559
+ phase,
560
+ status: "running",
561
+ startedAt: now,
562
+ log: "",
563
+ });
564
+ }
565
+ touched = true;
566
+ } else if (job.steps && job.steps.length) {
567
+ // Non-marker content → belongs to the currently running step (if any),
568
+ // so the user can drill into the per-step log just like GitHub.
569
+ const current = [...job.steps]
570
+ .reverse()
571
+ .find((s) => s.status === "running");
572
+ if (current && rest.trim()) {
573
+ const stripped = rest.replace(/^[|\s]+/, "");
574
+ const next = `${current.log ?? ""}${stripped}\n`;
575
+ current.log =
576
+ next.length > MAX_STEP_LOG_CHARS
577
+ ? next.slice(0, MAX_STEP_LOG_CHARS) + "\n[step log truncated]\n"
578
+ : next;
579
+ }
580
+ }
581
+
582
+ // ── Job terminal markers — act always prints these once per job. ──
583
+ if (/Job succeeded\b/i.test(rest)) {
584
+ job.status = "success";
585
+ job.endedAt = now;
586
+ touched = true;
587
+ } else if (/Job failed\b/i.test(rest)) {
588
+ job.status = "failed";
589
+ job.endedAt = now;
590
+ touched = true;
591
+ } else if (/Job skipped\b/i.test(rest)) {
592
+ job.status = "skipped";
593
+ job.endedAt = now;
594
+ touched = true;
595
+ } else if (!existing) {
596
+ job.status = "running";
597
+ }
598
+
599
+ if (job.startedAt && job.endedAt) {
600
+ job.durationMs =
601
+ new Date(job.endedAt).getTime() - new Date(job.startedAt).getTime();
602
+ }
603
+
604
+ if (!touched) {
605
+ // Pure mid-step log line — we already mutated the step buffer above,
606
+ // but we still want the UI to refresh so the step log grows live.
607
+ this.jobs.set(jobName, job);
608
+ this.onUpdate({ ...job, steps: job.steps?.map((s) => ({ ...s })) });
609
+ return;
610
+ }
611
+
612
+ this.jobs.set(jobName, job);
613
+ this.onUpdate({ ...job, steps: job.steps?.map((s) => ({ ...s })) });
614
+ }
615
+ }
616
+
617
+ // ─── Run history listing ────────────────────────────────────────────────
618
+
619
+ export interface GhaRunListOptions {
620
+ questionId?: string;
621
+ fileId?: string;
622
+ limit?: number;
623
+ }
624
+
625
+ async function readRunMetadata(
626
+ runId: string,
627
+ ): Promise<GhaRunMetadata | undefined> {
628
+ const file = path.join(getGhaRunsDir(), runId, "metadata.json");
629
+ const raw = await readJsonFile(file);
630
+ if (!raw || typeof raw !== "object") return undefined;
631
+ return raw as GhaRunMetadata;
632
+ }
633
+
634
+ export async function listGhaRuns(
635
+ options: GhaRunListOptions = {},
636
+ ): Promise<GhaRunMetadata[]> {
637
+ const dir = getGhaRunsDir();
638
+ let entries: string[] = [];
639
+ try {
640
+ entries = await fs.readdir(dir);
641
+ } catch (err: any) {
642
+ if (err?.code === "ENOENT") return [];
643
+ throw err;
644
+ }
645
+ const limit = Math.max(1, Math.min(options.limit ?? 50, 200));
646
+ const results: GhaRunMetadata[] = [];
647
+ for (const entry of entries) {
648
+ const meta = await readRunMetadata(entry);
649
+ if (!meta) continue;
650
+ if (options.fileId && meta.fileId !== options.fileId) continue;
651
+ if (options.questionId && meta.questionId !== options.questionId) continue;
652
+ results.push(meta);
653
+ }
654
+ results.sort((a, b) => (a.startedAt < b.startedAt ? 1 : -1));
655
+ return results.slice(0, limit);
656
+ }
657
+
658
+ export interface GhaRunDetails extends GhaRunMetadata {
659
+ log: string;
660
+ }
661
+
662
+ export async function getGhaRun(runId: string): Promise<GhaRunDetails> {
663
+ const meta = await readRunMetadata(runId);
664
+ if (!meta) throw new Error("Run not found");
665
+ let log = "";
666
+ try {
667
+ log = await fs.readFile(
668
+ path.join(getGhaRunsDir(), runId, "run.log"),
669
+ "utf8",
670
+ );
671
+ } catch {
672
+ // log file may have been pruned; surface metadata only
673
+ }
674
+ return { ...meta, log };
365
675
  }
366
676
 
367
677
  export async function streamGhaCommand(
@@ -386,6 +696,10 @@ export async function streamGhaCommand(
386
696
  const emit = (msg: GhaStreamMessage) => input.onMessage?.(msg);
387
697
  emit({ type: "output", kind: "info", text: parsed.displayCommand });
388
698
 
699
+ // Track per-job status from act's prefixed stdout/stderr lines so the
700
+ // client can render a live DAG in addition to the raw console.
701
+ const tracker = new JobTracker((job) => emit({ type: "job", job }));
702
+
389
703
  const child = spawn("act", parsed.args, {
390
704
  cwd: workspaceDir,
391
705
  env: {
@@ -407,11 +721,13 @@ export async function streamGhaCommand(
407
721
  child.stdout.on("data", (chunk: Buffer) => {
408
722
  const text = stripAnsi(chunk.toString());
409
723
  logs = appendLog(logs, text);
724
+ tracker.feed(text);
410
725
  emit({ type: "output", kind: "stdout", text });
411
726
  });
412
727
  child.stderr.on("data", (chunk: Buffer) => {
413
728
  const text = stripAnsi(chunk.toString());
414
729
  logs = appendLog(logs, text);
730
+ tracker.feed(text);
415
731
  emit({ type: "output", kind: "stderr", text });
416
732
  });
417
733
  child.on("error", (err: NodeJS.ErrnoException) => {
@@ -438,6 +754,10 @@ export async function streamGhaCommand(
438
754
  });
439
755
  });
440
756
 
757
+ // Drain any partial line buffered by the tracker before we finalise.
758
+ tracker.flush();
759
+ tracker.finalize(exitCode);
760
+
441
761
  const completedAt = new Date().toISOString();
442
762
  const durationMs =
443
763
  new Date(completedAt).getTime() - new Date(startedAt).getTime();
@@ -454,6 +774,11 @@ export async function streamGhaCommand(
454
774
  durationMs,
455
775
  exitCode,
456
776
  ...(errorMessage ? { error: errorMessage } : {}),
777
+ jobs: tracker.snapshot(),
778
+ ...(parsed.event ? { event: parsed.event } : {}),
779
+ ...(workspace.defaultWorkflow
780
+ ? { workflow: workspace.defaultWorkflow }
781
+ : {}),
457
782
  };
458
783
 
459
784
  await fs.writeFile(