@jakobm/peacekeeper 0.25.2 → 0.27.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 +464 -89
- package/dist/cmdabra.yaml +174 -110
- package/dist/package.json +6 -5
- package/dist/src/modules/cli/legacy-commands.js +37 -0
- package/dist/src/modules/cli/service.js +48 -39
- package/dist/src/modules/configuration/convention-rules.js +93 -0
- package/dist/src/modules/configuration/facade.js +1 -0
- package/dist/src/modules/configuration/project-config-defaults.json +5 -1
- package/dist/src/modules/configuration/project-config.js +28 -9
- package/dist/src/modules/configuration/update-config.js +16 -2
- package/dist/src/modules/dependencies.yaml +4 -4
- package/dist/src/modules/external.js +5 -0
- package/dist/src/modules/lifecycle/checkpoint-instructions.js +1 -1
- package/dist/src/modules/lifecycle/cleanup-ended-session.js +1 -1
- package/dist/src/modules/maintenance/cleanup-merged-branches.js +4 -4
- package/dist/src/modules/maintenance/initialize-codex-worktree.js +1 -1
- package/dist/src/modules/maintenance/remove-empty-directories.js +1 -1
- package/dist/src/modules/projects/check-project-requirements.txt +32 -31
- package/dist/src/modules/projects/check-project.js +16 -16
- package/dist/src/modules/projects/codex-setup-prefix.sh +2 -2
- package/dist/src/modules/projects/create-project-core.js +13 -28
- package/dist/src/modules/projects/generate-github-setup.js +16 -55
- package/dist/src/modules/projects/github-setup-prefix.sh +29 -2
- package/dist/src/modules/projects/github-setup-repository-template.sh +1 -40
- package/dist/src/modules/projects/github-setup-suffix-template.sh +7 -5
- package/dist/src/modules/projects/install-hooks.js +6 -5
- package/dist/src/modules/releases/configure-github.js +57 -0
- package/dist/src/modules/releases/facade.js +3 -2
- package/dist/src/modules/releases/github-configuration.js +166 -0
- package/dist/src/modules/releases/github-policy.js +45 -11
- package/dist/src/modules/releases/github-remote.js +230 -0
- package/dist/src/modules/testing/check-conventions.js +41 -0
- package/dist/src/modules/testing/check-test-receipt.js +17 -22
- package/dist/src/modules/testing/conventions.js +168 -0
- package/dist/src/modules/testing/facade.js +2 -1
- package/dist/src/modules/testing/receipt-state.js +27 -1
- package/dist/src/modules/testing/record-test-receipt.js +14 -13
- package/dist/src/modules/testing/run-tests.js +23 -14
- package/dist/src/modules/testing/types.js +1 -0
- package/package.json +6 -5
|
@@ -1,59 +1,20 @@
|
|
|
1
|
-
export default ({
|
|
2
|
-
|
|
3
|
-
const { githubSetup, repositoryIdentity } = createProjectCore;
|
|
4
|
-
function api(endpoint, missingAllowed = false) {
|
|
5
|
-
const response = spawnSync('gh', ['api', '--hostname', 'github.com', '--method', 'GET', endpoint], {
|
|
6
|
-
encoding: 'utf8',
|
|
7
|
-
});
|
|
8
|
-
if (response.status === 0) {
|
|
9
|
-
try {
|
|
10
|
-
return JSON.parse(response.stdout);
|
|
11
|
-
}
|
|
12
|
-
catch {
|
|
13
|
-
throw new Error(`GitHub returned invalid JSON for ${endpoint}.`);
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
if (missingAllowed && /HTTP 404\b/u.test(response.stderr || ''))
|
|
17
|
-
return undefined;
|
|
18
|
-
throw new Error(`Cannot read GitHub configuration (${endpoint}): ${response.error?.message
|
|
19
|
-
|| response.stderr?.trim() || `exit ${response.status}`}`);
|
|
20
|
-
}
|
|
21
|
-
function loadRepositorySetup(repository) {
|
|
22
|
-
const identity = repositoryIdentity(repository);
|
|
23
|
-
const slug = `${identity.owner}/${identity.repositoryName}`;
|
|
24
|
-
const metadata = api(`repos/${slug}`);
|
|
25
|
-
if (typeof metadata?.default_branch !== 'string' || !metadata.default_branch) {
|
|
26
|
-
throw new Error(`GitHub did not return a default branch for ${slug}.`);
|
|
27
|
-
}
|
|
28
|
-
const endpoint = `repos/${slug}/contents/peacekeeper.config.yaml?ref=${encodeURIComponent(metadata.default_branch)}`;
|
|
29
|
-
const file = api(endpoint, true);
|
|
30
|
-
let config;
|
|
31
|
-
if (file === undefined) {
|
|
32
|
-
const legacyEndpoint = `repos/${slug}/contents/peacekeeper.config.json?ref=${encodeURIComponent(metadata.default_branch)}`;
|
|
33
|
-
if (api(legacyEndpoint, true) !== undefined) {
|
|
34
|
-
throw new Error(`${slug}/peacekeeper.config.json: rename this legacy JSON configuration to peacekeeper.config.yaml and convert it to YAML.`);
|
|
35
|
-
}
|
|
36
|
-
config = structuredClone(projectConfigDefaults);
|
|
37
|
-
}
|
|
38
|
-
else {
|
|
39
|
-
if (file.type !== 'file' || file.encoding !== 'base64' || typeof file.content !== 'string') {
|
|
40
|
-
throw new Error(`${slug}/peacekeeper.config.yaml: GitHub returned invalid file contents.`);
|
|
41
|
-
}
|
|
42
|
-
try {
|
|
43
|
-
config = YAML.parse(Buffer.from(file.content, 'base64').toString('utf8'));
|
|
44
|
-
}
|
|
45
|
-
catch (error) {
|
|
46
|
-
throw new Error(`${slug}/peacekeeper.config.yaml: ${error instanceof Error ? error.message : String(error)}`);
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
validateConfig(config, `${slug}/peacekeeper.config.yaml`);
|
|
50
|
-
return { ...identity, requiredChecks: config.git.releaseRequiredChecks,
|
|
51
|
-
requiredApprover: config.git.requiredApprover || identity.owner,
|
|
52
|
-
defaultBranch: metadata.default_branch };
|
|
53
|
-
}
|
|
54
|
-
function run({ repository: repositories }) {
|
|
1
|
+
export default ({ createProjectCore, releases, external: { runtime } }) => {
|
|
2
|
+
function run({ repository: repositories, policyPr, sourceRef }) {
|
|
55
3
|
try {
|
|
56
|
-
|
|
4
|
+
if (repositories.length !== 1 && (policyPr !== undefined || sourceRef !== undefined)) {
|
|
5
|
+
throw new Error('--policy-pr and --source-ref require exactly one --repository. Generate separate wrappers for different policy sources.');
|
|
6
|
+
}
|
|
7
|
+
const sources = repositories.map(repository => {
|
|
8
|
+
const identity = createProjectCore.repositoryIdentity(repository);
|
|
9
|
+
const plan = releases.planGithub({ repository: `${identity.owner}/${identity.repositoryName}`, policyPr, sourceRef });
|
|
10
|
+
if (plan.blockers.length)
|
|
11
|
+
throw new Error(`${repository}: ${plan.blockers.join('; ')}`);
|
|
12
|
+
return { ...identity, sourceRef: plan.source.sha, policyPr: plan.source.policyPr };
|
|
13
|
+
});
|
|
14
|
+
const slugs = sources.map(source => `${source.owner}/${source.repositoryName}`.toLowerCase());
|
|
15
|
+
if (new Set(slugs).size !== slugs.length)
|
|
16
|
+
throw new Error('Each repository may be specified only once.');
|
|
17
|
+
runtime.stdout.write(createProjectCore.githubSetup(sources));
|
|
57
18
|
}
|
|
58
19
|
catch (error) {
|
|
59
20
|
runtime.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
@@ -1,5 +1,32 @@
|
|
|
1
1
|
#!/usr/bin/env bash
|
|
2
2
|
set -euo pipefail
|
|
3
3
|
|
|
4
|
-
#
|
|
5
|
-
|
|
4
|
+
# Run this script with a plan directory to review and save the GitHub changes.
|
|
5
|
+
# Run it again with --execute and the same directory to apply those saved plans.
|
|
6
|
+
# Review deletions carefully: protection on other branches will be removed.
|
|
7
|
+
mode=plan
|
|
8
|
+
if [[ "${1:-}" == --execute ]]; then
|
|
9
|
+
mode=execute
|
|
10
|
+
shift
|
|
11
|
+
fi
|
|
12
|
+
if [[ $# != 1 || -z "$1" ]]; then
|
|
13
|
+
printf 'Usage: %s [--execute] PLAN_DIRECTORY\n' "$0" >&2
|
|
14
|
+
exit 2
|
|
15
|
+
fi
|
|
16
|
+
plan_directory=$1
|
|
17
|
+
if [[ "$mode" == plan ]]; then
|
|
18
|
+
mkdir -p -- "$plan_directory"
|
|
19
|
+
fi
|
|
20
|
+
|
|
21
|
+
configure_repository() {
|
|
22
|
+
local repository=$1 plan_name=$2 policy_pr=$3 source_ref=$4
|
|
23
|
+
local args=(github configure --plan-file "$plan_directory/$plan_name")
|
|
24
|
+
if [[ "$mode" == execute ]]; then
|
|
25
|
+
args+=(--execute --repository "$repository")
|
|
26
|
+
else
|
|
27
|
+
args+=(--repository "$repository")
|
|
28
|
+
if [[ -n "$policy_pr" ]]; then args+=(--policy-pr "$policy_pr"); fi
|
|
29
|
+
if [[ -n "$source_ref" ]]; then args+=(--source-ref "$source_ref"); fi
|
|
30
|
+
fi
|
|
31
|
+
npm exec --yes --package '@jakobm/peacekeeper@{{VERSION}}' -- peacekeeper "${args[@]}"
|
|
32
|
+
}
|
|
@@ -1,40 +1 @@
|
|
|
1
|
-
|
|
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
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
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', '
|
|
5
|
-
['Stop', '
|
|
6
|
-
['SessionEnd', '
|
|
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
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
.
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
.
|
|
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,
|
|
159
|
+
requiredCheckContexts, sameMembers, canonical, normalizeRuleset, exactPolicy, same };
|
|
126
160
|
return api;
|
|
127
161
|
};
|