@davidvornholt/standards 0.11.0 → 0.11.1
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 +5 -3
- package/package.json +2 -1
- package/src/cli.ts +30 -76
- package/src/github-api.ts +2 -0
- package/src/github-labels.ts +2 -2
- package/src/github-live-drift.ts +21 -0
- package/src/github-paginate.ts +14 -2
- package/src/managed-files.ts +64 -0
package/README.md
CHANGED
|
@@ -18,11 +18,13 @@ standards poller --print-units --config <path>
|
|
|
18
18
|
|
|
19
19
|
`dependabot --write` regenerates the composed `.github/dependabot.yml` from the canonical `.github/dependabot.base.yml` and the optional repo-owned `.github/dependabot.local.yml`; `init` and `sync` do the same automatically. `dependabot --check` verifies the generated file still matches its sources, and `doctor`/`check` include the same verification. The overlay is deliberately lean and additive only: new update blocks for repo-specific ecosystems, top-level private registry definitions, and `ignore` or `registries` entries appended by repeating a canonical block's normalized target. Matching blocks cannot add labels, groups, cooldowns, pull-request limits, or other policy.
|
|
20
20
|
|
|
21
|
-
`
|
|
21
|
+
`check` also rejects the raw token formed by `biome-` + `ignore` anywhere in lock-listed canonical files. The intentionally blunt policy keeps synced sources compatible with consumer Biome configurations without invoking Biome or maintaining language-aware comment parsing.
|
|
22
|
+
|
|
23
|
+
`github --check` compares the live GitHub repository (merge settings, rulesets, and declared labels) against the merged declaration in `.github/settings.json` + `.github/settings.local.json`; `github --apply` converges that declared state. Undeclared live labels remain untouched, while undeclared repository-owned rulesets are removed. `check` runs the same comparison whenever `.github/settings.json` is present, and fails closed: declared state the token cannot see fails the gate with a message naming the token fix instead of passing unverified. The canonical workflow sets `STANDARDS_SKIP_GITHUB_CHECK=true` only in its unprivileged quality step because its isolated `github-settings` job runs the live comparison with the settings-read token; this is a workflow-internal integration seam, not a general way to disable the local gate. The CLI prints an explicit diagnostic whenever that exact value skips either `check`'s live phase or `github --check`; `github --apply` is never skipped. `--apply` re-diffs the PATCH response, so a setting GitHub accepts with HTTP 200 but silently ignores (plan-unavailable features) is a reported failure, not a false success. A repository whose GitHub plan cannot enforce rulesets can declare that in the seam (see `rulesetEnforcement` below); both commands then skip rulesets and plan-gated repository settings, converge the rest, and print an unprotected-branch notice on every run.
|
|
22
24
|
|
|
23
25
|
`structure` enforces the canonical monorepo structure contract: workspace scripts (`check-types`, `lint`, `lint:fix`, `test`), root gate scripts, filtered Turbo convenience aliases, internal `0.0.0`/`workspace:*` versioning, package `exports`, shared tsconfig inheritance, and browser a11y wiring. Only a workspace containing an explicit `*.a11y.ts` suite must provide a `test:a11y` script and direct `@axe-core/playwright` and `@playwright/test` dependencies. `check` includes `structure`, so these rules gate every consumer PR.
|
|
24
26
|
|
|
25
|
-
`poller` runs one tick of the fix poller: host-level automation that turns maintainer-approved GitHub issues into verified draft PRs and maintainer-approved draft PRs into completed review-fix cycles, using headless Codex runs. All workflow state lives in GitHub labels, comments, and draft PRs, so ticks are stateless, re-runnable, and safe to schedule from any host. A tick claims work by label (`fix-in-progress` / `review-in-progress`), releases claims stale for longer than `staleClaimHours`, and fails loudly — a red tick means jobs stalled, never silence. Trust is verified per event, not per configuration: the approval labels (`approved-for-fix`, `approved-for-review`) only count when the applying user holds the `admin` or `maintain` role, bind to the exact approved issue revision or PR head, and are revalidated before publication; only admin/maintain comments are treated as answers to agent questions. The poller removes its direct GitHub token variables before launching Codex, but the approved run shares the host service identity and can read its other ambient credentials and logged-in tool state; that accepted visibility must not be treated as credential isolation. The run works in a throwaway git worktree, hands results back through a structured outcome file, and the poller verifies effects (commits exist, no protected paths touched) before pushing, opening the draft PR, or posting the review — the required CI checks on the resulting PR remain the quality gate. Host mutation is declarative-only: `--print-units` emits a correctly escaped systemd service and timer for the polling host's infrastructure repository to adapt and deploy. That repository owns the service identity, writable HOME, PATH, GitHub token environment, lingering, and deployment. The service's tick budget (`TimeoutStartSec`) is derived from `maxJobsPerTick` × `runTimeoutMinutes` plus overhead, so re-render and redeploy the units after changing either value.
|
|
27
|
+
`poller` runs one tick of the fix poller: host-level automation that turns maintainer-approved GitHub issues into verified draft PRs and maintainer-approved draft PRs into completed review-fix cycles, using headless Codex runs. All workflow state lives in GitHub labels, comments, and draft PRs (the labels are canonical declared settings — see `github --apply`), so ticks are stateless, re-runnable, and safe to schedule from any host. A tick claims work by label (`fix-in-progress` / `review-in-progress`), releases claims stale for longer than `staleClaimHours`, and fails loudly — a red tick means jobs stalled, never silence. Trust is verified per event, not per configuration: the approval labels (`approved-for-fix`, `approved-for-review`) only count when the applying user holds the `admin` or `maintain` role, bind to the exact approved issue revision or PR head, and are revalidated before publication; only admin/maintain comments are treated as answers to agent questions. The poller removes its direct GitHub token variables before launching Codex, but the approved run shares the host service identity and can read its other ambient credentials and logged-in tool state; that accepted visibility must not be treated as credential isolation. The run works in a throwaway git worktree, hands results back through a structured outcome file, and the poller verifies effects (commits exist, no protected paths touched) before pushing, opening the draft PR, or posting the review — the required CI checks on the resulting PR remain the quality gate. Host mutation is declarative-only: `--print-units` emits a correctly escaped systemd service and timer for the polling host's infrastructure repository to adapt and deploy. That repository owns the service identity, writable HOME, PATH, GitHub token environment, lingering, and deployment. The service's tick budget (`TimeoutStartSec`) is derived from `maxJobsPerTick` × `runTimeoutMinutes` plus overhead, so re-render and redeploy the units after changing either value.
|
|
26
28
|
|
|
27
29
|
`structure --profile source` validates the standards source repository itself, which is deliberately not a consumer. The profile pins its intentional exceptions so they cannot drift silently: exact, ordered root gate scripts that run this CLI from the local checkout (`structure --profile source`, `dependabot --check` or `dependabot --write`, `github --check`, and the Turbo gate) instead of a recursive `standards check`, and a non-private published bin-only CLI workspace that carries a stable release SemVer and exactly maps the `standards` bin to `src/cli.ts` without `exports`. Every other consumer rule still applies.
|
|
28
30
|
|
|
@@ -32,6 +34,6 @@ standards poller --print-units --config <path>
|
|
|
32
34
|
- **`sync-standards.local.json`** (optional) — consumer-owned sync policy at the repo root, validated by `doctor`/`check` and every `init`/`sync` even when an explicit ref or local source makes its `"ref"` irrelevant. All fields optional; a missing file means the defaults. `"ref"` is a non-empty single-line string that pins a tag, branch, or full commit sha to sync from instead of `main` (an explicit `--ref` overrides it; a local-path `--from` source is used as-is and ignores only the validated pin). `"autoSync": false` is read by the standards-sync workflow, not the CLI, and skips the weekly scheduled run. Version 0.7.0 removes the legacy `STANDARDS_AUTO_SYNC` and `STANDARDS_SYNC_REF` variable behavior; consumers must upgrade the package and lockfile before adopting a policy file.
|
|
33
35
|
- **`.github/settings.local.json` `"rulesetEnforcement": "unavailable-on-plan"`** (optional) — declares that the repository's GitHub plan cannot enforce rulesets (private repositories on GitHub Free, both personal accounts and organizations). `github --check` and `--apply` then skip rulesets instead of comparing them, because a comparison cannot be trusted there: personal accounts answer ruleset reads with HTTP 403, and free-plan organizations report declared rulesets as active while silently not enforcing them. Plan-gated repository settings that only function alongside branch protection (`allow_auto_merge`) are skipped for the same reason — GitHub accepts a PATCH for them with HTTP 200 and silently keeps the old value. The remaining repository merge settings are still checked and converged, and both commands print an unprotected-branch notice on every run. The only accepted value is `"unavailable-on-plan"` (enforcement is the default; omit the key on paid plans), and combining the opt-out with additional local rulesets is rejected. After upgrading the plan, remove the declaration and run `bun standards github --apply` to restore enforcement.
|
|
34
36
|
- **Poller config file** (required for `poller`, passed via `--config`) — host-level JSON, deliberately not repository state. Required: `"repos"` (unique `owner/repo` strings — one poller watches any number of repositories), `"model"` and `"reasoningEffort"` (passed to `codex exec`; the model choice is deliberate and has no default). Optional: `"maxJobsPerTick"` (default 1 — the concurrency and rate-limit guard; subscription-authenticated Codex runs share the interactive rate window), `"staleClaimHours"` (default 6; must exceed `runTimeoutMinutes` so a sweep can never release the claim of a job that is still running), `"runTimeoutMinutes"` (default 240 — the timeout catches wedged agents, not honest multi-hour review runs), `"cacheDir"` (default `~/.cache/standards-poller`; holds bare mirrors and job worktrees; relative paths resolve against the config file), `"extraCodexArgs"` (extra `codex exec` arguments, e.g. enabling the collaboration feature for subagent fan-out). Unknown keys are rejected. The poller needs `git`, `codex` (authenticated — its rotating auth state must live in a writable location), and a GitHub token per the bullet below; the token needs issues, pull-requests, and contents write on the watched repos, and nothing else.
|
|
35
|
-
- **`GH_TOKEN` / `GITHUB_TOKEN`** (optional) — GitHub API token for the `github` command and the GitHub portion of `check`. When neither is set, the token from the local `gh` CLI is used; with no token at all, reads still work on public repositories. `--apply` needs an admin token. GitHub's REST API reveals repo merge settings only to write-capable viewers — `check` retries REST-hidden keys over GraphQL, which serves them to read-only tokens —
|
|
37
|
+
- **`GH_TOKEN` / `GITHUB_TOKEN`** (optional) — GitHub API token for the `github` command and the GitHub portion of `check`. When neither is set, the token from the local `gh` CLI is used; with no token at all, reads still work on public repositories. `--apply` needs an admin token. GitHub's REST API reveals repo merge settings only to write-capable viewers — `check` retries REST-hidden keys over GraphQL, which serves them to read-only tokens — ruleset `bypass_actors` requires repository Administration read, and private-repository labels require Issues read (or Pull requests read); a token that still cannot see declared state fails the check rather than passing unverified. In CI, the canonical workflow decrypts `ci.github_settings_read_token` from the SOPS-encrypted `secrets/ci.yaml`: a repository-scoped fine-grained PAT with read-only "Administration" and "Issues" access.
|
|
36
38
|
|
|
37
39
|
See the standards repository README for the ownership model and adoption workflow.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@davidvornholt/standards",
|
|
3
|
-
"version": "0.11.
|
|
3
|
+
"version": "0.11.1",
|
|
4
4
|
"description": "Bootstrap, synchronize, and validate davidvornholt/standards consumers",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -36,6 +36,7 @@
|
|
|
36
36
|
"src/github-settings-merge.ts",
|
|
37
37
|
"src/github-settings-parse.ts",
|
|
38
38
|
"src/github-settings.ts",
|
|
39
|
+
"src/managed-files.ts",
|
|
39
40
|
"src/poller-approval.ts",
|
|
40
41
|
"src/poller-claim.ts",
|
|
41
42
|
"src/poller-codex.ts",
|
package/src/cli.ts
CHANGED
|
@@ -13,25 +13,9 @@
|
|
|
13
13
|
import { execFileSync } from 'node:child_process';
|
|
14
14
|
import { createHash } from 'node:crypto';
|
|
15
15
|
import { existsSync, mkdtempSync, rmSync } from 'node:fs';
|
|
16
|
-
import {
|
|
17
|
-
cp,
|
|
18
|
-
mkdir,
|
|
19
|
-
readdir,
|
|
20
|
-
readFile,
|
|
21
|
-
rm,
|
|
22
|
-
stat,
|
|
23
|
-
writeFile,
|
|
24
|
-
} from 'node:fs/promises';
|
|
16
|
+
import { cp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
25
17
|
import { tmpdir } from 'node:os';
|
|
26
|
-
import {
|
|
27
|
-
dirname,
|
|
28
|
-
isAbsolute,
|
|
29
|
-
join,
|
|
30
|
-
posix,
|
|
31
|
-
relative,
|
|
32
|
-
resolve,
|
|
33
|
-
sep,
|
|
34
|
-
} from 'node:path';
|
|
18
|
+
import { dirname, isAbsolute, join, posix, resolve } from 'node:path';
|
|
35
19
|
import process from 'node:process';
|
|
36
20
|
import {
|
|
37
21
|
composeDependabot,
|
|
@@ -44,6 +28,10 @@ import { CANONICAL_SETTINGS_FILE, LOCAL_SETTINGS_FILE } from './github-api';
|
|
|
44
28
|
import { runGithubApply, runGithubCheck } from './github-commands';
|
|
45
29
|
import { loadGithubSettings } from './github-settings';
|
|
46
30
|
import { isNonEmptyString, isRecord } from './github-settings-parse';
|
|
31
|
+
import {
|
|
32
|
+
findManagedFilesContainingBiomeDirectiveToken,
|
|
33
|
+
listManagedFiles,
|
|
34
|
+
} from './managed-files';
|
|
47
35
|
import { runPollerCommand } from './poller-commands';
|
|
48
36
|
import { collectStructureProblems } from './structure-check';
|
|
49
37
|
import type { StructureProfile } from './structure-profile';
|
|
@@ -57,17 +45,6 @@ const HASH_PREVIEW_LENGTH = 12;
|
|
|
57
45
|
const GITHUB_PREFIX = 'github:';
|
|
58
46
|
const SKIP_GITHUB_CHECK_ENV = 'STANDARDS_SKIP_GITHUB_CHECK';
|
|
59
47
|
|
|
60
|
-
// Never mirrored, even under a managed directory path: build output, VCS
|
|
61
|
-
// metadata, and installed dependencies would otherwise pollute the lock when
|
|
62
|
-
// syncing from a working tree that has them.
|
|
63
|
-
const IGNORED_DIRS = new Set([
|
|
64
|
-
'node_modules',
|
|
65
|
-
'.git',
|
|
66
|
-
'.turbo',
|
|
67
|
-
'dist',
|
|
68
|
-
'.next',
|
|
69
|
-
]);
|
|
70
|
-
|
|
71
48
|
type Manifest = {
|
|
72
49
|
readonly upstream: string;
|
|
73
50
|
readonly seedDir: string;
|
|
@@ -113,8 +90,6 @@ type CliOptions = {
|
|
|
113
90
|
const sha256 = (buf: Buffer): string =>
|
|
114
91
|
createHash('sha256').update(buf).digest('hex');
|
|
115
92
|
|
|
116
|
-
const toPosix = (p: string): string => p.split(sep).join('/');
|
|
117
|
-
|
|
118
93
|
const assertSafeRelativePath = (path: string, label: string): void => {
|
|
119
94
|
// POSIX semantics on every platform: managed paths are repository-relative
|
|
120
95
|
// POSIX paths, and win32 normalize would rewrite `/` to `\` and reject them.
|
|
@@ -244,38 +219,6 @@ const resolveSource = (src: string, ref: string | undefined): Source => {
|
|
|
244
219
|
return { dir, sha, cleanup };
|
|
245
220
|
};
|
|
246
221
|
|
|
247
|
-
// Recursively collect files under `abs`, keyed by their POSIX path relative to
|
|
248
|
-
// `base`. Missing paths are skipped so a manifest entry with no files is inert.
|
|
249
|
-
const walk = async (
|
|
250
|
-
abs: string,
|
|
251
|
-
base: string,
|
|
252
|
-
out: Map<string, string>,
|
|
253
|
-
): Promise<void> => {
|
|
254
|
-
const info = await stat(abs).catch(() => null);
|
|
255
|
-
if (info === null) {
|
|
256
|
-
return;
|
|
257
|
-
}
|
|
258
|
-
if (info.isDirectory()) {
|
|
259
|
-
const entries = await readdir(abs);
|
|
260
|
-
await Promise.all(
|
|
261
|
-
entries
|
|
262
|
-
.filter((entry) => !IGNORED_DIRS.has(entry))
|
|
263
|
-
.map((entry) => walk(join(abs, entry), base, out)),
|
|
264
|
-
);
|
|
265
|
-
return;
|
|
266
|
-
}
|
|
267
|
-
out.set(toPosix(relative(base, abs)), abs);
|
|
268
|
-
};
|
|
269
|
-
|
|
270
|
-
const listManaged = async (
|
|
271
|
-
dir: string,
|
|
272
|
-
paths: ReadonlyArray<string>,
|
|
273
|
-
): Promise<Map<string, string>> => {
|
|
274
|
-
const out = new Map<string, string>();
|
|
275
|
-
await Promise.all(paths.map((p) => walk(join(dir, p), dir, out)));
|
|
276
|
-
return out;
|
|
277
|
-
};
|
|
278
|
-
|
|
279
222
|
const isUnder = (a: string, b: string): boolean =>
|
|
280
223
|
a === b || a.startsWith(`${b}/`);
|
|
281
224
|
|
|
@@ -325,7 +268,7 @@ const mirror = async ({
|
|
|
325
268
|
for (const rel of Object.keys(previous)) {
|
|
326
269
|
assertSafeRelativePath(rel, 'sync-standards.lock file');
|
|
327
270
|
}
|
|
328
|
-
const upstream = await
|
|
271
|
+
const upstream = await listManagedFiles(srcDir, manifest.paths);
|
|
329
272
|
const next: Record<string, string> = {};
|
|
330
273
|
const created: Array<string> = [];
|
|
331
274
|
const updated: Array<string> = [];
|
|
@@ -400,14 +343,12 @@ const reportMirror = (result: MirrorResult, dryRun: boolean): void => {
|
|
|
400
343
|
}
|
|
401
344
|
};
|
|
402
345
|
|
|
403
|
-
const seedTargets =
|
|
346
|
+
const seedTargets = (
|
|
404
347
|
srcDir: string,
|
|
405
348
|
seedDir: string,
|
|
406
|
-
): Promise<
|
|
349
|
+
): Promise<ReadonlyMap<string, string>> => {
|
|
407
350
|
const root = join(srcDir, seedDir);
|
|
408
|
-
|
|
409
|
-
await walk(root, root, out);
|
|
410
|
-
return out;
|
|
351
|
+
return listManagedFiles(root, ['.']);
|
|
411
352
|
};
|
|
412
353
|
|
|
413
354
|
const runInit = async (
|
|
@@ -505,6 +446,7 @@ const runCheck = async (consumer: string): Promise<boolean> => {
|
|
|
505
446
|
for (const rel of Object.keys(lock.files)) {
|
|
506
447
|
assertSafeRelativePath(rel, 'sync-standards.lock file');
|
|
507
448
|
}
|
|
449
|
+
const lockedFiles = await listManagedFiles(consumer, Object.keys(lock.files));
|
|
508
450
|
const results = await Promise.all(
|
|
509
451
|
Object.entries(lock.files).map(async ([rel, hash]) => {
|
|
510
452
|
const dest = join(consumer, rel);
|
|
@@ -519,6 +461,8 @@ const runCheck = async (consumer: string): Promise<boolean> => {
|
|
|
519
461
|
}),
|
|
520
462
|
);
|
|
521
463
|
const problems = results.filter((p): p is string => p !== null);
|
|
464
|
+
const directiveFiles =
|
|
465
|
+
await findManagedFilesContainingBiomeDirectiveToken(lockedFiles);
|
|
522
466
|
if (problems.length > 0) {
|
|
523
467
|
console.error(
|
|
524
468
|
`standards: ${problems.length} canonical file(s) drifted from the last synced state:`,
|
|
@@ -527,12 +471,22 @@ const runCheck = async (consumer: string): Promise<boolean> => {
|
|
|
527
471
|
console.error(
|
|
528
472
|
'These files are read-only. Restore them with `bun standards sync`, or move your change upstream.',
|
|
529
473
|
);
|
|
530
|
-
return false;
|
|
531
474
|
}
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
475
|
+
if (directiveFiles.length > 0) {
|
|
476
|
+
console.error(
|
|
477
|
+
`standards: ${directiveFiles.length} canonical file(s) contain the forbidden inline Biome directive token:`,
|
|
478
|
+
);
|
|
479
|
+
console.error(directiveFiles.map((path) => ` - ${path}`).join('\n'));
|
|
480
|
+
console.error(
|
|
481
|
+
'Canonical synced files must remain compatible with consumer lint configurations.',
|
|
482
|
+
);
|
|
483
|
+
}
|
|
484
|
+
if (problems.length === 0) {
|
|
485
|
+
console.log(
|
|
486
|
+
`standards: ${Object.keys(lock.files).length} canonical file(s) match the last synced state`,
|
|
487
|
+
);
|
|
488
|
+
}
|
|
489
|
+
return problems.length === 0 && directiveFiles.length === 0;
|
|
536
490
|
};
|
|
537
491
|
|
|
538
492
|
const readTextIfPresent = async (path: string): Promise<string | null> =>
|
|
@@ -624,7 +578,7 @@ const prepareProspectiveDependabot = async (
|
|
|
624
578
|
consumer: string,
|
|
625
579
|
localSeed: string | null,
|
|
626
580
|
): Promise<ProspectiveDependabot> => {
|
|
627
|
-
const incoming = await
|
|
581
|
+
const incoming = await listManagedFiles(srcDir, manifest.paths);
|
|
628
582
|
const basePath = incoming.get(DEPENDABOT_BASE_FILE);
|
|
629
583
|
if (basePath === undefined) {
|
|
630
584
|
throw new Error(
|
|
@@ -1013,7 +967,7 @@ const runCheckCommand = async (consumer: string): Promise<boolean> => {
|
|
|
1013
967
|
};
|
|
1014
968
|
|
|
1015
969
|
// The canonical workflow sets this only for its unprivileged quality job,
|
|
1016
|
-
// where a separate isolated job runs the same live check with the
|
|
970
|
+
// where a separate isolated job runs the same live check with the settings-read
|
|
1017
971
|
// token. Absent that exact workflow seam, local and explicit checks remain
|
|
1018
972
|
// fail-closed.
|
|
1019
973
|
const runGithubCheckGate = (consumer: string): Promise<boolean> => {
|
package/src/github-api.ts
CHANGED
|
@@ -21,6 +21,8 @@ const GITHUB_REMOTE_PATTERN =
|
|
|
21
21
|
export const HTTP_OK = 200;
|
|
22
22
|
export const HTTP_CREATED = 201;
|
|
23
23
|
export const HTTP_NO_CONTENT = 204;
|
|
24
|
+
export const HTTP_UNAUTHORIZED = 401;
|
|
25
|
+
export const HTTP_FORBIDDEN = 403;
|
|
24
26
|
|
|
25
27
|
export const CANONICAL_SETTINGS_FILE = '.github/settings.json';
|
|
26
28
|
export const LOCAL_SETTINGS_FILE = '.github/settings.local.json';
|
package/src/github-labels.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// Live issue-label reading, drift, and convergence. Labels are an additive
|
|
2
2
|
// floor: every declared label must exist with the declared color and
|
|
3
3
|
// description; undeclared live labels (GitHub defaults, ad-hoc triage labels)
|
|
4
|
-
// are ignored.
|
|
5
|
-
//
|
|
4
|
+
// are ignored. Private-repository reads require Issues read (or Pull requests
|
|
5
|
+
// read), and an API denial fails the settings check closed.
|
|
6
6
|
|
|
7
7
|
import { apiError, HTTP_CREATED, HTTP_OK, request } from './github-api';
|
|
8
8
|
import { labelIdentity } from './github-label-identity';
|
package/src/github-live-drift.ts
CHANGED
|
@@ -6,7 +6,9 @@ import {
|
|
|
6
6
|
apiError,
|
|
7
7
|
fetchLiveRulesets,
|
|
8
8
|
fetchMergeSettingsViaGraphql,
|
|
9
|
+
HTTP_FORBIDDEN,
|
|
9
10
|
HTTP_OK,
|
|
11
|
+
HTTP_UNAUTHORIZED,
|
|
10
12
|
request,
|
|
11
13
|
resolveGithubRepo,
|
|
12
14
|
resolveToken,
|
|
@@ -18,8 +20,24 @@ import {
|
|
|
18
20
|
} from './github-command-shared';
|
|
19
21
|
import { diffRepositorySettings, diffRulesets } from './github-diff';
|
|
20
22
|
import { diffLabels, fetchLiveLabels } from './github-labels';
|
|
23
|
+
import { GithubListResponseError } from './github-paginate';
|
|
21
24
|
import { type GithubSettings, isRecord } from './github-settings-parse';
|
|
22
25
|
|
|
26
|
+
const LABEL_VISIBILITY_PROBLEM =
|
|
27
|
+
'declared labels not visible to this token, so the gate cannot verify them. In CI, use a valid ci.github_settings_read_token from secrets/ci.yaml with read-only "Issues" access (or "Pull requests" read); locally use a token with one of those permissions';
|
|
28
|
+
const PERMISSION_DENIAL_MESSAGES: ReadonlySet<string> = new Set([
|
|
29
|
+
'Resource not accessible by integration',
|
|
30
|
+
'Resource not accessible by personal access token',
|
|
31
|
+
]);
|
|
32
|
+
|
|
33
|
+
const isLabelPermissionDenial = (error: unknown): boolean =>
|
|
34
|
+
error instanceof GithubListResponseError &&
|
|
35
|
+
(error.status === HTTP_UNAUTHORIZED ||
|
|
36
|
+
(error.status === HTTP_FORBIDDEN &&
|
|
37
|
+
isRecord(error.responseBody) &&
|
|
38
|
+
typeof error.responseBody.message === 'string' &&
|
|
39
|
+
PERMISSION_DENIAL_MESSAGES.has(error.responseBody.message)));
|
|
40
|
+
|
|
23
41
|
const repositoryDrift = async (
|
|
24
42
|
token: string | null,
|
|
25
43
|
repo: string,
|
|
@@ -100,6 +118,9 @@ export const collectLiveDrift = async (
|
|
|
100
118
|
...labelDrift,
|
|
101
119
|
];
|
|
102
120
|
} catch (error) {
|
|
121
|
+
if (isLabelPermissionDenial(error)) {
|
|
122
|
+
return [LABEL_VISIBILITY_PROBLEM];
|
|
123
|
+
}
|
|
103
124
|
return [
|
|
104
125
|
`GitHub API unreachable: ${error instanceof Error ? error.message : String(error)}`,
|
|
105
126
|
];
|
package/src/github-paginate.ts
CHANGED
|
@@ -4,11 +4,23 @@
|
|
|
4
4
|
// comments break answer detection, and truncated label lists read as drift.
|
|
5
5
|
// Overflow past the page cap fails loudly instead of silently truncating.
|
|
6
6
|
|
|
7
|
-
import { apiError, HTTP_OK, request } from './github-api';
|
|
7
|
+
import { type ApiResponse, apiError, HTTP_OK, request } from './github-api';
|
|
8
8
|
|
|
9
9
|
const PAGE_SIZE = 100;
|
|
10
10
|
const MAX_PAGES = 30;
|
|
11
11
|
|
|
12
|
+
export class GithubListResponseError extends Error {
|
|
13
|
+
readonly responseBody: unknown;
|
|
14
|
+
readonly status: number;
|
|
15
|
+
|
|
16
|
+
constructor(context: string, response: ApiResponse) {
|
|
17
|
+
super(apiError(context, response));
|
|
18
|
+
this.name = 'GithubListResponseError';
|
|
19
|
+
this.responseBody = response.body;
|
|
20
|
+
this.status = response.status;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
12
24
|
export const listAllPages = async (
|
|
13
25
|
token: string | null,
|
|
14
26
|
path: string,
|
|
@@ -24,7 +36,7 @@ export const listAllPages = async (
|
|
|
24
36
|
`${path}${separator}per_page=${PAGE_SIZE}&page=${page}`,
|
|
25
37
|
);
|
|
26
38
|
if (response.status !== HTTP_OK || !Array.isArray(response.body)) {
|
|
27
|
-
throw new
|
|
39
|
+
throw new GithubListResponseError(context, response);
|
|
28
40
|
}
|
|
29
41
|
items.push(...response.body);
|
|
30
42
|
if (response.body.length < PAGE_SIZE) {
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { readdir, readFile, stat } from 'node:fs/promises';
|
|
2
|
+
import { join, relative, sep } from 'node:path';
|
|
3
|
+
|
|
4
|
+
// Never mirrored, even under a managed directory path: build output, VCS
|
|
5
|
+
// metadata, and installed dependencies would otherwise pollute the lock when
|
|
6
|
+
// syncing from a working tree that has them.
|
|
7
|
+
const IGNORED_DIRECTORIES = new Set([
|
|
8
|
+
'node_modules',
|
|
9
|
+
'.git',
|
|
10
|
+
'.turbo',
|
|
11
|
+
'dist',
|
|
12
|
+
'.next',
|
|
13
|
+
]);
|
|
14
|
+
|
|
15
|
+
const directiveToken = Buffer.from(['biome', 'ignore'].join('-'));
|
|
16
|
+
|
|
17
|
+
const toPosix = (path: string): string => path.split(sep).join('/');
|
|
18
|
+
|
|
19
|
+
const walkManagedFiles = async (
|
|
20
|
+
path: string,
|
|
21
|
+
repositoryRoot: string,
|
|
22
|
+
files: Map<string, string>,
|
|
23
|
+
): Promise<void> => {
|
|
24
|
+
const info = await stat(path).catch(() => null);
|
|
25
|
+
if (info === null) {
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
if (info.isDirectory()) {
|
|
29
|
+
const entries = await readdir(path);
|
|
30
|
+
await Promise.all(
|
|
31
|
+
entries
|
|
32
|
+
.filter((entry) => !IGNORED_DIRECTORIES.has(entry))
|
|
33
|
+
.map((entry) =>
|
|
34
|
+
walkManagedFiles(join(path, entry), repositoryRoot, files),
|
|
35
|
+
),
|
|
36
|
+
);
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
files.set(toPosix(relative(repositoryRoot, path)), path);
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export const listManagedFiles = async (
|
|
43
|
+
repositoryRoot: string,
|
|
44
|
+
paths: ReadonlyArray<string>,
|
|
45
|
+
): Promise<ReadonlyMap<string, string>> => {
|
|
46
|
+
const files = new Map<string, string>();
|
|
47
|
+
await Promise.all(
|
|
48
|
+
paths.map((path) =>
|
|
49
|
+
walkManagedFiles(join(repositoryRoot, path), repositoryRoot, files),
|
|
50
|
+
),
|
|
51
|
+
);
|
|
52
|
+
return files;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
export const findManagedFilesContainingBiomeDirectiveToken = async (
|
|
56
|
+
files: ReadonlyMap<string, string>,
|
|
57
|
+
): Promise<ReadonlyArray<string>> => {
|
|
58
|
+
const matches = await Promise.all(
|
|
59
|
+
[...files].map(async ([path, absolutePath]) =>
|
|
60
|
+
(await readFile(absolutePath)).includes(directiveToken) ? path : null,
|
|
61
|
+
),
|
|
62
|
+
);
|
|
63
|
+
return matches.filter((path): path is string => path !== null).sort();
|
|
64
|
+
};
|