lastlight-core 0.21.14 → 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 (124) hide show
  1. package/config/default.yaml +119 -1
  2. package/dist/admin/routes.js +195 -38
  3. package/dist/admin/routes.js.map +1 -1
  4. package/dist/config/config-resolve.d.ts +38 -1
  5. package/dist/config/config-resolve.js +41 -17
  6. package/dist/config/config-resolve.js.map +1 -1
  7. package/dist/config/config.d.ts +114 -0
  8. package/dist/config/config.js +225 -7
  9. package/dist/config/config.js.map +1 -1
  10. package/dist/config/repo-config.d.ts +120 -0
  11. package/dist/config/repo-config.js +447 -0
  12. package/dist/config/repo-config.js.map +1 -0
  13. package/dist/connectors/github-webhook.d.ts +17 -0
  14. package/dist/connectors/github-webhook.js +150 -17
  15. package/dist/connectors/github-webhook.js.map +1 -1
  16. package/dist/connectors/types.d.ts +48 -1
  17. package/dist/cron/dependabot-discovery.d.ts +68 -11
  18. package/dist/cron/dependabot-discovery.js +78 -20
  19. package/dist/cron/dependabot-discovery.js.map +1 -1
  20. package/dist/cron/fanout.d.ts +10 -0
  21. package/dist/cron/fanout.js +35 -2
  22. package/dist/cron/fanout.js.map +1 -1
  23. package/dist/cron/jobs.d.ts +16 -2
  24. package/dist/cron/jobs.js +69 -9
  25. package/dist/cron/jobs.js.map +1 -1
  26. package/dist/cron/repo-crons.d.ts +110 -0
  27. package/dist/cron/repo-crons.js +169 -0
  28. package/dist/cron/repo-crons.js.map +1 -0
  29. package/dist/cron/review-discovery.d.ts +33 -20
  30. package/dist/cron/review-discovery.js +23 -30
  31. package/dist/cron/review-discovery.js.map +1 -1
  32. package/dist/engine/agent-executor.d.ts +1 -1
  33. package/dist/engine/agent-executor.js +1 -1
  34. package/dist/engine/agent-executor.js.map +1 -1
  35. package/dist/engine/dispatcher.d.ts +98 -1
  36. package/dist/engine/dispatcher.js +248 -231
  37. package/dist/engine/dispatcher.js.map +1 -1
  38. package/dist/engine/executors/orchestrator.js +39 -15
  39. package/dist/engine/executors/orchestrator.js.map +1 -1
  40. package/dist/engine/executors/shared.d.ts +43 -0
  41. package/dist/engine/executors/shared.js +65 -0
  42. package/dist/engine/executors/shared.js.map +1 -1
  43. package/dist/engine/fix-harvest.d.ts +169 -0
  44. package/dist/engine/fix-harvest.js +345 -0
  45. package/dist/engine/fix-harvest.js.map +1 -0
  46. package/dist/engine/fix-markers.d.ts +184 -0
  47. package/dist/engine/fix-markers.js +329 -0
  48. package/dist/engine/fix-markers.js.map +1 -0
  49. package/dist/engine/fix-scratch.d.ts +76 -0
  50. package/dist/engine/fix-scratch.js +77 -0
  51. package/dist/engine/fix-scratch.js.map +1 -0
  52. package/dist/engine/github/github.d.ts +302 -5
  53. package/dist/engine/github/github.js +614 -54
  54. package/dist/engine/github/github.js.map +1 -1
  55. package/dist/engine/github/profiles.d.ts +45 -1
  56. package/dist/engine/github/profiles.js +35 -0
  57. package/dist/engine/github/profiles.js.map +1 -1
  58. package/dist/engine/pr-decisions.d.ts +342 -0
  59. package/dist/engine/pr-decisions.js +721 -0
  60. package/dist/engine/pr-decisions.js.map +1 -0
  61. package/dist/engine/pr-escalation.d.ts +152 -0
  62. package/dist/engine/pr-escalation.js +320 -0
  63. package/dist/engine/pr-escalation.js.map +1 -0
  64. package/dist/engine/pr-notes.d.ts +175 -0
  65. package/dist/engine/pr-notes.js +315 -0
  66. package/dist/engine/pr-notes.js.map +1 -0
  67. package/dist/engine/pr-state.d.ts +313 -0
  68. package/dist/engine/pr-state.js +515 -0
  69. package/dist/engine/pr-state.js.map +1 -0
  70. package/dist/engine/review-check.d.ts +200 -0
  71. package/dist/engine/review-check.js +305 -0
  72. package/dist/engine/review-check.js.map +1 -0
  73. package/dist/engine/router.d.ts +27 -0
  74. package/dist/engine/router.js +156 -22
  75. package/dist/engine/router.js.map +1 -1
  76. package/dist/evals-api.d.ts +10 -0
  77. package/dist/evals-api.js +38 -0
  78. package/dist/evals-api.js.map +1 -1
  79. package/dist/index.js +313 -23
  80. package/dist/index.js.map +1 -1
  81. package/dist/sandbox/index.d.ts +13 -0
  82. package/dist/sandbox/index.js +30 -0
  83. package/dist/sandbox/index.js.map +1 -1
  84. package/dist/sandbox/k8s/init-clone.d.ts +5 -0
  85. package/dist/sandbox/k8s/init-clone.js +27 -0
  86. package/dist/sandbox/k8s/init-clone.js.map +1 -1
  87. package/dist/sandbox/k8s/kubernetes-sandbox.d.ts +26 -1
  88. package/dist/sandbox/k8s/kubernetes-sandbox.js +30 -1
  89. package/dist/sandbox/k8s/kubernetes-sandbox.js.map +1 -1
  90. package/dist/state/execution-store.d.ts +27 -0
  91. package/dist/state/execution-store.js +45 -0
  92. package/dist/state/execution-store.js.map +1 -1
  93. package/dist/state/workflow-run-store.d.ts +73 -0
  94. package/dist/state/workflow-run-store.js +106 -24
  95. package/dist/state/workflow-run-store.js.map +1 -1
  96. package/dist/workflows/pr-scope.d.ts +63 -0
  97. package/dist/workflows/pr-scope.js +113 -0
  98. package/dist/workflows/pr-scope.js.map +1 -0
  99. package/dist/workflows/resume.js +113 -8
  100. package/dist/workflows/resume.js.map +1 -1
  101. package/dist/workflows/runner.d.ts +2 -1
  102. package/dist/workflows/runner.js +143 -10
  103. package/dist/workflows/runner.js.map +1 -1
  104. package/dist/workflows/simple.d.ts +280 -1
  105. package/dist/workflows/simple.js +499 -8
  106. package/dist/workflows/simple.js.map +1 -1
  107. package/dist/workflows/target-policy.d.ts +0 -12
  108. package/dist/workflows/target-policy.js +9 -15
  109. package/dist/workflows/target-policy.js.map +1 -1
  110. package/package.json +4 -4
  111. package/skills/README.md +11 -5
  112. package/skills/dependency-impact/SKILL.md +83 -0
  113. package/skills/fixing/SKILL.md +190 -0
  114. package/skills/pr-review/SKILL.md +26 -9
  115. package/workflows/cron-dependabot-ci-fix.yaml +8 -5
  116. package/workflows/cron-review.yaml +14 -5
  117. package/workflows/dependabot-ci-fix.yaml +86 -2
  118. package/workflows/dependabot-pr-merge.yaml +13 -1
  119. package/workflows/pr-fix.yaml +84 -1
  120. package/workflows/pr-review.yaml +7 -0
  121. package/workflows/prompts/dependabot-ci-fix.md +70 -17
  122. package/workflows/prompts/dependabot-pr-merge.md +203 -80
  123. package/workflows/prompts/diagnose-ci.md +96 -0
  124. package/workflows/prompts/pr-fix.md +63 -4
@@ -1,4 +1,28 @@
1
1
  import { githubAppClient, githubTokenClient, } from "./github-app-client.js";
2
+ const REPO_CONFIG_DIR = ".lastlight";
3
+ const REPO_CONFIG_DEFAULT_MAX_FILES = 200;
4
+ const REPO_CONFIG_DEFAULT_MAX_BYTES = 2 * 1024 * 1024;
5
+ /** octokit surfaces HTTP failures as errors carrying the numeric `status`. */
6
+ function httpStatus(err) {
7
+ const status = err?.status;
8
+ return typeof status === "number" ? status : undefined;
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
+ }
2
26
  /**
3
27
  * GitHub client for the harness — uses GitHub App auth.
4
28
  * Used by the orchestrator to post comments, not by agent sessions.
@@ -36,6 +60,33 @@ export class GitHubClient {
36
60
  });
37
61
  return data.id;
38
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
+ }
39
90
  /**
40
91
  * List every repository the App installation can access, as `owner/repo`
41
92
  * full names. Used at boot to seed the managed-repo list from the App grant
@@ -201,6 +252,131 @@ export class GitHubClient {
201
252
  const { data } = await this.octokit.rest.repos.get({ owner, repo });
202
253
  return data.default_branch;
203
254
  }
255
+ /**
256
+ * Fetch a repo's committed `.lastlight/` subtree — its per-repo configuration
257
+ * layer (issue #180) — from the repo's **default branch**.
258
+ *
259
+ * SECURITY — the default branch is the entire trust model here. This subtree
260
+ * can re-point models, disable workflows and add approval gates for every run
261
+ * against the repo, so it must only ever be read from a ref that already
262
+ * passed the repo's own review/branch-protection. It is resolved live from the
263
+ * repo metadata on every call (never assumed to be `main`), and NEVER read
264
+ * from a PR head or from the sandbox checkout — otherwise a pull request could
265
+ * rewrite the configuration of the agent reviewing it.
266
+ *
267
+ * Cheap by design, because a cron fanning out over N repos calls this N times:
268
+ * - `options.etag` (the previous call's root-tree ETag) short-circuits an
269
+ * untouched repo at a conditional 304 — 2 requests, no downloads.
270
+ * - `options.treeSha` (the previous `.lastlight/` tree SHA) short-circuits a
271
+ * repo that has committed elsewhere since. A git tree SHA is the content
272
+ * hash of the whole subtree, so equality means byte-identical.
273
+ * - a repo with no `.lastlight/` returns `{ status: "absent" }` — the common
274
+ * case is a normal negative result, not an exception.
275
+ * Only when both conditionals miss does it download blobs, bounded by
276
+ * `maxFiles` / `maxBytes` so a hostile repo can't make the harness pull an
277
+ * unbounded tree.
278
+ *
279
+ * Lives on the client (rather than raw octokit at the call site) because the
280
+ * evals harness swaps this whole seam for fixtures.
281
+ */
282
+ async fetchRepoConfigTree(owner, repo, options = {}) {
283
+ const maxFiles = options.maxFiles ?? REPO_CONFIG_DEFAULT_MAX_FILES;
284
+ const maxBytes = options.maxBytes ?? REPO_CONFIG_DEFAULT_MAX_BYTES;
285
+ // The trust ref. Resolved every time — a repo can rename its default branch,
286
+ // and caching the name would silently keep reading a stale (possibly
287
+ // unprotected) ref.
288
+ const { data: repoData } = await this.octokit.rest.repos.get({ owner, repo });
289
+ const defaultBranch = repoData.default_branch;
290
+ // Conditional read of the branch's root tree. `If-None-Match` is only worth
291
+ // sending when we also hold the previous tree SHA — a 304 tells us "nothing
292
+ // changed", which we can only turn into a useful answer if we can name what
293
+ // didn't change.
294
+ const conditional = options.etag && options.treeSha;
295
+ let rootTree;
296
+ try {
297
+ rootTree = await this.octokit.rest.git.getTree({
298
+ owner,
299
+ repo,
300
+ tree_sha: defaultBranch,
301
+ ...(conditional ? { headers: { "if-none-match": options.etag } } : {}),
302
+ });
303
+ }
304
+ catch (err) {
305
+ const status = httpStatus(err);
306
+ // octokit surfaces a conditional-request hit as a thrown HttpError with
307
+ // status 304 (anything non-2xx throws) — that's the cheap path, not a
308
+ // failure. `If-None-Match` is only ever sent alongside a stored tree SHA
309
+ // (see `conditional` above), so there is always one to hand back.
310
+ if (status === 304 && options.treeSha) {
311
+ return { status: "not-modified", defaultBranch, treeSha: options.treeSha, etag: options.etag };
312
+ }
313
+ // 404 = no commits yet (a brand-new empty repo); 409 = "Git Repository is
314
+ // empty". Neither is an error worth propagating — there is simply no
315
+ // config to read.
316
+ if (status === 404 || status === 409)
317
+ return { status: "absent", defaultBranch };
318
+ throw err;
319
+ }
320
+ const etag = typeof rootTree.headers?.etag === "string" ? rootTree.headers.etag : undefined;
321
+ const dirEntry = rootTree.data.tree.find((e) => e.path === REPO_CONFIG_DIR && e.type === "tree");
322
+ if (!dirEntry?.sha)
323
+ return { status: "absent", defaultBranch };
324
+ const treeSha = dirEntry.sha;
325
+ // Content-exact conditional: same subtree SHA ⇒ same bytes, whatever else
326
+ // the repo committed since.
327
+ if (options.treeSha && options.treeSha === treeSha) {
328
+ return { status: "not-modified", defaultBranch, treeSha, etag };
329
+ }
330
+ let subtree;
331
+ try {
332
+ subtree = await this.octokit.rest.git.getTree({
333
+ owner,
334
+ repo,
335
+ tree_sha: treeSha,
336
+ recursive: "1",
337
+ });
338
+ }
339
+ catch (err) {
340
+ if (httpStatus(err) === 404)
341
+ return { status: "absent", defaultBranch };
342
+ throw err;
343
+ }
344
+ const files = [];
345
+ let bytes = 0;
346
+ let truncated = subtree.data.truncated === true;
347
+ for (const entry of subtree.data.tree) {
348
+ // `commit` entries are submodules (no blob to read); `tree` entries are
349
+ // directories, implied by their children's paths.
350
+ if (entry.type !== "blob" || !entry.path || !entry.sha)
351
+ continue;
352
+ if (options.includePath && !options.includePath(entry.path))
353
+ continue;
354
+ const size = typeof entry.size === "number" ? entry.size : 0;
355
+ if (files.length >= maxFiles || bytes + size > maxBytes) {
356
+ // Stop materializing rather than throwing: the caller decides how to
357
+ // report an over-cap repo, and a partial tree is still flagged.
358
+ truncated = true;
359
+ continue;
360
+ }
361
+ const { data: blob } = await this.octokit.rest.git.getBlob({ owner, repo, file_sha: entry.sha });
362
+ const content = Buffer.from(blob.content ?? "", blob.encoding ?? "base64");
363
+ // Re-check against the ACTUAL length. `entry.size` is absent on some tree
364
+ // entries and defaults to 0 above, so the pre-check degrades to
365
+ // `bytes + 0 > maxBytes` and would admit a blob of any size.
366
+ // `sanitizeRepoFiles` applies the cap again downstream, but this one is
367
+ // meant to hold on its own. `continue`, not `break`, for the same reason
368
+ // as above: a later small file is still admissible.
369
+ if (bytes + content.length > maxBytes) {
370
+ truncated = true;
371
+ continue;
372
+ }
373
+ bytes += content.length;
374
+ // Record the true size, not the (possibly absent, possibly wrong) size
375
+ // the tree reported — downstream cap checks key off this.
376
+ files.push({ path: entry.path, mode: entry.mode ?? "100644", size: content.length, content });
377
+ }
378
+ return { status: "ok", defaultBranch, treeSha, etag, files, truncated };
379
+ }
204
380
  /** Convenience: fetch only the PR's head commit SHA. Used by check-run code. */
205
381
  async getPullRequestHeadSha(owner, repo, pullNumber) {
206
382
  const { data } = await this.octokit.rest.pulls.get({
@@ -217,15 +393,26 @@ export class GitHubClient {
217
393
  * `name` in their list will gate merges on the eventual conclusion.
218
394
  *
219
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.
220
402
  */
221
403
  async createCheckRun(owner, repo, headSha, name, options = {}) {
404
+ const status = options.status ?? "in_progress";
222
405
  const { data } = await this.octokit.rest.checks.create({
223
406
  owner,
224
407
  repo,
225
408
  name,
226
409
  head_sha: headSha,
227
- status: "in_progress",
228
- 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
+ : {}),
229
416
  ...(options.detailsUrl ? { details_url: options.detailsUrl } : {}),
230
417
  ...(options.output ? { output: options.output } : {}),
231
418
  });
@@ -333,65 +520,212 @@ export class GitHubClient {
333
520
  * discovery and the fix prompt agree on what "red" means.
334
521
  * "passing" — there ARE checks/statuses and none are failing or pending.
335
522
  */
336
- 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 = {}) {
337
544
  const [{ data: checks }, { data: status }] = await Promise.all([
338
545
  this.octokit.rest.checks.listForRef({ owner, repo, ref, filter: "latest" }),
339
546
  this.octokit.rest.repos.getCombinedStatusForRef({ owner, repo, ref }),
340
547
  ]);
341
- 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);
342
551
  const statuses = status.statuses ?? [];
343
- if (runs.length === 0 && statuses.length === 0)
344
- return "none";
345
- 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;
346
553
  const statusPending = statuses.length > 0 && status.state === "pending";
347
- if (runPending || statusPending)
348
- 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
+ }
349
562
  const runFailing = runs.some((r) => r.conclusion === "failure" || r.conclusion === "timed_out");
350
563
  const statusFailing = status.state === "failure" || status.state === "error";
351
564
  if (runFailing || statusFailing)
352
- return "failing";
353
- return "passing";
565
+ return { state: "failing", settledCount, pendingCount };
566
+ return { state: "passing", settledCount, pendingCount };
354
567
  }
355
568
  /**
356
- * Get failed check runs for a PR's head SHA.
357
- * Fetches the actual job logs (not just annotations) to show real errors.
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.
358
580
  */
359
- async getFailedChecks(owner, repo, ref) {
360
- try {
361
- const { data } = await this.octokit.rest.checks.listForRef({
362
- owner,
363
- repo,
364
- ref,
365
- filter: "latest",
366
- });
367
- const failed = data.check_runs.filter((r) => r.conclusion === "failure" || r.conclusion === "timed_out");
368
- if (failed.length === 0)
369
- return "No failed checks found.";
370
- const summaries = await Promise.all(failed.map(async (run) => {
371
- let logExcerpt = "";
372
- // Try to fetch the actual Actions job log using the job id from details_url.
373
- const jobId = actionsJobIdFromDetailsUrl(run.details_url);
374
- if (jobId !== null) {
375
- try {
376
- const { data: logData } = await this.octokit.rest.actions.downloadJobLogsForWorkflowRun({
377
- owner,
378
- repo,
379
- job_id: jobId,
380
- });
381
- const fullLog = typeof logData === "string" ? logData : String(logData);
382
- logExcerpt = extractErrorExcerpt(fullLog);
383
- }
384
- catch {
385
- // Job logs may not be available — fall back to annotations
386
- }
581
+ async getCommitAuthorName(owner, repo, ref) {
582
+ const { data } = await this.octokit.rest.repos.getCommit({ owner, repo, ref });
583
+ return data.commit?.author?.name ?? "";
584
+ }
585
+ /**
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".
594
+ */
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;
387
680
  }
388
- // Fall back to annotations if no job logs
389
- if (!logExcerpt) {
390
- 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
+ }
391
698
  }
392
- return `### ${run.name}: ${run.conclusion}\n${logExcerpt || "No log details available."}`;
393
- }));
394
- 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));
395
729
  }
396
730
  catch (err) {
397
731
  const message = err instanceof Error ? err.message : String(err);
@@ -406,6 +740,109 @@ export class GitHubClient {
406
740
  const TIMESTAMP_RE = /^\d{4}-\d{2}-\d{2}T[\d:.]+Z\s/;
407
741
  /** Lines that carry no actionable signal on their own. */
408
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
+ }
409
846
  /**
410
847
  * Parse the Actions job id from a check-run's `details_url`.
411
848
  * Actions URLs look like: `.../actions/runs/<runId>/job/<jobId>`
@@ -417,6 +854,92 @@ export function actionsJobIdFromDetailsUrl(url) {
417
854
  const m = url.match(/\/job\/(\d+)/);
418
855
  return m ? parseInt(m[1], 10) : null;
419
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
+ }
420
943
  /**
421
944
  * Strip the leading timestamp from a raw Actions log line.
422
945
  */
@@ -427,9 +950,17 @@ function stripTimestamp(line) {
427
950
  * Given the full text of an Actions job log, return a compact excerpt
428
951
  * highlighting the real error lines with surrounding context.
429
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.
430
959
  */
431
- export function extractErrorExcerpt(fullLog) {
432
- 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");
433
964
  const lines = rawLines.map(stripTimestamp);
434
965
  // Collect indices of real (non-noise) error lines
435
966
  const realErrorIndices = [];
@@ -447,11 +978,18 @@ export function extractErrorExcerpt(fullLog) {
447
978
  }
448
979
  // Prefer real error lines; fall back to noise-only if that's all we have
449
980
  const anchorIndices = realErrorIndices.length > 0 ? realErrorIndices : noiseOnlyIndices;
450
- if (anchorIndices.length > 0) {
451
- return buildContextExcerpt(lines, anchorIndices);
452
- }
453
- // No error lines at all — return the last 30 lines as a tail
454
- 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}`;
455
993
  }
456
994
  /**
457
995
  * Build a de-duplicated context excerpt from the given anchor line indices.
@@ -467,6 +1005,28 @@ function buildContextExcerpt(lines, anchorIndices) {
467
1005
  const sorted = Array.from(included).sort((a, b) => a - b);
468
1006
  return sorted.slice(0, 50).map((i) => lines[i]).join("\n");
469
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
+ }
470
1030
  /**
471
1031
  * Fetch annotation lines for a check run, trying failure-level first then
472
1032
  * warning-level so the block is never emptier than necessary.