From 8fd2f6b7b00586ccb8888e4a68f2f2edef779480 Mon Sep 17 00:00:00 2001 From: Trecek Date: Sat, 24 Oct 2026 07:57:37 -0700 Subject: [PATCH 01/19] fix(recipe): drive PR merges from a shared ordered cursor --- scripts/recipe/advance_queue_pr.sh | 15 -- src/autoskillit/recipe/_cmd_rpc.py | 6 +- src/autoskillit/recipe/_cmd_rpc_merge.py | 6 +- src/autoskillit/recipe/cmd_rpc/__init__.py | 9 +- src/autoskillit/recipe/cmd_rpc/_cmd_rpc.py | 3 +- .../recipe/cmd_rpc/_cmd_rpc_merge.py | 64 +++++-- src/autoskillit/recipe/skill_contracts.yaml | 26 ++- src/autoskillit/recipes/diagrams/merge-prs.md | 56 +++--- src/autoskillit/recipes/merge-prs.json | 88 ++++++--- src/autoskillit/recipes/merge-prs.yaml | 107 ++++++----- .../recipes/scripts/advance_queue_pr.sh | 15 -- .../skills_extended/analyze-prs/SKILL.md | 26 ++- .../skills_extended/merge-pr/SKILL.md | 20 +- .../test_completion_receipt_fitness.py | 58 ++++++ tests/infra/test_recipe_read_guard.py | 3 +- .../test_recipe_read_guard_callable_parity.py | 3 +- tests/recipe/test_cmd_rpc_merge.py | 174 ++++++++++++++++++ tests/recipe/test_contracts.py | 10 +- tests/recipe/test_merge_prs_pr_cursor.py | 115 ++++++++++++ tests/recipe/test_merge_prs_queue_common.py | 15 +- tests/recipe/test_merge_prs_queue_pmp.py | 34 +++- tests/recipe/test_rules_dataflow_nullable.py | 4 +- 22 files changed, 658 insertions(+), 199 deletions(-) delete mode 100755 scripts/recipe/advance_queue_pr.sh delete mode 100755 src/autoskillit/recipes/scripts/advance_queue_pr.sh create mode 100644 tests/recipe/test_merge_prs_pr_cursor.py diff --git a/scripts/recipe/advance_queue_pr.sh b/scripts/recipe/advance_queue_pr.sh deleted file mode 100755 index 18fc768c28..0000000000 --- a/scripts/recipe/advance_queue_pr.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -# Args: $1=current_pr_number $2=pr_order_file -CURRENT="$1" -PR_ORDER_FILE="$2" - -NEXT=$(jq -r --arg cur "$CURRENT" ' - (to_entries | map(select(.value.number == ($cur | tonumber))) | .[0].key) as $idx | - if ($idx + 1) < length then .[$idx + 1].number | tostring - else "done" - end -' "$PR_ORDER_FILE") - -echo "$NEXT" diff --git a/src/autoskillit/recipe/_cmd_rpc.py b/src/autoskillit/recipe/_cmd_rpc.py index 7d31eaacd7..d9492bdad9 100644 --- a/src/autoskillit/recipe/_cmd_rpc.py +++ b/src/autoskillit/recipe/_cmd_rpc.py @@ -7,7 +7,6 @@ from __future__ import annotations from autoskillit.recipe.cmd_rpc._cmd_rpc import ( - advance_queue_pr, attempt_cheap_rebase, batch_create_issues, check_dropped_ci_loop, @@ -21,9 +20,11 @@ emit_fallback_map, ensure_results, export_local_bundle, + first_ordered_pr, force_push_and_wait_mergeability, immediate_merge_conflict_fix, main_repo_guard, + next_ordered_pr, proactive_rebase_next_pr, queue_ejected_fix, refetch_issues, @@ -36,7 +37,8 @@ ) __all__ = [ - "advance_queue_pr", + "first_ordered_pr", + "next_ordered_pr", "attempt_cheap_rebase", "batch_create_issues", "check_dropped_ci_loop", diff --git a/src/autoskillit/recipe/_cmd_rpc_merge.py b/src/autoskillit/recipe/_cmd_rpc_merge.py index 713dfbee09..3056bf31a9 100644 --- a/src/autoskillit/recipe/_cmd_rpc_merge.py +++ b/src/autoskillit/recipe/_cmd_rpc_merge.py @@ -13,16 +13,17 @@ _attempt_rebase_with_conflict_report, _detect_remote, _write_rebase_conflict_report, - advance_queue_pr, annotations, atomic_write, attempt_cheap_rebase, create_persistent_integration, direct_merge_conflict_fix, + first_ordered_pr, force_push_and_wait_mergeability, get_logger, immediate_merge_conflict_fix, logger, + next_ordered_pr, proactive_rebase_next_pr, queue_ejected_fix, review_path_rebase, @@ -39,7 +40,8 @@ "_attempt_rebase_with_conflict_report", "_detect_remote", "_write_rebase_conflict_report", - "advance_queue_pr", + "first_ordered_pr", + "next_ordered_pr", "annotations", "atomic_write", "attempt_cheap_rebase", diff --git a/src/autoskillit/recipe/cmd_rpc/__init__.py b/src/autoskillit/recipe/cmd_rpc/__init__.py index d59d99a9b6..05f02e2dfc 100644 --- a/src/autoskillit/recipe/cmd_rpc/__init__.py +++ b/src/autoskillit/recipe/cmd_rpc/__init__.py @@ -11,7 +11,6 @@ if TYPE_CHECKING: from ._cmd_rpc import ( - advance_queue_pr, attempt_cheap_rebase, batch_create_issues, check_dropped_ci_loop, @@ -25,9 +24,11 @@ emit_fallback_map, ensure_results, export_local_bundle, + first_ordered_pr, force_push_and_wait_mergeability, immediate_merge_conflict_fix, main_repo_guard, + next_ordered_pr, proactive_rebase_next_pr, queue_ejected_fix, refetch_issues, @@ -112,7 +113,8 @@ def __getattr__(name: str): ) _LAZY_SYMBOL_TO_MODULE: dict[str, str] = { - "advance_queue_pr": "_cmd_rpc_merge", + "first_ordered_pr": "_cmd_rpc_merge", + "next_ordered_pr": "_cmd_rpc_merge", "attempt_cheap_rebase": "_cmd_rpc_merge", "batch_create_issues": "_cmd_rpc_issues", "check_dropped_ci_loop": "_cmd_rpc_guards", @@ -202,7 +204,8 @@ def __getattr__(name: str): "_strip_ticket_body", "_validate_mutation_variables", "_write_rebase_conflict_report", - "advance_queue_pr", + "first_ordered_pr", + "next_ordered_pr", "atomic_write", "attempt_cheap_rebase", "batch_create_issues", diff --git a/src/autoskillit/recipe/cmd_rpc/_cmd_rpc.py b/src/autoskillit/recipe/cmd_rpc/_cmd_rpc.py index 902626ced8..c13c7e9c7a 100644 --- a/src/autoskillit/recipe/cmd_rpc/_cmd_rpc.py +++ b/src/autoskillit/recipe/cmd_rpc/_cmd_rpc.py @@ -21,12 +21,13 @@ refetch_issues, ) from autoskillit.recipe.cmd_rpc._cmd_rpc_merge import ( # noqa: F401 - advance_queue_pr, attempt_cheap_rebase, create_persistent_integration, direct_merge_conflict_fix, + first_ordered_pr, force_push_and_wait_mergeability, immediate_merge_conflict_fix, + next_ordered_pr, proactive_rebase_next_pr, queue_ejected_fix, review_path_rebase, diff --git a/src/autoskillit/recipe/cmd_rpc/_cmd_rpc_merge.py b/src/autoskillit/recipe/cmd_rpc/_cmd_rpc_merge.py index f1356b4b3e..9fcc1d67e7 100644 --- a/src/autoskillit/recipe/cmd_rpc/_cmd_rpc_merge.py +++ b/src/autoskillit/recipe/cmd_rpc/_cmd_rpc_merge.py @@ -310,29 +310,55 @@ def force_push_and_wait_mergeability( raise RuntimeError(msg) -def advance_queue_pr( - current_pr_number: str, - pr_order_file: str, -) -> dict[str, str]: - """Find next PR in queue order file.""" - if not current_pr_number: - return {"error": f"current_pr_number is required, got {current_pr_number!r}"} +_PR_COMPLEXITIES = frozenset({"simple", "needs_check"}) + + +def _load_pr_order(pr_order_file: str) -> list[tuple[str, str]]: + if not Path(pr_order_file).is_absolute(): + raise ValueError(f"pr_order_file must be absolute: {pr_order_file!r}") try: with open(pr_order_file) as f: order = json.load(f) except (OSError, json.JSONDecodeError) as exc: - raise RuntimeError(str(exc)) from exc - current = int(current_pr_number) - idx = None - for i, entry in enumerate(order): - if entry.get("number") == current: - idx = i - break - if idx is None: - return {"current_pr_number": "done"} - if (idx + 1) < len(order): - return {"current_pr_number": str(order[idx + 1]["number"])} - return {"current_pr_number": "done"} + raise RuntimeError(f"{pr_order_file}: {exc}") from exc + if not isinstance(order, dict) or not isinstance(order.get("prs"), list): + raise ValueError(f"{pr_order_file}: expected an object with a prs list") + entries: list[tuple[str, str]] = [] + seen: set[int] = set() + for index, entry in enumerate(order["prs"]): + location = f"{pr_order_file}: prs[{index}]" + if not isinstance(entry, dict): + raise ValueError(f"{location}: expected an object") + number, complexity = entry.get("number"), entry.get("complexity") + if isinstance(number, bool) or not isinstance(number, int) or number <= 0: + raise ValueError(f"{location}: number must be a positive integer") + if not isinstance(complexity, str) or complexity not in _PR_COMPLEXITIES: + raise ValueError(f"{location}: complexity must be simple or needs_check") + if number in seen: + raise ValueError(f"{location}: duplicate PR number {number}") + seen.add(number) + entries.append((str(number), complexity)) + return entries + + +def _cursor_result(entry: tuple[str, str], *, done: bool) -> dict[str, str]: + return {"pr_number": entry[0], "complexity": entry[1], "done": "true" if done else "false"} + + +def first_ordered_pr(pr_order_file: str) -> dict[str, str]: + """Select the first eligible PR from the analyze-prs order artifact.""" + entries = _load_pr_order(pr_order_file) + return _cursor_result(entries[0] if entries else ("", ""), done=not entries) + + +def next_ordered_pr(pr_order_file: str, current_pr_number: str) -> dict[str, str]: + """Advance by file order, retaining the last PR when the order is exhausted.""" + entries = _load_pr_order(pr_order_file) + for index, entry in enumerate(entries): + if entry[0] == current_pr_number: + done = index + 1 == len(entries) + return _cursor_result(entry if done else entries[index + 1], done=done) + raise ValueError(f"{pr_order_file}: current_pr_number {current_pr_number!r} is not in prs") def review_path_rebase( diff --git a/src/autoskillit/recipe/skill_contracts.yaml b/src/autoskillit/recipe/skill_contracts.yaml index 619c5865cd..95ac95263b 100644 --- a/src/autoskillit/recipe/skill_contracts.yaml +++ b/src/autoskillit/recipe/skill_contracts.yaml @@ -3683,20 +3683,36 @@ callable_contracts: outputs: - name: ok type: str - autoskillit.recipe._cmd_rpc.advance_queue_pr: + autoskillit.recipe._cmd_rpc.first_ordered_pr: inputs: - - name: current_pr_number + - name: pr_order_file type: str required: true - nullable: false + outputs: + - name: pr_number + type: str + - name: complexity + type: str + - name: done + type: str + allowed_values: ['true', 'false'] + autoskillit.recipe._cmd_rpc.next_ordered_pr: + inputs: - name: pr_order_file type: str required: true - outputs: - name: current_pr_number type: str - - name: error + required: true + nullable: false + outputs: + - name: pr_number + type: str + - name: complexity type: str + - name: done + type: str + allowed_values: ['true', 'false'] autoskillit.recipe._cmd_rpc.proactive_rebase_next_pr: inputs: - name: work_dir diff --git a/src/autoskillit/recipes/diagrams/merge-prs.md b/src/autoskillit/recipes/diagrams/merge-prs.md index 13944979f8..8d14b6d171 100644 --- a/src/autoskillit/recipes/diagrams/merge-prs.md +++ b/src/autoskillit/recipes/diagrams/merge-prs.md @@ -1,34 +1,28 @@ - + ## merge-prs -Merge multiple PRs into an integration branch with conflict resolution and CI gates. -### Graph -clone → setup_remote → check_repo_ci_event -| -check_integration_exists → confirm_create_integration (optional) -| -fetch_merge_queue_data → analyze_prs → route_by_queue_mode -| -+-- [queue mode]: -| enqueue → wait → advance → next PR -| → resolve ejected conflicts on failure -| -+-- [integration mode]: -| create_batch_branch → publish → check_pr_merge_loop -| | -| ┌────┤ FOR EACH PR: -| │ merge_pr → plan → verify → implement → test -| │ → merge → push → next_or_done -| └────┘ -| | -| audit_impl → remediate (optional) -| | -| open_integration_pr → ci_watch → review -| -+-- diagnose_ci → resolve_ci (on CI failure) -| -patch_token_summary (optional) -───────────────────────────────────── -done "Complete." -escalate_stop "Failed." +``` + analyze-prs + | + +-- queue mode: + | +-- ejected conflicts: make-plan -> resolve-merge-conflicts + | +-- proactive rebase conflicts: make-plan -> resolve-merge-conflicts + | +-- x fail -> diagnose-ci + | + +-- classic mode, for each ordered PR: + | merge-pr + | | + | +-- needs plan: + | make-plan + | +----+ FOR EACH PLAN PART: + | | dry-walkthrough -> implement -> test <-> [x fail -> fix] + | +----+ + | + +-- [audit] (optional) + | x fail -> make-plan [-> dry-walkthrough] + | + open-pr + | + +-- [analyze-pipeline-health] (optional, success or failure) +``` diff --git a/src/autoskillit/recipes/merge-prs.json b/src/autoskillit/recipes/merge-prs.json index 671a8d820b..1915fefdd8 100644 --- a/src/autoskillit/recipes/merge-prs.json +++ b/src/autoskillit/recipes/merge-prs.json @@ -1,7 +1,7 @@ { "name": "merge-prs", "description": "Merge open PRs into an integration branch", - "summary": "clone > setup_remote > analyze_prs > create_batch_branch > [loop per PR: merge_pr or (plan > verify > create_conflict_worktree > implement > test > push_worktree_branch > create_conflict_pr > wait_for_conflict_ci > merge_conflict_pr)] > push_batch_branch > collect_artifacts > check_impl_plans > (audit_impl?) > open_integration_pr > wait_for_review_pr_mergeability > check_mergeability > (resolve_integration_conflicts > force_push_after_rebase)? > review_pr_integration > (resolve_review_integration > re_push_review_integration)? > ci_watch_pr > cleanup", + "summary": "clone > setup_remote > analyze_prs > get_first_pr_number > route_by_queue_mode > create_batch_branch > [loop per PR: merge_pr > advance_merge_pr or (plan > verify > create_conflict_worktree > implement > test > push_worktree_branch > create_conflict_pr > wait_for_conflict_ci > merge_conflict_pr)] > push_batch_branch > collect_artifacts > check_impl_plans > (audit_impl?) > open_integration_pr > wait_for_review_pr_mergeability > check_mergeability > (resolve_integration_conflicts > force_push_after_rebase)? > review_pr_integration > (resolve_review_integration > re_push_review_integration)? > ci_watch_pr > cleanup", "recipe_version": "1.0.0", "requires_packs": [ "github", @@ -83,13 +83,13 @@ "SEQUENTIAL LOOP: Process one PR at a time through the full merge cycle before advancing to the next PR. Never batch-assess all PRs before starting merges.", "SEQUENTIAL EXECUTION: complete full cycle (verify → create_conflict_worktree → implement → test → push_worktree_branch → create_conflict_pr → wait_for_conflict_ci → merge_conflict_pr) per plan part before advancing to the next part or PR.", "INTEGRATION BRANCH: Two distinct branches exist. inputs.base_branch is the target branch that PRs point to (e.g. main, develop). context.batch_branch is the per-run batch branch (e.g. pr-batch/pr-merge-{ts}) created from base_branch for this pipeline run. All PR merges and worktree merges target context.batch_branch. The final review PR opens from context.batch_branch into inputs.base_branch.", - "PR QUEUE: The agent reads context.pr_order_file once at analyze_prs and maintains an ordered queue. context.current_pr_number tracks the current PR. advance_queue_pr captures the next PR number at the recipe level after each successful merge.", + "PR QUEUE: Only get_first_pr_number, advance_queue_pr and advance_merge_pr write context.current_pr_number and context.current_pr_complexity. Never set or advance these values yourself. The cursor reads the immutable analyze_prs order file.", "COMPLEX PR PATH: When merge_pr returns needs_plan=true, context.task is set to the conflict_report_path. Pass context.task to make-plan. The plan+implement cycle creates a worktree from the integration branch; the worktree branch is then pushed to origin and merged into the integration batch branch via GitHub PR (push_worktree_branch → create_conflict_pr → wait_for_conflict_ci → merge_conflict_pr).", "SOURCE ISOLATION: After clone_repo returns, the source_dir is strictly off-limits. Never run any command in source_dir — no git checkout, git fetch, git reset, git pull, run_cmd, run_skill, or any other operation. All work — skill invocations, git operations, file reads — happens exclusively in the clone (work_dir). source_dir is used ONLY to read the remote URL inside push_to_remote.", "GITHUB API MERGE: All PR merges into the integration branch go through GitHub's merge interface (gh pr merge --squash). This enforces the branch ruleset required status checks. Never use merge_worktree or local git merge to merge into the integration batch branch.", "PUSH DISCIPLINE: push_worktree_branch (inside the complex PR cycle), publish_batch_branch / push_batch_branch, force_push_and_wait_mergeability (authorized for conflict-resolution rebases), and push_rebased_next_pr (authorized for proactive pre-enqueue rebase) are the only authorized push steps. Never add ad-hoc run_cmd git push calls elsewhere in the loop.", "QUEUE MODE: When context.queue_mode == true, PRs merge directly into base_branch via the merge queue. The batch branch (context.batch_branch) is the same as base_branch. Never invoke create_batch_branch, publish_batch_branch, merge_pr, or push_batch_branch in queue mode.", - "QUEUE LOOP: In queue mode, context.current_pr_number tracks the current PR being waited on. Initialized by get_first_pr_number from pr_order_file[0]. advance_queue_pr looks up the current number in pr_order_file and captures the next entry's number.", + "QUEUE LOOP: get_first_pr_number initializes the PR number and complexity before selecting either mode. In queue mode, advance_queue_pr selects the successor by file position and returns done after the last PR without changing the artifact.", "CONFLICT REPORT PATHS: context.all_conflict_report_paths accumulates conflict_report_path values from resolve_ejected_conflicts and resolve_integration_conflicts via capture_list. Pass it as the 5th argument to open_integration_pr and 4th argument to audit_impl. It is empty string when no conflict resolution occurred — downstream skills treat empty string as absent." ], "steps": { @@ -200,40 +200,48 @@ "batch_branch": "${{ result.batch_branch }}", "queue_mode": "${{ result.queue_mode }}" }, - "on_success": "route_by_queue_mode", + "on_success": "get_first_pr_number", "on_failure": "register_clone_failure", "on_rate_limit": "register_clone_failure", "optional_context_refs": [ "merge_queue_data_path" ], - "note": "Captures pr_order_file (path to JSON with ordered PRs + complexity tags), batch_branch (e.g. integration/pr-merge-20250228-143052), and queue_mode (\"true\" when a GitHub merge queue with MERGEABLE entries is active on base_branch; \"false\" otherwise). If the skill reports pr_count=0 (no open PRs), skip directly to cleanup_success — no integration branch is needed. merge_queue_data_path is pre-computed by fetch_merge_queue_data step.\n" + "note": "Captures pr_order_file (path to JSON with ordered PRs + complexity tags), batch_branch (e.g. integration/pr-merge-20250228-143052), and queue_mode (\"true\" when a GitHub merge queue with MERGEABLE entries is active on base_branch; \"false\" otherwise). get_first_pr_number selects the initial cursor in either mode. An empty eligible prs list routes to register_clone_success without creating a batch branch. merge_queue_data_path is pre-computed by fetch_merge_queue_data.\n" }, "route_by_queue_mode": { "action": "route", "on_result": [ { "when": "${{ context.queue_mode }} == true", - "route": "get_first_pr_number" + "route": "get_current_pr_branch" }, { "route": "create_batch_branch" } ], - "note": "Routes to queue mode (get_first_pr_number) when analyze-prs detected a merge queue on the target branch. Falls back to the classic batch-branch path otherwise. context.queue_mode is captured from analyze_prs result.\n" + "note": "The cursor is already initialized. Select queue mode at get_current_pr_branch when analyze-prs detected a merge queue; otherwise select the classic batch-branch path." }, "get_first_pr_number": { - "tool": "run_cmd", + "tool": "run_python", "with": { - "cmd": "jq -r '.[0].number' '${{ context.pr_order_file }}'", - "cwd": "${{ context.work_dir }}", - "step_name": "get_first_pr_number" + "callable": "autoskillit.recipe._cmd_rpc.first_ordered_pr", + "pr_order_file": "${{ context.pr_order_file }}" }, "capture": { - "current_pr_number": "${{ result.stdout | trim }}" + "current_pr_number": "${{ result.pr_number }}", + "current_pr_complexity": "${{ result.complexity }}" }, - "on_success": "get_current_pr_branch", + "on_result": [ + { + "when": "${{ result.done }} == true", + "route": "register_clone_success" + }, + { + "route": "route_by_queue_mode" + } + ], "on_failure": "register_clone_failure", - "note": "Queue mode only. Extracts the first PR's number from pr_order_file to initialize context.current_pr_number before the sequential enqueue loop.\n" + "note": "Selects the first eligible PR number and complexity for both modes. An empty prs list means there is nothing eligible to merge and ends successfully without a batch branch." }, "get_current_pr_branch": { "tool": "run_cmd", @@ -323,7 +331,7 @@ }, "on_success": "wait_queue_pr", "on_failure": "verify_queue_enrollment", - "note": "Queue mode only. Submits a single PR to the merge queue via the unified enqueue_pr tool. Called once per PR in the sequential enqueue loop: get_first_pr_number → get_current_pr_branch → wait_ci_pre_enqueue → enqueue_current_pr → wait_queue_pr → (merged) → advance_queue_pr → get_current_pr_branch → wait_ci_pre_enqueue → enqueue_current_pr → ...\n" + "note": "Queue mode only. Submits a single PR to the merge queue via the unified enqueue_pr tool. Called once per PR in the sequential enqueue loop: get_first_pr_number → route_by_queue_mode → get_current_pr_branch → wait_ci_pre_enqueue → enqueue_current_pr → wait_queue_pr → (merged) → advance_queue_pr → get_current_pr_branch → wait_ci_pre_enqueue → enqueue_current_pr → ...\n" }, "wait_queue_pr": { "tool": "wait_for_merge_queue", @@ -774,16 +782,17 @@ "advance_queue_pr": { "tool": "run_python", "with": { - "callable": "autoskillit.recipe._cmd_rpc.advance_queue_pr", + "callable": "autoskillit.recipe._cmd_rpc.next_ordered_pr", "current_pr_number": "${{ context.current_pr_number }}", "pr_order_file": "${{ context.pr_order_file }}" }, "capture": { - "current_pr_number": "${{ result.current_pr_number }}" + "current_pr_number": "${{ result.pr_number }}", + "current_pr_complexity": "${{ result.complexity }}" }, "on_result": [ { - "when": "${{ result.current_pr_number }} == done", + "when": "${{ result.done }} == true", "route": "collect_and_check_impl_plans" }, { @@ -791,7 +800,7 @@ } ], "on_failure": "register_clone_failure", - "note": "Advances to the next PR by looking up the current PR number in pr_order_file and returning the next entry. Outputs the next PR number (or \"done\"). The capture block sets current_pr_number at the recipe level — no agent-managed variable updates. Routes to get_next_pr_branch for proactive rebase, or collect_and_check_impl_plans when done.\n" + "note": "Advances by file position and captures the next PR number and complexity. At the end, retains the last PR and returns done. Continues through proactive rebase or collects implementation plans when done." }, "get_next_pr_branch": { "tool": "run_cmd", @@ -1011,8 +1020,8 @@ "with": { "skill_command": "/autoskillit:merge-pr", "skill_inputs": { - "complexity": "{complexity}", - "pr_number": "{pr_number}" + "complexity": "${{ context.current_pr_complexity }}", + "pr_number": "${{ context.current_pr_number }}" }, "cwd": "${{ context.work_dir }}", "step_name": "merge_pr", @@ -1026,7 +1035,6 @@ "escalation_required": "${{ result.escalation_required }}", "escalation_reason": "${{ result.escalation_reason }}", "task": "${{ result.conflict_report_path }}", - "current_pr_number": "${{ result.pr_number }}", "merged": "${{ result.merged }}" }, "on_result": [ @@ -1051,7 +1059,7 @@ "on_exhausted": "register_clone_failure", "on_context_limit": "register_clone_failure", "on_rate_limit": "register_clone_failure", - "note": "The agent reads context.pr_order_file at context.current_pr_number to get the current PR's number and complexity. Both values are passed via structured skill_inputs (skill_inputs.pr_number and skill_inputs.complexity) — do NOT append them to skill_command, which stays the fixed literal /autoskillit:merge-pr. escalation_required=true → ambiguous conflict, human intervention needed → escalate_stop. needs_plan=true → conflict_report_path set as context.task → plan. merged=false (timeout/conflict) → register_clone_failure. merged=true + fallthrough → PR merged directly → next_part_or_next_pr.\n" + "note": "Both inputs come from the recipe-level cursor. Send context.current_pr_number and context.current_pr_complexity exactly as strings in structured skill_inputs. skill_command stays the fixed literal /autoskillit:merge-pr. escalation_required=true routes to escalate_stop. needs_plan=true sets conflict_report_path as context.task and routes to plan. merged=false routes to register_clone_failure. A successful direct merge routes to next_part_or_next_pr." }, "plan": { "tool": "run_skill", @@ -1443,11 +1451,37 @@ "field": "next", "routes": { "more_parts": "select_next_plan_part", - "more_prs": "check_pr_merge_loop", - "all_done": "push_batch_branch" + "next_pr": "advance_merge_pr" } }, - "note": "Routing step — no tool call. The agent evaluates what comes next: 1. If more plan_parts remain for the current PR → verify (next part). 2. If all parts done, advance current_pr_number. If more PRs remain → check_pr_merge_loop. 3. If all PRs processed → push_batch_branch.\n" + "note": "The agent decides only whether plan parts remain for the current PR. More parts route to select_next_plan_part; otherwise advance_merge_pr determines whether another PR remains." + }, + "advance_merge_pr": { + "tool": "run_python", + "with": { + "callable": "autoskillit.recipe._cmd_rpc.next_ordered_pr", + "current_pr_number": "${{ context.current_pr_number }}", + "pr_order_file": "${{ context.pr_order_file }}" + }, + "capture": { + "current_pr_number": "${{ result.pr_number }}", + "current_pr_complexity": "${{ result.complexity }}" + }, + "on_result": [ + { + "when": "${{ context.queue_mode }} == true and ${{ result.done }} == true", + "route": "collect_and_check_impl_plans" + }, + { + "when": "${{ result.done }} == true", + "route": "push_batch_branch" + }, + { + "route": "check_pr_merge_loop" + } + ], + "on_failure": "register_clone_failure", + "note": "Classic and post-remediation advance, keyed on current_pr_number once per finished PR. Queue-mode audit remediation re-enters at the last PR and exits to collect_and_check_impl_plans through the first done arm." }, "select_next_plan_part": { "tool": "run_cmd", @@ -1485,7 +1519,7 @@ "optional_context_refs": [ "pr_merge_loop_count" ], - "note": "Guards the merge_pr → next_part_or_next_pr outer loop. The loop is data-bounded by the finite pr_order_file list; this provides a structural bound for the cycle validator. 50 iterations allows large batch runs. Unlike retry loops (capped at 3–15 attempts), this cap is an outer iteration over data items (PRs to merge), not a retry count — hence the higher bound is safe: it tracks distinct work units, not repeated attempts on the same operation.\n" + "note": "Guards the merge_pr → next_part_or_next_pr → advance_merge_pr outer loop. The cursor advances through the finite prs list; this provides a structural bound for the cycle validator. 50 iterations allows large batch runs. Unlike retry loops (capped at 3–15 attempts), this cap is an outer iteration over data items (PRs to merge), not a retry count — hence the higher bound is safe: it tracks distinct work units, not repeated attempts on the same operation.\n" }, "push_batch_branch": { "tool": "push_to_remote", diff --git a/src/autoskillit/recipes/merge-prs.yaml b/src/autoskillit/recipes/merge-prs.yaml index c7c8aeafbb..06923673f7 100644 --- a/src/autoskillit/recipes/merge-prs.yaml +++ b/src/autoskillit/recipes/merge-prs.yaml @@ -1,6 +1,6 @@ name: merge-prs description: Merge open PRs into an integration branch -summary: 'clone > setup_remote > analyze_prs > create_batch_branch > [loop per PR: merge_pr or (plan > verify > create_conflict_worktree > implement +summary: 'clone > setup_remote > analyze_prs > get_first_pr_number > route_by_queue_mode > create_batch_branch > [loop per PR: merge_pr > advance_merge_pr or (plan > verify > create_conflict_worktree > implement > test > push_worktree_branch > create_conflict_pr > wait_for_conflict_ci > merge_conflict_pr)] > push_batch_branch > collect_artifacts > check_impl_plans > (audit_impl?) > open_integration_pr > wait_for_review_pr_mergeability > check_mergeability > (resolve_integration_conflicts > force_push_after_rebase)? > review_pr_integration > (resolve_review_integration > re_push_review_integration)? > ci_watch_pr @@ -76,8 +76,8 @@ kitchen_rules: develop). context.batch_branch is the per-run batch branch (e.g. pr-batch/pr-merge-{ts}) created from base_branch for this pipeline run. All PR merges and worktree merges target context.batch_branch. The final review PR opens from context.batch_branch into inputs.base_branch.' -- 'PR QUEUE: The agent reads context.pr_order_file once at analyze_prs and maintains an ordered queue. context.current_pr_number - tracks the current PR. advance_queue_pr captures the next PR number at the recipe level after each successful merge.' +- 'PR QUEUE: Only get_first_pr_number, advance_queue_pr and advance_merge_pr write context.current_pr_number and + context.current_pr_complexity. Never set or advance these values yourself. The cursor reads the immutable analyze_prs order file.' - 'COMPLEX PR PATH: When merge_pr returns needs_plan=true, context.task is set to the conflict_report_path. Pass context.task to make-plan. The plan+implement cycle creates a worktree from the integration branch; the worktree branch is then pushed to origin and merged into the integration batch branch via GitHub PR (push_worktree_branch → create_conflict_pr → wait_for_conflict_ci @@ -95,8 +95,8 @@ kitchen_rules: - 'QUEUE MODE: When context.queue_mode == true, PRs merge directly into base_branch via the merge queue. The batch branch (context.batch_branch) is the same as base_branch. Never invoke create_batch_branch, publish_batch_branch, merge_pr, or push_batch_branch in queue mode.' -- 'QUEUE LOOP: In queue mode, context.current_pr_number tracks the current PR being waited on. Initialized by get_first_pr_number - from pr_order_file[0]. advance_queue_pr looks up the current number in pr_order_file and captures the next entry''s number.' +- 'QUEUE LOOP: get_first_pr_number initializes the PR number and complexity before selecting either mode. In queue mode, + advance_queue_pr selects the successor by file position and returns done after the last PR without changing the artifact.' - 'CONFLICT REPORT PATHS: context.all_conflict_report_paths accumulates conflict_report_path values from resolve_ejected_conflicts and resolve_integration_conflicts via capture_list. Pass it as the 5th argument to open_integration_pr and 4th argument to audit_impl. It is empty string when no conflict resolution occurred — downstream skills treat empty string as absent.' @@ -222,41 +222,40 @@ steps: pr_order_file: ${{ result.pr_order_file }} batch_branch: ${{ result.batch_branch }} queue_mode: ${{ result.queue_mode }} - on_success: route_by_queue_mode + on_success: get_first_pr_number on_failure: register_clone_failure on_rate_limit: register_clone_failure optional_context_refs: - merge_queue_data_path note: 'Captures pr_order_file (path to JSON with ordered PRs + complexity tags), batch_branch (e.g. integration/pr-merge-20250228-143052), and queue_mode ("true" when a GitHub merge queue with MERGEABLE entries is active on base_branch; "false" otherwise). - If the skill reports pr_count=0 (no open PRs), skip directly to cleanup_success — no integration branch is needed. merge_queue_data_path - is pre-computed by fetch_merge_queue_data step. + get_first_pr_number selects the initial cursor in either mode. An empty eligible prs list routes to register_clone_success + without creating a batch branch. merge_queue_data_path is pre-computed by fetch_merge_queue_data. ' route_by_queue_mode: action: route on_result: - when: ${{ context.queue_mode }} == true - route: get_first_pr_number + route: get_current_pr_branch - route: create_batch_branch - note: 'Routes to queue mode (get_first_pr_number) when analyze-prs detected a merge queue on the target branch. Falls - back to the classic batch-branch path otherwise. context.queue_mode is captured from analyze_prs result. - - ' + note: 'The cursor is already initialized. Select queue mode at get_current_pr_branch when analyze-prs detected a merge + queue; otherwise select the classic batch-branch path.' get_first_pr_number: - tool: run_cmd + tool: run_python with: - cmd: jq -r '.[0].number' '${{ context.pr_order_file }}' - cwd: ${{ context.work_dir }} - step_name: get_first_pr_number + callable: autoskillit.recipe._cmd_rpc.first_ordered_pr + pr_order_file: ${{ context.pr_order_file }} capture: - current_pr_number: ${{ result.stdout | trim }} - on_success: get_current_pr_branch + current_pr_number: ${{ result.pr_number }} + current_pr_complexity: ${{ result.complexity }} + on_result: + - when: ${{ result.done }} == true + route: register_clone_success + - route: route_by_queue_mode on_failure: register_clone_failure - note: 'Queue mode only. Extracts the first PR''s number from pr_order_file to initialize context.current_pr_number before - the sequential enqueue loop. - - ' + note: 'Selects the first eligible PR number and complexity for both modes. An empty prs list means there is nothing + eligible to merge and ends successfully without a batch branch.' get_current_pr_branch: tool: run_cmd with: @@ -334,7 +333,7 @@ steps: on_success: wait_queue_pr on_failure: verify_queue_enrollment note: 'Queue mode only. Submits a single PR to the merge queue via the unified enqueue_pr tool. Called once per PR in - the sequential enqueue loop: get_first_pr_number → get_current_pr_branch → wait_ci_pre_enqueue → enqueue_current_pr + the sequential enqueue loop: get_first_pr_number → route_by_queue_mode → get_current_pr_branch → wait_ci_pre_enqueue → enqueue_current_pr → wait_queue_pr → (merged) → advance_queue_pr → get_current_pr_branch → wait_ci_pre_enqueue → enqueue_current_pr → ... ' @@ -669,21 +668,19 @@ steps: advance_queue_pr: tool: run_python with: - callable: autoskillit.recipe._cmd_rpc.advance_queue_pr + callable: autoskillit.recipe._cmd_rpc.next_ordered_pr current_pr_number: ${{ context.current_pr_number }} pr_order_file: ${{ context.pr_order_file }} capture: - current_pr_number: ${{ result.current_pr_number }} + current_pr_number: ${{ result.pr_number }} + current_pr_complexity: ${{ result.complexity }} on_result: - - when: ${{ result.current_pr_number }} == done + - when: ${{ result.done }} == true route: collect_and_check_impl_plans - route: get_next_pr_branch on_failure: register_clone_failure - note: 'Advances to the next PR by looking up the current PR number in pr_order_file and returning the next entry. Outputs - the next PR number (or "done"). The capture block sets current_pr_number at the recipe level — no agent-managed variable - updates. Routes to get_next_pr_branch for proactive rebase, or collect_and_check_impl_plans when done. - - ' + note: 'Advances by file position and captures the next PR number and complexity. At the end, retains the last PR and + returns done. Continues through proactive rebase or collects implementation plans when done.' get_next_pr_branch: tool: run_cmd with: @@ -880,8 +877,8 @@ steps: with: skill_command: /autoskillit:merge-pr skill_inputs: - complexity: '{complexity}' - pr_number: '{pr_number}' + complexity: ${{ context.current_pr_complexity }} + pr_number: ${{ context.current_pr_number }} cwd: ${{ context.work_dir }} step_name: merge_pr output_dir: '{{AUTOSKILLIT_TEMP}}/merge-prs/iter_${{ context.pr_merge_loop_count }}' @@ -892,7 +889,6 @@ steps: escalation_required: ${{ result.escalation_required }} escalation_reason: ${{ result.escalation_reason }} task: ${{ result.conflict_report_path }} - current_pr_number: ${{ result.pr_number }} merged: ${{ result.merged }} on_result: - when: ${{ result.escalation_required }} == true @@ -907,13 +903,10 @@ steps: on_exhausted: register_clone_failure on_context_limit: register_clone_failure on_rate_limit: register_clone_failure - note: "The agent reads context.pr_order_file at context.current_pr_number to get the current PR's number and complexity.\ - \ Both values are passed via structured skill_inputs (skill_inputs.pr_number\ - \ and skill_inputs.complexity) \u2014 do NOT append them to skill_command, which\ - \ stays the fixed literal /autoskillit:merge-pr. escalation_required=true\ - \ → ambiguous conflict, human intervention needed → escalate_stop. needs_plan=true → conflict_report_path set as context.task\ - \ → plan. merged=false (timeout/conflict) → register_clone_failure. merged=true + fallthrough → PR merged directly →\ - \ next_part_or_next_pr.\n" + note: 'Both inputs come from the recipe-level cursor. Send context.current_pr_number and context.current_pr_complexity + exactly as strings in structured skill_inputs. skill_command stays the fixed literal /autoskillit:merge-pr. + escalation_required=true routes to escalate_stop. needs_plan=true sets conflict_report_path as context.task and routes + to plan. merged=false routes to register_clone_failure. A successful direct merge routes to next_part_or_next_pr.' plan: tool: run_skill model: '' @@ -1264,13 +1257,27 @@ steps: field: next routes: more_parts: select_next_plan_part - more_prs: check_pr_merge_loop - all_done: push_batch_branch - note: 'Routing step — no tool call. The agent evaluates what comes next: 1. If more plan_parts remain for the current - PR → verify (next part). 2. If all parts done, advance current_pr_number. If more PRs remain → check_pr_merge_loop. - 3. If all PRs processed → push_batch_branch. - - ' + next_pr: advance_merge_pr + note: 'The agent decides only whether plan parts remain for the current PR. More parts route to select_next_plan_part; + otherwise advance_merge_pr determines whether another PR remains.' + advance_merge_pr: + tool: run_python + with: + callable: autoskillit.recipe._cmd_rpc.next_ordered_pr + current_pr_number: ${{ context.current_pr_number }} + pr_order_file: ${{ context.pr_order_file }} + capture: + current_pr_number: ${{ result.pr_number }} + current_pr_complexity: ${{ result.complexity }} + on_result: + - when: ${{ context.queue_mode }} == true and ${{ result.done }} == true + route: collect_and_check_impl_plans + - when: ${{ result.done }} == true + route: push_batch_branch + - route: check_pr_merge_loop + on_failure: register_clone_failure + note: 'Classic and post-remediation advance, keyed on current_pr_number once per finished PR. Queue-mode audit remediation + re-enters at the last PR and exits to collect_and_check_impl_plans through the first done arm.' select_next_plan_part: tool: run_cmd with: @@ -1300,7 +1307,7 @@ steps: on_failure: register_clone_failure optional_context_refs: - pr_merge_loop_count - note: 'Guards the merge_pr → next_part_or_next_pr outer loop. The loop is data-bounded by the finite pr_order_file list; + note: 'Guards the merge_pr → next_part_or_next_pr → advance_merge_pr outer loop. The cursor advances through the finite prs list; this provides a structural bound for the cycle validator. 50 iterations allows large batch runs. Unlike retry loops (capped at 3–15 attempts), this cap is an outer iteration over data items (PRs to merge), not a retry count — hence the higher bound is safe: it tracks distinct work units, not repeated attempts on the same operation. diff --git a/src/autoskillit/recipes/scripts/advance_queue_pr.sh b/src/autoskillit/recipes/scripts/advance_queue_pr.sh deleted file mode 100755 index 18fc768c28..0000000000 --- a/src/autoskillit/recipes/scripts/advance_queue_pr.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -# Args: $1=current_pr_number $2=pr_order_file -CURRENT="$1" -PR_ORDER_FILE="$2" - -NEXT=$(jq -r --arg cur "$CURRENT" ' - (to_entries | map(select(.value.number == ($cur | tonumber))) | .[0].key) as $idx | - if ($idx + 1) < length then .[$idx + 1].number | tostring - else "done" - end -' "$PR_ORDER_FILE") - -echo "$NEXT" diff --git a/src/autoskillit/skills_extended/analyze-prs/SKILL.md b/src/autoskillit/skills_extended/analyze-prs/SKILL.md index 3ad30a3100..f2fccb468c 100644 --- a/src/autoskillit/skills_extended/analyze-prs/SKILL.md +++ b/src/autoskillit/skills_extended/analyze-prs/SKILL.md @@ -87,8 +87,30 @@ Run: gh pr list --base {base_branch} --state open --json number,title,headRefName,author,body,additions,deletions,changedFiles --limit 100 ``` -If zero PRs are returned: write a summary to terminal and exit cleanly with an empty -`pr_order_{ts}.json` (zero PRs, no integration branch needed). +If zero PRs are returned, compute `{ts}` with `YYYY-MM-DD_HHMMSS` and the batch +branch name from Step 5 without creating the branch. Write +`{{AUTOSKILLIT_TEMP}}/merge-prs/pr_order_{ts}.json` as the documented object with +`batch_branch`, `base_branch`, `generated_at`, `"pr_count": 0`, `"prs": []`, +`"ci_blocked_prs": []` and `"review_blocked_prs": []`. The artifact must exist; +its output path must be absolute and inside the session cwd. + +Print a summary, then emit this token block as the last output. No analysis plan +is written on this early exit, so omit `analysis_file`. Queue detection has not run. + +``` +pr_order_file = {absolute_path_to_pr_order_json} +batch_branch = {batch_branch_name} +pr_count = 0 +simple_count = 0 +needs_check_count = 0 +ci_blocked_count = 0 +review_blocked_count = 0 +queue_mode = false +``` + +When open PRs exist but all are filtered into the blocked arrays, complete the +normal output flow: preserve those arrays, their counts, the detected queue mode, +and the analysis file. The eligible `prs` list is still empty. If `gh` returns an auth error: abort with a clear message. diff --git a/src/autoskillit/skills_extended/merge-pr/SKILL.md b/src/autoskillit/skills_extended/merge-pr/SKILL.md index 6a33cc86af..d36026ddd9 100644 --- a/src/autoskillit/skills_extended/merge-pr/SKILL.md +++ b/src/autoskillit/skills_extended/merge-pr/SKILL.md @@ -45,12 +45,18 @@ conflicts from earlier merges in the queue. ## Arguments +The recipe supplies structured `skill_inputs`, for example +`{"pr_number": "42", "complexity": "simple"}`. + +- `pr_number` — GitHub PR number as a positive-integer string +- `complexity` — `simple` or `needs_check`; the recipe cursor selects it from + the `analyze-prs` order artifact. This provenance does not require a file argument. + +Standalone callers such as `process-issues` may also use inline arguments: + ``` -{pr_number} {complexity} +/autoskillit:merge-pr {pr_number} {complexity} ``` - -- `pr_number` — GitHub PR number (integer) -- `complexity` — `simple` or `needs_check` (from `analyze-prs` pr_order JSON) - Workflow value `{output_dir}` — the literal directory printed in the conflict-plan workflow and pasted into its later `mkdir` call; it is not a positional argument. @@ -80,8 +86,10 @@ conflicts from earlier merges in the queue. ### Step 0: Validate Inputs -- Parse `pr_number` (must be a positive integer) -- Parse `complexity` (must be `simple` or `needs_check`) +- Validate the supplied structured `skill_inputs` (or standalone inline arguments). +- Parse `pr_number` (must be a positive-integer string). +- Parse `complexity` (must be `simple` or `needs_check`). +- Use these supplied values; do not reselect a PR or complexity from the order file. - Verify git working tree is clean: `git status --porcelain` must be empty. If dirty: abort with error. - Identify current branch: `git branch --show-current` (this is the integration branch) diff --git a/tests/contracts/test_completion_receipt_fitness.py b/tests/contracts/test_completion_receipt_fitness.py index 4486289493..2ec9b6cef0 100644 --- a/tests/contracts/test_completion_receipt_fitness.py +++ b/tests/contracts/test_completion_receipt_fitness.py @@ -145,6 +145,64 @@ def test_implementation_shape_supplies_unavailable_context( assert dict(bound) == assembled +@pytest.mark.parametrize( + ("pr_number", "complexity"), + [ + pytest.param("4", "needs_check", id="single-digit-cursor"), + pytest.param("123", "simple", id="multi-digit-cursor"), + ], +) +def test_merge_pr_admits_realistic_cursor_values( + pr_number: str, + complexity: str, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + from autoskillit.recipe._binding import bind_runtime_skill_invocation + from autoskillit.recipe.api import _api_cache + from autoskillit.recipe.api._api_cache import LoadCache + from autoskillit.server.recipe import _recipe_generation + + monkeypatch.setattr(_api_cache, "_LOAD_CACHE", LoadCache()) + monkeypatch.setattr(_recipe_generation, "_RECIPE_GENERATION_STORE", RecipeGenerationStore()) + payload, projection = _full_open_kitchen_generation("merge-prs") + tool_ctx = cast( + Any, + SimpleNamespace( + backend=None, + **kitchen_identity_fields(f"merge-pr-cursor-{pr_number}-{complexity}"), + temp_dir=tmp_path, + ), + ) + prepared = prepare_recipe_delivery_generation( + payload, + recipe_name="merge-prs", + tool_ctx=tool_ctx, + finalized_projection=projection, + ) + credential = build_recipe_execution_credential(prepared.execution_snapshot) + shape = credential.as_wire_block()["skill_input_shapes"]["merge_pr"] + assert shape["keys"] == ["pr_number", "complexity"] + + template = prepared.execution_snapshot.templates["merge_pr"] + actual_mcp_kwargs = { + value.name: value.effective_value + for value in template.invocation.mcp_kwargs + if isinstance(value.effective_value, (str, int, bool)) + } + skill_inputs = {"pr_number": pr_number, "complexity": complexity} + bound = bind_runtime_skill_invocation( + template, + execution_id=prepared.execution_snapshot.execution_id, + step_name="merge_pr", + skill_command="/autoskillit:merge-pr", + skill_inputs=skill_inputs, + actual_mcp_kwargs=actual_mcp_kwargs, + ) + + assert dict(bound) == skill_inputs + + @pytest.mark.parametrize( "recipe_name", delivery_recipe_names(Path(__file__).resolve().parents[2]), ids=lambda n: n ) diff --git a/tests/infra/test_recipe_read_guard.py b/tests/infra/test_recipe_read_guard.py index d9455d9257..c27746a15a 100644 --- a/tests/infra/test_recipe_read_guard.py +++ b/tests/infra/test_recipe_read_guard.py @@ -211,7 +211,8 @@ def test_cmd_rpc_callables_not_blocked(self): "autoskillit.recipe._cmd_rpc_merge.wait_for_review_pr_mergeability", "autoskillit.recipe._cmd_rpc_merge.create_persistent_integration", "autoskillit.recipe._cmd_rpc_merge.force_push_and_wait_mergeability", - "autoskillit.recipe._cmd_rpc_merge.advance_queue_pr", + "autoskillit.recipe._cmd_rpc.first_ordered_pr", + "autoskillit.recipe._cmd_rpc.next_ordered_pr", "autoskillit.recipe._cmd_rpc_merge.review_path_rebase", "autoskillit.recipe._cmd_rpc_merge.proactive_rebase_next_pr", "autoskillit.recipe._cmd_rpc_issues.refetch_issues", diff --git a/tests/infra/test_recipe_read_guard_callable_parity.py b/tests/infra/test_recipe_read_guard_callable_parity.py index f968c5b7c0..0c4d22067e 100644 --- a/tests/infra/test_recipe_read_guard_callable_parity.py +++ b/tests/infra/test_recipe_read_guard_callable_parity.py @@ -31,7 +31,8 @@ "autoskillit.recipe._cmd_rpc_merge.wait_for_review_pr_mergeability", "autoskillit.recipe._cmd_rpc_merge.create_persistent_integration", "autoskillit.recipe._cmd_rpc_merge.force_push_and_wait_mergeability", - "autoskillit.recipe._cmd_rpc_merge.advance_queue_pr", + "autoskillit.recipe._cmd_rpc.first_ordered_pr", + "autoskillit.recipe._cmd_rpc.next_ordered_pr", "autoskillit.recipe._cmd_rpc_merge.review_path_rebase", "autoskillit.recipe._cmd_rpc_merge.proactive_rebase_next_pr", "autoskillit.recipe._cmd_rpc_issues.refetch_issues", diff --git a/tests/recipe/test_cmd_rpc_merge.py b/tests/recipe/test_cmd_rpc_merge.py index 3c25939a6a..c083e4825b 100644 --- a/tests/recipe/test_cmd_rpc_merge.py +++ b/tests/recipe/test_cmd_rpc_merge.py @@ -2,10 +2,12 @@ from __future__ import annotations +import json from unittest.mock import MagicMock, patch import pytest +import autoskillit.recipe._cmd_rpc as _cmd_rpc import autoskillit.recipe.cmd_rpc._cmd_rpc_merge as _patch_cmd_rpc__cmd_rpc_merge pytestmark = [pytest.mark.layer("recipe"), pytest.mark.small] @@ -219,3 +221,175 @@ def test_proactive_rebase_next_pr_publishes_conflict_report(tmp_path): assert result["status"] == "conflicts" assert result["conflict_report_path"] == str(report_path) assert "src/y.py" in report_path.read_text() + + +def _ordered_pr(number: object, complexity: object = "simple") -> dict[str, object]: + return { + "number": number, + "title": f"PR {number}", + "branch": f"feature/{number}", + "complexity": complexity, + "files_changed": [f"src/{number}.py"], + "test_files_changed": [f"tests/test_{number}.py"], + "additions": 2, + "deletions": 1, + "overlap_with_pr_numbers": [], + } + + +def _order_document(prs: list[dict[str, object]]) -> dict[str, object]: + return { + "batch_branch": "pr-batch/pr-merge-20261024-120000", + "base_branch": "main", + "generated_at": "2026-10-24T12:00:00Z", + "pr_count": len(prs), + "prs": prs, + } + + +def _write_order_file(tmp_path, document: object): + path = tmp_path / "pr-order.json" + path.write_text(json.dumps(document), encoding="utf-8") + return path + + +@pytest.fixture +def pr_order_file(tmp_path): + return _write_order_file( + tmp_path, + _order_document( + [ + _ordered_pr(42), + _ordered_pr(4, "needs_check"), + _ordered_pr(123), + ] + ), + ) + + +def test_first_ordered_pr_returns_first_number_and_complexity(pr_order_file): + assert _cmd_rpc.first_ordered_pr(pr_order_file=str(pr_order_file)) == { + "pr_number": "42", + "complexity": "simple", + "done": "false", + } + + +def test_first_ordered_pr_returns_done_for_empty_order(tmp_path): + path = _write_order_file(tmp_path, _order_document([])) + + assert _cmd_rpc.first_ordered_pr(pr_order_file=str(path)) == { + "pr_number": "", + "complexity": "", + "done": "true", + } + + +@pytest.mark.parametrize( + ("current", "number", "complexity"), [("42", "4", "needs_check"), ("4", "123", "simple")] +) +def test_next_ordered_pr_advances_by_file_position(pr_order_file, current, number, complexity): + assert _cmd_rpc.next_ordered_pr( + pr_order_file=str(pr_order_file), current_pr_number=current + ) == { + "pr_number": number, + "complexity": complexity, + "done": "false", + } + + +def test_next_ordered_pr_repeats_last_entry_as_done_without_mutating_file( + pr_order_file, +): + before = pr_order_file.read_bytes() + + expected = {"pr_number": "123", "complexity": "simple", "done": "true"} + first = _cmd_rpc.next_ordered_pr(pr_order_file=str(pr_order_file), current_pr_number="123") + second = _cmd_rpc.next_ordered_pr(pr_order_file=str(pr_order_file), current_pr_number="123") + + assert first == expected + assert second == expected + assert pr_order_file.read_bytes() == before + + +def test_first_ordered_pr_rejects_relative_path_before_file_access(): + with pytest.raises(ValueError): + _cmd_rpc.first_ordered_pr(pr_order_file="relative-pr-order.json") + + +@pytest.mark.parametrize("current_pr_number", ["", "999", "done", "#4"]) +def test_next_ordered_pr_rejects_invalid_current_number(pr_order_file, current_pr_number): + with pytest.raises(ValueError): + _cmd_rpc.next_ordered_pr( + pr_order_file=str(pr_order_file), current_pr_number=current_pr_number + ) + + +@pytest.mark.parametrize( + ("field", "value"), + [ + pytest.param("complexity", [], id="complexity-list"), + pytest.param("complexity", "unknown", id="complexity-unknown"), + pytest.param("number", True, id="number-bool"), + pytest.param("number", 0, id="number-zero"), + pytest.param("number", -1, id="number-negative"), + pytest.param("number", "42", id="number-string"), + ], +) +def test_first_ordered_pr_reports_invalid_pr_field_location(tmp_path, field, value): + pr = _ordered_pr(42) + pr[field] = value + path = _write_order_file(tmp_path, _order_document([pr])) + + with pytest.raises(ValueError) as exc_info: + _cmd_rpc.first_ordered_pr(pr_order_file=str(path)) + + message = str(exc_info.value) + assert str(path) in message + assert "prs[0]" in message + + +def test_first_ordered_pr_reports_duplicate_number_location(tmp_path): + path = _write_order_file(tmp_path, _order_document([_ordered_pr(42), _ordered_pr(42)])) + + with pytest.raises(ValueError) as exc_info: + _cmd_rpc.first_ordered_pr(pr_order_file=str(path)) + + assert str(path) in str(exc_info.value) + assert "prs[1]" in str(exc_info.value) + + +@pytest.mark.parametrize( + "malformation", ["top-level-list", "missing-prs", "nonlist-prs", "nondict-entry"] +) +def test_first_ordered_pr_reports_invalid_order_document(tmp_path, malformation): + document = _order_document([_ordered_pr(42)]) + if malformation == "top-level-list": + document = [] + elif malformation == "missing-prs": + document.pop("prs") + elif malformation == "nonlist-prs": + document["prs"] = {} + else: + document["prs"] = [None] + path = _write_order_file(tmp_path, document) + + with pytest.raises(ValueError) as exc_info: + _cmd_rpc.first_ordered_pr(pr_order_file=str(path)) + + message = str(exc_info.value) + assert str(path) in message + if malformation == "nondict-entry": + assert "prs[0]" in message + + +@pytest.mark.parametrize("file_contents", [None, "{"]) +def test_first_ordered_pr_wraps_file_read_errors_as_runtime_error(tmp_path, file_contents): + path = tmp_path / "pr-order.json" + if file_contents is not None: + path.write_text(file_contents, encoding="utf-8") + + with pytest.raises(RuntimeError) as exc_info: + _cmd_rpc.first_ordered_pr(pr_order_file=str(path)) + + assert str(path) in str(exc_info.value) diff --git a/tests/recipe/test_contracts.py b/tests/recipe/test_contracts.py index 25a318eb6d..2bdaa0a3ba 100644 --- a/tests/recipe/test_contracts.py +++ b/tests/recipe/test_contracts.py @@ -1075,16 +1075,16 @@ def test_callable_contract_nullable_field() -> None: manifest = load_bundled_manifest() contracts = manifest.get("callable_contracts", {}) - assert "autoskillit.recipe._cmd_rpc.advance_queue_pr" in contracts, ( - "advance_queue_pr must be declared in callable_contracts" + assert "autoskillit.recipe._cmd_rpc.next_ordered_pr" in contracts, ( + "next_ordered_pr must be declared in callable_contracts" ) - aq_contract = contracts["autoskillit.recipe._cmd_rpc.advance_queue_pr"] - pr_input = next((i for i in aq_contract["inputs"] if i["name"] == "current_pr_number"), None) + next_contract = contracts["autoskillit.recipe._cmd_rpc.next_ordered_pr"] + pr_input = next((i for i in next_contract["inputs"] if i["name"] == "current_pr_number"), None) assert pr_input is not None, "current_pr_number input must be declared" assert pr_input.get("nullable") is False, ( "current_pr_number must be explicitly non-nullable (nullable: false)" ) - parsed = get_callable_contract("autoskillit.recipe._cmd_rpc.advance_queue_pr", manifest) + parsed = get_callable_contract("autoskillit.recipe._cmd_rpc.next_ordered_pr", manifest) assert parsed is not None pr_parsed = next((i for i in parsed.inputs if i.name == "current_pr_number"), None) assert pr_parsed is not None diff --git a/tests/recipe/test_merge_prs_pr_cursor.py b/tests/recipe/test_merge_prs_pr_cursor.py new file mode 100644 index 0000000000..9c82a2e02a --- /dev/null +++ b/tests/recipe/test_merge_prs_pr_cursor.py @@ -0,0 +1,115 @@ +"""Dataflow and routing contracts for the merge-prs PR cursor.""" + +from __future__ import annotations + +import pytest + +from autoskillit.core import BoundValueOrigin +from autoskillit.recipe._analysis import make_validation_context +from autoskillit.recipe._binding import bind_recipe +from autoskillit.recipe.analysis._analysis_detectors import _context_refs_in_value +from autoskillit.recipe.io import builtin_recipes_dir, load_recipe + +pytestmark = [pytest.mark.layer("recipe"), pytest.mark.small] + + +@pytest.fixture(scope="module") +def recipe(): + return load_recipe(builtin_recipes_dir() / "merge-prs.yaml") + + +def test_cursor_steps_have_defined_inputs_and_single_writer(recipe) -> None: + invocation = bind_recipe(recipe).for_step("merge_pr") + assert invocation is not None + for name, dependency in ( + ("pr_number", "current_pr_number"), + ("complexity", "current_pr_complexity"), + ): + bound = invocation.skill_input(name) + assert bound is not None + assert bound.origin is BoundValueOrigin.CONTEXT + assert bound.context_dependencies == (dependency,) + + cursor_fields = {"current_pr_number", "current_pr_complexity"} + cursor_steps = { + "get_first_pr_number": "autoskillit.recipe._cmd_rpc.first_ordered_pr", + "advance_queue_pr": "autoskillit.recipe._cmd_rpc.next_ordered_pr", + "advance_merge_pr": "autoskillit.recipe._cmd_rpc.next_ordered_pr", + } + + must_defined = make_validation_context(recipe).must_defined_context + for step_name in ("advance_queue_pr", "advance_merge_pr"): + assert {"current_pr_number", "pr_order_file"} <= must_defined.get(step_name, frozenset()) + + writers = { + name + for name, step in recipe.steps.items() + if cursor_fields.intersection(set(step.capture) | set(step.capture_list)) + } + assert writers == set(cursor_steps) + assert not cursor_fields.intersection( + set(recipe.steps["merge_pr"].capture) | set(recipe.steps["merge_pr"].capture_list) + ) + merge_inputs = recipe.steps["merge_pr"].with_args["skill_inputs"] + assert merge_inputs["pr_number"] == "${{ context.current_pr_number }}" + assert merge_inputs["complexity"] == "${{ context.current_pr_complexity }}" + + for step_name, callable_name in cursor_steps.items(): + step = recipe.steps[step_name] + assert step.tool == "run_python" + assert step.with_args.get("callable") == callable_name + assert cursor_fields <= set(step.capture) + assert step.capture["current_pr_number"].from_ == "${{ result.pr_number }}" + assert step.capture["current_pr_complexity"].from_ == "${{ result.complexity }}" + + +def test_pr_order_file_has_declared_recipe_consumers(recipe) -> None: + consumers = { + name + for name, step in recipe.steps.items() + if "pr_order_file" in _context_refs_in_value(step.declared_with_args or {}) + } + assert consumers == { + "get_first_pr_number", + "advance_queue_pr", + "advance_merge_pr", + "open_integration_pr", + } + + writers = { + name + for name, step in recipe.steps.items() + if "pr_order_file" in step.capture or "pr_order_file" in step.capture_list + } + assert writers == {"analyze_prs"} + + integration_inputs = recipe.steps["open_integration_pr"].with_args["skill_inputs"] + assert integration_inputs["pr_order_file"] == "${{ context.pr_order_file }}" + + shell_readers = { + name + for name, step in recipe.steps.items() + if step.tool == "run_cmd" + and "pr_order_file" in _context_refs_in_value((step.declared_with_args or {}).get("cmd")) + } + assert shell_readers == set() + + +def test_cursor_routes_preserve_plan_iteration_and_pr_advancement(recipe) -> None: + next_part = recipe.steps["next_part_or_next_pr"] + assert next_part.on_result is not None + assert next_part.on_result.routes == { + "more_parts": "select_next_plan_part", + "next_pr": "advance_merge_pr", + } + + advance = recipe.steps["advance_merge_pr"] + assert advance.on_result is not None + assert [(condition.when, condition.route) for condition in advance.on_result.conditions] == [ + ( + "${{ context.queue_mode }} == true and ${{ result.done }} == true", + "collect_and_check_impl_plans", + ), + ("${{ result.done }} == true", "push_batch_branch"), + (None, "check_pr_merge_loop"), + ] diff --git a/tests/recipe/test_merge_prs_queue_common.py b/tests/recipe/test_merge_prs_queue_common.py index 00a8ada112..997c20e8a3 100644 --- a/tests/recipe/test_merge_prs_queue_common.py +++ b/tests/recipe/test_merge_prs_queue_common.py @@ -824,13 +824,16 @@ class TestMergePrsPreEnqueueCiGate: def pmp(self, pmp_recipe) -> Recipe: return pmp_recipe - def test_get_first_pr_number_routes_to_get_current_pr_branch(self, pmp) -> None: - """get_first_pr_number.on_success must route to get_current_pr_branch.""" + def test_get_first_pr_number_routes_to_route_by_queue_mode(self, pmp) -> None: + """The first cursor result routes by queue mode unless the queue is done.""" step = pmp.steps["get_first_pr_number"] - assert step.on_success == "get_current_pr_branch", ( - f"get_first_pr_number.on_success must be 'get_current_pr_branch', " - f"got: {step.on_success!r}" - ) + assert step.on_result is not None + done_routes = [c for c in step.on_result.conditions if c.when and "done" in c.when] + assert done_routes + assert done_routes[0].route == "register_clone_success" + fallback = [c for c in step.on_result.conditions if c.when is None] + assert fallback + assert fallback[0].route == "route_by_queue_mode" def test_get_current_pr_branch_exists(self, pmp) -> None: """get_current_pr_branch step must exist.""" diff --git a/tests/recipe/test_merge_prs_queue_pmp.py b/tests/recipe/test_merge_prs_queue_pmp.py index d24d580fc7..d7ff53b0b1 100644 --- a/tests/recipe/test_merge_prs_queue_pmp.py +++ b/tests/recipe/test_merge_prs_queue_pmp.py @@ -46,6 +46,22 @@ def test_merge_prs_route_by_queue_mode_is_route_action(pmp_recipe) -> None: assert step.action == "route" +def test_merge_prs_route_by_queue_mode_targets_queue_and_classic_paths(pmp_recipe) -> None: + """Queue mode goes through the CI gate; classic mode creates a batch branch.""" + step = pmp_recipe.steps["route_by_queue_mode"] + assert step.on_result is not None + queue_route = next( + (condition for condition in step.on_result.conditions if condition.when), None + ) + fallback = next( + (condition for condition in step.on_result.conditions if condition.when is None), None + ) + assert queue_route is not None + assert queue_route.route == "get_current_pr_branch" + assert fallback is not None + assert fallback.route == "create_batch_branch" + + def test_merge_prs_enqueue_current_pr_exists(pmp_recipe) -> None: """enqueue_current_pr step must exist with tool=enqueue_pr.""" assert "enqueue_current_pr" in pmp_recipe.steps @@ -85,10 +101,10 @@ def test_merge_prs_analyze_prs_captures_queue_mode(pmp_recipe) -> None: ) -def test_merge_prs_analyze_prs_routes_to_route_by_queue_mode(pmp_recipe) -> None: - """analyze_prs.on_success must route to route_by_queue_mode.""" +def test_merge_prs_analyze_prs_routes_to_get_first_pr_number(pmp_recipe) -> None: + """analyze_prs.on_success must route to get_first_pr_number.""" step = pmp_recipe.steps["analyze_prs"] - assert step.on_success == "route_by_queue_mode" + assert step.on_success == "get_first_pr_number" # --------------------------------------------------------------------------- @@ -140,10 +156,16 @@ def test_merge_prs_get_first_pr_number_captures_pr_number(pmp_recipe) -> None: assert "current_pr_number" in (step.capture or {}) -def test_merge_prs_get_first_pr_number_routes_to_enqueue(pmp_recipe) -> None: - """get_first_pr_number.on_success must route to get_current_pr_branch (CI gate added).""" +def test_merge_prs_get_first_pr_number_routes_to_route_by_queue_mode(pmp_recipe) -> None: + """The first cursor result routes done runs to success and others by queue mode.""" step = pmp_recipe.steps["get_first_pr_number"] - assert step.on_success == "get_current_pr_branch" + assert step.on_result is not None + done_routes = [c for c in step.on_result.conditions if c.when and "done" in c.when] + assert done_routes + assert done_routes[0].route == "register_clone_success" + fallback = [c for c in step.on_result.conditions if c.when is None] + assert fallback + assert fallback[0].route == "route_by_queue_mode" # --------------------------------------------------------------------------- diff --git a/tests/recipe/test_rules_dataflow_nullable.py b/tests/recipe/test_rules_dataflow_nullable.py index 6c30c3b6ac..493f8d0222 100644 --- a/tests/recipe/test_rules_dataflow_nullable.py +++ b/tests/recipe/test_rules_dataflow_nullable.py @@ -19,7 +19,7 @@ def test_optional_context_ref_to_non_nullable_input_is_error(self) -> None: "advance": { "tool": "run_python", "with": { - "callable": "autoskillit.recipe._cmd_rpc.advance_queue_pr", + "callable": "autoskillit.recipe._cmd_rpc.next_ordered_pr", "args": { "current_pr_number": "${{ context.current_pr }}", "pr_order_file": "/some/path", @@ -43,7 +43,7 @@ def test_non_optional_context_ref_does_not_trigger_rule(self) -> None: "advance": { "tool": "run_python", "with": { - "callable": "autoskillit.recipe._cmd_rpc.advance_queue_pr", + "callable": "autoskillit.recipe._cmd_rpc.next_ordered_pr", "args": { "current_pr_number": "${{ context.current_pr }}", "pr_order_file": "/some/path", From 7643c9eee35387f76b580654b82f74dc7f81bb87 Mon Sep 17 00:00:00 2001 From: Trecek Date: Sat, 24 Oct 2026 08:29:21 -0700 Subject: [PATCH 02/19] fix(recipe): reject unresolved skill input templates --- src/autoskillit/recipe/rules/rules_inputs.py | 60 ++++++ .../recipe/test_rules_skill_input_template.py | 202 ++++++++++++++++++ 2 files changed, 262 insertions(+) create mode 100644 tests/recipe/test_rules_skill_input_template.py diff --git a/src/autoskillit/recipe/rules/rules_inputs.py b/src/autoskillit/recipe/rules/rules_inputs.py index b0e5f94030..60c5424991 100644 --- a/src/autoskillit/recipe/rules/rules_inputs.py +++ b/src/autoskillit/recipe/rules/rules_inputs.py @@ -3,6 +3,7 @@ from __future__ import annotations from collections.abc import Iterator +from typing import cast import regex as re from packaging.version import Version @@ -15,6 +16,7 @@ BindingFailureCode, BoundValue, BoundValueOrigin, + BoundValueState, Severity, get_logger, ) @@ -31,6 +33,64 @@ logger = get_logger(__name__) +_WHOLE_VALUE_PLACEHOLDER_RE = re.compile(r"\{\{?\s*(?!AUTOSKILLIT_)[A-Za-z_]\w*\s*\}\}?") + + +def _unresolved_template_reason(bound: BoundValue, *, per_item: bool) -> str | None: + value = cast(str, bound.declared_value) + scan = value + for name in bound.template_dependencies: + scan = scan.replace("{{" + name + "}}", "") + if "${{" in scan and not bound.context_dependencies and not bound.input_dependencies: + return ( + "the binder treats this unresolved expression as static, so admission accepts only " + "the compiled effective value" + ) + if not per_item and _WHOLE_VALUE_PLACEHOLDER_RE.fullmatch(value.strip()): + return "this is a whole-value placeholder the binder treats as a static literal" + return None + + +@semantic_rule( + name="unresolved-skill-input-template", + description=( + "Recipe skill inputs must be literals or recognised ${{ context.* }} / ${{ inputs.* }} " + "references; unresolved template tokens compile to static values runtime admission " + "cannot accept (recipe validation only)." + ), + severity=Severity.ERROR, +) +def _check_unresolved_skill_input_template(ctx: ValidationContext) -> list[RuleFinding]: + findings: list[RuleFinding] = [] + for step_name, step in ctx.recipe.steps.items(): + if step.tool not in SKILL_TOOLS: + continue + invocation = ctx.binding_projection.for_step(step_name) + if invocation is None or invocation.skill_name is None: + continue + per_item = "dispatch_items" in (step.declared_with_args or {}) + for bound in invocation.skill_inputs: + if bound.state is not BoundValueState.PRESENT or not isinstance( + bound.declared_value, str + ): + continue + reason = _unresolved_template_reason(bound, per_item=per_item) + if reason is not None: + findings.append( + make_finding( + rule_name="unresolved-skill-input-template", + step_name=step_name, + message=( + f"Skill input '{bound.name}' declares {bound.declared_value!r}: " + f"{reason}. " + "Bind ${{ context. }} from a recipe-level producer step, " + "or ${{ inputs. }}." + ), + ) + ) + return findings + + @semantic_rule( name="outdated-recipe-version", description="Recipe's autoskillit_version is below the installed package version", diff --git a/tests/recipe/test_rules_skill_input_template.py b/tests/recipe/test_rules_skill_input_template.py new file mode 100644 index 0000000000..8669c04177 --- /dev/null +++ b/tests/recipe/test_rules_skill_input_template.py @@ -0,0 +1,202 @@ +"""Tests for unresolved templates in run_skill inputs. + +Composite values such as ``PR-{pr_number}`` and exotic forms such as ``{0}``, +``{x!r}``, ``${x}``, and ```` remain outside the rule's scope. The +``dispatch_items`` exemption preserves inline arguments for per-item fan-out; +revisit that exemption with #5307. +""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from autoskillit.core.types import Severity +from autoskillit.recipe.registry import ( + RuleFinding, + compute_recipe_validity, + run_semantic_rules, +) +from tests.recipe.conftest import _make_workflow + +pytestmark = [pytest.mark.layer("recipe"), pytest.mark.small] + +_RULE = "unresolved-skill-input-template" + + +def _skill_input_template_findings( + with_args: dict[str, Any], *, step_name: str = "step" +) -> list[RuleFinding]: + recipe = _make_workflow( + { + step_name: { + "tool": "run_skill", + "with": with_args, + "on_success": "done", + }, + "done": {"action": "stop", "message": "Done"}, + } + ) + return [finding for finding in run_semantic_rules(recipe) if finding.rule == _RULE] + + +def _assert_error_names_input(findings: list[RuleFinding], input_name: str) -> None: + assert len(findings) == 1 + assert findings[0].severity == Severity.ERROR + assert input_name in findings[0].message + + +@pytest.mark.parametrize( + "value", + [ + pytest.param("{pr_number}", id="whole-placeholder"), + pytest.param(" {pr_number} ", id="padded-placeholder"), + pytest.param("{{ pr_number }}", id="double-braced-placeholder"), + pytest.param("${{ result.pr_number }}", id="unknown-result-namespace"), + pytest.param("${{ context.pr_number", id="unterminated-expression"), + pytest.param("${{ context.pr_number | trim }}", id="filter-expression"), + pytest.param( + "${{AUTOSKILLIT_TEMP}}/${{ result.x }}", + id="macro-does-not-hide-unresolved-expression", + ), + ], +) +def test_unresolved_structured_skill_input_templates_are_errors(value: str) -> None: + findings = _skill_input_template_findings( + { + "skill_command": "/autoskillit:merge-pr", + "skill_inputs": { + "pr_number": value, + "complexity": "${{ context.c }}", + }, + } + ) + + _assert_error_names_input(findings, "pr_number") + + +@pytest.mark.parametrize( + "skill_command", + [ + pytest.param("/autoskillit:merge-pr {pr_number} simple", id="named-placeholder"), + pytest.param("/autoskillit:merge-pr ${{ result.x }} simple", id="unresolved-expression"), + ], +) +def test_unresolved_inline_skill_arguments_are_errors(skill_command: str) -> None: + findings = _skill_input_template_findings({"skill_command": skill_command}) + + _assert_error_names_input(findings, "pr_number") + + +@pytest.mark.parametrize( + ("skill_command", "input_name", "value"), + [ + pytest.param( + "/autoskillit:merge-pr", + "pr_number", + "${{ context.pr_number }}", + id="valid-context-reference", + ), + pytest.param( + "/autoskillit:merge-pr", + "pr_number", + "iter_${{ context.n }}", + id="expression-with-literal-prefix", + ), + pytest.param( + "/autoskillit:merge-pr", + "pr_number", + "{{AUTOSKILLIT_TEMP}}/x", + id="path-macro", + ), + pytest.param( + "/autoskillit:merge-pr", + "pr_number", + "{{AUTOSKILLIT_TEMP}}", + id="whole-value-brace-macro", + ), + pytest.param( + "/autoskillit:merge-pr", + "pr_number", + "${{AUTOSKILLIT_TEMP}}", + id="whole-value-expression-macro", + ), + pytest.param("/autoskillit:merge-pr", "pr_number", "{}", id="empty-braces"), + pytest.param("/autoskillit:merge-pr", "pr_number", "42", id="string-literal"), + pytest.param("/autoskillit:merge-pr", "pr_number", 42, id="integer-literal"), + pytest.param( + "/autoskillit:investigate", + "topic", + "${{ '--depth deep ' if inputs.depth == 'deep' else '' }}" + "${{ inputs.task }} ${{ inputs.issue_url }}", + id="remediation-investigate-topic", + ), + ], +) +def test_resolved_or_accepted_skill_input_values_are_clean( + skill_command: str, input_name: str, value: Any +) -> None: + skill_inputs = {input_name: value} + if input_name == "pr_number": + skill_inputs["complexity"] = "${{ context.c }}" + findings = _skill_input_template_findings( + { + "skill_command": skill_command, + "skill_inputs": skill_inputs, + }, + step_name="investigate" if input_name == "topic" else "step", + ) + + assert findings == [] + + +def test_dynamic_skill_with_context_path_placeholder_is_clean() -> None: + findings = _skill_input_template_findings( + { + "skill_command": "/autoskillit:arch-lens-{slug}", + "skill_inputs": {"context_path": "{context_path}"}, + } + ) + + assert findings == [] + + +def test_simple_dispatch_items_allows_inline_per_item_skill_arguments() -> None: + findings = _skill_input_template_findings( + { + "skill_command": "/autoskillit:merge-pr {pr_number} simple", + "dispatch_items": "${{ context.items }}", + } + ) + + assert findings == [] + + +def test_dispatch_items_does_not_exempt_unresolved_expression() -> None: + findings = _skill_input_template_findings( + { + "skill_command": "/autoskillit:merge-pr ${{ result.x }} simple", + "dispatch_items": "${{ context.items }}", + } + ) + + _assert_error_names_input(findings, "pr_number") + + +def test_merge_pr_structured_placeholder_reproduction_is_invalid() -> None: + findings = _skill_input_template_findings( + { + "skill_command": "/autoskillit:merge-pr", + "skill_inputs": { + "complexity": "{complexity}", + "pr_number": "{pr_number}", + }, + } + ) + + assert len(findings) == 2 + assert all(finding.severity == Severity.ERROR for finding in findings) + assert any("complexity" in finding.message for finding in findings) + assert any("pr_number" in finding.message for finding in findings) + assert compute_recipe_validity([], findings, []) is False From 3b05af55e06d96bf835a1832a2b162191cb7393a Mon Sep 17 00:00:00 2001 From: Trecek Date: Sat, 24 Oct 2026 10:33:07 -0700 Subject: [PATCH 03/19] fix(review): describe the template rule's checked scope --- src/autoskillit/recipe/rules/rules_inputs.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/autoskillit/recipe/rules/rules_inputs.py b/src/autoskillit/recipe/rules/rules_inputs.py index 60c5424991..9309f90c36 100644 --- a/src/autoskillit/recipe/rules/rules_inputs.py +++ b/src/autoskillit/recipe/rules/rules_inputs.py @@ -54,9 +54,8 @@ def _unresolved_template_reason(bound: BoundValue, *, per_item: bool) -> str | N @semantic_rule( name="unresolved-skill-input-template", description=( - "Recipe skill inputs must be literals or recognised ${{ context.* }} / ${{ inputs.* }} " - "references; unresolved template tokens compile to static values runtime admission " - "cannot accept (recipe validation only)." + "Reject whole-value skill input placeholders and unresolved ${{ ... }} expressions " + "that compile to static values runtime admission cannot accept (recipe validation only)." ), severity=Severity.ERROR, ) From c3ed0f8c3f3c054860d8f2c6b5781b714c5410ee Mon Sep 17 00:00:00 2001 From: Trecek Date: Sat, 24 Oct 2026 10:35:49 -0700 Subject: [PATCH 04/19] fix(review): reject result expressions mixed with skill input references --- src/autoskillit/recipe/rules/rules_inputs.py | 6 +++++- src/autoskillit/recipes/diagrams/merge-prs.md | 2 +- tests/recipe/test_rules_skill_input_template.py | 8 ++++++++ 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/autoskillit/recipe/rules/rules_inputs.py b/src/autoskillit/recipe/rules/rules_inputs.py index 9309f90c36..0c62b5c461 100644 --- a/src/autoskillit/recipe/rules/rules_inputs.py +++ b/src/autoskillit/recipe/rules/rules_inputs.py @@ -22,6 +22,7 @@ ) from autoskillit.recipe._analysis import ValidationContext, bfs_reachable from autoskillit.recipe.contracts import ( + RESULT_CAPTURE_RE, SkillInput, get_skill_contract, load_bundled_manifest, @@ -41,7 +42,10 @@ def _unresolved_template_reason(bound: BoundValue, *, per_item: bool) -> str | N scan = value for name in bound.template_dependencies: scan = scan.replace("{{" + name + "}}", "") - if "${{" in scan and not bound.context_dependencies and not bound.input_dependencies: + if "${{" in scan and ( + RESULT_CAPTURE_RE.search(scan) + or (not bound.context_dependencies and not bound.input_dependencies) + ): return ( "the binder treats this unresolved expression as static, so admission accepts only " "the compiled effective value" diff --git a/src/autoskillit/recipes/diagrams/merge-prs.md b/src/autoskillit/recipes/diagrams/merge-prs.md index 8d14b6d171..6f49cb8826 100644 --- a/src/autoskillit/recipes/diagrams/merge-prs.md +++ b/src/autoskillit/recipes/diagrams/merge-prs.md @@ -1,4 +1,4 @@ - + ## merge-prs diff --git a/tests/recipe/test_rules_skill_input_template.py b/tests/recipe/test_rules_skill_input_template.py index 8669c04177..e88e72b894 100644 --- a/tests/recipe/test_rules_skill_input_template.py +++ b/tests/recipe/test_rules_skill_input_template.py @@ -54,6 +54,14 @@ def _assert_error_names_input(findings: list[RuleFinding], input_name: str) -> N pytest.param(" {pr_number} ", id="padded-placeholder"), pytest.param("{{ pr_number }}", id="double-braced-placeholder"), pytest.param("${{ result.pr_number }}", id="unknown-result-namespace"), + pytest.param( + "${{ context.pr_number }}/${{ result.x }}", + id="context-does-not-hide-result-expression", + ), + pytest.param( + "${{ inputs.pr_number }}/${{ result.x }}", + id="input-does-not-hide-result-expression", + ), pytest.param("${{ context.pr_number", id="unterminated-expression"), pytest.param("${{ context.pr_number | trim }}", id="filter-expression"), pytest.param( From c470e8ff7728da13eac2e07e54e03b52da2d17dd Mon Sep 17 00:00:00 2001 From: Trecek Date: Sat, 24 Oct 2026 10:38:07 -0700 Subject: [PATCH 05/19] refactor(review): share PR advancement across merge modes --- src/autoskillit/recipes/merge-prs.json | 41 +++++-------------- src/autoskillit/recipes/merge-prs.yaml | 35 +++++----------- tests/recipe/test_merge_prs_pr_cursor.py | 8 ++-- tests/recipe/test_merge_prs_queue_pmp.py | 51 ++++++++++++------------ 4 files changed, 51 insertions(+), 84 deletions(-) diff --git a/src/autoskillit/recipes/merge-prs.json b/src/autoskillit/recipes/merge-prs.json index 1915fefdd8..6e66c6f8b6 100644 --- a/src/autoskillit/recipes/merge-prs.json +++ b/src/autoskillit/recipes/merge-prs.json @@ -83,13 +83,13 @@ "SEQUENTIAL LOOP: Process one PR at a time through the full merge cycle before advancing to the next PR. Never batch-assess all PRs before starting merges.", "SEQUENTIAL EXECUTION: complete full cycle (verify → create_conflict_worktree → implement → test → push_worktree_branch → create_conflict_pr → wait_for_conflict_ci → merge_conflict_pr) per plan part before advancing to the next part or PR.", "INTEGRATION BRANCH: Two distinct branches exist. inputs.base_branch is the target branch that PRs point to (e.g. main, develop). context.batch_branch is the per-run batch branch (e.g. pr-batch/pr-merge-{ts}) created from base_branch for this pipeline run. All PR merges and worktree merges target context.batch_branch. The final review PR opens from context.batch_branch into inputs.base_branch.", - "PR QUEUE: Only get_first_pr_number, advance_queue_pr and advance_merge_pr write context.current_pr_number and context.current_pr_complexity. Never set or advance these values yourself. The cursor reads the immutable analyze_prs order file.", + "PR QUEUE: Only get_first_pr_number and advance_merge_pr write context.current_pr_number and context.current_pr_complexity. Never set or advance these values yourself. The cursor reads the immutable analyze_prs order file.", "COMPLEX PR PATH: When merge_pr returns needs_plan=true, context.task is set to the conflict_report_path. Pass context.task to make-plan. The plan+implement cycle creates a worktree from the integration branch; the worktree branch is then pushed to origin and merged into the integration batch branch via GitHub PR (push_worktree_branch → create_conflict_pr → wait_for_conflict_ci → merge_conflict_pr).", "SOURCE ISOLATION: After clone_repo returns, the source_dir is strictly off-limits. Never run any command in source_dir — no git checkout, git fetch, git reset, git pull, run_cmd, run_skill, or any other operation. All work — skill invocations, git operations, file reads — happens exclusively in the clone (work_dir). source_dir is used ONLY to read the remote URL inside push_to_remote.", "GITHUB API MERGE: All PR merges into the integration branch go through GitHub's merge interface (gh pr merge --squash). This enforces the branch ruleset required status checks. Never use merge_worktree or local git merge to merge into the integration batch branch.", "PUSH DISCIPLINE: push_worktree_branch (inside the complex PR cycle), publish_batch_branch / push_batch_branch, force_push_and_wait_mergeability (authorized for conflict-resolution rebases), and push_rebased_next_pr (authorized for proactive pre-enqueue rebase) are the only authorized push steps. Never add ad-hoc run_cmd git push calls elsewhere in the loop.", "QUEUE MODE: When context.queue_mode == true, PRs merge directly into base_branch via the merge queue. The batch branch (context.batch_branch) is the same as base_branch. Never invoke create_batch_branch, publish_batch_branch, merge_pr, or push_batch_branch in queue mode.", - "QUEUE LOOP: get_first_pr_number initializes the PR number and complexity before selecting either mode. In queue mode, advance_queue_pr selects the successor by file position and returns done after the last PR without changing the artifact.", + "QUEUE LOOP: get_first_pr_number initializes the PR number and complexity before selecting either mode. In queue mode, advance_merge_pr selects the successor by file position and returns done after the last PR without changing the artifact.", "CONFLICT REPORT PATHS: context.all_conflict_report_paths accumulates conflict_report_path values from resolve_ejected_conflicts and resolve_integration_conflicts via capture_list. Pass it as the 5th argument to open_integration_pr and 4th argument to audit_impl. It is empty string when no conflict resolution occurred — downstream skills treat empty string as absent." ], "steps": { @@ -331,7 +331,7 @@ }, "on_success": "wait_queue_pr", "on_failure": "verify_queue_enrollment", - "note": "Queue mode only. Submits a single PR to the merge queue via the unified enqueue_pr tool. Called once per PR in the sequential enqueue loop: get_first_pr_number → route_by_queue_mode → get_current_pr_branch → wait_ci_pre_enqueue → enqueue_current_pr → wait_queue_pr → (merged) → advance_queue_pr → get_current_pr_branch → wait_ci_pre_enqueue → enqueue_current_pr → ...\n" + "note": "Queue mode only. Submits a single PR to the merge queue via the unified enqueue_pr tool. Called once per PR in the sequential enqueue loop: get_first_pr_number → route_by_queue_mode → get_current_pr_branch → wait_ci_pre_enqueue → enqueue_current_pr → wait_queue_pr → (merged) → advance_merge_pr → get_current_pr_branch → wait_ci_pre_enqueue → enqueue_current_pr → ...\n" }, "wait_queue_pr": { "tool": "wait_for_merge_queue", @@ -350,7 +350,7 @@ "on_result": [ { "when": "${{ result.pr_state }} == merged", - "route": "advance_queue_pr" + "route": "advance_merge_pr" }, { "when": "${{ result.pr_state }} == ejected_ci_failure", @@ -621,7 +621,7 @@ "on_result": [ { "when": "${{ result.pr_state }} == merged", - "route": "advance_queue_pr" + "route": "advance_merge_pr" }, { "when": "${{ result.pr_state }} == ejected_ci_failure", @@ -730,7 +730,7 @@ "on_result": [ { "when": "${{ result.pr_state }} == merged", - "route": "advance_queue_pr" + "route": "advance_merge_pr" }, { "when": "${{ result.pr_state }} == ejected_ci_failure", @@ -779,29 +779,6 @@ "on_failure": "verify_queue_enrollment", "note": "Re-submits the fixed PR to the merge queue after conflict resolution. Routes back to wait_queue_pr to continue monitoring.\n" }, - "advance_queue_pr": { - "tool": "run_python", - "with": { - "callable": "autoskillit.recipe._cmd_rpc.next_ordered_pr", - "current_pr_number": "${{ context.current_pr_number }}", - "pr_order_file": "${{ context.pr_order_file }}" - }, - "capture": { - "current_pr_number": "${{ result.pr_number }}", - "current_pr_complexity": "${{ result.complexity }}" - }, - "on_result": [ - { - "when": "${{ result.done }} == true", - "route": "collect_and_check_impl_plans" - }, - { - "route": "get_next_pr_branch" - } - ], - "on_failure": "register_clone_failure", - "note": "Advances by file position and captures the next PR number and complexity. At the end, retains the last PR and returns done. Continues through proactive rebase or collects implementation plans when done." - }, "get_next_pr_branch": { "tool": "run_cmd", "with": { @@ -1476,12 +1453,16 @@ "when": "${{ result.done }} == true", "route": "push_batch_branch" }, + { + "when": "${{ context.queue_mode }} == true", + "route": "get_next_pr_branch" + }, { "route": "check_pr_merge_loop" } ], "on_failure": "register_clone_failure", - "note": "Classic and post-remediation advance, keyed on current_pr_number once per finished PR. Queue-mode audit remediation re-enters at the last PR and exits to collect_and_check_impl_plans through the first done arm." + "note": "Advances by file position once per finished PR in either mode. Queue mode continues through proactive rebase or collects implementation plans when done; classic mode continues its merge loop or pushes the batch branch. Queue-mode audit remediation re-enters at the last PR and collects implementation plans without changing the artifact." }, "select_next_plan_part": { "tool": "run_cmd", diff --git a/src/autoskillit/recipes/merge-prs.yaml b/src/autoskillit/recipes/merge-prs.yaml index 06923673f7..9ae82a4c82 100644 --- a/src/autoskillit/recipes/merge-prs.yaml +++ b/src/autoskillit/recipes/merge-prs.yaml @@ -76,7 +76,7 @@ kitchen_rules: develop). context.batch_branch is the per-run batch branch (e.g. pr-batch/pr-merge-{ts}) created from base_branch for this pipeline run. All PR merges and worktree merges target context.batch_branch. The final review PR opens from context.batch_branch into inputs.base_branch.' -- 'PR QUEUE: Only get_first_pr_number, advance_queue_pr and advance_merge_pr write context.current_pr_number and +- 'PR QUEUE: Only get_first_pr_number and advance_merge_pr write context.current_pr_number and context.current_pr_complexity. Never set or advance these values yourself. The cursor reads the immutable analyze_prs order file.' - 'COMPLEX PR PATH: When merge_pr returns needs_plan=true, context.task is set to the conflict_report_path. Pass context.task to make-plan. The plan+implement cycle creates a worktree from the integration branch; the worktree branch is then pushed @@ -96,7 +96,7 @@ kitchen_rules: (context.batch_branch) is the same as base_branch. Never invoke create_batch_branch, publish_batch_branch, merge_pr, or push_batch_branch in queue mode.' - 'QUEUE LOOP: get_first_pr_number initializes the PR number and complexity before selecting either mode. In queue mode, - advance_queue_pr selects the successor by file position and returns done after the last PR without changing the artifact.' + advance_merge_pr selects the successor by file position and returns done after the last PR without changing the artifact.' - 'CONFLICT REPORT PATHS: context.all_conflict_report_paths accumulates conflict_report_path values from resolve_ejected_conflicts and resolve_integration_conflicts via capture_list. Pass it as the 5th argument to open_integration_pr and 4th argument to audit_impl. It is empty string when no conflict resolution occurred — downstream skills treat empty string as absent.' @@ -334,7 +334,7 @@ steps: on_failure: verify_queue_enrollment note: 'Queue mode only. Submits a single PR to the merge queue via the unified enqueue_pr tool. Called once per PR in the sequential enqueue loop: get_first_pr_number → route_by_queue_mode → get_current_pr_branch → wait_ci_pre_enqueue → enqueue_current_pr - → wait_queue_pr → (merged) → advance_queue_pr → get_current_pr_branch → wait_ci_pre_enqueue → enqueue_current_pr → ... + → wait_queue_pr → (merged) → advance_merge_pr → get_current_pr_branch → wait_ci_pre_enqueue → enqueue_current_pr → ... ' wait_queue_pr: @@ -351,7 +351,7 @@ steps: queue_pr_state: ${{ result.pr_state }} on_result: - when: ${{ result.pr_state }} == merged - route: advance_queue_pr + route: advance_merge_pr - when: ${{ result.pr_state }} == ejected_ci_failure route: diagnose_queue_ci - when: ${{ result.pr_state }} == dropped_merge_group_ci @@ -555,7 +555,7 @@ steps: max_merge_group_drops: '1' on_result: - when: ${{ result.pr_state }} == merged - route: advance_queue_pr + route: advance_merge_pr - when: ${{ result.pr_state }} == ejected_ci_failure route: register_clone_failure - when: ${{ result.pr_state }} == dropped_merge_group_ci @@ -631,7 +631,7 @@ steps: max_merge_group_drops: 1 on_result: - when: ${{ result.pr_state }} == merged - route: advance_queue_pr + route: advance_merge_pr - when: ${{ result.pr_state }} == ejected_ci_failure route: diagnose_queue_ci - when: ${{ result.pr_state }} == not_enrolled @@ -665,22 +665,6 @@ steps: monitoring. ' - advance_queue_pr: - tool: run_python - with: - callable: autoskillit.recipe._cmd_rpc.next_ordered_pr - current_pr_number: ${{ context.current_pr_number }} - pr_order_file: ${{ context.pr_order_file }} - capture: - current_pr_number: ${{ result.pr_number }} - current_pr_complexity: ${{ result.complexity }} - on_result: - - when: ${{ result.done }} == true - route: collect_and_check_impl_plans - - route: get_next_pr_branch - on_failure: register_clone_failure - note: 'Advances by file position and captures the next PR number and complexity. At the end, retains the last PR and - returns done. Continues through proactive rebase or collects implementation plans when done.' get_next_pr_branch: tool: run_cmd with: @@ -1274,10 +1258,13 @@ steps: route: collect_and_check_impl_plans - when: ${{ result.done }} == true route: push_batch_branch + - when: ${{ context.queue_mode }} == true + route: get_next_pr_branch - route: check_pr_merge_loop on_failure: register_clone_failure - note: 'Classic and post-remediation advance, keyed on current_pr_number once per finished PR. Queue-mode audit remediation - re-enters at the last PR and exits to collect_and_check_impl_plans through the first done arm.' + note: 'Advances by file position once per finished PR in either mode. Queue mode continues through proactive rebase + or collects implementation plans when done; classic mode continues its merge loop or pushes the batch branch. + Queue-mode audit remediation re-enters at the last PR and collects implementation plans without changing the artifact.' select_next_plan_part: tool: run_cmd with: diff --git a/tests/recipe/test_merge_prs_pr_cursor.py b/tests/recipe/test_merge_prs_pr_cursor.py index 9c82a2e02a..52ac244755 100644 --- a/tests/recipe/test_merge_prs_pr_cursor.py +++ b/tests/recipe/test_merge_prs_pr_cursor.py @@ -33,13 +33,13 @@ def test_cursor_steps_have_defined_inputs_and_single_writer(recipe) -> None: cursor_fields = {"current_pr_number", "current_pr_complexity"} cursor_steps = { "get_first_pr_number": "autoskillit.recipe._cmd_rpc.first_ordered_pr", - "advance_queue_pr": "autoskillit.recipe._cmd_rpc.next_ordered_pr", "advance_merge_pr": "autoskillit.recipe._cmd_rpc.next_ordered_pr", } must_defined = make_validation_context(recipe).must_defined_context - for step_name in ("advance_queue_pr", "advance_merge_pr"): - assert {"current_pr_number", "pr_order_file"} <= must_defined.get(step_name, frozenset()) + assert {"current_pr_number", "pr_order_file"} <= must_defined.get( + "advance_merge_pr", frozenset() + ) writers = { name @@ -71,7 +71,6 @@ def test_pr_order_file_has_declared_recipe_consumers(recipe) -> None: } assert consumers == { "get_first_pr_number", - "advance_queue_pr", "advance_merge_pr", "open_integration_pr", } @@ -111,5 +110,6 @@ def test_cursor_routes_preserve_plan_iteration_and_pr_advancement(recipe) -> Non "collect_and_check_impl_plans", ), ("${{ result.done }} == true", "push_batch_branch"), + ("${{ context.queue_mode }} == true", "get_next_pr_branch"), (None, "check_pr_merge_loop"), ] diff --git a/tests/recipe/test_merge_prs_queue_pmp.py b/tests/recipe/test_merge_prs_queue_pmp.py index d7ff53b0b1..0b263e8d65 100644 --- a/tests/recipe/test_merge_prs_queue_pmp.py +++ b/tests/recipe/test_merge_prs_queue_pmp.py @@ -81,10 +81,10 @@ def test_merge_prs_reenter_queue_exists(pmp_recipe) -> None: assert "reenter_queue" in pmp_recipe.steps -def test_merge_prs_advance_queue_pr_exists(pmp_recipe) -> None: - """advance_queue_pr step must exist with tool=run_python.""" - assert "advance_queue_pr" in pmp_recipe.steps - step = pmp_recipe.steps["advance_queue_pr"] +def test_merge_prs_advance_merge_pr_exists(pmp_recipe) -> None: + """advance_merge_pr step must exist with tool=run_python.""" + assert "advance_merge_pr" in pmp_recipe.steps + step = pmp_recipe.steps["advance_merge_pr"] assert step.tool == "run_python" @@ -232,16 +232,15 @@ def test_merge_prs_checkout_ejected_pr_removed(pmp_recipe) -> None: # --------------------------------------------------------------------------- -def test_merge_prs_advance_queue_pr_fallthrough_routes_to_get_next_pr_branch( +def test_merge_prs_advance_merge_pr_queue_route_to_get_next_pr_branch( pmp_recipe, ) -> None: - step = pmp_recipe.steps["advance_queue_pr"] + step = pmp_recipe.steps["advance_merge_pr"] assert step.on_result is not None - fallback_route = next( - (c.route for c in step.on_result.conditions if c.when is None), - None, - ) - assert fallback_route == "get_next_pr_branch" + queue_routes = [ + c.route for c in step.on_result.conditions if c.when == "${{ context.queue_mode }} == true" + ] + assert queue_routes == ["get_next_pr_branch"] def test_merge_prs_get_next_pr_branch_exists(pmp_recipe) -> None: @@ -397,36 +396,36 @@ def test_merge_prs_ci_watch_routes_to_reenter(pmp_recipe) -> None: # --------------------------------------------------------------------------- -def test_merge_prs_advance_queue_pr_is_run_python(pmp_recipe) -> None: - """advance_queue_pr step must exist with tool=run_python.""" - assert "advance_queue_pr" in pmp_recipe.steps - step = pmp_recipe.steps["advance_queue_pr"] +def test_merge_prs_advance_merge_pr_is_run_python(pmp_recipe) -> None: + """advance_merge_pr step must exist with tool=run_python.""" + assert "advance_merge_pr" in pmp_recipe.steps + step = pmp_recipe.steps["advance_merge_pr"] assert step.tool == "run_python" def test_merge_prs_next_queue_pr_or_done_removed(pmp_recipe) -> None: - """next_queue_pr_or_done step must be removed (replaced by advance_queue_pr).""" + """next_queue_pr_or_done step must be removed (replaced by advance_merge_pr).""" assert "next_queue_pr_or_done" not in pmp_recipe.steps -def test_merge_prs_advance_queue_pr_callable_references_pr_order(pmp_recipe) -> None: - """advance_queue_pr callable args must reference pr_order_file and current_pr_number.""" - step = pmp_recipe.steps["advance_queue_pr"] +def test_merge_prs_advance_merge_pr_callable_references_pr_order(pmp_recipe) -> None: + """advance_merge_pr callable args must reference pr_order_file and current_pr_number.""" + step = pmp_recipe.steps["advance_merge_pr"] args = step.with_args assert "pr_order_file" in args assert "current_pr_number" in args -def test_merge_prs_advance_queue_pr_captures_pr_number(pmp_recipe) -> None: - """advance_queue_pr must have a capture block for current_pr_number.""" - step = pmp_recipe.steps["advance_queue_pr"] +def test_merge_prs_advance_merge_pr_captures_pr_number(pmp_recipe) -> None: + """advance_merge_pr must have a capture block for current_pr_number.""" + step = pmp_recipe.steps["advance_merge_pr"] capture = step.capture or {} assert "current_pr_number" in capture -def test_merge_prs_advance_queue_pr_routing(pmp_recipe) -> None: - """advance_queue_pr routes to get_next_pr_branch (default) or collect_and_check_impl_plans.""" - step = pmp_recipe.steps["advance_queue_pr"] +def test_merge_prs_advance_merge_pr_routing(pmp_recipe) -> None: + """advance_merge_pr handles queue completion and the classic fallback.""" + step = pmp_recipe.steps["advance_merge_pr"] assert step.on_result is not None conditions = step.on_result.conditions done_routes = [c for c in conditions if c.when and "done" in c.when] @@ -434,7 +433,7 @@ def test_merge_prs_advance_queue_pr_routing(pmp_recipe) -> None: assert done_routes[0].route == "collect_and_check_impl_plans" default_routes = [c for c in conditions if c.when is None] assert default_routes, "must have a default route" - assert default_routes[0].route == "get_next_pr_branch" + assert default_routes[0].route == "check_pr_merge_loop" # --------------------------------------------------------------------------- From d8b4d885c1180d923a922213c2deb51a42c8356e Mon Sep 17 00:00:00 2001 From: Trecek Date: Sat, 24 Oct 2026 10:39:03 -0700 Subject: [PATCH 06/19] test(review): keep one exact first-PR routing assertion --- tests/recipe/test_merge_prs_queue_common.py | 10 ++++------ tests/recipe/test_merge_prs_queue_pmp.py | 12 ------------ 2 files changed, 4 insertions(+), 18 deletions(-) diff --git a/tests/recipe/test_merge_prs_queue_common.py b/tests/recipe/test_merge_prs_queue_common.py index 997c20e8a3..4432a3d18d 100644 --- a/tests/recipe/test_merge_prs_queue_common.py +++ b/tests/recipe/test_merge_prs_queue_common.py @@ -828,12 +828,10 @@ def test_get_first_pr_number_routes_to_route_by_queue_mode(self, pmp) -> None: """The first cursor result routes by queue mode unless the queue is done.""" step = pmp.steps["get_first_pr_number"] assert step.on_result is not None - done_routes = [c for c in step.on_result.conditions if c.when and "done" in c.when] - assert done_routes - assert done_routes[0].route == "register_clone_success" - fallback = [c for c in step.on_result.conditions if c.when is None] - assert fallback - assert fallback[0].route == "route_by_queue_mode" + assert [(c.when, c.route) for c in step.on_result.conditions] == [ + ("${{ result.done }} == true", "register_clone_success"), + (None, "route_by_queue_mode"), + ] def test_get_current_pr_branch_exists(self, pmp) -> None: """get_current_pr_branch step must exist.""" diff --git a/tests/recipe/test_merge_prs_queue_pmp.py b/tests/recipe/test_merge_prs_queue_pmp.py index 0b263e8d65..d6aee7ce0d 100644 --- a/tests/recipe/test_merge_prs_queue_pmp.py +++ b/tests/recipe/test_merge_prs_queue_pmp.py @@ -156,18 +156,6 @@ def test_merge_prs_get_first_pr_number_captures_pr_number(pmp_recipe) -> None: assert "current_pr_number" in (step.capture or {}) -def test_merge_prs_get_first_pr_number_routes_to_route_by_queue_mode(pmp_recipe) -> None: - """The first cursor result routes done runs to success and others by queue mode.""" - step = pmp_recipe.steps["get_first_pr_number"] - assert step.on_result is not None - done_routes = [c for c in step.on_result.conditions if c.when and "done" in c.when] - assert done_routes - assert done_routes[0].route == "register_clone_success" - fallback = [c for c in step.on_result.conditions if c.when is None] - assert fallback - assert fallback[0].route == "route_by_queue_mode" - - # --------------------------------------------------------------------------- # merge-prs.yaml — cheap rebase pre-check (Test 1C) # --------------------------------------------------------------------------- From 0452543c79c77da151e0396facfa616914fd5c3a Mon Sep 17 00:00:00 2001 From: Trecek Date: Sat, 24 Oct 2026 10:40:07 -0700 Subject: [PATCH 07/19] fix(review): preserve PR order paths in UTF-8 read errors --- src/autoskillit/recipe/cmd_rpc/_cmd_rpc_merge.py | 4 ++-- tests/recipe/test_cmd_rpc_merge.py | 6 ++++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/autoskillit/recipe/cmd_rpc/_cmd_rpc_merge.py b/src/autoskillit/recipe/cmd_rpc/_cmd_rpc_merge.py index 9fcc1d67e7..385bff36d3 100644 --- a/src/autoskillit/recipe/cmd_rpc/_cmd_rpc_merge.py +++ b/src/autoskillit/recipe/cmd_rpc/_cmd_rpc_merge.py @@ -317,9 +317,9 @@ def _load_pr_order(pr_order_file: str) -> list[tuple[str, str]]: if not Path(pr_order_file).is_absolute(): raise ValueError(f"pr_order_file must be absolute: {pr_order_file!r}") try: - with open(pr_order_file) as f: + with open(pr_order_file, encoding="utf-8") as f: order = json.load(f) - except (OSError, json.JSONDecodeError) as exc: + except (OSError, UnicodeError, json.JSONDecodeError) as exc: raise RuntimeError(f"{pr_order_file}: {exc}") from exc if not isinstance(order, dict) or not isinstance(order.get("prs"), list): raise ValueError(f"{pr_order_file}: expected an object with a prs list") diff --git a/tests/recipe/test_cmd_rpc_merge.py b/tests/recipe/test_cmd_rpc_merge.py index c083e4825b..1d70205622 100644 --- a/tests/recipe/test_cmd_rpc_merge.py +++ b/tests/recipe/test_cmd_rpc_merge.py @@ -383,10 +383,12 @@ def test_first_ordered_pr_reports_invalid_order_document(tmp_path, malformation) assert "prs[0]" in message -@pytest.mark.parametrize("file_contents", [None, "{"]) +@pytest.mark.parametrize("file_contents", [None, "{", b"\xff"]) def test_first_ordered_pr_wraps_file_read_errors_as_runtime_error(tmp_path, file_contents): path = tmp_path / "pr-order.json" - if file_contents is not None: + if isinstance(file_contents, bytes): + path.write_bytes(file_contents) + elif file_contents is not None: path.write_text(file_contents, encoding="utf-8") with pytest.raises(RuntimeError) as exc_info: From 46d231aee56d394f9c1cf57fb216aed596f20b75 Mon Sep 17 00:00:00 2001 From: Trecek Date: Sat, 24 Oct 2026 10:41:25 -0700 Subject: [PATCH 08/19] refactor(review): name cursor values at their use sites --- src/autoskillit/recipe/cmd_rpc/_cmd_rpc_merge.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/autoskillit/recipe/cmd_rpc/_cmd_rpc_merge.py b/src/autoskillit/recipe/cmd_rpc/_cmd_rpc_merge.py index 385bff36d3..1a4d99bd9b 100644 --- a/src/autoskillit/recipe/cmd_rpc/_cmd_rpc_merge.py +++ b/src/autoskillit/recipe/cmd_rpc/_cmd_rpc_merge.py @@ -342,7 +342,8 @@ def _load_pr_order(pr_order_file: str) -> list[tuple[str, str]]: def _cursor_result(entry: tuple[str, str], *, done: bool) -> dict[str, str]: - return {"pr_number": entry[0], "complexity": entry[1], "done": "true" if done else "false"} + pr_number, complexity = entry + return {"pr_number": pr_number, "complexity": complexity, "done": "true" if done else "false"} def first_ordered_pr(pr_order_file: str) -> dict[str, str]: @@ -355,7 +356,8 @@ def next_ordered_pr(pr_order_file: str, current_pr_number: str) -> dict[str, str """Advance by file order, retaining the last PR when the order is exhausted.""" entries = _load_pr_order(pr_order_file) for index, entry in enumerate(entries): - if entry[0] == current_pr_number: + pr_number, _ = entry + if pr_number == current_pr_number: done = index + 1 == len(entries) return _cursor_result(entry if done else entries[index + 1], done=done) raise ValueError(f"{pr_order_file}: current_pr_number {current_pr_number!r} is not in prs") From e9b51ebbf8f85bdbb744a79123ef777a73f06eb1 Mon Sep 17 00:00:00 2001 From: Trecek Date: Sat, 24 Oct 2026 10:42:40 -0700 Subject: [PATCH 09/19] style(review): keep cursor exports alphabetically ordered --- src/autoskillit/recipe/_cmd_rpc.py | 4 ++-- src/autoskillit/recipe/_cmd_rpc_merge.py | 4 ++-- src/autoskillit/recipe/cmd_rpc/__init__.py | 8 ++++---- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/autoskillit/recipe/_cmd_rpc.py b/src/autoskillit/recipe/_cmd_rpc.py index d9492bdad9..5968179eb5 100644 --- a/src/autoskillit/recipe/_cmd_rpc.py +++ b/src/autoskillit/recipe/_cmd_rpc.py @@ -37,8 +37,6 @@ ) __all__ = [ - "first_ordered_pr", - "next_ordered_pr", "attempt_cheap_rebase", "batch_create_issues", "check_dropped_ci_loop", @@ -52,9 +50,11 @@ "emit_fallback_map", "ensure_results", "export_local_bundle", + "first_ordered_pr", "force_push_and_wait_mergeability", "immediate_merge_conflict_fix", "main_repo_guard", + "next_ordered_pr", "proactive_rebase_next_pr", "queue_ejected_fix", "refetch_issues", diff --git a/src/autoskillit/recipe/_cmd_rpc_merge.py b/src/autoskillit/recipe/_cmd_rpc_merge.py index 3056bf31a9..2e7c93d023 100644 --- a/src/autoskillit/recipe/_cmd_rpc_merge.py +++ b/src/autoskillit/recipe/_cmd_rpc_merge.py @@ -40,17 +40,17 @@ "_attempt_rebase_with_conflict_report", "_detect_remote", "_write_rebase_conflict_report", - "first_ordered_pr", - "next_ordered_pr", "annotations", "atomic_write", "attempt_cheap_rebase", "create_persistent_integration", "direct_merge_conflict_fix", + "first_ordered_pr", "force_push_and_wait_mergeability", "get_logger", "immediate_merge_conflict_fix", "logger", + "next_ordered_pr", "proactive_rebase_next_pr", "queue_ejected_fix", "review_path_rebase", diff --git a/src/autoskillit/recipe/cmd_rpc/__init__.py b/src/autoskillit/recipe/cmd_rpc/__init__.py index 05f02e2dfc..da7f36a8ea 100644 --- a/src/autoskillit/recipe/cmd_rpc/__init__.py +++ b/src/autoskillit/recipe/cmd_rpc/__init__.py @@ -113,8 +113,6 @@ def __getattr__(name: str): ) _LAZY_SYMBOL_TO_MODULE: dict[str, str] = { - "first_ordered_pr": "_cmd_rpc_merge", - "next_ordered_pr": "_cmd_rpc_merge", "attempt_cheap_rebase": "_cmd_rpc_merge", "batch_create_issues": "_cmd_rpc_issues", "check_dropped_ci_loop": "_cmd_rpc_guards", @@ -128,9 +126,11 @@ def __getattr__(name: str): "emit_fallback_map": "_cmd_rpc_issues", "ensure_results": "_cmd_rpc_issues", "export_local_bundle": "_cmd_rpc_issues", + "first_ordered_pr": "_cmd_rpc_merge", "force_push_and_wait_mergeability": "_cmd_rpc_merge", "immediate_merge_conflict_fix": "_cmd_rpc_merge", "main_repo_guard": "_cmd_rpc_guards", + "next_ordered_pr": "_cmd_rpc_merge", "proactive_rebase_next_pr": "_cmd_rpc_merge", "queue_ejected_fix": "_cmd_rpc_merge", "refetch_issues": "_cmd_rpc_issues", @@ -204,8 +204,6 @@ def __getattr__(name: str): "_strip_ticket_body", "_validate_mutation_variables", "_write_rebase_conflict_report", - "first_ordered_pr", - "next_ordered_pr", "atomic_write", "attempt_cheap_rebase", "batch_create_issues", @@ -222,12 +220,14 @@ def __getattr__(name: str): "emit_fallback_map", "ensure_results", "export_local_bundle", + "first_ordered_pr", "force_push_and_wait_mergeability", "get_logger", "immediate_merge_conflict_fix", "is_generated_path", "logger", "main_repo_guard", + "next_ordered_pr", "proactive_rebase_next_pr", "queue_ejected_fix", "read_stable_contained_bytes", From fc51a21f2ad33ddecc45b696beef05772084f37c Mon Sep 17 00:00:00 2001 From: Trecek Date: Sat, 24 Oct 2026 10:44:02 -0700 Subject: [PATCH 10/19] test(review): remove cursor assertions implied by exact inventories --- tests/recipe/test_merge_prs_pr_cursor.py | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/tests/recipe/test_merge_prs_pr_cursor.py b/tests/recipe/test_merge_prs_pr_cursor.py index 52ac244755..58f32fe453 100644 --- a/tests/recipe/test_merge_prs_pr_cursor.py +++ b/tests/recipe/test_merge_prs_pr_cursor.py @@ -47,9 +47,6 @@ def test_cursor_steps_have_defined_inputs_and_single_writer(recipe) -> None: if cursor_fields.intersection(set(step.capture) | set(step.capture_list)) } assert writers == set(cursor_steps) - assert not cursor_fields.intersection( - set(recipe.steps["merge_pr"].capture) | set(recipe.steps["merge_pr"].capture_list) - ) merge_inputs = recipe.steps["merge_pr"].with_args["skill_inputs"] assert merge_inputs["pr_number"] == "${{ context.current_pr_number }}" assert merge_inputs["complexity"] == "${{ context.current_pr_complexity }}" @@ -85,14 +82,6 @@ def test_pr_order_file_has_declared_recipe_consumers(recipe) -> None: integration_inputs = recipe.steps["open_integration_pr"].with_args["skill_inputs"] assert integration_inputs["pr_order_file"] == "${{ context.pr_order_file }}" - shell_readers = { - name - for name, step in recipe.steps.items() - if step.tool == "run_cmd" - and "pr_order_file" in _context_refs_in_value((step.declared_with_args or {}).get("cmd")) - } - assert shell_readers == set() - def test_cursor_routes_preserve_plan_iteration_and_pr_advancement(recipe) -> None: next_part = recipe.steps["next_part_or_next_pr"] From 461ddca11a42b639aca10c2d4d59ef1771832011 Mon Sep 17 00:00:00 2001 From: Trecek Date: Sat, 24 Oct 2026 10:44:35 -0700 Subject: [PATCH 11/19] test(review): annotate the order-file helper boundary --- tests/recipe/test_cmd_rpc_merge.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/recipe/test_cmd_rpc_merge.py b/tests/recipe/test_cmd_rpc_merge.py index 1d70205622..a45a2c01f5 100644 --- a/tests/recipe/test_cmd_rpc_merge.py +++ b/tests/recipe/test_cmd_rpc_merge.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +from pathlib import Path from unittest.mock import MagicMock, patch import pytest @@ -247,7 +248,7 @@ def _order_document(prs: list[dict[str, object]]) -> dict[str, object]: } -def _write_order_file(tmp_path, document: object): +def _write_order_file(tmp_path: Path, document: object) -> Path: path = tmp_path / "pr-order.json" path.write_text(json.dumps(document), encoding="utf-8") return path From fe64f7809839bf8910ea9b289f5bbc0a8096cda0 Mon Sep 17 00:00:00 2001 From: Trecek Date: Sat, 24 Oct 2026 10:45:21 -0700 Subject: [PATCH 12/19] test(review): keep PR order fixtures focused on cursor fields --- tests/recipe/test_cmd_rpc_merge.py | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/tests/recipe/test_cmd_rpc_merge.py b/tests/recipe/test_cmd_rpc_merge.py index a45a2c01f5..36e218dc88 100644 --- a/tests/recipe/test_cmd_rpc_merge.py +++ b/tests/recipe/test_cmd_rpc_merge.py @@ -227,25 +227,12 @@ def test_proactive_rebase_next_pr_publishes_conflict_report(tmp_path): def _ordered_pr(number: object, complexity: object = "simple") -> dict[str, object]: return { "number": number, - "title": f"PR {number}", - "branch": f"feature/{number}", "complexity": complexity, - "files_changed": [f"src/{number}.py"], - "test_files_changed": [f"tests/test_{number}.py"], - "additions": 2, - "deletions": 1, - "overlap_with_pr_numbers": [], } def _order_document(prs: list[dict[str, object]]) -> dict[str, object]: - return { - "batch_branch": "pr-batch/pr-merge-20261024-120000", - "base_branch": "main", - "generated_at": "2026-10-24T12:00:00Z", - "pr_count": len(prs), - "prs": prs, - } + return {"prs": prs} def _write_order_file(tmp_path: Path, document: object) -> Path: From 67a51be0d6ffc1d8c8adc9ab81e18b466e1d5645 Mon Sep 17 00:00:00 2001 From: Trecek Date: Sat, 24 Oct 2026 10:45:54 -0700 Subject: [PATCH 13/19] test(review): name the dynamic-skill deferral behavior --- tests/recipe/test_rules_skill_input_template.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/recipe/test_rules_skill_input_template.py b/tests/recipe/test_rules_skill_input_template.py index e88e72b894..e0518cd7a6 100644 --- a/tests/recipe/test_rules_skill_input_template.py +++ b/tests/recipe/test_rules_skill_input_template.py @@ -159,7 +159,7 @@ def test_resolved_or_accepted_skill_input_values_are_clean( assert findings == [] -def test_dynamic_skill_with_context_path_placeholder_is_clean() -> None: +def test_dynamic_skill_templates_are_deferred_to_fanout() -> None: findings = _skill_input_template_findings( { "skill_command": "/autoskillit:arch-lens-{slug}", From 27c360bc9723a81acb34223f14e345d604fbbd9f Mon Sep 17 00:00:00 2001 From: Trecek Date: Sat, 24 Oct 2026 10:46:28 -0700 Subject: [PATCH 14/19] test(review): pin documented literal template forms --- tests/recipe/test_rules_skill_input_template.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/recipe/test_rules_skill_input_template.py b/tests/recipe/test_rules_skill_input_template.py index e0518cd7a6..6af1df28a3 100644 --- a/tests/recipe/test_rules_skill_input_template.py +++ b/tests/recipe/test_rules_skill_input_template.py @@ -133,6 +133,10 @@ def test_unresolved_inline_skill_arguments_are_errors(skill_command: str) -> Non pytest.param("/autoskillit:merge-pr", "pr_number", "{}", id="empty-braces"), pytest.param("/autoskillit:merge-pr", "pr_number", "42", id="string-literal"), pytest.param("/autoskillit:merge-pr", "pr_number", 42, id="integer-literal"), + *[ + pytest.param("/autoskillit:merge-pr", "pr_number", value, id=f"literal-{value}") + for value in ("PR-{pr_number}", "{0}", "{x!r}", "${x}", "") + ], pytest.param( "/autoskillit:investigate", "topic", From b44ac1a148f46f6fac4e2e9612e8a343b7a82663 Mon Sep 17 00:00:00 2001 From: Trecek Date: Sat, 24 Oct 2026 10:59:26 -0700 Subject: [PATCH 15/19] fix(review): preserve routing boundaries while sharing cursor bindings --- src/autoskillit/recipes/diagrams/merge-prs.md | 2 +- src/autoskillit/recipes/merge-prs.json | 41 +++++++++++---- src/autoskillit/recipes/merge-prs.yaml | 44 +++++++++------- tests/recipe/test_merge_prs_pr_cursor.py | 15 ++++-- tests/recipe/test_merge_prs_queue_pmp.py | 51 ++++++++++--------- 5 files changed, 94 insertions(+), 59 deletions(-) diff --git a/src/autoskillit/recipes/diagrams/merge-prs.md b/src/autoskillit/recipes/diagrams/merge-prs.md index 6f49cb8826..42aa3bc1c0 100644 --- a/src/autoskillit/recipes/diagrams/merge-prs.md +++ b/src/autoskillit/recipes/diagrams/merge-prs.md @@ -1,4 +1,4 @@ - + ## merge-prs diff --git a/src/autoskillit/recipes/merge-prs.json b/src/autoskillit/recipes/merge-prs.json index 6e66c6f8b6..1915fefdd8 100644 --- a/src/autoskillit/recipes/merge-prs.json +++ b/src/autoskillit/recipes/merge-prs.json @@ -83,13 +83,13 @@ "SEQUENTIAL LOOP: Process one PR at a time through the full merge cycle before advancing to the next PR. Never batch-assess all PRs before starting merges.", "SEQUENTIAL EXECUTION: complete full cycle (verify → create_conflict_worktree → implement → test → push_worktree_branch → create_conflict_pr → wait_for_conflict_ci → merge_conflict_pr) per plan part before advancing to the next part or PR.", "INTEGRATION BRANCH: Two distinct branches exist. inputs.base_branch is the target branch that PRs point to (e.g. main, develop). context.batch_branch is the per-run batch branch (e.g. pr-batch/pr-merge-{ts}) created from base_branch for this pipeline run. All PR merges and worktree merges target context.batch_branch. The final review PR opens from context.batch_branch into inputs.base_branch.", - "PR QUEUE: Only get_first_pr_number and advance_merge_pr write context.current_pr_number and context.current_pr_complexity. Never set or advance these values yourself. The cursor reads the immutable analyze_prs order file.", + "PR QUEUE: Only get_first_pr_number, advance_queue_pr and advance_merge_pr write context.current_pr_number and context.current_pr_complexity. Never set or advance these values yourself. The cursor reads the immutable analyze_prs order file.", "COMPLEX PR PATH: When merge_pr returns needs_plan=true, context.task is set to the conflict_report_path. Pass context.task to make-plan. The plan+implement cycle creates a worktree from the integration branch; the worktree branch is then pushed to origin and merged into the integration batch branch via GitHub PR (push_worktree_branch → create_conflict_pr → wait_for_conflict_ci → merge_conflict_pr).", "SOURCE ISOLATION: After clone_repo returns, the source_dir is strictly off-limits. Never run any command in source_dir — no git checkout, git fetch, git reset, git pull, run_cmd, run_skill, or any other operation. All work — skill invocations, git operations, file reads — happens exclusively in the clone (work_dir). source_dir is used ONLY to read the remote URL inside push_to_remote.", "GITHUB API MERGE: All PR merges into the integration branch go through GitHub's merge interface (gh pr merge --squash). This enforces the branch ruleset required status checks. Never use merge_worktree or local git merge to merge into the integration batch branch.", "PUSH DISCIPLINE: push_worktree_branch (inside the complex PR cycle), publish_batch_branch / push_batch_branch, force_push_and_wait_mergeability (authorized for conflict-resolution rebases), and push_rebased_next_pr (authorized for proactive pre-enqueue rebase) are the only authorized push steps. Never add ad-hoc run_cmd git push calls elsewhere in the loop.", "QUEUE MODE: When context.queue_mode == true, PRs merge directly into base_branch via the merge queue. The batch branch (context.batch_branch) is the same as base_branch. Never invoke create_batch_branch, publish_batch_branch, merge_pr, or push_batch_branch in queue mode.", - "QUEUE LOOP: get_first_pr_number initializes the PR number and complexity before selecting either mode. In queue mode, advance_merge_pr selects the successor by file position and returns done after the last PR without changing the artifact.", + "QUEUE LOOP: get_first_pr_number initializes the PR number and complexity before selecting either mode. In queue mode, advance_queue_pr selects the successor by file position and returns done after the last PR without changing the artifact.", "CONFLICT REPORT PATHS: context.all_conflict_report_paths accumulates conflict_report_path values from resolve_ejected_conflicts and resolve_integration_conflicts via capture_list. Pass it as the 5th argument to open_integration_pr and 4th argument to audit_impl. It is empty string when no conflict resolution occurred — downstream skills treat empty string as absent." ], "steps": { @@ -331,7 +331,7 @@ }, "on_success": "wait_queue_pr", "on_failure": "verify_queue_enrollment", - "note": "Queue mode only. Submits a single PR to the merge queue via the unified enqueue_pr tool. Called once per PR in the sequential enqueue loop: get_first_pr_number → route_by_queue_mode → get_current_pr_branch → wait_ci_pre_enqueue → enqueue_current_pr → wait_queue_pr → (merged) → advance_merge_pr → get_current_pr_branch → wait_ci_pre_enqueue → enqueue_current_pr → ...\n" + "note": "Queue mode only. Submits a single PR to the merge queue via the unified enqueue_pr tool. Called once per PR in the sequential enqueue loop: get_first_pr_number → route_by_queue_mode → get_current_pr_branch → wait_ci_pre_enqueue → enqueue_current_pr → wait_queue_pr → (merged) → advance_queue_pr → get_current_pr_branch → wait_ci_pre_enqueue → enqueue_current_pr → ...\n" }, "wait_queue_pr": { "tool": "wait_for_merge_queue", @@ -350,7 +350,7 @@ "on_result": [ { "when": "${{ result.pr_state }} == merged", - "route": "advance_merge_pr" + "route": "advance_queue_pr" }, { "when": "${{ result.pr_state }} == ejected_ci_failure", @@ -621,7 +621,7 @@ "on_result": [ { "when": "${{ result.pr_state }} == merged", - "route": "advance_merge_pr" + "route": "advance_queue_pr" }, { "when": "${{ result.pr_state }} == ejected_ci_failure", @@ -730,7 +730,7 @@ "on_result": [ { "when": "${{ result.pr_state }} == merged", - "route": "advance_merge_pr" + "route": "advance_queue_pr" }, { "when": "${{ result.pr_state }} == ejected_ci_failure", @@ -779,6 +779,29 @@ "on_failure": "verify_queue_enrollment", "note": "Re-submits the fixed PR to the merge queue after conflict resolution. Routes back to wait_queue_pr to continue monitoring.\n" }, + "advance_queue_pr": { + "tool": "run_python", + "with": { + "callable": "autoskillit.recipe._cmd_rpc.next_ordered_pr", + "current_pr_number": "${{ context.current_pr_number }}", + "pr_order_file": "${{ context.pr_order_file }}" + }, + "capture": { + "current_pr_number": "${{ result.pr_number }}", + "current_pr_complexity": "${{ result.complexity }}" + }, + "on_result": [ + { + "when": "${{ result.done }} == true", + "route": "collect_and_check_impl_plans" + }, + { + "route": "get_next_pr_branch" + } + ], + "on_failure": "register_clone_failure", + "note": "Advances by file position and captures the next PR number and complexity. At the end, retains the last PR and returns done. Continues through proactive rebase or collects implementation plans when done." + }, "get_next_pr_branch": { "tool": "run_cmd", "with": { @@ -1453,16 +1476,12 @@ "when": "${{ result.done }} == true", "route": "push_batch_branch" }, - { - "when": "${{ context.queue_mode }} == true", - "route": "get_next_pr_branch" - }, { "route": "check_pr_merge_loop" } ], "on_failure": "register_clone_failure", - "note": "Advances by file position once per finished PR in either mode. Queue mode continues through proactive rebase or collects implementation plans when done; classic mode continues its merge loop or pushes the batch branch. Queue-mode audit remediation re-enters at the last PR and collects implementation plans without changing the artifact." + "note": "Classic and post-remediation advance, keyed on current_pr_number once per finished PR. Queue-mode audit remediation re-enters at the last PR and exits to collect_and_check_impl_plans through the first done arm." }, "select_next_plan_part": { "tool": "run_cmd", diff --git a/src/autoskillit/recipes/merge-prs.yaml b/src/autoskillit/recipes/merge-prs.yaml index 9ae82a4c82..4043751778 100644 --- a/src/autoskillit/recipes/merge-prs.yaml +++ b/src/autoskillit/recipes/merge-prs.yaml @@ -76,7 +76,7 @@ kitchen_rules: develop). context.batch_branch is the per-run batch branch (e.g. pr-batch/pr-merge-{ts}) created from base_branch for this pipeline run. All PR merges and worktree merges target context.batch_branch. The final review PR opens from context.batch_branch into inputs.base_branch.' -- 'PR QUEUE: Only get_first_pr_number and advance_merge_pr write context.current_pr_number and +- 'PR QUEUE: Only get_first_pr_number, advance_queue_pr and advance_merge_pr write context.current_pr_number and context.current_pr_complexity. Never set or advance these values yourself. The cursor reads the immutable analyze_prs order file.' - 'COMPLEX PR PATH: When merge_pr returns needs_plan=true, context.task is set to the conflict_report_path. Pass context.task to make-plan. The plan+implement cycle creates a worktree from the integration branch; the worktree branch is then pushed @@ -96,7 +96,7 @@ kitchen_rules: (context.batch_branch) is the same as base_branch. Never invoke create_batch_branch, publish_batch_branch, merge_pr, or push_batch_branch in queue mode.' - 'QUEUE LOOP: get_first_pr_number initializes the PR number and complexity before selecting either mode. In queue mode, - advance_merge_pr selects the successor by file position and returns done after the last PR without changing the artifact.' + advance_queue_pr selects the successor by file position and returns done after the last PR without changing the artifact.' - 'CONFLICT REPORT PATHS: context.all_conflict_report_paths accumulates conflict_report_path values from resolve_ejected_conflicts and resolve_integration_conflicts via capture_list. Pass it as the 5th argument to open_integration_pr and 4th argument to audit_impl. It is empty string when no conflict resolution occurred — downstream skills treat empty string as absent.' @@ -334,7 +334,7 @@ steps: on_failure: verify_queue_enrollment note: 'Queue mode only. Submits a single PR to the merge queue via the unified enqueue_pr tool. Called once per PR in the sequential enqueue loop: get_first_pr_number → route_by_queue_mode → get_current_pr_branch → wait_ci_pre_enqueue → enqueue_current_pr - → wait_queue_pr → (merged) → advance_merge_pr → get_current_pr_branch → wait_ci_pre_enqueue → enqueue_current_pr → ... + → wait_queue_pr → (merged) → advance_queue_pr → get_current_pr_branch → wait_ci_pre_enqueue → enqueue_current_pr → ... ' wait_queue_pr: @@ -351,7 +351,7 @@ steps: queue_pr_state: ${{ result.pr_state }} on_result: - when: ${{ result.pr_state }} == merged - route: advance_merge_pr + route: advance_queue_pr - when: ${{ result.pr_state }} == ejected_ci_failure route: diagnose_queue_ci - when: ${{ result.pr_state }} == dropped_merge_group_ci @@ -555,7 +555,7 @@ steps: max_merge_group_drops: '1' on_result: - when: ${{ result.pr_state }} == merged - route: advance_merge_pr + route: advance_queue_pr - when: ${{ result.pr_state }} == ejected_ci_failure route: register_clone_failure - when: ${{ result.pr_state }} == dropped_merge_group_ci @@ -631,7 +631,7 @@ steps: max_merge_group_drops: 1 on_result: - when: ${{ result.pr_state }} == merged - route: advance_merge_pr + route: advance_queue_pr - when: ${{ result.pr_state }} == ejected_ci_failure route: diagnose_queue_ci - when: ${{ result.pr_state }} == not_enrolled @@ -665,6 +665,22 @@ steps: monitoring. ' + advance_queue_pr: + tool: run_python + with: &advance_pr_inputs + callable: autoskillit.recipe._cmd_rpc.next_ordered_pr + current_pr_number: ${{ context.current_pr_number }} + pr_order_file: ${{ context.pr_order_file }} + capture: &pr_cursor_outputs + current_pr_number: ${{ result.pr_number }} + current_pr_complexity: ${{ result.complexity }} + on_result: + - when: ${{ result.done }} == true + route: collect_and_check_impl_plans + - route: get_next_pr_branch + on_failure: register_clone_failure + note: 'Advances by file position and captures the next PR number and complexity. At the end, retains the last PR and + returns done. Continues through proactive rebase or collects implementation plans when done.' get_next_pr_branch: tool: run_cmd with: @@ -1246,25 +1262,17 @@ steps: otherwise advance_merge_pr determines whether another PR remains.' advance_merge_pr: tool: run_python - with: - callable: autoskillit.recipe._cmd_rpc.next_ordered_pr - current_pr_number: ${{ context.current_pr_number }} - pr_order_file: ${{ context.pr_order_file }} - capture: - current_pr_number: ${{ result.pr_number }} - current_pr_complexity: ${{ result.complexity }} + with: *advance_pr_inputs + capture: *pr_cursor_outputs on_result: - when: ${{ context.queue_mode }} == true and ${{ result.done }} == true route: collect_and_check_impl_plans - when: ${{ result.done }} == true route: push_batch_branch - - when: ${{ context.queue_mode }} == true - route: get_next_pr_branch - route: check_pr_merge_loop on_failure: register_clone_failure - note: 'Advances by file position once per finished PR in either mode. Queue mode continues through proactive rebase - or collects implementation plans when done; classic mode continues its merge loop or pushes the batch branch. - Queue-mode audit remediation re-enters at the last PR and collects implementation plans without changing the artifact.' + note: 'Classic and post-remediation advance, keyed on current_pr_number once per finished PR. Queue-mode audit remediation + re-enters at the last PR and exits to collect_and_check_impl_plans through the first done arm.' select_next_plan_part: tool: run_cmd with: diff --git a/tests/recipe/test_merge_prs_pr_cursor.py b/tests/recipe/test_merge_prs_pr_cursor.py index 58f32fe453..2ef1294421 100644 --- a/tests/recipe/test_merge_prs_pr_cursor.py +++ b/tests/recipe/test_merge_prs_pr_cursor.py @@ -33,13 +33,13 @@ def test_cursor_steps_have_defined_inputs_and_single_writer(recipe) -> None: cursor_fields = {"current_pr_number", "current_pr_complexity"} cursor_steps = { "get_first_pr_number": "autoskillit.recipe._cmd_rpc.first_ordered_pr", + "advance_queue_pr": "autoskillit.recipe._cmd_rpc.next_ordered_pr", "advance_merge_pr": "autoskillit.recipe._cmd_rpc.next_ordered_pr", } must_defined = make_validation_context(recipe).must_defined_context - assert {"current_pr_number", "pr_order_file"} <= must_defined.get( - "advance_merge_pr", frozenset() - ) + for step_name in ("advance_queue_pr", "advance_merge_pr"): + assert {"current_pr_number", "pr_order_file"} <= must_defined.get(step_name, frozenset()) writers = { name @@ -68,6 +68,7 @@ def test_pr_order_file_has_declared_recipe_consumers(recipe) -> None: } assert consumers == { "get_first_pr_number", + "advance_queue_pr", "advance_merge_pr", "open_integration_pr", } @@ -99,6 +100,12 @@ def test_cursor_routes_preserve_plan_iteration_and_pr_advancement(recipe) -> Non "collect_and_check_impl_plans", ), ("${{ result.done }} == true", "push_batch_branch"), - ("${{ context.queue_mode }} == true", "get_next_pr_branch"), (None, "check_pr_merge_loop"), ] + + queue_advance = recipe.steps["advance_queue_pr"] + assert queue_advance.on_result is not None + assert [(c.when, c.route) for c in queue_advance.on_result.conditions] == [ + ("${{ result.done }} == true", "collect_and_check_impl_plans"), + (None, "get_next_pr_branch"), + ] diff --git a/tests/recipe/test_merge_prs_queue_pmp.py b/tests/recipe/test_merge_prs_queue_pmp.py index d6aee7ce0d..837d5044de 100644 --- a/tests/recipe/test_merge_prs_queue_pmp.py +++ b/tests/recipe/test_merge_prs_queue_pmp.py @@ -81,10 +81,10 @@ def test_merge_prs_reenter_queue_exists(pmp_recipe) -> None: assert "reenter_queue" in pmp_recipe.steps -def test_merge_prs_advance_merge_pr_exists(pmp_recipe) -> None: - """advance_merge_pr step must exist with tool=run_python.""" - assert "advance_merge_pr" in pmp_recipe.steps - step = pmp_recipe.steps["advance_merge_pr"] +def test_merge_prs_advance_queue_pr_exists(pmp_recipe) -> None: + """advance_queue_pr step must exist with tool=run_python.""" + assert "advance_queue_pr" in pmp_recipe.steps + step = pmp_recipe.steps["advance_queue_pr"] assert step.tool == "run_python" @@ -220,15 +220,16 @@ def test_merge_prs_checkout_ejected_pr_removed(pmp_recipe) -> None: # --------------------------------------------------------------------------- -def test_merge_prs_advance_merge_pr_queue_route_to_get_next_pr_branch( +def test_merge_prs_advance_queue_pr_fallthrough_routes_to_get_next_pr_branch( pmp_recipe, ) -> None: - step = pmp_recipe.steps["advance_merge_pr"] + step = pmp_recipe.steps["advance_queue_pr"] assert step.on_result is not None - queue_routes = [ - c.route for c in step.on_result.conditions if c.when == "${{ context.queue_mode }} == true" - ] - assert queue_routes == ["get_next_pr_branch"] + fallback_route = next( + (c.route for c in step.on_result.conditions if c.when is None), + None, + ) + assert fallback_route == "get_next_pr_branch" def test_merge_prs_get_next_pr_branch_exists(pmp_recipe) -> None: @@ -384,36 +385,36 @@ def test_merge_prs_ci_watch_routes_to_reenter(pmp_recipe) -> None: # --------------------------------------------------------------------------- -def test_merge_prs_advance_merge_pr_is_run_python(pmp_recipe) -> None: - """advance_merge_pr step must exist with tool=run_python.""" - assert "advance_merge_pr" in pmp_recipe.steps - step = pmp_recipe.steps["advance_merge_pr"] +def test_merge_prs_advance_queue_pr_is_run_python(pmp_recipe) -> None: + """advance_queue_pr step must exist with tool=run_python.""" + assert "advance_queue_pr" in pmp_recipe.steps + step = pmp_recipe.steps["advance_queue_pr"] assert step.tool == "run_python" def test_merge_prs_next_queue_pr_or_done_removed(pmp_recipe) -> None: - """next_queue_pr_or_done step must be removed (replaced by advance_merge_pr).""" + """next_queue_pr_or_done step must be removed (replaced by advance_queue_pr).""" assert "next_queue_pr_or_done" not in pmp_recipe.steps -def test_merge_prs_advance_merge_pr_callable_references_pr_order(pmp_recipe) -> None: - """advance_merge_pr callable args must reference pr_order_file and current_pr_number.""" - step = pmp_recipe.steps["advance_merge_pr"] +def test_merge_prs_advance_queue_pr_callable_references_pr_order(pmp_recipe) -> None: + """advance_queue_pr callable args must reference pr_order_file and current_pr_number.""" + step = pmp_recipe.steps["advance_queue_pr"] args = step.with_args assert "pr_order_file" in args assert "current_pr_number" in args -def test_merge_prs_advance_merge_pr_captures_pr_number(pmp_recipe) -> None: - """advance_merge_pr must have a capture block for current_pr_number.""" - step = pmp_recipe.steps["advance_merge_pr"] +def test_merge_prs_advance_queue_pr_captures_pr_number(pmp_recipe) -> None: + """advance_queue_pr must have a capture block for current_pr_number.""" + step = pmp_recipe.steps["advance_queue_pr"] capture = step.capture or {} assert "current_pr_number" in capture -def test_merge_prs_advance_merge_pr_routing(pmp_recipe) -> None: - """advance_merge_pr handles queue completion and the classic fallback.""" - step = pmp_recipe.steps["advance_merge_pr"] +def test_merge_prs_advance_queue_pr_routing(pmp_recipe) -> None: + """advance_queue_pr routes to get_next_pr_branch (default) or collect_and_check_impl_plans.""" + step = pmp_recipe.steps["advance_queue_pr"] assert step.on_result is not None conditions = step.on_result.conditions done_routes = [c for c in conditions if c.when and "done" in c.when] @@ -421,7 +422,7 @@ def test_merge_prs_advance_merge_pr_routing(pmp_recipe) -> None: assert done_routes[0].route == "collect_and_check_impl_plans" default_routes = [c for c in conditions if c.when is None] assert default_routes, "must have a default route" - assert default_routes[0].route == "check_pr_merge_loop" + assert default_routes[0].route == "get_next_pr_branch" # --------------------------------------------------------------------------- From 3790e580b8a4aa8933daebcb0fbde9db6533a63a Mon Sep 17 00:00:00 2001 From: Trecek Date: Sat, 24 Oct 2026 11:10:05 -0700 Subject: [PATCH 16/19] fix(review): retain declarations required by guarded recipe delivery --- src/autoskillit/recipes/diagrams/merge-prs.md | 2 +- src/autoskillit/recipes/merge-prs.yaml | 13 +++++++++---- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/autoskillit/recipes/diagrams/merge-prs.md b/src/autoskillit/recipes/diagrams/merge-prs.md index 42aa3bc1c0..6f49cb8826 100644 --- a/src/autoskillit/recipes/diagrams/merge-prs.md +++ b/src/autoskillit/recipes/diagrams/merge-prs.md @@ -1,4 +1,4 @@ - + ## merge-prs diff --git a/src/autoskillit/recipes/merge-prs.yaml b/src/autoskillit/recipes/merge-prs.yaml index 4043751778..06923673f7 100644 --- a/src/autoskillit/recipes/merge-prs.yaml +++ b/src/autoskillit/recipes/merge-prs.yaml @@ -667,11 +667,11 @@ steps: ' advance_queue_pr: tool: run_python - with: &advance_pr_inputs + with: callable: autoskillit.recipe._cmd_rpc.next_ordered_pr current_pr_number: ${{ context.current_pr_number }} pr_order_file: ${{ context.pr_order_file }} - capture: &pr_cursor_outputs + capture: current_pr_number: ${{ result.pr_number }} current_pr_complexity: ${{ result.complexity }} on_result: @@ -1262,8 +1262,13 @@ steps: otherwise advance_merge_pr determines whether another PR remains.' advance_merge_pr: tool: run_python - with: *advance_pr_inputs - capture: *pr_cursor_outputs + with: + callable: autoskillit.recipe._cmd_rpc.next_ordered_pr + current_pr_number: ${{ context.current_pr_number }} + pr_order_file: ${{ context.pr_order_file }} + capture: + current_pr_number: ${{ result.pr_number }} + current_pr_complexity: ${{ result.complexity }} on_result: - when: ${{ context.queue_mode }} == true and ${{ result.done }} == true route: collect_and_check_impl_plans From 2b35ca228d1dd2a2aebc02e5778e743d8972e7bd Mon Sep 17 00:00:00 2001 From: Trecek Date: Sat, 24 Oct 2026 11:48:43 -0700 Subject: [PATCH 17/19] fix(recipe): refresh merge-prs diagram hash after rebase --- src/autoskillit/recipes/diagrams/merge-prs.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/autoskillit/recipes/diagrams/merge-prs.md b/src/autoskillit/recipes/diagrams/merge-prs.md index 6f49cb8826..8d14b6d171 100644 --- a/src/autoskillit/recipes/diagrams/merge-prs.md +++ b/src/autoskillit/recipes/diagrams/merge-prs.md @@ -1,4 +1,4 @@ - + ## merge-prs From aae7e142bb22a4f0546dc616820048f41634d0ee Mon Sep 17 00:00:00 2001 From: Trecek Date: Sat, 24 Oct 2026 12:03:13 -0700 Subject: [PATCH 18/19] test: retire resolved merge-pr admission xfail for #5306 --- tests/server/test_attested_admission_replay.py | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/tests/server/test_attested_admission_replay.py b/tests/server/test_attested_admission_replay.py index fe52d281bd..5c8e0b305b 100644 --- a/tests/server/test_attested_admission_replay.py +++ b/tests/server/test_attested_admission_replay.py @@ -96,18 +96,6 @@ reason="Blocked by #5307: planner item placeholders compile as static inputs", ), ), - ("merge-prs", "merge_pr"): pytest.param( - "merge-prs", - "merge_pr", - "recipe_execution_static_input_mismatch", - "static skill input 'pr_number'", - id="merge-prs-merge_pr", - marks=pytest.mark.xfail( - strict=True, - raises=AdmissionDefect, - reason="Blocked by #5306: merge item placeholders compile as static inputs", - ), - ), ("bem-wrapper", "run_bem"): pytest.param( "bem-wrapper", "run_bem", From 4e76ef88ae2dca63cd3610723718ae0ac33c2c3f Mon Sep 17 00:00:00 2001 From: Trecek Date: Sat, 24 Oct 2026 12:08:26 -0700 Subject: [PATCH 19/19] fix(recipe): refresh diagram after develop admission update --- src/autoskillit/recipes/diagrams/merge-prs.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/autoskillit/recipes/diagrams/merge-prs.md b/src/autoskillit/recipes/diagrams/merge-prs.md index 8d14b6d171..2059b2a269 100644 --- a/src/autoskillit/recipes/diagrams/merge-prs.md +++ b/src/autoskillit/recipes/diagrams/merge-prs.md @@ -1,4 +1,4 @@ - + ## merge-prs