vouchington-tooling 0.88.0 → 1.0.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 (64) hide show
  1. package/README.md +1 -8
  2. package/dist/agent-blackboard/feedback-journal-audit.mjs +14 -6
  3. package/dist/agent-blackboard/feedback-journal-sandbox.d.mts +4 -2
  4. package/dist/agent-blackboard/feedback-journal-sandbox.mjs +14 -6
  5. package/dist/audit-journal/audit-block.d.mts +2 -0
  6. package/dist/audit-journal/audit-block.mjs +13 -8
  7. package/dist/audit-journal/ci-failures.d.mts +6 -2
  8. package/dist/audit-journal/ci-failures.mjs +12 -6
  9. package/dist/audit-journal/journal.d.mts +2 -0
  10. package/dist/audit-journal/journal.mjs +18 -3
  11. package/dist/audit-journal/scope.d.mts +25 -0
  12. package/dist/audit-journal/scope.mjs +47 -0
  13. package/dist/audit-journal/types.d.mts +3 -0
  14. package/dist/cli/index.mjs +0 -6
  15. package/dist/cli/parse-forwarded-commands.d.mts +1 -1
  16. package/dist/cli/parse-forwarded-commands.mjs +0 -2
  17. package/dist/cli/parse.d.mts +1 -7
  18. package/dist/cli/parse.mjs +0 -1
  19. package/dist/cli/script-paths.mjs +0 -1
  20. package/dist/cli/usage-text.d.mts +1 -1
  21. package/dist/cli/usage-text.mjs +0 -6
  22. package/dist/gh-cli/exec.d.mts +8 -2
  23. package/dist/gh-cli/exec.mjs +3 -3
  24. package/dist/gha-review-payload/index.d.mts +0 -2
  25. package/dist/gha-review-payload/index.mjs +0 -1
  26. package/dist/index.d.mts +2 -8
  27. package/dist/index.mjs +1 -4
  28. package/dist/mcp-server/pr-diff-size.d.mts +16 -0
  29. package/dist/mcp-server/pr-diff-size.mjs +49 -0
  30. package/dist/mcp-server/pr-live.d.mts +3 -0
  31. package/dist/mcp-server/pr-live.mjs +8 -2
  32. package/dist/mcp-server/pr-prepare.mjs +3 -1
  33. package/dist/mcp-server/worktree.mjs +1 -1
  34. package/docs/mcp-server.md +20 -3
  35. package/package.json +1 -16
  36. package/scripts/__pycache__/run_bounded_process.cpython-314.pyc +0 -0
  37. package/skills/retrospective/SKILL.md +2 -1
  38. package/dist/gha-check-run/cli.d.mts +0 -2
  39. package/dist/gha-check-run/cli.mjs +0 -81
  40. package/dist/gha-check-run/github.d.mts +0 -30
  41. package/dist/gha-check-run/github.mjs +0 -63
  42. package/dist/gha-check-run/index.d.mts +0 -2
  43. package/dist/gha-check-run/index.mjs +0 -2
  44. package/dist/gha-claude-post-review/index.d.mts +0 -3
  45. package/dist/gha-claude-post-review/index.mjs +0 -2
  46. package/dist/gha-post-review/claude-token.d.mts +0 -25
  47. package/dist/gha-post-review/claude-token.mjs +0 -109
  48. package/dist/gha-post-review/cli.d.mts +0 -1
  49. package/dist/gha-post-review/cli.mjs +0 -22
  50. package/dist/gha-post-review/github.d.mts +0 -13
  51. package/dist/gha-post-review/github.mjs +0 -58
  52. package/dist/gha-post-review/index.d.mts +0 -13
  53. package/dist/gha-post-review/index.mjs +0 -8
  54. package/dist/gha-post-review/post.d.mts +0 -24
  55. package/dist/gha-post-review/post.mjs +0 -39
  56. package/dist/gha-post-review/pull-io.d.mts +0 -13
  57. package/dist/gha-post-review/pull-io.mjs +0 -88
  58. package/dist/gha-post-review/token.d.mts +0 -9
  59. package/dist/gha-post-review/token.mjs +0 -21
  60. package/dist/gha-review-payload/cli.d.mts +0 -1
  61. package/dist/gha-review-payload/cli.mjs +0 -24
  62. package/dist/gha-review-payload/file.d.mts +0 -7
  63. package/dist/gha-review-payload/file.mjs +0 -62
  64. package/scripts/gha/materialize-pr-context.sh +0 -123
@@ -1,4 +1,3 @@
1
1
  export { MAX_REVIEW_COMMENTS, MAX_REVIEW_PAYLOAD_BYTES, ReviewPayloadError, parseReviewPayload, reviewCommentSubject, } from "./payload.mjs";
2
2
  export { indexReviewFiles, parsePatchCommentable, parseReviewFilesJson } from "./diff.mjs";
3
3
  export { nearestReviewLine, placeReviewComment, remapReviewComments, rewriteSnappedSuggestion, snapReviewNote, } from "./remap.mjs";
4
- export { readRegularReviewPayload, stageReviewPayload, writeStagedOutput } from "./file.mjs";
package/dist/index.d.mts CHANGED
@@ -68,14 +68,8 @@ export { MissingResponseBodyError, readResponseBody, readResponseBodyAsBuffer, R
68
68
  export type { ReadResponseBodyOptions } from './http-body/index.mts';
69
69
  export { parseAstGrepRuleArgs, runAstGrepRule } from './ast-grep-rule/index.mts';
70
70
  export type { AstGrepRuleInvocation, RunAstGrepRuleOptions } from './ast-grep-rule/index.mts';
71
- export { indexReviewFiles, MAX_REVIEW_COMMENTS, MAX_REVIEW_PAYLOAD_BYTES, nearestReviewLine, parsePatchCommentable, parseReviewFilesJson, parseReviewPayload, readRegularReviewPayload, remapReviewComments, ReviewPayloadError, reviewCommentSubject, rewriteSnappedSuggestion, snapReviewNote, stageReviewPayload, writeStagedOutput, } from './gha-review-payload/index.mts';
72
- export type { CommentableIndex, CommentableLine, LineKind, PayloadRequirement, ReviewComment, ReviewFile, ReviewSide, SanitizedReview, } from './gha-review-payload/index.mts';
73
- export { PostReviewError, requireEnv, runPostReview, runPostReviewCli, postReviewWithTokenFromEnv, } from './gha-post-review/index.mts';
74
- export type { PostResult, PostReviewIo, PullFile } from './gha-post-review/index.mts';
75
- /** @deprecated Import Claude helpers from vouchington-tooling/gha-claude-post-review. */
76
- export { CLAUDE_OIDC_AUDIENCE, createActionsClaudeTokenIo, mintClaudeAppToken, resolveReviewPostToken, revokeClaudeAppToken, withClaudeAppToken, } from './gha-post-review/index.mts';
77
- /** @deprecated Import Claude helpers from vouchington-tooling/gha-claude-post-review. */
78
- export type { ClaudeTokenIo, ReviewPostToken } from './gha-post-review/index.mts';
71
+ export { indexReviewFiles, MAX_REVIEW_COMMENTS, MAX_REVIEW_PAYLOAD_BYTES, nearestReviewLine, parsePatchCommentable, parseReviewFilesJson, parseReviewPayload, remapReviewComments, ReviewPayloadError, reviewCommentSubject, rewriteSnappedSuggestion, snapReviewNote, } from './gha-review-payload/index.mts';
72
+ export type { CommentableIndex, CommentableLine, LineKind, ReviewComment, ReviewFile, ReviewSide, SanitizedReview, } from './gha-review-payload/index.mts';
79
73
  export { nextPageCursorFromLinkHeader, nextPageUrlFromLinkHeader, validatePaginationRequestUrl, } from './http-link-pagination/index.mts';
80
74
  export { cmdDownloadCoverage, cmdDownloadVitestBlobs, cmdUpload, mintPresignedControl, transportObjectKeys, } from './coverage-transport/index.mts';
81
75
  export type { ExpectedTransportIdentity, ObjectSigner, PresignIdentity, TransportControl, } from './coverage-transport/index.mts';
package/dist/index.mjs CHANGED
@@ -36,10 +36,7 @@ export { decide, deriveRetryAttempt } from "./transient-retry/index.mjs";
36
36
  export { escapeSpreadsheetFormula, parseCsvRows, streamCsvRows, stripCsvBom } from "./csv/index.mjs";
37
37
  export { MissingResponseBodyError, readResponseBody, readResponseBodyAsBuffer, ResponseBodyTooLargeError, } from "./http-body/index.mjs";
38
38
  export { parseAstGrepRuleArgs, runAstGrepRule } from "./ast-grep-rule/index.mjs";
39
- export { indexReviewFiles, MAX_REVIEW_COMMENTS, MAX_REVIEW_PAYLOAD_BYTES, nearestReviewLine, parsePatchCommentable, parseReviewFilesJson, parseReviewPayload, readRegularReviewPayload, remapReviewComments, ReviewPayloadError, reviewCommentSubject, rewriteSnappedSuggestion, snapReviewNote, stageReviewPayload, writeStagedOutput, } from "./gha-review-payload/index.mjs";
40
- export { PostReviewError, requireEnv, runPostReview, runPostReviewCli, postReviewWithTokenFromEnv, } from "./gha-post-review/index.mjs";
41
- /** @deprecated Import Claude helpers from vouchington-tooling/gha-claude-post-review. */
42
- export { CLAUDE_OIDC_AUDIENCE, createActionsClaudeTokenIo, mintClaudeAppToken, resolveReviewPostToken, revokeClaudeAppToken, withClaudeAppToken, } from "./gha-post-review/index.mjs";
39
+ export { indexReviewFiles, MAX_REVIEW_COMMENTS, MAX_REVIEW_PAYLOAD_BYTES, nearestReviewLine, parsePatchCommentable, parseReviewFilesJson, parseReviewPayload, remapReviewComments, ReviewPayloadError, reviewCommentSubject, rewriteSnappedSuggestion, snapReviewNote, } from "./gha-review-payload/index.mjs";
43
40
  export { nextPageCursorFromLinkHeader, nextPageUrlFromLinkHeader, validatePaginationRequestUrl, } from "./http-link-pagination/index.mjs";
44
41
  export { cmdDownloadCoverage, cmdDownloadVitestBlobs, cmdUpload, mintPresignedControl, transportObjectKeys, } from "./coverage-transport/index.mjs";
45
42
  export { EPOCH_PRUNED_AT, normalizeDeployedLayer, pruneDeployedRuntimeDeps, restoreDeployedWorkspacePackages, } from "./pnpm-deploy/index.mjs";
@@ -0,0 +1,16 @@
1
+ import type { RunTextCommand } from '../gh-cli/exec.mts';
2
+ import type { LivePullRequest } from './pr-live.mts';
3
+ /** What the policy's `validatePullRequest` learns about the size of the change. */
4
+ export type DiffSize = {
5
+ additions: number;
6
+ deletions: number;
7
+ changedFiles: number;
8
+ source: 'github' | 'git';
9
+ } | {
10
+ unavailable: string;
11
+ };
12
+ export declare const DIFF_MAX_OUTPUT: number;
13
+ /** Sums `git diff --numstat` output; a binary file (`-`) counts as a file with no lines. */
14
+ export declare function parseNumstat(output: string): DiffSize;
15
+ /** GitHub's own counts for a live pull request, else the local numstat. Never throws. */
16
+ export declare function diffFor(git: RunTextCommand, live: LivePullRequest | undefined, base: string): Promise<DiffSize>;
@@ -0,0 +1,49 @@
1
+ /** The longest the local diff may run, and the most numstat output it may produce. */
2
+ const DIFF_TIMEOUT_MS = 30_000;
3
+ export const DIFF_MAX_OUTPUT = 1024 * 1024;
4
+ /** Sums `git diff --numstat` output; a binary file (`-`) counts as a file with no lines. */
5
+ export function parseNumstat(output) {
6
+ let additions = 0;
7
+ let deletions = 0;
8
+ let changedFiles = 0;
9
+ for (const line of output.split('\n')) {
10
+ if (line === '')
11
+ continue;
12
+ const [added, removed] = line.split('\t');
13
+ changedFiles += 1;
14
+ additions += Number(added) || 0;
15
+ deletions += Number(removed) || 0;
16
+ }
17
+ return { additions, deletions, changedFiles, source: 'git' };
18
+ }
19
+ /** execFile kills the child on its timeout (`killed`, with a signal) and fails on a full buffer. */
20
+ function failureReason(error, base) {
21
+ const { killed, code } = (error ?? {});
22
+ if (killed === true)
23
+ return 'git diff timed out';
24
+ if (code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER')
25
+ return 'git diff output too large';
26
+ return `git diff origin/${base}...HEAD failed`;
27
+ }
28
+ /** The change a pull request with no live counterpart would carry: `origin/<base>...HEAD`. */
29
+ async function localDiff(git, base) {
30
+ try {
31
+ const output = await git(['diff', '--numstat', '--no-ext-diff', `origin/${base}...HEAD`, '--'], {
32
+ timeout: DIFF_TIMEOUT_MS,
33
+ maxBuffer: DIFF_MAX_OUTPUT,
34
+ });
35
+ if (output.length > DIFF_MAX_OUTPUT)
36
+ return { unavailable: 'git diff output too large' };
37
+ return parseNumstat(output);
38
+ }
39
+ catch (error) {
40
+ return { unavailable: failureReason(error, base) };
41
+ }
42
+ }
43
+ /** GitHub's own counts for a live pull request, else the local numstat. Never throws. */
44
+ export async function diffFor(git, live, base) {
45
+ if (live === undefined)
46
+ return localDiff(git, base);
47
+ const { additions, deletions, changedFiles } = live;
48
+ return { additions, deletions, changedFiles, source: 'github' };
49
+ }
@@ -5,6 +5,9 @@ export type LivePullRequest = {
5
5
  headRefOid: string;
6
6
  baseRefName: string;
7
7
  state: string;
8
+ additions: number;
9
+ deletions: number;
10
+ changedFiles: number;
8
11
  };
9
12
  /** The live pull request as gh reports it, whatever its state. */
10
13
  export declare function readLivePullRequest(gh: RunTextCommand, pr: number): Promise<LivePullRequest>;
@@ -1,5 +1,7 @@
1
1
  import { findShepherdJournal } from "./pr-journal.mjs";
2
- const FIELDS = ['body', 'headRefName', 'headRefOid', 'baseRefName', 'state'];
2
+ const TEXT_FIELDS = ['body', 'headRefName', 'headRefOid', 'baseRefName', 'state'];
3
+ const COUNT_FIELDS = ['additions', 'deletions', 'changedFiles'];
4
+ const FIELDS = [...TEXT_FIELDS, ...COUNT_FIELDS];
3
5
  /** The live pull request as gh reports it, whatever its state. */
4
6
  export async function readLivePullRequest(gh, pr) {
5
7
  const output = await gh(['pr', 'view', String(pr), '--json', FIELDS.join(',')]);
@@ -17,7 +19,11 @@ export async function livePullRequest(gh, pr) {
17
19
  return live;
18
20
  }
19
21
  function isLive(value) {
20
- return FIELDS.every((field) => typeof value?.[field] === 'string');
22
+ return (TEXT_FIELDS.every((field) => typeof value?.[field] === 'string') &&
23
+ COUNT_FIELDS.every((field) => {
24
+ const count = value?.[field];
25
+ return typeof count === 'number' && Number.isSafeInteger(count) && count >= 0;
26
+ }));
21
27
  }
22
28
  /**
23
29
  * The base to validate an existing pull request against: its live base. An explicit `base` that
@@ -7,11 +7,12 @@ import { createGhRunner, ghEnvironment } from "./pr-gh.mjs";
7
7
  import { checkTitleLength, readPullRequestInput } from "./pr-input.mjs";
8
8
  import { preserveShepherdJournal } from "./pr-journal.mjs";
9
9
  import { credentials, liveBase, livePullRequest, readLivePullRequest, redactCredentials, } from "./pr-live.mjs";
10
+ import { diffFor } from "./pr-diff-size.mjs";
10
11
  import { noSourceStatement } from "./pr-no-source.mjs";
11
12
  import { runValidator } from "./policy-run.mjs";
12
13
  import { parseWorktreeList } from "./worktree.mjs";
13
14
  export function gitIn(context) {
14
- return (args) => context.runGit(['-C', context.worktree, ...args]);
15
+ return (args, limits) => context.runGit(['-C', context.worktree, ...args], limits);
15
16
  }
16
17
  export function ghIn(context) {
17
18
  const run = context.runGh ?? createGhRunner(context.env);
@@ -115,6 +116,7 @@ export async function prepare(args, context, kind, pr) {
115
116
  mode: input.mode,
116
117
  ...(input.noSourceIssue === undefined ? {} : { noSourceIssue: input.noSourceIssue }),
117
118
  ...(pr === undefined ? {} : { pr }),
119
+ diff: await diffFor(git, live, input.base),
118
120
  },
119
121
  });
120
122
  const errors = 'errors' in report ? report.errors : [];
@@ -13,7 +13,7 @@ export function isolatedGitEnv() {
13
13
  const { LANGUAGE: _language, ...env } = gitEnv();
14
14
  return { ...env, LC_ALL: 'C' };
15
15
  }
16
- export const runIsolatedGit = createCommandRunner('git', (command, args) => execFileAsync(command, args, { env: isolatedGitEnv() }));
16
+ export const runIsolatedGit = createCommandRunner('git', (command, args, options) => execFileAsync(command, args, { ...options, env: isolatedGitEnv() }));
17
17
  async function canonical(path) {
18
18
  try {
19
19
  return await realpath(path);
@@ -296,7 +296,11 @@ sessionId>` when that would exceed 256 bytes. Re-saving identical content return
296
296
  stored receipt and timestamp. Changed content under the same `sourceEventId` is an
297
297
  `event-conflict`; a revision needs a new `sourceEventId`. `compose` regenerates the document from
298
298
  the live journal and repository, so repeating a `compose` call is not a retry: when an interactive
299
- save is retained in the outbox, deliver it with `outbox_flush`.
299
+ save is retained in the outbox, deliver it with `outbox_flush`. The CI Failures and Sandbox &
300
+ Permission Audit sections use only the journal entries created after the session's newest earlier
301
+ retrospective (by the blackboard's `createdAt`), and each section with excluded blocks adds an
302
+ `Excluded: N blocks from before retrospective <sourceEventId>` line; a revision keeps its own
303
+ blocks because the boundary is the newest retrospective older than the newest block.
300
304
 
301
305
  ### Policy module
302
306
 
@@ -322,7 +326,7 @@ whole process group is killed, so nothing it started outlives the call. The runn
322
326
  | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | ------- |
323
327
  | `validateRetrospective` | `sessionId`, `parentSessionId`, `mode`, `workOutcome`, `feedbackCoverage`, `repositories`, `markdown`, `sourceEventId`, `metadata` (`date`, `issues`, `prs`, `description`) | `{ errors: string[], warnings?: string[] }` | 30 s |
324
328
  | `pullRequestDefaults` | `{}` from `retrospective_save`; `{ title, base, relatedIssues }` from `pr_create` | `{ repositories?, labels?, milestone?, project? }` (an object) | 120 s |
325
- | `validatePullRequest` | `title`, `body`, `base`, `head`, the trusted `mode`, `noSourceIssue` when given, and `pr` when set | `{ errors: string[], warnings?: string[] }` | 120 s |
329
+ | `validatePullRequest` | `title`, `body`, `base`, `head`, the trusted `mode`, `noSourceIssue` when given, `pr` when set, and `diff` (see below) | `{ errors: string[], warnings?: string[] }` | 120 s |
326
330
 
327
331
  Any `errors` reject the save and write nothing. A non-zero exit, a timeout (reported as
328
332
  `policy <export> timed out after <N>s`), output over 1 MB, malformed JSON, or a result of the wrong
@@ -367,6 +371,19 @@ that launched the server: `CODEX_THREAD_ID` (codex), `CLAUDECODE=1` or `CLAUDE_C
367
371
  is derivable the line says `unknown`. Making `agent` optional is compatible with existing callers,
368
372
  which may keep sending it.
369
373
 
374
+ ### Change size for the validator
375
+
376
+ `validatePullRequest` receives `diff`, so a policy can bound the size of a change. It is
377
+ `{ additions, deletions, changedFiles, source }` or `{ unavailable: reason }`. With a live pull
378
+ request (`pr_update`, and `pr_validate` with `pr`) the counts are GitHub's own for that pull
379
+ request, read in the same `gh pr view` as the body (`source: 'github'`), so they are right even
380
+ when the worktree is on another commit; a live count that is not a non-negative integer rejects the
381
+ call. Without one (`pr_create`, and `pr_validate` without `pr`) the server runs
382
+ `git diff --numstat --no-ext-diff origin/<base>...HEAD --` in the worktree and sums it
383
+ (`source: 'git'`; a binary file counts as a file with no lines). That git call is limited to 30 s and
384
+ 1 MiB of output; when it fails, times out, overflows, or `origin/<base>` is not fetched, `diff` is
385
+ `{ unavailable }` and the call still succeeds.
386
+
370
387
  ### Pull requests with no source issue
371
388
 
372
389
  Pass `noSourceIssue: { reason }` (a single line) with an empty `relatedIssues`, or with a
@@ -423,7 +440,7 @@ with the repository's stack tooling instead.
423
440
  ### Tools
424
441
 
425
442
  - `pr_validate` (read-only): renders the body, runs the policy `validatePullRequest({ title, body,
426
- base, head, mode, noSourceIssue?, pr? })` export and returns `{ ok, body, errors, warnings }`. Blocking errors do not fail the tool call: callers must
443
+ base, head, mode, noSourceIssue?, pr?, diff })` export and returns `{ ok, body, errors, warnings }`. Blocking errors do not fail the tool call: callers must
427
444
  check `ok` (true only when `errors` is empty) or `errors`. With
428
445
  `pr`, the live body is read (never written) so its Shepherd Journal is preserved as in
429
446
  `pr_update`. The liveness checks of `pr_update` do not apply: any state (merged or closed
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vouchington-tooling",
3
- "version": "0.88.0",
3
+ "version": "1.0.0",
4
4
  "description": "Vouchington CLI and extractable tooling libraries.",
5
5
  "homepage": "https://github.com/vouchington/vouchington-tooling/tree/main/packages/vouchington-tooling#readme",
6
6
  "bugs": {
@@ -256,21 +256,6 @@
256
256
  "import": "./dist/gha-review-payload/index.mjs",
257
257
  "default": "./dist/gha-review-payload/index.mjs"
258
258
  },
259
- "./gha-post-review": {
260
- "types": "./dist/gha-post-review/index.d.mts",
261
- "import": "./dist/gha-post-review/index.mjs",
262
- "default": "./dist/gha-post-review/index.mjs"
263
- },
264
- "./gha-claude-post-review": {
265
- "types": "./dist/gha-claude-post-review/index.d.mts",
266
- "import": "./dist/gha-claude-post-review/index.mjs",
267
- "default": "./dist/gha-claude-post-review/index.mjs"
268
- },
269
- "./gha-check-run": {
270
- "types": "./dist/gha-check-run/index.d.mts",
271
- "import": "./dist/gha-check-run/index.mjs",
272
- "default": "./dist/gha-check-run/index.mjs"
273
- },
274
259
  "./provider-replay": {
275
260
  "types": "./dist/provider-replay/index.d.mts",
276
261
  "import": "./dist/provider-replay/index.mjs",
@@ -28,7 +28,8 @@ answer is `unknown — no journal`, never a guess.
28
28
  `feedbackCoverage`, and `repositories`. Pass `compose.transcript.harnessSessionId` whenever the
29
29
  harness session id differs from the call's `sessionId`. The composer builds the CI failures and
30
30
  sandbox audit sections from the session's hosted journal entries alone, so do not rerun
31
- collectors to fill them. A session unknown to the journal reports both as unavailable, not as
31
+ collectors to fill them. Both sections cover only journal entries created after the session's
32
+ newest earlier retrospective and say how many earlier blocks were excluded. A session unknown to the journal reports both as unavailable, not as
32
33
  none observed. Put sensitive values only in
33
34
  `compose.knownSensitiveValues`, or `knownSensitiveValues` for a markdown save. Keep exact factual
34
35
  section markers generated, preserve unavailable counts, and never replace missing evidence with
@@ -1,2 +0,0 @@
1
- import { type GhExec } from '../gha-post-review/github.mts';
2
- export declare function runCheckRunCli(argv?: readonly string[], env?: NodeJS.ProcessEnv, exec?: GhExec): number;
@@ -1,81 +0,0 @@
1
- import { appendFileSync } from 'node:fs';
2
- import { fileURLToPath } from 'node:url';
3
- import { createGhExec } from "../gha-post-review/github.mjs";
4
- import { completeCheckRun, createCheckRun, CheckRunError, } from "./github.mjs";
5
- function requireEnv(name, env) {
6
- const value = env[name];
7
- if (!value)
8
- throw new CheckRunError(`${name} is required.`);
9
- return value;
10
- }
11
- function parseStatus(value) {
12
- if (value !== 'in_progress' && value !== 'completed') {
13
- throw new CheckRunError(`STATUS must be "in_progress" or "completed" (got "${value}").`);
14
- }
15
- return value;
16
- }
17
- function parseConclusion(value) {
18
- if (value !== 'success' && value !== 'neutral') {
19
- throw new CheckRunError(`CONCLUSION must be "success" or "neutral" (got "${value}").`);
20
- }
21
- return value;
22
- }
23
- function appendOutput(name, value, outputPath) {
24
- if (!outputPath)
25
- return;
26
- appendFileSync(outputPath, `${name}=${value}\n`);
27
- }
28
- /** Builds a create-check-run input from env, requiring CONCLUSION only when STATUS is completed. */
29
- function readCreateInput(env) {
30
- const status = parseStatus(requireEnv('STATUS', env));
31
- const shared = {
32
- repository: requireEnv('GITHUB_REPOSITORY', env),
33
- name: requireEnv('CHECK_NAME', env),
34
- headSha: requireEnv('HEAD_SHA', env),
35
- title: requireEnv('TITLE', env),
36
- summary: requireEnv('SUMMARY', env),
37
- };
38
- if (status === 'completed') {
39
- return { ...shared, status, conclusion: parseConclusion(requireEnv('CONCLUSION', env)) };
40
- }
41
- return { ...shared, status };
42
- }
43
- function runCreate(env, exec) {
44
- const id = createCheckRun(readCreateInput(env), exec);
45
- appendOutput('check_run_id', id, env.GITHUB_OUTPUT);
46
- }
47
- /** No-ops when CHECK_RUN_ID is unset: the create step may have already finalized the check. */
48
- function runComplete(env, exec) {
49
- const checkRunId = env.CHECK_RUN_ID ?? '';
50
- if (checkRunId === '')
51
- return;
52
- completeCheckRun({
53
- repository: requireEnv('GITHUB_REPOSITORY', env),
54
- checkRunId,
55
- conclusion: parseConclusion(requireEnv('CONCLUSION', env)),
56
- title: requireEnv('TITLE', env),
57
- summary: requireEnv('SUMMARY', env),
58
- }, exec);
59
- }
60
- export function runCheckRunCli(argv = process.argv, env = process.env, exec = createGhExec()) {
61
- const subcommand = argv[2];
62
- try {
63
- if (subcommand === 'create') {
64
- runCreate(env, exec);
65
- return 0;
66
- }
67
- if (subcommand === 'complete') {
68
- runComplete(env, exec);
69
- return 0;
70
- }
71
- throw new CheckRunError(`Unknown subcommand "${String(subcommand)}". Use create or complete.`);
72
- }
73
- catch (error) {
74
- process.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`);
75
- return 1;
76
- }
77
- }
78
- /* v8 ignore next 3 */
79
- if (process.argv[1] === fileURLToPath(import.meta.url)) {
80
- process.exitCode = runCheckRunCli();
81
- }
@@ -1,30 +0,0 @@
1
- import type { GhExec } from '../gha-post-review/github.mts';
2
- export declare class CheckRunError extends Error {
3
- constructor(message: string);
4
- }
5
- export type CheckRunStatus = 'in_progress' | 'completed';
6
- export type CheckRunConclusion = 'success' | 'neutral';
7
- export type CreateCheckRunInput = {
8
- repository: string;
9
- name: string;
10
- headSha: string;
11
- title: string;
12
- summary: string;
13
- } & ({
14
- status: 'in_progress';
15
- conclusion?: undefined;
16
- } | {
17
- status: 'completed';
18
- conclusion: CheckRunConclusion;
19
- });
20
- export type CompleteCheckRunInput = {
21
- repository: string;
22
- checkRunId: string;
23
- conclusion: CheckRunConclusion;
24
- title: string;
25
- summary: string;
26
- };
27
- /** Creates a GitHub check run, returning the API-assigned check run id. */
28
- export declare function createCheckRun(input: CreateCheckRunInput, exec: GhExec): string;
29
- /** Transitions an existing check run to `completed` with a final conclusion. */
30
- export declare function completeCheckRun(input: CompleteCheckRunInput, exec: GhExec): void;
@@ -1,63 +0,0 @@
1
- export class CheckRunError extends Error {
2
- constructor(message) {
3
- super(message);
4
- this.name = 'CheckRunError';
5
- }
6
- }
7
- function isFullCommitSha(value) {
8
- return /^[0-9a-f]{40}$/u.test(value);
9
- }
10
- function isCheckRunId(value) {
11
- return /^[0-9]+$/u.test(value);
12
- }
13
- function parseCheckRunId(raw) {
14
- let parsed;
15
- try {
16
- parsed = JSON.parse(raw);
17
- }
18
- catch {
19
- throw new CheckRunError('Check run creation response was not valid JSON.');
20
- }
21
- const id = parsed !== null && typeof parsed === 'object' ? parsed.id : undefined;
22
- if (typeof id !== 'number' && typeof id !== 'string') {
23
- throw new CheckRunError('Check run creation response did not include an id.');
24
- }
25
- return String(id);
26
- }
27
- /** Creates a GitHub check run, returning the API-assigned check run id. */
28
- export function createCheckRun(input, exec) {
29
- if (!isFullCommitSha(input.headSha)) {
30
- throw new CheckRunError('headSha must be a full lowercase 40-character commit SHA.');
31
- }
32
- const body = {
33
- name: input.name,
34
- head_sha: input.headSha,
35
- status: input.status,
36
- output: { title: input.title, summary: input.summary },
37
- };
38
- if (input.status === 'completed')
39
- body.conclusion = input.conclusion;
40
- const raw = exec(['api', '--method', 'POST', `repos/${input.repository}/check-runs`, '--input', '-'], {
41
- input: JSON.stringify(body),
42
- });
43
- return parseCheckRunId(raw);
44
- }
45
- /** Transitions an existing check run to `completed` with a final conclusion. */
46
- export function completeCheckRun(input, exec) {
47
- if (!isCheckRunId(input.checkRunId)) {
48
- throw new CheckRunError('checkRunId must be a positive integer.');
49
- }
50
- const body = {
51
- status: 'completed',
52
- conclusion: input.conclusion,
53
- output: { title: input.title, summary: input.summary },
54
- };
55
- exec([
56
- 'api',
57
- '--method',
58
- 'PATCH',
59
- `repos/${input.repository}/check-runs/${input.checkRunId}`,
60
- '--input',
61
- '-',
62
- ], { input: JSON.stringify(body) });
63
- }
@@ -1,2 +0,0 @@
1
- export { CheckRunError, completeCheckRun, createCheckRun, type CheckRunConclusion, type CheckRunStatus, type CompleteCheckRunInput, type CreateCheckRunInput, } from './github.mts';
2
- export { runCheckRunCli } from './cli.mts';
@@ -1,2 +0,0 @@
1
- export { CheckRunError, completeCheckRun, createCheckRun, } from "./github.mjs";
2
- export { runCheckRunCli } from "./cli.mjs";
@@ -1,3 +0,0 @@
1
- export { CLAUDE_APP_TOKEN_EXCHANGE_URL, CLAUDE_OIDC_AUDIENCE, CLAUDE_POSTER_PERMISSIONS, GITHUB_INSTALLATION_TOKEN_URL, createActionsClaudeTokenIo, mintClaudeAppToken, oidcTokenRequest, revokeClaudeAppToken, withClaudeAppToken, } from '../gha-post-review/claude-token.mts';
2
- export type { ClaudeTokenIo, FetchLike } from '../gha-post-review/claude-token.mts';
3
- export { postClaudeReviewFromEnv } from '../gha-post-review/github.mts';
@@ -1,2 +0,0 @@
1
- export { CLAUDE_APP_TOKEN_EXCHANGE_URL, CLAUDE_OIDC_AUDIENCE, CLAUDE_POSTER_PERMISSIONS, GITHUB_INSTALLATION_TOKEN_URL, createActionsClaudeTokenIo, mintClaudeAppToken, oidcTokenRequest, revokeClaudeAppToken, withClaudeAppToken, } from "../gha-post-review/claude-token.mjs";
2
- export { postClaudeReviewFromEnv } from "../gha-post-review/github.mjs";
@@ -1,25 +0,0 @@
1
- export declare const CLAUDE_OIDC_AUDIENCE = "claude-code-github-action";
2
- export declare const CLAUDE_APP_TOKEN_EXCHANGE_URL = "https://api.anthropic.com/api/github/github-app-token-exchange";
3
- export declare const CLAUDE_POSTER_PERMISSIONS: {
4
- readonly contents: "read";
5
- readonly pull_requests: "write";
6
- };
7
- export declare const GITHUB_INSTALLATION_TOKEN_URL = "https://api.github.com/installation/token";
8
- export type FetchLike = (url: string, init: RequestInit) => Promise<{
9
- ok: boolean;
10
- status: number;
11
- json(): Promise<unknown>;
12
- }>;
13
- export type ClaudeTokenIo = {
14
- getOidcToken(): Promise<string>;
15
- fetch: FetchLike;
16
- mask(token: string): void;
17
- };
18
- export declare function oidcTokenRequest(env: NodeJS.ProcessEnv): {
19
- url: string;
20
- token: string;
21
- };
22
- export declare function mintClaudeAppToken(io: ClaudeTokenIo): Promise<string>;
23
- export declare function revokeClaudeAppToken(token: string, io: Pick<ClaudeTokenIo, 'fetch'>): Promise<void>;
24
- export declare function withClaudeAppToken<T>(io: ClaudeTokenIo, fn: (token: string) => T | Promise<T>): Promise<T>;
25
- export declare function createActionsClaudeTokenIo(env?: NodeJS.ProcessEnv, fetchImpl?: FetchLike): ClaudeTokenIo;
@@ -1,109 +0,0 @@
1
- import { ReviewPayloadError as PostReviewError } from "../gha-review-payload/index.mjs";
2
- export const CLAUDE_OIDC_AUDIENCE = 'claude-code-github-action';
3
- export const CLAUDE_APP_TOKEN_EXCHANGE_URL = 'https://api.anthropic.com/api/github/github-app-token-exchange';
4
- // Anthropic rejects the exchange unless custom permissions include contents
5
- // (read or write), even when the token is only used to POST /reviews.
6
- export const CLAUDE_POSTER_PERMISSIONS = {
7
- contents: 'read',
8
- pull_requests: 'write',
9
- };
10
- export const GITHUB_INSTALLATION_TOKEN_URL = 'https://api.github.com/installation/token';
11
- export function oidcTokenRequest(env) {
12
- const base = env.ACTIONS_ID_TOKEN_REQUEST_URL;
13
- const token = env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;
14
- if (!base || !token) {
15
- throw new PostReviewError('OIDC token request env is missing.');
16
- }
17
- const separator = base.includes('?') ? '&' : '?';
18
- return {
19
- url: `${base}${separator}audience=${encodeURIComponent(CLAUDE_OIDC_AUDIENCE)}`,
20
- token,
21
- };
22
- }
23
- function readToken(payload) {
24
- if (payload === null || typeof payload !== 'object')
25
- return '';
26
- // oxlint-disable-next-line no-mistakes/ts-no-const-aliases -- establish a record view after validating the untrusted response object
27
- const record = payload;
28
- const token = record.token ?? record.app_token ?? record.value;
29
- return typeof token === 'string' ? token : '';
30
- }
31
- function readErrorMessage(payload) {
32
- if (payload === null || typeof payload !== 'object')
33
- return '';
34
- // oxlint-disable-next-line no-mistakes/ts-no-const-aliases -- establish a record view after validating the untrusted response object
35
- const record = payload;
36
- if (typeof record.message === 'string' && record.message.length > 0)
37
- return record.message;
38
- const nested = record.error;
39
- if (nested !== null && typeof nested === 'object') {
40
- const message = nested.message;
41
- if (typeof message === 'string')
42
- return message;
43
- }
44
- return '';
45
- }
46
- function exchangeErrorMessage(status, payload) {
47
- const detail = readErrorMessage(payload);
48
- const suffix = detail.length > 0 ? `: ${detail}` : '';
49
- return `Claude App token exchange failed (HTTP ${status})${suffix}.`;
50
- }
51
- export async function mintClaudeAppToken(io) {
52
- const oidcToken = await io.getOidcToken();
53
- const response = await io.fetch(CLAUDE_APP_TOKEN_EXCHANGE_URL, {
54
- method: 'POST',
55
- headers: {
56
- Authorization: `Bearer ${oidcToken}`,
57
- 'Content-Type': 'application/json',
58
- },
59
- body: JSON.stringify({ permissions: CLAUDE_POSTER_PERMISSIONS }),
60
- });
61
- if (!response.ok) {
62
- throw new PostReviewError(exchangeErrorMessage(response.status, await response.json().catch(() => null)));
63
- }
64
- const appToken = readToken(await response.json());
65
- if (appToken.length === 0) {
66
- throw new PostReviewError('Claude App token exchange returned no token.');
67
- }
68
- io.mask(appToken);
69
- return appToken;
70
- }
71
- export async function revokeClaudeAppToken(token, io) {
72
- await io.fetch(GITHUB_INSTALLATION_TOKEN_URL, {
73
- method: 'DELETE',
74
- headers: {
75
- Accept: 'application/vnd.github+json',
76
- Authorization: `Bearer ${token}`,
77
- },
78
- });
79
- }
80
- export async function withClaudeAppToken(io, fn) {
81
- const token = await mintClaudeAppToken(io);
82
- try {
83
- return await fn(token);
84
- }
85
- finally {
86
- await revokeClaudeAppToken(token, io);
87
- }
88
- }
89
- export function createActionsClaudeTokenIo(env = process.env, fetchImpl = fetch) {
90
- return {
91
- async getOidcToken() {
92
- const request = oidcTokenRequest(env);
93
- const response = await fetchImpl(request.url, {
94
- headers: { Authorization: `Bearer ${request.token}` },
95
- });
96
- if (!response.ok) {
97
- throw new PostReviewError(`OIDC token request failed (HTTP ${response.status}).`);
98
- }
99
- const jwt = readToken(await response.json());
100
- if (jwt.length === 0)
101
- throw new PostReviewError('OIDC token request returned no token.');
102
- return jwt;
103
- },
104
- fetch: fetchImpl,
105
- mask(token) {
106
- process.stdout.write(`::add-mask::${token}\n`);
107
- },
108
- };
109
- }
@@ -1 +0,0 @@
1
- export declare function runPostReviewCli(env?: NodeJS.ProcessEnv): Promise<number>;
@@ -1,22 +0,0 @@
1
- import { fileURLToPath } from 'node:url';
2
- import { writePostedOutput, postReviewFromEnv } from "./github.mjs";
3
- export async function runPostReviewCli(env = process.env) {
4
- try {
5
- const result = await postReviewFromEnv(env);
6
- writePostedOutput(result.posted, result.commentCount, env.GITHUB_OUTPUT);
7
- return 0;
8
- }
9
- catch (error) {
10
- process.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`);
11
- return 1;
12
- }
13
- }
14
- /* v8 ignore next 12 */
15
- if (process.argv[1] === fileURLToPath(import.meta.url)) {
16
- runPostReviewCli().then((code) => {
17
- process.exitCode = code;
18
- }, (error) => {
19
- process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
20
- process.exitCode = 1;
21
- });
22
- }
@@ -1,13 +0,0 @@
1
- import { execFileSync } from 'node:child_process';
2
- import { type PostReviewResult } from './post.mts';
3
- export { createGhPostReviewIo, postWithGh } from './pull-io.mts';
4
- export type GhExec = (args: readonly string[], options?: {
5
- input?: string;
6
- env?: NodeJS.ProcessEnv;
7
- }) => string;
8
- export declare function createGhExec(exec?: typeof execFileSync): GhExec;
9
- export declare function writePostedOutput(posted: boolean, commentCount: number, outputPath?: string | undefined): void;
10
- /** @deprecated Use postReviewWithTokenFromEnv or postClaudeReviewFromEnv explicitly. */
11
- export declare function postReviewFromEnv(env?: NodeJS.ProcessEnv, exec?: GhExec, claudeIo?: import("./claude-token.mts").ClaudeTokenIo): Promise<PostReviewResult>;
12
- export declare function postReviewWithTokenFromEnv(env?: NodeJS.ProcessEnv, exec?: GhExec, token?: string | undefined): PostReviewResult;
13
- export declare function postClaudeReviewFromEnv(env?: NodeJS.ProcessEnv, exec?: GhExec, claudeIo?: import("./claude-token.mts").ClaudeTokenIo): Promise<PostReviewResult>;