lastlight-core 0.22.0 → 0.23.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 (102) hide show
  1. package/config/default.yaml +70 -2
  2. package/dist/config/config.d.ts +35 -0
  3. package/dist/config/config.js +152 -3
  4. package/dist/config/config.js.map +1 -1
  5. package/dist/config/repo-config.d.ts +7 -0
  6. package/dist/config/repo-config.js +15 -0
  7. package/dist/config/repo-config.js.map +1 -1
  8. package/dist/connectors/github-webhook.d.ts +17 -0
  9. package/dist/connectors/github-webhook.js +150 -17
  10. package/dist/connectors/github-webhook.js.map +1 -1
  11. package/dist/connectors/types.d.ts +48 -1
  12. package/dist/cron/dependabot-discovery.d.ts +68 -11
  13. package/dist/cron/dependabot-discovery.js +78 -20
  14. package/dist/cron/dependabot-discovery.js.map +1 -1
  15. package/dist/cron/jobs.d.ts +4 -0
  16. package/dist/cron/jobs.js +38 -4
  17. package/dist/cron/jobs.js.map +1 -1
  18. package/dist/cron/review-discovery.d.ts +33 -20
  19. package/dist/cron/review-discovery.js +23 -30
  20. package/dist/cron/review-discovery.js.map +1 -1
  21. package/dist/engine/agent-executor.d.ts +1 -1
  22. package/dist/engine/agent-executor.js +1 -1
  23. package/dist/engine/agent-executor.js.map +1 -1
  24. package/dist/engine/dispatcher.d.ts +98 -1
  25. package/dist/engine/dispatcher.js +248 -231
  26. package/dist/engine/dispatcher.js.map +1 -1
  27. package/dist/engine/executors/shared.d.ts +43 -0
  28. package/dist/engine/executors/shared.js +65 -0
  29. package/dist/engine/executors/shared.js.map +1 -1
  30. package/dist/engine/fix-harvest.d.ts +169 -0
  31. package/dist/engine/fix-harvest.js +345 -0
  32. package/dist/engine/fix-harvest.js.map +1 -0
  33. package/dist/engine/fix-markers.d.ts +184 -0
  34. package/dist/engine/fix-markers.js +329 -0
  35. package/dist/engine/fix-markers.js.map +1 -0
  36. package/dist/engine/fix-scratch.d.ts +76 -0
  37. package/dist/engine/fix-scratch.js +77 -0
  38. package/dist/engine/fix-scratch.js.map +1 -0
  39. package/dist/engine/github/github.d.ts +212 -5
  40. package/dist/engine/github/github.js +481 -54
  41. package/dist/engine/github/github.js.map +1 -1
  42. package/dist/engine/pr-decisions.d.ts +342 -0
  43. package/dist/engine/pr-decisions.js +721 -0
  44. package/dist/engine/pr-decisions.js.map +1 -0
  45. package/dist/engine/pr-escalation.d.ts +152 -0
  46. package/dist/engine/pr-escalation.js +320 -0
  47. package/dist/engine/pr-escalation.js.map +1 -0
  48. package/dist/engine/pr-notes.d.ts +175 -0
  49. package/dist/engine/pr-notes.js +315 -0
  50. package/dist/engine/pr-notes.js.map +1 -0
  51. package/dist/engine/pr-state.d.ts +313 -0
  52. package/dist/engine/pr-state.js +515 -0
  53. package/dist/engine/pr-state.js.map +1 -0
  54. package/dist/engine/review-check.d.ts +200 -0
  55. package/dist/engine/review-check.js +305 -0
  56. package/dist/engine/review-check.js.map +1 -0
  57. package/dist/engine/router.d.ts +27 -0
  58. package/dist/engine/router.js +156 -22
  59. package/dist/engine/router.js.map +1 -1
  60. package/dist/evals-api.d.ts +7 -0
  61. package/dist/evals-api.js +30 -0
  62. package/dist/evals-api.js.map +1 -1
  63. package/dist/index.js +268 -20
  64. package/dist/index.js.map +1 -1
  65. package/dist/sandbox/index.d.ts +13 -0
  66. package/dist/sandbox/index.js +30 -0
  67. package/dist/sandbox/index.js.map +1 -1
  68. package/dist/sandbox/k8s/init-clone.d.ts +5 -0
  69. package/dist/sandbox/k8s/init-clone.js +27 -0
  70. package/dist/sandbox/k8s/init-clone.js.map +1 -1
  71. package/dist/state/execution-store.d.ts +27 -0
  72. package/dist/state/execution-store.js +45 -0
  73. package/dist/state/execution-store.js.map +1 -1
  74. package/dist/state/workflow-run-store.d.ts +73 -0
  75. package/dist/state/workflow-run-store.js +106 -24
  76. package/dist/state/workflow-run-store.js.map +1 -1
  77. package/dist/workflows/pr-scope.d.ts +63 -0
  78. package/dist/workflows/pr-scope.js +113 -0
  79. package/dist/workflows/pr-scope.js.map +1 -0
  80. package/dist/workflows/resume.js +17 -4
  81. package/dist/workflows/resume.js.map +1 -1
  82. package/dist/workflows/simple.d.ts +94 -1
  83. package/dist/workflows/simple.js +206 -3
  84. package/dist/workflows/simple.js.map +1 -1
  85. package/dist/workflows/target-policy.d.ts +0 -12
  86. package/dist/workflows/target-policy.js +9 -15
  87. package/dist/workflows/target-policy.js.map +1 -1
  88. package/package.json +4 -4
  89. package/skills/README.md +11 -5
  90. package/skills/dependency-impact/SKILL.md +83 -0
  91. package/skills/fixing/SKILL.md +190 -0
  92. package/skills/pr-review/SKILL.md +26 -9
  93. package/workflows/cron-dependabot-ci-fix.yaml +8 -5
  94. package/workflows/cron-review.yaml +14 -5
  95. package/workflows/dependabot-ci-fix.yaml +86 -2
  96. package/workflows/dependabot-pr-merge.yaml +13 -1
  97. package/workflows/pr-fix.yaml +84 -1
  98. package/workflows/pr-review.yaml +7 -0
  99. package/workflows/prompts/dependabot-ci-fix.md +70 -17
  100. package/workflows/prompts/dependabot-pr-merge.md +203 -80
  101. package/workflows/prompts/diagnose-ci.md +96 -0
  102. package/workflows/prompts/pr-fix.md +63 -4
@@ -7,6 +7,22 @@ function httpStatus(err) {
7
7
  const status = err?.status;
8
8
  return typeof status === "number" ? status : undefined;
9
9
  }
10
+ /**
11
+ * Apply {@link ChecksQueryOptions.excludeApp} to a check-run list.
12
+ *
13
+ * One helper rather than the same `filter` inline at each query, because
14
+ * "which reads drop our own checks" is a correctness property (07 §7.2) that
15
+ * should be greppable — `getCiFailureReport` was the one settle-path read that
16
+ * silently didn't, and our own `CHANGES_REQUESTED` review check concludes
17
+ * `failure` (../review-check.ts), so the fix agent was handed its own
18
+ * reviewer's verdict as CI evidence to fix.
19
+ *
20
+ * Only check runs carry an `app`; commit statuses do not, and we never post
21
+ * one, so there is nothing to exclude on that side.
22
+ */
23
+ function excludingApp(runs, opts) {
24
+ return opts.excludeApp ? runs.filter((r) => r.app?.slug !== opts.excludeApp) : runs;
25
+ }
10
26
  /**
11
27
  * GitHub client for the harness — uses GitHub App auth.
12
28
  * Used by the orchestrator to post comments, not by agent sessions.
@@ -44,6 +60,33 @@ export class GitHubClient {
44
60
  });
45
61
  return data.id;
46
62
  }
63
+ /**
64
+ * Add labels to an issue/PR, leaving existing labels alone.
65
+ *
66
+ * The only harness-side label WRITE. Every other label mutation in the system
67
+ * happens INSIDE the sandbox, through agentic-pi's `github_*` tools driven
68
+ * from a prompt — which is the right place for a label whose value is an
69
+ * agent's judgement (`dependency-trivial`, the triage vocabulary). This one
70
+ * is different in kind: the dispatch-time escalation
71
+ * (`../pr-escalation.ts`) fires precisely when we have decided NOT to
72
+ * provision a sandbox, so there is no agent to ask.
73
+ *
74
+ * GitHub's own endpoint creates a label that does not exist yet (with an
75
+ * arbitrary colour), so there is no `ensureLabels` companion to write.
76
+ * Idempotent by construction — re-adding a present label is a no-op — but
77
+ * that is NOT what makes the escalation post one comment; see
78
+ * `../pr-escalation.ts` for the record that does.
79
+ */
80
+ async addLabels(owner, repo, issueNumber, labels) {
81
+ if (labels.length === 0)
82
+ return;
83
+ await this.octokit.rest.issues.addLabels({
84
+ owner,
85
+ repo,
86
+ issue_number: issueNumber,
87
+ labels,
88
+ });
89
+ }
47
90
  /**
48
91
  * List every repository the App installation can access, as `owner/repo`
49
92
  * full names. Used at boot to seed the managed-repo list from the App grant
@@ -350,15 +393,26 @@ export class GitHubClient {
350
393
  * `name` in their list will gate merges on the eventual conclusion.
351
394
  *
352
395
  * Requires the GitHub App to have `Checks: Read and write` permission.
396
+ *
397
+ * `status` defaults to `in_progress` (the historical behaviour). The other
398
+ * two exist for the review PLACEHOLDERS: `queued` says "waiting for CI"
399
+ * under `review.trigger: after-checks`, and `completed` + `conclusion:
400
+ * neutral` says "available on request" under `on-request` — see
401
+ * `reviewCheckPlacement` in ../pr-decisions.ts.
353
402
  */
354
403
  async createCheckRun(owner, repo, headSha, name, options = {}) {
404
+ const status = options.status ?? "in_progress";
355
405
  const { data } = await this.octokit.rest.checks.create({
356
406
  owner,
357
407
  repo,
358
408
  name,
359
409
  head_sha: headSha,
360
- status: "in_progress",
361
- started_at: new Date().toISOString(),
410
+ status,
411
+ // `queued` has not started, so it must not claim a start time.
412
+ ...(status === "queued" ? {} : { started_at: new Date().toISOString() }),
413
+ ...(status === "completed"
414
+ ? { conclusion: options.conclusion ?? "neutral", completed_at: new Date().toISOString() }
415
+ : {}),
362
416
  ...(options.detailsUrl ? { details_url: options.detailsUrl } : {}),
363
417
  ...(options.output ? { output: options.output } : {}),
364
418
  });
@@ -466,65 +520,212 @@ export class GitHubClient {
466
520
  * discovery and the fix prompt agree on what "red" means.
467
521
  * "passing" — there ARE checks/statuses and none are failing or pending.
468
522
  */
469
- async getChecksConclusion(owner, repo, ref) {
523
+ async getChecksConclusion(owner, repo, ref, opts = {}) {
524
+ return (await this.getChecksSummary(owner, repo, ref, opts)).state;
525
+ }
526
+ /**
527
+ * {@link getChecksConclusion} plus the COUNT of checks behind the verdict, in
528
+ * the same two API calls.
529
+ *
530
+ * `settledCount` exists because "passing" alone is not evidence of anything:
531
+ * on a repo with no CI at all, `getChecksConclusion` returns `"none"` and a
532
+ * repo with one trivial check returns `"passing"` — and the auto-merge
533
+ * decision needs to tell "CI approved this" from "nothing looked at it"
534
+ * (`dependencies.minSettledChecks`; see `mayMerge` in ../pr-decisions.ts and
535
+ * 09-state-machine.md → D10). Deriving it in the client rather than at the
536
+ * call site keeps it to ONE round trip: recomputing the count from a second
537
+ * `listForRef` would double the cost of every PR-state resolution.
538
+ *
539
+ * A check run counts as settled when it has left queued/in_progress —
540
+ * whatever it concluded. Status contexts are settled unless the combined
541
+ * state is `pending`.
542
+ */
543
+ async getChecksSummary(owner, repo, ref, opts = {}) {
470
544
  const [{ data: checks }, { data: status }] = await Promise.all([
471
545
  this.octokit.rest.checks.listForRef({ owner, repo, ref, filter: "latest" }),
472
546
  this.octokit.rest.repos.getCombinedStatusForRef({ owner, repo, ref }),
473
547
  ]);
474
- const runs = checks.check_runs;
548
+ // Drop OUR OWN check runs when the caller is deciding whether to TRIGGER
549
+ // work — see {@link ChecksQueryOptions.excludeApp}.
550
+ const runs = excludingApp(checks.check_runs, opts);
475
551
  const statuses = status.statuses ?? [];
476
- if (runs.length === 0 && statuses.length === 0)
477
- return "none";
478
- const runPending = runs.some((r) => r.status === "queued" || r.status === "in_progress");
552
+ const runPendingCount = runs.filter((r) => r.status === "queued" || r.status === "in_progress").length;
479
553
  const statusPending = statuses.length > 0 && status.state === "pending";
480
- if (runPending || statusPending)
481
- return "pending";
554
+ const pendingCount = runPendingCount + (statusPending ? statuses.length : 0);
555
+ const settledCount = runs.length - runPendingCount + (statusPending ? 0 : statuses.length);
556
+ if (runs.length === 0 && statuses.length === 0) {
557
+ return { state: "none", settledCount: 0, pendingCount: 0 };
558
+ }
559
+ if (runPendingCount > 0 || statusPending) {
560
+ return { state: "pending", settledCount, pendingCount };
561
+ }
482
562
  const runFailing = runs.some((r) => r.conclusion === "failure" || r.conclusion === "timed_out");
483
563
  const statusFailing = status.state === "failure" || status.state === "error";
484
564
  if (runFailing || statusFailing)
485
- return "failing";
486
- return "passing";
565
+ return { state: "failing", settledCount, pendingCount };
566
+ return { state: "passing", settledCount, pendingCount };
567
+ }
568
+ /**
569
+ * The git AUTHOR NAME on a commit — not a GitHub login.
570
+ *
571
+ * This is the discriminator the fix state machine uses to answer "did WE push
572
+ * this head, or did the world move?" (09-state-machine.md → S1, the attempt
573
+ * table). It has to be the git author name because that is what
574
+ * `git-auth.ts` stamps on the agent's own commits (`user.name = botLogin`),
575
+ * and it is the same field `check_suite.head_commit.author.name` carries on
576
+ * the webhook path — so the webhook and the cron agree by construction.
577
+ *
578
+ * Returns `""` when GitHub reports no author name, so callers get a value
579
+ * that simply never equals `botLogin` rather than a null to branch on.
580
+ */
581
+ async getCommitAuthorName(owner, repo, ref) {
582
+ const { data } = await this.octokit.rest.repos.getCommit({ owner, repo, ref });
583
+ return data.commit?.author?.name ?? "";
487
584
  }
488
585
  /**
489
- * Get failed check runs for a PR's head SHA.
490
- * Fetches the actual job logs (not just annotations) to show real errors.
586
+ * Check state of a PR's BASE branch head — a branch name is a valid `ref` for
587
+ * the checks API, so this is {@link getChecksConclusion} pointed at the base
588
+ * tip.
589
+ *
590
+ * It has its own name because the *question* is different: "is the PR at
591
+ * fault, or was `main` already red?". A red base makes retrying the PR
592
+ * pointless, and call sites asking that shouldn't have to know it's the same
593
+ * query as "is this PR red".
491
594
  */
492
- async getFailedChecks(owner, repo, ref) {
493
- try {
494
- const { data } = await this.octokit.rest.checks.listForRef({
495
- owner,
496
- repo,
497
- ref,
498
- filter: "latest",
499
- });
500
- const failed = data.check_runs.filter((r) => r.conclusion === "failure" || r.conclusion === "timed_out");
501
- if (failed.length === 0)
502
- return "No failed checks found.";
503
- const summaries = await Promise.all(failed.map(async (run) => {
504
- let logExcerpt = "";
505
- // Try to fetch the actual Actions job log using the job id from details_url.
506
- const jobId = actionsJobIdFromDetailsUrl(run.details_url);
507
- if (jobId !== null) {
508
- try {
509
- const { data: logData } = await this.octokit.rest.actions.downloadJobLogsForWorkflowRun({
510
- owner,
511
- repo,
512
- job_id: jobId,
513
- });
514
- const fullLog = typeof logData === "string" ? logData : String(logData);
515
- logExcerpt = extractErrorExcerpt(fullLog);
516
- }
517
- catch {
518
- // Job logs may not be available — fall back to annotations
519
- }
595
+ async getBaseChecksState(owner, repo, baseRef, opts = {}) {
596
+ return this.getChecksConclusion(owner, repo, baseRef, opts);
597
+ }
598
+ /**
599
+ * Structured CI failure evidence for a ref — the HEAVY counterpart to
600
+ * {@link getChecksConclusion}: one Actions job-log download per failed check
601
+ * run, plus the job and workflow-run metadata that says *where* it failed.
602
+ *
603
+ * Every Actions read here needs the App's optional `Actions: read`
604
+ * permission. None of them is required: each degrades independently to
605
+ * `undefined` / the annotation fallback, and the per-job + report-level
606
+ * `logsAvailable` flags are what let the renderer say so out loud instead of
607
+ * passing annotations off as job logs (issue #251).
608
+ *
609
+ * Throws if the check-run listing itself fails — a report cannot represent
610
+ * "I couldn't look". {@link getFailedChecks} catches that for prompt callers.
611
+ *
612
+ * **Bounded on purpose.** `resolvePrState` awaits this synchronously on the
613
+ * dispatch path a webhook handler takes, BEFORE any disposition is taken — so
614
+ * it is paid in full even on dispatches that go on to skip as
615
+ * `already-reviewed` / `human-hold` / `run-in-flight`. `checks.listForRef`
616
+ * returns up to 30 runs, and the first cut of this method downloaded every
617
+ * failed one's FULL log concurrently, uncapped and with no deadline: thirty
618
+ * multi-megabyte strings resident at once, on a host with a 2 GB agent cap and
619
+ * no swap. Hence {@link CI_LOG_FETCH_CONCURRENCY},
620
+ * {@link CI_REPORT_DEADLINE_MS} and the byte cap inside
621
+ * {@link extractErrorExcerpt}.
622
+ */
623
+ async getCiFailureReport(owner, repo, ref, opts = {}) {
624
+ const { data } = await this.octokit.rest.checks.listForRef({
625
+ owner,
626
+ repo,
627
+ ref,
628
+ filter: "latest",
629
+ });
630
+ const failed = excludingApp(data.check_runs, opts).filter((r) => r.conclusion === "failure" || r.conclusion === "timed_out");
631
+ if (failed.length === 0)
632
+ return { jobs: [], logsAvailable: false };
633
+ // ONE deadline for the whole report rather than one per request: what the
634
+ // dispatch path can afford is a total wall-clock budget, and per-request
635
+ // timeouts multiply by the number of concurrency waves. An aborted read is
636
+ // classified `unavailable` like any other fetch failure, so a slow GitHub
637
+ // costs us evidence, never the dispatch.
638
+ const signal = AbortSignal.timeout(CI_REPORT_DEADLINE_MS);
639
+ const request = { signal };
640
+ // A failing matrix shares one workflow run, so `path` is one lookup for all
641
+ // of its shards, not one per shard. Memoized per report, not per client —
642
+ // a workflow file can be edited between runs.
643
+ const workflowPaths = new Map();
644
+ const workflowPathFor = (runId) => {
645
+ let pending = workflowPaths.get(runId);
646
+ if (!pending) {
647
+ pending = this.octokit.rest.actions
648
+ .getWorkflowRun({ owner, repo, run_id: runId, request })
649
+ .then((res) => res.data.path)
650
+ .catch(() => undefined);
651
+ workflowPaths.set(runId, pending);
652
+ }
653
+ return pending;
654
+ };
655
+ const jobs = await mapWithConcurrency(failed, CI_LOG_FETCH_CONCURRENCY, async (run) => {
656
+ const jobId = actionsJobIdFromDetailsUrl(run.details_url);
657
+ const runId = actionsRunIdFromDetailsUrl(run.details_url);
658
+ let logExcerpt = "";
659
+ let logsAvailable = false;
660
+ let cause;
661
+ let failingStep;
662
+ let workflowPath;
663
+ if (jobId !== null) {
664
+ // The three Actions reads are independent — a permission denial or an
665
+ // expired log on one must not cost us the other two. Only the LOG
666
+ // read's failure is classified: it is the one the banner speaks about.
667
+ const [log, job, path] = await Promise.all([
668
+ this.octokit.rest.actions
669
+ .downloadJobLogsForWorkflowRun({ owner, repo, job_id: jobId, request })
670
+ .then((res) => ({ ok: true, data: res.data }))
671
+ .catch((err) => ({ ok: false, cause: logFetchCause(err) })),
672
+ this.octokit.rest.actions
673
+ .getJobForWorkflowRun({ owner, repo, job_id: jobId, request })
674
+ .then((res) => res.data)
675
+ .catch(() => null),
676
+ runId !== null ? workflowPathFor(runId) : Promise.resolve(undefined),
677
+ ]);
678
+ if (!log.ok) {
679
+ cause = log.cause;
520
680
  }
521
- // Fall back to annotations if no job logs
522
- if (!logExcerpt) {
523
- logExcerpt = await fetchAnnotationExcerpt(this.octokit, owner, repo, run.id);
681
+ else {
682
+ const text = decodeJobLog(log.data);
683
+ // A body in a shape we don't recognise is not evidence — and it is
684
+ // specifically the shape that used to stringify to
685
+ // "[object ArrayBuffer]" and pass for a real log. See decodeJobLog.
686
+ if (text === null)
687
+ cause = "unavailable";
688
+ else {
689
+ logExcerpt = extractErrorExcerpt(text);
690
+ // An excerpt we can't show is not evidence either: treat a blank
691
+ // one as "no logs" so it falls through to annotations AND says so,
692
+ // rather than claiming real logs and rendering nothing.
693
+ if (logExcerpt.trim().length === 0) {
694
+ logExcerpt = "";
695
+ cause = "empty";
696
+ }
697
+ }
524
698
  }
525
- return `### ${run.name}: ${run.conclusion}\n${logExcerpt || "No log details available."}`;
526
- }));
527
- return summaries.join("\n\n");
699
+ logsAvailable = logExcerpt.length > 0;
700
+ failingStep = job?.steps?.find((s) => s.conclusion === "failure" || s.conclusion === "timed_out")?.name;
701
+ workflowPath = path;
702
+ }
703
+ if (!logExcerpt) {
704
+ logExcerpt = await fetchAnnotationExcerpt(this.octokit, owner, repo, run.id);
705
+ }
706
+ return {
707
+ name: run.name,
708
+ conclusion: run.conclusion,
709
+ ...(workflowPath ? { workflowPath } : {}),
710
+ ...(failingStep ? { failingStep } : {}),
711
+ logExcerpt,
712
+ ...(run.details_url ? { jobUrl: run.details_url } : {}),
713
+ logsAvailable,
714
+ ...(cause ? { logUnavailableCause: cause } : {}),
715
+ };
716
+ });
717
+ const logsAvailable = jobs.some((j) => j.logsAvailable);
718
+ const cause = logsAvailable ? undefined : dominantLogUnavailableCause(jobs);
719
+ return { jobs, logsAvailable, ...(cause ? { logUnavailableCause: cause } : {}) };
720
+ }
721
+ /**
722
+ * Get failed check runs for a PR's head SHA as the markdown blob
723
+ * `{{ciSection}}` has always carried — a thin renderer over
724
+ * {@link getCiFailureReport}, kept so prompt-only callers are unchanged.
725
+ */
726
+ async getFailedChecks(owner, repo, ref, opts = {}) {
727
+ try {
728
+ return renderCiFailureReport(await this.getCiFailureReport(owner, repo, ref, opts));
528
729
  }
529
730
  catch (err) {
530
731
  const message = err instanceof Error ? err.message : String(err);
@@ -539,6 +740,109 @@ export class GitHubClient {
539
740
  const TIMESTAMP_RE = /^\d{4}-\d{2}-\d{2}T[\d:.]+Z\s/;
540
741
  /** Lines that carry no actionable signal on their own. */
541
742
  const NOISE_RE = /Process completed with exit code|##\[error\]Process completed|^##\[error\]$/i;
743
+ /**
744
+ * Hard BYTE cap on one job's excerpt.
745
+ *
746
+ * `buildContextExcerpt` bounds LINES (50), and the no-anchor path bounds them
747
+ * at 30 — neither bounds bytes, and a minified bundle, a base64 blob or a
748
+ * single-line JSON dump is ONE line of arbitrary length. Roughly 4k tokens:
749
+ * enough for a stack trace plus its build context, small enough that several of
750
+ * these don't crowd out the prompt.
751
+ *
752
+ * Same cap, for the same reason, as agentic-pi's `excerptJobLog`
753
+ * (`packages/agentic-pi/src/extensions/github/log-excerpt.ts`, whose header
754
+ * explains the strategy). Duplicated rather than imported: that module is not
755
+ * on agentic-pi's public entry (`src/index.ts`) and widening a published
756
+ * package's API to share one constant is the wrong trade. Keep the two in step.
757
+ */
758
+ const MAX_CI_LOG_EXCERPT_BYTES = 16_000;
759
+ /**
760
+ * Cap on how much of a raw log we even SCAN. Beyond this we keep the TAIL —
761
+ * the failure that stopped the job is the last one, and a long log's early
762
+ * errors are usually retried-and-recovered noise. Without it a 100 MB log costs
763
+ * a 100 MB `split("\n")` plus a regex per line before the excerpt cap above
764
+ * ever gets a chance to apply.
765
+ */
766
+ const MAX_CI_LOG_SCAN_BYTES = 512 * 1024;
767
+ /**
768
+ * How many failed checks we resolve at once. `checks.listForRef` defaults to 30
769
+ * runs and each resolution holds a whole job log in memory, so unbounded
770
+ * `Promise.all` means up to 30 concurrent multi-megabyte strings — see
771
+ * {@link GitHubClient.getCiFailureReport} for why that lands on the dispatch
772
+ * path whether or not the dispatch goes anywhere.
773
+ */
774
+ const CI_LOG_FETCH_CONCURRENCY = 4;
775
+ /**
776
+ * Total wall-clock budget for every Actions read in one report. A webhook
777
+ * handler is waiting on this, and the report is best-effort evidence: losing it
778
+ * to a deadline costs the fix agent context, while hanging on it costs the
779
+ * dispatch.
780
+ */
781
+ const CI_REPORT_DEADLINE_MS = 20_000;
782
+ /**
783
+ * `Promise.all` with a ceiling on how many run at once. Results stay in input
784
+ * order, so the report reads in check-run order however the waves interleaved.
785
+ */
786
+ async function mapWithConcurrency(items, limit, fn) {
787
+ const results = new Array(items.length);
788
+ let next = 0;
789
+ const worker = async () => {
790
+ for (let i = next++; i < items.length; i = next++) {
791
+ results[i] = await fn(items[i]);
792
+ }
793
+ };
794
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
795
+ return results;
796
+ }
797
+ /**
798
+ * Decode an Actions job-log response body into text, or `null` when it isn't
799
+ * one we recognise.
800
+ *
801
+ * Octokit only hands back a `string` when the response carried a `text/*`
802
+ * content type or a utf-8 charset; **anything else lands as an `ArrayBuffer`**
803
+ * (`@octokit/request`'s `getResponseData`). This endpoint 302s to blob storage
804
+ * whose content type we do not control, so that branch is reachable — and the
805
+ * `typeof data === "string" ? data : String(data)` this replaces would have
806
+ * turned it into the literal `"[object ArrayBuffer]"`: non-empty, so
807
+ * `logsAvailable` went TRUE, the annotation fallback was skipped and the
808
+ * degradation banner suppressed. That is precisely the silent degradation this
809
+ * phase exists to kill, so an unrecognised shape is reported, not stringified.
810
+ */
811
+ function decodeJobLog(data) {
812
+ if (typeof data === "string")
813
+ return data;
814
+ if (data instanceof ArrayBuffer)
815
+ return Buffer.from(data).toString("utf8");
816
+ // Buffer / Uint8Array — a view over someone else's ArrayBuffer, so the
817
+ // offset+length matter.
818
+ if (ArrayBuffer.isView(data)) {
819
+ return Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString("utf8");
820
+ }
821
+ return null;
822
+ }
823
+ /** Classify a failed job-log download — see {@link CiLogUnavailableCause}. */
824
+ function logFetchCause(err) {
825
+ const status = httpStatus(err);
826
+ if (status === 403)
827
+ return "forbidden";
828
+ if (status === 410)
829
+ return "expired";
830
+ // 429 / 5xx / an aborted request / a network error all land here: we could
831
+ // not fetch, and we do not know more than that.
832
+ return "unavailable";
833
+ }
834
+ /**
835
+ * The cause the report-level banner speaks with, in decreasing order of "what
836
+ * should the operator do about it".
837
+ *
838
+ * `forbidden` leads because a 403 is App-wide — one job reporting it settles
839
+ * the question for every job — and it is the only cause with an action attached.
840
+ * `empty` trails because it is not a fetch failure at all.
841
+ */
842
+ function dominantLogUnavailableCause(jobs) {
843
+ const order = ["forbidden", "expired", "unavailable", "empty"];
844
+ return order.find((c) => jobs.some((j) => j.logUnavailableCause === c));
845
+ }
542
846
  /**
543
847
  * Parse the Actions job id from a check-run's `details_url`.
544
848
  * Actions URLs look like: `.../actions/runs/<runId>/job/<jobId>`
@@ -550,6 +854,92 @@ export function actionsJobIdFromDetailsUrl(url) {
550
854
  const m = url.match(/\/job\/(\d+)/);
551
855
  return m ? parseInt(m[1], 10) : null;
552
856
  }
857
+ /**
858
+ * Parse the Actions *run* id out of the same `details_url`. The run — not the
859
+ * job — is what knows the workflow file's `path`, and the URL already carries
860
+ * it, so resolving `workflowPath` costs no extra lookup to discover the id.
861
+ * Returns `null` for non-Actions checks or unparseable URLs.
862
+ */
863
+ export function actionsRunIdFromDetailsUrl(url) {
864
+ if (!url)
865
+ return null;
866
+ const m = url.match(/\/actions\/runs\/(\d+)/);
867
+ return m ? parseInt(m[1], 10) : null;
868
+ }
869
+ /**
870
+ * The three-line banner that fires when the report degraded to annotations —
871
+ * one per {@link CiLogUnavailableCause}.
872
+ *
873
+ * This is the actual fix for issue #251's "Finding 1". The missing permission
874
+ * was never the real damage — the damage was that its absence looked exactly
875
+ * like normal operation, so every install that followed our own setup docs has
876
+ * been diagnosing CI failures from truncated annotations without anyone
877
+ * noticing. Saying so in the prompt makes the degradation legible to both the
878
+ * agent and whoever reads the transcript.
879
+ *
880
+ * Which is exactly why there are four of these and not one. A banner that
881
+ * names the wrong cause reintroduces the same failure in miniature: an operator
882
+ * told to grant a permission they already granted stops reading, and the run
883
+ * that produced a 410 or a rate limit goes on looking normal. Only `forbidden`
884
+ * may mention the permission, because only a 403 is evidence of it.
885
+ */
886
+ const LOGS_UNAVAILABLE_NOTES = {
887
+ forbidden: [
888
+ "NOTE: GitHub Actions job logs are unavailable (the App lacks `Actions: read`).",
889
+ "The excerpts below are check-run annotations only, which are usually truncated.",
890
+ "Grant Actions: read for full CI output.",
891
+ ].join("\n"),
892
+ expired: [
893
+ "NOTE: GitHub Actions job logs are unavailable — GitHub has expired them (410 Gone; Actions keeps logs for a limited retention window).",
894
+ "The excerpts below are check-run annotations only, which are usually truncated.",
895
+ "This is NOT a permission problem and nothing needs granting: only a fresh CI run can produce readable logs.",
896
+ ].join("\n"),
897
+ unavailable: [
898
+ "NOTE: GitHub Actions job logs could not be fetched (the request failed or timed out — e.g. a rate limit or a GitHub 5xx).",
899
+ "The excerpts below are check-run annotations only, which are usually truncated.",
900
+ "This is NOT a permission problem and is usually transient: a later attempt may well get them.",
901
+ ].join("\n"),
902
+ empty: [
903
+ "NOTE: GitHub Actions returned an EMPTY job log for every failed check.",
904
+ "The excerpts below are check-run annotations only, which are usually truncated.",
905
+ "This is NOT a permission problem — the job produced no output GitHub kept.",
906
+ ].join("\n"),
907
+ };
908
+ /**
909
+ * Render a {@link CiFailureReport} as the markdown `{{ciSection}}` carries.
910
+ *
911
+ * The "No failed checks found." sentinel is load-bearing: `dispatchWorkflow`
912
+ * tests the rendered string for `"No failed checks"` to decide whether to
913
+ * populate `ciSection` at all.
914
+ */
915
+ export function renderCiFailureReport(report) {
916
+ if (report.jobs.length === 0)
917
+ return "No failed checks found.";
918
+ const sections = report.jobs.map((job) => {
919
+ const locators = [
920
+ job.workflowPath ? `workflow: ${job.workflowPath}` : null,
921
+ job.failingStep ? `failing step: ${job.failingStep}` : null,
922
+ ].filter(Boolean);
923
+ return [
924
+ `### ${job.name}: ${job.conclusion}`,
925
+ locators.length ? `(${locators.join(" — ")})` : null,
926
+ job.logExcerpt || "No log details available.",
927
+ ]
928
+ .filter(Boolean)
929
+ .join("\n");
930
+ });
931
+ // Only blame the permission when there was an Actions job whose logs we could
932
+ // have read. A CircleCI-only repo has no Actions logs to be missing, and
933
+ // telling its operator to grant `Actions: read` would be a lie.
934
+ const hadActionsJob = report.jobs.some((j) => actionsJobIdFromDetailsUrl(j.jobUrl) !== null);
935
+ if (report.logsAvailable || !hadActionsJob)
936
+ return sections.join("\n\n");
937
+ // No recorded cause means nobody classified the failure, so the honest banner
938
+ // is the one that claims least — never the permission one, which is a claim
939
+ // about a status code we would not have seen.
940
+ const note = LOGS_UNAVAILABLE_NOTES[report.logUnavailableCause ?? "unavailable"];
941
+ return [note, ...sections].join("\n\n");
942
+ }
553
943
  /**
554
944
  * Strip the leading timestamp from a raw Actions log line.
555
945
  */
@@ -560,9 +950,17 @@ function stripTimestamp(line) {
560
950
  * Given the full text of an Actions job log, return a compact excerpt
561
951
  * highlighting the real error lines with surrounding context.
562
952
  * Timestamps are stripped; pure noise lines are deprioritised.
953
+ *
954
+ * Bounded in BYTES as well as lines ({@link MAX_CI_LOG_EXCERPT_BYTES}), because
955
+ * the line bounds below are no bound at all on a log whose failure is one
956
+ * 8 MB minified line — and this excerpt is held on `PrState.ciReport` and
957
+ * rendered into a prompt. The cap is applied here rather than at the call site
958
+ * so every caller is bounded by construction.
563
959
  */
564
- export function extractErrorExcerpt(fullLog) {
565
- const rawLines = fullLog.split("\n");
960
+ export function extractErrorExcerpt(fullLog, maxBytes = MAX_CI_LOG_EXCERPT_BYTES) {
961
+ // Scan-window first: everything below is O(log size), and the byte cap can
962
+ // only help once we have already paid for the split.
963
+ const rawLines = tailBytes(fullLog, MAX_CI_LOG_SCAN_BYTES).split("\n");
566
964
  const lines = rawLines.map(stripTimestamp);
567
965
  // Collect indices of real (non-noise) error lines
568
966
  const realErrorIndices = [];
@@ -580,11 +978,18 @@ export function extractErrorExcerpt(fullLog) {
580
978
  }
581
979
  // Prefer real error lines; fall back to noise-only if that's all we have
582
980
  const anchorIndices = realErrorIndices.length > 0 ? realErrorIndices : noiseOnlyIndices;
583
- if (anchorIndices.length > 0) {
584
- return buildContextExcerpt(lines, anchorIndices);
585
- }
586
- // No error lines at all — return the last 30 lines as a tail
587
- return lines.slice(-30).join("\n");
981
+ const excerpt = anchorIndices.length > 0
982
+ ? buildContextExcerpt(lines, anchorIndices)
983
+ : // No error lines at all — return the last 30 lines as a tail
984
+ lines.slice(-30).join("\n");
985
+ const capped = tailBytes(excerpt, maxBytes);
986
+ if (capped === excerpt)
987
+ return excerpt;
988
+ // Say so in-band: a silently truncated excerpt reads like a complete one, and
989
+ // the agent would reason about a stack trace it can't see the top of.
990
+ const shown = Buffer.byteLength(capped, "utf8");
991
+ const total = Buffer.byteLength(excerpt, "utf8");
992
+ return `[truncated — showing the last ${shown} of ${total} bytes of this excerpt]\n${capped}`;
588
993
  }
589
994
  /**
590
995
  * Build a de-duplicated context excerpt from the given anchor line indices.
@@ -600,6 +1005,28 @@ function buildContextExcerpt(lines, anchorIndices) {
600
1005
  const sorted = Array.from(included).sort((a, b) => a - b);
601
1006
  return sorted.slice(0, 50).map((i) => lines[i]).join("\n");
602
1007
  }
1008
+ /**
1009
+ * Keep the last `maxBytes` bytes, then drop the leading partial line. That
1010
+ * second step also repairs the mojibake a byte-exact cut through a multi-byte
1011
+ * character would otherwise leave at the front. Cutting from the END because
1012
+ * the failure that stopped a job is the last thing in it.
1013
+ *
1014
+ * Mirrors agentic-pi's `tailBytes` (see {@link MAX_CI_LOG_EXCERPT_BYTES}).
1015
+ */
1016
+ function tailBytes(text, maxBytes) {
1017
+ const buf = Buffer.from(text, "utf8");
1018
+ if (buf.byteLength <= maxBytes)
1019
+ return text;
1020
+ const tail = buf.subarray(buf.byteLength - maxBytes).toString("utf8");
1021
+ const nl = tail.indexOf("\n");
1022
+ if (nl === -1)
1023
+ return tail;
1024
+ const whole = tail.slice(nl + 1);
1025
+ // One enormous line followed by a newline leaves nothing after the cut. A
1026
+ // ragged first line beats reporting the log as empty, which is a different
1027
+ // (and wrong) claim about why there is no evidence.
1028
+ return whole.trim().length > 0 ? whole : tail;
1029
+ }
603
1030
  /**
604
1031
  * Fetch annotation lines for a check run, trying failure-level first then
605
1032
  * warning-level so the block is never emptier than necessary.