From b51c7d0c604fd787d027201d38387f18aea34faa Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Wed, 25 Nov 2026 15:07:37 -0500 Subject: [PATCH] refactor(skills): retire legacy Gitea skills and update installer and tests - skills/: remove retired legacy directories gitea-plan, implement-slice, verify-slice, and gitea-pr replaced by GitHub-native projects, implement, and verify - install.sh: update ACTIVE_PORTABLE_SKILLS and OBSOLETE_SKILLS, drop stale gt warning block from check_prerequisites, return exit 1 from check when missing > 0, and prune repo-scoped dangling symlinks under $SCRIPT_DIR/skills/* - tests/fixtures/test_skills_behavioral_contracts.py: retire WorkflowNode/WorkflowEngine mocks and Gitea-only assertions, update all 8 legacy contract blocks for GitHub-native skills, and add coverage for projects, implement, code-review, verify, and isolated install.sh behavior - tests/fixtures/run_regression.sh: run both test_skills_behavioral_contracts.py and test_build_review.py via python3 -m unittest and update Step 3 grep checks to target projects, implement, code-review, and gt-usage --- install.sh | 36 +- skills/gitea-plan/SKILL.md | 73 -- .../references/decomposition-tiers.md | 99 --- skills/gitea-plan/references/tea-cli.md | 26 - skills/gitea-pr/SKILL.md | 71 -- skills/gitea-pr/references/gt-pulls.md | 111 --- skills/gitea-pr/references/pr-lifecycle.md | 90 --- skills/gitea-pr/references/tea-pulls.md | 28 - skills/implement-slice/SKILL.md | 45 -- .../references/handoff-contracts.md | 147 ---- .../references/orchestration-tiers.md | 105 --- skills/verify-slice/SKILL.md | 37 - .../verify-slice/references/perspectives.md | 48 -- tests/fixtures/run_regression.sh | 16 +- .../test_skills_behavioral_contracts.py | 736 ++++++++---------- 15 files changed, 341 insertions(+), 1327 deletions(-) delete mode 100644 skills/gitea-plan/SKILL.md delete mode 100644 skills/gitea-plan/references/decomposition-tiers.md delete mode 100644 skills/gitea-plan/references/tea-cli.md delete mode 100644 skills/gitea-pr/SKILL.md delete mode 100644 skills/gitea-pr/references/gt-pulls.md delete mode 100644 skills/gitea-pr/references/pr-lifecycle.md delete mode 100644 skills/gitea-pr/references/tea-pulls.md delete mode 100644 skills/implement-slice/SKILL.md delete mode 100644 skills/implement-slice/references/handoff-contracts.md delete mode 100644 skills/implement-slice/references/orchestration-tiers.md delete mode 100644 skills/verify-slice/SKILL.md delete mode 100644 skills/verify-slice/references/perspectives.md diff --git a/install.sh b/install.sh index ec828ab..2ed97c0 100755 --- a/install.sh +++ b/install.sh @@ -33,11 +33,11 @@ while [[ $# -gt 0 ]]; do done # Active skills to install -ACTIVE_PORTABLE_SKILLS=(build-skill code-review derive-skill diagnose document git-manager gitea-plan gitea-pr gt-usage implement-slice inspect-flake-update nix-devshell practice reconcile-docs tdd verify-slice) +ACTIVE_PORTABLE_SKILLS=(build-skill code-review derive-skill diagnose document git-manager gt-usage implement inspect-flake-update nix-devshell practice projects reconcile-docs tdd verify) ACTIVE_EXTENSION_SKILLS=() # Legacy / deprecated skills to clean up or back up if found in target -OBSOLETE_SKILLS=(engineering-tutor engineering-investigation skill-builder documentation-router inbox-curation commit-logger git-commit git-workspace journal-builder draft-curation) +OBSOLETE_SKILLS=(engineering-tutor engineering-investigation skill-builder documentation-router inbox-curation commit-logger git-commit git-workspace journal-builder draft-curation gitea-plan implement-slice verify-slice gitea-pr) OBSOLETE_AGENTS=(anne-droid.md) check_prerequisites() { @@ -46,22 +46,6 @@ check_prerequisites() { echo " [ERROR] git is required but not found in PATH." >&2 status=1 fi - if ! command -v gt >/dev/null 2>&1; then - echo " [WARNING] 'gt' CLI not found in PATH." >&2 - echo " Gitea skills (gt-usage, gitea-plan, gitea-pr, implement-slice) require the official Gitea CLI (v1.0.0+)." >&2 - echo " Install via package manager or download from https://gitea.com/gitea/cli/releases" >&2 - else - local missing_subcommands=() - for sub in issue milestone project pr; do - if ! gt "$sub" --help >/dev/null 2>&1; then - missing_subcommands+=("$sub") - fi - done - if [[ ${#missing_subcommands[@]} -gt 0 ]]; then - echo " [WARNING] 'gt' CLI found but lacks required capabilities: ${missing_subcommands[*]}" >&2 - echo " Update gt to the official release (https://gitea.com/gitea/cli)." >&2 - fi - fi return "$status" } @@ -108,8 +92,9 @@ if [[ "$CHECK_ONLY" -eq 1 ]]; then fi if [[ "$missing" -eq 0 ]]; then echo "All active skills are present." + exit 0 fi - exit 0 + exit 1 fi # Prepare backup directory timestamp if needed @@ -144,6 +129,19 @@ for a in "${OBSOLETE_AGENTS[@]}"; do fi done +# Prune repo-scoped dangling symlinks in target directory +for entry in "$TARGET_DIR"/*; do + if [[ -L "$entry" && ! -e "$entry" ]]; then + link_target="$(readlink "$entry")" + case "$link_target" in + "$SCRIPT_DIR/skills/"*) + rm -f "$entry" + echo " [PRUNED] dangling symlink $(basename "$entry") -> $link_target" + ;; + esac + fi +done + # Install portable skills for s in "${ACTIVE_PORTABLE_SKILLS[@]}"; do src="$SCRIPT_DIR/skills/$s" diff --git a/skills/gitea-plan/SKILL.md b/skills/gitea-plan/SKILL.md deleted file mode 100644 index da80b61..0000000 --- a/skills/gitea-plan/SKILL.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -name: gitea-plan -description: >- - Translate technical goals, user requests, and architecture plans into Gitea planning - primitives (issues, milestones, project boards) with tiered complexity scaling. - Use when decomposing work, creating or updating Gitea issues, or establishing planning - milestones. Not for managing pull requests: use gitea-pr. ---- - -# Gitea Plan - -## Use when -- Decomposing a project, feature request, or technical plan into trackable Gitea units. -- Creating or editing milestones, project boards, and issues with falsifiable criteria. -- Setting rolling planning horizons for multi-phase epics. -- Not for orchestrating slice implementation across subagents: use `implement-slice`. -- Not for branch or worktree management: use `git-manager`. -- Not for pull request lifecycle or review tracking: use `gitea-pr`. - -## Steps -1. **Reconcile artifacts bidirectionally.** Check specs, roadmaps, assets, and Gitea - state for contradictions. Flag zombie in-progress, premature completed, or horizon - divergence conflicts before planning new work. When closing a milestone or before - decomposing the next rolling milestone, if `ARCHITECTURE.md`, `ROADMAP.md`, or - `docs/designs/*.md` lag behind `Completed` board cards, hand off to `reconcile-docs` - first. See [references/decomposition-tiers.md](references/decomposition-tiers.md). -2. **Assess scope and select tier.** Assign `Small`, `Medium`, or `Large`. - Emit explicit `### Project Board Policy: (Rationale)`. -3. **Decompose into deliverable outcome slices.** Map work into verifiable issues - with test seams and falsifiable acceptance criteria (Context, Solution, Criteria), - grouping TDD test seams vertically by submodule or capability rather than a single - monolithic upfront test block across all modules. -4. **Run independent reproducibility audit (`Medium`/`Large` mandatory).** For `Medium` - and `Large` plans, spawn a clean-room subagent with raw input manifest (commit SHA, - specs, proposed issue markdown) to resolve material ambiguities before the human gate. -5. **Present decomposition for approval.** Emit `### Reproducibility Audit: (Subagent: | Omitted: Small tier)` - alongside proposed milestone, board, issues, and any `AGENTS.md` contract diff. Stop - for approval before mutating Gitea entities or `AGENTS.md`. -6. **Execute Gitea operations via `gt` CLI.** Use verified commands from `gt-usage`: - - Milestones: `gt milestone create "" -d "<desc>" --json id,url`. - - Projects: create with `gt project create "<title>" --template none --json id,url` if - missing (with `--org <org>` for multi-repo orgs), or reconcile an existing board in - place (`PATCH` matched role aliases, `POST` missing columns, set `Backlog` default, - and apply the Deep Signal hex colors per [decomposition-tiers](references/decomposition-tiers.md)). - - Issues: `gt issue create -t "<title>" -F <file> -m <id> -p <id> --json id,number,url` - (or attach to org board: `gt issue edit <number> -R <repo> --add-project <id>`). - Extract server IDs directly; never guess sequence numbers or construct `/milestone/1`. -7. **Verify created state.** Inspect `gt issue list`, `gt milestone list`, and board - columns to confirm server IDs, column colors/order, and non-hallucinated canonical URLs. -8. **Formalize repo planning contract in `AGENTS.md`.** When establishing or changing - `Medium`/`Large` planning structure, record a concise sync rule in `AGENTS.md`: - - Pin **stable coordinates only**: roadmap/checklist paths (`docs/roadmap.md`, `todo.txt`), - Gitea repo + Project Board ID + `{Backlog, Ready, Work in Progress, Review, Completed -> column_id}` - map, mirror policy, and the trigger to re-run `gitea-plan` on scope shifts or Readiness Gates. - - **Never** hardcode rotating sprint state (milestone numbers or open issues) in `AGENTS.md`. - -## Your call -- **Planning tier selection**: confirm Small vs. Medium vs. Large ceremony level. -- **Issue decomposition boundaries**: approve or revise proposed issue slices. -- **Batch entity creation**: approve structured batch creation and `AGENTS.md` contract edits per `profile/AGENTS.md`. - -## Done when -- Target milestone, board, and issues exist on Gitea with verified server IDs, - canonical URLs, and falsifiable acceptance criteria. -- Repository `AGENTS.md` contains an accurate, state-free planning sync contract - whenever `Medium`/`Large` planning structure is created or updated. - -## Hands off to -- `implement-slice`: to deliver an approved issue (`Suggested Next Step: /implement-slice #<first-ready-issue>`). -- `git-manager`: to create dedicated branches or worktrees for decomposed issues. -- `gitea-pr`: to link, review, and close issues via pull requests. -- `reconcile-docs`: when canonical docs lag behind completed cards (`Suggested Next Step: /reconcile-docs`). -- Emit one outcome-matched `Suggested Next Step` per [skeleton](../build-skill/references/skeleton.md). diff --git a/skills/gitea-plan/references/decomposition-tiers.md b/skills/gitea-plan/references/decomposition-tiers.md deleted file mode 100644 index 53dc261..0000000 --- a/skills/gitea-plan/references/decomposition-tiers.md +++ /dev/null @@ -1,99 +0,0 @@ -# Project Sizing, Ceremony Tiers, and Artifact Contracts - -Reference for `gitea-plan`. Guidelines for scaling planning ceremony to risk and scope, preserving momentum while keeping architecture traceable and reproducible. - -## 1. Core Axiom: Issues vs. Commits - -- An **Issue** represents an **independently deliverable outcome** (what is built, verified, and closed by a pull request). It defines falsifiable acceptance criteria and expected behavior. -- A **Commit** represents an **atomic, reversible implementation checkpoint** (a step within that issue's branch). Commits must compile and pass tests, but do not need to represent an entire closed issue on their own. -- **Anti-pattern**: Never create 1:1 Gitea issues for micro-commits (such as "fix typo", "add helper function", or "clean up lint"). Group cohesive checkpoints under a single deliverable issue. -- **Vertical Submodule TDD Grouping**: Inside a multi-module issue, organize acceptance criteria and TDD test drafts vertically by submodule or dependency layer (e.g. `protocols` -> `ssap` -> `pointer` -> `manager`) rather than a single horizontal "write all tests for the entire issue first" section, so `implement-slice` executes incremental Red->Green cycles per submodule. - ---- - -## 2. Entity Semantics: Issues, Boards, and Milestones - -Each Gitea planning primitive tracks a distinct dimension of engineering reality: -- **Issue State (`Open` vs. `Closed`)**: Deliverable completion on `main`. -- **Board State (Columns: *Backlog*, *Ready*, *Work in Progress*, *Review*, *Completed*)**: Spatial workflow stage in the active pipeline. -- **Milestone**: Strategic delivery horizon (capacity-driven or time-bounded release boundary). - -### Canonical 5-Column Pipeline & Semantic Colors (Deep Signal Palette) - -| Sorting | Canonical Title | Role Aliases (Matched Case-Insensitively) | Hex Color | Default | Transition Owner | -| :--- | :--- | :--- | :--- | :--- | :--- | -| `0` | **Backlog** | `backlog`, `to-do`, `todo`, `icebox`, `triage` | `#475569` (Slate Gray) | `true` | `gitea-plan` (default placement for dependent issues) | -| `1` | **Ready** | `ready`, `next`, `up next`, `queued`, `groomed` | `#1d76db` (Signal Blue) | `false` | `implement-slice` (Step 1 preflight readiness check) | -| `2` | **Work in Progress** | `work in progress`, `in progress`, `wip`, `doing`, `active` | `#d97706` (Warm Amber) | `false` | `implement-slice` (Step 4 worker start) | -| `3` | **Review** | `review`, `in review`, `qa`, `testing`, `verification` | `#6d28d9` (Royal Purple) | `false` | `implement-slice` (Step 7 final-HEAD pass) / `gitea-pr` | -| `4` | **Completed** | `completed`, `done`, `closed`, `shipped` | `#15803d` (Forest Green) | `false` | `gitea-pr` (on owner-authorized merge) / `implement-slice` | - -### Board Provisioning & Non-Destructive Reconciliation (`gitea-plan`) -1. **Create if missing**: When `Project Board Policy` is `Recommended` or `Required` and no open board exists, create one with `gt project create "<title>" --template none -d "<desc>" --json id,title,url`, then `POST` the 5 canonical columns (`sorting: 0..4`) with their Deep Signal hex colors and set `Backlog` as `default: true` (using the recipes in `gt-usage`). -2. **Reconcile in place if existing**: Never assume an existing board already adheres to the convention, and never delete columns that hold cards. Query `/projects/<id>/columns`, match existing columns to the 5 roles by their case-insensitive aliases, and `PATCH` matched columns in place (`title`, `color`, `sorting`) so attached cards stay intact. Create only the missing canonical columns via `POST`, and ensure `Backlog` is marked `default: true`. -3. **Pin column IDs in `AGENTS.md`**: Record the resolved Project Board ID and `{Backlog, Ready, Work in Progress, Review, Completed -> column_id}` map in the repository's `AGENTS.md` planning contract so `implement-slice` and `gitea-pr` move cards without guessing names. - -### Meaningful Conflict Reconciliation -Never mechanically mirror or silently mutate state. Instead, detect and report semantic conflicts: -- **Zombie In-Progress**: Issue or PR is closed on Gitea, but its card still sits in *Backlog*, *Ready*, *Work in Progress*, or *Review* on the board. -- **Premature Completed**: Card is moved to *Completed*, but the issue remains open or lacks a merged PR / commit on `main`. -- **Review Orphan**: Card sits in *Review*, but no active PR or static review packet exists. -- **Horizon Divergence**: Open issue is assigned to a milestone that is closed or diverges from the active milestone in `ROADMAP.md`. - ---- - -## 3. Planning Ceremony Tiers & Project Board Policy - -| Tier | Typical Work | Gitea Primitives | Project Board Policy | Decomposition Rule | -| :--- | :--- | :--- | :--- | :--- | -| **Small** | Single-step bugfix, documentation tweak, dependency bump, routine chore | 1 Issue linked directly to 1 PR / Commit | **Omitted by Policy** (issue tracker suffices) | Zero milestones. Zero project boards. Keep description concise (Context, Solution, Acceptance Criteria). | -| **Medium** | Vertical feature slice, multi-step refactor, performance spike (2 to 5 issues) | 1 Milestone + 2 to 5 Issues | **Recommended** (5-column Kanban: *Backlog*, *Ready*, *Work in Progress*, *Review*, *Completed*) | Each issue has its own branch and PR. All issues include explicit numbered acceptance criteria and test seams. | -| **Large** | Architectural epic, platform cutover, multi-service evolution | Roadmap Doc + Rolling Milestones + Deliverable Issues | **Required** (Board coordinates rolling horizons) | Source of truth remains in repo docs (`ARCHITECTURE.md`, `ROADMAP.md`, ADRs). Gitea coordinates rolling execution. | - -**Deterministic Output Headers**: Every planning proposal must explicitly state both headers before asking for approval: -```markdown -### Project Board Policy: <Omitted|Recommended|Required> (Rationale) -### Reproducibility Audit: <Passed | Remediated> (Subagent: `<conversation-id>` | `Omitted: Small tier`) -``` - ---- - -## 4. Independent Zero-Context Reproducibility Audit (`Medium` and `Large` Mandatory) - -Before presenting a `Medium` or `Large` decomposition for approval (Step 5), spawn a clean-room audit subagent to verify plan reproducibility without conversational context and record its `<conversation-id>` in the `### Reproducibility Audit:` header: - -### Input Manifest (Strict Clean-Room) -The auditor receives strictly raw artifacts and pinned repository state: -1. Pinned repository root and commit SHA. -2. Canonical specifications (`docs/specs/*.md`) and `ROADMAP.md`. -3. Proposed raw issue titles, descriptions, and acceptance criteria markdown. -4. Proposed milestone and board specifications. -5. Declared asset paths and prerequisite environment variables. - -### Auditor Report Schema -The auditor reports across five explicit sections: -1. **Reconstructed from Source Artifacts**: Scope and sequence directly supported by source text. -2. **Inferred Requirements**: Deductions made from titles or conventions lacking explicit spec text. -3. **Undetermined Seams**: Gaps or ambiguities that could not be resolved without guessing. -4. **Materiality Classification**: - - *Material*: Forces an implementer to guess about scope, behavior, acceptance, or prerequisites. - - *Non-Material*: Cosmetic or self-evident convention. -5. **Concrete Remediation Plan**: Specific edits to specs, assets, or criteria to resolve material ambiguities. - ---- - -## 5. Rolling Horizons for Large Projects - -When planning large epics, avoid waterfall decomposition where every future task is pre-created as an issue weeks before implementation: -1. **Active Milestone (Immediate Horizon)**: Decomposed into 2 to 5 concrete deliverable issues with falsifiable acceptance criteria. -2. **Future Milestones (Deferred Horizons)**: Represented as high-level milestones or single coarse placeholder issues in Gitea. -3. **Architecture Synchronization**: Update repository docs (`reconcile-docs`) before decomposing the next rolling milestone. - ---- - -## 6. Multi-Repository Organizations and Shared Boards - -When planning across multi-repository architectures (where an organization hub coordinates multiple deliverable repositories or services): -- **Root Kanban at Organization Level**: Create the shared board at the organization level (`gt project create "<title>" --org <org> --template none`) and reconcile the 5 canonical columns. Do not isolate tracking into separate child repository boards. -- **Attach Child Issues to Org Board**: Deliverable issues and pull requests created in child repositories attach to the organization board via `gt issue create ... -p <project-id>` or `gt issue edit <number> -R <owner/repo> --add-project <project-id>`. -- **Hub Documentation Alignment**: Architectural strategy, shared documentation, and roadmaps remain centralized in the hub repository, while the organization-level Kanban board coordinates unified cross-repo delivery status. diff --git a/skills/gitea-plan/references/tea-cli.md b/skills/gitea-plan/references/tea-cli.md deleted file mode 100644 index 1681029..0000000 --- a/skills/gitea-plan/references/tea-cli.md +++ /dev/null @@ -1,26 +0,0 @@ -# [DEPRECATED] Tea CLI Subroutines - -> **Notice**: Upstream `tea` CLI is archived and officially deprecated in favor of `gt` (`gitea/cli`). -> For verified command patterns, JSON extraction discipline, and sovereign instance conventions, use the official skill: -> **`skills/gt-usage/`** and its reference manual **`skills/gt-usage/references/commands.md`**. - -This document is preserved for historical reference and legacy instance migrations only. - ---- - -## Legacy Commands Reference (Archived) - -### 1. Issue Management (Legacy) -```sh -tea issues create --title "<title>" --description "<description>" -tea issues list -tea issues edit <index> --title "<new-title>" -tea issues close <index> -``` - -### 2. Milestone Management (Legacy) -```sh -tea milestones create --title "<milestone-title>" --description "<overview>" -tea milestones list -tea milestones close "<milestone-title>" -``` diff --git a/skills/gitea-pr/SKILL.md b/skills/gitea-pr/SKILL.md deleted file mode 100644 index 7e6a280..0000000 --- a/skills/gitea-pr/SKILL.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -name: gitea-pr -description: >- - Manage pull request lifecycle on Gitea: verify branch readiness, synthesize structured PR - descriptions from code-review and verify-slice evidence packets, link issues, digest review - feedback, and report merge readiness. Not for code inspection: use code-review. Not for - runtime QA: use verify-slice. Not for Git branch, commit, or merge mechanics: use git-manager. ---- - -# Gitea PR - -## Use when -- Opening or updating a pull request on Gitea after implementing an issue or feature. -- Synthesizing static code review and runtime verification evidence into a reviewable PR. -- Tracking review comments, requested changes, and CI checks toward merge readiness. -- Not for static code inspection or publishing PR review blocks: use `code-review`. -- Not for runtime behavioral verification: use `verify-slice`. -- Not for branch creation, committing, rebasing, or local history integration: use `git-manager`. - -## Steps -1. **Verify branch readiness.** Confirm the local working tree is clean (`git status --short`), - the branch tracks an upstream remote (`git rev-parse @{u}`), unpushed commits are pushed, - and the target base branch exists on the remote. -2. **Collect review and verification evidence.** Inspect outputs from preceding skills: - - `code-review`: Static provenance, covered commits/diff fingerprint, findings disposition, - and overall recommendation (`Ready`). - - `verify-slice`: Runtime evidence ledger across behavioral, security, and state checks, - confirming zero unhandled `FAIL` outcomes. - If either packet is missing or stale relative to current `HEAD`, stop and run that skill first. -3. **Draft structured PR description.** Compose the PR body following - [references/pr-lifecycle.md](references/pr-lifecycle.md): - - Issue Linkage: `Closes #<issue-index>`. - - Summary of Changes: Problem, solution, and scope boundary. - - Static Review Provenance: Base/head SHAs, diff SHA256, and 4-axis disposition. - - Runtime Verification Ledger: Markdown table of executed checks and outcomes. - - Residual Risks and Rollback: Operational considerations and reversibility. -4. **Present for human approval.** Present proposed title, target base branch, milestone, - and description body to the user per `profile/AGENTS.md`. Stop for confirmation before - creating or editing the pull request. -5. **Create or update pull request via `gt pr` and move card to `Review`.** Run verified - commands from [references/gt-pulls.md](references/gt-pulls.md): - `gt pr create -t "<title>" -B "<base>" -H "<branch>" -F <body-file> --json number,url`. - Pass `--draft` if work remains in progress. Extract verified PR number and URL, and ensure - the linked issue card is in `Review` (`Work in Progress -> Review`) on the project board. -6. **Track review feedback, enforce finding triage, merge on owner approval, and move card `Review -> Completed`.** - Inspect status checks (`gt pr checks <number>`), mergeability - (`gt pr view <number> --json mergeable,review_decision`), and review comments - (`gt pr review comments <number>`). If the current PR head lacks a published `code-review` - comment, hand off to `code-review`. Never report `Ready for Merge` while any `code-review` - finding is `Pending Triage`: every finding must first be (A) fixed in-branch, (B) promoted - to a live tracker (Gitea issue or `todo.txt` via `tuxedo add`) and linked in a PR reply, or - (C) explicitly accepted by the owner as a permanent trade-off. When checks pass and all - findings are triaged/resolved, report `Ready for Merge`. Once the owner explicitly authorizes - merge, run `gt pr merge <number>` and move the linked issue card `Review -> Completed`. - -## Your call -- **PR title and description approval**: review and approve the draft PR content and issue linkage. -- **Review feedback triage**: decide how to address review comments (rework, clarification, deferral). -- **Merge and release authorization**: decide when to merge the PR into the target base branch. - -## Done when -- Pull request is created or updated in Gitea with complete evidence provenance, and its current - review and mergeability status is reported to the user. - -## Hands off to -- `code-review`: if the PR head lacks a static review comment or the diff changed (`Suggested Next Step: /code-review <pr-number>`). -- `verify-slice`: if new code requires runtime verification (`Suggested Next Step: /verify-slice`). -- `reconcile-docs`: after merge when docs/milestones shift (`Suggested Next Step: /reconcile-docs`). -- `implement-slice`: after merge when next issue is queued (`Suggested Next Step: /implement-slice #<next-issue>`). -- `git-manager`: to commit review fixes, rebase, or update against base. -- Emit one outcome-matched `Suggested Next Step` on every standalone turn (including when CI is pending after PR creation: `/code-review <pr-number>` or `/gitea-pr <pr-number>`) per [skeleton](../build-skill/references/skeleton.md). diff --git a/skills/gitea-pr/references/gt-pulls.md b/skills/gitea-pr/references/gt-pulls.md deleted file mode 100644 index d487335..0000000 --- a/skills/gitea-pr/references/gt-pulls.md +++ /dev/null @@ -1,111 +0,0 @@ -# Verified `gt pr` Pull Request Subroutines - -Reference for `gitea-pr`. Canonical, verified syntax for managing pull requests, status checks, and review threads via `gt`. - -## 1. Inspecting Pull Requests - -### List Pull Requests -```bash -# List open PRs with structured fields -gt pr list --json number,title,state,url - -# List all PRs including closed/merged -gt pr list --state all --json number,title,state,url -``` - -### View Pull Request Details & Status Checks -```bash -# View basic PR details -gt pr view <number> - -# Inspect mergeability and review decision -gt pr view <number> --json number,title,state,mergeable,review_decision,url - -# Show status of CI checks on the head commit -gt pr checks <number> - -# Wait for CI checks to complete -gt pr checks <number> --watch -``` - ---- - -## 2. Creating and Updating Pull Requests - -### Create a Pull Request -- Create standard PR with multi-line body from file: - ```bash - gt pr create -t "<title>" -B "<base-branch>" -H "<feature-branch>" -F <body-file> --json number,url - ``` -- Create as a Draft / WIP PR: - ```bash - gt pr create -t "WIP: <title>" --draft -B "<base-branch>" -H "<feature-branch>" -F <body-file> --json number,url - ``` -- Assign milestone and project: - ```bash - gt pr create -t "<title>" -B "<base>" -H "<branch>" -m <milestone-id> -p <project-id> -F <body-file> --json number,url - ``` - -### Edit a Pull Request -```bash -# Update title or base branch -gt pr edit <number> --title "<new-title>" - -# Mark a draft PR as ready for review -gt pr ready <number> -``` - ---- - -## 3. Review Comments and Discussions - -### List Review Comments -```bash -# List inline review comments -gt pr review comments <number> - -# View PR activity and top-level comments -gt pr timeline <number> -``` - -### Reply to Review Comments -```bash -# Reply to an inline comment -gt pr review reply <number> <comment-id> "Fixed in <sha>" - -# Add top-level comment -gt pr comment <number> -b "<comment-text>" -``` - -### Resolve Review Comments -```bash -# Mark an inline thread as resolved -gt pr review resolve <comment-id> - -# Reopen an inline thread -gt pr review unresolve <comment-id> -``` - -*(Publishing new `code-review` PR review blocks is owned by `code-review` in `skills/code-review/references/finding-schema.md`.)* - ---- - -## 4. Closing and Merging Pull Requests - -### Close or Reopen PR -```bash -gt pr close <number> -gt pr reopen <number> -``` - -### Merge Pull Request and Move Card `Review -> Completed` (Requires Explicit Human Authorization) -Release and merge authority belongs exclusively to the human owner. Once the owner explicitly approves merging: -```bash -# 1. Merge pull request (fast-forward / merge commit, or --squash --delete-branch) -gt pr merge <number> - -# 2. Extract global issue ID of the linked issue and move its project board card to Completed -issue_global_id=$(gt issue view <issue-number> --json id -q .id) -gt api -X POST /repos/{owner}/{repo}/projects/<project-id>/issues/${issue_global_id}/move -F column_id=<completed-col-id> -``` -Do not attach the PR itself (`-p <project-id>`) as a duplicate board card when the linked issue is already on the board; if a PR card was attached separately, move it to `Completed` as well. diff --git a/skills/gitea-pr/references/pr-lifecycle.md b/skills/gitea-pr/references/pr-lifecycle.md deleted file mode 100644 index 3ca88f6..0000000 --- a/skills/gitea-pr/references/pr-lifecycle.md +++ /dev/null @@ -1,90 +0,0 @@ -# Pull Request Lifecycle and Evidence Synthesis - -Reference for `gitea-pr`. Defines PR states, evidence synthesis template, and feedback triage workflow. - -## 1. Pull Request Lifecycle States - -```text -Draft (WIP) -> Review -> Changes Requested -> Ready for Merge -> Merged - | | - +-- [Rework/Fix] ----+ -``` - -1. **Draft (WIP)**: PR opened early for visibility. In Gitea, prefixed with `WIP:` or flagged `--draft`. CI may run; reviews are informal. -2. **Review**: Feature complete, working tree clean, static `code-review` and runtime `verify-slice` evidence packets attached. Ready for formal audit. -3. **Changes Requested**: Reviewer identified defects, missing tests, or security concerns. Agent addresses feedback, commits fixes via `git-manager`, and refreshes evidence. -4. **Ready for Merge**: All review threads resolved, every `code-review` finding has completed one of the 3 mandatory exits (fixed in-branch, promoted to an open Gitea issue or `todo.txt` task with a linked reply, or explicitly granted permanent `Accepted Trade-off` by the human owner), static review confirms `Ready` on current `head_sha`, runtime checks pass, and mergeability is green. Linked issue card sits in `Review`. -5. **Completed (Merged)**: After explicit authorization by the human owner, `gitea-pr` merges the PR into the target base branch (`gt pr merge <number>`), verifies Gitea auto-closed the linked issue (`Closes #<id>`), and moves the issue card `Review -> Completed` on the project board. - ---- - -## 2. Standard PR Description Template - -Every PR description synthesizes static provenance and runtime evidence into a transparent record: - -```markdown -Closes #<issue-index> - -## Summary of Changes -<Concise overview of what was built, why, and what architectural decisions were made.> - -## Scope & Non-Goals -- **In Scope**: <Itemized list of changes included in this PR> -- **Out of Scope**: <Explicitly deferred items or non-goals> - -## Static Review Provenance (`code-review`) -- **Base Commit**: `<base-sha>` -> **Head Commit**: `<head-sha>` -- **Committed Diff Fingerprint**: `sha256:<hash>` -- **Axes Breakdown**: - - Spec & Scope: Pass - - Standards & Smells: Pass - - Seam & Test Integrity: Pass - - Defensive Invariants: Pass -- **Review Status**: `Ready` - -## Runtime Verification Ledger (`verify-slice`) -| Check ID | Perspective | Scope | Description | Outcome | -| :--- | :--- | :--- | :--- | :--- | -| RV-01 | Behavioral / Seam | local | Unit & integration suite execution | PASS | -| RV-02 | State & Concurrency | local | Race condition & lock invariant check | PASS | -| RV-03 | Security / Host Boundary | local | Host socket validation boundary | PASS | - -## Residual Risks & Operational Considerations -- **Environment Prerequisites**: <Any required environment variables, sockets, or permissions> -- **Reversibility**: <How to cleanly revert this slice if unexpected regressions occur> -``` - ---- - -## 3. Review Feedback Triage Workflow - -When comments or change requests arrive on a PR: - -1. **Extract review comments**: - ```sh - gt pr review comments <number> - ``` -2. **Categorize comments**: - - *Defects & Invariants*: Logic errors, broken tests, edge-case crashes (require code fix). - - *Spec & Scope Clarifications*: Questions about intent or architectural fit (require response or doc update). - - *Nits / Polish*: Minor style preferences that do not violate repo standards (human owner decides priority). - Findings published from a `code-review` comment block arrive pre-labelled with their ID, disposition, and follow-up route (`record` or `issue`); keep those labels instead of re-categorizing. -3. **Implement fixes on the feature branch**: - - Use `tdd` or direct edits. - - Commit fixes incrementally following `git-manager` conventions (e.g. `fix(gitea-pr): address review feedback`). -4. **Re-verify after changes**: - - Run `code-review` to confirm the updated diff fingerprint is clean. - - Run `verify-slice` to substantiate runtime assertions. -5. **Reply and resolve threads via `gt pr`**: - - Reply to comment: `gt pr review reply <number> <comment-id> "Fixed in <sha>"` - - Resolve thread: `gt pr review resolve <comment-id>` -6. **Push updates to remote**: - - `git push origin <branch>` - ---- - -## 4. Release Authority Guardrail - -Automated skills and checks inform the human owner; they never make the merge decision independently: -- Neither passing unit tests nor a `Ready` code review implies permission to execute `gt pr merge`. -- The human owner reviews the consolidated ledger, assesses residual risks, and explicitly authorizes merge execution. diff --git a/skills/gitea-pr/references/tea-pulls.md b/skills/gitea-pr/references/tea-pulls.md deleted file mode 100644 index c5f8501..0000000 --- a/skills/gitea-pr/references/tea-pulls.md +++ /dev/null @@ -1,28 +0,0 @@ -# [DEPRECATED] Tea CLI Pull Request Subroutines - -> **Notice**: Upstream `tea` CLI is archived and officially deprecated in favor of `gt` (`gitea/cli`). -> For verified command patterns and JSON recipes, use **`skills/gitea-pr/references/gt-pulls.md`**. - -This document is preserved for historical reference and legacy instance migrations only. - ---- - -## Legacy Commands Reference (Archived) - -### 1. Inspecting Pull Requests (Legacy) -```sh -tea pulls list -tea pulls <index> -``` - -### 2. Creating Pull Requests (Legacy) -```sh -tea pulls create --title "<title>" --base "<base>" --head "<head>" --description-file - -``` - -### 3. Review Comments (Legacy) -```sh -tea pulls review-comments <index> -tea pulls reply <index> <comment-id> "<reply-text>" -tea pulls resolve <comment-id> -``` diff --git a/skills/implement-slice/SKILL.md b/skills/implement-slice/SKILL.md deleted file mode 100644 index 5f14db0..0000000 --- a/skills/implement-slice/SKILL.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -name: implement-slice -description: >- - Orchestrates end-to-end delivery of a Gitea issue or vertical feature slice - across delegated implementation and QA subagents, checkpoint commits, static - review, and pull request packaging. Never edits implementation code or - self-certifies QA. Not for decomposing epics into issues (use gitea-plan) or - executing a single already-delegated worker task (use tdd and git-manager). ---- - -# Implement Slice - -## Use when -- Delivering an approved Gitea issue or bounded feature slice end to end via coordinated subagents. -- Coordinating multi-task checkpoints, pre-committed QA rubrics, and final review gates. -- Not for decomposing raw epics into milestones and issues: use `gitea-plan`. -- Not inside an already-delegated implementation worker task: follow the assigned worker contract (`tdd`, `git-manager`) without re-invoking `implement-slice`. - -## Steps -1. **Preflight branch check, readiness audit, and `Backlog -> Ready`.** Check session mode per `profile/AGENTS.md`. Classify working tree per [handoff-contracts](references/handoff-contracts.md) (`CLEAN_BASE`, `ADOPTABLE_DIFF`, `CONFLICTING_STATE`, `WRONG_BASE`). Stop on conflicts. Read target Gitea issue/milestone/board state via `gt issue`, `gt milestone`, direction docs (`ARCHITECTURE.md`, `ROADMAP.md`, `docs/designs/*.md`, `AGENTS.md`), and `git status --short`. Reconcile issue acceptance criteria against current `HEAD` (handing off to `reconcile-docs` if canonical design docs drifted during upstream slices, or updating the Gitea issue after owner approval) and, when `--dry-run` is not active, move the issue card `Backlog -> Ready` on the project board. Hand off to `gitea-plan` if tracking issues must be created first. -2. **Select orchestration topology (`complexity x risk`).** Combine planning size with assurance risk per [orchestration-tiers](references/orchestration-tiers.md). Keep pure-orchestrator invariants: retain plan, status, commit SHAs, QA dispositions, blockers; never edit implementation files, repair Git via code edits, self-certify QA, or ingest full test logs unless resolving a failure. -3. **Lock Planned Workflow and pre-committed rubrics.** Formulate the Planned Workflow using the Canonical Node Schema (5-tuples: `node_id`, `claim`, `method`, `executor`, `pass_condition`), decomposing multi-module slices into bottom-up vertical per-submodule `Red -> Green` tasks rather than horizontal "all tests first, all code second" batching per [orchestration-tiers](references/orchestration-tiers.md). Project a dynamic Mermaid diagram deriving directly from node IDs with visible rework edges. If `--dry-run` is active, halt after displaying the plan (enforce 0 file changes, 0 commits, 0 remote calls). Hard gate: pause for human approval. -4. **Move card `Ready -> Work in Progress`, start slice clock, and delegate.** Once the human approves Step 3, move the issue card `Ready -> Work in Progress` on the project board and record `started_at=$(date +%s)` per [handoff-contracts](references/handoff-contracts.md). Govern branch/worktree lifecycle through `git-manager` per [orchestration-tiers](references/orchestration-tiers.md). Dispatch worker subagent(s) with the Implementation Assignment in [handoff-contracts](references/handoff-contracts.md). Never run concurrent workers in the same working tree. Update the runtime Execution Record table as nodes change state. -5. **Audit worker reports and run rubric QA.** Verify worker reports via read-only Git checks. Spawn read-only QA subagents running `verify-slice` against pre-committed rubrics. Update Execution Record with concrete evidence (SHA, exit codes). -6. **Triage outcomes and route rework.** Classify failures using [handoff-contracts](references/handoff-contracts.md): route code defects to existing worker via `send_message`; record justified rubric amendments if criteria change. Loop Steps 4-6 until all nodes pass. -7. **Enforce final-HEAD evidence, log elapsed time, move card `Work in Progress -> Review`, and integrate.** Confirm `code-review` (`Ready`) and `verify-slice` match the exact final `HEAD` and base, log elapsed issue time (`POST .../issues/<index>/times`) and move the issue card `Work in Progress -> Review` on the project board per [handoff-contracts](references/handoff-contracts.md). Present the Execution Deviation Report (skipped/added checks, rework iterations, scope drift; if scope drift evolved a contract in `docs/designs/*.md` or `ARCHITECTURE.md`, prompt to run `reconcile-docs` before the next slice). Integrate per [orchestration-tiers](references/orchestration-tiers.md) Policy Matrix: fast-forward merge (and move card `Review -> Completed`) if repo `AGENTS.md` permits and user approves, else hand off to `gitea-pr`. - -## Your call -- **Session mode**: decide whether to switch from `learning` to `delivery` before autonomous delegation. -- **Planned workflow and rubrics**: approve task breakdown, node 5-tuples, assurance tier, and QA rubrics before workers spawn. -- **Rubric amendments, live-infra, and trade-offs**: approve rubric criteria changes, authorize `live-infra` checks, and adjudicate review conflicts. -- **Integration authorization**: authorize direct merge to main or PR creation and merge. - -## Done when -- All slice checkpoints are committed on a clean target branch, `code-review` (`Ready`) and `verify-slice` match the same final `HEAD`, the Execution Deviation Report is recorded, and the branch is integrated per policy. - -## Hands off to -- `gitea-plan`: when goals or epics require milestone and issue decomposition before slice execution. -- `git-manager`: to create/integrate slice branches and worktrees, commit worker checkpoints, or stop on conflicts. -- `tdd`: inside workers for seam-level red-green development, or standalone test hardening (`Suggested Next Step: /tdd <test-path>`). -- `verify-slice`: inside QA subagents for pre-committed chunk and final-`HEAD` runtime verification. -- `code-review`: for final-slice 4-axis static and strategic alignment inspection. -- `diagnose`: when an unexpected failure requires evidence-first root-cause investigation. -- `gitea-pr`: when policy or remote CI mandates a PR and final-`HEAD` packets are ready (`Suggested Next Step: /gitea-pr #<issue>`). -- `reconcile-docs`: when design specs drifted (`Suggested Next Step: /reconcile-docs`); on `--dry-run` or post-merge next slice, emit `Suggested Next Step: /implement-slice #<issue>`. diff --git a/skills/implement-slice/references/handoff-contracts.md b/skills/implement-slice/references/handoff-contracts.md deleted file mode 100644 index 5ded128..0000000 --- a/skills/implement-slice/references/handoff-contracts.md +++ /dev/null @@ -1,147 +0,0 @@ -# Handoff Contracts, Failure Triage, and Final-HEAD Invariant - -Reference for `implement-slice`. Every delegation uses explicit, bounded schemas so subagents execute deterministically and return compact evidence packets. - -## 1. Preflight Branch and Worktree Safeguards - -Before decomposing or delegating work, inspect `git status --short` and `git branch -v`: - -| Working Tree & Branch State | Classification | Orchestrator Action | -| :--- | :--- | :--- | -| **Clean tree on target base branch** | `CLEAN_BASE` | Proceed directly to plan formulation. | -| **Tree contains uncommitted changes matching the target slice** | `ADOPTABLE_DIFF` | Offer to adopt uncommitted changes into the new slice branch. | -| **Tree has uncommitted edits to unrelated files or sits on an unmerged PR branch** | `CONFLICTING_STATE` | **Hard Stop.** Report active branch and diff stat. Offer structured options (stash, commit to existing branch, switch). | -| **Current branch does not match intended base** | `WRONG_BASE` | **Hard Stop.** Halt and prompt user to switch to target base before branching. | - ---- - -## 2. Implementation Assignment (Orchestrator -> Worker) - -Provide before spawning (or messaging) an implementation worker: - -- **Session Mode & Anti-Recursion**: Active mode (`mode: delivery`) plus explicit instruction: execute this task directly using `tdd` and `git-manager`; do not invoke `implement-slice` or spawn nested workers unless explicitly authorized. -- **Task ID & Objective**: Concrete deliverable outcome and linked Gitea issue (`#<id>` when applicable). -- **Assigned Workspace & Branch**: Exact repository/worktree path and non-default working branch name. -- **Scope Boundary**: In-scope files/interfaces and explicit out-of-scope exclusions (preventing opportunistic refactors). -- **Acceptance Criteria**: Numbered, falsifiable conditions this task must satisfy. -- **Checkpoint Expectation**: Expected coherent commit boundary (or boundaries) following `git-manager` Conventional Commits. -- **Required Compact Report**: Request concise structured output (no raw multi-hundred-line logs unless a check fails) and instruct the worker to suppress standalone `Suggested Next Step` footers. - -## 3. Implementation Report (Worker -> Orchestrator) - -Require each worker to return: - -- **Summary of Changes**: Touched files/seams and 2-5 bullet summary of what changed. -- **Criteria Coverage**: Mapping from assigned acceptance criteria to test or command proof. -- **Verification Summary**: Commands run (`pytest`, `cargo test`, typecheck, lint) with exit codes and pass counts. -- **Checkpoint Commits**: Exact commit SHA(s) and subject lines created, plus confirmation that `git status --short` is clean. -- **Scope Deviations or Open Risks**: Any unexpected constraint, untouched edge case, or blocker encountered (`None` if clean). - ---- - -## 4. Pre-Committed QA Rubric Assignment (Orchestrator -> QA Subagent) - -The rubric is written and approved during Step 3 (before implementation begins). When spawning the QA subagent: - -- **Target Revision & Workspace**: Exact commit SHA (`HEAD`), base ref, and workspace path. State clearly: do not modify tracked files; leave `git status --short` clean. -- **Assurance Tier & Mode**: `Lightweight`, `Standard`, or `High-Assurance` per `verify-slice`. For `High-Assurance` black-box runs, withhold the diff narrative and worker self-audit. -- **Pre-Committed Falsifiable Checks**: Numbered checks with scope (`local` vs. `live-infra`), exact pass conditions, `FAIL if ...` signals, and any `code-review` Step 6 `RV-*` checks. -- **Authorization Boundary**: Explicitly state whether any `live-infra` check has human owner authorization for this run (default: unauthorized -> record `BLOCKED (out-of-bounds)`). Suppress standalone `Suggested Next Step` footers; return only the compact QA report. - -## 5. QA Report (QA Subagent -> Orchestrator) - -Follows the `verify-slice` disposition contract: - -- **Tested Revision**: Confirmed `HEAD` SHA and clean working-tree verification. -- **Check Dispositions**: Per-criterion result (`PASS`, `FAIL`, `BLOCKED (env/fixture)`, `BLOCKED (out-of-bounds)`, or `INCONCLUSIVE`) with concise observable evidence. -- **Confirmed Defects**: Reproducible failure steps, severity, and expected vs. actual behavior. -- **Rubric Fitness**: Explicit note if any rubric criterion proved ambiguous, untestable, or mismatched against repository reality. - ---- - -## 6. The Tripartite Workflow Contract Schemas - -### A. Planned Workflow Schema (Step 3 Gate) -```markdown -### Planned Workflow -- **Task Breakdown**: - - `TASK-01`: <Objective> (Role: Worker, Scope: <files>, Commits: <expected-commits>) -- **Verification Plan**: - - `CHK-01`: Claim: <invariant>, Method: <cmd>, Executor: <role>, Pass: <condition>, Failure: <route> -- **Workflow Graph**: - ```mermaid - <dynamic-projection-from-nodes> - ``` -``` - -### B. Execution Record Schema (Steps 4-5 Log) -Updated dynamically in orchestrator turns: -```markdown -| Node ID | Claim / Invariant | Method | Executor | Evidence | Pass Condition | Status | -| :--- | :--- | :--- | :--- | :--- | :--- | :--- | -| `TASK-01` | <claim> | <method> | <role> | Commit `<sha>` | Clean tree | `passed` | -| `CHK-01` | <claim> | <method> | <role> | Exit 0 stdout | Exit 0 | `passed` | -``` - -### C. Deviation Report Schema (Step 6 Handoff) -```markdown -### Execution Deviation Report -- **Skipped Checks**: <None | List of skipped checks with explicit rationale> -- **Added Checks**: <None | New checks introduced in response to findings> -- **Rework Iterations**: <0 | Details of remediation loops and commit references> -- **Scope Drift**: <None | Differences between planned and actual seams; if an approved contract evolution leaves `docs/designs/*.md` or `ARCHITECTURE.md` stale, flag a `reconcile-docs` handoff before the next slice> -``` - -### Dynamic Mermaid Projection Rules -- **Derive directly from nodes**: Nodes in the graph must match `node_id`s from the planned workflow table. -- **Expose falsification routes**: Graph edges must explicitly show failure paths (e.g. `QA -- "Fail (rework)" --> Worker`). -- **Never paste generic templates**: Every diagram must reflect the exact slice tasks and assurance checks. - ---- - -## 7. Failure Triage and Rubric Amendment Routing - -Never relay "QA failed" blindly. Classify each non-passing outcome and route to the right owner: - -| Observed Outcome | Classification | Orchestrator Action | -| :--- | :--- | :--- | -| Behavioral check `FAIL` or `code-review` `Needs Rework` | **Implementation or test defect** | Send targeted actionable feedback (check ID, repro, expected contract) to the existing worker via `send_message` when live. | -| Acceptance criterion lacks public-seam test proof | **Missing seam test** | Route back to the existing worker (`tdd`) to add a non-tautological seam test and commit checkpoint. | -| `BLOCKED (env/fixture)` | **Environment or fixture blocker** | Delegate fixture/devshell repair (`nix-devshell` or worker task) or surface environment blocker to user before judging product code. | -| `BLOCKED (out-of-bounds)` | **Unauthorized `live-infra` boundary** | Preserve exact command and criteria; pause for human owner authorization, operator run, or documented deferral. | -| Symptom contradicts hypotheses across retries | **Unknown root cause** | Stop blind retries; hand off to `diagnose` for evidence-first root-cause investigation. | -| Criterion contradicts actual system architecture or tests the wrong seam | **Defective rubric** | Record an explicit **Rubric Amendment** stating what changed and why. Pause for human approval whenever an amendment relaxes an acceptance criterion or alters slice scope; never silently rewrite criteria to match worker output. | - ---- - -## 8. Final-HEAD Evidence Invariant and Terminal Delivery - -### The Invariant - -> Before `gitea-pr` creates or marks a PR ready (or before terminal delivery when no PR applies), the required `code-review` and `verify-slice` evidence must identify the same final `HEAD` and applicable base revision. Any change to the reviewed diff invalidates affected evidence. - -### Recovery Rules When `HEAD` Advances or Checks Emit - -1. **Post-QA commit**: If `HEAD` changes after `verify-slice` (for example, to address a `code-review` finding or rebase onto base), rerun `verify-slice` against the new `HEAD`. -2. **Post-review commit**: If `HEAD` changes after `code-review`, rerun `code-review` against `<base>...HEAD`. -3. **Emitted `RV-*` runtime checks**: If `code-review` Step 6 emits executable `RV-*` checks, execute them via `verify-slice` against the final `HEAD` before packaging. -4. **Handshake reuse condition**: `verify-slice` may reuse a preceding `code-review` report for static provenance only when its recommendation is `Ready` (including `Ready (Conditional)` once open items are adjudicated by the human owner per `code-review`) and its recorded base SHA, `HEAD` SHA, and working-tree diff fingerprint still match exactly. - -### Conditional Terminal Paths - -- **PR applies**: Once `code-review` (`Ready`) and `verify-slice` (zero unhandled `FAIL`) match final `HEAD`, hand off both packets to `gitea-pr` to draft the PR description, pause for human PR approval, create/update the PR, and report merge readiness. -- **No PR applies** (local repo, approved solo-branch workflow, or bounded spike): Enforce the identical final-`HEAD` evidence invariant, then present the commit range (`<base>..HEAD`), static review disposition, runtime verification ledger, and any open residual-risk decisions directly to the user. - - ---- - -## 9. Project Board Card Transitions Owned by `implement-slice` - -When the repository tracks a Gitea Project Board (resolved from the `AGENTS.md` planning contract or `gt project list`), `implement-slice` owns moving the target issue's card across the pipeline using the `gt-usage` move recipe (`POST /repos/{owner}/{repo}/projects/<project-id>/issues/<global-issue-id>/move -F column_id=<target-col-id>` for repo boards, or `POST /orgs/<org>/projects/<project-id>/issues/<global-issue-id>/move -F column_id=<target-col-id>` for organization-level boards): - -| Step | Transition | Condition | -| :--- | :--- | :--- | -| **Step 1 (Preflight & Readiness)** | `Backlog -> Ready` | Blocking issues are closed, issue acceptance criteria are reconciled against current `HEAD` and `AGENTS.md`, and `--dry-run` is **not** active. | -| **Step 4 (Worker Delegation)** | `Ready -> Work in Progress` | Human owner approved the Step 3 Planned Workflow and implementation branch/worker starts. Also record `started_at=$(date +%s)` in the Execution Record (never use Gitea's global `stopwatch/start`, which blocks parallel issues with `409 Conflict`). | -| **Step 7 (Final-HEAD Gate)** | `Work in Progress -> Review` | Final-`HEAD` `code-review` (`Ready`) and `verify-slice` pass with zero unhandled `FAIL` outcomes. Compute `elapsed=$(( $(date +%s) - started_at ))` (when `started_at` was recorded and `elapsed > 0`) and log it to the issue via `gt api -X POST /repos/{owner}/{repo}/issues/<issue-index>/times -F time=${elapsed}`. | -| **Step 7 (Direct Merge Only)** | `Review -> Completed` | Only when repository policy permits direct fast-forward merge to `main`, human owner approves, and the issue is closed. Otherwise `gitea-pr` owns `Review -> Completed`. | diff --git a/skills/implement-slice/references/orchestration-tiers.md b/skills/implement-slice/references/orchestration-tiers.md deleted file mode 100644 index 6868ae6..0000000 --- a/skills/implement-slice/references/orchestration-tiers.md +++ /dev/null @@ -1,105 +0,0 @@ -# Orchestration Topology, Boundaries, and Workspace Ownership - -Reference for `implement-slice`. Defines how the orchestrator combines existing planning and assurance tiers without redefining them, preserves context efficiency, and prevents workspace contention. - -## 1. Pure-Orchestrator and Context-Budget Invariants - -These boundaries hold across every slice size and risk tier: - -1. **No implementation or self-certified QA**: The orchestrator never edits product or test files, creates ad-hoc fixup commits, executes mutations to repair broken code, or declares runtime QA passing without worker/QA evidence. Read-only inspection (`gt`, `git status`, `git log`, `git diff --stat`, targeted file reads to check a contradiction) is allowed. -2. **Context-budget discipline**: - - **Retain in orchestrator context**: approved slice plan, task dependency status, assigned workspace/branch refs, checkpoint commit SHAs, QA check dispositions, active blockers, and open human decisions. - - **Delegate out of orchestrator context**: full test suite transcripts, build logs, browser traces, and line-by-line edit narratives. Require concise structured reports with exact references (commit SHAs, `path:line` locations, check IDs, or log/artifact paths) and inspect raw output only when resolving a discrepancy or failure. - ---- - -## 2. Combining `Complexity x Risk` (Single-Owner Tier Mapping) - -`implement-slice` does not define new sizing or risk vocabularies; it composes the canonical tiers owned by sibling skills: - -- **Planning size (`Small`, `Medium`, `Large`)**: owned by [`gitea-plan`](../../gitea-plan/references/decomposition-tiers.md). Governs Gitea planning ceremony and task decomposition granularity. -- **Assurance rigor (`Lightweight`, `Standard`, `High-Assurance`)**: owned by [`code-review`](../../code-review/references/axes.md) and [`verify-slice`](../../verify-slice/references/perspectives.md). Governs worker independence, runtime check depth, and static review isolation. - -**Risk override rule**: Always compute assurance rigor from failure consequences, never diff line count alone. Touching authentication, permissions, secrets, payments, concurrent state, data migrations, deployment/infrastructure, destructive operations, or core shared libraries elevates even a `Small` slice to `High-Assurance` verification and review while keeping `Small` planning ceremony. - -| Planning Size x Assurance Rigor | Worker Delegation | Mid-Slice QA (`verify-slice`) | Final Slice Gate (`<base>...HEAD`) | -| :--- | :--- | :--- | :--- | -| **`Small` x `Lightweight`** | 1 implementation worker subagent on slice branch (`tdd` where applicable + `git-manager` checkpoint commit + self-audit). | Skip separate mid-slice QA subagent if deterministic worker evidence satisfies the pre-committed rubric; run final-`HEAD` `verify-slice` Lightweight checks. | Single-pass `code-review` (`Lightweight`) + final-`HEAD` `verify-slice` confirmation. | -| **`Small`/`Medium` x `Standard`** | Sequential worker subagent(s) per task/chunk on slice branch (or isolated worktrees only if tasks are genuinely independent). | Spawn independent rubric QA subagent (`verify-slice` `Standard`) at chunk boundary or slice completion when stateful/UI/API behavior warrants separation. | Independent `code-review` (`Standard`, including strategic alignment) + final-`HEAD` `verify-slice` packet. | -| **Any Size x `High-Assurance`** (or `Large` multi-chunk slice) | Sequential tasks on slice branch or isolated per-task worktrees for independent tracks; strict checkpoint boundaries. | Spawn clean black-box QA subagent (`verify-slice` `High-Assurance`), withholding diff narrative and worker self-audit per `verify-slice` Step 3. | Spawn isolated `code-review` subagents (`High-Assurance`: dedicated Axis 3 `Seam & Test Integrity` subagent + Axes 1/2/4 subagent) + final-`HEAD` `verify-slice` packet (including any emitted `RV-*` checks). | - ---- - -## 3. Branch, Worktree, and QA Ownership Boundaries - -Explicit ownership prevents concurrent working-tree corruption and keeps Git recovery out of the orchestrator: - -| Role | Exact Responsibility | -| :--- | :--- | -| **Orchestrator (`implement-slice`)** | Decides branch/worktree topology in the approved plan, assigns each worker an explicit workspace path and target branch, and verifies resulting refs/SHAs read-only. Never repairs broken Git state by editing files or committing directly. | -| **`git-manager`** | Owns and governs branch creation, `.worktrees/<task>` creation/removal, branch integration (`rebase`, `merge`, `cherry-pick`), conflict stops, and evidence-first `reflog` recovery. On any merge/rebase conflict or unfamiliar dirty tree, `git-manager` stops immediately for human decision. | -| **Implementation Worker** | Modifies code and tests only inside its assigned workspace and scope boundary; runs local checks via `tdd` and commits verified checkpoints autonomously on the non-default working branch per `git-manager`. | -| **QA Subagent (`verify-slice`)** | Evaluates a pinned commit SHA (`HEAD`) without modifying tracked repository files. Writes temporary fixtures or scratch state only in isolated temp directories (such as `mktemp -d`), leaving `git status --short` clean. | - -### Contention and Worker Reuse Rules - -1. **Sequential default**: Prefer sequential task delegation on a single slice branch when tasks touch related modules or take minutes rather than hours; parallel worktrees pay an integration cost. -2. **Mandatory isolation for concurrency**: Never run two implementation subagents concurrently in the same working directory. Concurrent implementation tasks require separate `git-manager` worktrees and an explicit integration step before final-`HEAD` review. -3. **Stateful worker reuse**: Retain each worker's subagent `conversationId`. When QA or `code-review` routes actionable rework back on a task, message that existing worker (`send_message`) so it retains design context instead of spawning a cold worker. Spawn a fresh worker only for a distinct new task or when the original worker session is unavailable. - ---- - -## 4. Canonical Workflow Node Schema & Proportional Scaling - -Every task, check, and gate in the slice workflow is represented by a structured node to enable inspectability and comparison: - -### Mandatory Core Fields (All Nodes) -- **`node_id`**: Stable identifier (e.g. `TASK-01`, `CHK-UNIT-01`, `GATE-MERGE`). -- **`claim`**: The observable behavior, contract, or invariant being asserted. -- **`method`**: Concrete execution mechanism or harness (e.g. `node:test`, `pytest -m contract`, `git diff --check`, manual user review). -- **`executor`**: Specific assigned role (`Implementation Worker`, `Independent QA Subagent`, `Reviewer Subagent`, `Human Owner`). -- **`pass_condition`**: Deterministic pass/fail criterion (e.g. exit code 0, regex match, zero uncommitted files). -- **`status`**: Evidence-backed execution state: - * `planned`: Defined, not yet executed. - * `blocked`: Cannot run due to unmet prerequisite. - * `skipped`: Deliberately omitted, with recorded rationale. - * `failed`: Ran and failed pass condition (failure log recorded). - * `passed`: Verified with concrete evidence. Missing evidence strictly prohibits `passed`. - -### Optional / Scaled Fields (Omitted or Simplified for Simple Slices) -- **`failure_route`**: For routine/doc tasks, defaults to *"rework in-place and rerun affected check"*; complex slices specify explicit rework loops across delegated subagents. -- **`evidence`**: Simple doc/format tasks record exit code and commit SHA; complex code tasks attach stdout, DOM snapshots, or test run logs. -- **Separate QA Executor**: Documentation and routine edits use the implementation agent directly; high-risk slices mandate independent verifier subagents. - -### Vertical Submodule TDD Decomposition (Anti-Horizontal Batching) -When a slice spans multiple modules or layers (for example, `protocols.py` -> `ssap.py` -> `pointer.py` -> `manager.py`), never decompose the workflow horizontally into `TASK-00: write all tests for every module` followed by `TASK-01..02: implement all modules`. Instead, sequence tasks as **bottom-up vertical Red->Green cycles per submodule or capability**: -1. Each submodule task writes its own focused Red test(s) (committing a Red `@pytest.mark.xfail(strict=True)` checkpoint when requested by repo SOP), implements that submodule to turn its tests Green, and commits the Green checkpoint before the next higher-level submodule writes its tests against the settled lower layer. -2. This preserves organic Git history (`git log` and `git bisect` trace each building block in dependency order) and prevents writing tests against imagined lower-level interfaces. - ---- - -## 5. Runtime Observability Timeline & Dry-Run Invariants - -Observability is an active oversight instrument during execution, not a retrospective summary: - -1. **Pre-Execution (Gate 1)**: Orchestrator surfaces the **Planned Workflow** (structured node definitions and dynamic Mermaid projection) in chat prose for human approval before spawning workers. -2. **During Execution (Runtime Updates)**: Orchestrator dynamically updates the **Execution Record** as nodes transition states (`planned` -> `passed` / `failed` / `blocked` / `skipped`), exposing progress and failure-rework loops in orchestrator turn updates. -3. **Post-Execution (Step 6 Handoff)**: Orchestrator presents the **Deviation Report** comparing actual execution against the plan, alongside links to verified commit SHAs. - -### Dry-Run Mode (`/implement-slice --dry-run`) -Dry-run mode is defined strictly by **zero side-effects and zero mutations**: -- Produces the complete planned workflow, scope analysis, verification 5-tuples, and proposed diffs. -- Enforces 0 uncommitted changes, 0 new Git commits, 0 remote pushes, and 0 Gitea issue/PR/milestone mutations. - ---- - -## 6. Policy-Aware Integration Strategy Matrix - -The choice between direct fast-forward merge and opening a Gitea pull request is governed by repository policy and authorization, not developer convenience: - -| Factor | Direct Fast-Forward Merge | Pull Request (`gt pr create`) | -| :--- | :--- | :--- | -| **Repository `AGENTS.md`** | Must explicitly permit direct commits/merges to `main`. | Mandatory whenever repo policy prohibits direct commits to `main`. | -| **CI / Actions Requirement** | Permitted only if no remote CI workflows are required before merge. | Mandatory whenever remote Gitea Actions CI or deployment pipelines must validate branch. | -| **Review & QA Status** | Final-`HEAD` `code-review` and `verify-slice` evidence packets must be clean. | Packaged into PR body (`Closes #<id>`, review provenance, verification ledger). | -| **Human Authorization** | Explicit human approval required before merging. | Human owner authorizes creation and final merge. | diff --git a/skills/verify-slice/SKILL.md b/skills/verify-slice/SKILL.md deleted file mode 100644 index dd97100..0000000 --- a/skills/verify-slice/SKILL.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -name: verify-slice -description: >- - Runs risk-proportional verification and pull request review across behavioral, - state, security, ergonomic, and regression perspectives using falsifiable - assertions. Use when verifying a vertical feature slice, reviewing a pull - request before merge, or planning QA checks. Not for root-cause debugging; - use diagnose. ---- - -# Verify Slice - -## Use when -- Verifying a vertical feature slice or pull request before human release review. -- Building or executing risk-proportional QA checks against acceptance criteria. -- Not for investigating an unknown failure from raw symptoms: use `diagnose`. - -## Steps -1. **Size checks to risk and evaluate review handshake.** Inspect touched files, boundaries, and failure consequences, then apply the matching minimum check set in [perspectives](references/perspectives.md) (`Lightweight`, `Standard`, or `High-Assurance`) plus only the perspectives warranted by the diff. Reuse a preceding `code-review` report for static provenance only when its status is `Ready` (completed across all four axes, no unresolved blocking findings remain, and covered scope is identified), the reviewed base and head revisions match, and the current relevant working-tree diff is unchanged from the reviewed diff. Proceed directly on routine checks within authorized scope; pause for confirmation only when verification would materially expand scope, require `live-infra` authorization, incur substantial setup or subagent cost, or introduce a trade-off. -2. **Write falsifiable assertions.** Convert acceptance criteria, `code-review` Step 6 fenced checks (when present), and selected perspectives into concrete checks with explicit failure conditions (`FAIL if ...`), scope classification (`local` vs. `live-infra`), and required evidence. Never use open-ended observational prompts ("record what happens"). -3. **Verify runtime behavior.** Execute `local` behavioral, state, and persistence checks against the live system when the tier requires it, confirming mutations via both UI state and authoritative backend reads. Execute `live-infra` checks only when the human owner has explicitly authorized the target environment and operation; otherwise record `BLOCKED (out-of-bounds)` with the preserved command and criteria. Execute directly by default; use a clean subagent (withholding the diff, PR narrative, and author self-audit) only when independent execution is likely to expose blind spots in stateful workflows or `High-Assurance` changes. -4. **Inspect the diff (unless handshake invariant holds).** When Step 1 verified a reusable `Ready` review on the exact unchanged diff, bypass static diff re-inspection and cite that review as static provenance (runtime verification provides behavioral evidence and never substitutes for static review). Otherwise (standalone run, non-`Ready` review, revision mismatch, or changed working-tree diff), audit the changed delta or full diff against the selected code-level perspectives (untrusted data and URL sinks, authoritative state reconciliation, scope containment, and test coverage claims). -5. **Record dispositions honestly.** Score every check as `PASS`, `FAIL`, `BLOCKED` (`env/fixture` vs. `out-of-bounds`), or `INCONCLUSIVE` with evidence (see [perspectives](references/perspectives.md)). Never rationalize an unexpected result as a design trade-off, treat a missing or `BLOCKED` check as passing, or treat either static provenance or runtime evidence as release approval. -6. **Present the evidence packet.** Distinguish static provenance (`diff` audit vs. `code-review` handshake) from runtime evidence, note discrepancies against the implementer's self-audit, separate `BLOCKED (env/fixture)` repairs from `BLOCKED (out-of-bounds)` operator checks, and recommend a disposition without waiving failed criteria. - -## Your call -- **Expanded verification scope and `live-infra` authorization**: approve before running `live-infra` operations against privileged or external environments, spinning up costly test setups, or launching isolated subagents outside previously authorized boundaries. -- **Handling non-passing checks**: decide whether a `FAIL`, `BLOCKED`, or `INCONCLUSIVE` check triggers a repair loop, an environment fix, an authorized operator window, a tracked follow-up issue, or an explicit waiver. -- **Release decision**: decide whether to accept residual risks and merge; neither static review nor runtime verification authorizes release on its own. - -## Done when -- Every required check has an evidence-backed disposition (`PASS`, `FAIL`, `BLOCKED (env/fixture)`, `BLOCKED (out-of-bounds)`, or `INCONCLUSIVE`), static provenance and runtime evidence are clearly distinguished, and the human owner has reviewed the packet to decide release or rework. - -## Hands off to -- `diagnose`: when a failed or blocked check needs root-cause investigation. -- `git-manager`: when committing verified repair changes or managing test branches. -- `document`: when verification uncovers a durable architectural insight or decision. diff --git a/skills/verify-slice/references/perspectives.md b/skills/verify-slice/references/perspectives.md deleted file mode 100644 index 5395274..0000000 --- a/skills/verify-slice/references/perspectives.md +++ /dev/null @@ -1,48 +0,0 @@ -# Verification Tiers, Perspectives, and Dispositions - -Reference for `verify-slice`. Keep effort proportional to failure consequences and change uncertainty rather than diff line count alone. - -## 1. Operational Rigor Tiers - -Each tier defines the minimum required checks. Escalate individual perspectives when a small diff touches a high-risk boundary (for example, a two-line auth or URL sanitizer change). When a reusable `Ready` `code-review` handshake covers the exact unchanged base, head, and working-tree diff (see `SKILL.md` Steps 1 and 4), that review satisfies the tier's static diff audit as static provenance while `verify-slice` supplies runtime behavioral evidence; if any relevant file changed post-review, audit at least the changed delta. - -| Tier | Typical Slice | Minimum Required Checks | Execution Mode | -| :--- | :--- | :--- | :--- | -| **Lightweight** | Copy updates, styling tweaks, isolated low-risk fixes with no new state or untrusted inputs | 1. Run relevant existing automated tests.<br/>2. Targeted smoke/regression check on the touched view.<br/>3. Concise diff check for scope containment. | Direct execution in current session. | -| **Standard** | New UI component, ordinary API integration, or modification to an established workflow | 1. Falsifiable assertions for every acceptance criterion.<br/>2. Automated test suite, typecheck, and lint.<br/>3. Runtime check of happy, empty, and error states plus persistence reload.<br/>4. Targeted regression check on shared entrypoints.<br/>5. White-box diff review of untrusted sinks and state updates. | Direct execution by default. Use an isolated black-box subagent only if multi-step workflow bias or author self-audit independence warrants the cost. | -| **High-Assurance** | Auth, permissions, payments, destructive actions, sensitive data, concurrent/conflict state, or cross-cutting architecture | All `Standard` checks, plus:<br/>1. Explicit conflict, duplicate-submission, and aggregate-state reconciliation assertions.<br/>2. Source-to-sink security audit with adversarial input tests.<br/>3. Secondary backend/API reads confirming persisted truth after mutations. | Independent black-box subagent for behavioral scenarios paired with separate white-box diff review. | - -## 2. Selectable Review Perspectives - -Select only the perspectives relevant to the slice's risk profile. Give each selected perspective concrete assertions rather than vague instructions ("review security"). - -| Perspective | Core Question | Concrete Checks to Construct | -| :--- | :--- | :--- | -| **Behavioral & Workflow** | Can the user complete the intended end-to-end task across real states? | Verify each required user journey across loading, empty, error/retry, partial, and success states; confirm state survives reload and matches backend reads. | -| **State & Concurrency** | Do local UI elements, sibling rows, and aggregate counters stay aligned with authoritative state? | Check duplicate-click guards, timeout/retry recovery, and conflict responses (such as `409`); assert that aggregate counters and sibling items reconcile with authoritative server state rather than drifting via partial local heuristics. | -| **Security Boundaries** | Can untrusted data execute code, break attributes, or route to unsafe destinations? | Trace every dynamic value into DOM/template sinks: verify safe DOM APIs or HTML escaping for text and quoted attributes, context-appropriate URL validation for `href`/`src`/`action` (never relying on HTML escaping alone for URLs), and at least one adversarial payload check. | -| **Ergonomics & Accessibility** | Is the slice usable on narrow screens, with touch, and via keyboard/assistive tech? | Check narrow mobile viewport (`375px`) for overflow, `>= 44x44px` touch targets, sequential keyboard `Tab` focus, visible `:focus-visible` outlines, and `aria-live` announcements for dynamic feedback. | -| **Scope & Regression** | Did the slice disturb adjacent features or smuggle unrelated refactors? | Inspect shared files (`main`, routers, shared types/styles) for minimal additive footprint; run targeted smoke checks on neighboring views/endpoints. | -| **Commit & Evidence Hygiene** | Are commits localizable and does claimed test coverage match reality? | Separates two distinct responsibilities: (1) **Static review** (commit structure, diff scope, source and test inspection) is covered by a matching `Ready` review handshake. (2) **Runtime evidence reconciliation** verifies that reported outcomes are supported by executed checks and relevant test assertions substantiate claimed contracts. | - -## 3. Four-State Disposition Contract and Boundary Matrix - -Every required assertion ends in exactly one disposition. `BLOCKED` records an honest execution boundary, never permission to assume correctness or count an unexecuted check as `PASS`: - -| Situation | Disposition | Required Action | -| :--- | :--- | :--- | -| Check executes (`local`, or `live-infra` explicitly authorized by the human owner) and satisfies expected condition | `PASS` | Attach observable proof (command output, HTTP status, DOM measurement, or screenshot). | -| Check executes and contradicts expected behavior | `FAIL` | Record reproducible steps and observed vs. expected output. | -| Local fixture, seed, or tool setup prevents execution | `BLOCKED (env/fixture)` | Diagnose and repair the local blocker before judging the implementation (distinct from a product bug). | -| `live-infra` check requires permissions or infrastructure (host rebuilds, production migrations, privileged network changes) unavailable or not explicitly authorized for this run | `BLOCKED (out-of-bounds)` | Do not fabricate execution or mark `PASS`; preserve the exact command and pass/fail criteria for an authorized operator run or maintenance window. | -| Check executes, but available evidence cannot prove or falsify the assertion | `INCONCLUSIVE` | State what signal is missing and how to make the check deterministically falsifiable. | - -### Authority Separation Invariant -- `code-review` establishes **static provenance** for a specific revision range and working-tree diff. -- `verify-slice` establishes **runtime behavioral evidence** for selected assertions. -- Neither substitutes for the other, and neither grants release approval; only the human owner authorizes release. - -### Anti-Rationalization Rules -1. **Expected values before observation**: State the exact pass/fail condition before running the check. If an assertion expects `2` and the system shows `1`, record `FAIL`, never `PASS` with a narrative excuse ("targeted reconciliation trade-off"). -2. **Separate seed/fixture health from product bugs**: Avoid fragile raw SQL test seeds when domain services or API helpers exist; if a fixture mismatches schema reality, mark `BLOCKED` and fix the fixture. -3. **Unique provenance**: When comparing author self-audit, black-box QA, and diff review, label whether each confirmed defect was caught by self-audit, black-box execution, or code inspection so process value stays measurable. diff --git a/tests/fixtures/run_regression.sh b/tests/fixtures/run_regression.sh index 56f6b2f..52128f5 100755 --- a/tests/fixtures/run_regression.sh +++ b/tests/fixtures/run_regression.sh @@ -18,16 +18,18 @@ echo "--- [1/3] Verifying Skills Installation & Symlinks ---" # 2. Run Python deterministic behavioral contracts suite echo echo "--- [2/3] Running Behavioral Contract & Invariant Tests ---" -python3 "${SCRIPT_DIR}/test_skills_behavioral_contracts.py" -v +python3 -m unittest "${SCRIPT_DIR}/test_skills_behavioral_contracts.py" "${SCRIPT_DIR}/test_build_review.py" -v # 3. Qualitative Dogfood Protocol Verification echo -echo "--- [3/3] Validating Clean-Room Reproducibility & Deviation Protocol ---" -# Verify that gitea-plan references clean-room audit schema -grep -q "Independent Zero-Context Reproducibility Audit" "${REPO_ROOT}/skills/gitea-plan/references/decomposition-tiers.md" -grep -q "Auditor Report Schema" "${REPO_ROOT}/skills/gitea-plan/references/decomposition-tiers.md" -# Verify that implement-slice defines tripartite schema -grep -q "The Tripartite Workflow Contract Schemas" "${REPO_ROOT}/skills/implement-slice/references/handoff-contracts.md" +echo "--- [3/3] Validating Clean-Room Reproducibility & Contract Protocols ---" +# Verify that projects references clean-room audit schema +grep -q "Independent Zero-Context Reproducibility Audit" "${REPO_ROOT}/skills/projects/references/tiers-and-audit.md" +grep -q "Auditor Report Schema" "${REPO_ROOT}/skills/projects/references/tiers-and-audit.md" +# Verify that implement defines preflight working-tree classification +grep -q "CLEAN_BASE" "${REPO_ROOT}/skills/implement/references/preflight.md" +# Verify that code-review defines cr-review-meta provenance marker +grep -q "cr-review-meta" "${REPO_ROOT}/skills/code-review/references/finding-schema.md" # Verify that gt-usage defines project column move recipe grep -q "Move issue card between columns" "${REPO_ROOT}/skills/gt-usage/references/commands.md" diff --git a/tests/fixtures/test_skills_behavioral_contracts.py b/tests/fixtures/test_skills_behavioral_contracts.py index d36fc17..7a07bd1 100755 --- a/tests/fixtures/test_skills_behavioral_contracts.py +++ b/tests/fixtures/test_skills_behavioral_contracts.py @@ -4,25 +4,21 @@ test_skills_behavioral_contracts.py Deterministic behavioral contract test suite for kiskaadee/skills. Verifies: -1. Prerequisite guidance on missing gt binary -2. Anti-hallucination resource ID querying rules -3. Proportionality scaling (lightweight docs vs standard code) -4. Feature verification canonical node 5-tuples and dynamic Mermaid projection -5. Security invariant verification seams -6. Rework routing and execution record transitions -7. Deviation reporting on skipped checks -8. Strict dry-run zero-mutation invariants -9. Skill inventory, line count (<= 80), em-dash absence, and path portability -10. Review comment publishing ownership (code-review drafts, gitea-pr posts with guards) -11. Project board 5-column reconciliation, semantic hex colors, and transition ownership -12. reconcile-docs read-only Gitea ingestion and bidirectional hooks with gitea-plan / implement-slice -13. Polyglot TDD hardening (Mode A/B, 5 languages, 5 empirical invariants), code-review Axis 3 binding, and Suggested Next Step soft-chaining -14. Subagent provenance output-slot guards for High-Assurance code-review and gitea-plan reproducibility audit +1. Anti-hallucination resource ID querying rules (projects dynamic GraphQL/REST + gt-usage --json) +2. Review comment publishing ownership (code-review via build_review.py; implement read-only on reviews) +3. Project board 5-column reconciliation, fixed GitHub color enums, and transition ownership +4. reconcile-docs read-only GitHub ingestion and bidirectional hooks with projects / implement +5. Repo-scoped documentation boundaries and vault deprecation +6. Polyglot TDD hardening (Mode A/B, 5 languages, 5 empirical invariants) and code-review Axis 3 binding +7. Suggested Next Step soft-chaining and delegated footer suppression +8. Subagent provenance output-slot guards for High-Assurance code-review and projects reproducibility audit +9. Core GitHub delivery skill contracts (projects, implement, code-review, verify) +10. Isolated install.sh check exit codes and repo-scoped dangling-symlink pruning +11. Skill inventory, line count (<= 80), em-dash absence, and path portability """ import os import re -import shutil import subprocess import tempfile import unittest @@ -30,7 +26,7 @@ from pathlib import Path REPO_ROOT = Path(__file__).resolve().parent.parent.parent -# Canonical Active Portable Skills list from install.sh +# Canonical Active Portable Skills list from install.sh (sorted) EXPECTED_SKILLS = [ "build-skill", "code-review", @@ -38,464 +34,172 @@ EXPECTED_SKILLS = [ "diagnose", "document", "git-manager", - "gitea-plan", - "gitea-pr", "gt-usage", - "implement-slice", + "implement", "inspect-flake-update", "nix-devshell", "practice", + "projects", "reconcile-docs", "tdd", + "verify", +] + +RETIRED_LEGACY_SKILLS = [ + "gitea-plan", + "gitea-pr", + "implement-slice", "verify-slice", ] -class WorkflowNode: - """Canonical 5-tuple workflow node.""" - def __init__(self, node_id, claim, method, executor, pass_condition, failure_route=None): - self.node_id = node_id - self.claim = claim - self.method = method - self.executor = executor - self.pass_condition = pass_condition - self.failure_route = failure_route - self.status = "planned" - self.evidence = None - - def validate_schema(self): - assert re.match(r"^[A-Z0-9_-]+$", self.node_id), f"Invalid node_id: {self.node_id}" - assert self.claim and isinstance(self.claim, str), "claim must be non-empty string" - assert self.method and isinstance(self.method, str), "method must be non-empty string" - assert self.executor in [ - "Implementation Worker", - "Independent QA Subagent", - "Reviewer Subagent", - "Human Owner", - "Orchestrator", - ], f"Invalid executor: {self.executor}" - assert self.pass_condition and isinstance(self.pass_condition, str), "pass_condition must be non-empty string" - - def to_dict(self): - return { - "node_id": self.node_id, - "claim": self.claim, - "method": self.method, - "executor": self.executor, - "pass_condition": self.pass_condition, - "status": self.status, - "evidence": self.evidence, - } - - -class WorkflowEngine: - """ - Reference model of implement-slice adaptive workflow generator. - Encodes rules from orchestration-tiers.md and handoff-contracts.md. - """ - @staticmethod - def plan_slice(title, scope_files, is_security_sensitive=False, is_dry_run=False): - nodes = [] - is_doc_only = all(f.endswith(".md") or f.endswith(".txt") for f in scope_files) - - if is_doc_only: - # Proportionality: Lightweight tier - nodes.append(WorkflowNode( - node_id="TASK-DOC-01", - claim=f"Author documentation updates for {title}", - method="text editor", - executor="Implementation Worker", - pass_condition="Files updated matching scope and clean diff", - )) - nodes.append(WorkflowNode( - node_id="CHK-FORMAT", - claim="Documentation formatting conforms to line caps and style", - method="wc -l && grep checks", - executor="Implementation Worker", - pass_condition="Exit code 0", - failure_route="rework in-place", - )) - else: - # Standard / High-Assurance tier - nodes.append(WorkflowNode( - node_id="TASK-IMPL-01", - claim=f"Implement core logic for {title}", - method="editor & compiler", - executor="Implementation Worker", - pass_condition="Clean working tree and coherent checkpoint commit", - )) - nodes.append(WorkflowNode( - node_id="CHK-UNIT-01", - claim="Unit and seam test suites pass", - method="test harness", - executor="Independent QA Subagent", - pass_condition="Exit code 0, 100% assertions green", - failure_route="route to existing worker session", - )) - if is_security_sensitive: - nodes.append(WorkflowNode( - node_id="CHK-SEC-01", - claim="Defensive invariants hold: zero cleartext secrets and strict permissions", - method="secret scan and stat -c '%a'", - executor="Independent QA Subagent", - pass_condition="Zero matches for secrets, permissions 0600", - failure_route="block commit, sanitize diff", - )) - nodes.append(WorkflowNode( - node_id="GATE-REVIEW", - claim="Final HEAD 4-axis static and strategic review passed", - method="code-review", - executor="Reviewer Subagent", - pass_condition="Ready disposition matching exact final HEAD", - failure_route="rework review comments", - )) - - mermaid_graph = WorkflowEngine.project_mermaid(nodes) - return { - "title": title, - "is_doc_only": is_doc_only, - "is_dry_run": is_dry_run, - "nodes": nodes, - "mermaid": mermaid_graph, - } - - @staticmethod - def project_mermaid(nodes): - lines = ["flowchart TD"] - for node in nodes: - lines.append(f' {node.node_id}["{node.node_id}: {node.claim}"]') - # Add sequence edges and explicit failure/rework edges - for i in range(len(nodes) - 1): - lines.append(f" {nodes[i].node_id} --> {nodes[i+1].node_id}") - if nodes[i+1].failure_route: - lines.append(f' {nodes[i+1].node_id} -.->|Fail / Rework| {nodes[0].node_id}') - return "\n".join(lines) - - @staticmethod - def generate_deviation_report(nodes): - skipped = [n for n in nodes if n.status == "skipped"] - rework = [n for n in nodes if n.status == "failed"] - return { - "skipped_checks": [ - {"node_id": n.node_id, "rationale": n.evidence or "No rationale recorded"} - for n in skipped - ], - "rework_count": len(rework), - "clean_pass": len(skipped) == 0 and len(rework) == 0, - } - - class TestSkillsBehavioralContracts(unittest.TestCase): - def test_prerequisite_guidance(self): - """Proves missing gt binary triggers actionable prerequisite instructions.""" - with tempfile.TemporaryDirectory() as tmp_dir: - tmp_bin = Path(tmp_dir) / "bin" - tmp_bin.mkdir() - git_path = shutil.which("git") - self.assertIsNotNone(git_path, "git must exist on host") - (tmp_bin / "git").symlink_to(git_path) - - orig_dirs = os.environ.get("PATH", "").split(os.pathsep) - new_dirs = [d for d in orig_dirs if not (Path(d) / "gt").exists()] - new_dirs.insert(0, str(tmp_bin)) - - env = os.environ.copy() - env["PATH"] = os.pathsep.join(new_dirs) - - res = subprocess.run( - ["./install.sh", "check"], - cwd=REPO_ROOT, - env=env, - capture_output=True, - text=True, - ) - # Must output actionable warning about gt CLI - combined = res.stdout + res.stderr - self.assertIn("'gt' CLI not found in PATH", combined) - self.assertIn("Gitea skills (gt-usage, gitea-plan, gitea-pr, implement-slice) require the official Gitea CLI", combined) - self.assertIn("https://gitea.com/gitea/cli/releases", combined) - def test_resource_id_querying_rules(self): - """Proves milestone/issue planning recipes forbid hardcoded ID guessing and require gt --json.""" + """Proves planning recipes forbid hardcoded ID guessing and require dynamic queries.""" gt_usage_cmd = REPO_ROOT / "skills" / "gt-usage" / "references" / "commands.md" self.assertTrue(gt_usage_cmd.exists()) - content = gt_usage_cmd.read_text() + gt_content = gt_usage_cmd.read_text() - # Must mandate --json for querying IDs - self.assertIn("gt milestone list --json id,title,state,url", content) - self.assertIn("gt issue list --json id,number,title,state,url", content) - self.assertIn("gt project list --json id,title,state,url", content) + # Standalone gt-usage still mandates --json for querying IDs + self.assertIn("gt milestone list --json id,title,state,url", gt_content) + self.assertIn("gt issue list --json id,number,title,state,url", gt_content) + self.assertIn("gt project list --json id,title,state,url", gt_content) - # Anti-hallucination check: ensure gitea-plan explicitly forbids constructing /milestone/1 - gitea_plan = REPO_ROOT / "skills" / "gitea-plan" / "SKILL.md" - self.assertIn("never guess sequence numbers or construct `/milestone/1`", gitea_plan.read_text()) - - def test_proportionality_scaling(self): - """Proves a documentation-only task produces a lightweight workflow without synthetic test ceremony.""" - doc_slice = WorkflowEngine.plan_slice( - title="Update architecture notes", - scope_files=["docs/adr/0001.md", "README.md"], - ) - self.assertTrue(doc_slice["is_doc_only"]) - # Should have lightweight nodes, no Independent QA Subagent, no unit test harness - executors = [n.executor for n in doc_slice["nodes"]] - methods = [n.method for n in doc_slice["nodes"]] - self.assertNotIn("Independent QA Subagent", executors) - self.assertNotIn("test harness", methods) - self.assertEqual(len(doc_slice["nodes"]), 2) - - def test_feature_verification_canonical_schema(self): - """Proves a multi-file code slice produces valid canonical 5-tuples and dynamic Mermaid projection.""" - code_slice = WorkflowEngine.plan_slice( - title="Add authentication middleware", - scope_files=["src/auth.py", "src/tokens.py"], - is_security_sensitive=False, - ) - self.assertFalse(code_slice["is_doc_only"]) - self.assertGreaterEqual(len(code_slice["nodes"]), 3) - - # Validate canonical schema on each node - for node in code_slice["nodes"]: - node.validate_schema() - - # Dynamic Mermaid projection validation - mermaid = code_slice["mermaid"] - self.assertIn("flowchart TD", mermaid) - for node in code_slice["nodes"]: - self.assertIn(node.node_id, mermaid) - # Rework edge exists - self.assertIn("Fail / Rework", mermaid) - - def test_security_invariants(self): - """Proves a security-sensitive slice produces explicit defensive verification seams.""" - sec_slice = WorkflowEngine.plan_slice( - title="Update SSH key loader", - scope_files=["src/ssh_loader.py"], - is_security_sensitive=True, - ) - node_ids = [n.node_id for n in sec_slice["nodes"]] - self.assertIn("CHK-SEC-01", node_ids) - sec_node = next(n for n in sec_slice["nodes"] if n.node_id == "CHK-SEC-01") - sec_node.validate_schema() - self.assertIn("defensive invariants", sec_node.claim.lower()) - self.assertIn("permissions", sec_node.pass_condition.lower()) - - def test_rework_routing(self): - """Proves a simulated check failure correctly triggers rework and logs the failure in execution record.""" - code_slice = WorkflowEngine.plan_slice( - title="Add parser", - scope_files=["src/parser.py"], - ) - unit_node = next(n for n in code_slice["nodes"] if n.node_id == "CHK-UNIT-01") - - # Simulate failure - unit_node.status = "failed" - unit_node.evidence = "AssertionError: line 42 expected 'ok' got 'error' (Exit code 1)" - self.assertEqual(unit_node.status, "failed") - self.assertEqual(unit_node.failure_route, "route to existing worker session") - - # Simulate rework resolution via live worker session - unit_node.evidence = "Fixed in commit 1a2b3c4; Exit code 0, 12 passed" - unit_node.status = "passed" - self.assertEqual(unit_node.status, "passed") - - def test_deviation_reporting(self): - """Proves a skipped check generates an explicit entry with rationale in the deviation report.""" - code_slice = WorkflowEngine.plan_slice( - title="Deploy live monitor", - scope_files=["src/monitor.py"], - ) - # Add an optional live-infra check that gets skipped due to missing human authorization - live_check = WorkflowNode( - node_id="CHK-LIVE-01", - claim="Live infrastructure endpoint responds HTTP 200", - method="curl https://roadtotech.me", - executor="Independent QA Subagent", - pass_condition="HTTP 200", - ) - code_slice["nodes"].append(live_check) - - # Mark skipped due to authorization boundary - live_check.status = "skipped" - live_check.evidence = "BLOCKED (out-of-bounds): live-infra unapproved by human owner" - - report = WorkflowEngine.generate_deviation_report(code_slice["nodes"]) - self.assertFalse(report["clean_pass"]) - self.assertEqual(len(report["skipped_checks"]), 1) - self.assertEqual(report["skipped_checks"][0]["node_id"], "CHK-LIVE-01") - self.assertIn("live-infra unapproved", report["skipped_checks"][0]["rationale"]) - - def test_dry_run_zero_mutation(self): - """Proves --dry-run produces complete plans without mutating git status, commits, or files.""" - # Record initial git status - initial_status = subprocess.check_output( - ["git", "status", "--porcelain"], - cwd=REPO_ROOT, - text=True, - ) - initial_commit = subprocess.check_output( - ["git", "rev-parse", "HEAD"], - cwd=REPO_ROOT, - text=True, - ).strip() - - # Execute dry-run planning - plan = WorkflowEngine.plan_slice( - title="Spike feature", - scope_files=["src/spike.py"], - is_dry_run=True, - ) - self.assertTrue(plan["is_dry_run"]) - self.assertGreater(len(plan["nodes"]), 0) - - # Verify zero mutations - current_status = subprocess.check_output( - ["git", "status", "--porcelain"], - cwd=REPO_ROOT, - text=True, - ) - current_commit = subprocess.check_output( - ["git", "rev-parse", "HEAD"], - cwd=REPO_ROOT, - text=True, - ).strip() - - # The only allowed diff is the test file itself if it is running in-tree - # But during execution, zero new commits and zero external branch creation - self.assertEqual(initial_commit, current_commit) + # Anti-hallucination check: projects explicitly forbids guessing IDs or constructing /milestone/1 + projects_skill = (REPO_ROOT / "skills" / "projects" / "SKILL.md").read_text() + projects_v2 = (REPO_ROOT / "skills" / "projects" / "references" / "github-projects-v2.md").read_text() + self.assertIn("Resolve all IDs dynamically", projects_skill) + self.assertIn("/milestone/1", projects_skill) + self.assertIn("Never hardcode or guess IDs", projects_v2) + self.assertIn("gh api repos/{owner}/{repo}/milestones", projects_v2) def test_review_comment_publishing_ownership(self): - """Proves code-review auto-publishes guarded PR reviews, bans self-assigned Accepted Trade-off, and gates gitea-pr merge on 3 triage exits.""" + """Proves code-review owns guarded GitHub PR review publishing and implement never publishes reviews.""" cr_dir = REPO_ROOT / "skills" / "code-review" + cr_skill = (cr_dir / "SKILL.md").read_text() + cr_schema = (cr_dir / "references" / "finding-schema.md").read_text() cr_text = "\n".join(p.read_text() for p in cr_dir.rglob("*.md")) - self.assertIn("review-body.md", cr_text) - self.assertIn("inline-comments.json", cr_text) - self.assertIn("No non-rejected findings.", cr_text) - self.assertIn("read-only regarding the codebase", cr_text) - self.assertIn("Never self-assign `Accepted Trade-off`", cr_text) + + self.assertIn("build_review.py", cr_skill) self.assertIn("Pending Triage", cr_text) - self.assertIn("live-tracker", cr_text) + self.assertIn("Exit A", cr_schema) + self.assertIn("Exit B", cr_schema) + self.assertIn("Exit C", cr_schema) + self.assertNotIn("Accepted Trade-off", cr_text) + self.assertIn("read-only regarding the codebase", cr_schema) + self.assertIn('"event": "COMMENT"', cr_schema) + self.assertIn('"commit_id": "<head_sha>"', cr_schema) + self.assertIn("Never emit `APPROVE` or `REQUEST_CHANGES`", cr_schema) + self.assertIn("no open PR was found", cr_skill) - schema = (cr_dir / "references" / "finding-schema.md").read_text() - publish = schema.split("### Auto-Publishing via `gt pr review`", 1)[1] - post_cmd = re.search(r"gt pr review <number> --comment[^\n]*\n[^\n]*", publish).group(0) - # pinned to the reviewed commit, comment-only, no blanket confirmation - self.assertIn("--commit <reviewed-head-sha>", post_cmd) - for forbidden in ("--approve", "--request-changes", "--yes"): - self.assertNotIn(forbidden, post_cmd) - # staleness and duplicate guards precede posting - self.assertLess(publish.index("head_sha"), publish.index(post_cmd)) - self.assertLess(publish.index("gt pr review list"), publish.index(post_cmd)) - - # gitea-pr gates Ready for Merge on Pending Triage resolution and no longer duplicates publish recipe - pr_skill = (REPO_ROOT / "skills" / "gitea-pr" / "SKILL.md").read_text() - pr_pulls = (REPO_ROOT / "skills" / "gitea-pr" / "references" / "gt-pulls.md").read_text() - self.assertIn("Pending Triage", pr_skill) - self.assertNotIn("Publish review findings", pr_skill) - self.assertNotIn("### Publish a `code-review` Comment Block", pr_pulls) - self.assertIn("/orgs/<org>/projects/<project-id>/issues/<global-issue-id>/move", (REPO_ROOT / "skills" / "implement-slice" / "references" / "handoff-contracts.md").read_text()) - - # Elapsed issue time tracking uses lock-free POST .../times rather than global stopwatch/start - gt_cmds = (REPO_ROOT / "skills" / "gt-usage" / "references" / "commands.md").read_text() - impl_skill = (REPO_ROOT / "skills" / "implement-slice" / "SKILL.md").read_text() - impl_handoff = (REPO_ROOT / "skills" / "implement-slice" / "references" / "handoff-contracts.md").read_text() - self.assertIn("/issues/<issue-index>/times", gt_cmds) - self.assertIn("started_at=$(date +%s)", impl_skill) - self.assertIn("/issues/<issue-index>/times", impl_handoff) - self.assertNotIn("stopwatch/start", impl_skill) + # implement never publishes PR reviews or inline review comments + impl_skill = (REPO_ROOT / "skills" / "implement" / "SKILL.md").read_text() + impl_pr = (REPO_ROOT / "skills" / "implement" / "references" / "pr-and-drift.md").read_text() + self.assertIn("never publish PR review comments", impl_skill) + self.assertIn("`code-review` is the sole owner of PR review publishing", impl_pr) def test_project_board_reconciliation_and_card_transitions(self): - """Proves 5-column board reconciliation, Deep Signal colors, and card transition ownership.""" - tiers_text = (REPO_ROOT / "skills" / "gitea-plan" / "references" / "decomposition-tiers.md").read_text() - gt_cmds = (REPO_ROOT / "skills" / "gt-usage" / "references" / "commands.md").read_text() - impl_skill = (REPO_ROOT / "skills" / "implement-slice" / "SKILL.md").read_text() - impl_handoff = (REPO_ROOT / "skills" / "implement-slice" / "references" / "handoff-contracts.md").read_text() - pr_skill = (REPO_ROOT / "skills" / "gitea-pr" / "SKILL.md").read_text() - pr_pulls = (REPO_ROOT / "skills" / "gitea-pr" / "references" / "gt-pulls.md").read_text() + """Proves 5-column GitHub Projects v2 board schema, fixed color enums, and transition ownership.""" + contract_text = (REPO_ROOT / "skills" / "projects" / "references" / "planning-contract.md").read_text() + v2_text = (REPO_ROOT / "skills" / "projects" / "references" / "github-projects-v2.md").read_text() + impl_skill = (REPO_ROOT / "skills" / "implement" / "SKILL.md").read_text() + impl_pr = (REPO_ROOT / "skills" / "implement" / "references" / "pr-and-drift.md").read_text() + verify_skill = (REPO_ROOT / "skills" / "verify" / "SKILL.md").read_text() + verify_closeout = (REPO_ROOT / "skills" / "verify" / "references" / "closeout-and-abort.md").read_text() cr_dir = REPO_ROOT / "skills" / "code-review" cr_text = "\n".join(p.read_text() for p in cr_dir.rglob("*.md")) - # 1. Canonical 5 columns and Deep Signal hex colors in gitea-plan + # 1. Canonical 5 columns and fixed GitHub color enums in projects (no hex colors) expected_columns = { - "Backlog": "#475569", - "Ready": "#1d76db", - "Work in Progress": "#d97706", - "Review": "#6d28d9", - "Completed": "#15803d", + "Backlog": "GRAY", + "Ready": "BLUE", + "Work in Progress": "YELLOW", + "Review": "PURPLE", + "Completed": "GREEN", } - for col_title, hex_color in expected_columns.items(): - self.assertIn(col_title, tiers_text) - self.assertIn(hex_color, tiers_text) - self.assertIn("PATCH", tiers_text) - self.assertIn("PATCH /repos/{owner}/{repo}/projects/<project-id>/columns/<column-id>", gt_cmds) + for col_title, color_enum in expected_columns.items(): + self.assertIn(col_title, contract_text) + self.assertIn(color_enum, contract_text) + self.assertIn(col_title, v2_text) + self.assertIn(color_enum, v2_text) + self.assertIsNone( + re.search(r"#[0-9a-fA-F]{6}\b", contract_text + "\n" + v2_text), + "projects must use GitHub color enums rather than Gitea #RRGGBB hex colors", + ) - # 2. Card transition ownership across implement-slice and gitea-pr - self.assertIn("Backlog -> Ready", impl_skill) + # 2. Card transition ownership across implement and verify self.assertIn("Ready -> Work in Progress", impl_skill) - self.assertIn("Work in Progress -> Review", impl_skill) - self.assertIn("Backlog -> Ready", impl_handoff) - self.assertIn("Work in Progress -> Review", pr_skill) - self.assertIn("Review -> Completed", pr_skill) - self.assertIn("/issues/${issue_global_id}/move -F column_id=<completed-col-id>", pr_pulls) + self.assertIn("keep the\n board card in `Work in Progress`", impl_skill) + self.assertIn("Never\n move the card to `Review` here", impl_pr) + self.assertIn("Work in Progress -> Review", verify_skill) + self.assertIn("Review -> Completed", verify_skill) + self.assertIn("Review -> Work in Progress", verify_skill) + self.assertIn("updateProjectV2ItemFieldValue", verify_closeout) # 3. code-review never mutates project boards self.assertIsNone( - re.search(r"/projects/[^\n]*/move", cr_text), + re.search(r"(updateProjectV2ItemFieldValue|/projects/[^\n]*/move)", cr_text), "code-review must remain read-only and never execute project board card moves", ) - def test_reconcile_docs_gitea_ingestion_and_hooks(self): - """Proves reconcile-docs ingests Gitea state read-only and hooks into gitea-plan and implement-slice.""" + def test_reconcile_docs_github_ingestion_and_hooks(self): + """Proves reconcile-docs ingests GitHub state read-only and hooks into projects and implement.""" rd_dir = REPO_ROOT / "skills" / "reconcile-docs" rd_skill = (rd_dir / "SKILL.md").read_text() rd_all = "\n".join(p.read_text() for p in rd_dir.rglob("*.md")) - plan_skill = (REPO_ROOT / "skills" / "gitea-plan" / "SKILL.md").read_text() - impl_skill = (REPO_ROOT / "skills" / "implement-slice" / "SKILL.md").read_text() + projects_skill = (REPO_ROOT / "skills" / "projects" / "SKILL.md").read_text() + verify_skill = (REPO_ROOT / "skills" / "verify" / "SKILL.md").read_text() - # 1. reconcile-docs reads Gitea PR comments and board state, and targets docs/designs/*.md + # 1. reconcile-docs reads GitHub PRs, milestones, and board state read-only, targeting docs/designs/*.md self.assertIn("docs/designs/*.md", rd_skill) self.assertIn("Project Board", rd_skill) - self.assertIn("Never mutate Gitea issues, PRs, or board cards", rd_skill) + self.assertIn("gh repo view --json url", rd_skill) + self.assertIn("gh pr list --state merged", rd_skill) + self.assertIn("Never mutate GitHub issues, PRs, or board cards", rd_skill) self.assertIn("Mid-Slice Spec Drift", rd_all) self.assertIsNone( - re.search(r"(/projects/[^\n]*/move|gt (issue|pr|project) (create|edit|close|merge))", rd_all), - "reconcile-docs must never mutate Gitea issues, PRs, or project boards", + re.search(r"(updateProjectV2ItemFieldValue|gh (issue|pr) (create|edit|close|merge))", rd_all), + "reconcile-docs must never mutate GitHub issues, PRs, or project boards", ) - # 2. Bidirectional hooks across reconcile-docs, gitea-plan, and implement-slice - self.assertIn("gitea-plan", rd_skill) - self.assertIn("reconcile-docs", plan_skill) - self.assertIn("reconcile-docs", impl_skill) + # 2. Bidirectional hooks across reconcile-docs, projects, implement, and verify + self.assertIn("projects", rd_skill) + self.assertIn("implement", rd_skill) + self.assertIn("reconcile-docs", projects_skill) + self.assertIn("reconcile-docs", verify_skill) def test_repo_scoped_documentation_and_vault_deprecation(self): """Proves ~/Brain, 00-inbox, draft-curation, and journal-builder are deprecated in favor of repo docs/ and .internal/.""" - doc_dir = REPO_ROOT / "skills" / "document" - doc_all = "\n".join(p.read_text() for p in doc_dir.rglob("*.md")) - prac_dir = REPO_ROOT / "skills" / "practice" - prac_all = "\n".join(p.read_text() for p in prac_dir.rglob("*.md")) + doc_all = "\n".join(p.read_text() for p in (REPO_ROOT / "skills" / "document").rglob("*.md")) + prac_all = "\n".join(p.read_text() for p in (REPO_ROOT / "skills" / "practice").rglob("*.md")) + projects_all = "\n".join(p.read_text() for p in (REPO_ROOT / "skills" / "projects").rglob("*.md")) + impl_all = "\n".join(p.read_text() for p in (REPO_ROOT / "skills" / "implement").rglob("*.md")) profile_agents = (REPO_ROOT / "profile" / "AGENTS.md").read_text() install_sh = (REPO_ROOT / "install.sh").read_text() - # 1. No ~/Brain, 00-inbox, or draft-curation in active skills or profile + # 1. No ~/Brain, 00-inbox, draft-curation, or journal-builder in active skills or profile for forbidden in ("~/Brain", "00-inbox", "draft-curation", "journal-builder"): self.assertNotIn(forbidden, doc_all) self.assertNotIn(forbidden, prac_all) + self.assertNotIn(forbidden, projects_all) + self.assertNotIn(forbidden, impl_all) self.assertNotIn(forbidden, profile_agents) # 2. Repo-scoped paths present self.assertIn("docs/adr/", doc_all) self.assertIn("docs/designs/", doc_all) self.assertIn(".internal/practice/", prac_all) + self.assertIn("docs/designs/*.md", projects_all) + self.assertIn(".internal/", projects_all) + self.assertIn("docs/designs/*.md", impl_all) + self.assertIn(".internal/", impl_all) self.assertIn("OBSOLETE_SKILLS=(", install_sh) self.assertIn("journal-builder", install_sh) self.assertIn("draft-curation", install_sh) - # 3. Vertical per-submodule Red->Green decomposition in gitea-plan and implement-slice - plan_all = "\n".join(p.read_text() for p in (REPO_ROOT / "skills" / "gitea-plan").rglob("*.md")) - impl_all = "\n".join(p.read_text() for p in (REPO_ROOT / "skills" / "implement-slice").rglob("*.md")) - self.assertIn("Vertical Submodule TDD Grouping", plan_all) - self.assertIn("Vertical Submodule TDD Decomposition (Anti-Horizontal Batching)", impl_all) + # 3. Vertical Submodule TDD Grouping in projects + self.assertIn("Vertical Submodule TDD Grouping", projects_all) def test_tdd_supports_dual_mode_with_mode_b_gates(self): """Proves tdd supports Mode A and Mode B with production-signature Your call and sensitivity Done when gates.""" @@ -542,18 +246,19 @@ class TestSkillsBehavioralContracts(unittest.TestCase): self.assertIn("Suggested Next Step", schema) def test_skeleton_defines_suggested_next_step_suppression(self): - """Proves skeleton.md owns Suggested Next Step suppression and handoff-contracts.md enforces it without en-dash debt.""" + """Proves skeleton.md owns Suggested Next Step suppression and implement enforces it on delegated workers.""" skeleton = (REPO_ROOT / "skills" / "build-skill" / "references" / "skeleton.md").read_text() - handoffs = (REPO_ROOT / "skills" / "implement-slice" / "references" / "handoff-contracts.md").read_text() + impl_skill = (REPO_ROOT / "skills" / "implement" / "SKILL.md").read_text() + impl_roles = (REPO_ROOT / "skills" / "implement" / "references" / "decomposition-and-roles.md").read_text() self.assertIn("Suggested Next Step", skeleton) self.assertIn("Delegated subagent runs omit that footer", skeleton) - self.assertIn("Suppress", handoffs) - self.assertNotIn("Steps 4–5", handoffs) + self.assertIn("suppress\n when delegated", impl_skill) + self.assertIn("Suppress any standalone `Suggested Next Step:` footer", impl_roles) def test_chained_skills_include_suggested_next_step_routing(self): """Proves all 6 chained skills include Suggested Next Step routing and valid relative markdown links.""" link_re = re.compile(r"\]\(([^)#]+\.md)(?:#[^)]+)?\)") - for skill_name in ("gitea-plan", "implement-slice", "tdd", "code-review", "gitea-pr", "reconcile-docs"): + for skill_name in ("projects", "implement", "tdd", "code-review", "verify", "reconcile-docs"): skill_path = REPO_ROOT / "skills" / skill_name / "SKILL.md" text = skill_path.read_text() self.assertIn("Suggested Next Step:", text, f"{skill_name} missing Suggested Next Step routing") @@ -562,21 +267,210 @@ class TestSkillsBehavioralContracts(unittest.TestCase): self.assertTrue(resolved.exists(), f"{skill_name} has broken relative link: {rel_link} -> {resolved}") def test_subagent_provenance_output_slot_guards(self): - """Proves High-Assurance code-review and Medium/Large gitea-plan require subagent provenance slots in output templates.""" + """Proves High-Assurance code-review and Medium/Large projects require subagent provenance slots in output templates.""" cr_skill = (REPO_ROOT / "skills" / "code-review" / "SKILL.md").read_text() cr_schema = (REPO_ROOT / "skills" / "code-review" / "references" / "finding-schema.md").read_text() - impl_tiers = (REPO_ROOT / "skills" / "implement-slice" / "references" / "orchestration-tiers.md").read_text() - plan_skill = (REPO_ROOT / "skills" / "gitea-plan" / "SKILL.md").read_text() - plan_tiers = (REPO_ROOT / "skills" / "gitea-plan" / "references" / "decomposition-tiers.md").read_text() + projects_skill = (REPO_ROOT / "skills" / "projects" / "SKILL.md").read_text() + projects_tiers = (REPO_ROOT / "skills" / "projects" / "references" / "tiers-and-audit.md").read_text() - self.assertIn("record both subagent IDs in `Execution Mode`", cr_skill) + self.assertIn("record\n both subagent IDs in `Execution Mode`", cr_skill) self.assertIn("Dedicated Axis 3 Tests subagent `<id>`", cr_schema) - self.assertIn("dedicated Axis 3 `Seam & Test Integrity` subagent + Axes 1/2/4 subagent", impl_tiers) - self.assertIn("### Reproducibility Audit:", plan_skill) - self.assertIn("### Reproducibility Audit:", plan_tiers) + self.assertIn("### Reproducibility Audit:", projects_skill) + self.assertIn("### Reproducibility Audit:", projects_tiers) + + def test_projects_contract_and_dynamic_graphql_state_machine(self): + """Proves projects defines state-free project_number contract and dynamic owner.projectV2 / issue.projectItems queries.""" + contract = (REPO_ROOT / "skills" / "projects" / "references" / "planning-contract.md").read_text() + v2 = (REPO_ROOT / "skills" / "projects" / "references" / "github-projects-v2.md").read_text() + + self.assertIn("project_number: <int>", contract) + self.assertIn("Zero brittle Node IDs", contract) + self.assertIn("gh repo view --json url", contract) + self.assertIn("owner.projectV2(number: $project_number)", v2) + self.assertIn("addProjectV2ItemById", v2) + self.assertIn("issue.projectItems", v2) + self.assertIn("updateProjectV2ItemFieldValue", v2) + self.assertIn("DATE", v2) + + def test_implement_preflight_checkpointing_and_timeout_wrapper(self): + """Proves implement defines preflight classifications, --dry-run, git-common-dir checkpointing without tuxedo, and setsid timeout.""" + preflight = (REPO_ROOT / "skills" / "implement" / "references" / "preflight.md").read_text() + roles = (REPO_ROOT / "skills" / "implement" / "references" / "decomposition-and-roles.md").read_text() + + for classification in ( + "CLEAN_BASE", + "EXISTING_SLICE_BRANCH", + "ADOPTABLE_DIFF", + "CONFLICTING_STATE", + "WRONG_BASE", + ): + self.assertIn(classification, preflight) + + self.assertIn("--dry-run", preflight) + self.assertIn("zero mutations", preflight) + self.assertIn("git rev-parse --git-common-dir", preflight) + self.assertIn("implement-state/${branch_slug}.txt", preflight) + self.assertIn("Never\n invoke `tuxedo`", preflight) + + self.assertIn("setsid timeout -k 10 <N>s <cmd> < /dev/null", roles) + self.assertIn("CI=true", roles) + self.assertIn("GIT_TERMINAL_PROMPT=0", roles) + self.assertIn("PAGER=cat", roles) + for timeout_tier in ("60s", "180s", "600s"): + self.assertIn(timeout_tier, roles) + + def test_code_review_build_review_and_metadata_contract(self): + """Proves code-review integrates build_review.py, monotonic CR-XX, cr-review-meta verdict, RV-* body checks, and local no-PR notice.""" + build_script = REPO_ROOT / "skills" / "code-review" / "scripts" / "build_review.py" + self.assertTrue(build_script.exists(), "build_review.py must exist under skills/code-review/scripts/") + + cr_skill = (REPO_ROOT / "skills" / "code-review" / "SKILL.md").read_text() + cr_schema = (REPO_ROOT / "skills" / "code-review" / "references" / "finding-schema.md").read_text() + + self.assertIn("skills/code-review/scripts/build_review.py", cr_skill) + self.assertIn("cr-review-meta: max_id=NN head_sha=<sha> verdict=ready|needs_rework", cr_schema) + self.assertIn("CR-01", cr_schema) + self.assertIn("RV-*", cr_schema) + self.assertIn("3-rework-cycle cap", cr_schema) + self.assertIn("No open GitHub PR found; findings reported locally.", cr_schema) + + def test_verify_three_phase_flow_and_zero_todo_txt(self): + """Proves verify defines 3-phase flow, zero todo.txt responsibility, gh pr ready -> Review, and post-merge Completed.""" + verify_skill = (REPO_ROOT / "skills" / "verify" / "SKILL.md").read_text() + qa = (REPO_ROOT / "skills" / "verify" / "references" / "qa-dispositions.md").read_text() + closeout = (REPO_ROOT / "skills" / "verify" / "references" / "closeout-and-abort.md").read_text() + + self.assertIn("Phase 1: Read-Only Runtime QA and CI", verify_skill) + self.assertIn("Phase 2: Promotion", verify_skill) + self.assertIn("Phase 3: Human Merge Gate and Closeout", verify_skill) + self.assertIn("zero\n`todo.txt` cleanup responsibility", verify_skill) + self.assertIn("Zero `todo.txt` responsibility", closeout) + + self.assertIn("cr-review-meta", qa) + self.assertIn("verdict=ready", qa) + self.assertIn("gh pr checks", qa) + for disposition in ( + "PASS", + "FAIL", + "BLOCKED (env/fixture)", + "BLOCKED (out-of-bounds)", + "INCONCLUSIVE", + ): + self.assertIn(disposition, qa) + + self.assertIn("gh pr ready", closeout) + self.assertIn("Work in Progress -> Review", closeout) + self.assertIn("Review -> Completed", closeout) + self.assertIn("gh pr ready --undo", closeout) + self.assertIn("gh pr close", closeout) + + def test_install_sh_check_exit_codes_and_dangling_symlink_pruning(self): + """Proves install.sh check exits 1 on missing/obsolete skills, exits 0 when clean, and prunes only repo-scoped dangling symlinks.""" + with tempfile.TemporaryDirectory() as tmp_dir: + tmp_path = Path(tmp_dir) + target_skills = tmp_path / "skills" + target_agents = tmp_path / "agents" + target_profile = tmp_path / "AGENTS.md" + target_skills.mkdir() + target_agents.mkdir() + + env = os.environ.copy() + env["PROFILE_TARGET"] = str(target_profile) + env["AGENTS_DIR_TARGET"] = str(target_agents) + + # 1. Empty target must fail check with exit 1 + res_empty = subprocess.run( + ["./install.sh", "--target", str(target_skills), "check"], + cwd=REPO_ROOT, + env=env, + capture_output=True, + text=True, + ) + self.assertEqual(res_empty.returncode, 1, res_empty.stdout + res_empty.stderr) + self.assertIn("[MISSING]", res_empty.stdout) + + # 2. Install into isolated temp dir must succeed (exit 0), then check must exit 0 + res_install = subprocess.run( + ["./install.sh", "--target", str(target_skills)], + cwd=REPO_ROOT, + env=env, + capture_output=True, + text=True, + ) + self.assertEqual(res_install.returncode, 0, res_install.stdout + res_install.stderr) + + res_clean = subprocess.run( + ["./install.sh", "--target", str(target_skills), "check"], + cwd=REPO_ROOT, + env=env, + capture_output=True, + text=True, + ) + self.assertEqual(res_clean.returncode, 0, res_clean.stdout + res_clean.stderr) + self.assertIn("All active skills are present.", res_clean.stdout) + + # 3. Adding an obsolete legacy skill must cause check to exit 1 + obsolete_link = target_skills / "gitea-plan" + obsolete_link.symlink_to(REPO_ROOT / "skills" / "gitea-plan") + res_obs = subprocess.run( + ["./install.sh", "--target", str(target_skills), "check"], + cwd=REPO_ROOT, + env=env, + capture_output=True, + text=True, + ) + self.assertEqual(res_obs.returncode, 1, res_obs.stdout + res_obs.stderr) + self.assertIn("[OBSOLETE PRESENT] gitea-plan", res_obs.stdout) + + # 4. Repo-scoped dangling symlink is pruned on install; unrelated dangling symlink is preserved + repo_dangling = target_skills / "stale-repo-skill" + repo_dangling.symlink_to(REPO_ROOT / "skills" / "nonexistent-deleted-skill") + unrelated_dangling = target_skills / "external-skill" + unrelated_dangling.symlink_to(Path("/tmp/nonexistent-unrelated-skill-target")) + + res_reinstall = subprocess.run( + ["./install.sh", "--target", str(target_skills)], + cwd=REPO_ROOT, + env=env, + capture_output=True, + text=True, + ) + self.assertEqual(res_reinstall.returncode, 0, res_reinstall.stdout + res_reinstall.stderr) + self.assertFalse(obsolete_link.is_symlink(), "Obsolete skill symlink should be backed up and removed") + self.assertFalse(repo_dangling.is_symlink(), "Repo-scoped dangling symlink should be pruned") + self.assertTrue(unrelated_dangling.is_symlink(), "Unrelated external symlink must be preserved") + + # 5. Clean check passes again after reinstall + res_post = subprocess.run( + ["./install.sh", "--target", str(target_skills), "check"], + cwd=REPO_ROOT, + env=env, + capture_output=True, + text=True, + ) + self.assertEqual(res_post.returncode, 0, res_post.stdout + res_post.stderr) def test_skill_inventory_and_skeletons(self): - """Proves all 16 active skills meet line count (<= 80), em-dash, and path portability rules.""" + """Proves all 15 active skills meet line count (<= 80), em-dash, and path portability rules, and legacy skills are retired.""" + install_sh = (REPO_ROOT / "install.sh").read_text() + + # Verify ACTIVE_PORTABLE_SKILLS matches EXPECTED_SKILLS exactly + active_match = re.search(r"ACTIVE_PORTABLE_SKILLS=\(([^)]*)\)", install_sh) + self.assertIsNotNone(active_match, "ACTIVE_PORTABLE_SKILLS missing from install.sh") + active_skills = active_match.group(1).split() + self.assertEqual(active_skills, EXPECTED_SKILLS) + + # Verify all 4 retired legacy skills appear in OBSOLETE_SKILLS and are absent from skills/ + obsolete_match = re.search(r"OBSOLETE_SKILLS=\(([^)]*)\)", install_sh) + self.assertIsNotNone(obsolete_match, "OBSOLETE_SKILLS missing from install.sh") + obsolete_skills = obsolete_match.group(1).split() + for retired in RETIRED_LEGACY_SKILLS: + self.assertIn(retired, obsolete_skills, f"{retired} must be listed in OBSOLETE_SKILLS") + self.assertFalse( + (REPO_ROOT / "skills" / retired).exists(), + f"Retired legacy skill directory still exists: skills/{retired}", + ) + for skill_name in EXPECTED_SKILLS: skill_path = REPO_ROOT / "skills" / skill_name / "SKILL.md" self.assertTrue(skill_path.exists(), f"Missing skill file: {skill_path}")