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..5968179eb5 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,6 @@ ) __all__ = [ - "advance_queue_pr", "attempt_cheap_rebase", "batch_create_issues", "check_dropped_ci_loop", @@ -50,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 713dfbee09..2e7c93d023 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,16 +40,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", diff --git a/src/autoskillit/recipe/cmd_rpc/__init__.py b/src/autoskillit/recipe/cmd_rpc/__init__.py index d59d99a9b6..da7f36a8ea 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,6 @@ def __getattr__(name: str): ) _LAZY_SYMBOL_TO_MODULE: dict[str, str] = { - "advance_queue_pr": "_cmd_rpc_merge", "attempt_cheap_rebase": "_cmd_rpc_merge", "batch_create_issues": "_cmd_rpc_issues", "check_dropped_ci_loop": "_cmd_rpc_guards", @@ -126,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", @@ -202,7 +204,6 @@ def __getattr__(name: str): "_strip_ticket_body", "_validate_mutation_variables", "_write_rebase_conflict_report", - "advance_queue_pr", "atomic_write", "attempt_cheap_rebase", "batch_create_issues", @@ -219,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", 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..1a4d99bd9b 100644 --- a/src/autoskillit/recipe/cmd_rpc/_cmd_rpc_merge.py +++ b/src/autoskillit/recipe/cmd_rpc/_cmd_rpc_merge.py @@ -310,29 +310,57 @@ 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: + with open(pr_order_file, encoding="utf-8") 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"} + 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") + 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]: + 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]: + """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): + 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") def review_path_rebase( diff --git a/src/autoskillit/recipe/rules/rules_inputs.py b/src/autoskillit/recipe/rules/rules_inputs.py index b0e5f94030..0c62b5c461 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,11 +16,13 @@ BindingFailureCode, BoundValue, BoundValueOrigin, + BoundValueState, Severity, get_logger, ) from autoskillit.recipe._analysis import ValidationContext, bfs_reachable from autoskillit.recipe.contracts import ( + RESULT_CAPTURE_RE, SkillInput, get_skill_contract, load_bundled_manifest, @@ -31,6 +34,66 @@ 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 ( + 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" + ) + 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=( + "Reject whole-value skill input placeholders and unresolved ${{ ... }} expressions " + "that 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/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..2059b2a269 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..36e218dc88 100644 --- a/tests/recipe/test_cmd_rpc_merge.py +++ b/tests/recipe/test_cmd_rpc_merge.py @@ -2,10 +2,13 @@ from __future__ import annotations +import json +from pathlib import Path 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 +222,164 @@ 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, + "complexity": complexity, + } + + +def _order_document(prs: list[dict[str, object]]) -> dict[str, object]: + return {"prs": prs} + + +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 + + +@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, "{", 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 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: + _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..2ef1294421 --- /dev/null +++ b/tests/recipe/test_merge_prs_pr_cursor.py @@ -0,0 +1,111 @@ +"""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) + 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 }}" + + +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"), + ] + + 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_common.py b/tests/recipe/test_merge_prs_queue_common.py index 00a8ada112..4432a3d18d 100644 --- a/tests/recipe/test_merge_prs_queue_common.py +++ b/tests/recipe/test_merge_prs_queue_common.py @@ -824,13 +824,14 @@ 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 + 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 d24d580fc7..837d5044de 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,12 +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_enqueue(pmp_recipe) -> None: - """get_first_pr_number.on_success must route to get_current_pr_branch (CI gate added).""" - step = pmp_recipe.steps["get_first_pr_number"] - assert step.on_success == "get_current_pr_branch" - - # --------------------------------------------------------------------------- # merge-prs.yaml — cheap rebase pre-check (Test 1C) # --------------------------------------------------------------------------- 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", 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..6af1df28a3 --- /dev/null +++ b/tests/recipe/test_rules_skill_input_template.py @@ -0,0 +1,214 @@ +"""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 }}/${{ 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( + "${{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:merge-pr", "pr_number", value, id=f"literal-{value}") + for value in ("PR-{pr_number}", "{0}", "{x!r}", "${x}", "") + ], + 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_templates_are_deferred_to_fanout() -> 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 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",