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
17 changes: 10 additions & 7 deletions kits/profile-dev-kit/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -502,24 +502,27 @@ optional `status_path`. It reads the recorded Approval and the latest
consistent Report, validates the feature branch and parent gitlink, then runs
fetch, land, push, pull request, checks, merge and refetch. The pull request
contains references only: the story key, spec path, Change id and approved
revision.
revision. Merge runs only after `github_pr_checks_wait` passes for the tip;
pending checks never pass, and a no-checks result is recorded as `no_checks`.

The stage refuses before host work for an absent or invalid Approval, a pending
Report, unapproved commits, invalid inputs, a bad parent or a malformed status
file. It confirms the merge from Git after a successful fetch and pins the host
merge to the checked branch tip. A rerun reuses a merged tip and an existing
parent pointer instead of repeating those actions.
file. It refuses with `base.stale` when the fetched base is not an ancestor of
the tip. It confirms the merge from Git after a successful fetch and pins the
host merge to the checked branch tip. A rerun reuses a merged tip and an
existing parent pointer instead of repeating those actions.

It records one `integrate` outcome at the Change-repository boundary and one at
the parent boundary. Common reasons include `approval.absent`,
`verdict.has_pendency`, `revision.unapproved`, `merge.confirmed`,
`verdict.has_pendency`, `revision.unapproved`, `base.stale`, `merge.confirmed`,
`merge.reused`, `pointer.unpublished`, `integrate.complete` and
`fetch.failed`. The status mapping is edited only after a successful parent
fetch confirms the pointer on the parent remote. The workflow never approves,
verifies or pushes the parent; the owner commits the status file and pushes
the parent.
the parent. Agent pushes to `main` are denied by the runtime and by the Story 8.6
spec, not by `AGENTS.md`, which permits a direct monorepo push to `main` under
Planned Story Delivery Authorization.

```text
```text
beddel run -i ... workflows/integrate-story.yaml
```
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from beddel_profile_dev.tools.report import profile_read_report


_REF_NAMES = ("boundary", "spec_path", "branch", "base_branch", "change_id", "revision", "tip", "approval", "report", "pr", "merge", "sub_path", "pointer", "status_path", "status_written")
_REF_NAMES = ("boundary", "spec_path", "branch", "base_branch", "change_id", "revision", "tip", "approval", "report", "pr", "merge", "sub_path", "pointer", "status_path", "status_written", "no_checks")


def _refs(**values: Any) -> dict[str, Any]:
Expand Down Expand Up @@ -230,6 +230,7 @@ def profile_integrate_reconcile(repo_path: str, story_key: str, change_id: str,
tracking = _tracking(repo, str(remote), str(base))
if phase == "land":
if is_ancestor(repo, tip, tracking): return _with(prior, merged=True, pr=False, phase="land", tip=tip)
if not is_ancestor(repo, tracking, tip): return _refuse(story, "base.stale", _carry_refs(prior, tip=tip), **_carry(prior), phase="land", tip=tip, pr=False, merged=False)
if _symbolic_branch(repo) != branch: return _fail(story, "branch.not_current", _carry_refs(prior, tip=tip), **_carry(prior), phase="land", tip=tip, pr=False, merged=False)
return _with(prior, phase="land", pr=True, merged=False, tip=tip)
contained = is_ancestor(repo, tip, tracking)
Expand All @@ -241,7 +242,9 @@ def profile_integrate_reconcile(repo_path: str, story_key: str, change_id: str,
reported = result.get("merge_sha") if isinstance(result, Mapping) else None
if reported != merge_sha: return _fail(story, "merge.mismatch", _carry_refs(prior, tip=tip, merge=merge_sha), **_carry(prior), phase="confirm", tip=tip, merge=merge_sha)
number = pull_request.get("result", {}).get("number") if isinstance(pull_request, Mapping) and isinstance(pull_request.get("result"), Mapping) else None
refs = _carry_refs(prior, boundary="repository", tip=tip, merge=merge_sha, pr=number)
check_result = checks.get("result") if isinstance(checks, Mapping) else None
no_checks = check_result.get("no_checks") if isinstance(check_result, Mapping) and isinstance(check_result.get("no_checks"), bool) else None
refs = _carry_refs(prior, boundary="repository", tip=tip, merge=merge_sha, pr=number, no_checks=no_checks)
return _with(prior, outcome="succeeded", reason="merge.confirmed" if prior.get("pr") else "merge.reused", refs=refs, phase="confirm", tip=tip, merge=merge_sha, merged=True)
if prior.get("pr") is True:
for item, reason in ((push, "push.failed"), (pull_request, "pr.failed"), (checks, "checks.failed"), (merge, "merge.failed")):
Expand Down
54 changes: 54 additions & 0 deletions kits/profile-dev-kit/tests/test_integrate.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,57 @@ def test_settle_rejects_missing_prior(tmp_path: Path) -> None:
@pytest.mark.parametrize("value", ["Done", "done now", "", "x" * 33])
def test_status_value_contract(value: str) -> None:
assert integrate.STATUS_VALUE.fullmatch(value) is None


def _land_prior(repo: Path, tip: str) -> dict[str, Any]:
return {
"stage": "integrate",
"phase": "prepare",
"story_key": STORY,
"change_id": "c1",
"repo": str(repo),
"branch": "feature/work",
"base_branch": "main",
"remote": "origin",
"tip": tip,
"refs": {},
"outcome": None,
}


def test_reconcile_rejects_stale_base_and_reuses_contained_tip(
tmp_path: Path,
) -> None:
repo = init_repo(tmp_path / "repo")
git(repo, "config", "user.name", "Fixture")
git(repo, "config", "user.email", "fixture@example.invalid")
(repo / "base").write_text("base\n")
base = commit_all(repo, "base")
git(repo, "switch", "-c", "feature/work")
(repo / "feature").write_text("feature\n")
tip = commit_all(repo, "feature")
git(repo, "switch", "-c", "main", base)
(repo / "remote").write_text("remote\n")
remote_tip = commit_all(repo, "remote")
git(repo, "switch", "feature/work")
git(repo, "update-ref", "refs/remotes/origin/main", remote_tip)
prior = _land_prior(repo, tip)
stale = tools.profile_integrate_reconcile(
str(repo), STORY, "c1", "land", prior, {"ok": True}
)
assert stale["outcome"] == "refused"
assert stale["reason"] == "base.stale"
assert stale["remote"] is None
assert stale["pr"] is False

git(repo, "update-ref", "refs/remotes/origin/main", tip)
reused = tools.profile_integrate_reconcile(
str(repo), STORY, "c1", "land", prior, {"ok": True}
)
assert reused["outcome"] is None
assert reused["merged"] is True
assert reused["pr"] is False


def test_integrate_refs_have_sixteen_keys() -> None:
assert len(tools._REF_NAMES) == 16
102 changes: 97 additions & 5 deletions kits/profile-dev-kit/tests/test_integrate_workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,18 @@ def test_integrate_workflow_shape() -> None:
"change_id",
"revision",
}
assert (
next(step for step in document["steps"] if step["id"] == "checks")["config"][
"arguments"
]["expected_head_sha"]
== "$stepResult.land.result.tip"
)
assert (
next(step for step in document["steps"] if step["id"] == "merge")["config"][
"arguments"
]["number"]
== "$stepResult.checks.result.number"
)
assert (
next(step for step in document["steps"] if step["id"] == "merge")["config"][
"arguments"
Expand Down Expand Up @@ -102,10 +114,12 @@ def test_integrate_workflow_parses_and_conditions_pair() -> None:
import sys
from typing import Any

import pytest
from beddel.domain.executor import WorkflowExecutor
from beddel.domain.kit import parse_kit_manifest
from beddel.domain.models import DefaultDependencies
from beddel.domain.registry import PrimitiveRegistry
from beddel.error_codes import PRIM_TOOL_EXEC_FAILED
from beddel.primitives import register_builtins
from beddel.tools.kits import load_kit

Expand All @@ -115,6 +129,7 @@ def test_integrate_workflow_parses_and_conditions_pair() -> None:
KITS_ROOT = KIT_ROOT.parent
sys.path.insert(0, str(KITS_ROOT / "tools-git-kit" / "python"))
sys.path.insert(0, str(KITS_ROOT / "tools-github-kit" / "python"))

STORY = "7-6-integrate-workflow-completes-only-after-approval"
BRANCH = "feat/work"

Expand Down Expand Up @@ -159,6 +174,8 @@ def __init__(self, env: dict[str, Any]) -> None:
self.env = env
self.calls: list[str] = []
self.fail_checks = False
self.check_error_code: str | None = None
self.no_checks = False

async def create(self, **kwargs: Any) -> dict[str, Any]:
self.calls.append("pr")
Expand All @@ -167,10 +184,22 @@ async def create(self, **kwargs: Any) -> dict[str, Any]:
async def checks(self, **kwargs: Any) -> dict[str, Any]:
self.calls.append("checks")
if self.fail_checks:
if self.check_error_code is not None:
from beddel_tools_github import GitHubToolError

raise GitHubToolError(self.check_error_code, "fake checks failure")
raise RuntimeError("checks failed")
return {"status": "passed"}
return {
"number": kwargs["number"],
"head_sha": kwargs["expected_head_sha"],
"passed": True,
"no_checks": self.no_checks,
"checks": [] if self.no_checks else ["ci"],
}

async def merge(self, **kwargs: Any) -> dict[str, Any]:
if not isinstance(kwargs["number"], int):
raise TypeError("merge number must be an integer")
self.calls.append("merge")
if self.fail_checks:
raise RuntimeError("merge blocked after checks failure")
Expand All @@ -189,6 +218,7 @@ def _run(
report: dict[str, Any] | None,
monkeypatch: Any,
overrides: dict[str, Any] | None = None,
real_merge: bool = False,
) -> dict[str, Any]:
from beddel_profile_dev.tools import integrate as module

Expand All @@ -201,11 +231,12 @@ def _run(
registry: dict[str, Any] = {}
for name in ("profile-dev-kit", "tools-git-kit", "tools-github-kit"):
registry.update(load_kit(parse_kit_manifest(KITS_ROOT / name / "kit.yaml")))
real_github_merge = registry["github_pr_merge"]
registry.update(
{
"github_pr_create_or_reuse": host.create,
"github_pr_checks_wait": host.checks,
"github_pr_merge": host.merge,
"github_pr_merge": real_github_merge if real_merge else host.merge,
}
)
registry.update(overrides or {})
Expand Down Expand Up @@ -261,6 +292,8 @@ def test_workflow_happy_path_owner_push_and_complete_rerun(
"merge.confirmed",
"pointer.unpublished",
]
assert records[0]["refs"]["no_checks"] is False
assert records[1]["refs"]["no_checks"] is False
assert first["step_results"]["pointer"]["result"]["pointer"]
git(env["parent"], "push", "-q", "origin", "main")
second = _run(env, host, approval, report, monkeypatch)
Expand All @@ -276,6 +309,42 @@ def test_workflow_happy_path_owner_push_and_complete_rerun(
assert host.calls.count("merge") == 1


def test_workflow_records_no_checks(tmp_path: Path, monkeypatch: Any) -> None:
env = _fixture(tmp_path)
monkeypatch.setenv("HOME", str(tmp_path / "home"))
(tmp_path / "home").mkdir(exist_ok=True)
host = _Host(env)
host.no_checks = True
approval, report = _approval(env)
_run(env, host, approval, report, monkeypatch)
records = _records(tmp_path / "home")
assert [record["refs"]["no_checks"] for record in records] == [True, True]


def test_workflow_stale_base_refuses_without_host_work(
tmp_path: Path, monkeypatch: Any
) -> None:
env = _fixture(tmp_path)
monkeypatch.setenv("HOME", str(tmp_path / "home"))
(tmp_path / "home").mkdir(exist_ok=True)
clone = env["root"] / "stale-base"
git(env["root"], "clone", "-q", str(env["sub_bare"]), str(clone))
(clone / "base-advance").write_text("advanced\n")
commit_all(clone, "advance base")
git(clone, "push", "-q", "origin", "main")
host = _Host(env)
approval, report = _approval(env)
_run(env, host, approval, report, monkeypatch)
records = _records(tmp_path / "home")
assert [(record["outcome"], record["reason"]) for record in records] == [
("refused", "base.stale")
]
assert host.calls == []
assert (
git(env["sub_bare"], "for-each-ref", "--format=%(refname)") == "refs/heads/main"
)


def test_workflow_absent_approval_has_no_host_calls_or_push(
tmp_path: Path, monkeypatch: Any
) -> None:
Expand All @@ -294,21 +363,43 @@ def test_workflow_absent_approval_has_no_host_calls_or_push(
)


@pytest.mark.parametrize(
"error_code",
["GITHUB_CHECKS_PENDING", "GITHUB_CHECKS_FAILED", "GITHUB_PR_MISMATCH"],
)
def test_workflow_checks_failure_has_no_parent_record(
tmp_path: Path, monkeypatch: Any
tmp_path: Path, monkeypatch: Any, error_code: str
) -> None:
from beddel_tools_github import GitHubCLI

env = _fixture(tmp_path)
monkeypatch.setenv("HOME", str(tmp_path / "home"))
(tmp_path / "home").mkdir(exist_ok=True)
host = _Host(env)
host.fail_checks = True
host.check_error_code = error_code
approval, report = _approval(env)
_run(env, host, approval, report, monkeypatch)
gh_calls: list[tuple[Any, ...]] = []

async def no_gh(self: Any, *args: Any, **kwargs: Any) -> Any:
gh_calls.append(args)
raise AssertionError("gh must not be invoked")

monkeypatch.setattr(GitHubCLI, "run", no_gh)
result = _run(env, host, approval, report, monkeypatch, real_merge=True)
records = _records(tmp_path / "home")
assert [(record["outcome"], record["reason"]) for record in records] == [
("failed", "checks.failed")
]
assert host.calls == ["pr", "checks", "merge"]
assert host.calls == ["pr", "checks"]
# The tool primitive normalizes kit-local GITHUB_* errors to its stable code.
assert {
(error["step_id"], error["error_code"]) for error in result["absorbed_errors"]
} == {
("checks", PRIM_TOOL_EXEC_FAILED),
("merge", PRIM_TOOL_EXEC_FAILED),
}
assert gh_calls == []


def test_workflow_failed_refetch_reuses_merge(tmp_path: Path, monkeypatch: Any) -> None:
Expand All @@ -331,4 +422,5 @@ async def flaky_fetch(**kwargs: Any) -> Any:
assert _records(tmp_path / "home")[-1]["reason"] == "fetch.failed"
_run(env, host, approval, report, monkeypatch)
assert _records(tmp_path / "home")[-2]["reason"] == "merge.reused"
assert _records(tmp_path / "home")[-2]["refs"]["no_checks"] is None
assert host.calls.count("merge") == 1
3 changes: 2 additions & 1 deletion kits/profile-dev-kit/workflows/integrate-story.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ steps:
arguments:
cwd: "$input.repo_path"
number: "$stepResult.pull_request.result.number"
expected_head_sha: "$stepResult.land.result.tip"
- id: merge
primitive: tool
if: "$stepResult.land.result.pr == true"
Expand All @@ -117,7 +118,7 @@ steps:
timeout: 400
arguments:
cwd: "$input.repo_path"
number: "$stepResult.pull_request.result.number"
number: "$stepResult.checks.result.number"
merge_method: merge
expected_head_sha: "$stepResult.land.result.tip"
- id: refetch
Expand Down
10 changes: 6 additions & 4 deletions kits/tools-github-kit/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,12 @@ Revision: <revision>
```

`github_pr_checks_wait` invokes `gh pr view <number> --json
number,state,headRefOid,statusCheckRollup`. A configured check is every entry
in that rollup. Completed `SUCCESS`, `NEUTRAL`, and `SKIPPED` CheckRuns and
`SUCCESS` StatusContexts pass. Pending entries wait; all other conclusions or
states fail. An empty rollup passes only after `grace` seconds.
number,state,headRefOid,statusCheckRollup`. With `expected_head_sha`, any other
head raises `GITHUB_PR_MISMATCH`, so checks are pinned to the head being merged.
A configured check is every entry in that rollup. Completed `SUCCESS`,
`NEUTRAL`, and `SKIPPED` CheckRuns and `SUCCESS` StatusContexts pass. Pending
entries never pass and wait; all other conclusions or states fail. An empty
rollup passes only after `grace` seconds.

`github_pr_merge` first views the requested number, refuses failed or pending
checks, runs `gh pr merge <number> --<merge|squash|rebase> --match-head-commit
Expand Down
11 changes: 11 additions & 0 deletions kits/tools-github-kit/python/beddel_tools_github/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,7 @@ async def github_pr_checks_wait(
*,
cwd: str,
number: int,
expected_head_sha: str | None = None,
interval: float = 10,
max_wait: float = 1800,
grace: float = 30,
Expand All @@ -494,6 +495,11 @@ async def github_pr_checks_wait(
"""Poll the pull request rollup until it passes, fails, or times out."""
cwd_value = _validate_cwd(cwd)
number_value = _validate_number(number)
expected_value = (
None
if expected_head_sha is None
else _validate_sha(expected_head_sha, "expected_head_sha")
)
interval_value, max_wait_value, grace_value = _validate_wait_values(
interval, max_wait, grace
)
Expand All @@ -504,6 +510,11 @@ async def github_pr_checks_wait(
first_poll = True
while True:
view, rollup, command = await _read_checks(cli, cwd_value, number_value)
if expected_value is not None and view["headRefOid"] != expected_value:
raise GitHubToolError(
GITHUB_PR_MISMATCH,
"The pull request does not match the requested number or head.",
)
status, names, failed = _rollup_status(rollup, command)
now = time.monotonic()
if status == "empty":
Expand Down
Loading
Loading