From d63e1c6f09ef84687d4eff87ce137e2ac202986c Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sun, 15 Nov 2026 21:23:17 -0500 Subject: [PATCH] feat(tdd,code-review): add polyglot test-hardening invariants, Axis 3 binding, and soft-chaining - build-skill & implement-slice: add single-owner Suggested Next Step chaining and subagent suppression to skeleton.md and handoff-contracts.md; clean en-dash in Steps 4-5 Log - tdd: support Mode A (Red->Green) and Mode B (standalone test-suite hardening); add the 5 PR #7 invariants across Python, TypeScript, Bash, Rust, and Java - code-review: bind Axis 3 directly to tdd/references/, isolate Axis 3 normatively in High-Assurance reviews, and add Suggested Next Step to finding-schema.md - gitea-plan, implement-slice, gitea-pr, reconcile-docs: add outcome-matched Suggested Next Step routing in Hands off to within <= 76 lines - tests: add test_polyglot_tdd_hardening_code_review_binding_and_soft_chaining --- skills/build-skill/references/skeleton.md | 1 + skills/code-review/SKILL.md | 10 ++-- skills/code-review/references/axes.md | 4 +- .../code-review/references/finding-schema.md | 3 +- skills/gitea-plan/SKILL.md | 20 ++++---- skills/gitea-pr/SKILL.md | 11 +++-- skills/implement-slice/SKILL.md | 6 +-- .../references/handoff-contracts.md | 6 +-- skills/reconcile-docs/SKILL.md | 5 +- skills/tdd/SKILL.md | 40 ++++++++-------- skills/tdd/references/seams-and-mocking.md | 31 ++++++++++-- skills/tdd/references/test-quality.md | 34 +++++++++---- .../test_skills_behavioral_contracts.py | 48 +++++++++++++++++++ 13 files changed, 156 insertions(+), 63 deletions(-) diff --git a/skills/build-skill/references/skeleton.md b/skills/build-skill/references/skeleton.md index 02f88e0..3870fd3 100644 --- a/skills/build-skill/references/skeleton.md +++ b/skills/build-skill/references/skeleton.md @@ -53,3 +53,4 @@ description: >- - **No em-dashes** in skill text. - **The `name` is the slash command.** Must match `^[a-z0-9-]+$`. Never use underscores (`_`) or uppercase; never create a separate wrapper skill to expose a command. - **Public repo hygiene.** Never hardcode user home paths (`/home/...`) or secrets. +- **Next-step chaining & subagent suppression.** Skills that chain into downstream workflows emit one outcome-matched `Suggested Next Step: / ` line at the end of standalone turns (inside `## Hands off to` or their output template). Delegated subagent runs omit that footer and return only their parent handoff format. diff --git a/skills/code-review/SKILL.md b/skills/code-review/SKILL.md index 61ee433..b3cb6a7 100644 --- a/skills/code-review/SKILL.md +++ b/skills/code-review/SKILL.md @@ -21,7 +21,7 @@ description: >- 3. **Inspect the four axes.** Evaluate the diff against each axis independently using [axes](references/axes.md): - **Spec & Scope**: originating requirements satisfied, aligned with canonical project direction (`ARCHITECTURE.md`, `ROADMAP.md`, ADRs, active milestone) when present, minimal shared-file footprint, zero scope creep. - **Standards & Smells**: repository rules and Fowler smell diagnostics from [smell-heuristics](references/smell-heuristics.md) (evaluated as confirmed violations, potential smells, or contextual trade-offs). - - **Seam & Test Integrity**: tests verify public interface seams, assertions are non-tautological, negative/boundary paths covered, vertical slices prioritized over bulk imagined tests. + - **Seam & Test Integrity**: audit test diffs against [seams-and-mocking](../tdd/references/seams-and-mocking.md) and [test-quality](../tdd/references/test-quality.md) (public seams, injected timing callables, deterministic waits/teardown, non-tautological literals, boundary coverage, single-behavior naming). - **Defensive Invariants**: system properties from [defensive-invariants](references/defensive-invariants.md) (trust boundaries, authority, consistency, failure semantics, resource limits). 4. **Record structured findings.** Record every finding using the schema in [finding-schema](references/finding-schema.md) (`ID`, `Axis`, `Severity`, `Evidence`, `Invariant`, `Impact`, `Disposition`). A strong pass on one axis never compensates for a failure on another. 5. **Aggregate without silent resolution.** When multiple reviewers or passes disagree, keep the disagreement visible under `Unresolved` until evidence settles it. @@ -39,7 +39,9 @@ description: >- - All four axes have been inspected across working-tree and committed changes, every finding is recorded with evidence and disposition, executable Step 6 runtime checks are emitted for `verify-slice` if needed, and the human owner has reviewed the findings. ## Hands off to -- `diagnose`: when a finding exposes a root cause that requires deeper troubleshooting. -- `verify-slice`: to execute behavioral and runtime verification scenarios. +- `tdd`: when Axis 3 fails (`Suggested Next Step: /tdd `) or production rework needs test-first fixes (`Suggested Next Step: /tdd `). +- `diagnose`: when a finding exposes an unknown root cause (`Suggested Next Step: /diagnose`). +- `verify-slice`: when `Ready` and runtime/`RV-*` checks are needed (`Suggested Next Step: /verify-slice`). - `git-manager`: when branching, committing review fixes, or rebasing. -- `gitea-pr`: to publish the drafted PR comment block on the pull request after owner approval. +- `gitea-pr`: when `Ready` on an open PR with clean runtime checks (`Suggested Next Step: /gitea-pr `). +- Emit one outcome-matched `Suggested Next Step` on standalone turns; suppress when delegated (per [skeleton](../../build-skill/references/skeleton.md)). diff --git a/skills/code-review/references/axes.md b/skills/code-review/references/axes.md index b2b4360..243591f 100644 --- a/skills/code-review/references/axes.md +++ b/skills/code-review/references/axes.md @@ -10,7 +10,7 @@ Derived and adapted from Matt Pocock's skills repository (github.com/mattpocock/ | :--- | :--- | :--- | :--- | | **Spec & Scope** | Did we build what was requested, aligned with project direction, and only that? | Scope creep, missing requirements, architectural or roadmap drift, leaky abstractions | 1. Does the diff satisfy the originating issue or specification contract?
2. When canonical direction docs exist (`ARCHITECTURE.md`, `ROADMAP.md`, ADRs, or active milestone scope), does the change align with long-term boundaries and trajectory?
3. Is there unrequested functionality or premature generalization?
4. Are changes to shared entrypoints (e.g., routers, base config) minimal and additive? | | **Standards & Smells** | Is the implementation maintainable and consistent? | Structural debt, friction with conventions | 1. Does the code adhere to repo standards (`CODING_STANDARDS.md`, linter configs)?
2. Are code smells present that warrant refactoring? (See [smell-heuristics](smell-heuristics.md)).
3. Is naming clear and aligned with domain vocabulary? | -| **Seam & Test Integrity** | Do tests prove actual contracts at public interfaces? | Tautological tests, implementation coupling | 1. Are tests verifying public interfaces (seams) rather than mocking private internals?
2. Are assertions non-tautological (do not mirror code logic or pass by construction)?
3. Prefer tests establishing observable behavior through meaningful vertical slices. Batch independent cases when doing so preserves clear contracts and does not substitute test quantity for behavioral evidence. | +| **Seam & Test Integrity** | Do tests prove actual contracts at public interfaces? | Tautological tests, implementation coupling, boundary gaps, flaky waits | Audit against [seams-and-mocking](../../tdd/references/seams-and-mocking.md) and [test-quality](../../tdd/references/test-quality.md):
1. Public seams only; boundary mocks only; injected timing/clock callables instead of global runtime monkeypatching; deterministic waits and guaranteed teardown.
2. Non-tautological assertions with independent literals (no imported production value constants), exact+neighbor boundary points (`[min-1, min, max, max+1]`), and single-behavior test names (no vague buckets or `_and_` chains). | | **Defensive Invariants** | Does the code preserve critical system properties under stress? | Injection, state desync, unhandled crashes | 1. Are untrusted inputs sanitized before reaching sinks? (See [defensive-invariants](defensive-invariants.md)).
2. Does state reconcile against authoritative sources rather than local heuristic drift?
3. Are failure semantics, timeouts, and resource limits explicit? | ### Non-Compensation Invariant @@ -46,7 +46,7 @@ To keep review overhead proportional to risk, execution mode reuses the tiers es | :--- | :--- | :--- | | **Lightweight** | Copy updates, styling adjustments, isolated bugfixes with no new state or untrusted data. | Single-agent sequential pass inspecting all 4 axes in order. | | **Standard** | New UI components, regular API endpoints, database queries, or schema additions. | Independent review passes over the diff. Subagents may be used when helpful to prevent bias. | -| **High-Assurance** | Auth, permissions, payments, concurrent state reconciliation, destructive actions, or core shared libraries. | Fully isolated reviewers for separate axes (e.g., Subagent 1 on Spec, Invariants, and Tests; Subagent 2 on Standards and Smells), followed by independent aggregation. | +| **High-Assurance** | Auth, permissions, payments, concurrent state reconciliation, destructive actions, or core shared libraries. | Assign a dedicated isolated reviewer to **Seam & Test Integrity** (Axis 3, auditing test diffs against `tdd/references/`), separate from `Spec & Scope` + `Defensive Invariants` and `Standards & Smells`, followed by independent aggregation. | ## 4. Aggregation and Anti-Silence Rules diff --git a/skills/code-review/references/finding-schema.md b/skills/code-review/references/finding-schema.md index 1dd82c6..bd3eb89 100644 --- a/skills/code-review/references/finding-schema.md +++ b/skills/code-review/references/finding-schema.md @@ -91,7 +91,8 @@ systemctl reload app-daemon.service && systemctl is-active --quiet app-daemon.se ## Overall Recommendation - **Status**: `Ready` | `Needs Rework` | `Blocked` -- **Next Action**: State whether to hand off to `verify-slice` for runtime verification, `diagnose` for root-cause fixes, or present to human owner for adjudication. Static provenance and runtime verification remain distinct inputs; neither authorizes release on its own. +- **Next Action**: State whether to hand off to `verify-slice` for runtime verification, `diagnose` for root-cause fixes, `tdd` for Mode B test hardening, or `gitea-pr` for PR packaging/comment publishing. Static provenance and runtime verification remain distinct inputs; neither authorizes release on its own. +- **Suggested Next Step**: `/ ` (emit one concrete command matched to the recommendation on standalone turns; omit when running inside a delegated subagent). ``` ## 4. PR Comment Block (Drafted Here, Published by `gitea-pr`) diff --git a/skills/gitea-plan/SKILL.md b/skills/gitea-plan/SKILL.md index 9a67cf5..14771cf 100644 --- a/skills/gitea-plan/SKILL.md +++ b/skills/gitea-plan/SKILL.md @@ -48,16 +48,11 @@ description: >- 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 or reconcile a concise sync rule in the - repository's `AGENTS.md` so day-to-day coding agents keep trackers updated without - reloading `gitea-plan`: - - Pin **stable structural coordinates only**: canonical roadmap/checklist paths - (e.g., `docs/roadmap.md`, `todo.txt`), authoritative Gitea repo + Project Board ID - + `{Backlog, Ready, Work in Progress, Review, Completed -> column_id}` map, - remote mirror policy (e.g., GitHub code-only), and the escalation trigger to - re-run `gitea-plan` on scope shifts or epic Readiness Gates. - - **Never** hardcode rotating sprint state (active milestone numbers or open issue - lists) inside `AGENTS.md`; let `docs/roadmap.md`, `todo.txt`, and `gt` hold state. + `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. @@ -71,7 +66,8 @@ description: >- whenever `Medium`/`Large` planning structure is created or updated. ## Hands off to -- `implement-slice`: to orchestrate end-to-end delivery of an approved issue or slice. +- `implement-slice`: to deliver an approved issue (`Suggested Next Step: /implement-slice #`). - `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 or design specs lag behind completed slices or milestone boundaries. +- `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-pr/SKILL.md b/skills/gitea-pr/SKILL.md index bfaa12c..8a96a63 100644 --- a/skills/gitea-pr/SKILL.md +++ b/skills/gitea-pr/SKILL.md @@ -67,7 +67,10 @@ description: >- review and mergeability status is reported to the user. ## Hands off to -- `code-review`: if the diff changes and needs renewed static inspection. -- `verify-slice`: if new code requires runtime verification. -- `git-manager`: to commit review fixes, rebase, or update the branch against upstream base. -- `gitea-plan`: to create the follow-up issue for a finding routed `issue` before publishing. +- `code-review`: if review packet is missing/stale (`Suggested Next Step: /code-review ..HEAD`). +- `verify-slice`: if runtime QA packet is missing/stale (`Suggested Next Step: /verify-slice`). +- `gitea-plan`: to create follow-up issues routed `issue` (`Suggested Next Step: /gitea-plan`). +- `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 #`). +- `git-manager`: to commit review fixes, rebase, or update against base. +- Emit one outcome-matched `Suggested Next Step` per [skeleton](../../build-skill/references/skeleton.md). diff --git a/skills/implement-slice/SKILL.md b/skills/implement-slice/SKILL.md index 846c6fe..6e7e0d5 100644 --- a/skills/implement-slice/SKILL.md +++ b/skills/implement-slice/SKILL.md @@ -37,9 +37,9 @@ description: >- ## 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 implementation workers for seam-level red-green development. +- `tdd`: inside workers for seam-level red-green development, or standalone test hardening (`Suggested Next Step: /tdd `). - `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 pull request and final-`HEAD` packets are ready. -- `reconcile-docs`: when upstream slices or approved scope drift leave canonical docs or design specs out of sync with `HEAD`. +- `gitea-pr`: when policy or remote CI mandates a PR and final-`HEAD` packets are ready (`Suggested Next Step: /gitea-pr #`). +- `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 #`. diff --git a/skills/implement-slice/references/handoff-contracts.md b/skills/implement-slice/references/handoff-contracts.md index 308fe54..ee8688a 100644 --- a/skills/implement-slice/references/handoff-contracts.md +++ b/skills/implement-slice/references/handoff-contracts.md @@ -25,7 +25,7 @@ Provide before spawning (or messaging) an implementation worker: - **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). +- **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) @@ -46,7 +46,7 @@ The rubric is written and approved during Step 3 (before implementation begins). - **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)`). +- **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) @@ -74,7 +74,7 @@ Follows the `verify-slice` disposition contract: ``` ``` -### B. Execution Record Schema (Steps 4–5 Log) +### B. Execution Record Schema (Steps 4-5 Log) Updated dynamically in orchestrator turns: ```markdown | Node ID | Claim / Invariant | Method | Executor | Evidence | Pass Condition | Status | diff --git a/skills/reconcile-docs/SKILL.md b/skills/reconcile-docs/SKILL.md index cbc85bb..f9b3075 100644 --- a/skills/reconcile-docs/SKILL.md +++ b/skills/reconcile-docs/SKILL.md @@ -39,5 +39,6 @@ description: >- - The Reconciliation Report is approved by the user, canonical documentation files are written or updated, and consistency validation passes cleanly. ## Hands off to -- `git-manager`: for branch setup or committing updated documentation files. -- `gitea-plan`: when reconciled `ROADMAP.md` or `docs/designs/*.md` require new or updated Gitea milestones, issues, or board reconciliation. +- `git-manager`: for branch setup or committing updated documentation (`Suggested Next Step: /git-manager`). +- `gitea-plan`: when reconciled `ROADMAP.md` or `docs/designs/*.md` require new or updated Gitea milestones, issues, or board reconciliation (`Suggested Next Step: /gitea-plan`). +- Emit one outcome-matched `Suggested Next Step` on standalone turns per [skeleton](../../build-skill/references/skeleton.md). diff --git a/skills/tdd/SKILL.md b/skills/tdd/SKILL.md index 4b515a1..514d756 100644 --- a/skills/tdd/SKILL.md +++ b/skills/tdd/SKILL.md @@ -1,40 +1,42 @@ --- name: tdd description: >- - Guides test-driven development through public interface seams using red-green - vertical slices, boundary-only mocking, and non-tautological assertions. Use - when the user types /tdd, asks for test-first implementation, requests a - failing reproduction test for a bug, or writes unit and integration tests. Do - not use for trivial fixes, styling, copy, declarative configuration, or - routine edits where test-first was not requested. + Guides test-driven development through public interface seams (Mode A: write-time + Red-Green vertical slices) and standalone test-suite audit and hardening (Mode B) + across Python, TypeScript, Bash, Rust, and Java. Use when the user types /tdd, + asks for test-first implementation or bug reproduction, or requests hardening an + existing test file, branch, or PR suite. Do not use for trivial fixes, styling, + copy, declarative configuration, or read-only multi-axis diff review (code-review). --- # Test-Driven Development ## Use when -- `/tdd`, or explicit requests for test-first implementation, red-green loops, or bug reproduction tests. -- Authoring or refactoring unit and integration tests around behavioral contracts. +- `/tdd` for Mode A (test-first implementation, red-green vertical slices, or failing bug reproduction). +- `/tdd ` for Mode B (active audit and hardening of existing tests against [seams-and-mocking](references/seams-and-mocking.md) and [test-quality](references/test-quality.md)). - Not for trivial two-line fixes, copy, styling, declarative config, or pure wiring: edit directly instead. -- Not for pre-merge diff inspection (`code-review`) or live browser/deployment QA (`verify-slice`). +- Not for read-only pre-merge multi-axis diff inspection (`code-review`) or live runtime/browser QA (`verify-slice`). ## Steps -1. **Check applicability.** Confirm the task introduces or changes observable logic at a testable boundary. If the change is trivial (typo, styling, static config, pure wiring) and `/tdd` was not explicitly requested, skip this skill and apply the change directly. Read project domain docs (`GLOSSARY.md` or local ADRs) if present so test and interface names match domain terms. -2. **Establish the public seam.** Identify the public interface where callers observe behavior without reaching into internals (see [seams-and-mocking](references/seams-and-mocking.md)). If the seam already exists and is unambiguous (such as adding a regression test to an established endpoint or function), proceed directly. Pause to confirm with the human owner only when introducing a new public interface, choosing between multiple candidate seams, or introducing test doubles. -3. **Write one failing tracer bullet (Red).** Write a focused test at the agreed seam describing *what* capability or invariant holds, not *how* internals work (see [test-quality](references/test-quality.md)). Derive expected values from an independent source of truth (known literals, worked domain examples, specification rules), never by mirroring the implementation's formula. +1. **Check applicability and select mode.** Confirm the task tests observable logic at a testable boundary (skip and edit directly for trivial config/copy when `/tdd` was not requested). Read project domain docs (`GLOSSARY.md` or local ADRs) if present. Select **Mode A** when adding new behavior, reproducing a bug, or writing a new test; select **Mode B** when asked to audit/harden existing tests or fix `code-review` Axis 3 findings, and follow the Mode B checklist in [test-quality](references/test-quality.md). +2. **Establish the public seam.** Identify the public interface where callers observe behavior without reaching into internals (see [seams-and-mocking](references/seams-and-mocking.md)). If the seam already exists and is unambiguous, proceed directly. Pause to confirm with the human owner when introducing a new public interface, changing a production signature, or introducing test doubles. +3. **Write one failing tracer bullet (Red).** Write a focused test at the agreed seam describing *what* capability or invariant holds, not *how* internals work (see [test-quality](references/test-quality.md)). Derive expected values from independent spec literals, never by importing production value constants or mirroring implementation logic. 4. **Verify observable failure.** Run the targeted test command and confirm the test fails for the expected behavioral reason, not a syntax, import, or fixture setup error. 5. **Write the minimal implementation (Green).** Write only enough production code to make the failing test pass. Avoid speculative abstractions or untested branches. -6. **Cover negative, conflict, and boundary cases.** Once the happy-path slice passes, run additional red-to-green cycles for material failure modes (invalid inputs, conflict states such as `409`, timeouts, or state reconciliation invariants). Batch independent table-driven cases only after a vertical slice establishes the real contract. -7. **Clean up and hand off.** Remove duplication and clarify names while keeping the suite green, or defer broader structural cleanup to `code-review`. +6. **Cover negative, conflict, and boundary cases.** Once the happy-path slice passes, run red-to-green cycles for material failure modes, two-sided/one-sided boundary edges, and deterministic async/teardown behavior per [test-quality](references/test-quality.md). +7. **Clean up and hand off.** Remove duplication and clarify test names while keeping the suite green. ## Your call -- **New seams and mock boundaries**: approve proposed public seams and any external mocks vs. real lightweight fixtures (such as an in-memory or temporary test database) before test authoring begins on new interfaces. +- **New seams, signatures, and mock boundaries**: approve proposed public seams, external doubles vs. real lightweight fixtures, and any Mode B production signature widening (such as adding an injected timing/clock callable) before editing production interfaces. - **Coverage depth**: decide when edge-case and negative-path slices are sufficient for the risk level of the change. ## Done when -- Every targeted test was observed failing for the expected reason before passing, all tests verify public seams without tautological assertions, and the relevant test suite passes cleanly. +- **Mode A**: Every targeted test was observed failing for the expected reason before passing, all tests verify public seams without tautologies, and the suite passes cleanly. +- **Mode B**: Every rewritten/hardened test is verified sensitive to its target invariant (observed failing under fault/boundary check before passing green) and the suite passes cleanly. ## Hands off to -- `code-review`: to inspect the resulting diff, code smells, defensive invariants, and test seam integrity. -- `verify-slice`: when the slice also needs live runtime, browser DOM, or multi-service verification. -- `diagnose`: when an unexpected test or fixture failure needs root-cause investigation. +- `code-review`: to inspect the resulting diff, smells, invariants, and Axis 3 test integrity (`Suggested Next Step: /code-review ..HEAD`). +- `verify-slice`: when the slice also needs live runtime, browser DOM, or multi-service verification (`Suggested Next Step: /verify-slice`). +- `diagnose`: when an unexpected test or fixture failure needs root-cause investigation (`Suggested Next Step: /diagnose `). - `git-manager`: for branch isolation or committing cohesive vertical slices. +- Emit one outcome-matched `Suggested Next Step` on standalone turns; suppress when delegated (per [skeleton](../../build-skill/references/skeleton.md)). diff --git a/skills/tdd/references/seams-and-mocking.md b/skills/tdd/references/seams-and-mocking.md index f858e2a..b4acb57 100644 --- a/skills/tdd/references/seams-and-mocking.md +++ b/skills/tdd/references/seams-and-mocking.md @@ -14,9 +14,11 @@ When proposing a new seam to the human owner, state two things in one line: | Stack | Typical Public Seam | Avoid Testing Directly | | :--- | :--- | :--- | -| **Python API (FastAPI)** | HTTP route contract via `TestClient` / `AsyncClient` or domain service entrypoint | Private helper functions, ORM query-builder internals | -| **TypeScript UI** | Rendered component DOM + user events + typed API client boundary | Internal component state variables, private render helpers | +| **Python API / Library** | HTTP route contract (`TestClient` / `AsyncClient`), CLI, or public service/client entrypoint | Private helper functions, ORM query-builder internals | +| **TypeScript UI / Client** | Rendered component DOM + user events + typed API client boundary | Internal component state variables, private render helpers | +| **Bash CLI / Script** | Script execution (`bats` `run ./script.sh` or subshell with exit code, stdout/stderr, files) | Internal shell helper functions sourced in isolation | | **Rust CLI / Crate** | Public crate functions/traits or CLI command execution (`assert_cmd`) | Private module helpers, internal buffer representations | +| **Java Service / API** | Public service/controller interface (`MockMvc` / `TestRestTemplate` / domain facade) | Private methods, reflection-accessed fields | ## 2. Where to Mock (System Boundaries Only) @@ -35,5 +37,26 @@ Never mock **collaborators you own**: ## 3. Shaping Interfaces for Clean Boundary Doubles -1. **Inject external dependencies explicitly**: Pass clocks, HTTP adapters, or external clients into functions/constructors rather than instantiating globals or reading environment variables inside domain logic. -2. **Use operation-specific adapter methods**: Prefer typed boundary methods (`api.getSession(id)`, `api.checkInAttendee(id)`) over a single generic `fetch(url, options)` mock. Operation-specific methods let each test stub one explicit response without reimplementing URL routing conditionals inside test setup. +1. **Inject timing, clock, and external dependencies explicitly**: Pass clocks, sleep functions, HTTP/transport adapters, or external clients into functions/constructors with production defaults instead of globally monkeypatching stdlib runtime primitives in tests. +2. **Use operation-specific adapter methods**: Prefer typed boundary methods (`api.getSession(id)`, `api.checkInAttendee(id)`) over a single generic `fetch(url, options)` mock so each test stubs one explicit response without reimplementing URL routing inside test setup. + +| Language | Ban Global Runtime Patching | Inject Timing / Clock Seam Instead | +| :--- | :--- | :--- | +| **Python** | `monkeypatch.setattr(asyncio, "sleep", ...)`, `patch("time.monotonic")` | `sleep_fn: Callable[[float], Awaitable[None]] = asyncio.sleep`, `clock_fn = time.monotonic` | +| **TypeScript** | `vi.spyOn(globalThis, "setTimeout")` / global `Date` patching when avoidable | Optional `{ now = Date.now, sleep = defaultSleep }` dependency param | +| **Bash** | Replacing system `sleep`/`date` globally in `PATH` when an arg/env seam fits | Injected env var/command hook (e.g. `SLEEP_CMD="${SLEEP_CMD:-sleep}"`) or CLI flag | +| **Rust** | Global static mutable clocks or `#[cfg(test)]` timer branches | Trait bound or closure param (`impl Fn() -> Instant` / `sleep: impl Fn(Duration)`) | +| **Java** | `MockedStatic` / `System` time overrides | Inject `java.time.Clock` (`Clock.fixed(...)` in tests) or `Sleeper` functional interface | + +## 4. Deterministic Async Synchronization and Guaranteed Teardown + +1. **Never synchronize concurrent work with fixed sleeps or silent loops**: Fixed delays (`asyncio.sleep(0.02)`, `setTimeout(..., 50)`, `sleep 1`, `thread::sleep`, `Thread.sleep`) flake under CI load, and `for _ in range(N)` loops that break silently mask hung background tasks. Wait on explicit events/barriers or use a bounded condition helper that fails with a clear timeout error. +2. **Guarantee cleanup on assertion failure**: Every test spawning background tasks, subprocesses, sockets, or temp files must clean up even when an assertion fails. + +| Language | Deterministic Synchronization | Guaranteed Teardown | +| :--- | :--- | :--- | +| **Python** | `asyncio.Event` / bounded `wait_for(predicate, timeout=1.0)` raising `AssertionError` | `pytest` `yield` fixture, `async with`, or `try...finally` | +| **TypeScript** | `vi.waitFor(...)` / `expect.poll(...)` / explicit deferred `Promise` | `afterEach` / `try...finally` | +| **Bash** | Bounded readiness polling loop exiting non-zero on timeout | `trap 'rm -rf "$tmpdir"; kill "$bg_pid" 2>/dev/null || true' EXIT` | +| **Rust** | Channels (`mpsc`), `Notify`, or bounded poll loop panicking on timeout | RAII `Drop` guards and `tempfile::TempDir` | +| **Java** | `CountDownLatch`, `CompletableFuture`, or `Awaitility.await()` | `@AfterEach` and `try-with-resources` (`AutoCloseable`) | diff --git a/skills/tdd/references/test-quality.md b/skills/tdd/references/test-quality.md index e223f07..ae78a42 100644 --- a/skills/tdd/references/test-quality.md +++ b/skills/tdd/references/test-quality.md @@ -12,17 +12,17 @@ Derived and adapted from Matt Pocock's `tdd` skill (`github.com/mattpocock/skill - **Fix**: Act through the public write seam and assert through the public read seam or rendered output. ### B. Tautological Assertions -- **Smell**: Recomputing the expected value with the same logic as production code, asserting a constant equals itself, or mocking a boundary to return `X` and only asserting `result == X`. -- **Tell**: A bug in the formula or contract would change both the code and the expected expression identically, keeping the test green. -- **Fix**: Use concrete literals, worked domain examples, or specification tables as an independent source of truth. +- **Smell**: Recomputing the expected value with the same logic as production code, importing production value constants (`PERMISSIONS`, `DEFAULT_PORT`, `ALLOWLIST`, error templates) to construct the expected value, or mocking a boundary to return `X` and only asserting `result == X`. +- **Tell**: A bug in the formula or a typo/accidental change to the production constant keeps the test green. +- **Fix**: Use independent hardcoded literals, worked domain examples, or specification tables as the expected value (importing public *types* or *exception classes* such as `pytest.raises(ConfigError)` is valid). ```python -# BAD: Recomputes expected value using the same arithmetic -def test_calculate_total(): - items = [Item(price=10), Item(price=5)] - assert calculate_total(items) == sum(i.price for i in items) +# BAD: Recomputes expected value or imports the production constant under test +def test_calculate_total_and_port(): + assert calculate_total([Item(price=10), Item(price=5)]) == sum(i.price for i in items) + assert client.port == DEFAULT_PORT -# GOOD: Independent literal from worked example +# GOOD: Independent literals from worked example and spec def test_calculate_total_sums_item_prices(): assert calculate_total([Item(price=10), Item(price=5)]) == 15 ``` @@ -40,4 +40,20 @@ def test_calculate_total_sums_item_prices(): After the primary capability turns green, add focused red-to-green tests for the failure modes present in the slice: - **Conflict and retry paths**: Duplicate submissions, `409` responses, network errors, and idempotent retries. - **Untrusted input boundaries**: Special characters or HTML payloads (``) rendered safely as literal text rather than executable markup. -- **Empty and boundary values**: Zero items, maximum capacity limits, missing optional fields, and unauthorized callers. +- **Empty and boundary values (Boundary Value Analysis)**: For any closed range `[min, max]` or length/capacity limit, test all four boundary neighbors `[min - 1, min, max, max + 1]` (accepting `min` and `max`; rejecting `min - 1` and `max + 1`). For one-sided lower bounds (`>= min` or non-empty length), test `[min - 1, min]`; for one-sided upper bounds (`<= max`), test `[max, max + 1]` (adapting to `<` / `>` exclusive boundaries). Parametrize cleanly (`@pytest.mark.parametrize`, `test.each`, Bash loops, Rust test tables, JUnit `@ParameterizedTest`). + +## 3. Single-Behavior Test Naming and Focus + +Name every test ` + ` so failures identify the exact broken contract without reading the test body: +- **Python (`pytest`) / Bash (`bats`) / Rust (`#[test]`)**: `test__` (for example, `test_set_volume_rejects_above_max`). +- **TypeScript (`vitest`/`jest`)**: `describe("", () => it(""))`. +- **Java (`JUnit 5`)**: `@Test void _()` (or `@DisplayName(" ")`). +- **Ban vague bucket names**: Never name tests `test_validation`, `test_defaults`, `test_edge_cases`, or `test_helpers`. +- **Ban multi-behavior `_and_` chains**: Split compound tests (`test_wake_coalesces_and_handles_connected_and_pairing`) into focused single-behavior tests or parameterized cases so an early assertion failure never hides sibling behaviors. Atomic domain terms (such as `search_and_replace`) remain valid. + +## 4. Mode B Audit and Hardening Checklist + +When `/tdd` is invoked in **Mode B** on existing tests, a branch, or `code-review` Axis 3 findings: +1. **Inventory test defects** against [seams-and-mocking](seams-and-mocking.md) (global timer monkeypatching, fixed sleeps/silent loops, missing teardown, internal collaborator mocks) and Sections 1-3 above (tautological constant imports, missing `[min-1, min, max, max+1]` boundary points, vague or `_and_` names). +2. **Gate signature changes**: Pause at `## Your call` before adding an injected timing/clock parameter or changing any production signature; rewrite test-only fixes directly. +3. **Harden and verify sensitivity**: Apply fixes one seam at a time, confirm each rewritten test fails when its target invariant or boundary is violated (via temporary/reverted fault check or explicit invalid-input assertion), and verify the full test suite passes green. diff --git a/tests/fixtures/test_skills_behavioral_contracts.py b/tests/fixtures/test_skills_behavioral_contracts.py index 77833b7..be4c2ee 100755 --- a/tests/fixtures/test_skills_behavioral_contracts.py +++ b/tests/fixtures/test_skills_behavioral_contracts.py @@ -16,6 +16,7 @@ Verifies: 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 """ import os @@ -480,6 +481,53 @@ class TestSkillsBehavioralContracts(unittest.TestCase): self.assertIn("Vertical Submodule TDD Grouping", plan_all) self.assertIn("Vertical Submodule TDD Decomposition (Anti-Horizontal Batching)", impl_all) + def test_polyglot_tdd_hardening_code_review_binding_and_soft_chaining(self): + """Proves dual-mode tdd, 5-language invariants, single-owner code-review Axis 3 binding, and Suggested Next Step soft-chaining.""" + tdd_dir = REPO_ROOT / "skills" / "tdd" + tdd_skill = (tdd_dir / "SKILL.md").read_text() + seams = (tdd_dir / "references" / "seams-and-mocking.md").read_text() + quality = (tdd_dir / "references" / "test-quality.md").read_text() + tdd_refs = seams + "\n" + quality + + # 1. Dual-mode tdd & 5 target languages + self.assertIn("Mode A", tdd_skill) + self.assertIn("Mode B", tdd_skill) + for lang in ("Python", "TypeScript", "Bash", "Rust", "Java"): + self.assertIn(lang, seams) + self.assertIn(lang, quality) + + # 2. All 5 empirical invariants live in tdd/references/ + self.assertIn("sleep_fn", seams) + self.assertIn("Deterministic Async Synchronization and Guaranteed Teardown", seams) + self.assertIn("[min - 1, min, max, max + 1]", quality) + self.assertIn("production value constants", quality) + self.assertIn("Single-Behavior Test Naming and Focus", quality) + self.assertIn("Mode B Audit and Hardening Checklist", quality) + + # 3. code-review binds Axis 3 directly to tdd/references/ without duplicating fenced code blocks, and isolates Axis 3 in High-Assurance + cr_skill = (REPO_ROOT / "skills" / "code-review" / "SKILL.md").read_text() + axes = (REPO_ROOT / "skills" / "code-review" / "references" / "axes.md").read_text() + schema = (REPO_ROOT / "skills" / "code-review" / "references" / "finding-schema.md").read_text() + self.assertIn("../tdd/references/seams-and-mocking.md", cr_skill) + self.assertIn("../tdd/references/test-quality.md", cr_skill) + self.assertIn("../../tdd/references/seams-and-mocking.md", axes) + self.assertIn("../../tdd/references/test-quality.md", axes) + self.assertIn("dedicated isolated reviewer to **Seam & Test Integrity**", axes) + self.assertNotIn("calculate_total", axes) + self.assertIn("Suggested Next Step", schema) + + # 4. Canonical Suggested Next Step + suppression contract in skeleton.md and handoff-contracts.md + skeleton = (REPO_ROOT / "skills" / "build-skill" / "references" / "skeleton.md").read_text() + handoffs = (REPO_ROOT / "skills" / "implement-slice" / "references" / "handoff-contracts.md").read_text() + self.assertIn("Suggested Next Step", skeleton) + self.assertIn("Suppress", handoffs) + self.assertNotIn("Steps 4–5", handoffs) + + # 5. All 6 chained skills include Suggested Next Step routing + for skill_name in ("gitea-plan", "implement-slice", "tdd", "code-review", "gitea-pr", "reconcile-docs"): + text = (REPO_ROOT / "skills" / skill_name / "SKILL.md").read_text() + self.assertIn("Suggested Next Step:", text, f"{skill_name} missing Suggested Next Step routing") + def test_skill_inventory_and_skeletons(self): """Proves all 16 active skills meet line count (<= 80), em-dash, and path portability rules.""" for skill_name in EXPECTED_SKILLS: