@jakobm/peacekeeper 0.26.0 → 0.28.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 (36) hide show
  1. package/README.md +307 -129
  2. package/dist/cmdabra.yaml +174 -116
  3. package/dist/package.json +5 -6
  4. package/dist/src/modules/cli/legacy-commands.js +37 -0
  5. package/dist/src/modules/cli/service.js +48 -40
  6. package/dist/src/modules/configuration/facade.js +1 -0
  7. package/dist/src/modules/configuration/project-config-defaults.json +2 -1
  8. package/dist/src/modules/configuration/project-config.js +20 -8
  9. package/dist/src/modules/configuration/update-config.js +16 -2
  10. package/dist/src/modules/dependencies.yaml +2 -2
  11. package/dist/src/modules/external.js +0 -2
  12. package/dist/src/modules/lifecycle/checkpoint-instructions.js +1 -1
  13. package/dist/src/modules/lifecycle/cleanup-ended-session.js +1 -1
  14. package/dist/src/modules/maintenance/cleanup-merged-branches.js +4 -4
  15. package/dist/src/modules/maintenance/initialize-codex-worktree.js +1 -1
  16. package/dist/src/modules/maintenance/remove-empty-directories.js +1 -1
  17. package/dist/src/modules/projects/check-project-requirements.txt +38 -57
  18. package/dist/src/modules/projects/check-project.js +19 -45
  19. package/dist/src/modules/projects/create-project-core.js +13 -32
  20. package/dist/src/modules/projects/generate-github-setup.js +16 -55
  21. package/dist/src/modules/projects/github-setup-prefix.sh +29 -2
  22. package/dist/src/modules/projects/github-setup-repository-template.sh +1 -40
  23. package/dist/src/modules/projects/github-setup-suffix-template.sh +7 -5
  24. package/dist/src/modules/projects/install-hooks.js +6 -5
  25. package/dist/src/modules/releases/configure-github.js +57 -0
  26. package/dist/src/modules/releases/facade.js +3 -2
  27. package/dist/src/modules/releases/github-configuration.js +166 -0
  28. package/dist/src/modules/releases/github-policy.js +45 -11
  29. package/dist/src/modules/releases/github-remote.js +230 -0
  30. package/dist/src/modules/testing/check-test-receipt.js +17 -22
  31. package/dist/src/modules/testing/receipt-state.js +27 -1
  32. package/dist/src/modules/testing/record-test-receipt.js +14 -13
  33. package/dist/src/modules/testing/run-tests.js +23 -14
  34. package/dist/src/modules/testing/types.js +1 -0
  35. package/package.json +5 -6
  36. package/dist/src/modules/projects/codex-setup-prefix.sh +0 -25
@@ -1,40 +1 @@
1
- # Verify repository access and personal ownership for {{OWNER}}/{{REPOSITORY_NAME}}.
2
- gh repo view '{{OWNER}}/{{REPOSITORY_NAME}}' >/dev/null
3
- if [[ "$(gh api 'repos/{{OWNER}}/{{REPOSITORY_NAME}}' --jq '.owner.login | ascii_downcase')" != '{{REQUIRED_APPROVER_LOWER}}' ]]; then
4
- printf 'Expected %s/%s to be owned by the personal account %s.\n' '{{OWNER}}' '{{REPOSITORY_NAME}}' '{{REQUIRED_APPROVER}}' >&2
5
- exit 1
6
- fi
7
-
8
- # Configure repository-wide branch cleanup, auto-merge, and merge methods.
9
- gh api --method PATCH 'repos/{{OWNER}}/{{REPOSITORY_NAME}}' {{REPOSITORY_PATCH_ARGUMENTS}} >/dev/null
10
-
11
- # Create or update one named ruleset without changing unrelated rulesets.
12
- upsert_ruleset() {
13
- local name=$1 ids count id
14
- ids=$(gh api --paginate 'repos/{{OWNER}}/{{REPOSITORY_NAME}}/rulesets?includes_parents=false' --jq ".[] | select(.name == \"$name\") | .id" </dev/null)
15
- count=$(printf '%s\n' "$ids" | sed '/^$/d' | wc -l | tr -d ' ')
16
- if [[ "$count" == 0 ]]; then
17
- gh api --method POST 'repos/{{OWNER}}/{{REPOSITORY_NAME}}/rulesets' --input - >/dev/null
18
- elif [[ "$count" == 1 ]]; then
19
- id=$ids
20
- gh api --method PUT 'repos/{{OWNER}}/{{REPOSITORY_NAME}}/rulesets/'"$id" --input - >/dev/null
21
- else
22
- printf 'Multiple rulesets named %s exist; remove duplicates before retrying.\n' "$name" >&2
23
- exit 1
24
- fi
25
- }
26
-
27
- # Protect the default branch with pull requests, merge commits, and strict CI.
28
- upsert_ruleset 'Peacekeeper base protection' <<'JSON'
29
- {{BASE_RULESET}}
30
- JSON
31
-
32
- # Require fresh code-owner approval while allowing the owner to bypass this rule.
33
- upsert_ruleset 'Peacekeeper owner approval' <<JSON
34
- {{APPROVAL_RULESET}}
35
- JSON
36
-
37
- # Remove legacy branch protection now superseded by the rulesets above.
38
- if gh api 'repos/{{OWNER}}/{{REPOSITORY_NAME}}/branches/{{DEFAULT_BRANCH}}/protection' >/dev/null 2>&1; then
39
- gh api --method DELETE 'repos/{{OWNER}}/{{REPOSITORY_NAME}}/branches/{{DEFAULT_BRANCH}}/protection' >/dev/null
40
- fi
1
+ configure_repository '{{REPOSITORY}}' '{{PLAN_NAME}}' '{{POLICY_PR}}' '{{SOURCE_REF}}'
@@ -1,5 +1,7 @@
1
- # Add every repository when synchronizing the release-policy secret.
2
- groundskeeper secrets sync --name RELEASE_POLICY_TOKEN {{NEW_REPO_ARGUMENTS}}
3
-
4
- # Confirm that every configuration step completed.
5
- printf 'GitHub configuration completed for all repositories.\n'
1
+ if [[ "$mode" == execute ]]; then
2
+ # Synchronize the release-policy secret only after every saved plan succeeded.
3
+ groundskeeper secrets sync --name RELEASE_POLICY_TOKEN {{NEW_REPO_ARGUMENTS}}
4
+ printf 'GitHub configuration and secret synchronization completed.\n'
5
+ else
6
+ printf 'Plans saved. Review them, then rerun this script with --execute and the same directory.\n'
7
+ fi
@@ -1,11 +1,12 @@
1
1
  export default ({ configuration, external: { fs, modulesRoot, output, path, runtime } }) => {
2
2
  const { repositoryRoot } = configuration;
3
3
  const DEFINITIONS = [
4
- ['SessionStart', 'checkpoint-codex-session-start', 30, 'Loading Codex checkpoint instructions'],
5
- ['Stop', 'checkpoint-codex-stop', 30, 'Checking for an uncommitted Codex checkpoint'],
6
- ['SessionEnd', 'cleanup-ended-session', 3, 'Scheduling merged branch cleanup'],
4
+ ['SessionStart', 'codex session-start', 30, 'Loading Codex checkpoint instructions'],
5
+ ['Stop', 'codex stop', 30, 'Checking for an uncommitted Codex checkpoint'],
6
+ ['SessionEnd', 'codex session-end', 3, 'Scheduling merged branch cleanup'],
7
7
  ];
8
- const COMMANDS = DEFINITIONS.map(([, command]) => command);
8
+ const COMMANDS = [...DEFINITIONS.map(([, command]) => command),
9
+ 'checkpoint-codex-session-start', 'checkpoint-codex-stop', 'cleanup-ended-session'];
9
10
  // Recognize complete, standalone invocations only. Shell composition, arguments,
10
11
  // environment assignments, and wrappers require inspection instead of replacement.
11
12
  function classifyCommand(command) {
@@ -14,7 +15,7 @@ export default ({ configuration, external: { fs, modulesRoot, output, path, runt
14
15
  const related = /peacekeeper|checkpoint-codex-(?:stop|session-start)|cleanup-ended-session/.test(command);
15
16
  if (!related)
16
17
  return 'other';
17
- const text = command.trim();
18
+ const text = command.trim().replace(/[ \t]+/gu, ' ');
18
19
  const action = COMMANDS.find((name) => text.endsWith(` ${name}`) || text.endsWith(`\t${name}`));
19
20
  if (!action) {
20
21
  const legacy = /^(?:node\s+)(?:\.\/)?(?:node_modules\/@jakobm\/peacekeeper\/)?scripts\/(checkpoint-codex-stop|checkpoint-codex-session-start|cleanup-ended-session)\.js$/;
@@ -0,0 +1,57 @@
1
+ export default ({ githubConfiguration, external: { fs, packageVersion, runtime } }) => {
2
+ function run(options) {
3
+ let result;
4
+ try {
5
+ if (options.execute) {
6
+ if (!options.planFile || options.policyPr || options.sourceRef) {
7
+ throw new Error('--execute requires --plan-file and cannot override the policy source.');
8
+ }
9
+ if (fs.statSync(options.planFile).size > 16 * 1024 * 1024)
10
+ throw new Error('Plan file exceeds 16 MiB.');
11
+ const saved = JSON.parse(fs.readFileSync(options.planFile, 'utf8'));
12
+ if (options.repository && options.repository.toLowerCase() !== saved?.repository?.slug?.toLowerCase()) {
13
+ throw new Error('--repository does not match the saved plan target.');
14
+ }
15
+ result = githubConfiguration.execute(saved);
16
+ }
17
+ else {
18
+ if (!options.repository)
19
+ throw new Error('--repository is required when planning.');
20
+ const plan = githubConfiguration.plan(options);
21
+ if (options.planFile)
22
+ fs.writeFileSync(options.planFile, `${JSON.stringify(plan, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
23
+ result = { status: plan.blockers.length ? 'blocked' : 'planned', plan };
24
+ }
25
+ }
26
+ catch (error) {
27
+ const message = error instanceof Error ? error.message : String(error);
28
+ result = { status: options.execute ? 'failed' : 'blocked', error: message, blockers: [message],
29
+ ...(options.execute ? { completed: [] } : {}) };
30
+ }
31
+ result = { resultFormatVersion: 1, peacekeeperVersion: packageVersion, ...result };
32
+ if (options.json)
33
+ runtime.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
34
+ else {
35
+ runtime.stdout.write(`GitHub configuration: ${result.status}\n`);
36
+ if (result.plan) {
37
+ runtime.stdout.write(`${result.plan.repository.slug} at ${result.plan.source.sha}\n`);
38
+ runtime.stdout.write(`${result.plan.changes.length} change(s); configuration source: ${result.plan.configSource}.\n`);
39
+ runtime.stdout.write('Scope: all repository-owned branch rulesets and all classic protections, including other branches.\n');
40
+ runtime.stdout.write(`${JSON.stringify(result.plan.changes, null, 2)}\n`);
41
+ for (const blocker of result.plan.blockers)
42
+ runtime.stdout.write(`Blocker: ${blocker}\n`);
43
+ }
44
+ if (result.bootstrap || result.plan?.bootstrap)
45
+ runtime.stdout.write('Bootstrap: CODEOWNERS from the policy PR takes effect after merging into the default branch.\n');
46
+ for (const blocker of result.blockers || [])
47
+ runtime.stdout.write(`Blocker: ${blocker}\n`);
48
+ if (result.error)
49
+ runtime.stderr.write(`${result.error}\n`);
50
+ if (result.completed)
51
+ runtime.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
52
+ }
53
+ if (!['planned', 'succeeded'].includes(result.status))
54
+ runtime.exitCode = 1;
55
+ }
56
+ return { run };
57
+ };
@@ -1,8 +1,9 @@
1
- export const porticoFacade = ({ assessRelease, githubPolicy, release, releaseCore, verifyRelease, verifyReleaseProtection, verifyReleaseVersion }) => ({
1
+ export const porticoFacade = ({ assessRelease, configureGithub, githubConfiguration, githubPolicy, release, releaseCore, verifyRelease, verifyReleaseProtection, verifyReleaseVersion }) => ({
2
2
  assessRelease: assessRelease.run,
3
+ configureGithub: configureGithub.run,
4
+ planGithub: githubConfiguration.plan,
3
5
  createGithubPolicy: githubPolicy.createGithubPolicy,
4
6
  ensureLockfilesMatch: releaseCore.ensureLockfilesMatch,
5
- githubSetupPlan: githubPolicy.setupPlan,
6
7
  inspectWorkflow: releaseCore.inspectWorkflow,
7
8
  release: release.run,
8
9
  verifyRelease: verifyRelease.run,
@@ -0,0 +1,166 @@
1
+ export default ({ githubPolicy, githubRemote, external: { packageVersion } }) => {
2
+ const { canonical, createGithubPolicy, exactPolicy, same } = githubPolicy;
3
+ const { loadSource, inventory, request, graphql } = githubRemote;
4
+ function inheritedBlockers(observed, desired) {
5
+ // A matching inherited rule is compatible when it contributes an already
6
+ // canonical requirement. Otherwise only its organization can resolve it.
7
+ const canonicalRules = desired.rulesets.flatMap(ruleset => ruleset.rules);
8
+ return observed.inheritedRulesets.filter(item => item.policy.enforcement === 'active'
9
+ && item.policy.rules.some(rule => !canonicalRules.some(expected => same(rule, expected))))
10
+ .map(item => `Inherited branch ruleset ${item.id} (${item.source}: ${item.policy.name}) prevents proving the exact policy; resolve it at its source.`);
11
+ }
12
+ function changesFor(observed, desired) {
13
+ const changes = [];
14
+ if (!same(observed.repository, desired.repository))
15
+ changes.push({ kind: 'repository', action: 'update',
16
+ before: observed.repository, after: desired.repository });
17
+ const retained = new Set();
18
+ for (const wanted of desired.rulesets) {
19
+ const candidates = observed.rulesets.filter(item => item.policy.name === wanted.name)
20
+ .sort((a, b) => Number(same(b.policy, wanted)) - Number(same(a.policy, wanted)) || a.id - b.id);
21
+ const existing = candidates[0];
22
+ if (!existing)
23
+ changes.push({ kind: 'ruleset', action: 'create', after: wanted });
24
+ else {
25
+ retained.add(existing.id);
26
+ if (!same(existing.policy, wanted))
27
+ changes.push({ kind: 'ruleset', action: 'update',
28
+ id: existing.id, before: existing.policy, after: wanted });
29
+ }
30
+ }
31
+ for (const item of [...observed.rulesets].sort((a, b) => a.id - b.id)) {
32
+ if (!retained.has(item.id))
33
+ changes.push({ kind: 'ruleset', action: 'delete', id: item.id, before: item.policy });
34
+ }
35
+ for (const item of observed.classicProtections)
36
+ changes.push({ kind: 'classic-protection', action: 'delete', id: item.id, before: item });
37
+ return changes;
38
+ }
39
+ function plan(options) {
40
+ const { metadata, source, config, configSource, requiredApprover, blockers } = loadSource(options);
41
+ const policy = createGithubPolicy({ branch: source.defaultBranch, checks: config.git.releaseRequiredChecks, requiredApprover });
42
+ const desired = exactPolicy(policy, metadata.owner.id);
43
+ const observed = inventory(metadata, desired.repository);
44
+ return {
45
+ formatVersion: 1, peacekeeperVersion: packageVersion,
46
+ repository: { id: metadata.id, slug: metadata.full_name }, source,
47
+ bootstrap: source.kind === 'pull-request', configSource, observed, desired,
48
+ changes: changesFor(observed, desired), blockers: [...blockers, ...inheritedBlockers(observed, desired)].sort(),
49
+ };
50
+ }
51
+ function refreshed(saved) {
52
+ return plan({ repository: saved.repository.slug,
53
+ ...(saved.source.kind === 'pull-request' ? { policyPr: String(saved.source.policyPr) } : {}),
54
+ sourceRef: saved.source.sha });
55
+ }
56
+ function validate(saved) {
57
+ if (!saved || saved.formatVersion !== 1 || saved.peacekeeperVersion !== packageVersion) {
58
+ throw new Error('Plan format or Peacekeeper version does not match; create a new plan with this version.');
59
+ }
60
+ if (!Number.isSafeInteger(saved.repository?.id) || typeof saved.repository?.slug !== 'string'
61
+ || !['default-branch', 'pull-request'].includes(saved.source?.kind)
62
+ || typeof saved.source.sha !== 'string' || !/^[a-f0-9]{40}$/u.test(saved.source.sha)
63
+ || (saved.source.kind === 'pull-request' && (!Number.isSafeInteger(saved.source.policyPr) || saved.source.policyPr <= 0))) {
64
+ throw new Error('Invalid saved plan identity or policy source.');
65
+ }
66
+ const current = refreshed(saved);
67
+ if (!same(saved, current))
68
+ throw new Error('Plan does not match the canonical policy and current GitHub preconditions; create a new plan.');
69
+ return current;
70
+ }
71
+ function readback(plan) {
72
+ // Inspect remaining configuration even when the policy ref moved or its PR
73
+ // closed. Such a source must not prevent reporting a partially applied state.
74
+ try {
75
+ const metadata = request(`repos/${plan.repository.slug}`);
76
+ if (metadata?.id !== plan.repository.id || metadata.full_name !== plan.repository.slug) {
77
+ throw new Error('Repository identity changed during read-back.');
78
+ }
79
+ return { observed: inventory(metadata, plan.desired.repository) };
80
+ }
81
+ catch (error) {
82
+ return { readbackError: message(error) };
83
+ }
84
+ }
85
+ function assertCurrent(plan, expected, deleting) {
86
+ const current = refreshed(plan);
87
+ const { changes: _changes, observed: _observed, ...identity } = current;
88
+ const { changes: _originalChanges, observed: _originalObserved, ...originalIdentity } = plan;
89
+ if (!same(identity, originalIdentity) || !same(current.observed, expected)) {
90
+ throw new Error('GitHub preconditions changed during execution; stop and create a new plan.');
91
+ }
92
+ if (deleting && plan.desired.rulesets.some(wanted => !current.observed.rulesets.some(item => same(item.policy, wanted)))) {
93
+ throw new Error('Canonical branch protections must be established and read back before any deletion.');
94
+ }
95
+ return current;
96
+ }
97
+ function apply(slug, change, expected) {
98
+ const base = `repos/${slug}`;
99
+ if (change.kind === 'repository') {
100
+ request(base, 'PATCH', change.after);
101
+ expected.repository = change.after;
102
+ }
103
+ else if (change.kind === 'classic-protection') {
104
+ const result = graphql(`mutation PeacekeeperDeleteProtection($id:ID!) {
105
+ deleteBranchProtectionRule(input:{branchProtectionRuleId:$id}) { clientMutationId }
106
+ }`, { id: change.id });
107
+ if (!result.deleteBranchProtectionRule)
108
+ throw new Error('GitHub did not confirm classic protection deletion.');
109
+ expected.classicProtections = expected.classicProtections.filter(item => item.id !== change.id);
110
+ }
111
+ else if (change.action === 'delete') {
112
+ request(`${base}/rulesets/${change.id}`, 'DELETE');
113
+ expected.rulesets = expected.rulesets.filter(item => item.id !== change.id);
114
+ }
115
+ else {
116
+ const endpoint = change.action === 'create' ? `${base}/rulesets` : `${base}/rulesets/${change.id}`;
117
+ const result = request(endpoint, change.action === 'create' ? 'POST' : 'PUT', change.after);
118
+ const id = change.action === 'create' ? result?.id : change.id;
119
+ if (!Number.isSafeInteger(id) || (change.action === 'create' && expected.rulesets.some(item => item.id === id))) {
120
+ throw new Error('GitHub did not return a valid new ruleset identity.');
121
+ }
122
+ expected.rulesets = expected.rulesets.filter(item => item.id !== id);
123
+ expected.rulesets.push({ id: id, policy: change.after });
124
+ }
125
+ }
126
+ function execute(saved) {
127
+ let current;
128
+ try {
129
+ current = validate(saved);
130
+ }
131
+ catch (error) {
132
+ return { status: 'stale', error: message(error), completed: [] };
133
+ }
134
+ if (current.blockers.length)
135
+ return { status: 'blocked', blockers: current.blockers,
136
+ completed: [], bootstrap: current.bootstrap };
137
+ const expected = canonical(current.observed);
138
+ const completed = [];
139
+ let attempted;
140
+ try {
141
+ for (const change of current.changes) {
142
+ assertCurrent(current, expected, change.action === 'delete');
143
+ attempted = change;
144
+ apply(current.repository.slug, change, expected);
145
+ completed.push(change);
146
+ attempted = undefined;
147
+ }
148
+ }
149
+ catch (error) {
150
+ return { status: completed.length || attempted ? 'partial' : 'stale', error: message(error),
151
+ completed, ...(attempted ? { attempted } : {}), ...readback(current), bootstrap: current.bootstrap };
152
+ }
153
+ try {
154
+ const final = assertCurrent(current, expected, false);
155
+ if (final.blockers.length || final.changes.length)
156
+ throw new Error('Read-back state does not match the exact canonical policy.');
157
+ return { status: 'succeeded', completed, observed: final.observed, bootstrap: current.bootstrap };
158
+ }
159
+ catch (error) {
160
+ return { status: 'verification-failed', completed, error: message(error),
161
+ ...readback(current), bootstrap: current.bootstrap };
162
+ }
163
+ }
164
+ function message(error) { return error instanceof Error ? error.message : String(error); }
165
+ return { plan, execute };
166
+ };
@@ -63,18 +63,52 @@ export default ({ external: { fs, modulesRoot, path, structuredClone } }) => {
63
63
  repository: base.repository,
64
64
  baseRuleset: base.ruleset,
65
65
  approvalRuleset: ownerApproval.ruleset,
66
+ absence: { otherRepositoryBranchRulesets: true, classicBranchProtections: true },
66
67
  };
67
68
  }
68
- function setupPlan(policy) {
69
- return {
70
- branch: policy.branch,
71
- branchPath: encodeURIComponent(policy.branch),
72
- repositoryPatchArguments: Object.entries(policy.repository)
73
- .map(([name, value]) => `-F ${name}=${value}`).join(' '),
74
- baseRuleset: JSON.stringify(policy.baseRuleset, null, 2),
75
- approvalRuleset: JSON.stringify(policy.approvalRuleset, null, 2)
76
- .replace(JSON.stringify(ownerIdMarker), "$(gh api 'users/{{REQUIRED_APPROVER}}' --jq .id)"),
77
- };
69
+ // All policy arrays represent unordered sets (rules, actors, refs and checks).
70
+ // Preserve unknown policy fields, but ignore GitHub's response metadata.
71
+ function canonical(value) {
72
+ if (Array.isArray(value))
73
+ return value.map(canonical)
74
+ .sort((a, b) => JSON.stringify(a) < JSON.stringify(b) ? -1 : JSON.stringify(a) > JSON.stringify(b) ? 1 : 0);
75
+ if (value && typeof value === 'object')
76
+ return Object.fromEntries(Object.keys(value).sort()
77
+ .map(key => [key, canonical(value[key])]));
78
+ return value;
79
+ }
80
+ function normalizeRuleset(ruleset) {
81
+ const rules = ruleset.rules.map(rule => {
82
+ const parameters = structuredClone(rule.parameters || {});
83
+ if (rule.type === 'pull_request') {
84
+ // GitHub defaults this newer parameter to true when it is omitted.
85
+ parameters.require_extra_approval_for_unattributed_changes ??= true;
86
+ // GitHub adds this empty field even when it was not supplied.
87
+ if (Array.isArray(parameters.required_reviewers) && parameters.required_reviewers.length === 0)
88
+ delete parameters.required_reviewers;
89
+ }
90
+ if (rule.type === 'required_status_checks' && Array.isArray(parameters.required_status_checks)) {
91
+ parameters.required_status_checks = parameters.required_status_checks.map(check => {
92
+ const result = { ...check };
93
+ if (result.integration_id === null)
94
+ delete result.integration_id;
95
+ return result;
96
+ });
97
+ }
98
+ const { parameters: _parameters, ...fields } = rule;
99
+ return { ...fields, ...(Object.keys(parameters).length ? { parameters } : {}) };
100
+ });
101
+ return canonical({ name: ruleset.name, target: ruleset.target, enforcement: ruleset.enforcement,
102
+ bypass_actors: ruleset.bypass_actors, conditions: ruleset.conditions, rules });
103
+ }
104
+ function exactPolicy(policy, ownerId) {
105
+ const approval = structuredClone(policy.approvalRuleset);
106
+ approval.bypass_actors[0].actor_id = ownerId;
107
+ return canonical({ repository: policy.repository,
108
+ rulesets: [policy.baseRuleset, approval].map(normalizeRuleset), absence: policy.absence });
109
+ }
110
+ function same(actual, expected) {
111
+ return JSON.stringify(canonical(actual)) === JSON.stringify(canonical(expected));
78
112
  }
79
113
  function sameMembers(actual, expected) {
80
114
  return actual.length === expected.length
@@ -122,6 +156,6 @@ export default ({ external: { fs, modulesRoot, path, structuredClone } }) => {
122
156
  return matchesShape(withoutBypass(expected), actual);
123
157
  }
124
158
  const api = { approvalParameters, createGithubPolicy, managedRulesetMatches,
125
- requiredCheckContexts, sameMembers, setupPlan };
159
+ requiredCheckContexts, sameMembers, canonical, normalizeRuleset, exactPolicy, same };
126
160
  return api;
127
161
  };
@@ -0,0 +1,230 @@
1
+ export default ({ configuration, githubPolicy, external: { buffer: Buffer, projectConfigDefaults, spawnSync, structuredClone, YAML, } }) => {
2
+ const { canonical, normalizeRuleset } = githubPolicy;
3
+ const shaPattern = /^[a-f0-9]{40}$/u;
4
+ function request(endpoint, method = 'GET', body) {
5
+ const args = ['api', '--hostname', 'github.com', '--method', method, endpoint];
6
+ if (body !== undefined)
7
+ args.push('--input', '-');
8
+ const result = spawnSync('gh', args, { encoding: 'utf8',
9
+ ...(body === undefined ? {} : { input: JSON.stringify(body) }) });
10
+ if (result.error || result.status !== 0)
11
+ throw new Error(`GitHub ${method} ${endpoint}: ${result.error?.message || result.stderr?.trim() || `exit ${result.status}`}`);
12
+ if (method === 'DELETE' && !result.stdout?.trim())
13
+ return undefined;
14
+ let response;
15
+ try {
16
+ response = JSON.parse(result.stdout);
17
+ }
18
+ catch {
19
+ throw new Error(`GitHub returned invalid JSON for ${endpoint}.`);
20
+ }
21
+ if (response?.errors?.length)
22
+ throw new Error(`GitHub ${endpoint}: ${response.errors.map(error => error.message).join('; ')}`);
23
+ return response;
24
+ }
25
+ function graphql(query, variables) {
26
+ const result = request('graphql', 'POST', { query, variables });
27
+ if (!result?.data)
28
+ throw new Error('GitHub returned incomplete GraphQL data.');
29
+ return result.data;
30
+ }
31
+ function repositorySlug(value) {
32
+ if (typeof value !== 'string' || !/^[A-Za-z0-9-]+\/[A-Za-z0-9_.-]+$/u.test(value)
33
+ || ['.', '..'].includes(value.split('/')[1]))
34
+ throw new Error('--repository must be OWNER/REPO on github.com.');
35
+ return value;
36
+ }
37
+ function commitSha(value) {
38
+ if (typeof value !== 'string' || !shaPattern.test(value))
39
+ throw new Error('GitHub did not return an exact commit SHA.');
40
+ return value;
41
+ }
42
+ function readTree(slug, sha) {
43
+ const response = request(`repos/${slug}/git/trees/${sha}`);
44
+ if (!Array.isArray(response?.tree) || response.truncated !== false)
45
+ throw new Error('Cannot completely inspect the policy source tree.');
46
+ return response.tree;
47
+ }
48
+ function readBlob(slug, sha, name, tree, basename = name) {
49
+ const entry = tree.find(item => item.path === basename);
50
+ if (!entry)
51
+ return undefined;
52
+ if (entry.type !== 'blob' || !['100644', '100755'].includes(entry.mode))
53
+ throw new Error(`${name} must be a regular file.`);
54
+ const file = request(`repos/${slug}/contents/${name}?ref=${sha}`);
55
+ if (file?.type !== 'file' || file.encoding !== 'base64' || typeof file.content !== 'string' || file.sha !== entry.sha) {
56
+ throw new Error(`GitHub returned invalid policy file contents for ${name}.`);
57
+ }
58
+ return Buffer.from(file.content, 'base64').toString('utf8');
59
+ }
60
+ function loadSource({ repository, policyPr, sourceRef }) {
61
+ const slug = repositorySlug(repository);
62
+ if (sourceRef !== undefined && !shaPattern.test(sourceRef))
63
+ throw new Error('--source-ref must be a full lowercase commit SHA.');
64
+ const metadata = request(`repos/${slug}`);
65
+ if (!Number.isSafeInteger(metadata?.id) || typeof metadata.full_name !== 'string'
66
+ || metadata.full_name.toLowerCase() !== slug.toLowerCase()
67
+ || typeof metadata.default_branch !== 'string' || !metadata.default_branch
68
+ || !Number.isSafeInteger(metadata.owner?.id) || typeof metadata.owner.login !== 'string') {
69
+ throw new Error('GitHub returned incomplete repository metadata.');
70
+ }
71
+ const base = `repos/${metadata.full_name}`;
72
+ const defaultSha = commitSha(request(`${base}/commits/${encodeURIComponent(metadata.default_branch)}`).sha);
73
+ let sha = defaultSha;
74
+ let number;
75
+ if (policyPr !== undefined) {
76
+ if (!/^[1-9][0-9]*$/u.test(String(policyPr)) || !Number.isSafeInteger(Number(policyPr)))
77
+ throw new Error('--policy-pr must be a positive PR number.');
78
+ number = Number(policyPr);
79
+ const pr = request(`${base}/pulls/${number}`);
80
+ if (pr?.number !== number || pr.state !== 'open' || pr.base?.repo?.id !== metadata.id
81
+ || pr.head?.repo?.id !== metadata.id || pr.base?.ref !== metadata.default_branch) {
82
+ throw new Error('Policy PR must be open, originate in this repository and target its current default branch.');
83
+ }
84
+ sha = commitSha(pr.head.sha);
85
+ }
86
+ if (sourceRef !== undefined && sourceRef !== sha)
87
+ throw new Error('Policy source moved from --source-ref; create a new plan.');
88
+ const root = readTree(metadata.full_name, sha);
89
+ const contents = readBlob(metadata.full_name, sha, 'peacekeeper.config.yaml', root);
90
+ let config;
91
+ if (contents === undefined) {
92
+ if (root.some(item => item.path === 'peacekeeper.config.json'))
93
+ throw new Error('Rename legacy peacekeeper.config.json to peacekeeper.config.yaml and convert it to YAML.');
94
+ config = structuredClone(projectConfigDefaults);
95
+ }
96
+ else {
97
+ try {
98
+ config = YAML.parse(contents);
99
+ }
100
+ catch (error) {
101
+ throw new Error(`peacekeeper.config.yaml: ${error instanceof Error ? error.message : String(error)}`);
102
+ }
103
+ }
104
+ configuration.validateConfig(config, `${metadata.full_name}/peacekeeper.config.yaml`);
105
+ const requiredApprover = config.git.requiredApprover || metadata.owner.login;
106
+ const blockers = [];
107
+ if (metadata.owner.type !== 'User' || requiredApprover.toLowerCase() !== metadata.owner.login.toLowerCase()) {
108
+ blockers.push('git.requiredApprover must be the personal GitHub repository owner.');
109
+ }
110
+ const github = root.find(item => item.path === '.github');
111
+ if (github && github.type !== 'tree')
112
+ throw new Error('.github must be a directory in the policy source.');
113
+ const tree = github ? readTree(metadata.full_name, github.sha) : [];
114
+ const codeowners = readBlob(metadata.full_name, sha, '.github/CODEOWNERS', tree, 'CODEOWNERS');
115
+ const codeownersError = configuration.codeownersError(codeowners, requiredApprover);
116
+ if (codeownersError)
117
+ blockers.push(codeownersError);
118
+ const source = { kind: number === undefined ? 'default-branch' : 'pull-request',
119
+ sha, defaultBranch: metadata.default_branch, defaultSha, ...(number === undefined ? {} : { policyPr: number }) };
120
+ return { metadata, config, requiredApprover, blockers, source,
121
+ configSource: contents === undefined ? 'defaults' : 'remote' };
122
+ }
123
+ function restPages(endpoint) {
124
+ const all = [];
125
+ for (let page = 1;; page += 1) {
126
+ const batch = request(`${endpoint}${endpoint.includes('?') ? '&' : '?'}per_page=100&page=${page}`);
127
+ if (!Array.isArray(batch))
128
+ throw new Error(`Cannot completely inventory ${endpoint}.`);
129
+ all.push(...batch);
130
+ if (batch.length < 100)
131
+ return all;
132
+ }
133
+ }
134
+ function connectionPages(read) {
135
+ let cursor = null;
136
+ const cursors = new Set();
137
+ const result = [];
138
+ for (;;) {
139
+ const connection = read(cursor);
140
+ if (!Array.isArray(connection?.nodes) || connection.nodes.some(node => !node)
141
+ || typeof connection.pageInfo?.hasNextPage !== 'boolean')
142
+ throw new Error('Cannot completely inventory GitHub protection rules.');
143
+ result.push(...connection.nodes);
144
+ if (!connection.pageInfo.hasNextPage)
145
+ return result;
146
+ cursor = connection.pageInfo.endCursor;
147
+ if (!cursor || cursors.has(cursor))
148
+ throw new Error('GitHub returned invalid protection pagination.');
149
+ cursors.add(cursor);
150
+ }
151
+ }
152
+ const protectionFields = `id pattern allowsDeletions allowsForcePushes blocksCreations
153
+ dismissesStaleReviews isAdminEnforced lockAllowsFetchAndMerge lockBranch requireLastPushApproval
154
+ requiredApprovingReviewCount requiredDeploymentEnvironments requiredStatusCheckContexts
155
+ requiredStatusChecks { context app { id } }
156
+ requiresApprovingReviews requiresCodeOwnerReviews requiresCommitSignatures
157
+ requiresConversationResolution requiresDeployments requiresLinearHistory requiresStatusChecks
158
+ requiresStrictStatusChecks restrictsPushes restrictsReviewDismissals`;
159
+ function classicProtections(slug) {
160
+ const [owner, name] = slug.split('/');
161
+ const query = `query PeacekeeperProtections($owner:String!,$name:String!,$cursor:String) {
162
+ repository(owner:$owner,name:$name) { branchProtectionRules(first:100,after:$cursor) {
163
+ nodes { ${protectionFields} } pageInfo { hasNextPage endCursor }
164
+ } }
165
+ }`;
166
+ const rules = connectionPages(cursor => graphql(query, { owner, name, cursor }).repository?.branchProtectionRules);
167
+ if (new Set(rules.map(rule => rule.id)).size !== rules.length)
168
+ throw new Error('Duplicate classic protection IDs in inventory.');
169
+ for (const rule of rules) {
170
+ if (typeof rule.id !== 'string' || !rule.id || typeof rule.pattern !== 'string')
171
+ throw new Error('GitHub returned invalid classic protection.');
172
+ for (const field of ['pushAllowances', 'reviewDismissalAllowances', 'bypassPullRequestAllowances', 'bypassForcePushAllowances']) {
173
+ const allowances = connectionPages(cursor => graphql(`query PeacekeeperAllowances($id:ID!,$cursor:String) {
174
+ node(id:$id) { ... on BranchProtectionRule { ${field}(first:100,after:$cursor) {
175
+ nodes { actor { __typename ... on Node { id } } } pageInfo { hasNextPage endCursor }
176
+ } } }
177
+ }`, { id: rule.id, cursor }).node?.[field]);
178
+ if (allowances.some(item => typeof item.actor?.id !== 'string'))
179
+ throw new Error('Cannot inspect classic protection allowance actors.');
180
+ rule[field] = allowances;
181
+ }
182
+ }
183
+ return canonical(rules);
184
+ }
185
+ function readRuleset(base, summary) {
186
+ if (!Number.isSafeInteger(summary.id))
187
+ throw new Error('GitHub returned invalid ruleset identity.');
188
+ const ruleset = request(`${base}/rulesets/${summary.id}`);
189
+ if (ruleset?.id !== summary.id || ruleset.target !== 'branch'
190
+ || ruleset.source !== summary.source || ruleset.source_type !== summary.source_type
191
+ || typeof ruleset.name !== 'string' || !['active', 'disabled', 'evaluate'].includes(ruleset.enforcement)
192
+ || !Array.isArray(ruleset.rules) || !Array.isArray(ruleset.bypass_actors)
193
+ || !ruleset.conditions?.ref_name || !Array.isArray(ruleset.conditions.ref_name.include)
194
+ || !Array.isArray(ruleset.conditions.ref_name.exclude))
195
+ throw new Error(`Cannot fully inspect branch ruleset ${summary.id}, including bypass actors.`);
196
+ return { id: summary.id, policy: normalizeRuleset(ruleset) };
197
+ }
198
+ function inventory(metadata, repositoryFields) {
199
+ const base = `repos/${metadata.full_name}`;
200
+ const repository = Object.fromEntries(Object.keys(repositoryFields).map(key => {
201
+ if (typeof metadata[key] !== 'boolean')
202
+ throw new Error(`Cannot inspect repository setting ${key}.`);
203
+ return [key, metadata[key]];
204
+ }));
205
+ const owned = restPages(`${base}/rulesets?includes_parents=false`);
206
+ const all = restPages(`${base}/rulesets?includes_parents=true`);
207
+ if (owned.some(rule => rule.source_type !== 'Repository' || rule.source !== metadata.full_name)) {
208
+ throw new Error('Cannot determine repository ruleset ownership.');
209
+ }
210
+ if (owned.some(rule => !['branch', 'tag', 'push'].includes(rule.target)))
211
+ throw new Error('Cannot determine ruleset target.');
212
+ if (all.some(rule => !['branch', 'tag', 'push'].includes(rule.target)
213
+ || !['Repository', 'Organization', 'Enterprise'].includes(rule.source_type)))
214
+ throw new Error('Cannot determine inherited ruleset ownership.');
215
+ const ownedIds = owned.filter(rule => rule.target === 'branch').map(rule => rule.id);
216
+ const allOwnedIds = all.filter(rule => rule.target === 'branch' && rule.source_type === 'Repository'
217
+ && rule.source === metadata.full_name).map(rule => rule.id);
218
+ if (new Set(all.map(rule => rule.id)).size !== all.length
219
+ || !githubPolicy.same(ownedIds, allOwnedIds))
220
+ throw new Error('Ruleset inventory changed between requests; create a new plan.');
221
+ const rulesets = owned.filter(rule => rule.target === 'branch').map(rule => readRuleset(base, rule));
222
+ const inheritedRulesets = all.filter(rule => rule.target === 'branch'
223
+ && (rule.source_type !== 'Repository' || rule.source !== metadata.full_name))
224
+ .map(rule => ({ ...readRuleset(base, rule), source: rule.source }));
225
+ if (new Set(rulesets.map(rule => rule.id)).size !== rulesets.length)
226
+ throw new Error('Duplicate ruleset IDs in inventory.');
227
+ return canonical({ repository, rulesets, inheritedRulesets, classicProtections: classicProtections(metadata.full_name) });
228
+ }
229
+ return { request, graphql, repositorySlug, loadSource, inventory };
230
+ };