@comforge/github 0.1.0 → 0.2.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.
package/README.md CHANGED
@@ -41,7 +41,7 @@ const files = await github.listPullRequestFiles(7, pr.head.sha); // refuses if t
41
41
  if (!checks.ok) throw new Error("required checks are not green for this exact commit");
42
42
  ```
43
43
 
44
- A complete, runnable consumer with a fake GitHub transport: [examples/factory-github-consumer](https://github.com/vikramrao1994/comforge/tree/github/v0.1.0/examples/factory-github-consumer/).
44
+ A complete, runnable consumer with a fake GitHub transport: [examples/factory-github-consumer](https://github.com/vikramrao1994/comforge/tree/github/v0.2.0/examples/factory-github-consumer/).
45
45
 
46
46
  ## The transport
47
47
 
@@ -60,6 +60,7 @@ export interface PullRequestEvidence {
60
60
  repository: string | null;
61
61
  };
62
62
  }
63
+ export type PatchStatus = "included" | "truncated" | "omitted-budget" | "omitted-by-request" | "unavailable";
63
64
  export interface ChangedFile {
64
65
  path: string;
65
66
  previousPath: string | null;
@@ -67,6 +68,34 @@ export interface ChangedFile {
67
68
  additions: number;
68
69
  deletions: number;
69
70
  changes: number;
71
+ /** GitHub sent no patch and the name is a binary format: there is no text to show. */
72
+ binary: boolean;
73
+ /**
74
+ * Why `patch` is or is not here. `unavailable`: GitHub sent none (binary or too large for it);
75
+ * never an empty patch. `omitted-*`: GitHub sent one and the caller's request or budget left it out.
76
+ */
77
+ patchStatus: PatchStatus;
78
+ patch: UntrustedText | null;
79
+ }
80
+ export interface PatchLimits {
81
+ /** Characters kept of one file's patch. */
82
+ perFileMaxChars: number;
83
+ /** Characters kept across all patches, in GitHub's file order. */
84
+ totalMaxChars: number;
85
+ }
86
+ export declare const DEFAULT_PATCH_LIMITS: PatchLimits;
87
+ export interface WorkflowRunEvidence {
88
+ repository: string;
89
+ sha: string;
90
+ /** Workflow runs for exactly `sha`. Evidence of what ran, never a verdict on required checks. */
91
+ runs: {
92
+ id: number;
93
+ name: string | null;
94
+ status: string | null;
95
+ conclusion: string | null;
96
+ event: string;
97
+ createdAt: string;
98
+ }[];
70
99
  }
71
100
  export interface PullRequestFilesEvidence {
72
101
  repository: string;
@@ -90,6 +119,7 @@ export interface CheckEvidence {
90
119
  status: string;
91
120
  conclusion: string | null;
92
121
  app: string | null;
122
+ startedAt: string | null;
93
123
  completedAt: string | null;
94
124
  }[];
95
125
  required: {
@@ -100,6 +130,18 @@ export interface CheckEvidence {
100
130
  /** Every required check has a successful run on exactly `sha`. False when nothing is required. */
101
131
  ok: boolean;
102
132
  }
133
+ export interface CommitComparison {
134
+ repository: string;
135
+ base: string;
136
+ head: string;
137
+ /** How `head` relates to `base`: `ahead` means `head` has commits `base` lacks. */
138
+ status: "identical" | "ahead" | "behind" | "diverged";
139
+ /** Commits on `head` that are not on `base`. */
140
+ aheadBy: number;
141
+ /** Commits on `base` that are not on `head`. */
142
+ behindBy: number;
143
+ mergeBase: string;
144
+ }
103
145
  export interface GitHubEvidence {
104
146
  readonly repository: string;
105
147
  getIssue(number: number): Promise<IssueEvidence>;
@@ -110,14 +152,26 @@ export interface GitHubEvidence {
110
152
  getPullRequest(number: number, options?: {
111
153
  expectedHeadSha?: string;
112
154
  }): Promise<PullRequestEvidence>;
113
- /** The changed files of a pull request whose head is exactly `headSha`, before and after the read. */
114
- listPullRequestFiles(number: number, headSha: string): Promise<PullRequestFilesEvidence>;
155
+ /**
156
+ * The changed files of a pull request whose head is exactly `headSha`, before and after the
157
+ * read. With `patches`, each file's patch text within the per-file and total budgets.
158
+ */
159
+ listPullRequestFiles(number: number, headSha: string, options?: {
160
+ patches?: Partial<PatchLimits> | true;
161
+ }): Promise<PullRequestFilesEvidence>;
115
162
  /** Reviews; with `commitSha`, only those submitted on that exact commit. */
116
163
  listReviews(number: number, options?: {
117
164
  commitSha?: string;
118
165
  }): Promise<ReviewEvidence[]>;
119
166
  /** Check runs GitHub recorded for exactly `sha`, judged against `required` check names. */
120
167
  getChecks(sha: string, required?: readonly string[]): Promise<CheckEvidence>;
168
+ /**
169
+ * Workflow runs GitHub recorded for exactly `sha`: a read for credentials without check-run
170
+ * access. Which one to trust when is the caller's policy; this never reports success.
171
+ */
172
+ listWorkflowRuns(sha: string): Promise<WorkflowRunEvidence>;
173
+ /** How commit `head` relates to commit `base` (both full SHAs), as GitHub's compare reports it. */
174
+ compareCommits(base: string, head: string): Promise<CommitComparison>;
121
175
  }
122
176
  export declare function createGitHubEvidence(options: {
123
177
  transport: GitHubTransport;
package/dist/evidence.js CHANGED
@@ -52,6 +52,7 @@ const FileSchema = z.object({
52
52
  additions: z.number().int(),
53
53
  deletions: z.number().int(),
54
54
  changes: z.number().int(),
55
+ patch: z.string().optional(),
55
56
  });
56
57
  const ReviewSchema = z.object({
57
58
  id: z.number().int(),
@@ -69,10 +70,36 @@ const CheckRunsSchema = z.object({
69
70
  head_sha: z.string(),
70
71
  status: z.string(),
71
72
  conclusion: z.string().nullable(),
73
+ started_at: z.string().nullable().optional(),
72
74
  completed_at: z.string().nullable().optional(),
73
75
  app: z.object({ slug: z.string() }).nullable().optional(),
74
76
  })),
75
77
  });
78
+ const WorkflowRunsSchema = z.object({
79
+ total_count: z.number().int().nonnegative(),
80
+ workflow_runs: z.array(z.object({
81
+ id: z.number().int(),
82
+ name: z.string().nullable(),
83
+ head_sha: z.string(),
84
+ status: z.string().nullable(),
85
+ conclusion: z.string().nullable(),
86
+ event: z.string(),
87
+ created_at: z.string(),
88
+ })),
89
+ });
90
+ /** Extensions whose missing patch means binary content, not an unreadable one. */
91
+ const BINARY_EXTENSIONS = /\.(png|jpe?g|gif|webp|avif|ico|pdf|zip|gz|woff2?|ttf|bin|db|sqlite)$/i;
92
+ const CompareSchema = z.object({
93
+ status: z.enum(["identical", "ahead", "behind", "diverged"]),
94
+ ahead_by: z.number().int().nonnegative(),
95
+ behind_by: z.number().int().nonnegative(),
96
+ base_commit: z.object({ sha: z.string().regex(SHA) }),
97
+ merge_base_commit: z.object({ sha: z.string().regex(SHA) }),
98
+ });
99
+ export const DEFAULT_PATCH_LIMITS = {
100
+ perFileMaxChars: 20_000,
101
+ totalMaxChars: 100_000,
102
+ };
76
103
  function positive(value, what) {
77
104
  if (!Number.isSafeInteger(value) || value < 1)
78
105
  throw new GitHubAdapterError("invalid-input", `Invalid ${what}`);
@@ -173,26 +200,60 @@ export function createGitHubEvidence(options) {
173
200
  return all.map(issueEvidence).filter((i) => !i.isPullRequest);
174
201
  },
175
202
  getPullRequest,
176
- async listPullRequestFiles(number, headSha) {
203
+ async listPullRequestFiles(number, headSha, opts = {}) {
177
204
  sha(headSha, "headSha");
205
+ const patchLimits = opts.patches === undefined
206
+ ? null
207
+ : { ...DEFAULT_PATCH_LIMITS, ...(opts.patches === true ? {} : opts.patches) };
208
+ if (patchLimits &&
209
+ !(Number.isSafeInteger(patchLimits.perFileMaxChars) &&
210
+ Number.isSafeInteger(patchLimits.totalMaxChars) &&
211
+ patchLimits.perFileMaxChars >= 1 &&
212
+ patchLimits.totalMaxChars >= 1))
213
+ throw new GitHubAdapterError("invalid-input", "Invalid patch limits");
178
214
  await getPullRequest(number, { expectedHeadSha: headSha });
179
215
  const files = await pages(["pulls", number, "files"], {}, (body) => ({
180
216
  items: parse(z.array(FileSchema), body, "pull request files"),
181
217
  }));
182
218
  // The listing is of whatever the head was while it was read; prove it did not move.
183
219
  await getPullRequest(number, { expectedHeadSha: headSha });
220
+ let budget = patchLimits?.totalMaxChars ?? 0;
184
221
  return {
185
222
  repository,
186
223
  number,
187
224
  headSha,
188
- files: files.map((f) => ({
189
- path: f.filename,
190
- previousPath: f.previous_filename ?? null,
191
- status: f.status,
192
- additions: f.additions,
193
- deletions: f.deletions,
194
- changes: f.changes,
195
- })),
225
+ files: files.map((f) => {
226
+ let patchStatus = "unavailable";
227
+ let patch = null;
228
+ if (f.patch !== undefined) {
229
+ if (!patchLimits)
230
+ patchStatus = "omitted-by-request";
231
+ else if (budget <= 0)
232
+ patchStatus = "omitted-budget";
233
+ else {
234
+ const max = Math.min(patchLimits.perFileMaxChars, budget);
235
+ const truncated = f.patch.length > max;
236
+ patch = {
237
+ text: truncated ? f.patch.slice(0, max) : f.patch,
238
+ truncated,
239
+ trust: UNTRUSTED,
240
+ };
241
+ budget -= patch.text.length;
242
+ patchStatus = truncated ? "truncated" : "included";
243
+ }
244
+ }
245
+ return {
246
+ path: f.filename,
247
+ previousPath: f.previous_filename ?? null,
248
+ status: f.status,
249
+ additions: f.additions,
250
+ deletions: f.deletions,
251
+ changes: f.changes,
252
+ binary: f.patch === undefined && BINARY_EXTENSIONS.test(f.filename),
253
+ patchStatus,
254
+ patch,
255
+ };
256
+ }),
196
257
  };
197
258
  },
198
259
  async listReviews(number, opts = {}) {
@@ -224,6 +285,7 @@ export function createGitHubEvidence(options) {
224
285
  status: r.status,
225
286
  conclusion: r.conclusion,
226
287
  app: r.app?.slug ?? null,
288
+ startedAt: r.started_at ?? null,
227
289
  completedAt: r.completed_at ?? null,
228
290
  }));
229
291
  // Any successful run of a required name on exactly this commit proves it passed on this tree.
@@ -244,5 +306,43 @@ export function createGitHubEvidence(options) {
244
306
  ok: requiredEvidence.length > 0 && requiredEvidence.every((r) => r.satisfied),
245
307
  };
246
308
  },
309
+ async listWorkflowRuns(commit) {
310
+ sha(commit);
311
+ const runs = await pages(["actions", "runs"], { head_sha: commit }, (body) => {
312
+ const page = parse(WorkflowRunsSchema, body, "workflow runs");
313
+ return { items: page.workflow_runs, total: page.total_count };
314
+ });
315
+ if (runs.some((r) => r.head_sha !== commit))
316
+ throw new GitHubAdapterError("malformed-response", "A workflow run belongs to another commit");
317
+ return {
318
+ repository,
319
+ sha: commit,
320
+ runs: runs.map((r) => ({
321
+ id: r.id,
322
+ name: r.name,
323
+ status: r.status,
324
+ conclusion: r.conclusion,
325
+ event: r.event,
326
+ createdAt: r.created_at,
327
+ })),
328
+ };
329
+ },
330
+ async compareCommits(baseSha, headSha) {
331
+ sha(baseSha, "base");
332
+ sha(headSha, "head");
333
+ const c = parse(CompareSchema, await get(["compare", `${baseSha}...${headSha}`]), "a commit comparison");
334
+ // GitHub resolves the range itself; an answer about another base is not this comparison.
335
+ if (c.base_commit.sha !== baseSha)
336
+ throw new GitHubAdapterError("malformed-response", "The comparison names another base");
337
+ return {
338
+ repository,
339
+ base: baseSha,
340
+ head: headSha,
341
+ status: c.status,
342
+ aheadBy: c.ahead_by,
343
+ behindBy: c.behind_by,
344
+ mergeBase: c.merge_base_commit.sha,
345
+ };
346
+ },
247
347
  });
248
348
  }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export { GITHUB_ERROR_CODES, GitHubAdapterError, type GitHubErrorCode, type GitHubErrorDetail, } from "./errors.ts";
2
- export { type ChangedFile, type CheckEvidence, createGitHubEvidence, type EvidenceLimits, type GitHubEvidence, type IssueEvidence, type PullRequestEvidence, type PullRequestFilesEvidence, type RepositoryRef, type ReviewEvidence, type UntrustedText, } from "./evidence.ts";
2
+ export { type ChangedFile, type CheckEvidence, type CommitComparison, createGitHubEvidence, type EvidenceLimits, type GitHubEvidence, type IssueEvidence, type PatchLimits, type PatchStatus, type PullRequestEvidence, type PullRequestFilesEvidence, type RepositoryRef, type ReviewEvidence, type UntrustedText, type WorkflowRunEvidence, } from "./evidence.ts";
3
3
  export { type Reconciliation, readSpecificationIssue, reconcileSpecification, type SpecificationIssueEvidence, } from "./specification.ts";
4
4
  export { createFetchTransport, type FetchTransportOptions, type GitHubTransport, } from "./transport.ts";
package/dist/transport.js CHANGED
@@ -36,6 +36,12 @@ export function classifyStatus(status, headers) {
36
36
  return new GitHubAdapterError("http-error", `GitHub returned HTTP ${status}`, { status });
37
37
  }
38
38
  const PATH = /^\/[A-Za-z0-9._~%/-]*$/;
39
+ /**
40
+ * GitHub's commit-comparison range (`compare/BASE...HEAD`) is the only API path with dots in a
41
+ * row. It is accepted only as the last segment and only between two full commit SHAs, so it can
42
+ * never spell a parent-directory step; every other `..` is refused.
43
+ */
44
+ const COMPARE_RANGE = /\/compare\/[0-9a-f]{40}\.\.\.[0-9a-f]{40}$/;
39
45
  /** A request that never completed: a timeout, or the network. */
40
46
  function unreachable(error, message, status) {
41
47
  const timedOut = error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
@@ -52,7 +58,7 @@ export function createFetchTransport(options) {
52
58
  async get(path, query) {
53
59
  if (typeof path !== "string" ||
54
60
  !PATH.test(path) ||
55
- path.includes("..") ||
61
+ path.replace(COMPARE_RANGE, "/compare/range").includes("..") ||
56
62
  path.includes("//"))
57
63
  throw new GitHubAdapterError("invalid-input", "The request path is not an API path");
58
64
  const url = new URL(`${base}${path}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@comforge/github",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "GitHub evidence for Comforge governance: typed, exact-SHA reads of issues, pull requests, reviews and checks, and published-specification verification through @comforge/core. Injected transport; no writes.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {