Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .githooks/commit-msg
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@
set -euo pipefail

root="$(git rev-parse --show-toplevel)"
if [[ -n "${NEW_PROJECT_SEED_REQUEST:-}" ]]; then
[[ $# == 1 ]] || exit 1
python3 -B "$root/.governance/seed_baseline.py" hook-check --root "$root" \
--request "$NEW_PROJECT_SEED_REQUEST" --message-file "$1"
exit $?
fi
policy_runner="$root/.governance/repository_policy.py"
[[ -f "$policy_runner" ]] || policy_runner="$root/scripts/repository_policy.py"
if [[ -f "$policy_runner" ]]; then
Expand Down
79 changes: 70 additions & 9 deletions .githooks/pre-commit
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,26 @@ set -euo pipefail
root="$(git rev-parse --show-toplevel)"
branch="$(git symbolic-ref --short HEAD 2>/dev/null || true)"

# A seed request can authorize only the allocator's exact prepared root commit.
# Existing history, product files and an unprepared request fail closed here.
if [[ -n "${NEW_PROJECT_SEED_REQUEST:-}" ]]; then
python3 -B "$root/.governance/seed_baseline.py" hook-check --root "$root" \
--request "$NEW_PROJECT_SEED_REQUEST"
exit $?
fi

# Run before every profile/status success path. Identity is supplied by the
# session launcher; the hook must never infer it from the lease holder.
if [[ "$branch" =~ (^|/)ticket[-/][0-9]{3,} ]]; then
writer_runner="$root/.governance/change_lease_check.py"
[[ -f "$writer_runner" ]] || writer_runner="$root/scripts/change_lease_check.py"
if [[ ! -f "$writer_runner" ]]; then
echo "GOV-CHANGE-LEASE-001: writer-lease checker is missing; restore the managed installation." >&2
exit 1
fi
python3 -B "$writer_runner" writer-check --root "$root" --operation commit --ref "refs/heads/$branch"
fi

run_worktree_guard() {
local runner="$root/.governance/worktree_guard.py"
if [[ -f "$runner" ]]; then
Expand Down Expand Up @@ -70,13 +90,13 @@ if [[ -z "$branch" || "$branch" == "HEAD" ]]; then
exit 1
fi

if [[ ! "$branch" =~ ticket[-/]([0-9]{3,}) ]]; then
if [[ ! "$branch" =~ (^|/)ticket[-/]([0-9]{3,}) ]]; then
echo "GOV-AGENT-HOST-001: branch '$branch' is not bound to ticket-NNN." >&2
echo " Allocate with ./project/new-ticket.sh and commit on a ticket branch." >&2
exit 1
fi

ticket="ticket-${BASH_REMATCH[1]}"
ticket="ticket-${BASH_REMATCH[2]}"
readme_rel="project/$ticket/README.md"

ticket_storage="$(git config --local --get new-project.ticketStorage 2>/dev/null || true)"
Expand All @@ -98,6 +118,36 @@ else
exit 1
fi

# A carrier-only follow-up commit (for example the delivery contract that the
# gate asks for after the material change) is admitted only when the ticket
# branch already delivers a material change relative to its target branch.
# A branch without one still needs a material first commit; CI re-checks the
# whole range (GOV-MATERIAL-001).
branch_has_material_delivery() {
local target base path
target="$(PYTHONDONTWRITEBYTECODE=1 python3 - "$root/project/$ticket/intent.json" 2>/dev/null <<'PYTARGET'
import json
import sys
try:
delivery = json.load(open(sys.argv[1], encoding="utf-8")).get("delivery")
value = delivery.get("targetBranch") if isinstance(delivery, dict) else None
except (OSError, ValueError, AttributeError):
value = None
ok = isinstance(value, str) and value and not any(c.isspace() for c in value) and ".." not in value
print(value if ok else "main")
PYTARGET
)" || return 1
base="$(git merge-base HEAD "refs/remotes/origin/$target" 2>/dev/null)" || return 1
[[ -n "$base" ]] || return 1
while IFS= read -r -d '' path; do
case "$path" in
project/ticket-*/*|TODO.md|project/TICKETS.md|config/artifact-registry.json) ;;
*) return 0 ;;
esac
done < <(git diff --no-renames --name-only -z "$base" HEAD --)
return 1
}

governance_only_transition() {
# SQLite transitions never require a Git carrier commit.
[[ "${ticket_storage:-files}" == files ]] || return 1
Expand All @@ -124,14 +174,25 @@ if grep -Eiq '^-[[:space:]]+\*\*Status\*\*:[[:space:]]*IN_PROGRESS([[:space:]]|$
exit 0
fi

# NUL-framed rename records carry both paths. Moving a material file into
# tracking storage still changes the material source at its previous path.
material=false
while IFS= read -r -d '' path; do
case "$path" in
project/ticket-*/*|TODO.md|project/TICKETS.md|config/artifact-registry.json) ;;
*) material=true; break ;;
esac
done < <(git diff --cached --name-only -z --diff-filter=AM --)
if [[ "$material" != true ]]; then
while IFS= read -r -d '' change; do
IFS= read -r -d '' path || break
change_paths=("$path")
if [[ "$change" == R* ]]; then
IFS= read -r -d '' path || break
change_paths+=("$path")
fi
for path in "${change_paths[@]}"; do
case "$path" in
project/ticket-*/*|TODO.md|project/TICKETS.md|config/artifact-registry.json) ;;
*) material=true; break ;;
esac
done
if [[ "$material" == true ]]; then break; fi
done < <(git diff --cached --name-status -z --diff-filter=AMR --)
if [[ "$material" != true ]] && ! branch_has_material_delivery; then
echo "GOV-AGENT-HOST-007: staged change contains only ticket tracking carriers." >&2
echo " Add a material deliverable, or emit an external no-change receipt without committing." >&2
exit 1
Expand Down
76 changes: 76 additions & 0 deletions .githooks/pre-push
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
#!/usr/bin/env bash
# Git invokes this before a push. Delivery reaches the declared target branch only
# through a reviewed pull request merged by the validator; a direct push skips
# review, required checks and CI (GOV-PUSH-001). Repositories whose delivery
# profile is main-only or local-audit commit on the target branch by design.
set -euo pipefail

root="$(git rev-parse --show-toplevel)"
allow_target=false
policy_runner="$root/.governance/repository_policy.py"
[[ -f "$policy_runner" ]] || policy_runner="$root/scripts/repository_policy.py"
if [[ -f "$policy_runner" ]]; then
profile="$(PYTHONDONTWRITEBYTECODE=1 python3 "$policy_runner" --root "$root" --profile 2>/dev/null || true)"
case "$profile" in
local-audit|main-only-planfile|main-only-files) allow_target=true ;;
esac
fi

if ! targets="$(PYTHONDONTWRITEBYTECODE=1 python3 - "$root" <<'PY'
import json, sys
from pathlib import Path
root = Path(sys.argv[1])
try:
for rel in (".governance/manifest.json", ".governance/manifest.base.json", "governance/manifest.hub.json"):
path = root / rel
if not path.exists():
continue
manifest = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(manifest, dict):
raise ValueError("manifest must be an object")
delivery = manifest.get("delivery", {})
if not isinstance(delivery, dict):
raise ValueError("delivery must be an object")
if "targetBranches" not in delivery:
continue
branches = delivery["targetBranches"]
if not isinstance(branches, list) or not branches or not all(isinstance(b, str) and b and not any(c.isspace() for c in b) for b in branches):
raise ValueError("target branches must be a nonempty list of branch names")
print("\n".join(branches))
break
else:
print("main")
except (OSError, UnicodeError, ValueError):
print("GOV-PUSH-001: invalid or unreadable target-branch policy; restore the declared manifest before pushing.", file=sys.stderr)
sys.exit(1)
PY
)"; then
exit 1
fi

refused=0
while read -r local_ref local_sha remote_ref remote_sha; do
[[ -n "${remote_ref:-}" ]] || continue
for ref in "$local_ref" "$remote_ref"; do
if [[ "$ref" =~ ^refs/heads/(.*/)?ticket[-/][0-9]{3,} ]]; then
writer_runner="$root/.governance/change_lease_check.py"
[[ -f "$writer_runner" ]] || writer_runner="$root/scripts/change_lease_check.py"
if [[ ! -f "$writer_runner" ]]; then
echo "GOV-CHANGE-LEASE-001: writer-lease checker is missing; restore the managed installation." >&2
refused=1
elif ! python3 -B "$writer_runner" writer-check --root "$root" --operation push --ref "$ref"; then
refused=1
fi
fi
done
[[ "$allow_target" == true ]] && continue
while IFS= read -r target; do
if [[ "$remote_ref" == "refs/heads/$target" ]]; then
echo "GOV-PUSH-001: direct push to '$target' refused ($local_ref -> $remote_ref)." >&2
echo " Push the ticket branch and open a pull request; the validator merges it." >&2
refused=1
fi
done <<< "$targets"
done

exit "$refused"
67 changes: 11 additions & 56 deletions .github/workflows/new-project-branch-hygiene.yml
Original file line number Diff line number Diff line change
@@ -1,16 +1,8 @@
name: new-project-branch-hygiene

# `delete_branch_on_merge` covers the merge exit. This workflow covers the
# other one: a branch whose pull request was closed without merging. Nothing
# in the toolchain removes those, and `GOV-BRANCH-LIFECYCLE-002` validates the
# repository as a whole rather than the diff under review, so a single left
# behind branch fails `governance / remote lifecycle` on *every* later pull
# request, indefinitely and through no fault of its own.
#
# Closing a pull request without merging is the explicit owner decision to
# discard the branch that the check's own remediation asks for, and GitHub
# keeps the branch restorable from the pull request page afterwards.

# GitHub's delete_branch_on_merge setting handles successfully merged branches.
# Closing an unmerged pull request does not authorize discarding its work.
# Explicit discard requires a separate owner decision and intent reconciliation.
on:
pull_request:
types: [closed]
Expand All @@ -19,54 +11,17 @@ permissions:
contents: read

jobs:
discard-unmerged-head:
# Forks cannot be written to, and the default branch is never a head to
# discard. Both guards are cheap and keep the job from ever running where
# deleting would be wrong.
if: >-
github.event.pull_request.merged == false &&
github.event.pull_request.head.repo.full_name == github.repository &&
github.event.pull_request.head.ref != github.event.repository.default_branch
preserve-unmerged-head:
if: github.event.pull_request.merged == false
runs-on: ${{ vars.NEW_PROJECT_RUNNER_LABEL || 'ubuntu-latest' }}
permissions:
contents: write
steps:
- name: Delete the closed pull request's head branch
- name: Report preserved pull request branch
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
with:
script: |
const ref = context.payload.pull_request.head.ref;

// Several pull requests may share one head branch. Deleting it
// while another is still open would break that one instead.
const owners = await github.paginate(github.rest.pulls.list, {
owner: context.repo.owner,
repo: context.repo.repo,
state: 'open',
head: `${context.repo.owner}:${ref}`,
per_page: 100,
});
if (owners.length > 0) {
const numbers = owners.map(pull => `#${pull.number}`).join(', ');
core.info(`Kept ${ref}: still owned by ${numbers}.`);
return;
}

try {
await github.rest.git.deleteRef({
owner: context.repo.owner,
repo: context.repo.repo,
ref: `heads/${ref}`,
});
core.info(
`Deleted ${ref}. GitHub keeps it restorable from the pull request page.`,
);
} catch (error) {
// The branch is commonly gone already, because the person
// closing the pull request ticked "delete branch".
if (error.status === 404 || error.status === 422) {
core.info(`${ref} was already deleted.`);
return;
}
throw error;
}
core.notice(
`Preserved ${JSON.stringify(ref)}. Closing a pull request does not ` +
'authorize branch deletion. Reconcile remaining intent and obtain ' +
'an explicit owner discard decision before a separate deletion.',
);
Loading
Loading