Skip to content

Commit b5ae0c1

Browse files
feat: keep an opt-in problem history for the Briefing (#165)
* feat: keep an opt-in problem history on codeboarding/briefing With `problem_history: 'true'`, each sync run collects the repository's issues and merged pull requests since the last update, plus each merged pull request's architecture findings from its review artifact, sends them to POST /v1/briefing and commits the returned ledger as problems.json on the orphan codeboarding/briefing branch. Every rule lives in the service; the Action only gathers facts and writes the answer. Off by default, and it never fails the run. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: bound the problem history step and follow briefing amendment 1 - Cut every issue body to 2000 UTF-16 code units, never splitting a surrogate pair; the oversize-only trimming is gone. - Stay under the service's caps by construction: 1000 open plus 1000 recently closed issues on a first run, 1000 plus 100 re-read later, 500 merged, 40 new plus 10 retried findings. - Send openIssues: every open issue number, read first in creation order, complete false past 5000, after a capped issue read, and on the conflict retry. - Ask again for findings of the 10 newest ledger merges whose findings were never read; send skipped envelopes so they count as read. - Re-read up to 100 stored open issues with an open linked pull request. - First-run caps are per pass, and issuesThrough never claims an issue a cap skipped. - Skip review artifacts over 50 MB, scan at most 20 pages of merged pull requests, give the service call 300 s, and stop the script after 10 minutes (a composite step cannot set timeout-minutes). - A ruleset or branch-name 422 on the ref update is a clear notice, not retried; a second lost race is a notice too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor: tighten problem_history without changing what it sends - Page a pull request's changed files through the shared `_nodes` pager, starting from the page MERGED_QUERY already returned, instead of a second hand-written cursor loop; `islice` keeps the 300-path cap from asking for a page past it. - Build issue, linked pull request and merged pull request facts as one literal each, with an `_author` spread for the optional login. - Pick a timeline event's pull request through one side table. - Read the ledger's ref and file under one 404 guard, and drop the unreachable assertion after the retry loop. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: share problem_history fakes and table-drive repeated cases - FakeGitHub gains add_review() for a run plus its review artifact and calls() for the GraphQL requests a test inspects; ledger(), numbers() and closed_node() replace literals repeated across tests. - Table-driven: the surrogate-safe cut, the 5000 open-issue boundary, first-run caps, read_architecture, main's never-fail outcomes and the three commit shapes (orphan, fast-forward, push-named). - The changed-paths test now also asserts no page past the 300-path cap is requested; the cap test asserts the uncapped run's issues. The new file passes against the code before the refactor, and the old file passes against the code after it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: trim the problem history README section and step comment Keep what a customer needs (opt-in, what is sent and its limits, what is written, permissions, never failing the run, how to turn it off) and drop the restatements: the Briefing's wording when it is off, and where the problem rules live, which the module docstring already says. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor: share the GitHub call, error message and packing with closed_features problem_history had its own copies of the GitHub request, the error-body message and the gzip-and-check step. closed_features now takes a method, payload, API base, token and timeout on _github, exposes _error_message and _gzip, and names what _check_size measured; problem_history uses them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: keep reading issues after a bulk edit past the cap A later run cut at 1000 issues recorded the last one read as issuesThrough. When more than 1000 issues share one update time, the next run starts on the same page and reads it again forever. A capped run now records at least the previous issuesThrough plus the overlap and a second, so each run moves on; ties left past the cap are lost. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: give every issue with an open linked pull request a turn to be read again Re-reads picked the 100 issues whose stored pull request moved most recently, so those were read every run and the rest never were. They now take turns in number order, starting where the previous update stopped, which the commit count of codeboarding/briefing tells. The ledger head is read with that count in one GraphQL query instead of the REST ref. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: keep the merged cursor at the oldest merge a capped run did not read Past 500 merged pull requests the scan stopped at the first 500 in update order, newest first, and said nothing. The service records the newest merge it is sent as where the next run starts, so the older ones were never read. A capped run now sends the 500 oldest, notes the cut, and the next run carries on from there. The README states the cap. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: read merged pull requests' findings only from this repository's own reviews, within bounds Retrying unread findings could cost tens of requests a run for nothing: every unread merge of 56 days was tried, any workflow's runs on its head commit were listed, and each head commit took its own pulls call. Retries now stop at the review artifact's 14-day retention, list only CodeBoarding runs of pull_request events, and read the heads in one aliased query. A fork's pull_request run executes the fork's workflow, so it could upload a forged review artifact. Findings now come only from runs whose head repository is this one, and only when metadata.json names the pull request. metadata.json and closed/architecture.json are not read past 1 MB each, and an envelope that would take the request over the service's limit is left out (largest first) instead of skipping the whole update. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: never send the run's GITHUB_TOKEN to the briefing service Without id-token: write, _bearer falls back to the run's GITHUB_TOKEN, which on the sync job holds contents: write. The problem history now skips the update with a notice to add id-token: write, before it reads anything. The input description, the README permissions and the failure hint list all five permissions, and the hint also fires when GraphQL refuses the repository or one of its lists (FORBIDDEN or INSUFFICIENT_SCOPES), which used to surface as a bare error. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: list the open issue numbers once a day rather than on every sync The full list costs a request per 100 open issues on every run, 20 for a repository with 2000, and only lets the service drop an issue that was deleted, transferred or made a discussion. It is now read by the first update of each UTC day (the ledger's updatedAt says which that is), and the other runs send it as incomplete, which drops nothing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor: count a failed head lookup once per merge it left unread Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent c546ce1 commit b5ae0c1

5 files changed

Lines changed: 1920 additions & 16 deletions

File tree

‎README.md‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,41 @@ Move this repository's CodeBoarding sync to the codeboarding/baseline analysis b
354354

355355
The first sync after the merge creates `codeboarding/baseline`, catching up from a saved analysis when there is one. To keep committing to the code branch instead, set `codeboarding_analysis_location: in_place`, as [above](#keep-the-analysis-on-the-code-branch).
356356

357+
## Problem history
358+
359+
Off by default. With `problem_history: 'true'` on the sync job, every sync (a push to the analysed branch) keeps a list of this repository's problems for the CodeBoarding Briefing: issues that report a bug, and merged changes that later needed a fix. Without it nothing is sent and nothing is written.
360+
361+
```yaml
362+
sync:
363+
if: github.event_name == 'push'
364+
runs-on: ubuntu-latest
365+
timeout-minutes: 60
366+
permissions:
367+
contents: write # also writes codeboarding/briefing
368+
actions: read # also reads merged pull requests' review artifacts
369+
issues: read
370+
pull-requests: read
371+
id-token: write
372+
steps:
373+
- uses: CodeBoarding/CodeBoarding-action@v1
374+
with:
375+
mode: sync
376+
llm: hosted
377+
problem_history: 'true'
378+
```
379+
380+
What is sent to `POST /v1/briefing` on `review_guide_url`, authenticated with the run's OIDC token (plus `license_key`, when set) and never with its `GITHUB_TOKEN`:
381+
382+
- **Issues**, never pull requests. The first run reads the open issues and those closed in the last 90 days, at most 1000 of each; later runs read those updated since, at most 1000, plus up to 100 stored open issues whose linked pull request is still open, taking turns when there are more. Later runs pick up what a limit skipped. For each: number, title, the first 2000 characters of the body, URL, state, open, close and update times, the author's login, bot flag and association, labels, assignees, the closing pull request, and linked pull requests (number, title, URL, state, draft, review decision, checks, author, last update, whether it closes the issue).
383+
- **Every open issue's number** (up to 5000), by the first update of each day (UTC), so the service can drop one that was deleted, transferred or made a discussion.
384+
- **Merged pull requests** into the analysed branch: the last 56 days on the first run, then those merged since, scanning at most the 1000 most recently updated. At most 500 a run, oldest first, so later runs read the rest. For each: number, title, URL, author, merge time, approvers and up to 300 changed paths. No code and no diffs.
385+
- **Architecture findings**: the `closed/architecture.json` from each one's newest successful CodeBoarding review artifact, for at most 40 merges per run plus 10 merged in the last 14 days (the artifact's retention) whose findings were not found yet. Only a review of this repository's own branch counts, never a fork's, and only when the artifact's `metadata.json` names that pull request. Artifacts over 50 MB are not downloaded, and neither file is read past 1 MB. Findings that would take the request over the service's size limit wait for a later run.
386+
- **The current problem list**, which the service updates and sends back. It keeps none of this.
387+
388+
What is written: one file, `problems.json`, on `codeboarding/briefing`, one commit per update (`Update problem history (<n> problems, through #<pr>)`) through the git data API. Like `codeboarding/baseline`, that branch is an orphan that is never merged and holds no workflow, so writing it runs nothing. It holds the last 56 days of merged pull requests, the issues above without their body (only the first sentence, and a `Priority:` line or CodeBoarding marker), High and Medium architecture findings, and the problems derived from them with a short status and priority history. The CodeBoarding web platform reads it from there.
389+
390+
The update runs after the baseline is saved, stops itself after 10 minutes and never fails the run: a missing permission, an unreachable service, a busy branch or a ruleset on `codeboarding/briefing` is a notice or warning in the log. Without `id-token: write` the update is skipped with a notice rather than sending the `GITHUB_TOKEN` in its place, since that token can write to this repository. `review_guide_url: ''` turns it off with the review features. Delete the branch to drop the history; the next sync starts it again.
391+
357392
## Inputs
358393

359394
| Input | Mode | Default | Description |
@@ -371,8 +406,9 @@ The first sync after the merge creates `codeboarding/baseline`, catching up from
371406
| `github_token` | both | `${{ github.token }}` | Token for comments and sync delivery. |
372407
| `codeboarding_analysis_location` | both | `codeboarding_branch` | Where the synced branch's analysis is stored: `codeboarding_branch` (on `codeboarding/baseline`, for the default branch; the code is never written) or `in_place` (committed as `.codeboarding/` on the synced branch). Sync saves it there and review reads it from there. |
373408
| `warmstart_retention_days` | review | `1` | Days to keep the reusable analysis. Only the next run reads it. |
374-
| `review_guide_url` | review | `https://jxivqwx4or6oip3krgdmdaiunm0iaybf.lambda-url.us-east-1.on.aws/` | Experimental. Shared base URL for `/v1/review-guide` and `/v1/architecture`. Saves `review_guide.json` and `closed/architecture.json` in the review artifact. Set to `''` to disable both. Never fails the run. |
409+
| `review_guide_url` | both | `https://jxivqwx4or6oip3krgdmdaiunm0iaybf.lambda-url.us-east-1.on.aws/` | Experimental. Shared base URL for `/v1/review-guide` and `/v1/architecture`, and for sync's `/v1/briefing` when `problem_history` is on. Saves `review_guide.json` and `closed/architecture.json` in the review artifact. Set to `''` to disable all three. Never fails the run. |
375410
| `closed_features_source` | review | `true` | Whether architecture checks may read this repository's source. Only the architecture request carries it, capped in size, and the service keeps nothing. The model sees code around a finding, never the tree. With `false`, source-dependent checks and model review do not run, and the result says so. |
411+
| `problem_history` | sync | `false` | Opt-in. With `'true'`, each sync sends this repository's issues and merged pull requests to `review_guide_url` and commits the returned problem list as `problems.json` on the orphan branch `codeboarding/briefing`. Needs `contents: write`, `issues: read`, `pull-requests: read`, `actions: read` and `id-token: write` on the sync job. See [Problem history](#problem-history). Never fails the run. |
376412

377413
`target_branch` and `sync_strategy` are deprecated, and read as the `codeboarding_analysis_location` they stand for, with a warning: `sync_strategy: push` as `in_place`, `sync_strategy: pull_request` as `codeboarding_branch`. `target_branch` is accepted only when it names the branch the run is on: the push trigger picks the branch. `force_full: true` is ignored with a warning. Anything the new input cannot express fails, linking to [moving an existing setup](#moving-an-existing-setup).
378414

‎action.yml‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,7 @@ inputs:
148148
Experimental. Service base URL for POST /v1/review-guide and POST /v1/architecture.
149149
Defaults to production. Both receive this run's analysis independently; results are stored
150150
as review_guide.json and closed/architecture.json. Set to an empty string to disable both.
151+
Sync's opt-in problem_history calls POST /v1/briefing on the same URL.
151152
required: false
152153
default: 'https://jxivqwx4or6oip3krgdmdaiunm0iaybf.lambda-url.us-east-1.on.aws/'
153154
closed_features_source:
@@ -158,6 +159,18 @@ inputs:
158159
With 'false' those checks and the model review do not run, and the result says so.
159160
required: false
160161
default: 'true'
162+
problem_history:
163+
description: >-
164+
Off by default: nothing is sent or written. When 'true', every sync run (a push to the
165+
analysed branch) sends this repository's issues and merged pull requests to the CodeBoarding
166+
service at review_guide_url, and commits the problem list it returns as problems.json on
167+
codeboarding/briefing, an orphan branch in this repository with one commit per update that is
168+
never merged and runs no workflow. The sync job then needs contents: write, issues: read,
169+
pull-requests: read, actions: read and id-token: write: the service is sent the run's OIDC
170+
token, never its GITHUB_TOKEN, and without id-token: write the update is skipped. It never
171+
fails the run.
172+
required: false
173+
default: 'false'
161174
github_token:
162175
description: 'Token used for comments and sync delivery.'
163176
required: false
@@ -571,6 +584,23 @@ runs:
571584
retention-days: 30
572585
if-no-files-found: ignore
573586

587+
# Opt-in; never fails the run. A composite step cannot set timeout-minutes (the runner rejects
588+
# the key), so the script stops itself after 10 minutes.
589+
- name: Update problem history
590+
id: problem_history
591+
if: steps.guard.outputs.skip != 'true' && steps.guard.outputs.mode == 'sync' && inputs.problem_history == 'true' && inputs.review_guide_url != ''
592+
continue-on-error: true
593+
shell: bash
594+
env:
595+
CLOSED_FUNCTIONS_URL: ${{ inputs.review_guide_url }}
596+
REPOSITORY: ${{ github.repository }}
597+
BRANCH: ${{ steps.guard.outputs.synced_branch }}
598+
PUSH_SHA: ${{ github.sha }}
599+
PUSH_BEFORE: ${{ github.event.before }}
600+
GITHUB_TOKEN: ${{ inputs.github_token }}
601+
LICENSE_KEY: ${{ inputs.license_key }}
602+
run: python3 "$GITHUB_ACTION_PATH/scripts/problem_history.py"
603+
574604
- name: Write sync summary
575605
if: always() && steps.guard.outputs.skip != 'true' && steps.guard.outputs.mode == 'sync'
576606
shell: bash

‎scripts/closed_features.py‎

Lines changed: 35 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -67,20 +67,40 @@ class Skip(Exception):
6767
"""A step that did not happen, for a reason worth one line in the log."""
6868

6969

70-
def _github(path: str, accept: str = "application/vnd.github+json") -> bytes:
71-
api = os.environ.get("GITHUB_API_URL", "https://api.github.com").rstrip("/")
70+
def _github(
71+
path: str,
72+
accept: str = "application/vnd.github+json",
73+
*,
74+
method: str = "GET",
75+
payload=None,
76+
api: str | None = None,
77+
token: str | None = None,
78+
timeout: int = 30,
79+
) -> bytes:
80+
"""A GitHub API call: `path` under `api` (default GITHUB_API_URL), or a full URL."""
81+
api = (api or os.environ.get("GITHUB_API_URL", "https://api.github.com")).rstrip("/")
7282
req = Request(
73-
f"{api}{path}",
83+
path if path.startswith("http") else f"{api}{path}",
84+
data=None if payload is None else json.dumps(payload).encode(),
85+
method=method,
7486
headers={
75-
"Authorization": f"Bearer {os.environ['GITHUB_TOKEN']}",
87+
"Authorization": f"Bearer {token or os.environ['GITHUB_TOKEN']}",
7688
"Accept": accept,
7789
"User-Agent": "codeboarding-action",
7890
},
7991
)
80-
with urlopen(req, timeout=30) as res: # nosec B310 - GitHub API URL
92+
with urlopen(req, timeout=timeout) as res: # nosec B310 - GitHub API URL
8193
return res.read()
8294

8395

96+
def _error_message(e: HTTPError) -> str:
97+
"""The `message` of an error answer's JSON body, or "" when it has none."""
98+
try:
99+
return str(json.loads(e.read()).get("message") or "")
100+
except (ValueError, AttributeError, OSError):
101+
return ""
102+
103+
84104
def _github_json(path: str):
85105
return json.loads(_github(path))
86106

@@ -308,37 +328,37 @@ def _no_architecture(ctx: dict, status: str, reason: str) -> dict:
308328
}
309329

310330

311-
def _post(url: str, body: bytes, headers: dict[str, str]) -> dict:
331+
def _post(url: str, body: bytes, headers: dict[str, str], timeout: int = 600) -> dict:
312332
req = Request(
313333
url,
314334
data=body,
315335
headers={**headers, "Content-Type": "application/gzip", "User-Agent": "codeboarding-action"},
316336
method="POST",
317337
)
318338
try:
319-
with urlopen(req, timeout=600) as res: # nosec B310 - service URL from workflow configuration
339+
with urlopen(req, timeout=timeout) as res: # nosec B310 - service URL from workflow configuration
320340
return json.loads(res.read())
321341
except HTTPError as e:
322-
try:
323-
message = json.loads(e.read()).get("message") or e.reason
324-
except (ValueError, AttributeError):
325-
message = e.reason
326-
reason = f"the service answered {e.code}: {message}"
342+
reason = f"the service answered {e.code}: {_error_message(e) or e.reason}"
327343
if e.code == 402:
328344
raise Skip(reason) from e
329345
raise RuntimeError(reason) from e
330346

331347

348+
def _gzip(body: dict) -> bytes:
349+
return gzip.compress(json.dumps(body).encode(), compresslevel=9)
350+
351+
332352
def _pack(ctx: dict, files: dict[str, str], omitted: dict[str, str]) -> bytes:
333353
body = {"version": 1, "repo": ctx["repo"], "pr": ctx["pr"], "files": files}
334354
if omitted:
335355
body["omitted"] = omitted
336-
return gzip.compress(json.dumps(body).encode(), compresslevel=9)
356+
return _gzip(body)
337357

338358

339-
def _check_size(data: bytes) -> None:
359+
def _check_size(data: bytes, what: str = "bundle") -> None:
340360
if len(data) > MAX_BUNDLE_BYTES:
341-
raise Skip(f"its bundle is {len(data) / 1e6:.1f} MB, over the service's limit")
361+
raise Skip(f"its {what} is {len(data) / 1e6:.1f} MB, over the service's limit")
342362

343363

344364
def run_review_guide(base: str, ctx: dict, inputs: dict, headers: dict, artifact: Path) -> None:

0 commit comments

Comments
 (0)