Skip to content

Promote integration to main (68 PRs, 57 issues, 40 fixes, 31 features) - #580

Merged
Trecek merged 81 commits into
mainfrom
integration
Apr 3, 2026
Merged

Trecek merged 81 commits into
mainfrom
integration

Conversation

@Trecek

@Trecek Trecek commented Apr 3, 2026

Copy link
Copy Markdown
Collaborator

Promotion: integration to main

This promotion delivers a substantially hardened AutoSkillit platform across session lifecycle management, developer experience, and pipeline reliability. Forty bug fixes address critical issues including token telemetry cross-contamination, terminal ownership races, session adjudication edge cases, and clone lifecycle coordination failures. Thirty-one new features ship a complete skill pack registry with configurable visibility, guided first-run onboarding, stale install detection, a terminal guard for alternate screen buffer isolation, and a two-skill promote-to-main workflow. Pipeline reliability is strengthened through deferred clone cleanup for parallel runs, three-way merge routing, merge queue detection, and a new pipeline identity layer. The test suite received a comprehensive eight-group cleanup pass removing tautological tests, fixing xdist isolation, strengthening HIGH-severity findings, and eliminating redundant coverage.

Stats: 308 files changed, 24,579 insertions(+), 2,794 deletions(-) across 118 commits and 68 merged PRs resolving 57 linked issues.

Highlights

Release Notes

New Features

Bug Fixes

Test Suite

A comprehensive eight-group cleanup pass addressed structural defects:

Infrastructure

  • New CI workflow patch-bump-integration.yml auto-applies patch version bumps on each PR merge to integration.
  • version-bump.yml updated to implement minor-bump-on-promote with dual version scheme (main: X.Y+1.0, integration: X.Y+1.1).
  • tests.yml updated to regenerate hooks.json and render recipes as CI preflight steps.
  • 3 new Claude Code hooks: session_start_reminder (SessionStart), token_summary_appender (PostToolUse), unsafe_install_guard (PreToolUse).
  • Config schema additions: allowed_labels, packs.enabled, workspace.worktree_root, workspace.runs_root.

Breaking Changes

  • skill_cmd_check path prefix: temp/ prefix removed from valid path prefixes — skill commands using bare temp/ paths must use .autoskillit/temp/ instead.
  • config.yaml strict validation: Unknown configuration keys now cause a startup error. Audit configs for stale or mistyped keys.
  • Minor-bump-on-promote: Version bump on promotion changed from reverse-sync to minor bump with dual-scheme strategy.

Attention Required

  • Regenerate hooks after upgrade: Run autoskillit doctor to detect and resolve hook drift. New hooks will not activate until autoskillit init or the doctor prompt regenerates them.
  • Review config.yaml: Strict schema validation will reject configs with unrecognized keys. Audit config files before promoting to production.
  • CI workflow overhaul: The two-tier versioning strategy (patch-bump-integration + minor-bump-on-promote) should be validated end-to-end.

Merged PRs

PR Title Author +/-
#577 Split promote-to-main into Changelog PR Skill + Review-Promotion Skill Trecek +633/-448
#574 Token Telemetry Cross-Contamination — order_id Scoping Trecek +948/-137
#573 Implementation Plan: Bug — prepare-issue Uses Summary Instead of Full Validated Report Trecek +109/-0
#571 Reduce audit-arch false positives with pre-flight & self-validation gates Trecek +207/-6
#570 Cohesion audit: server fixes, hook registry, docs, and test coverage Trecek +1974/-24
#569 [FIX] Rectify: Workspace Clean Does Not Discover or Remove Git Worktrees Trecek +769/-78
#568 Rectify: Session Adjudication False-Positive — Recovery/Channel-B Contract Breach Trecek +294/-53
#564 fix: resolve architectural audit findings across codebase Trecek +486/-75
#563 Implementation Plan: Fix xdist Isolation — Hardcoded /dev/shm and /tmp Paths (groupB) Trecek +14/-5
#562 Implementation Plan: Remove Over-Mocked Tests and Fix State Mutation (groupC) Trecek +10/-84
#561 Implementation Plan: Low-Severity Test Suite Fixes (groupH) Trecek +12/-15
#560 Fix Misleading Test Names and Stale Logic (groupF) Trecek +24/-50
#559 Implementation Plan: Strengthen Exception-Grade HIGH Findings (groupD) Trecek +38/-13
#558 Implementation Plan: Consolidate and Remove Redundant/Duplicate Tests (groupE) Trecek +38/-301
#557 Implementation Plan: Remove Tautological/Import-Only Tests — groupA Trecek +0/-99
#556 Fix Test Placement, Organization, and Documentation (groupG) Trecek +164/-141
#551 Implementation Plan: token_summary_appender — Replace gh pr edit/view with REST API Trecek +69/-24
#549 Implementation Plan: Skill Pack Registry and Configurable Visibility Infrastructure Trecek +517/-58
#548 Fix cook --resume UnusedCliTokensError Trecek +160/-35
#546 Rectify: Pipeline Identity Layer Trecek +500/-79
#545 Rectify: Stale-Check Dismiss/Snooze State Split Trecek +554/-36
#544 Rectify: push_to_remote Non-Fast-Forward Rejection After Rebase Trecek +530/-8
#543 Rectify: Headless Editable Install Poison Trecek +905/-11
#542 Rectify: MCP Tool Name Prefix Non-Determinism in Orchestrator Prompts Trecek +257/-28
#536 Rectify: terminal_guard() Exit-Only Ownership Contract Trecek +60/-22
#535 Rectify: SkillResult.session_id Channel B Backfill & Prompt Contract Enforcement Trecek +235/-17
#534 Rectify: Stale Hook Prompt Enters Infinite Loop When User Answers Y Trecek +197/-3
#531 Rectify: Session ID Resolution — Fragmented Sources, Late Merge, No Write-Back Trecek +298/-29
#530 Implementation Plan: Patch-Bump-Integration.yml Races When Merge Queue Batches Multiple PRs Trecek +33/-0
#528 Add validate-audit skill: parallel post-audit finding validation Trecek +365/-9
#521 Implementation Plan: terminal_guard() Alternate Screen Buffer Envelope Trecek +71/-0
#520 Rectify: TestRunner Protocol Returns Lossy Bare Tuple; Non-Pytest Runners Produce False Negatives Trecek +174/-43
#519 Rectify: MergeQueueWatcher Terminal State via Negative Inference Trecek +227/-14
#518 Detect Stale Installs — Doctor Check, Auto-Detect Prompt, and Dev-Mode Install Trecek +521/-2
#517 Replace Reverse-Sync Version Bumping with Minor-Bump-on-Promote Strategy Trecek +264/-213
#511 Rectify: Terminal Ownership Contract Trecek +431/-4
#510 Add --resume flag to cook and order CLI commands Trecek +552/-34
#508 Rectify: stdlib-only Contract for SKILL.md Python Blocks Trecek +1255/-171
#505 Implementation Plan: Add Configurable Label Whitelist to Dynaconf Config Trecek +346/-0
#502 Rectify: Formatter Raw/Derived Field Duplication Trecek +451/-6
#500 Merge Queue Detection Should Validate Workflow Has merge_group Trigger Trecek +255/-21
#495 Rectify: pretty_output Hook — Typed Payload Dispatch Trecek +222/-41
#493 Defer Clone Cleanup Until All Parallel Pipelines Complete Trecek +907/-42
#492 Implementation Plan: open-pr Skill Strips PART X ONLY Suffix from PR Title Trecek +27/-6
#491 Rectify: Hardcoded origin in Skill Bash Blocks — PART A ONLY Trecek +408/-19
#490 Rectify: format_ingredients_table GFM Width Cap Trecek +250/-14
#485 Rectify: Non-Blocking Dispatch Immunity — PART B ONLY Trecek +667/-170
#484 Rectify: Structured Output Instruction Hardening — PART B ONLY Trecek +743/-27
#483 Rectify: Advisory Step Context-Limit Routing — Remaining Steps — PART B ONLY Trecek +304/-1
#482 relocate temp artifact paths from temp/ to .autoskillit/temp/ Trecek +304/-261
#478 Rectify: Order Parameter Table Breaks With Long Descriptions — PART A ONLY Trecek +382/-79
#476 Rectify: Config Schema Contamination & Misplaced Secrets Immunity — PART A ONLY Trecek +327/-20
#474 Rectify: Secret Scanning Gate Ordering — PART A ONLY Trecek +297/-29
#473 Rectify: Root .gitignore Write Path — PART A ONLY Trecek +153/-10
#472 Implementation Plan: Three-Way Merge Routing for autoMergeAllowed Trecek +641/-48
#467 Rectify: Token Telemetry Contamination — PART A ONLY Trecek +588/-121
#465 Rectify: Structured Output Markdown Fragility — PART A ONLY Trecek +655/-31
#464 Implementation Plan: First-Run Detection and Guided Onboarding Experience Trecek +700/-27
#463 Add Parallel Step Scheduling Rule to Sous-Chef Prompt Trecek +227/-0
#460 Implementation Plan: Orchestrator Must Detect Merge Queue and Sequence Merges Trecek +160/-0
#459 Implementation Plan: Stable Recipe Listing Order: Bundled First, Then User-Defined Trecek +116/-3
#458 Implementation Plan: open-pr-main Token Usage Summary Trecek +101/-0
#454 Implementation Plan: Strict Schema Validation for config.yaml Trecek +223/-43
#453 Rectify: Retry Reason Routing Blindness — PART A ONLY Trecek +365/-34
#452 Init — Require Explicit Opt-in to Bypass Missing Secret Scanning Hook Trecek +316/-0
#451 Implementation Plan: Orchestrator Must Claim All Issues Upfront in Multi-Issue Runs Trecek +178/-39
#450 Rectify: Token Summary Note-Protocol Immunity Trecek +207/-187
#446 Implementation Plan: Auto-Merge Direct Merge Fallback (Issue #401) Trecek +401/-10
#442 Rectify: Init Gitignore Completeness Immunity Trecek +157/-1

Linked Issues

Issue Title Status
#401 Auto-merge should work without merge queue — direct merge fallback CLOSED
#427 feat: add --resume flag to cook and order CLI commands OPEN
#429 feat: validate-audit skill — post-audit finding validation with parallel subagents OPEN
#440 open-pr-main should include aggregate token usage from constituent PRs CLOSED
#441 Token summaries no longer appear in pipeline-created PRs targeting integration CLOSED
#444 Orchestrator must detect merge queue and sequence merges for non-queue repos CLOSED
#445 Orchestrator must claim all issues upfront in multi-issue runs CLOSED
#447 Bug: Empty headless session result misclassified as context limit CLOSED
#448 Init: require explicit opt-in to bypass missing secret scanning hook CLOSED
#449 Strict schema validation for config.yaml CLOSED
#456 Stable recipe listing order: bundled first, then user-defined CLOSED
#457 feat: First-Run Detection and Guided Onboarding Experience CLOSED
#461 Add Parallel Step Scheduling Rule to Sous-Chef Prompt CLOSED
#462 False positive adjudicated_failure on make-plan despite successful plan output CLOSED
#466 Token Usage Summary in PR Bodies Shows Garbage CLOSED
#468 Relocate temp directory from temp/ to .autoskillit/temp/ CLOSED
#469 direct_merge step fails silently on repos without autoMergeAllowed CLOSED
#470 Bug: secret scanning gate silently skipped during init in empty project CLOSED
#471 autoskillit init fails to add .secrets.yaml to root .gitignore CLOSED
#475 autoskillit order parameter table breaks with long descriptions CLOSED
#477 adjudicated_failure false positive: make-plan session killed after successful plan write CLOSED
#480 report_bug tool: non-blocking dispatch silently fails to create GitHub issue CLOSED
#481 Remediation recipe: review step lacks on_context_limit/retries CLOSED
#486 Defer clone cleanup until all parallel pipelines complete CLOSED
#487 resolve-merge-conflicts skill fetches from stale local origin CLOSED
#488 open-pr skill copies PART X ONLY suffix into PR title CLOSED
#494 pretty_output hook silently eats get_token_summary format="table" responses CLOSED
#498 Merge queue detection should validate workflow has merge_group trigger OPEN
#499 Duplicate ingredient row in recipe table OPEN
#503 Add configurable label whitelist to dynaconf config OPEN
#506 Token summary missing from PRs CLOSED
#507 wait_for_merge_queue misclassifies pending CI as ejected OPEN
#509 Terminal left in raw mode after abnormal exit OPEN
#512 Replace reverse-sync version bumping with minor-bump-on-promote OPEN
#513 test_check returns false negative for non-pytest test runners OPEN
#514 Detect stale installs: doctor check, auto-detect prompt OPEN
#516 terminal_guard() does not clear main-buffer TUI content CLOSED
#522 feat: Skill Pack Registry and Configurable Visibility Infrastructure OPEN
#527 SkillResult.session_id lost on stale/timeout paths OPEN
#529 patch-bump-integration.yml races when merge queue batches multiple PRs OPEN
#532 fix: stale hook prompt enters infinite loop when user answers Y OPEN
#533 terminal_guard() alternate screen buffer entry breaks scrollbar OPEN
#537 push_to_remote non-fast-forward rejection after rebase OPEN
#538 Headless editable install poison OPEN
#539 MCP tool name prefix non-determinism in orchestrator prompts OPEN
#540 SkillResult.session_id Channel B backfill not applied OPEN
#541 terminal_guard() exit-only ownership contract OPEN
#547 Stale-check dismiss/snooze state split OPEN
#550 token_summary_appender — replace gh pr edit/view with REST API OPEN
#553 Test suite audit groupA: Remove tautological/import-only tests OPEN
#554 Test suite audit groupE: Consolidate redundant tests OPEN
#555 Test suite audit groupF: Fix misleading test names OPEN
#565 Test suite audit groupB: Fix xdist isolation OPEN
#566 Test suite audit groupC: Remove over-mocked tests OPEN
#567 Test suite audit groupD: Strengthen HIGH findings OPEN
#572 Bug: prepare-issue uses summary instead of full report OPEN
#576 Split promote-to-main into Changelog PR + Review-Promotion OPEN

Attention Required

Three areas need human review:

  1. CI workflow overhaul: The two-tier versioning strategy (patch-bump-integration.yml + version-bump.yml) forms a new dual-version scheme that should be validated end-to-end.
  2. New hooks: token_summary_appender (uses gh api to mutate PR bodies), session_start_reminder (new SessionStart hook type), and unsafe_install_guard are all new production hooks.
  3. skill_cmd_check.py: Removed temp/ from valid path prefixes — any skills or plans referencing bare temp/ paths will now be blocked.

Architecture Impact

Module Dependency (Structural — "How are modules coupled?")

Click to expand module dependency diagram
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 70, 'curve': 'basis'}}}%%
graph TB
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;

    subgraph L3_APP ["L3 — APPLICATION"]
        direction TB
        subgraph L3_SERVER ["● server/"]
            direction LR
            SVR_INIT["● __init__<br/>━━━━━━━━━━<br/>FastMCP app, tag gating"]
            SVR_FACTORY["● _factory.py<br/>━━━━━━━━━━<br/>Composition Root"]
            SVR_HELPERS["● helpers.py<br/>━━━━━━━━━━<br/>Cross-cutting facade"]
            SVR_TOOLS["● tools_*.py<br/>━━━━━━━━━━<br/>14 tool modules"]
            SVR_GIT["● git.py<br/>━━━━━━━━━━<br/>Merge workflow"]
            SVR_GUARD["★ _editable_guard.py<br/>━━━━━━━━━━<br/>Worktree install guard"]
        end
        subgraph L3_CLI ["● cli/"]
            direction LR
            CLI_APP["● app.py<br/>━━━━━━━━━━<br/>CLI entry point"]
            CLI_COOK["● _cook.py<br/>━━━━━━━━━━<br/>Session launcher"]
            CLI_ONBOARD["★ _onboarding.py<br/>━━━━━━━━━━<br/>First-run menu"]
            CLI_STALE["★ _stale_check.py<br/>━━━━━━━━━━<br/>Stale install detect"]
            CLI_TERM["★ _terminal.py<br/>━━━━━━━━━━<br/>TTY guard"]
        end
    end

    subgraph L2_DOMAIN ["L2 — DOMAIN"]
        direction LR
        RCP["● recipe/<br/>━━━━━━━━━━<br/>Schema, rules, API"]
        MIG["migration/<br/>━━━━━━━━━━<br/>MigrationEngine"]
    end

    subgraph L1_SERVICES ["L1 — SERVICES"]
        direction LR
        EXEC["● execution/<br/>━━━━━━━━━━<br/>Headless, CI, merge queue"]
        PIP["● pipeline/<br/>━━━━━━━━━━<br/>★ background.py<br/>ToolContext, tokens"]
        WS["● workspace/<br/>━━━━━━━━━━<br/>★ clone_registry.py<br/>★ worktree.py"]
        CFG["● config/<br/>━━━━━━━━━━<br/>Layered settings"]
    end

    subgraph L0 ["L0 — FOUNDATION"]
        CORE["● core/<br/>━━━━━━━━━━<br/>★ _terminal_table.py<br/>fan-in: 93 files"]
    end

    subgraph HOOKS ["STANDALONE — HOOKS"]
        direction LR
        HK["★ 3 new hooks<br/>━━━━━━━━━━<br/>stdlib-only, self-contained"]
    end

    SVR_HELPERS --> RCP
    SVR_HELPERS --> EXEC
    SVR_HELPERS --> WS
    SVR_FACTORY --> PIP
    SVR_FACTORY --> CFG
    CLI_APP --> MIG
    CLI_COOK --> EXEC
    CLI_COOK --> WS
    RCP -.->|"deferred"| WS
    MIG -.->|"deferred"| RCP
    EXEC -.->|"TYPE_CHECKING"| PIP
    PIP --> CFG
    CFG --> CORE
    PIP --> CORE
    EXEC --> CORE
    WS --> CORE

    class SVR_INIT,SVR_FACTORY,SVR_HELPERS,SVR_TOOLS,SVR_GIT,CLI_APP,CLI_COOK cli;
    class RCP,MIG phase;
    class EXEC,PIP,WS,CFG handler;
    class CORE stateNode;
    class SVR_GUARD,CLI_ONBOARD,CLI_STALE,CLI_TERM,HK newComponent;
Loading

Legend: ● Modified | ★ New | Dashed = deferred/TYPE_CHECKING import | 0 layer violations found

Process Flow (Physiological — "How does it behave?")

Click to expand process flow diagram
%%{init: {'flowchart': {'nodeSpacing': 40, 'rankSpacing': 50, 'curve': 'basis'}}}%%
flowchart TB
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;

    START([run_skill called])

    subgraph HEADLESS ["● Headless Session Lifecycle"]
        direction TB
        HL_BUILD["● build_full_headless_cmd"]
        HL_RUN["● ctx.runner — async subprocess"]
        HL_TERM{"● Termination reason?"}
        HL_STALE["Stale recovery"]
        HL_PARSE["● parse_session_result"]
        HL_RECOVER["● Recovery chain"]
        HL_OUTCOME["● _compute_outcome"]
    end

    subgraph GATES ["● Post-Outcome Gates"]
        direction TB
        GT_PATH{"★ Path contamination?"}
        GT_BUDGET{"● Budget exhausted?"}
        GT_CONTRACT{"● Contract recovery?"}
        GT_ZERO{"★ Zero-write check?"}
    end

    T_SUCCESS([SUCCEEDED])
    T_RETRY([RETRIABLE])
    T_FAILED([FAILED])

    START --> HL_BUILD --> HL_RUN --> HL_TERM
    HL_TERM -->|"STALE"| HL_STALE
    HL_TERM -->|"TIMED_OUT"| T_FAILED
    HL_TERM -->|"NATURAL/COMPLETED"| HL_PARSE
    HL_STALE -->|"recovered"| T_SUCCESS
    HL_STALE -->|"failed"| GT_BUDGET
    HL_PARSE --> HL_RECOVER --> HL_OUTCOME
    HL_OUTCOME --> GT_PATH --> GT_BUDGET
    GT_BUDGET -->|"exhausted"| T_FAILED
    GT_BUDGET -->|"ok"| GT_CONTRACT --> GT_ZERO
    GT_ZERO -->|"pass"| T_SUCCESS
    GT_ZERO -->|"retriable"| T_RETRY
    GT_ZERO -->|"terminal"| T_FAILED

    class START,T_SUCCESS,T_RETRY,T_FAILED terminal;
    class HL_TERM stateNode;
    class GT_PATH,GT_BUDGET,GT_CONTRACT,GT_ZERO detector;
    class HL_BUILD,HL_RUN,HL_PARSE,HL_RECOVER,HL_OUTCOME,HL_STALE handler;
Loading

Legend: 9 RetryReasons (RESUME, STALE, DRAIN_RACE, PATH_CONTAMINATION, CONTRACT_RECOVERY, ZERO_WRITES, EARLY_STOP, EMPTY_OUTPUT, BUDGET_EXHAUSTED) | ★ = new gates added in this promotion

Development (Build & Test — "How is it built and tested?")

Click to expand development diagram
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;

    subgraph Structure ["PROJECT — 141 src, 273 test files"]
        direction LR
        SRC["● src/autoskillit/"]
        TESTS["● tests/ — 12 subdirs"]
    end

    subgraph Quality ["CODE QUALITY — 7 pre-commit hooks"]
        direction LR
        RUFF["● ruff format + check"]
        MYPY["mypy"]
        GITLEAKS["gitleaks"]
        NOGEN["★ no-generated-configs"]
    end

    subgraph Arch ["ARCHITECTURE ENFORCEMENT"]
        IL["● import-linter — 7 contracts"]
    end

    subgraph Test ["TEST — pytest -n4, asyncio_mode=auto"]
        direction LR
        PYTEST["● pytest + xdist"]
        CONFTEST["● conftest.py<br/>★ _isolated_home"]
    end

    subgraph CI ["CI/CD — 5 workflows"]
        direction TB
        TESTS_YML["● tests.yml<br/>★ hooks.json regen"]
        PATCH["★ patch-bump-integration.yml"]
        VERSION["● version-bump.yml<br/>★ minor-bump-on-promote"]
    end

    subgraph Entry ["ENTRY POINTS"]
        direction LR
        CLI["● autoskillit CLI"]
        MCP["● FastMCP — 42 tools"]
        HOOKS["● Hooks<br/>★ 3 new"]
    end

    SRC --> RUFF --> MYPY --> GITLEAKS --> NOGEN --> IL --> PYTEST
    TESTS --> PYTEST
    PYTEST --> CONFTEST
    CONFTEST --> TESTS_YML
    TESTS_YML -->|"PR merge"| PATCH
    PATCH -->|"promote"| VERSION
    SRC --> CLI
    SRC --> MCP
    SRC --> HOOKS

    class SRC,TESTS cli;
    class RUFF,MYPY,GITLEAKS detector;
    class IL stateNode;
    class PYTEST,CONFTEST handler;
    class TESTS_YML handler;
    class CLI,MCP,HOOKS output;
    class NOGEN,PATCH,VERSION newComponent;
Loading

Legend: ★ = new in this promotion | Version strategy: PR merge → patch bump (auto) → promote → minor bump (auto)

Closes #576
Closes #572
Closes #553
Closes #555
Closes #566
Closes #567
Closes #565
Closes #554
Closes #550
Closes #522
Closes #547
Closes #538
Closes #540
Closes #537
Closes #539
Closes #541
Closes #533
Closes #527
Closes #532
Closes #529
Closes #429
Closes #516
Closes #513
Closes #507
Closes #514
Closes #512
Closes #509
Closes #427
Closes #506
Closes #503
Closes #499
Closes #498
Closes #494
Closes #486
Closes #488
Closes #487
Closes #480
Closes #477
Closes #481
Closes #468
Closes #475
Closes #470
Closes #471
Closes #469
Closes #466
Closes #462
Closes #457
Closes #461
Closes #444
Closes #456
Closes #440
Closes #449
Closes #447
Closes #448
Closes #445
Closes #441
Closes #401

Generated with Claude Code via AutoSkillit

github-actions Bot and others added 30 commits March 24, 2026 03:37
#500)

## Summary

When `check_merge_queue` detects that a branch has an active GitHub
merge queue, the pipeline immediately routes to `enable_auto_merge`,
which enrolls the PR in the queue. However, if the repository's CI
workflow does not include the `merge_group` event trigger, CI never
fires on the temporary merge branch, the PR times out, and the pipeline
enters a futile ejection/rebase/re-entry loop.

This plan inserts a new `check_merge_group_trigger` step between
`check_merge_queue` and `check_auto_merge` that validates the presence
of `merge_group` in `.github/workflows/`. It also tightens the
`route_queue_mode` conditions to require the trigger to be confirmed
before routing to `enable_auto_merge`. When the trigger is absent, the
pipeline logs a clear warning and falls through to the non-queue merge
path.

The fix applies identically to all three affected recipes:
`implementation.yaml`, `remediation.yaml`, and
`implementation-groups.yaml`.

## Architecture Impact

### Process Flow Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;

    START([ci_watch succeeds])

    subgraph Detection ["Queue Detection Phase"]
        CMQ["● check_merge_queue<br/>━━━━━━━━━━<br/>GraphQL: mergeQueue.id<br/>→ queue_available<br/>skip_when_false: inputs.open_pr"]
        CMGT["★ check_merge_group_trigger<br/>━━━━━━━━━━<br/>gh api: .github/workflows/**<br/>grep merge_group in content<br/>→ merge_group_trigger<br/>skip_when_false: inputs.open_pr"]
        CAM["check_auto_merge<br/>━━━━━━━━━━<br/>GraphQL: autoMergeAllowed<br/>→ auto_merge_available<br/>skip_when_false: inputs.open_pr"]
    end

    subgraph Routing ["● route_queue_mode (updated conditions)"]
        RQM{"● route_queue_mode<br/>━━━━━━━━━━<br/>Evaluate context flags"}
    end

    subgraph QueuePath ["Queue Merge Path"]
        EAM["enable_auto_merge<br/>━━━━━━━━━━<br/>gh pr merge --squash --auto<br/>skip_when_false: inputs.open_pr"]
        WFQ["wait_for_queue<br/>━━━━━━━━━━<br/>wait_for_merge_queue tool<br/>timeout: 900s"]
    end

    subgraph NonQueuePaths ["Non-Queue Merge Paths"]
        DM["direct_merge<br/>━━━━━━━━━━<br/>autoMergeAllowed=true<br/>gh pr merge --squash --auto"]
        IM["immediate_merge<br/>━━━━━━━━━━<br/>fallthrough default<br/>gh pr merge --squash (no auto)"]
    end

    WARN["★ Warning: merge_group absent<br/>━━━━━━━━━━<br/>Logged to stderr<br/>merge_group_trigger = false"]
    SUCCESS([release_issue_success])
    EJECTED["queue_ejected_fix<br/>━━━━━━━━━━<br/>resolve-merge-conflicts"]
    STALLED["reenroll_stalled_pr"]
    TIMEOUT([release_issue_timeout])
    CLEANUP([confirm_cleanup])

    START --> CMQ
    CMQ -->|"open_pr=false → skipped<br/>on_failure"| CLEANUP
    CMQ -->|"on_success"| CMGT
    CMGT -->|"merge_group found"| CAM
    CMGT -->|"merge_group absent"| WARN
    WARN -. "merge_group_trigger=false" .-> CAM
    CAM --> RQM

    RQM -->|"inputs.auto_merge != true"| CLEANUP
    RQM -->|"queue_available=true<br/>AND merge_group_trigger=true"| EAM
    RQM -->|"auto_merge_available=true<br/>(queue unavailable or trigger absent)"| DM
    RQM -->|"default fallthrough"| IM

    EAM --> WFQ
    WFQ -->|"pr_state=merged"| SUCCESS
    WFQ -->|"pr_state=ejected"| EJECTED
    WFQ -->|"pr_state=stalled"| STALLED
    WFQ -->|"pr_state=timeout / default"| TIMEOUT
    DM --> SUCCESS
    IM --> SUCCESS

    %% CLASS ASSIGNMENTS %%
    class START,SUCCESS,TIMEOUT,CLEANUP terminal;
    class CMQ,CAM handler;
    class CMGT,WARN newComponent;
    class RQM stateNode;
    class EAM,WFQ,DM,IM phase;
    class EJECTED,STALLED detector;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | Terminal | Start, success, timeout, and cleanup endpoints
|
| Orange | Handler | Detection steps (check_merge_queue,
check_auto_merge) |
| Green | New Component | ★ New: check_merge_group_trigger step and
warning node |
| Teal | State | Route decision node (route_queue_mode) |
| Purple | Phase | Merge execution steps (enable_auto_merge,
wait_for_queue, etc.) |
| Red | Detector | Failure/ejection handling nodes |

Closes #498

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/impl-20260324-215204-828225/.autoskillit/temp/make-plan/merge-queue-detection-validate-workflow-trigger_plan_2026-03-24_000000.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
## Summary

`LoadRecipeResult` carries both `content` (raw YAML text including the
`ingredients:` block) and `ingredients_table` (a GFM table derived from
those same ingredients). The PostToolUse formatter
(`_fmt_recipe_body()`) rendered both unconditionally, causing duplicate
ingredient display. This PR installs the missing structural signal: a
`_LOAD_RECIPE_DERIVED_FROM` mapping that makes the derivation
relationship machine-readable, augments the field-coverage test to
validate it, and drives `_fmt_recipe_body()` to automatically strip
derived-field content from source fields. It also adds a
`pipeline-internal-not-hidden` semantic rule that enforces `hidden:
true` on ingredients whose descriptions reveal automation-only use, and
updates bundled recipe YAMLs accordingly.

## Architecture Impact

### Data Lineage Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart LR
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;

    subgraph Source ["Data Origin"]
        YAML["recipe.yaml<br/>━━━━━━━━━━<br/>ingredients: block<br/>steps:<br/>kitchen_rules:<br/>(hidden: true markers)"]
    end

    subgraph Producer ["● Producer: recipe/_api.py"]
        PARSE["load_and_validate()<br/>━━━━━━━━━━<br/>parse + validate<br/>find_recipe_by_name()"]
        RECIPE_OBJ["Recipe dataclass<br/>━━━━━━━━━━<br/>typed ingredient list"]
        MERGE["● _merge_sub_recipe()<br/>━━━━━━━━━━<br/>skips hidden=True<br/>sub-recipe ingredients"]
        BUILD["build_ingredient_rows()<br/>━━━━━━━━━━<br/>filters hidden=True<br/>sorts by priority"]
        RAWCONTENT["content: str<br/>━━━━━━━━━━<br/>full raw YAML text<br/>(source form)"]
        INGTABLE["ingredients_table: str<br/>━━━━━━━━━━<br/>GFM markdown table<br/>(derived display form)"]
    end

    subgraph Boundary ["● TypedDict Boundary"]
        LOADRESULT["● LoadRecipeResult<br/>━━━━━━━━━━<br/>content + ingredients_table<br/>+ suggestions + valid"]
    end

    subgraph Rule ["★ Semantic Rule: rules_inputs.py"]
        PINH["★ pipeline-internal-not-hidden<br/>━━━━━━━━━━<br/>warns when ingredient lacks<br/>hidden: true but description<br/>signals automation-only use"]
        SUGGESTIONS["suggestions: list<br/>━━━━━━━━━━<br/>WARNING findings<br/>flow into LoadRecipeResult"]
    end

    subgraph Contract ["★ Derivation Contract: pretty_output.py"]
        DERIVEDMAP["★ ● _LOAD_RECIPE_DERIVED_FROM<br/>━━━━━━━━━━<br/>{'ingredients_table': 'content'}<br/>machine-readable source map"]
        STRIPFN["★ _strip_yaml_ingredients_block()<br/>━━━━━━━━━━<br/>removes ingredients: YAML block<br/>when derived table present"]
    end

    subgraph Formatter ["● Formatter: _fmt_recipe_body()"]
        FMTBODY["● _fmt_recipe_body()<br/>━━━━━━━━━━<br/>consults derivation map<br/>strips source block<br/>when derived field present"]
        RECIPESEC["--- RECIPE ---<br/>━━━━━━━━━━<br/>YAML minus ingredients: block<br/>(steps, kitchen_rules only)"]
        TABLESEC["--- INGREDIENTS TABLE ---<br/>━━━━━━━━━━<br/>sole display of ingredients<br/>sorted + filtered"]
    end

    AGENT(["LLM Agent<br/>━━━━━━━━━━<br/>sees each ingredient once"])

    YAML -->|"read_text()"| PARSE
    PARSE -->|"raw text"| RAWCONTENT
    PARSE -->|"_parse_recipe()"| RECIPE_OBJ
    RECIPE_OBJ -->|"sub-recipe merge"| MERGE
    MERGE -->|"hidden filtered"| BUILD
    BUILD -->|"format_ingredients_table()"| INGTABLE
    RAWCONTENT --> LOADRESULT
    INGTABLE --> LOADRESULT
    RECIPE_OBJ -->|"validate ingredients"| PINH
    PINH -->|"RuleFinding WARNING"| SUGGESTIONS
    SUGGESTIONS --> LOADRESULT
    LOADRESULT -->|"PostToolUse hook stdin"| FMTBODY
    DERIVEDMAP -->|"consulted at render"| FMTBODY
    FMTBODY -->|"strip content"| STRIPFN
    STRIPFN -->|"stripped YAML"| RECIPESEC
    FMTBODY -->|"pass through"| TABLESEC
    RECIPESEC --> AGENT
    TABLESEC --> AGENT

    class YAML cli;
    class PARSE,BUILD handler;
    class RECIPE_OBJ,LOADRESULT stateNode;
    class RAWCONTENT,INGTABLE stateNode;
    class MERGE handler;
    class PINH detector;
    class SUGGESTIONS phase;
    class DERIVEDMAP,STRIPFN newComponent;
    class FMTBODY handler;
    class RECIPESEC,TABLESEC output;
    class AGENT terminal;
```

### Process Flow Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 40, 'rankSpacing': 50, 'curve': 'basis'}}}%%
flowchart TB
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;

    START(["PostToolUse Hook<br/>━━━━━━━━━━<br/>stdin: JSON event"])

    subgraph Dispatch ["Hook Dispatch"]
        RESOLVE["_resolve_payload()<br/>━━━━━━━━━━<br/>unwrap MCP envelope<br/>→ DictPayload"]
        ROUTE{"tool_name?<br/>━━━━━━━━━━<br/>short name match"}
        FMTLR["_fmt_load_recipe()<br/>━━━━━━━━━━<br/>wraps _fmt_recipe_body()"]
    end

    subgraph DerivCheck ["● Derivation-Aware Content Render"]
        GETFIELDS["get content, ingredients_table<br/>━━━━━━━━━━<br/>from data dict"]
        LOOPDERIV{"★ for each entry in<br/>_LOAD_RECIPE_DERIVED_FROM<br/>━━━━━━━━━━<br/>source_field == 'content'?"}
        HASDERIVED{"★ data.get(derived_field)<br/>━━━━━━━━━━<br/>derived value present?"}
        CALLSTRIP["★ _strip_yaml_ingredients_block()<br/>━━━━━━━━━━<br/>strip source block"]
        DISPLAYCONTENT["display_content<br/>━━━━━━━━━━<br/>original or stripped YAML"]
    end

    subgraph StripSM ["★ _strip_yaml_ingredients_block() — Line State Machine"]
        ITERLINES["iterate YAML lines<br/>━━━━━━━━━━<br/>splitlines(keepends=True)"]
        CHKINGKEY{"line starts with<br/>'ingredients:'?"}
        SETFLAG["in_ingredients = True<br/>━━━━━━━━━━<br/>skip this line"]
        CHKINDENT{"in_ingredients AND<br/>line non-empty AND<br/>not line[0].isspace()?"}
        CLEARFLAG["in_ingredients = False<br/>━━━━━━━━━━<br/>next top-level key"]
        KEEPLINE["append line to result"]
        SKIPLINE["skip line<br/>━━━━━━━━━━<br/>indented child of ingredients:"]
        JOINRESULT["''.join(result)<br/>━━━━━━━━━━<br/>return stripped YAML"]
    end

    subgraph RenderOut ["Output Render"]
        APPENDRECIPE["append --- RECIPE --- block<br/>━━━━━━━━━━<br/>display_content (stripped)"]
        HASINGTABLE{"ing_table present?"}
        APPENDTABLE["append --- INGREDIENTS TABLE ---<br/>━━━━━━━━━━<br/>GFM table pass-through"]
        HASERRORS{"errors in suggestions?"}
        APPENDERRORS["append N finding(s)<br/>━━━━━━━━━━<br/>error/warning count"]
    end

    subgraph RuleFlow ["★ pipeline-internal-not-hidden Rule (validation time)"]
        ITERINGR["iterate recipe.ingredients<br/>━━━━━━━━━━<br/>ValidationContext"]
        CHKHIDDEN{"ing.hidden == True?"}
        CHKPATTERN{"★ _PIPELINE_INTERNAL_PATTERNS<br/>━━━━━━━━━━<br/>.search(desc) matches?"}
        EMITFINDING["emit RuleFinding<br/>━━━━━━━━━━<br/>severity=WARNING<br/>rule=pipeline-internal-not-hidden"]
        SKIPINGR["skip (already correct)"]
    end

    HOOKOUT(["Hook stdout<br/>━━━━━━━━━━<br/>updatedMCPToolOutput<br/>Markdown-KV string"])

    START --> RESOLVE
    RESOLVE --> ROUTE
    ROUTE -->|"load_recipe / open_kitchen"| FMTLR
    ROUTE -->|"other tools"| HOOKOUT

    FMTLR --> GETFIELDS
    GETFIELDS --> LOOPDERIV
    LOOPDERIV -->|"source is 'content'"| HASDERIVED
    LOOPDERIV -->|"no more entries"| DISPLAYCONTENT
    HASDERIVED -->|"YES: table present"| CALLSTRIP
    HASDERIVED -->|"NO: table absent"| DISPLAYCONTENT
    CALLSTRIP --> JOINRESULT
    JOINRESULT --> DISPLAYCONTENT

    CALLSTRIP --> ITERLINES
    ITERLINES --> CHKINGKEY
    CHKINGKEY -->|"YES"| SETFLAG
    CHKINGKEY -->|"NO"| CHKINDENT
    SETFLAG --> ITERLINES
    CHKINDENT -->|"YES: top-level key"| CLEARFLAG
    CHKINDENT -->|"NO: still indented"| SKIPLINE
    CLEARFLAG --> KEEPLINE
    SKIPLINE --> ITERLINES
    KEEPLINE --> ITERLINES

    DISPLAYCONTENT --> APPENDRECIPE
    APPENDRECIPE --> HASINGTABLE
    HASINGTABLE -->|"YES"| APPENDTABLE
    HASINGTABLE -->|"NO"| HASERRORS
    APPENDTABLE --> HASERRORS
    HASERRORS -->|"YES"| APPENDERRORS
    HASERRORS -->|"NO"| HOOKOUT
    APPENDERRORS --> HOOKOUT

    ITERINGR --> CHKHIDDEN
    CHKHIDDEN -->|"YES"| SKIPINGR
    CHKHIDDEN -->|"NO"| CHKPATTERN
    CHKPATTERN -->|"MATCH"| EMITFINDING
    CHKPATTERN -->|"NO MATCH"| SKIPINGR
    EMITFINDING --> ITERINGR
    SKIPINGR --> ITERINGR

    class START,HOOKOUT terminal;
    class RESOLVE,FMTLR,GETFIELDS,APPENDRECIPE,APPENDTABLE,APPENDERRORS handler;
    class ROUTE,HASINGTABLE,HASERRORS stateNode;
    class LOOPDERIV,HASDERIVED,CALLSTRIP,DISPLAYCONTENT newComponent;
    class ITERLINES,CHKINGKEY,SETFLAG,CHKINDENT,CLEARFLAG,KEEPLINE,SKIPLINE,JOINRESULT newComponent;
    class ITERINGR,CHKPATTERN,EMITFINDING detector;
    class CHKHIDDEN,SKIPINGR phase;
```

Closes #499

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/remediation-20260324-221121-429358/.autoskillit/temp/rectify/rectify_duplicate-ingredient-row_2026-03-24_222100_part_a.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
…fig (#505)

## Summary

Add a `github.allowed_labels` list to the dynaconf configuration layer.
When configured, all label creation and application operations in the
server tool handlers validate each label name against this list before
executing. An empty or absent list preserves current behavior (no
restriction). The validation lives as a method on `GitHubConfig` — the
dataclass that owns the field — and is called at every label operation
site in the server layer.

## Requirements

### CFG

- **REQ-CFG-001:** The dynaconf configuration must support a
`github.allowed_labels` key that accepts a list of strings.
- **REQ-CFG-002:** The `github.allowed_labels` key must be optional —
when absent or empty, no label restriction is enforced.
- **REQ-CFG-003:** The bundled `defaults.yaml` must include a default
`github.allowed_labels` list containing the project's standard labels.

### VAL

- **REQ-VAL-001:** Any operation that creates a GitHub label must
validate the label name against the configured whitelist before
executing.
- **REQ-VAL-002:** Any operation that applies a label to an issue must
validate the label name against the configured whitelist before
executing.
- **REQ-VAL-003:** When a label is rejected by the whitelist, the system
must return a clear error message identifying the disallowed label and
listing allowed alternatives.

### TEST

- **REQ-TEST-001:** Unit tests must verify that whitelisted labels pass
validation.
- **REQ-TEST-002:** Unit tests must verify that non-whitelisted labels
are rejected with an actionable error message.
- **REQ-TEST-003:** Unit tests must verify that an empty or absent
whitelist permits all labels (backward compatibility).

## Architecture Impact

### Operational Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;

    subgraph Config ["● CONFIGURATION HIERARCHY (read-only)"]
        direction TB
        EnvVars["Environment Variables<br/>━━━━━━━━━━<br/>AUTOSKILLIT_GITHUB__ALLOWED_LABELS<br/>Highest priority override"]
        ProjectYAML["Project .autoskillit/config.yaml<br/>━━━━━━━━━━<br/>github.allowed_labels:<br/>  [custom list]"]
        DefaultsYAML["● defaults.yaml<br/>━━━━━━━━━━<br/>github.allowed_labels:<br/>  [bug, enhancement, in-progress,<br/>   staged, autoreported,<br/>   recipe:implementation,<br/>   recipe:remediation]"]
    end

    subgraph GitHubCfg ["● GITHUBCONFIG (read/write state)"]
        direction TB
        AllowedLabels["● GitHubConfig<br/>━━━━━━━━━━<br/>allowed_labels: list[str]<br/>in_progress_label: str<br/>staged_label: str"]
        CheckMethod["● check_label_allowed(label)<br/>━━━━━━━━━━<br/>Returns None → permitted<br/>Returns str → error message"]
    end

    subgraph CLI ["CLI ENTRY POINTS"]
        direction TB
        ConfigShow["autoskillit config show<br/>━━━━━━━━━━<br/>Inspect resolved allowed_labels<br/>(JSON output)"]
        ServeCmd["autoskillit serve<br/>━━━━━━━━━━<br/>Start MCP server<br/>Loads config at startup"]
    end

    subgraph ValidationGate ["● LABEL VALIDATION GATE (server layer)"]
        direction TB
        PrepareIssue["● prepare_issue<br/>━━━━━━━━━━<br/>check_labels_allowed(labels[])<br/>before skill session launch"]
        ClaimIssue["● claim_issue<br/>━━━━━━━━━━<br/>check_label_allowed(effective_label)<br/>before ensure_label + add_labels"]
        ReleaseIssue["● release_issue<br/>━━━━━━━━━━<br/>check_label_allowed(staged_label)<br/>before ensure_label + add_labels"]
        ReportBug["● _file_or_update_github_issue<br/>━━━━━━━━━━<br/>check_label_allowed per label<br/>before create_issue"]
    end

    subgraph Outcome ["OUTCOMES"]
        direction TB
        Proceed["Label Operation Proceeds<br/>━━━━━━━━━━<br/>GitHub API called normally"]
        Reject["Error Returned<br/>━━━━━━━━━━<br/>success=false / skipped=true<br/>Lists disallowed label + alternatives"]
    end

    %% CONFIG FLOW %%
    EnvVars -->|"highest priority"| AllowedLabels
    ProjectYAML -->|"project override"| AllowedLabels
    DefaultsYAML -->|"base defaults"| AllowedLabels

    %% VALIDATION FLOW %%
    AllowedLabels --> CheckMethod
    CheckMethod --> PrepareIssue
    CheckMethod --> ClaimIssue
    CheckMethod --> ReleaseIssue
    CheckMethod --> ReportBug

    %% CLI %%
    ConfigShow -->|"reads"| AllowedLabels
    ServeCmd -->|"loads"| AllowedLabels

    %% OUTCOMES %%
    PrepareIssue -->|"None = allowed"| Proceed
    ClaimIssue -->|"None = allowed"| Proceed
    ReleaseIssue -->|"None = allowed"| Proceed
    ReportBug -->|"None = allowed"| Proceed
    PrepareIssue -->|"str = rejected"| Reject
    ClaimIssue -->|"str = rejected"| Reject
    ReleaseIssue -->|"str = rejected"| Reject
    ReportBug -->|"str = rejected"| Reject

    %% CLASS ASSIGNMENTS %%
    class EnvVars,ProjectYAML,DefaultsYAML phase;
    class AllowedLabels,CheckMethod stateNode;
    class ConfigShow,ServeCmd cli;
    class PrepareIssue,ClaimIssue,ReleaseIssue,ReportBug handler;
    class Proceed output;
    class Reject detector;
```

### Security Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 40, 'rankSpacing': 50, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;

    subgraph Callers ["UNTRUSTED CALLERS (headless sessions / orchestrator)"]
        direction LR
        PrepareCall["prepare_issue call<br/>━━━━━━━━━━<br/>labels=[list supplied<br/>by AI session]"]
        ClaimCall["claim_issue call<br/>━━━━━━━━━━<br/>label= param<br/>or config default"]
        ReleaseCall["release_issue call<br/>━━━━━━━━━━<br/>staged_label param<br/>or config default"]
        ReportCall["report_bug call<br/>━━━━━━━━━━<br/>github_labels from<br/>report_bug config"]
    end

    subgraph WhitelistSource ["● WHITELIST SOURCE (read-only config)"]
        direction TB
        DefaultsYAML["● defaults.yaml<br/>━━━━━━━━━━<br/>bug, enhancement, in-progress,<br/>staged, autoreported,<br/>recipe:implementation,<br/>recipe:remediation"]
        ProjectOverride["Project config.yaml<br/>━━━━━━━━━━<br/>github.allowed_labels<br/>(operator-controlled)"]
        EnvOverride["Environment override<br/>━━━━━━━━━━<br/>AUTOSKILLIT_GITHUB__<br/>ALLOWED_LABELS"]
    end

    subgraph ValidationGate ["● VALIDATION GATE (server layer — trust boundary)"]
        direction TB
        GitHubCfg["● GitHubConfig.allowed_labels<br/>━━━━━━━━━━<br/>Resolved whitelist<br/>[] = permissive mode"]
        CheckSingle["● check_label_allowed(label)<br/>━━━━━━━━━━<br/>Single-label check<br/>used by claim/release/report"]
        CheckBatch["● check_labels_allowed(labels)<br/>━━━━━━━━━━<br/>Batch check<br/>used by prepare_issue"]
        Decision{"Label in<br/>allowed_labels<br/>OR list empty?"}
    end

    subgraph Blocked ["BLOCKED PATH"]
        ErrorResp["Error Response<br/>━━━━━━━━━━<br/>success=false / skipped=true<br/>Names disallowed label<br/>Lists allowed alternatives<br/>NO GitHub API call made"]
    end

    subgraph GitHubAPI ["TRUSTED EXTERNAL: GitHub API"]
        CreateLabel["gh label create<br/>━━━━━━━━━━<br/>Creates label on repo"]
        AddLabel["gh issue edit --add-label<br/>━━━━━━━━━━<br/>Applies label to issue"]
    end

    %% CONFIG FLOW %%
    DefaultsYAML -->|"base"| GitHubCfg
    ProjectOverride -->|"override"| GitHubCfg
    EnvOverride -->|"highest priority"| GitHubCfg

    %% VALIDATION ROUTING %%
    GitHubCfg --> CheckSingle
    GitHubCfg --> CheckBatch
    CheckSingle --> Decision
    CheckBatch --> Decision

    %% CALLER → GATE %%
    PrepareCall -->|"labels list"| CheckBatch
    ClaimCall -->|"effective_label"| CheckSingle
    ReleaseCall -->|"staged_label"| CheckSingle
    ReportCall -->|"each github_label"| CheckSingle

    %% OUTCOMES %%
    Decision -->|"DENY: str error"| ErrorResp
    Decision -->|"ALLOW: None"| CreateLabel
    Decision -->|"ALLOW: None"| AddLabel

    %% CLASS ASSIGNMENTS %%
    class PrepareCall,ClaimCall,ReleaseCall,ReportCall cli;
    class DefaultsYAML,ProjectOverride,EnvOverride phase;
    class GitHubCfg,CheckSingle,CheckBatch stateNode;
    class Decision detector;
    class ErrorResp gap;
    class CreateLabel,AddLabel output;
```

Closes #503

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/impl-20260325-091250-375300/.autoskillit/temp/make-plan/add_configurable_label_whitelist_plan_2026-03-25_000001.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
## Summary

SKILL.md bash blocks can embed `python3 -c` or `python3 - <<'EOF'`
blocks that import from the `autoskillit` package. These blocks execute
inside headless Claude Code sessions where the Python interpreter is the
user's system Python — not the project's virtual environment. The
package may not be installed there, causing silent or visible failures.
The architecture has no structural mechanism preventing this pattern.

This part adds a semantic validation rule that makes the pattern
statically unacceptable: any SKILL.md that imports `autoskillit` in a
python3 bash block fails validation at `validate_recipe()` time, before
the skill can be executed. Once merged, CI rejects future violations at
commit time rather than surfacing them silently at runtime.

Part B adds a deterministic PostToolUse hook (`token_summary_appender`)
replacing the LLM-dependent Step 0b token summary injection. Part C
fixes the remaining four SKILL.md import violations caught by the new
rule.

## Architecture Impact

### Module Dependency Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 70, 'curve': 'basis'}}}%%
graph TB
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000;

    subgraph L3_Hooks ["L3 — HOOKS (PostToolUse)"]
        direction LR
        TSA["★ token_summary_appender.py<br/>━━━━━━━━━━<br/>stdlib-only PostToolUse hook<br/>Appends token table to PR body"]
        HREG["● hook_registry.py<br/>━━━━━━━━━━<br/>HookDef, HOOK_REGISTRY<br/>imports: core.pkg_root"]
    end

    subgraph L2_Recipe ["L2 — RECIPE (Semantic Validation)"]
        direction LR
        RSC["● rules_skill_content.py<br/>━━━━━━━━━━<br/>+no-autoskillit-import rule<br/>imports: core, recipe._analysis,<br/>recipe._skill_placeholder_parser,<br/>recipe.contracts, recipe.registry"]
        REG["recipe/registry.py<br/>━━━━━━━━━━<br/>@semantic_rule, RuleFinding<br/>imports: core, recipe._analysis,<br/>recipe.schema"]
        SPP["recipe/_skill_placeholder_parser.py<br/>━━━━━━━━━━<br/>extract_bash_blocks()<br/>imports: stdlib only"]
        CON["● recipe/skill_contracts.yaml<br/>━━━━━━━━━━<br/>Contract definitions"]
    end

    subgraph L1_Exec ["L1 — EXECUTION"]
        direction LR
        EINIT["● execution/__init__.py<br/>━━━━━━━━━━<br/>Re-export hub<br/>+parse_hunk_ranges"]
    end

    subgraph L0_Core ["L0 — CORE (Foundation)"]
        direction LR
        CORE["core/<br/>━━━━━━━━━━<br/>Severity, pkg_root,<br/>SkillResult, types"]
    end

    subgraph Skills ["SKILL.md FILES (bash blocks — not Python imports)"]
        direction LR
        OPR["● open-pr/SKILL.md<br/>━━━━━━━━━━<br/>Removed python3 heredoc<br/>importing autoskillit"]
        OIP["● open-integration-pr/SKILL.md<br/>━━━━━━━━━━<br/>Replaced autoskillit import<br/>with stdlib inline"]
        RPR["● review-pr/SKILL.md<br/>━━━━━━━━━━<br/>Replaced autoskillit import<br/>with stdlib inline"]
        APR["● analyze-prs/SKILL.md<br/>━━━━━━━━━━<br/>Replaced __import__ autoskillit<br/>with stdlib inline"]
    end

    subgraph Tests ["TEST COVERAGE"]
        direction LR
        TTSA["★ test_token_summary_appender.py<br/>━━━━━━━━━━<br/>TSA-1 through TSA-8"]
        TRSC["● test_rules_skill_content.py<br/>━━━━━━━━━━<br/>SC-PKG-1 through SC-PKG-7"]
        TRVD["★ test_review_pr_diff_annotation.py"]
        THEX["● test_hook_executability.py"]
        THRC["● test_hook_registration_coverage.py"]
    end

    %% L2 internal dependencies %%
    RSC -->|"imports"| REG
    RSC -->|"imports"| SPP
    RSC -->|"imports"| CON

    %% Downward dependencies (valid) %%
    RSC -->|"imports Severity"| CORE
    REG -->|"imports Severity"| CORE
    HREG -->|"imports pkg_root"| CORE
    EINIT -->|"re-exports from"| CORE

    %% TSA is stdlib-only — no package dependencies %%
    TSA -.-x|"NO autoskillit imports<br/>(stdlib-only by design)"| CORE

    %% Semantic rule scans SKILL.md files %%
    RSC -.->|"validates bash blocks"| OPR
    RSC -.->|"validates bash blocks"| OIP
    RSC -.->|"validates bash blocks"| RPR
    RSC -.->|"validates bash blocks"| APR

    %% Test dependencies %%
    TTSA -.->|"tests"| TSA
    TRSC -.->|"tests"| RSC
    THEX -.->|"tests"| HREG
    THRC -.->|"tests"| HREG

    %% Class assignments %%
    class TSA,TTSA,TRVD newComponent;
    class RSC,REG,SPP,CON phase;
    class HREG handler;
    class EINIT handler;
    class CORE stateNode;
    class OPR,OIP,RPR,APR gap;
    class TRSC,THEX,THRC output;
```

### Process Flow Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000;

    START([Pipeline Start])

    subgraph Validation ["★ SEMANTIC VALIDATION (no-autoskillit-import rule)"]
        direction TB
        VR["● validate_recipe / load_recipe<br/>━━━━━━━━━━<br/>MCP tool entry point<br/>calls run_semantic_rules()"]
        VS["● run_semantic_rules()<br/>━━━━━━━━━━<br/>Iterates _RULE_REGISTRY<br/>calls each @semantic_rule"]
        VI{"★ _check_no_autoskillit_import<br/>━━━━━━━━━━<br/>step.tool == run_skill?"}
        VB["★ extract_bash_blocks()<br/>━━━━━━━━━━<br/>Parse SKILL.md content<br/>extract python3 blocks"]
        VM{"★ Pattern match?<br/>━━━━━━━━━━<br/>from autoskillit...<br/>import autoskillit...<br/>__import__ autoskillit"}
        VF["★ RuleFinding(ERROR)<br/>━━━━━━━━━━<br/>Skill X bash block contains<br/>autoskillit import"]
        VP["Pass<br/>━━━━━━━━━━<br/>No violation found"]
    end

    subgraph Hook ["★ POSTTOOLUSE HOOK (token_summary_appender)"]
        direction TB
        HT["★ PostToolUse fires<br/>━━━━━━━━━━<br/>on run_skill response"]
        HP{"★ PR URL in response?<br/>━━━━━━━━━━<br/>regex: github.com/.../pull/N"}
        HS["★ Read session logs<br/>━━━━━━━━━━<br/>sessions.jsonl + token_usage.json<br/>filter by cwd"]
        HF["★ Format token table<br/>━━━━━━━━━━<br/>stdlib-only markdown formatter"]
        HA["★ gh pr edit --body-file<br/>━━━━━━━━━━<br/>Append Token Usage Summary<br/>to PR body"]
        HN["Skip<br/>━━━━━━━━━━<br/>No PR URL or no data"]
    end

    subgraph SkillFix ["● SKILL.MD FIXES (bash block cleanup)"]
        direction TB
        SF["● 4 SKILL.md files<br/>━━━━━━━━━━<br/>open-pr, open-integration-pr,<br/>review-pr, analyze-prs"]
        SR["Replaced autoskillit imports<br/>━━━━━━━━━━<br/>with stdlib-only inline code<br/>or PostToolUse hook delegation"]
    end

    COMPLETE([Pipeline Complete])

    %% Validation flow %%
    START -->|"recipe loaded"| VR
    VR -->|"iterates rules"| VS
    VS -->|"invokes new rule"| VI
    VI -->|"yes: run_skill step"| VB
    VI -->|"no: skip step"| VP
    VB -->|"for each bash block"| VM
    VM -->|"match found"| VF
    VM -->|"no match"| VP

    %% Hook flow %%
    START -->|"run_skill completes"| HT
    HT --> HP
    HP -->|"yes"| HS
    HP -->|"no"| HN
    HS -->|"tokens found"| HF
    HS -->|"no data"| HN
    HF --> HA
    HA --> COMPLETE

    %% Skill fix flow %%
    SF --> SR
    SR -.->|"now passes"| VI

    class START,COMPLETE terminal;
    class VR,VS phase;
    class VI,VM,HP stateNode;
    class VB,HT,HS,HF,HA newComponent;
    class VF detector;
    class VP,HN handler;
    class SF,SR gap;
```

Closes #506

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/remediation-20260325-123256-483611/.autoskillit/temp/rectify/rectify_skill-python-autoskillit-import-contract_2026-03-25_160000_part_a.md`

:robot: Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
## Summary

Adds `--resume` flag support to `autoskillit cook` and `autoskillit
order`, enabling
users to restore a previous Claude Code session while preserving full
skill access and MCP
tool availability. Changes span the CLI layer, command builder, core
session-discovery
helper, ephemeral directory lifecycle, and a new `SessionStart` hook
that automatically
reminds Claude to reopen the kitchen on resume. Companion plan adds test
coverage for the
`order --resume` path to mirror the existing cook resume tests.

<details>
<summary>Individual Group Plans</summary>

### Group 1: Add --resume Flag to cook and order CLI Commands
Adds `--resume` flag support to `autoskillit cook` and `autoskillit
order`, allowing
users to restore a previous Claude Code session with full skill access
and MCP tool
availability. Changes span 8 files: a new `ClaudeFlags.RESUME` constant,
a
`find_latest_session_id()` path helper, updated
`build_interactive_cmd()`, removal of
eager ephemeral directory cleanup, new `--resume`/`--session-id` CLI
flags, a
`SessionStart` hook entry for automatic resume detection, and a new hook
script that
injects a `/autoskillit:open-kitchen` reminder when a session resumes.

### Group 2: Add order --resume Test Coverage
Add three tests to `tests/cli/test_cook.py` covering the `order
--resume` path: session
discovery via `find_latest_session_id`, explicit session ID bypass, and
no-prior-session
fallback. These mirror the three resume tests already present for
`cook()` in
`test_cook_interactive.py` (REQ-CLI-001 / REQ-CLI-002).

</details>

## Requirements

### CLI — Resume Flag

- **REQ-CLI-001:** `autoskillit cook --resume [session-id]` must launch
Claude Code with `--resume <id>` while also passing `--add-dir` and
`--plugin-dir` flags.
- **REQ-CLI-002:** When `--resume` is invoked without a session-id
argument, the CLI must discover the most recent cook session ID
automatically.
- **REQ-CLI-003:** `autoskillit order --resume [session-id]` must
recreate the orchestrator system prompt and pass `--resume <id>` to
Claude Code.
- **REQ-CLI-004:** The `--resume` flag must regenerate a fresh ephemeral
skill directory with the same skill set as the original session type
(cook_session=True for cook).

### EPH — Ephemeral Directory Lifecycle

- **REQ-EPH-001:** `_cook.py` must NOT delete the ephemeral skill
directory on session exit (remove the `shutil.rmtree` in the `finally`
block).
- **REQ-EPH-002:** `cleanup_stale()` default max age must be 72 hours
(259200 seconds) instead of 24 hours (86400 seconds).
- **REQ-EPH-003:** Stale cleanup must use access time (`st_atime`) to
avoid removing directories that are still being referenced by a resumed
session.

### HOOK — SessionStart Hook

- **REQ-HOOK-001:** A `SessionStart` hook must be registered in
`HOOK_REGISTRY` and generated into `hooks.json`.
- **REQ-HOOK-002:** The hook must detect whether the current session is
a resume (not a fresh start).
- **REQ-HOOK-003:** On resume detection, the hook must inject
`additionalContext` instructing Claude to call
`/autoskillit:open-kitchen` to restore MCP tool access.

### CMD — Command Builder

- **REQ-CMD-001:** `build_interactive_cmd()` must accept an optional
`resume_session_id` parameter and append `--resume <id>` to the command
when provided.

## Architecture Impact

### Operational Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;

    USER([Operator])

    subgraph CookCLI ["● autoskillit cook"]
        direction TB
        CookFresh["cook<br/>━━━━━━━━━━<br/>No flags<br/>Fresh session"]
        CookResume["● cook --resume<br/>━━━━━━━━━━<br/>★ Auto-discover session ID<br/>or use --session-id"]
    end

    subgraph OrderCLI ["● autoskillit order"]
        direction TB
        OrderFresh["order recipe<br/>━━━━━━━━━━<br/>No flags<br/>Fresh session"]
        OrderResume["● order --resume<br/>━━━━━━━━━━<br/>★ Auto-discover session ID<br/>or use --session-id"]
    end

    subgraph SessionDisc ["★ Session Discovery"]
        direction TB
        FindLatest["★ find_latest_session_id()<br/>━━━━━━━━━━<br/>~/.claude/projects/<br/>encoded-cwd/*.jsonl<br/>Sort by mtime → stem"]
        NoSession["Fallback: fresh start<br/>━━━━━━━━━━<br/>No prior session found"]
    end

    subgraph CmdBuild ["● Command Builder"]
        direction TB
        BuildCmd["● build_interactive_cmd()<br/>━━━━━━━━━━<br/>★ resume_session_id param<br/>--add-dir --plugin-dir<br/>--dangerously-skip-permissions"]
    end

    subgraph HookLayer ["★ SessionStart Hook"]
        direction TB
        HookReg["★ session_start_reminder.py<br/>━━━━━━━━━━<br/>Reads transcript_path size<br/>size > 0 = resumed session"]
        Reminder["★ additionalContext injected<br/>━━━━━━━━━━<br/>Call /autoskillit:open-kitchen<br/>to restore MCP tools"]
    end

    subgraph ClaudeProc ["Claude Code Process"]
        direction TB
        Fresh["claude (fresh)<br/>━━━━━━━━━━<br/>New session"]
        Resumed["claude --resume id<br/>━━━━━━━━━━<br/>Restored conversation"]
    end

    USER --> CookFresh & CookResume & OrderFresh & OrderResume
    CookResume & OrderResume --> FindLatest
    FindLatest -->|"ID found"| BuildCmd
    FindLatest -->|"None"| NoSession
    NoSession --> BuildCmd
    CookFresh & OrderFresh --> BuildCmd
    BuildCmd -->|"resume_session_id set"| Resumed
    BuildCmd -->|"no resume_session_id"| Fresh
    Resumed --> HookReg
    HookReg -->|"size > 0"| Reminder
    HookReg -->|"size == 0"| Fresh

    class CookFresh,CookResume,OrderFresh,OrderResume cli;
    class FindLatest,NoSession newComponent;
    class BuildCmd handler;
    class HookReg,Reminder newComponent;
    class Fresh,Resumed stateNode;
    class USER terminal;
```

### Process Flow Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 40, 'rankSpacing': 50, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;

    START([cook / order invoked])
    FRESH([Fresh session started])
    RESUMED([Session resumed])
    HOOK_DONE([Hook complete])

    subgraph ResumeResolution ["★ Resume Resolution (cook/_cook.py + app.py)"]
        direction TB
        D_RESUME{"● --resume flag<br/>━━━━━━━━━━<br/>provided?"}
        D_EXPLICIT{"● --session-id<br/>━━━━━━━━━━<br/>explicit value?"}
        FIND["★ find_latest_session_id()<br/>━━━━━━━━━━<br/>reads ~/.claude/projects/<br/>encoded-cwd/*.jsonl<br/>sorted by mtime"]
        D_FOUND{"session ID<br/>━━━━━━━━━━<br/>found?"}
        WARN["print: No previous session<br/>━━━━━━━━━━<br/>Starting fresh session"]
    end

    subgraph CmdBuild ["● Command Building (execution/commands.py)"]
        direction TB
        BUILD["● build_interactive_cmd()<br/>━━━━━━━━━━<br/>--add-dir --plugin-dir<br/>--dangerously-skip-permissions"]
        D_RESUME_ID{"● resume_session_id<br/>━━━━━━━━━━<br/>set?"}
        APPEND["append --resume id<br/>━━━━━━━━━━<br/>to command args"]
    end

    subgraph HookLayer ["★ SessionStart Hook"]
        direction TB
        HOOK_FIRE["★ session_start_reminder.py<br/>━━━━━━━━━━<br/>reads stdin JSON<br/>checks transcript_path"]
        D_SIZE{"★ transcript_path<br/>━━━━━━━━━━<br/>size > 0?"}
        INJECT["★ additionalContext injected<br/>━━━━━━━━━━<br/>Call /autoskillit:open-kitchen<br/>to restore MCP tools"]
    end

    START --> D_RESUME
    D_RESUME -->|"yes"| D_EXPLICIT
    D_RESUME -->|"no"| BUILD
    D_EXPLICIT -->|"yes (use explicit ID)"| D_RESUME_ID
    D_EXPLICIT -->|"no"| FIND
    FIND --> D_FOUND
    D_FOUND -->|"found"| D_RESUME_ID
    D_FOUND -->|"None"| WARN
    WARN --> BUILD
    D_RESUME_ID -->|"set"| APPEND
    D_RESUME_ID -->|"not set"| BUILD
    APPEND --> BUILD
    BUILD -->|"--resume id present"| RESUMED
    BUILD -->|"no --resume"| FRESH
    RESUMED --> HOOK_FIRE
    FRESH --> HOOK_FIRE
    HOOK_FIRE --> D_SIZE
    D_SIZE -->|"size > 0 (resumed)"| INJECT
    D_SIZE -->|"size == 0 (fresh)"| HOOK_DONE
    INJECT --> HOOK_DONE

    class START,FRESH,RESUMED,HOOK_DONE terminal;
    class D_RESUME,D_EXPLICIT,D_FOUND,D_RESUME_ID,D_SIZE stateNode;
    class BUILD,APPEND handler;
    class FIND,HOOK_FIRE,INJECT,WARN newComponent;
```

### State Lifecycle Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000;

    subgraph SessionIDDisc ["★ Session ID Discovery Contract (core/paths.py)"]
        direction TB
        SCAN["★ find_latest_session_id()<br/>━━━━━━━━━━<br/>reads ~/.claude/projects/<br/>-cwd-encoded-/*.jsonl<br/>sorted by st_mtime desc"]
        CONTRACT1["INIT_ONLY contract<br/>━━━━━━━━━━<br/>returns stem or None<br/>no mutation of source"]
        SYNTH["Synthetic ID guard<br/>━━━━━━━━━━<br/>no_session_ / crashed_<br/>→ never returned (not on disk)"]
    end

    subgraph EphemeralLifecycle ["● Ephemeral Skill Dir Lifecycle (workspace/session_skills.py)"]
        direction TB
        CLEANUP["● cleanup_stale()<br/>━━━━━━━━━━<br/>max_age=259200s (★72h)<br/>staleness via st_atime<br/>rmtree(ignore_errors=True)"]
        INIT["init_session()<br/>━━━━━━━━━━<br/>session_id validity gate<br/>no null/slash/dot<br/>mkdir exist_ok=True"]
        PRESERVE["INIT_PRESERVE contract<br/>━━━━━━━━━━<br/>new uuid per run<br/>skill dir always regenerated<br/>not restored from prior session"]
    end

    subgraph CmdContract ["● Command Builder Resume Contract (execution/commands.py)"]
        direction TB
        BUILD["● build_interactive_cmd()<br/>━━━━━━━━━━<br/>★ resume_session_id: str | None<br/>DERIVED: --resume id<br/>injected before all other flags"]
        FLAG["● ClaudeFlags.RESUME<br/>━━━━━━━━━━<br/>★ = --resume<br/>INIT_ONLY: value immutable<br/>appended at cmd position 2"]
    end

    subgraph HookResumeSafety ["★ SessionStart Resume Safety (hooks/session_start_reminder.py)"]
        direction TB
        DETECT["★ transcript_path probe<br/>━━━━━━━━━━<br/>reads size via stat()<br/>0 = fresh / &gt;0 = resumed"]
        GUARD["★ Fail-open contract<br/>━━━━━━━━━━<br/>any error → exit(0)<br/>never blocks session"]
        INJECT["★ additionalContext<br/>━━━━━━━━━━<br/>WRITE-ONLY output<br/>not read back by system"]
    end

    SCAN --> CONTRACT1
    SCAN --> SYNTH
    CONTRACT1 -->|"str | None"| BUILD
    CLEANUP --> INIT
    INIT --> PRESERVE
    PRESERVE -->|"fresh skills_dir"| BUILD
    BUILD --> FLAG
    FLAG -->|"--resume id prepended"| DETECT
    DETECT --> GUARD
    GUARD -->|"size > 0"| INJECT
    GUARD -->|"size == 0 or error"| SILENT["exit(0) — no output"]

    class SCAN,CONTRACT1 newComponent;
    class SYNTH detector;
    class CLEANUP,INIT handler;
    class PRESERVE gap;
    class BUILD,FLAG phase;
    class DETECT,GUARD,INJECT newComponent;
    class SILENT output;
```

Closes #427

## Implementation Plan

Plan files:
-
`.autoskillit/temp/make-plan/feat-add-resume-flag_plan_2026-03-25_000000.md`
-
`.autoskillit/temp/make-plan/add-order-resume-tests_plan_2026-03-25_000500.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
## Summary

Both interactive CLI launch sites (`cook()` in `cli/_cook.py` and
`_launch_cook_session()` in `cli/app.py`) call `subprocess.run(cmd,
env=env)` with fully inherited stdio and no terminal state management.
When Claude Code enters raw/application cursor mode and then crashes or
is killed, the parent terminal is left corrupted. The **architectural
weakness** is the absence of an *interactive subprocess ownership
protocol*: there is no concept of "I am transferring terminal control to
a subprocess; I am responsible for restoring it." The execution layer
already has the correct pattern (`create_temp_io()` context manager for
file handle lifecycle), but no equivalent exists for the CLI's TTY
lifecycle.

This PR creates `cli/_terminal.py` with a `terminal_guard()` context
manager and applies it to both interactive launch sites. A new test
suite verifies all recovery paths (normal exit, exception, `OSError`
fallback, non-TTY no-op). Part B (separate task) adds an AST-walk
structural enforcement test that makes this invariant unbreakable as a
CI gate.

## Architecture Impact

### Operational Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;

    subgraph CLI ["CLI ENTRY POINTS"]
        direction TB
        COOK["● autoskillit cook<br/>━━━━━━━━━━<br/>cli/_cook.py<br/>Full-skill session"]
        ORDER["autoskillit order<br/>━━━━━━━━━━<br/>cli/app.py<br/>Recipe-scoped session"]
    end

    subgraph Launch ["INTERACTIVE LAUNCH LAYER"]
        direction TB
        COOKFN["● cook()<br/>━━━━━━━━━━<br/>cli/_cook.py:cook<br/>Builds claude cmd<br/>Manages skill dir"]
        LAUNCHFN["● _launch_cook_session()<br/>━━━━━━━━━━<br/>cli/app.py:_launch_cook_session<br/>Builds claude cmd<br/>Applies extra env"]
    end

    subgraph Guard ["★ TERMINAL OWNERSHIP GUARD"]
        direction TB
        TGUARD["★ terminal_guard()<br/>━━━━━━━━━━<br/>cli/_terminal.py<br/>Context manager<br/>Wraps subprocess.run"]
        SAVE["Save TTY State<br/>━━━━━━━━━━<br/>termios.tcgetattr()<br/>stdin fileno"]
        RESTORE["Restore TTY State<br/>━━━━━━━━━━<br/>termios.tcsetattr()<br/>fallback: stty sane<br/>VT100 reset seqs"]
    end

    subgraph Subprocess ["SUBPROCESS EXECUTION"]
        direction TB
        CLAUDE["claude<br/>━━━━━━━━━━<br/>Interactive TUI<br/>Inherited stdio<br/>Raw/app-mode TTY"]
    end

    subgraph Config ["CONFIGURATION (READ)"]
        direction TB
        ENV["Environment Vars<br/>━━━━━━━━━━<br/>CLAUDECODE guard<br/>ANTHROPIC_API_KEY<br/>spec.env overrides"]
        SKILLDIR["Ephemeral Skills Dir<br/>━━━━━━━━━━<br/>Session skill manager<br/>Cleaned up in finally"]
    end

    subgraph Monitoring ["OBSERVABILITY (WRITE)"]
        direction TB
        SESSLOG["Session Diagnostics<br/>━━━━━━━━━━<br/>~/.local/share/autoskillit/logs/<br/>Session UUID indexed"]
        EXITCODE["Exit Code Propagation<br/>━━━━━━━━━━<br/>sys.exit(returncode)<br/>Non-zero forwarded"]
    end

    %% FLOWS %%
    COOK --> COOKFN
    ORDER --> LAUNCHFN
    COOKFN --> TGUARD
    LAUNCHFN --> TGUARD
    TGUARD --> SAVE
    SAVE --> CLAUDE
    CLAUDE --> RESTORE
    COOKFN --> ENV
    LAUNCHFN --> ENV
    COOKFN --> SKILLDIR
    CLAUDE --> SESSLOG
    CLAUDE --> EXITCODE

    %% CLASS ASSIGNMENTS %%
    class COOK,ORDER cli;
    class COOKFN,LAUNCHFN handler;
    class TGUARD,SAVE,RESTORE newComponent;
    class CLAUDE phase;
    class ENV,SKILLDIR stateNode;
    class SESSLOG,EXITCODE output;
```

### Process Flow Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 40, 'rankSpacing': 50, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;

    %% TERMINALS %%
    START(["● cook() / ● _launch_cook_session()"])
    DONE(["Terminal restored — control returns to caller"])

    subgraph Entry ["★ TERMINAL GUARD ENTRY"]
        direction TB
        ENTER["★ terminal_guard().__enter__<br/>━━━━━━━━━━<br/>cli/_terminal.py<br/>Context manager entered"]
        ISATTY{"stdin.isatty()?<br/>━━━━━━━━━━<br/>Is this a real TTY?"}
        SAVETTY["Save TTY attrs<br/>━━━━━━━━━━<br/>termios.tcgetattr(stdin.fileno())<br/>saved_attrs stored"]
        NOOP["No-op path<br/>━━━━━━━━━━<br/>CI / pipe / headless<br/>saved_attrs = None"]
    end

    subgraph Exec ["SUBPROCESS EXECUTION"]
        direction TB
        CLAUDE["subprocess.run(claude_cmd)<br/>━━━━━━━━━━<br/>Inherited stdio<br/>Claude TUI runs<br/>Raw/app-cursor mode active"]
    end

    subgraph Exit ["★ TERMINAL GUARD EXIT (always runs via finally)"]
        direction TB
        HASSAVED{"saved_attrs<br/>is not None?"}
        TERMIOS["termios.tcsetattr()<br/>━━━━━━━━━━<br/>TCSANOW — immediate<br/>Restore kernel TTY attrs"]
        TERMERR{"OSError or<br/>TypeError?"}
        STTY["stty sane<br/>━━━━━━━━━━<br/>os.system fallback<br/>Best-effort restore"]
        VT100["Emit VT100 reset<br/>━━━━━━━━━━<br/>\\033[?1049l alt-screen off<br/>\\033[?1l app-cursor off<br/>\\033> keypad off<br/>\\033[0m reset attrs<br/>\\033[?25h show cursor"]
        SKIPVT["Skip restore<br/>━━━━━━━━━━<br/>Non-TTY path<br/>Emit VT100 anyway"]
    end

    %% FLOW %%
    START --> ENTER
    ENTER --> ISATTY
    ISATTY -->|"yes"| SAVETTY
    ISATTY -->|"no (CI/pipe)"| NOOP
    SAVETTY --> CLAUDE
    NOOP --> CLAUDE

    CLAUDE --> HASSAVED
    HASSAVED -->|"yes"| TERMIOS
    HASSAVED -->|"no"| SKIPVT
    TERMIOS --> TERMERR
    TERMERR -->|"no error"| VT100
    TERMERR -->|"OSError/TypeError"| STTY
    STTY --> VT100
    SKIPVT --> DONE
    VT100 --> DONE

    %% CLASS ASSIGNMENTS %%
    class START,DONE terminal;
    class ENTER,SAVETTY,NOOP,VT100,SKIPVT newComponent;
    class CLAUDE handler;
    class ISATTY,HASSAVED,TERMERR stateNode;
    class TERMIOS phase;
    class STTY detector;
```

### Error/Resilience Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 40, 'rankSpacing': 50, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000;

    subgraph Gates ["VALIDATION GATES"]
        direction TB
        ISATTY{"stdin.isatty()?<br/>━━━━━━━━━━<br/>Gate: is this a<br/>real terminal?"}
        NOATTY["Non-TTY path<br/>━━━━━━━━━━<br/>CI / pipe / headless<br/>saved_attrs = None"]
    end

    subgraph Exec ["SUBPROCESS EXECUTION"]
        CLAUDE["● subprocess.run(claude)<br/>━━━━━━━━━━<br/>Raw/app-cursor mode<br/>TTY state mutated"]
        FAIL["Abnormal Exit<br/>━━━━━━━━━━<br/>Crash / SIGINT / OOM<br/>Unhandled exception"]
        OK["Normal Exit<br/>━━━━━━━━━━<br/>returncode 0 or non-0<br/>Clean Claude shutdown"]
    end

    subgraph Recovery ["★ TERMINAL RESTORATION (finally — always runs)"]
        direction TB
        CHKATTRS{"saved_attrs<br/>not None?"}
        TERMIOS["termios.tcsetattr()<br/>━━━━━━━━━━<br/>Primary restore path<br/>TCSANOW — immediate"]
        TERMERR{"OSError or<br/>TypeError?"}
        STTY["stty sane<br/>━━━━━━━━━━<br/>os.system fallback<br/>Best-effort TTY fix"]
        VT100["★ Emit VT100 reset<br/>━━━━━━━━━━<br/>\\033[?1049l alt-screen<br/>\\033[?1l app-cursor<br/>\\033> keypad mode<br/>\\033[0m reset attrs<br/>\\033[?25h cursor show<br/>Always emitted"]
    end

    subgraph Known_Gap ["KNOWN UNRECOVERABLE (documented)"]
        SIGKILL["SIGKILL to parent<br/>━━━━━━━━━━<br/>No finally possible<br/>User must: stty sane"]
    end

    subgraph Tests ["★ NEW TEST CONTRACTS"]
        direction TB
        T1["★ test_terminal.py<br/>━━━━━━━━━━<br/>Mocks termios<br/>Verifies: restore on normal exit<br/>Verifies: restore on exception<br/>Verifies: stty fallback on OSError<br/>Verifies: non-TTY no-op"]
        T2["★ test_interactive_subprocess_contracts.py<br/>━━━━━━━━━━<br/>AST-walk CI gate<br/>Enforces: every subprocess.run in cli/<br/>must be inside with terminal_guard()"]
        T3["● test_subpackage_isolation.py<br/>━━━━━━━━━━<br/>cli/_terminal.py is stdlib-only<br/>No autoskillit imports allowed"]
    end

    %% FLOW %%
    ISATTY -->|"yes — real TTY"| CLAUDE
    ISATTY -->|"no — CI/pipe"| NOATTY
    NOATTY --> VT100
    CLAUDE --> OK
    CLAUDE --> FAIL
    OK --> CHKATTRS
    FAIL --> CHKATTRS
    CHKATTRS -->|"yes"| TERMIOS
    CHKATTRS -->|"no (non-TTY)"| VT100
    TERMIOS --> TERMERR
    TERMERR -->|"no error"| VT100
    TERMERR -->|"OSError/TypeError"| STTY
    STTY --> VT100

    %% CLASS ASSIGNMENTS %%
    class ISATTY,CHKATTRS,TERMERR stateNode;
    class NOATTY phase;
    class CLAUDE handler;
    class OK output;
    class FAIL gap;
    class TERMIOS phase;
    class STTY detector;
    class VT100 newComponent;
    class SIGKILL gap;
    class T1,T2 newComponent;
    class T3 phase;
```

Closes #509

## Implementation Plan

Plan file:
`.autoskillit/temp/rectify/rectify_terminal-ownership-contract_2026-03-25_224500_part_a.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
…egy (#517)

## Summary

Replace the current reverse-sync version bumping strategy (which patches
main then force-pushes to integration then patches integration again)
with a clean two-trigger system:

1. **`patch-bump-integration.yml`** (new): patches integration's version
when any PR merges to integration.
2. **`version-bump.yml`** (rewritten): when the promotion PR
(integration → main) merges, bumps the minor version on **both**
branches — main gets `X.(Y+1).0`, integration gets `X.(Y+1).1`. No
force-push. No branch-protection manipulation.

Additionally, Phase 8 of the `promote-to-main` skill (the
threshold-based minor-bump commit made by the skill) is removed
entirely. Version management is now the exclusive responsibility of CI
workflows.

## Requirements

### Version Invariants

- **REQ-VER-001:** Main branch patch version must always be 0 after a
promotion.
- **REQ-VER-002:** Integration branch patch version must always be 1
immediately after a promotion.
- **REQ-VER-003:** Both branches must share the same major.minor version
after a promotion.
- **REQ-VER-004:** Patch version on integration must monotonically
increase between promotions.

### Patch Automation

- **REQ-PATCH-001:** The system must bump integration's patch version
when a PR merges to integration.
- **REQ-PATCH-002:** Each patch bump must update pyproject.toml and
execute version sync (task sync-plugin-version && uv lock).
- **REQ-PATCH-003:** Patch version must be able to accumulate from 1 to
at least 999 without triggering a minor bump.

### Promotion Automation

- **REQ-PROMO-001:** The promote-to-main workflow must bump the minor
version on both main and integration.
- **REQ-PROMO-002:** The promote-to-main workflow must reset main's
patch to 0 and integration's patch to 1.
- **REQ-PROMO-003:** When integration diverges from main after a
promotion, the minor version must be bumped if not already bumped, with
patch reset to 1.

### Cleanup

- **REQ-CLEAN-001:** The existing reverse-sync version bumping logic
must be removed entirely.
- **REQ-CLEAN-002:** All recipes, hooks, or CI workflows participating
in version management must be updated to the new strategy.
- **REQ-CLEAN-003:** Tests validating version bumping behavior must
cover the new lifecycle.

## Architecture Impact

### Development Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;

    %% TRIGGERS %%
    T_INT([PR merged to integration])
    T_MAIN([PR merged to main<br/>from integration])

    subgraph CI ["CI / CD WORKFLOWS"]
        direction TB
        PATCH["★ patch-bump-integration.yml<br/>━━━━━━━━━━<br/>Trigger: PR closed → integration<br/>Guard: merged == true<br/>Action: PATCH+1 on integration"]
        VB["● version-bump.yml<br/>━━━━━━━━━━<br/>Trigger: PR closed → main<br/>Guard: merged==true, head==integration<br/>Action: MINOR+1 on main+integration"]
        TESTS["tests.yml<br/>━━━━━━━━━━<br/>task test-all<br/>pytest -n 4"]
        RELEASE["release.yml<br/>━━━━━━━━━━<br/>stable → git tag<br/>gh release create"]
    end

    subgraph BUILD ["BUILD TOOLING"]
        direction LR
        TASK["Taskfile.yml<br/>━━━━━━━━━━<br/>test-all, test-check<br/>sync-plugin-version"]
        UV["uv@0.9.21<br/>━━━━━━━━━━<br/>Package manager<br/>uv lock"]
    end

    subgraph QUALITY ["CODE QUALITY GATES"]
        direction LR
        RUFF_FMT["ruff format<br/>━━━━━━━━━━<br/>Auto-fix formatter"]
        RUFF_LINT["ruff check<br/>━━━━━━━━━━<br/>Linter + auto-fix"]
        MYPY["mypy<br/>━━━━━━━━━━<br/>Type checking src/"]
    end

    subgraph TESTING ["TEST INFRASTRUCTURE"]
        direction TB
        TEST_WF["● test_release_workflows.py<br/>━━━━━━━━━━<br/>TestVersionBumpWorkflow (18)<br/>TestPatchBumpIntegrationWorkflow (13)<br/>TestReleaseWorkflow (12)"]
        PYTEST["pytest + xdist<br/>━━━━━━━━━━<br/>-n 4 parallel<br/>asyncio + httpx"]
    end

    subgraph VERSION_STATE ["VERSION STATE AFTER CI"]
        direction LR
        INT_STATE["integration = X.Y.N<br/>━━━━━━━━━━<br/>patch monotonically ↑"]
        MAIN_STATE["main = X.(Y+1).0<br/>integration = X.(Y+1).1<br/>━━━━━━━━━━<br/>post-promotion"]
    end

    %% FLOW %%
    T_INT --> PATCH
    T_MAIN --> VB
    PATCH --> INT_STATE
    VB --> MAIN_STATE

    TASK --> PYTEST
    PYTEST --> TEST_WF
    TESTS --> TASK

    RUFF_FMT --> RUFF_LINT --> MYPY

    %% CLASS ASSIGNMENTS %%
    class T_INT,T_MAIN terminal;
    class PATCH newComponent;
    class VB,TEST_WF handler;
    class TESTS,RELEASE,TASK phase;
    class UV output;
    class RUFF_FMT,RUFF_LINT,MYPY detector;
    class PYTEST handler;
    class INT_STATE,MAIN_STATE stateNode;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | Terminal | CI trigger events |
| Green | New Component (★) | New `patch-bump-integration.yml` workflow
|
| Orange | Modified (●) | Modified `version-bump.yml` and
`test_release_workflows.py` |
| Purple | Phase | Existing CI workflows and build tooling |
| Red | Quality | Pre-commit quality gates |
| Teal | State | Post-CI version states |

Closes #512

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/impl-20260326-162457-967149/.autoskillit/temp/make-plan/replace_reverse_sync_version_bumping_with_minor_bump_on_promote_plan_2026-03-26_000000.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit
…e Install (#518)

## Summary

Add two complementary surfaces for stale-install detection:

1. **Doctor check** (`_check_hook_registry_drift`): Structural
comparison of `generate_hooks_json()` output against what is deployed in
`settings.json`. Surfaces as a new `"hook_registry_drift"` check in
`autoskillit doctor`.

2. **CLI startup stale check** (`cli/_stale_check.py`): Non-blocking
check on every interactive CLI command that compares the running binary
version against the latest available (GitHub API), and counts
HOOK_REGISTRY drift. Shows a dismissable prompt (7-day cooldown per
check type) that offers to run the update command automatically.

3. **Dev mode** detected via `.autoskillit/dev` marker file or
`pkg_root()` inside a git main checkout. Dev mode changes "latest
available" source to the `integration` branch.

4. **`task install-dev`** added to Taskfile.yml for dev-mode reinstall
from `@integration`.

## Architecture Impact

### Operational Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
graph TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;

    ENTRY([autoskillit &lt;cmd&gt;])

    subgraph APP ["● app.py main()"]
        direction TB
        SERVE_GATE{"serve or\nCLAUDECODE?"}
    end

    subgraph STALE ["★ cli/_stale_check.py"]
        direction TB
        TTY_CHECK{"stdin/stdout\nis TTY?"}
        DEV_DETECT["★ is_dev_mode()<br/>━━━━━━━━━━<br/>~/.autoskillit/dev marker<br/>pkg_root() inside git"]
        FETCH["★ _fetch_latest_version()<br/>━━━━━━━━━━<br/>dev → @integration pyproject.toml<br/>normal → releases/latest"]
        DISMISS_READ["★ _read_dismiss_state()<br/>━━━━━━━━━━<br/>7-day cooldown window"]
        BIN_CMP{"Version(latest)\n> current?"}
        HOOK_CMP{"registry drift\n> 0 hooks?"}
        BIN_PROMPT["★ Binary update prompt<br/>━━━━━━━━━━<br/>AutoSkillit X.Y.Z available<br/>[Y/n]"]
        HOOK_PROMPT["★ Hook drift prompt<br/>━━━━━━━━━━<br/>N new/changed hooks<br/>[Y/n]"]
    end

    subgraph DISMISS ["★ Dismissal State"]
        DISMISS_FILE["★ ~/.autoskillit/<br/>update_check.json<br/>━━━━━━━━━━<br/>dismissed_at · check_type<br/>dismissed_version"]
    end

    subgraph DOCTOR ["● _doctor.py run_doctor()"]
        direction TB
        EXISTING["Checks 1–7a<br/>━━━━━━━━━━<br/>mcp_server, path, config,<br/>version, hook_health,<br/>hook_registration"]
        DRIFT_CHECK["★ _check_hook_registry_drift()<br/>━━━━━━━━━━<br/>generate_hooks_json() cmds<br/>vs settings.json cmds<br/>→ hook_registry_drift"]
        REST["Checks 8–9<br/>━━━━━━━━━━<br/>script_version_health<br/>gitignore, secret_scan"]
    end

    subgraph GITHUB ["GitHub API (read-only)"]
        direction TB
        API_RELEASE["releases/latest<br/>━━━━━━━━━━<br/>normal mode"]
        API_INTEGRATION["contents/pyproject.toml<br/>?ref=integration<br/>━━━━━━━━━━<br/>dev mode"]
    end

    subgraph ACTIONS ["Update Actions"]
        direction TB
        UPDATE_BIN["uv tool install --force<br/>@integration (dev)<br/>uv tool upgrade (normal)"]
        RUN_INSTALL["autoskillit install<br/>━━━━━━━━━━<br/>deploy hooks + plugin"]
    end

    subgraph TASKS ["★ Taskfile.yml"]
        INSTALL_DEV["★ task install-dev<br/>━━━━━━━━━━<br/>uv tool install --force @integration<br/>autoskillit install"]
    end

    subgraph SETTINGS ["Configuration (read-only)"]
        ENV_CLAUDE["CLAUDECODE=1<br/>━━━━━━━━━━<br/>skip check in headless"]
        SETTINGS_JSON["~/.claude/settings.json<br/>━━━━━━━━━━<br/>deployed hooks (doctor reads)"]
    end

    %% MAIN FLOW %%
    ENTRY --> SERVE_GATE
    SERVE_GATE -- "not serve" --> TTY_CHECK
    SERVE_GATE -- "serve / CLAUDECODE=1" --> SKIP([skip stale check])

    TTY_CHECK -- "yes" --> DEV_DETECT
    TTY_CHECK -- "no" --> SKIP

    DEV_DETECT --> FETCH
    FETCH --> DISMISS_READ
    DEV_DETECT -- dev mode --> API_INTEGRATION
    DEV_DETECT -- normal mode --> API_RELEASE

    DISMISS_READ --> BIN_CMP
    BIN_CMP -- "stale" --> BIN_PROMPT
    BIN_CMP -- "current" --> HOOK_CMP
    BIN_PROMPT -- "Y" --> UPDATE_BIN
    BIN_PROMPT -- "N/dismiss" --> DISMISS_FILE
    UPDATE_BIN --> RUN_INSTALL

    DISMISS_READ --> HOOK_CMP
    HOOK_CMP -- "drift > 0" --> HOOK_PROMPT
    HOOK_PROMPT -- "Y" --> RUN_INSTALL
    HOOK_PROMPT -- "N/dismiss" --> DISMISS_FILE

    %% DOCTOR FLOW %%
    ENTRY -- "doctor cmd" --> EXISTING
    EXISTING --> DRIFT_CHECK
    DRIFT_CHECK --> REST
    DRIFT_CHECK -- reads --> SETTINGS_JSON

    %% TASK FLOW %%
    INSTALL_DEV --> UPDATE_BIN

    %% ENV CONSTRAINTS %%
    ENV_CLAUDE -. "suppresses" .-> TTY_CHECK

    %% CLASS ASSIGNMENTS %%
    class ENTRY,SKIP terminal;
    class SERVE_GATE,BIN_CMP,HOOK_CMP,TTY_CHECK phase;
    class DEV_DETECT,FETCH,DISMISS_READ,BIN_PROMPT,HOOK_PROMPT newComponent;
    class DISMISS_FILE stateNode;
    class EXISTING,REST handler;
    class DRIFT_CHECK newComponent;
    class API_RELEASE,API_INTEGRATION output;
    class UPDATE_BIN,RUN_INSTALL handler;
    class INSTALL_DEV newComponent;
    class ENV_CLAUDE,SETTINGS_JSON cli;
```

### Process Flow Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 42, 'rankSpacing': 52, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;

    %% TERMINALS %%
    START([CLI cmd invoked])
    SKIP([skip — no output])
    DONE([stale check complete])

    %% ENTRY GUARD %%
    SERVE_GATE{"serve or\nCLAUDECODE=1?"}
    TTY_GATE{"stdin+stdout\nare TTY?"}

    subgraph DETECT ["★ is_dev_mode() — dev detection"]
        direction LR
        MARKER{"~/.autoskillit/dev\nor cwd/.autoskillit/dev?"}
        GIT_DIR{"pkg_root() has\n.git directory?"}
        DEV_FLAG["dev_mode = True"]
        NORMAL_FLAG["dev_mode = False"]
    end

    subgraph FETCH ["★ _fetch_latest_version()"]
        direction LR
        DEV_API["GET pyproject.toml<br/>━━━━━━━━━━<br/>?ref=integration<br/>parse version = line"]
        NORMAL_API["GET releases/latest<br/>━━━━━━━━━━<br/>read tag_name<br/>5s timeout"]
        FETCH_FAIL["silent return None<br/>━━━━━━━━━━<br/>network error / timeout"]
    end

    subgraph DISMISS ["★ _read_dismiss_state() — reads ~/.autoskillit/update_check.json"]
        DISMISS_LOAD["load dismissed_at<br/>dismissed_version<br/>check_type"]
    end

    subgraph BIN_CHECK ["★ Binary version check"]
        direction TB
        BIN_STALE{"Version(latest)\n> Version(current)?"}
        BIN_DISMISSED{"check_type='binary'\nand within 7 days?"}
        BIN_PROMPT["★ prompt user<br/>━━━━━━━━━━<br/>AutoSkillit X.Y.Z available<br/>Update now? [Y/n]"]
        BIN_Y["uv tool install --force<br/>@integration (dev) or<br/>uv tool upgrade (normal)<br/>+ autoskillit install"]
        BIN_N["★ write dismiss state<br/>━━━━━━━━━━<br/>check_type = 'binary'<br/>7-day cooldown"]
    end

    subgraph HOOK_CHECK ["★ Hook drift check"]
        direction TB
        HOOK_COUNT["★ _count_hook_registry_drift_for_path()<br/>━━━━━━━━━━<br/>generate_hooks_json() cmds<br/>MINUS deployed settings.json cmds"]
        HOOK_POS{"drift > 0?"}
        HOOK_DISMISSED{"check_type='hooks'\nand within 7 days?"}
        HOOK_PROMPT["★ prompt user<br/>━━━━━━━━━━<br/>N new/changed hooks detected<br/>Run install? [Y/n]"]
        HOOK_Y["autoskillit install"]
        HOOK_N["★ write dismiss state<br/>━━━━━━━━━━<br/>check_type = 'hooks'\n7-day cooldown"]
    end

    subgraph DOCTOR_CHECK ["● _check_hook_registry_drift() — doctor path"]
        direction TB
        GEN_HOOKS["generate_hooks_json()<br/>━━━━━━━━━━<br/>canonical cmd set"]
        LOAD_SETTINGS["load settings.json<br/>━━━━━━━━━━<br/>deployed cmd set"]
        DRIFT_CALC["★ canonical MINUS deployed<br/>━━━━━━━━━━<br/>drift count"]
        DRIFT_OK["DoctorResult OK<br/>━━━━━━━━━━<br/>Deployed hooks match"]
        DRIFT_WARN["DoctorResult WARNING<br/>━━━━━━━━━━<br/>Run autoskillit install<br/>to deploy N hooks"]
    end

    %% MAIN FLOW %%
    START --> SERVE_GATE
    SERVE_GATE -- "yes" --> SKIP
    SERVE_GATE -- "no" --> TTY_GATE
    TTY_GATE -- "no" --> SKIP
    TTY_GATE -- "yes" --> MARKER

    %% DEV DETECTION %%
    MARKER -- "exists" --> DEV_FLAG
    MARKER -- "absent" --> GIT_DIR
    GIT_DIR -- ".git is dir" --> DEV_FLAG
    GIT_DIR -- ".git is file / absent" --> NORMAL_FLAG

    %% VERSION FETCH %%
    DEV_FLAG --> DEV_API
    NORMAL_FLAG --> NORMAL_API
    DEV_API --> DISMISS_LOAD
    NORMAL_API --> DISMISS_LOAD
    DEV_API -- "error" --> FETCH_FAIL
    NORMAL_API -- "error" --> FETCH_FAIL
    FETCH_FAIL --> HOOK_COUNT

    %% BINARY CHECK %%
    DISMISS_LOAD --> BIN_STALE
    BIN_STALE -- "no / latest=None" --> HOOK_COUNT
    BIN_STALE -- "yes" --> BIN_DISMISSED
    BIN_DISMISSED -- "yes" --> HOOK_COUNT
    BIN_DISMISSED -- "no" --> BIN_PROMPT
    BIN_PROMPT -- "Y / enter" --> BIN_Y
    BIN_PROMPT -- "N" --> BIN_N
    BIN_Y --> DONE
    BIN_N --> DONE

    %% HOOK CHECK %%
    HOOK_COUNT --> HOOK_POS
    HOOK_POS -- "no" --> DONE
    HOOK_POS -- "yes" --> HOOK_DISMISSED
    HOOK_DISMISSED -- "yes" --> DONE
    HOOK_DISMISSED -- "no" --> HOOK_PROMPT
    HOOK_PROMPT -- "Y / enter" --> HOOK_Y
    HOOK_PROMPT -- "N" --> HOOK_N
    HOOK_Y --> DONE
    HOOK_N --> DONE

    %% DOCTOR FLOW (separate path) %%
    START -. "autoskillit doctor" .-> GEN_HOOKS
    GEN_HOOKS --> LOAD_SETTINGS
    LOAD_SETTINGS --> DRIFT_CALC
    DRIFT_CALC -- "drift = 0" --> DRIFT_OK
    DRIFT_CALC -- "drift > 0" --> DRIFT_WARN

    %% CLASS ASSIGNMENTS %%
    class START,SKIP,DONE terminal;
    class SERVE_GATE,TTY_GATE,BIN_STALE,BIN_DISMISSED,HOOK_POS,HOOK_DISMISSED,MARKER,GIT_DIR phase;
    class DEV_FLAG,NORMAL_FLAG,DISMISS_LOAD newComponent;
    class DEV_API,NORMAL_API output;
    class FETCH_FAIL detector;
    class BIN_PROMPT,HOOK_PROMPT,BIN_N,HOOK_N,HOOK_COUNT,DRIFT_CALC newComponent;
    class BIN_Y,HOOK_Y,GEN_HOOKS,LOAD_SETTINGS handler;
    class DRIFT_OK,DRIFT_WARN stateNode;
```

### Development Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;

    subgraph SOURCE ["SOURCE (changed)"]
        direction TB
        STALE["★ cli/_stale_check.py<br/>━━━━━━━━━━<br/>is_dev_mode()<br/>run_stale_check()<br/>dismiss state I/O"]
        DOCTOR["● cli/_doctor.py<br/>━━━━━━━━━━<br/>_check_hook_registry_drift()<br/>_count_hook_registry_drift()"]
        APP["● cli/app.py<br/>━━━━━━━━━━<br/>main() stale check hook"]
    end

    subgraph TASKFILE ["● Taskfile.yml — task runner"]
        direction LR
        TEST_ALL["task test-all<br/>━━━━━━━━━━<br/>lint + tests (human)"]
        TEST_CHECK["task test-check<br/>━━━━━━━━━━<br/>PASS/FAIL (CI/MCP)"]
        INSTALL_DEV["★ task install-dev<br/>━━━━━━━━━━<br/>uv tool install --force @integration<br/>autoskillit install"]
    end

    subgraph QUALITY ["PRE-COMMIT QUALITY GATES"]
        direction TB
        RUFF_FMT["ruff format<br/>━━━━━━━━━━<br/>auto-fix formatting"]
        RUFF_CHECK["ruff check<br/>━━━━━━━━━━<br/>auto-fix lint"]
        MYPY["mypy<br/>━━━━━━━━━━<br/>type checking<br/>no-print rule for _stale_check exempt"]
        UV_LOCK["uv lock --check<br/>━━━━━━━━━━<br/>lock file consistency"]
        GITLEAKS["gitleaks<br/>━━━━━━━━━━<br/>secret scanning"]
    end

    subgraph TESTS_CLI ["★ tests/cli/ (new & modified)"]
        direction TB
        TSC["★ test_stale_check.py<br/>━━━━━━━━━━<br/>13 tests (SC-01..13)<br/>dev mode · dismiss state<br/>TTY guard · CLAUDECODE guard"]
        TDR["● test_doctor.py<br/>━━━━━━━━━━<br/>+3 tests (DC-11..13)<br/>hook_registry_drift OK/WARN<br/>doctor --json output"]
        TTTY["● test_input_tty_contracts.py<br/>━━━━━━━━━━<br/>TTY contract coverage"]
    end

    subgraph TESTS_ARCH ["● tests/arch/ (modified)"]
        direction TB
        RULES["● _rules.py<br/>━━━━━━━━━━<br/>_PRINT_EXEMPT += _stale_check<br/>ARCH-001 no-print exemption"]
        SUB_ISOL["● test_subpackage_isolation.py<br/>━━━━━━━━━━<br/>cli/ file count bump → 14<br/>singleton locality exemption"]
    end

    subgraph TESTS_INFRA ["● tests/infra/ (modified)"]
        direction TB
        TF["● test_taskfile.py<br/>━━━━━━━━━━<br/>+2 tests (TF-6..7)<br/>install-dev exists<br/>uses @integration + autoskillit install"]
    end

    subgraph PYTEST ["PYTEST RUNNER"]
        direction LR
        XDIST["pytest-xdist<br/>━━━━━━━━━━<br/>-n 4 parallel<br/>xdist-safe tests"]
        ASYNCIO["pytest-asyncio<br/>━━━━━━━━━━<br/>async test support"]
    end

    %% PIPELINE FLOW %%
    SOURCE --> RUFF_FMT
    RUFF_FMT --> RUFF_CHECK
    RUFF_CHECK --> MYPY
    MYPY --> UV_LOCK
    UV_LOCK --> GITLEAKS

    TASKFILE --> PYTEST
    TESTS_CLI --> PYTEST
    TESTS_ARCH --> PYTEST
    TESTS_INFRA --> PYTEST
    SOURCE -.-> TESTS_CLI
    SOURCE -.-> TESTS_ARCH
    TASKFILE -.-> TESTS_INFRA

    %% CLASS ASSIGNMENTS %%
    class STALE newComponent;
    class DOCTOR,APP,RULES,SUB_ISOL,TDR,TTTY,TF cli;
    class TEST_ALL,TEST_CHECK phase;
    class INSTALL_DEV newComponent;
    class RUFF_FMT,RUFF_CHECK,MYPY,UV_LOCK,GITLEAKS detector;
    class TSC newComponent;
    class XDIST,ASYNCIO handler;
    class PYTEST output;
```

Closes #514

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/impl-20260326-162457-353623/.autoskillit/temp/make-plan/detect_stale_installs_plan_2026-03-26_000001.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
…ners Produce False Negatives (#520)

## Summary

The `TestRunner` Protocol (`core/_type_protocols.py`) returned a bare
positional `tuple[bool, str]` — the **only** Protocol in the codebase
that used a positional tuple for complex return data rather than a named
dataclass. This structural gap made it impossible to carry `stderr`
through the testing pipeline without a breaking change, which is why
`DefaultTestRunner.run()` silently discarded `result.stderr`. The
downstream consequence was twofold: (1) `check_test_passed()` operated
on stdout-only data, and (2) its closed-world assumption (CWA) —
returning `False` when no pytest summary was found — fired
unconditionally for all non-pytest runners (`cargo nextest`, `go test`,
custom scripts) that pass via exit code 0 with no pytest-format output.

The fix introduces a named `TestResult` dataclass (matching the
established pattern of `SkillResult`, `CleanupResult`, `CIRunScope` in
`_type_results.py`) and promotes it to the Protocol return type. This
makes it structurally impossible to silently drop stderr, forces every
caller to name the fields they consume, and eliminates the implicit
"bare tuple = stdout-only" assumption. The adjudication logic is
inverted to be runner-agnostic: trust exit code when no recognized
parser (pytest) matches.

Closes #513

## Architecture Impact

### Process Flow Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 40, 'rankSpacing': 50, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;

    START([test_check MCP call])
    PASS([PASS])
    FAIL([FAIL])

    subgraph Entry ["MCP Entry — ● tools_workspace.py"]
        TESTER{"tester<br/>configured?"}
        NOCFG["return error<br/>━━━━━━━━━━<br/>not configured"]
    end

    subgraph Execution ["Subprocess Execution — ● testing.py"]
        DTR["● DefaultTestRunner.run(cwd)<br/>━━━━━━━━━━<br/>reads config.test_check.command<br/>reads config.test_check.timeout"]
        RUNNER["SubprocessRunner<br/>━━━━━━━━━━<br/>executes command in cwd<br/>captures stdout + stderr"]
        SPR["SubprocessResult<br/>━━━━━━━━━━<br/>{returncode, stdout, stderr}"]
    end

    subgraph Adjudication ["● Adjudication — check_test_passed()"]
        RC{"returncode != 0?"}
        COMBINE["build combined<br/>━━━━━━━━━━<br/>stdout + '\n' + stderr"]
        PPS["● parse_pytest_summary(combined)<br/>━━━━━━━━━━<br/>2-pass: =-delimited + bare -q<br/>searches stdout AND stderr"]
        MATCH{"pytest summary<br/>found?"}
        TRUST["● Trust exit code<br/>━━━━━━━━━━<br/>returncode == 0 → True<br/>runner-agnostic path"]
        COUNTS{"failed > 0<br/>or error > 0?"}
    end

    subgraph Result ["● TestResult Contract — core/_type_results.py"]
        TR["● TestResult<br/>━━━━━━━━━━<br/>{passed: bool,<br/>stdout: str,<br/>stderr: str}"]
    end

    subgraph Response ["● MCP Response — tools_workspace.py"]
        RESP["● test_check response<br/>━━━━━━━━━━<br/>{passed, stdout, stderr}<br/>truncated text"]
    end

    subgraph MergeGate ["perform_merge() Test Gates — ● git.py"]
        GATE{"test_gate_on_merge?"}
        PRETEST["● Pre-rebase gate<br/>━━━━━━━━━━<br/>tester.run(worktree_path)<br/>blocks on failure"]
        REBASE["git rebase<br/>━━━━━━━━━━<br/>onto base branch"]
        POSTTEST["● Post-rebase gate<br/>━━━━━━━━━━<br/>tester.run(worktree_path)<br/>blocks on regression"]
        MERGE["git merge --ff-only<br/>━━━━━━━━━━<br/>fast-forward merge"]
    end

    MERGEPASS([MERGE SUCCESS])
    MERGEFAIL([MERGE BLOCKED])

    START --> TESTER
    TESTER -->|"yes"| DTR
    TESTER -->|"no"| NOCFG
    DTR --> RUNNER
    RUNNER --> SPR
    SPR -->|"stdout + stderr forwarded"| TR
    TR -->|"passed=?"| RC
    RC -->|"yes"| FAIL
    RC -->|"no"| COMBINE
    COMBINE --> PPS
    PPS --> MATCH
    MATCH -->|"no match"| TRUST
    MATCH -->|"pytest found"| COUNTS
    TRUST -->|"rc == 0"| PASS
    TRUST -->|"rc != 0"| FAIL
    COUNTS -->|"clean"| PASS
    COUNTS -->|"failures"| FAIL
    PASS --> TR
    FAIL --> TR
    TR --> RESP

    GATE -->|"yes"| PRETEST
    GATE -->|"no"| MERGE
    PRETEST -->|"passed"| REBASE
    PRETEST -->|"failed"| MERGEFAIL
    REBASE --> POSTTEST
    POSTTEST -->|"passed"| MERGE
    POSTTEST -->|"failed"| MERGEFAIL
    MERGE --> MERGEPASS

    class START terminal;
    class PASS,FAIL terminal;
    class MERGEPASS,MERGEFAIL terminal;
    class NOCFG detector;
    class DTR handler;
    class RUNNER,SPR stateNode;
    class TR newComponent;
    class RC,MATCH,TESTER,GATE,COUNTS stateNode;
    class COMBINE,PPS phase;
    class TRUST newComponent;
    class RESP output;
    class PRETEST,POSTTEST handler;
    class REBASE,MERGE phase;
```

### Module Dependency Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 70, 'curve': 'basis'}}}%%
graph TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef integration fill:#c62828,stroke:#ef9a9a,stroke-width:2px,color:#fff;
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;

    subgraph L0 ["L0 — CORE (Zero autoskillit imports)"]
        direction LR
        RESULTS["● core/_type_results.py<br/>━━━━━━━━━━<br/>TestResult dataclass added<br/>SkillResult, CleanupResult, etc."]
        PROTOCOLS["● core/_type_protocols.py<br/>━━━━━━━━━━<br/>TestRunner Protocol<br/>returns TestResult (was tuple)"]
        INIT["● core/__init__.py<br/>━━━━━━━━━━<br/>re-exports TestResult<br/>public surface"]
    end

    subgraph L1 ["L1 — EXECUTION / PIPELINE"]
        direction LR
        TESTING["● execution/testing.py<br/>━━━━━━━━━━<br/>DefaultTestRunner<br/>check_test_passed()"]
        CTX["pipeline/context.py<br/>━━━━━━━━━━<br/>tester: TestRunner | None<br/>DI container"]
    end

    subgraph L3 ["L3 — SERVER"]
        direction LR
        WORKSPACE["● server/tools_workspace.py<br/>━━━━━━━━━━<br/>test_check MCP handler<br/>returns {passed, stdout, stderr}"]
        GIT["● server/git.py<br/>━━━━━━━━━━<br/>perform_merge()<br/>pre + post rebase gates"]
        FACTORY["server/_factory.py<br/>━━━━━━━━━━<br/>wires DefaultTestRunner<br/>into ToolContext.tester"]
    end

    subgraph Tests ["TESTS (cross-layer)"]
        direction LR
        CONFTEST["● tests/conftest.py<br/>━━━━━━━━━━<br/>StatefulMockTester<br/>uses TestResult"]
        TTEST["● tests/execution/test_testing.py<br/>━━━━━━━━━━<br/>check_test_passed tests<br/>non-pytest runner tests"]
        CONTRACTS["● tests/contracts/test_protocol_satisfaction.py<br/>━━━━━━━━━━<br/>TestRunner return type<br/>verified as TestResult"]
        WTEST["● tests/server/test_tools_workspace.py<br/>━━━━━━━━━━<br/>schema: {passed,stdout,stderr}<br/>cargo nextest style test"]
        GTEST["● tests/server/test_git.py<br/>━━━━━━━━━━<br/>StatefulMockTester calls<br/>updated to TestResult"]
        TGTEST["● tests/server/test_tools_git.py<br/>━━━━━━━━━━<br/>ls-files result added<br/>merge gate tests"]
    end

    RESULTS -->|"imported by"| PROTOCOLS
    RESULTS -->|"re-exported via"| INIT
    RESULTS -->|"TestResult"| TESTING
    PROTOCOLS -->|"TestRunner Protocol"| CTX
    CTX -->|"ToolContext.tester"| WORKSPACE
    CTX -->|"ToolContext.tester"| GIT
    TESTING -->|"wired as tester"| FACTORY
    FACTORY -->|"injects"| CTX
    RESULTS -->|"TestResult"| CONFTEST
    PROTOCOLS -->|"TestRunner"| CONTRACTS
    TESTING -->|"check_test_passed"| TTEST
    CONFTEST -->|"StatefulMockTester"| WTEST
    CONFTEST -->|"StatefulMockTester"| GTEST
    GIT -->|"perform_merge"| TGTEST

    class RESULTS newComponent;
    class PROTOCOLS,INIT handler;
    class TESTING handler;
    class CTX stateNode;
    class WORKSPACE,GIT phase;
    class FACTORY phase;
    class CONFTEST,TTEST,CONTRACTS,WTEST,GTEST,TGTEST output;
```

### State Lifecycle Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000;

    subgraph SubprocessContract ["SUBPROCESS RESULT CONTRACT (immutable source)"]
        direction LR
        RC["SubprocessResult.returncode<br/>━━━━━━━━━━<br/>int — exit code<br/>INIT_ONLY: read once"]
        STDOUT["SubprocessResult.stdout<br/>━━━━━━━━━━<br/>str — process stdout<br/>INIT_ONLY: forwarded as-is"]
        STDERR["SubprocessResult.stderr<br/>━━━━━━━━━━<br/>str — process stderr<br/>INIT_ONLY: was DROPPED; now forwarded"]
    end

    subgraph AdjudicationGate ["● ADJUDICATION GATE — check_test_passed()"]
        direction TB
        RCGATE{"returncode != 0?<br/>━━━━━━━━━━<br/>FAIL-FAST gate"}
        COMBINE["combined = stdout + stderr<br/>━━━━━━━━━━<br/>DERIVED: ephemeral union<br/>used for parsing only"]
        PARSEGATE{"parse_pytest_summary(combined)<br/>━━━━━━━━━━<br/>counts found?"}
        TRUSTGATE["● trust exit code path<br/>━━━━━━━━━━<br/>no counts → rc==0 means PASS<br/>replaces old CWA: return False"]
        COUNTGATE{"failed > 0 or error > 0?<br/>━━━━━━━━━━<br/>pytest count validation"}
    end

    subgraph TestResultContract ["● TESTRESULT CONTRACT — core/_type_results.py"]
        direction LR
        TR_PASSED["● TestResult.passed<br/>━━━━━━━━━━<br/>bool: INIT_ONLY<br/>set by adjudication gate"]
        TR_STDOUT["● TestResult.stdout<br/>━━━━━━━━━━<br/>str: INIT_ONLY<br/>raw subprocess stdout"]
        TR_STDERR["● TestResult.stderr<br/>━━━━━━━━━━<br/>str: INIT_ONLY (was ABSENT)<br/>raw subprocess stderr — now carried"]
    end

    subgraph ProtocolGate ["● PROTOCOL CONFORMANCE GATE — core/_type_protocols.py"]
        PROTO["● TestRunner Protocol<br/>━━━━━━━━━━<br/>async run(cwd) → TestResult<br/>(was tuple[bool, str])"]
        MYPY["mypy type checker<br/>━━━━━━━━━━<br/>enforces return type<br/>at static analysis time"]
    end

    subgraph ConsumerContracts ["● CONSUMER FIELD CONTRACTS"]
        direction LR
        TC_RESP["● test_check response<br/>━━━━━━━━━━<br/>{passed, stdout, stderr}<br/>stderr: was ABSENT in response"]
        MERGE_PRE["● perform_merge pre-gate<br/>━━━━━━━━━━<br/>{test_stdout, test_stderr}<br/>stderr: was ABSENT in error dict"]
        MERGE_POST["● perform_merge post-gate<br/>━━━━━━━━━━<br/>test_result.passed<br/>(was: passed, _ = ...)"]
    end

    PASS_STATE(["passed = True"])
    FAIL_STATE(["passed = False"])

    RC -->|"read once"| RCGATE
    STDOUT -->|"forwarded"| COMBINE
    STDERR -->|"NOW forwarded"| COMBINE
    RCGATE -->|"yes: fail-fast"| FAIL_STATE
    RCGATE -->|"no"| COMBINE
    COMBINE --> PARSEGATE
    PARSEGATE -->|"no match"| TRUSTGATE
    PARSEGATE -->|"pytest found"| COUNTGATE
    TRUSTGATE -->|"rc == 0"| PASS_STATE
    TRUSTGATE -->|"rc != 0"| FAIL_STATE
    COUNTGATE -->|"clean"| PASS_STATE
    COUNTGATE -->|"failures"| FAIL_STATE
    PASS_STATE -->|"passed=True"| TR_PASSED
    FAIL_STATE -->|"passed=False"| TR_PASSED
    STDOUT -->|"stdout="| TR_STDOUT
    STDERR -->|"stderr="| TR_STDERR
    TR_PASSED --> PROTO
    TR_STDOUT --> PROTO
    TR_STDERR --> PROTO
    PROTO --> MYPY
    TR_PASSED -->|"test_result.passed"| TC_RESP
    TR_STDOUT -->|"truncated"| TC_RESP
    TR_STDERR -->|"truncated (NEW)"| TC_RESP
    TR_PASSED -->|"pre-gate check"| MERGE_PRE
    TR_STDOUT -->|"test_stdout"| MERGE_PRE
    TR_STDERR -->|"test_stderr (NEW)"| MERGE_PRE
    TR_PASSED -->|"post-gate check"| MERGE_POST

    class RC,STDOUT stateNode;
    class STDERR gap;
    class RCGATE,PARSEGATE,COUNTGATE stateNode;
    class COMBINE phase;
    class TRUSTGATE newComponent;
    class TR_PASSED,TR_STDOUT newComponent;
    class TR_STDERR newComponent;
    class PROTO,MYPY detector;
    class TC_RESP,MERGE_PRE,MERGE_POST output;
    class PASS_STATE,FAIL_STATE cli;
```

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/remediation-20260326-162603-381072/.autoskillit/temp/rectify/rectify_test_runner_protocol_lossy_tuple_2026-03-26_000000.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
## Summary

`DefaultMergeQueueWatcher.wait()` reached the `ejected` terminal via
**negative inference**: "not merged, not in queue, not a stall candidate
→ ejected." A PR with `BLOCKED` mergeStateStatus (GitHub's umbrella for
pending CI, missing reviews, and other blockers) was never a stall
candidate, so it fell through to ejection unconditionally — even when CI
was still running.

The fix replaces the negative-inference ejection path with a
**positive-confirmation model**: the `ejected` terminal is only
reachable once `statusCheckRollup.state` confirms checks are terminal
(`SUCCESS`/`FAILURE`/`ERROR`) or absent (`None`). Structural immunity is
provided by introducing a `PRFetchState` TypedDict that enforces at the
type level that the test helper and production code always agree on
which fields exist.

## Architecture Impact

### Process Flow Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 40, 'rankSpacing': 50, 'curve': 'basis'}}}%%
flowchart TB
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;

    START([wait called])
    MERGED([merged ✓])
    EJECTED([ejected ✗])
    STALLED([stalled ✗])
    TIMEOUT([timeout ✗])
    ERROR([error ✗])

    D0{"repo contains '/'?"}
    Fetch["● _fetch_pr_and_queue_state<br/>━━━━━━━━━━<br/>GraphQL: merged, state,<br/>mergeStateStatus, autoMergeRequest<br/>● statusCheckRollup.state"]
    D1{"merged?"}
    D2{"state == CLOSED?"}
    D3{"in_queue?"}
    D4{"queue_state ==<br/>UNMERGEABLE?"}
    D5{"confirmed absent?<br/>not_in_queue_cycles<br/>≥ 2"}
    D6{"is_stall_candidate?<br/>enabled_at set AND<br/>CLEAN or HAS_HOOKS"}
    D7{"★ checks_state in<br/>{PENDING, EXPECTED}?"}

    subgraph StallRecovery ["Stall Recovery"]
        direction TB
        DS1{"grace period<br/>elapsed?"}
        DS2{"budget<br/>remains?"}
        Toggle["_toggle_auto_merge<br/>━━━━━━━━━━<br/>disable → 2s → enable<br/>backoff = min(30×2ⁿ,120s)<br/>reset not_in_queue_cycles"]
    end

    Sleep["sleep(poll_interval)<br/>━━━━━━━━━━<br/>continue loop"]
    Deadline{"deadline<br/>exceeded?"}

    START --> D0
    D0 -->|"no"| ERROR
    D0 -->|"yes"| Fetch
    Fetch -->|"exception"| Sleep
    Fetch --> D1
    D1 -->|"yes"| MERGED
    D1 -->|"no"| D2
    D2 -->|"yes"| EJECTED
    D2 -->|"no"| D3
    D3 -->|"yes (in queue)"| D4
    D4 -->|"yes"| EJECTED
    D4 -->|"no (AWAITING_CHECKS)"| Sleep
    D3 -->|"no"| D5
    D5 -->|"not yet confirmed"| Sleep
    D5 -->|"confirmed"| D6
    D6 -->|"yes"| DS1
    DS1 -->|"no — within grace"| Sleep
    DS1 -->|"yes"| DS2
    DS2 -->|"yes"| Toggle
    Toggle --> Sleep
    DS2 -->|"no — exhausted"| STALLED
    D6 -->|"no"| D7
    D7 -->|"yes — CI running"| Sleep
    D7 -->|"no — terminal or None"| EJECTED
    Sleep --> Deadline
    Deadline -->|"no"| Fetch
    Deadline -->|"yes"| TIMEOUT

    class START,MERGED,EJECTED,STALLED,TIMEOUT,ERROR terminal;
    class Fetch handler;
    class D0,D1,D2,D3,D4,D5,D6,DS1,DS2 stateNode;
    class D7 newComponent;
    class Toggle phase;
    class Sleep handler;
    class Deadline detector;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | Terminal | Start, merged, ejected, stalled, timeout, error
states |
| Teal | State | Existing decision points in the polling loop |
| Orange | Handler | Fetch, sleep/continue nodes |
| Purple | Phase | Stall recovery (toggle + backoff) |
| Green | New Component | ★ Pending-CI guard (D7) — the immunity
addition |
| Red | Detector | Deadline check |

### State Lifecycle Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;

    subgraph Contract ["● PRFetchState TypedDict — Field Contract"]
        direction LR
        F1["merged: bool<br/>━━━━━━━━━━<br/>INIT_ONLY"]
        F2["state: str<br/>━━━━━━━━━━<br/>INIT_ONLY"]
        F3["merge_state_status: str<br/>━━━━━━━━━━<br/>INIT_ONLY"]
        F4["auto_merge_enabled_at: datetime | None<br/>━━━━━━━━━━<br/>INIT_ONLY"]
        F5["pr_node_id: str<br/>━━━━━━━━━━<br/>INIT_ONLY"]
        F6["in_queue: bool<br/>━━━━━━━━━━<br/>INIT_ONLY"]
        F7["queue_state: str | None<br/>━━━━━━━━━━<br/>INIT_ONLY"]
        F8["★ checks_state: str | None<br/>━━━━━━━━━━<br/>NEW — statusCheckRollup.state<br/>None = no CI configured"]
    end

    subgraph Production ["● _fetch_pr_and_queue_state()"]
        direction TB
        GraphQL["GraphQL request<br/>━━━━━━━━━━<br/>merged, state, mergeStateStatus<br/>autoMergeRequest.enabledAt<br/>● statusCheckRollup.state"]
        Extract["Extract fields<br/>━━━━━━━━━━<br/>parse enabledAt → datetime | None<br/>★ extract checks_rollup.state"]
        Return["return PRFetchState(...)<br/>━━━━━━━━━━<br/>type-checked by mypy<br/>missing key → type error at CI"]
    end

    subgraph TestHelper ["● _queue_state() test helper"]
        direction TB
        Helper["● _queue_state(**kwargs)<br/>━━━━━━━━━━<br/>merged, state, merge_state_status<br/>auto_merge_enabled_at, pr_node_id<br/>in_queue, queue_state<br/>★ checks_state=None (new param)"]
        HelperReturn["→ PRFetchState<br/>━━━━━━━━━━<br/>return type pinned to TypedDict<br/>divergence = mypy error"]
    end

    subgraph Enforcement ["Contract Enforcement Gates"]
        direction TB
        G1["mypy structural check<br/>━━━━━━━━━━<br/>PRFetchState keys vs return value<br/>gate: CI pre-merge"]
        G2["★ new field addition rule<br/>━━━━━━━━━━<br/>add to PRFetchState → mypy forces<br/>update to _queue_state() → forces<br/>test author to handle new field"]
        G3["test coverage gate<br/>━━━━━━━━━━<br/>_queue_state() typed → missing field<br/>in helper = compile-time error<br/>not runtime surprise"]
    end

    Production --> Contract
    Contract --> TestHelper
    TestHelper --> Enforcement
    G1 --> G2
    G2 --> G3

    class F1,F2,F3,F4,F5,F6,F7 detector;
    class F8 newComponent;
    class GraphQL,Extract handler;
    class Return output;
    class Helper phase;
    class HelperReturn output;
    class G1,G2,G3 stateNode;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Red | INIT_ONLY | Fields consumed each cycle (never mutated after
fetch) |
| Green | New Field | ★ `checks_state` — new field closing the silent
coverage gap |
| Orange | Fetch Logic | GraphQL extraction and field parsing |
| Dark Teal | Return/Pin | TypedDict-typed return — mutation contract
enforced by mypy |
| Purple | Test Helper | `_queue_state()` now typed as `-> PRFetchState`
|
| Teal | Gates | Enforcement gates: mypy, new-field rule, test coverage
|

Closes #507

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/remediation-20260326-162603-921687/.autoskillit/temp/rectify/rectify_wait_for_merge_queue_pending_ci_ejected_2026-03-26_162603.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
#521)

## Summary

`terminal_guard()` in `cli/_terminal.py` already emits `\033[?1049l`
(exit alternate screen) in its finally block but never enters the
alternate screen at the start. Claude Code's Ink-based TUI renders
directly to the **main** terminal buffer, so the exit escape is a no-op
and TUI content persists as visual afterimage after the cook session
exits.

The fix is minimal and surgical: emit `\033[?1049h` (enter alternate
screen buffer) in `terminal_guard()` immediately after confirming a
valid TTY fd, before yielding. This causes the subprocess (Claude Code)
to render its entire TUI in the alternate screen buffer, which is
automatically discarded when the existing `\033[?1049l` fires in the
finally block — restoring the user's terminal to its pre-session state
exactly as `vim`, `less`, and `htop` do. Three new tests cover
REQ-TEST-001 through REQ-TEST-003.

## Requirements

### ALTSCR — Alternate Screen Buffer Envelope

- **REQ-ALTSCR-001:** `terminal_guard()` must emit `\033[?1049h` (enter
alternate screen buffer) to stdout before yielding control to the
caller.
- **REQ-ALTSCR-002:** `terminal_guard()` must emit `\033[?1049l` (exit
alternate screen buffer) to stdout in its finally block, restoring the
main buffer content.
- **REQ-ALTSCR-003:** The alternate screen entry must occur after stdin
is confirmed as a TTY and termios attributes have been saved, but before
the subprocess launches.
- **REQ-ALTSCR-004:** The alternate screen exit must occur regardless of
how the subprocess terminates (clean exit, SIGINT, KeyboardInterrupt,
SystemExit, crash).

### XPLAT — Cross-Platform Terminal Compatibility

- **REQ-XPLAT-001:** The implementation must function correctly on Linux
(native, WSL2) and macOS (current supported versions).
- **REQ-XPLAT-002:** The escape sequences used must be standard
VT100/ANSI sequences supported by Terminal.app, iTerm2, VS Code
integrated terminal, GNOME Terminal, and Alacritty.
- **REQ-XPLAT-003:** The non-TTY no-op behavior must be preserved — when
stdin is not a real TTY (CI, pipes, headless), no escape sequences are
emitted.

### TEST — Test Coverage

- **REQ-TEST-001:** A test must verify that `\033[?1049h` is emitted to
stdout when `terminal_guard()` is entered with a valid TTY fd.
- **REQ-TEST-002:** A test must verify that `\033[?1049l` is emitted to
stdout when `terminal_guard()` exits normally, on KeyboardInterrupt, and
on SystemExit.
- **REQ-TEST-003:** A test must verify that no escape sequences are
emitted when stdin is not a TTY.
- **REQ-TEST-004:** The existing structural contract test
(`test_interactive_subprocess_contracts.py`) must continue to pass
without modification.

## Architecture Impact

### Process Flow Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 40, 'rankSpacing': 55, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;

    %% TERMINALS %%
    START([terminal_guard entered])
    NOOP([no-op exit — no sequences emitted])
    END([terminal_guard exits — main buffer restored])

    subgraph Entry ["Entry Phase (before yield)"]
        direction TB
        CheckTTY{"sys.stdin.isatty()?"}
        SaveTermios["tcgetattr(fd)<br/>━━━━━━━━━━<br/>save old_settings; fd set"]
        ErrPath["fd = None<br/>━━━━━━━━━━<br/>tcgetattr failed — guard no-ops"]
        EnterAlt["● emit \\033[?1049h<br/>━━━━━━━━━━<br/>enter alternate screen buffer<br/>stdout.write + flush"]
    end

    subgraph Execution ["Subprocess Execution"]
        Yield["yield<br/>━━━━━━━━━━<br/>subprocess.run(claude ...)<br/>TUI renders in alt screen"]
    end

    subgraph Cleanup ["Finally Block — all termination paths"]
        direction TB
        RestoreTermios["tcsetattr(TCSAFLUSH, old_settings)<br/>━━━━━━━━━━<br/>restore kernel TTY attrs<br/>(stty sane fallback on error)"]
        EmitReset["● emit \\033[?1049l\\033[?1l\\033>\\033[0m\\033[?25h<br/>━━━━━━━━━━<br/>exit alt screen → main buffer restored<br/>reset cursor/keypad/SGR/show cursor"]
    end

    %% FLOW %%
    START --> CheckTTY
    CheckTTY -->|"not a TTY<br/>(CI, pipe, headless)"| NOOP
    CheckTTY -->|"is TTY"| SaveTermios
    SaveTermios -->|"tcgetattr raises"| ErrPath
    ErrPath --> Yield
    SaveTermios -->|"fd saved"| EnterAlt
    EnterAlt --> Yield
    Yield -->|"clean exit / SIGINT /<br/>KeyboardInterrupt / SystemExit"| RestoreTermios
    RestoreTermios --> EmitReset
    EmitReset --> END

    %% CLASS ASSIGNMENTS %%
    class START,NOOP,END terminal;
    class CheckTTY stateNode;
    class SaveTermios,ErrPath handler;
    class EnterAlt output;
    class Yield phase;
    class RestoreTermios handler;
    class EmitReset output;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | Terminal | Entry/exit/no-op terminal states |
| Teal | State | Decision points (TTY detection) |
| Orange | Handler | Termios save/restore processing |
| Dark Teal | Output | ● Modified: alternate screen enter/exit emission
|
| Purple | Phase | Subprocess execution (yield point) |

### Operational Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;

    subgraph CLI ["CLI ENTRY POINTS"]
        direction LR
        CookCmd["autoskillit cook<br/>━━━━━━━━━━<br/>--resume / --session-id<br/>Interactive skill session"]
        OrderCmd["autoskillit order [recipe]<br/>━━━━━━━━━━<br/>--resume / --session-id<br/>Recipe-driven orchestration"]
    end

    subgraph Preflight ["PRE-FLIGHT CHECKS"]
        direction TB
        Check1["Verify claude on PATH<br/>━━━━━━━━━━<br/>CLAUDECODE env guard<br/>stdin interactive check"]
        RecipeLoad["Recipe validation<br/>━━━━━━━━━━<br/>YAML parse + semantic rules<br/>subset availability check"]
        UserConfirm{"Launch session?<br/>━━━━━━━━━━<br/>[Enter / n]"}
    end

    subgraph SessionSetup ["SESSION SETUP"]
        direction TB
        SkillMgr["SessionSkillManager<br/>━━━━━━━━━━<br/>ephemeral skill dir<br/>stale session cleanup"]
        CmdBuild["build_interactive_cmd<br/>━━━━━━━━━━<br/>claude --add-dir ...<br/>AUTOSKILLIT_HEADLESS env"]
    end

    subgraph TerminalBoundary ["● TERMINAL BOUNDARY (terminal_guard)"]
        direction TB
        EnterAlt["● emit \\033[?1049h<br/>━━━━━━━━━━<br/>enter alternate screen buffer<br/>save termios attrs"]
        ClaudeProc["subprocess.run(claude)<br/>━━━━━━━━━━<br/>full Claude Code TUI<br/>renders in alt screen"]
        ExitAlt["● emit \\033[?1049l + resets<br/>━━━━━━━━━━<br/>exit alt screen → main restored<br/>restore termios attrs"]
    end

    subgraph PostExit ["POST-EXIT"]
        direction TB
        OnboardMark["Onboarding marker written<br/>━━━━━━━━━━<br/>first-run complete flag"]
        ExitCode["sys.exit(result.returncode)<br/>━━━━━━━━━━<br/>propagate claude exit code"]
    end

    %% FLOWS %%
    CookCmd --> Check1
    OrderCmd --> Check1
    OrderCmd --> RecipeLoad
    Check1 --> UserConfirm
    RecipeLoad --> UserConfirm
    UserConfirm -->|"n / Ctrl-C"| ExitCode
    UserConfirm -->|"Enter"| SkillMgr
    SkillMgr --> CmdBuild
    CmdBuild --> EnterAlt
    EnterAlt --> ClaudeProc
    ClaudeProc -->|"exit / SIGINT / crash"| ExitAlt
    ExitAlt --> OnboardMark
    ExitAlt --> ExitCode

    %% CLASS ASSIGNMENTS %%
    class CookCmd,OrderCmd cli;
    class Check1,RecipeLoad handler;
    class UserConfirm stateNode;
    class SkillMgr,CmdBuild phase;
    class EnterAlt,ExitAlt output;
    class ClaudeProc detector;
    class OnboardMark,ExitCode handler;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | CLI | Entry point commands (cook, order) |
| Orange | Handler | Pre-flight validation and post-exit actions |
| Teal | Decision | User confirmation gate |
| Purple | Setup | Session and command preparation |
| Dark Teal | Output | ● Modified: terminal_guard() alternate screen
boundary |
| Red | Subprocess | Claude Code interactive process |

Closes #516

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/impl-20260326-171304-066736/.autoskillit/temp/make-plan/terminal_guard_altscreen_plan_2026-03-26_171500.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
## Summary

Implements the `validate-audit` skill — a parallel subagent audit
validator that examines findings from `audit-arch`, `audit-tests`, and
`audit-cohesion` against actual code, git history, and design intent.
Dispatches 9–10 agents simultaneously (8–9 code validators + 1 history
researcher) and produces a validated report with a `validated: true`
marker plus a separate contested findings file. This PR covers both the
test infrastructure (15 T-VAL contract tests) and the SKILL.md
implementation that makes them all pass.

<details>
<summary>Individual Group Plans</summary>

### Group 1: validate-audit Skill — Post-Audit Finding Validation with
Parallel Subagents — PART A ONLY

Create the `validate-audit` skill that validates audit findings from
`audit-arch`, `audit-tests`,
and `audit-cohesion` against actual code, git history, and design
intent. The skill dispatches
9–10 parallel subagents in a single message — 8–9 code validation agents
(one per thematic
finding batch, grouped by code area) and 1 history research agent.
Verdicts are VALID,
VALID BUT EXCEPTION WARRANTED, or CONTESTED. Output: a validated report
with `validated: true`
header marker (CONTESTED findings removed, exceptions documented,
severity adjustments noted)
plus a separate contested findings file. Interactive sessions prompt for
approval; headless
auto-writes.

**Part A covers:** Failing test infrastructure (update
`tests/workspace/test_skills.py` + create
`tests/skills/test_validate_audit_contracts.py`). After Part A, all new
tests fail as expected
because the skill directory does not yet exist.

### Group 2: validate-audit Skill — Post-Audit Finding Validation with
Parallel Subagents — PART B ONLY

Part B covers the primary deliverable: creating
`src/autoskillit/skills_extended/validate-audit/SKILL.md`. After this
part, all 15 T-VAL tests
from Part A pass.

Part A (separate task) covered: updating
`tests/workspace/test_skills.py` and creating
`tests/skills/test_validate_audit_contracts.py`. Do NOT re-do those
changes here; assume they
are already in place and the 15 tests are failing, awaiting this
SKILL.md.

</details>

## Requirements

### PARSE — Report Parsing

- **REQ-PARSE-001:** The skill must accept a file path argument pointing
to an audit report markdown file.
- **REQ-PARSE-002:** The parser must extract finding IDs, severity
levels, referenced code locations (file:line), and principle categories
from the report.
- **REQ-PARSE-003:** The parser must handle output formats from
`audit-arch`, `audit-tests`, and `audit-cohesion` skills.

### AGENT — Subagent Orchestration

- **REQ-AGENT-001:** The skill must partition findings into 9–10
thematic batches grouped by principle, severity cluster, or code area.
- **REQ-AGENT-002:** The skill must launch one code-validation subagent
per batch, each receiving the full finding text and referenced locations
for its batch.
- **REQ-AGENT-003:** The skill must launch one dedicated git/PR history
research subagent that cross-references all findings against commit
messages, PR descriptions, and open issues.
- **REQ-AGENT-004:** All subagents must be launched in parallel (single
message with multiple Agent tool calls).
- **REQ-AGENT-005:** Each code-validation subagent must read actual
source code, run `git log`/`git blame`, check `gh pr list
--state=merged`, and verify caller dependencies.
- **REQ-AGENT-006:** Each subagent must return a per-finding verdict
(VALID, VALID BUT EXCEPTION WARRANTED, or CONTESTED) with supporting
evidence.

### OUTPUT — Report Generation

- **REQ-OUTPUT-001:** The skill must produce a validated actionable
report that removes contested findings and expands exception-warranted
findings with constraint blockquotes.
- **REQ-OUTPUT-002:** The skill must produce a separate contested
findings file containing original finding text and the reason each was
contested.
- **REQ-OUTPUT-003:** The validated report must include an updated
executive summary with corrected counts, a validation status header, and
severity downgrade annotations.
- **REQ-OUTPUT-005:** The validated report must include a `validated:
true` marker in the Validation Status section header. This marker
signals to downstream tools and recipes that the report has been through
the validation process. Unvalidated reports must NOT have this marker.
- **REQ-OUTPUT-004:** Both output files must be written to the project's
`temp/` directory adjacent to the input report.

### VERDICT — Classification Criteria

- **REQ-VERDICT-001:** A finding is VALID when the referenced code
confirms the violation and no git history evidence justifies the current
state.
- **REQ-VERDICT-002:** A finding is VALID BUT EXCEPTION WARRANTED when
the violation is real but fixing it would conflict with documented
constraints (stdlib-only, separate entry points, intentional design
decisions).
- **REQ-VERDICT-003:** A finding is CONTESTED when the finding is
factually wrong, scope is overstated, the current code is the correct
design, or fixing would be counterproductive.
- **REQ-VERDICT-004:** Severity downgrades must be proposed when
evidence shows the original severity overstates the actual impact.

### POST — Post-Validation Actions

- **REQ-POST-001:** After synthesis, the skill must update the original
audit report in-place: remove contested findings, expand
exception-warranted findings with constraint blockquotes, apply severity
downgrades, and update executive summary counts.
- **REQ-POST-002:** The skill must write contested findings to a
separate file (e.g., `contested_findings_<date>.md`) adjacent to the
original report, preserving original finding text alongside the reason
each was contested.
- **REQ-POST-003:** If the session is interactive (not headless), the
skill must prompt the user: *"Update the original audit report with
validation results? [Y/n]"* before modifying the report. If headless,
update automatically.
- **REQ-POST-004:** After report updates, if the session is interactive
(not headless), the skill must prompt the user: *"File the validated
audit report as a GitHub issue via prepare-issue? [Y/n]"*. If the user
confirms, invoke `/prepare-issue` with the validated report as the issue
description, routing it as `recipe:implementation`.
- **REQ-POST-005:** In headless sessions, skip both prompts and perform
the report update automatically. Do NOT invoke prepare-issue in headless
mode.

## Architecture Impact

### Process Flow Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 40, 'rankSpacing': 50, 'curve': 'basis'}}}%%
flowchart TB
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;

    START([START: audit_report_path])
    END([END: output files written])

    subgraph Sequential ["★ MAIN THREAD — Sequential"]
        direction TB
        DETECT{"★ Detect Format<br/>━━━━━━━━━━<br/>audit-arch?<br/>audit-tests?<br/>audit-cohesion?"}
        PARSE["★ Parse Findings<br/>━━━━━━━━━━<br/>Extract ID, severity,<br/>file:line, category"]
        BATCH["★ Thematic Batcher<br/>━━━━━━━━━━<br/>Group by code area<br/>8–9 batches + history slot"]
        FORK["★ Single-Message Fork<br/>━━━━━━━━━━<br/>ALL Task calls<br/>in one message"]
        BARRIER["★ Barrier / Collect<br/>━━━━━━━━━━<br/>Wait for all agents<br/>Merge verdicts + context"]
        SYNTH["★ Synthesize<br/>━━━━━━━━━━<br/>Tally N_valid, N_exception,<br/>N_contested; upgrade findings<br/>if open PR/issue found"]
        GATE{"★ Interactive<br/>or Headless?<br/>━━━━━━━━━━<br/>AUTOSKILLIT_HEADLESS"}
        PROMPT["★ Approval Prompt<br/>━━━━━━━━━━<br/>Show verdict table<br/>Write? [Y/n]<br/>Offer prepare-issue"]
        WRITE["★ Write Output Files<br/>━━━━━━━━━━<br/>validated_report_{source}_{ts}.md<br/>contested_findings_{source}_{ts}.md"]
    end

    subgraph Workers ["★ PARALLEL SUBAGENT POOL — Single Message"]
        direction LR
        CV1["★ Code Validator 1<br/>━━━━━━━━━━<br/>Batch 1: pipeline/<br/>Read code + git log<br/>VALID / EXCEPTION / CONTESTED"]
        CV2["★ Code Validator 2<br/>━━━━━━━━━━<br/>Batch 2: execution/<br/>Read code + git log"]
        CVN["★ Code Validators 3–9<br/>━━━━━━━━━━<br/>One per code area<br/>8–9 total agents"]
        HR["★ History Researcher<br/>━━━━━━━━━━<br/>ALL findings<br/>git log 90d + gh issue list<br/>Surface in-progress fixes"]
    end

    START --> DETECT
    DETECT -->|"arch/tests/cohesion"| PARSE
    PARSE --> BATCH
    BATCH --> FORK
    FORK --> CV1 & CV2 & CVN & HR
    CV1 & CV2 & CVN & HR --> BARRIER
    BARRIER --> SYNTH
    SYNTH --> GATE
    GATE -->|"headless"| WRITE
    GATE -->|"interactive"| PROMPT
    PROMPT -->|"Y / confirmed"| WRITE
    WRITE --> END

    class START,END terminal;
    class DETECT,GATE stateNode;
    class PARSE,BATCH phase;
    class FORK,BARRIER detector;
    class CV1,CV2,CVN,HR,SYNTH,PROMPT,WRITE newComponent;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | Terminal | Start and end states |
| Teal | State/Decision | Format detection and mode gate |
| Purple | Phase | Parse and batch stages |
| Red | Synchronization | Single-message fork + barrier collect |
| Green (★) | New Components | All validate-audit nodes — new skill |

### Operational Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;

    subgraph Invocation ["INVOCATION PATHS"]
        direction TB
        COOK["autoskillit cook<br/>━━━━━━━━━━<br/>Interactive cook session<br/>All 61 skills via --plugin-dir"]
        HEADLESS["run_skill<br/>━━━━━━━━━━<br/>Automated headless session<br/>--add-dir skills_extended/"]
        CMD["★ /autoskillit:validate-audit<br/>━━━━━━━━━━<br/>[audit_report_path]<br/>categories: [audit]"]
    end

    subgraph Config ["CONFIGURATION"]
        direction TB
        HEADLESS_FLAG["AUTOSKILLIT_HEADLESS<br/>━━━━━━━━━━<br/>0 = interactive (default)<br/>1 = headless auto-write"]
        AUTO_DETECT["★ Auto-detect input<br/>━━━━━━━━━━<br/>Most recent mtime from:<br/>temp/audit-arch/<br/>temp/audit-tests/<br/>temp/audit-cohesion/"]
    end

    subgraph Discovery ["SKILL DISCOVERY"]
        direction TB
        RESOLVER["SkillResolver.list_all()<br/>━━━━━━━━━━<br/>Scans skills/ + skills_extended/<br/>Reads YAML frontmatter"]
        SKILLSEXT["★ skills_extended/<br/>validate-audit/SKILL.md<br/>━━━━━━━━━━<br/>SkillSource.BUNDLED_EXTENDED<br/>categories: [audit]"]
        WRITERECIPE["● write-recipe/SKILL.md<br/>━━━━━━━━━━<br/>validate-audit added to<br/>canonical skills list"]
    end

    subgraph Upstream ["UPSTREAM AUDIT SKILLS"]
        direction LR
        AUDITARCH["audit-arch<br/>━━━━━━━━━━<br/>Produces arch audit reports"]
        AUDITTESTS["audit-tests<br/>━━━━━━━━━━<br/>Produces test audit reports"]
        AUDITCOH["audit-cohesion<br/>━━━━━━━━━━<br/>Produces cohesion audit reports"]
    end

    subgraph Output ["OUTPUT ARTIFACTS"]
        direction TB
        VALRPT["★ validated_report_{source}_{ts}.md<br/>━━━━━━━━━━<br/>.autoskillit/temp/validate-audit/<br/>First line: validated: true"]
        CONTESTED["★ contested_findings_{source}_{ts}.md<br/>━━━━━━━━━━<br/>.autoskillit/temp/validate-audit/<br/>Written only when N_contested > 0"]
        PREPISSUE["prepare-issue<br/>━━━━━━━━━━<br/>Optional: file contested findings<br/>as GitHub issue (interactive only)"]
    end

    COOK --> CMD
    HEADLESS --> CMD
    CMD --> AUTO_DETECT
    CMD --> HEADLESS_FLAG
    AUDITARCH & AUDITTESTS & AUDITCOH -.->|"produces input for"| AUTO_DETECT
    AUTO_DETECT --> CMD
    RESOLVER --> SKILLSEXT
    SKILLSEXT --> CMD
    CMD --> VALRPT
    CMD --> CONTESTED
    CONTESTED -.->|"offer interactive"| PREPISSUE

    class COOK,HEADLESS,CMD cli;
    class HEADLESS_FLAG,AUTO_DETECT phase;
    class RESOLVER stateNode;
    class SKILLSEXT,VALRPT,CONTESTED newComponent;
    class WRITERECIPE handler;
    class AUDITARCH,AUDITTESTS,AUDITCOH detector;
    class PREPISSUE output;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | CLI | Invocation paths and slash commands |
| Purple | Config | Configuration and auto-detection |
| Teal | Discovery | SkillResolver state |
| Green (★) | New | New skill files and output artifacts |
| Orange (●) | Modified | Updated write-recipe skill list |
| Red | Upstream | Audit skills that produce input |
| Dark Teal | Output | Post-validation downstream |

Closes #429

## Implementation Plan

Plan files:
-
`/home/talon/projects/autoskillit-runs/impl-20260326-164058-424464/.autoskillit/temp/make-plan/validate_audit_skill_plan_2026-03-26_000100_part_a.md`
-
`/home/talon/projects/autoskillit-runs/impl-20260326-164058-424464/.autoskillit/temp/make-plan/validate_audit_skill_plan_2026-03-26_000100_part_b.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
…e Batches Multiple PRs (#530)

## Summary

`patch-bump-integration.yml` has no concurrency control. When GitHub's
merge queue
squash-merges a batch of PRs simultaneously, it fires N
`pull_request[closed]` events in
parallel. All N workflow runs check out the same HEAD, compute the same
next version, and
race to push. The first push wins; all subsequent runs fail with a
non-fast-forward
rejection — silently skipping a version bump for each remaining PR in
the batch.

The fix is a single YAML addition: a `concurrency` block at the workflow
level with
`cancel-in-progress: false`. This serializes queued runs so each PR in
the batch gets
its own sequential version bump.

## Architecture Impact

### Development Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;

    subgraph Structure ["PROJECT STRUCTURE"]
        SRC["src/autoskillit/<br/>━━━━━━━━━━<br/>12 sub-packages<br/>Python source"]
        TESTS["tests/<br/>━━━━━━━━━━<br/>unit · infra · integration<br/>pytest test suite"]
        WORKFLOWS[".github/workflows/<br/>━━━━━━━━━━<br/>CI/CD pipeline definitions<br/>GitHub Actions"]
    end

    subgraph PreCommit ["PRE-COMMIT QUALITY GATES"]
        FMT["ruff format<br/>━━━━━━━━━━<br/>Auto-fixes Python style<br/>Reads + Writes src/"]
        LINT["ruff check --fix<br/>━━━━━━━━━━<br/>Lints + auto-fixes<br/>E, F, I, UP, TID251"]
        MYPY["mypy src/<br/>━━━━━━━━━━<br/>Static type analysis<br/>--ignore-missing-imports"]
        UVLOCK["uv lock --check<br/>━━━━━━━━━━<br/>Lock file integrity<br/>Triggered on pyproject.toml"]
        GITLEAKS["gitleaks v8.30.0<br/>━━━━━━━━━━<br/>Secret scanning<br/>Reads git history"]
    end

    subgraph Build ["BUILD TOOLING"]
        PYPROJECT["pyproject.toml<br/>━━━━━━━━━━<br/>hatchling backend<br/>version = 0.6.7"]
        TASKFILE["Taskfile.yml<br/>━━━━━━━━━━<br/>task test-all · test-check<br/>pytest -n 4 -m 'not smoke'"]
        UVTOOL["uv package manager<br/>━━━━━━━━━━<br/>Deps: anyio, fastmcp, httpx<br/>Dev: pytest, ruff, mypy"]
    end

    subgraph Testing ["TEST FRAMEWORK"]
        TESTRUN["pytest + xdist<br/>━━━━━━━━━━<br/>-n 4 parallel workers<br/>asyncio_mode=auto"]
        INFRA["● tests/infra/<br/>test_release_workflows.py<br/>━━━━━━━━━━<br/>51 tests: version-bump,<br/>patch-bump-integration,<br/>release workflow contracts"]
        ILCHECK["import-linter<br/>━━━━━━━━━━<br/>IL-001 to IL-007<br/>L0→L3 layering contracts"]
    end

    subgraph CIWorkflows ["GITHUB ACTIONS WORKFLOWS"]
        PATCHBUMP["● patch-bump-integration.yml<br/>━━━━━━━━━━<br/>Trigger: PR closed → integration<br/>concurrency: patch-bump-integration<br/>cancel-in-progress: false"]
        VERSIONBUMP["version-bump.yml<br/>━━━━━━━━━━<br/>Trigger: PR closed → stable<br/>Minor version bump"]
        RELEASE["release.yml<br/>━━━━━━━━━━<br/>Trigger: PR closed → stable<br/>Annotated tag + GitHub Release"]
    end

    EP["autoskillit CLI<br/>━━━━━━━━━━<br/>autoskillit.cli:main<br/>serve · init · doctor · cook"]

    SRC --> PYPROJECT
    TESTS --> PYPROJECT
    WORKFLOWS --> PYPROJECT
    PYPROJECT --> UVTOOL
    PYPROJECT --> TASKFILE

    SRC --> FMT
    FMT --> LINT
    LINT --> MYPY
    MYPY --> UVLOCK
    UVLOCK --> GITLEAKS

    TASKFILE --> TESTRUN
    TESTRUN --> INFRA
    TESTRUN --> ILCHECK

    INFRA -->|"validates shape of"| PATCHBUMP
    INFRA -->|"validates shape of"| VERSIONBUMP
    INFRA -->|"validates shape of"| RELEASE

    PYPROJECT --> EP

    class SRC,TESTS,WORKFLOWS cli;
    class PYPROJECT,UVTOOL phase;
    class TASKFILE phase;
    class FMT,LINT,MYPY,UVLOCK,GITLEAKS detector;
    class TESTRUN,INFRA,ILCHECK handler;
    class PATCHBUMP,VERSIONBUMP,RELEASE stateNode;
    class EP output;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | Structure | Project directories and source layout |
| Purple | Build | Build config, task runner, package manager |
| Red | Quality Gates | Pre-commit hooks (ruff, mypy, gitleaks) |
| Orange | Testing | Test runner, infra test contracts, import-linter |
| Teal | CI Workflows | GitHub Actions workflow definitions |
| Dark Teal | Entry Point | `autoskillit` CLI binary |

### Concurrency Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 40, 'rankSpacing': 55, 'curve': 'basis'}}}%%
flowchart TB
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;

    subgraph MergeQueue ["MERGE QUEUE BATCH — simultaneous triggers"]
        direction LR
        T1["PR #A closed<br/>━━━━━━━━━━<br/>pull_request[closed]<br/>→ integration"]
        T2["PR #B closed<br/>━━━━━━━━━━<br/>pull_request[closed]<br/>→ integration"]
        TN["PR #N closed<br/>━━━━━━━━━━<br/>pull_request[closed]<br/>→ integration"]
    end

    GATE["● concurrency gate<br/>━━━━━━━━━━<br/>group: patch-bump-integration<br/>cancel-in-progress: false<br/>Serializes all queued runs"]

    subgraph RunA ["RUN #A — executes first"]
        direction TB
        CA["Checkout integration<br/>━━━━━━━━━━<br/>ref: integration, fetch-depth: 0<br/>Reads current HEAD"]
        VA["Compute patch version<br/>━━━━━━━━━━<br/>PATCH + 1 from pyproject.toml"]
        UA["Update files<br/>━━━━━━━━━━<br/>pyproject.toml + plugin.json<br/>Regenerate uv.lock"]
        PA["git push origin integration<br/>━━━━━━━━━━<br/>Fast-forward to X.Y.(P+1)<br/>Releases concurrency slot"]
    end

    subgraph RunB ["RUN #B — waits, then executes"]
        direction TB
        CB["Checkout integration<br/>━━━━━━━━━━<br/>ref: integration, fetch-depth: 0<br/>NOW sees Run A's push"]
        VB["Compute patch version<br/>━━━━━━━━━━<br/>PATCH + 1 from updated HEAD"]
        UB["Update files<br/>━━━━━━━━━━<br/>pyproject.toml + plugin.json<br/>Regenerate uv.lock"]
        PB["git push origin integration<br/>━━━━━━━━━━<br/>Fast-forward to X.Y.(P+2)<br/>Releases concurrency slot"]
    end

    RESULT["Each PR gets its own bump<br/>━━━━━━━━━━<br/>N PRs → N sequential pushes<br/>No race · No skipped bumps"]

    T1 --> GATE
    T2 --> GATE
    TN --> GATE

    GATE -->|"slot available"| CA
    CA --> VA --> UA --> PA

    PA -.->|"slot released<br/>Run B acquires"| GATE
    GATE -->|"slot available"| CB
    CB --> VB --> UB --> PB

    PB --> RESULT

    class T1,T2,TN terminal;
    class GATE newComponent;
    class CA,CB phase;
    class VA,VB phase;
    class UA,UB handler;
    class PA,PB output;
    class RESULT stateNode;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | Triggers | Simultaneous `pull_request[closed]` events from
merge queue |
| Green | ● Concurrency Gate | New serialization barrier (`concurrency`
block) |
| Purple | Checkout / Version | Sequential per-run read operations |
| Orange | File Updates | `pyproject.toml`, `plugin.json`, `uv.lock`
writes |
| Dark Teal | Push | Fast-forward git push releasing the concurrency
slot |
| Teal | Result | Guaranteed sequential ordering outcome |

Closes #529

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/impl-20260326-210820-364027/.autoskillit/temp/make-plan/patch_bump_integration_races_plan_2026-03-26_210820.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
…rite-Back (#531)

## Summary

The root architectural weakness was that session identity resolution was
fragmented across
three independent data sources (stdout `type=result` record, stdout
`type=system` record,
Channel B JSONL filename) but the merge of those sources was deferred to
`run_headless_core`
after `SkillResult` was already built — and the resolved value was never
written back.
Downstream callers, diagnostic lookups, and GitHub bug reports all
received `session_id=""`
on stale and timeout paths.

Two compound fixes provide full immunity: (1) session ID resolution is
moved to the transport
boundary with a single `_resolve_session_id` helper populating
`SubprocessResult.session_id`
from all race signals; (2) `RetryReason.STALE` is introduced to
distinguish transient stale
failures from context-exhaustion, with sous-chef routing them to the
`retries` counter rather
than `on_context_limit`.

## Architecture Impact

### Process Flow Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 40, 'rankSpacing': 52, 'curve': 'basis'}}}%%
flowchart TB
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;

    START([run_skill invocation])

    subgraph Transport ["Transport Layer — _process_race.py"]
        direction TB
        SYS["stdout type=system<br/>━━━━━━━━━━<br/>→ acc.stdout_session_id"]
        JSONL["JSONL filename stem<br/>━━━━━━━━━━<br/>→ acc.channel_b_session_id"]
        RES["stdout type=result<br/>━━━━━━━━━━<br/>→ session.session_id<br/>(parse_session_result)"]
    end

    subgraph Resolution ["● Resolution Boundary — process.py"]
        direction TB
        RESOLVE["● _resolve_session_id<br/>━━━━━━━━━━<br/>stdout_session_id OR<br/>channel_b_session_id OR ''"]
        SUB["● SubprocessResult<br/>━━━━━━━━━━<br/>.session_id = resolved<br/>.channel_b_session_id kept<br/>.termination = STALE|TIMED_OUT|…"]
    end

    subgraph Build ["● _build_skill_result — headless.py"]
        direction TB
        TERM_CHK{"termination<br/>type?"}
        STALE_PATH["STALE termination<br/>━━━━━━━━━━<br/>try recovery<br/>parse stale_session stdout"]
        STALE_REC{"recovery<br/>succeeded?"}
        STALE_OK["stale recovered<br/>━━━━━━━━━━<br/>session_id=<br/>stale_session.session_id<br/>OR result.session_id"]
        STALE_FAIL["● stale failure<br/>━━━━━━━━━━<br/>session_id=result.session_id<br/>retry_reason=RetryReason.STALE<br/>needs_retry=True"]
        TIMEOUT_PATH["TIMED_OUT<br/>━━━━━━━━━━<br/>synthetic ClaudeSessionResult<br/>session_id=result.session_id"]
        NORMAL_PATH["NATURAL_EXIT / other<br/>━━━━━━━━━━<br/>parse_session_result(stdout)<br/>session_id=<br/>session.session_id OR result.session_id"]
    end

    subgraph SkillOut ["● SkillResult — all paths resolved"]
        direction TB
        SR["● SkillResult<br/>━━━━━━━━━━<br/>.session_id = UUID (never '')<br/>.retry_reason = STALE|RESUME|NONE…"]
    end

    subgraph Core ["● run_headless_core — headless.py"]
        direction TB
        FLUSH["● flush_session_log<br/>━━━━━━━━━━<br/>session_id=skill_result.session_id<br/>(late merge removed)"]
    end

    subgraph Routing ["● Sous-Chef Routing — sous-chef/SKILL.md"]
        direction TB
        RR_CHK{"retry_reason?"}
        STALE_RT["● retry_reason=stale<br/>━━━━━━━━━━<br/>decrement retries counter<br/>re-execute same step<br/>NOT on_context_limit"]
        RESUME_RT["retry_reason=resume<br/>━━━━━━━━━━<br/>follow on_context_limit<br/>or on_failure"]
        RETRY_CHK{"retries<br/>remain?"}
        RE_EXEC["re-execute step"]
        ON_FAIL["on_failure"]
    end

    subgraph Downstream ["Storage & Downstream — all correct"]
        direction TB
        LOG["flush_session_log<br/>━━━━━━━━━━<br/>dir named by real UUID<br/>(coherent with SkillResult)"]
        MCP["MCP JSON response<br/>━━━━━━━━━━<br/>session_id: real UUID"]
        DIAG["_read_session_diagnostics<br/>━━━━━━━━━━<br/>lookup succeeds<br/>(no '' guard triggered)"]
    end

    DONE([SkillResult returned to caller])

    START --> SYS & JSONL & RES
    SYS --> RESOLVE
    JSONL --> RESOLVE
    RESOLVE --> SUB
    RES --> TERM_CHK
    SUB --> TERM_CHK

    TERM_CHK -->|"STALE"| STALE_PATH
    TERM_CHK -->|"TIMED_OUT"| TIMEOUT_PATH
    TERM_CHK -->|"NATURAL_EXIT / other"| NORMAL_PATH

    STALE_PATH --> STALE_REC
    STALE_REC -->|"yes"| STALE_OK
    STALE_REC -->|"no"| STALE_FAIL
    STALE_OK --> SR
    STALE_FAIL --> SR
    TIMEOUT_PATH --> SR
    NORMAL_PATH --> SR

    SR --> FLUSH
    FLUSH --> RR_CHK
    SR --> LOG & MCP & DIAG
    FLUSH --> LOG

    RR_CHK -->|"stale"| STALE_RT
    RR_CHK -->|"resume / drain_race"| RESUME_RT
    STALE_RT --> RETRY_CHK
    RETRY_CHK -->|"yes"| RE_EXEC
    RETRY_CHK -->|"no"| ON_FAIL
    RE_EXEC -.->|"retry loop"| START
    RESUME_RT --> ON_FAIL

    LOG --> DONE
    MCP --> DONE
    DIAG --> DONE
    ON_FAIL --> DONE

    class START,DONE terminal;
    class SYS,JSONL,RES cli;
    class RESOLVE newComponent;
    class SUB stateNode;
    class TERM_CHK,STALE_REC,RR_CHK,RETRY_CHK detector;
    class STALE_PATH,TIMEOUT_PATH,NORMAL_PATH handler;
    class STALE_OK,STALE_FAIL,FLUSH phase;
    class SR,RE_EXEC stateNode;
    class STALE_RT newComponent;
    class RESUME_RT,ON_FAIL handler;
    class LOG,MCP,DIAG output;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | Terminal | Start and end points |
| Dark Blue (entry) | CLI | Subprocess stdout/JSONL sources |
| Bright Green | New/Modified | `● _resolve_session_id`,
`RetryReason.STALE` routing |
| Teal | State | `SubprocessResult`, `SkillResult`, retry loop |
| Purple | Phase | `_build_skill_result` output paths,
`flush_session_log` |
| Orange | Handler | Termination path handlers, resume/on_failure
routing |
| Red | Decision | `termination type?`, `recovery succeeded?`, routing
decisions |
| Dark Teal | Output | Downstream consumers: logs, MCP response,
diagnostics |

Closes #527

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/remediation-20260326-190411-505931/.autoskillit/temp/rectify/rectify_session_id_resolution_2026-03-26_190411.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
…534)

## Summary

`run_stale_check()` spawns `subprocess.run(["autoskillit", "install"],
check=False)` at two sites (binary-update path and hook-drift path)
without injecting any re-entry guard into the child's environment.
Because `main()` unconditionally calls `run_stale_check()` for every
non-`serve` command, the child process re-enters the function, measures
the same un-synced drift, and re-prompts the user. If the user keeps
answering Y, the loop is unbounded.

The fix introduces `AUTOSKILLIT_SKIP_STALE_CHECK` as a subprocess
re-entry sentinel, injects it into the env at both call sites, extends
the guard check in `run_stale_check()`, registers the var in
`AUTOSKILLIT_PRIVATE_ENV_VARS` for automatic test stripping, and adds a
new AST-based structural contract test (`SPEC-1`) that prevents the bug
class from ever being silently re-introduced.

## Architecture Impact

### Process Flow Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 40, 'rankSpacing': 50, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;

    START([User: autoskillit install])
    END([COMPLETE])

    subgraph Preamble ["main() Preamble — app.py"]
        direction TB
        MAIN["main()<br/>━━━━━━━━━━<br/>first_arg != 'serve'"]
        STALECALL["run_stale_check()"]
    end

    subgraph GuardLayer ["● Guard Layer — _stale_check.py:169"]
        direction TB
        GUARD{"● Guard Check<br/>━━━━━━━━━━<br/>CLAUDECODE set?<br/>★ SKIP_STALE_CHECK set?<br/>stdin/stdout not TTY?"}
        EARLYRET(["return (silent)"])
    end

    subgraph EnvPrep ["★ Env Preparation — _stale_check.py:177"]
        direction TB
        SKIP_ENV["★ _skip_env<br/>━━━━━━━━━━<br/>{**os.environ,<br/>AUTOSKILLIT_SKIP_STALE_CHECK: '1'}<br/>Built once, shared by all spawns"]
    end

    subgraph BinaryCheck ["Binary Version Check — _stale_check.py:190"]
        direction TB
        BCHECK{"latest > current?<br/>━━━━━━━━━━<br/>and not dismissed?"}
        BINPROMPT["prompt: Update now? [Y/n]"]
        BDISMISS["write dismiss state<br/>━━━━━━━━━━<br/>state['binary'] = {...}"]
    end

    subgraph HookCheck ["Hook Drift Check — _stale_check.py:222"]
        direction TB
        HCHECK{"n_drift > 0?<br/>━━━━━━━━━━<br/>and not dismissed?"}
        HOOKPROMPT["prompt: Sync hooks? [Y/n]"]
        HDISMISS["write dismiss state<br/>━━━━━━━━━━<br/>state['hooks'] = {...}"]
    end

    subgraph SpawnLayer ["★ Subprocess Spawn with Guard — _stale_check.py:200,213,235"]
        direction TB
        DEVCHECK{"dev_mode?"}
        SPAWN_DEV["subprocess.run(<br/>  ['uv', 'tool', 'install', '--force', ...],<br/>  ● env=_skip_env<br/>)"]
        SPAWN_UPG["subprocess.run(<br/>  ['uv', 'tool', 'upgrade', 'autoskillit'],<br/>  ● env=_skip_env<br/>)"]
        SPAWN_INST["● subprocess.run(<br/>  ['autoskillit', 'install'],<br/>  ★ env=_skip_env<br/>)"]
    end

    subgraph ChildProcess ["Child: autoskillit install — re-entry blocked"]
        direction TB
        CHILD_MAIN["main() in child<br/>━━━━━━━━━━<br/>first_arg == 'install'"]
        CHILD_STALE["run_stale_check()"]
        CHILD_GUARD{"★ Guard fires<br/>━━━━━━━━━━<br/>SKIP_STALE_CHECK=1<br/>→ return immediately"}
        CHILD_APP["app() → install<br/>━━━━━━━━━━<br/>hooks sync proceeds"]
    end

    %% FLOW %%
    START --> MAIN
    MAIN --> STALECALL
    STALECALL --> GUARD
    GUARD -->|"guard var set"| EARLYRET
    GUARD -->|"interactive TTY"| SKIP_ENV
    SKIP_ENV --> BCHECK
    BCHECK -->|"no / dismissed"| HCHECK
    BCHECK -->|"yes"| BINPROMPT
    BINPROMPT -->|"N / dismiss"| BDISMISS
    BDISMISS --> HCHECK
    BINPROMPT -->|"Y"| DEVCHECK
    DEVCHECK -->|"dev mode"| SPAWN_DEV
    DEVCHECK -->|"normal"| SPAWN_UPG
    SPAWN_DEV --> SPAWN_INST
    SPAWN_UPG --> SPAWN_INST
    SPAWN_INST --> CHILD_MAIN
    CHILD_MAIN --> CHILD_STALE
    CHILD_STALE --> CHILD_GUARD
    CHILD_GUARD -->|"SKIP_STALE_CHECK=1"| CHILD_APP
    CHILD_APP --> END
    HCHECK -->|"no / dismissed"| END
    HCHECK -->|"yes"| HOOKPROMPT
    HOOKPROMPT -->|"N / dismiss"| HDISMISS
    HDISMISS --> END
    HOOKPROMPT -->|"Y"| SPAWN_INST

    %% CLASS ASSIGNMENTS %%
    class START,END,EARLYRET terminal;
    class MAIN,STALECALL,CHILD_MAIN,CHILD_APP handler;
    class GUARD,BCHECK,HCHECK,DEVCHECK stateNode;
    class CHILD_GUARD detector;
    class BINPROMPT,HOOKPROMPT phase;
    class SKIP_ENV,SPAWN_INST,CHILD_STALE newComponent;
    class SPAWN_DEV,SPAWN_UPG handler;
    class BDISMISS,HDISMISS phase;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | Terminal | Start, complete, and silent-return states |
| Teal | State | Decision points and guard checks |
| Orange | Handler | Process nodes (main, subprocess spawns, child app)
|
| Purple | Phase | Interactive prompt and dismiss-write nodes |
| Green | New/Modified | New or modified components (★ new, ● modified)
|
| Red | Detector | Child re-entry guard — blocks recursive loop |

### Development Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;

    subgraph Constants ["● Core Constants — _type_constants.py"]
        direction TB
        PRIVATE_VARS["● AUTOSKILLIT_PRIVATE_ENV_VARS<br/>━━━━━━━━━━<br/>frozenset{<br/>  'AUTOSKILLIT_HEADLESS',<br/>  ★ 'AUTOSKILLIT_SKIP_STALE_CHECK'<br/>}"]
    end

    subgraph Fixtures ["● Test Fixtures — tests/conftest.py"]
        direction TB
        HEADLESS_FIX["_clear_headless_env<br/>━━━━━━━━━━<br/>autouse: delenv AUTOSKILLIT_HEADLESS<br/>before every test"]
        SKIP_FIX["★ _clear_skip_stale_check_env<br/>━━━━━━━━━━<br/>autouse: delenv AUTOSKILLIT_SKIP_STALE_CHECK<br/>before every test<br/>prevents cross-test contamination"]
    end

    subgraph SanitizedEnv ["Test Subprocess Isolation — execution/testing.py"]
        direction TB
        BUILD_ENV["build_sanitized_env()<br/>━━━━━━━━━━<br/>strips all AUTOSKILLIT_PRIVATE_ENV_VARS<br/>from subprocess env before pytest runs"]
    end

    subgraph UnitTests ["● Unit Tests — tests/cli/test_stale_check.py"]
        direction TB
        SC14["★ SC-14<br/>━━━━━━━━━━<br/>binary update Y-path:<br/>both subprocess calls receive<br/>AUTOSKILLIT_SKIP_STALE_CHECK in env"]
        SC15["★ SC-15<br/>━━━━━━━━━━<br/>hook drift Y-path:<br/>subprocess call receives<br/>AUTOSKILLIT_SKIP_STALE_CHECK=1"]
        SC16["★ SC-16<br/>━━━━━━━━━━<br/>re-entry guard:<br/>run_stale_check() returns<br/>immediately when env var set"]
    end

    subgraph ContractTest ["★ Structural Contract — tests/cli/test_subprocess_env_contracts.py"]
        direction TB
        SPEC1["★ SPEC-1<br/>━━━━━━━━━━<br/>AST walker scans cli/**/*.py<br/>asserts every subprocess.run(['autoskillit',...])<br/>has env= kwarg AND guard string in file<br/>CI fails if future call omits guard"]
        AST_WALK["ast.parse + ast.walk<br/>━━━━━━━━━━<br/>collects all subprocess.run / Popen calls<br/>with 'autoskillit' as first list arg<br/>checks env= kwarg + guard string in file"]
    end

    subgraph QualityGate ["Quality Gate — task test-check"]
        direction TB
        RUNNER["pytest -n 4 --dist worksteal<br/>━━━━━━━━━━<br/>parallel execution<br/>xdist-safe fixtures"]
    end

    %% FLOW %%
    PRIVATE_VARS -->|"read by"| BUILD_ENV
    PRIVATE_VARS -->|"drives autouse strip"| SKIP_FIX
    HEADLESS_FIX -->|"autouse: per-test"| RUNNER
    SKIP_FIX -->|"autouse: per-test"| RUNNER
    BUILD_ENV -->|"sanitizes env for"| RUNNER
    SC14 --> RUNNER
    SC15 --> RUNNER
    SC16 --> RUNNER
    SPEC1 --> AST_WALK
    AST_WALK --> RUNNER

    %% CLASS ASSIGNMENTS %%
    class PRIVATE_VARS newComponent;
    class HEADLESS_FIX phase;
    class SKIP_FIX newComponent;
    class BUILD_ENV handler;
    class SC14,SC15,SC16 newComponent;
    class SPEC1,AST_WALK newComponent;
    class RUNNER detector;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Green | New/Modified | New or modified components (★ new, ● modified)
|
| Purple | Phase | Existing autouse fixtures |
| Orange | Handler | Environment sanitization utility |
| Red | Quality Gate | Test runner (quality enforcement) |

Closes #532

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/remediation-20260326-215123-408531/.autoskillit/temp/rectify/rectify_stale-hook-infinite-loop_2026-03-26_000000.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit
## Summary

`terminal_guard()` was designed as an **exit-only cleanup safety net** —
save termios on entry,
restore termios and emit VT100 cleanup sequences on exit. PR #521 broke
this contract by adding
an entry-side `\033[?1049h` (DECSET 1049, "smcup") emission before the
subprocess yield, causing
a scrollbar regression in Claude Code: Ink TUI emits its own `?1049h` on
startup and since DECSET
1049 is a boolean toggle with no nesting counter, the second emission
overwrites the DECSC cursor
save point, corrupting Ink's viewport height calculation.

The fix removes the 6-line entry block, updates the docstring to codify
the exit-only contract,
removes the test that validated the regression, and adds two
complementary guards: a mock-based
behavioral test asserting `?1049h` is NOT emitted before yield, and a
source-scanning structural
test that fails immediately if any future PR adds `?1049h` back to
`_terminal.py`.

## Requirements

- Fix MUST work on macOS (Terminal.app, iTerm2) in addition to Linux
  (native, WSL2)
- The exit-side safety net (`\033[?1049l` in finally block) must be
  preserved
- Existing test REQ-TEST-002 (exit sequence) and REQ-TEST-003 (non-TTY
  no-op) must continue to pass

## Architecture Impact

### Process Flow Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 40, 'rankSpacing': 50, 'curve': 'basis'}}}%%
flowchart TB
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;

    START([CLI: cook / order / stale_check])
    DONE([Terminal Restored — Clean Exit])

    subgraph GuardEntry ["● terminal_guard() — Entry (modified: exit-only)"]
        direction TB
        TTYCheck{"stdin.isatty()?<br/>━━━━━━━━━━<br/>Real TTY vs pipe/CI"}
        SaveTermios["● Save termios attrs<br/>━━━━━━━━━━<br/>tcgetattr(fd)<br/>fd = stdin.fileno()"]
        NoopPath["no-op path<br/>━━━━━━━━━━<br/>fd = None, old_settings = None<br/>CI / pipe / headless safe"]
    end

    subgraph SubProcess ["Claude Code Ink TUI — owns alt-screen entry"]
        direction TB
        InkSmcup["Ink emits smcup (?1049h)<br/>━━━━━━━━━━<br/>Enters alt-screen from primary<br/>DECSC: saves cursor at pos A"]
        InkRender["TUI renders correctly<br/>━━━━━━━━━━<br/>Full viewport height<br/>Scrollbar visible — scroll works"]
        InkRmcup["Ink emits rmcup (?1049l)<br/>━━━━━━━━━━<br/>Exits alt-screen to primary<br/>Cursor restored to pos A"]
    end

    subgraph GuardExit ["terminal_guard() — finally block (unchanged)"]
        direction TB
        FdCheck{"fd is not None?<br/>━━━━━━━━━━<br/>TTY path vs no-op path"}
        RestoreTermios["Restore termios attrs<br/>━━━━━━━━━━<br/>tcsetattr(TCSAFLUSH)<br/>fallback: stty sane"]
        SafetyNet["Emit VT100 safety net<br/>━━━━━━━━━━<br/>?1049l ?1l > [0m ?25h<br/>no-op if Ink exited cleanly"]
    end

    subgraph Contracts ["● Tests — structural + behavioral contracts"]
        direction LR
        BehavTest["● test_does_not_emit_entry_alt_screen<br/>━━━━━━━━━━<br/>Assert ?1049h NOT in pre-yield writes<br/>test_terminal.py"]
        SrcTest["● test_terminal_guard_never_emits_smcup<br/>━━━━━━━━━━<br/>Source scan: ?1049h absent from _terminal.py<br/>test_interactive_subprocess_contracts.py"]
    end

    START --> TTYCheck
    TTYCheck -->|"isatty=True"| SaveTermios
    TTYCheck -->|"isatty=False"| NoopPath
    SaveTermios --> InkSmcup
    NoopPath --> InkSmcup
    InkSmcup --> InkRender
    InkRender --> InkRmcup
    InkRmcup --> FdCheck
    FdCheck -->|"fd set"| RestoreTermios
    FdCheck -->|"fd=None"| DONE
    RestoreTermios --> SafetyNet
    SafetyNet --> DONE

    BehavTest -..->|"guards against"| SaveTermios
    SrcTest -..->|"guards against"| SaveTermios

    class START,DONE terminal;
    class TTYCheck,FdCheck stateNode;
    class SaveTermios,RestoreTermios,SafetyNet,NoopPath handler;
    class InkSmcup,InkRender,InkRmcup phase;
    class BehavTest,SrcTest newComponent;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | Terminal | CLI entry points and clean exit state |
| Teal | State | Decision points — isatty check, fd guard |
| Orange | Handler | terminal_guard() processing nodes (● modified) |
| Purple | Phase | Claude Code Ink TUI subprocess nodes |
| Green | New Component | ● Modified test contracts (behavioral +
structural) |

Closes #533

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/remediation-20260326-221329-908711/.autoskillit/temp/rectify/rectify_terminal_guard_exit_only_contract_2026-03-26_222900.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
…Enforcement (#535)

## Summary

Three related bugs cluster around the same structural weakness:
contracts that exist semantically but are not enforced structurally at
the boundary where they matter.

`run_headless_core` computes `effective_session_id` as a Channel B
fallback for `SkillResult.session_id`, correctly passes it to
`flush_session_log`, but never writes it back to the returned
`SkillResult`. Callers (including `tools_github.py`) receive
`session_id=""` on all stale and empty-stdout timeout paths, even when
Channel B discovered the real UUID from the JSONL filename. The fix
moves resolution to construction time via a new `_resolve_session_id`
helper and eliminates the post-hoc enrichment anti-pattern entirely.

A secondary fix corrects `_prompts.py:74` which instructs Claude to call
`open_kitchen('{recipe_name}')` in positional form — now enforced to
keyword form `open_kitchen(name=...)`. The sous-chef routing table is
also extended to a 2D key `(retry_reason, subtype)` so stale sessions
(watchdog kills) are re-executed rather than routed to
`on_context_limit`.

## Architecture Impact

### State Lifecycle Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000;
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;

    subgraph Sources ["INIT_ONLY SOURCE FIELDS"]
        direction LR
        ChannelA["ClaudeSessionResult<br/>━━━━━━━━━━<br/>.session_id (str)<br/>stdout-parsed UUID<br/>(Channel A — preferred)"]
        ChannelB["SubprocessResult<br/>━━━━━━━━━━<br/>.channel_b_session_id (str)<br/>JSONL filename stem<br/>(Channel B — fallback)"]
    end

    subgraph Gate ["★ RESOLUTION GATE — _resolve_session_id (NEW)"]
        direction TB
        Resolver["★ _resolve_session_id(session, result)<br/>━━━━━━━━━━<br/>if session and session.session_id:<br/>    return session.session_id<br/>return result.channel_b_session_id<br/>Single source of truth for priority rule"]
    end

    subgraph BuildSites ["● CONSTRUCTION SITES — _build_skill_result (MODIFIED)"]
        direction TB
        StaleSuccess["Stale recovery success path<br/>━━━━━━━━━━<br/>session_id=stale_session.session_id<br/>(stdout parse wins; no fallback needed)"]
        StaleFailure["● Stale failure path<br/>━━━━━━━━━━<br/>session_id=_resolve_session_id(None, result)<br/>NOW uses Channel B fallback"]
        TimeoutPath["● TIMED_OUT + empty-stdout path<br/>━━━━━━━━━━<br/>ClaudeSessionResult(session_id=<br/>    result.channel_b_session_id)<br/>Seeds session for normal constructor"]
        NormalPath["Normal path<br/>━━━━━━━━━━<br/>session_id=session.session_id<br/>(unchanged — already correct)"]
    end

    AntiPattern["effective_session_id [REMOVED]<br/>━━━━━━━━━━<br/>was: local var computed post-construction<br/>was: used for flush_session_log only<br/>was: NEVER written back to SkillResult"]

    subgraph Contract ["● INIT_ONLY CONTRACT — SkillResult.session_id (ENFORCED)"]
        direction TB
        SkillResultNode["● SkillResult<br/>━━━━━━━━━━<br/>.session_id: str  ← INIT_ONLY<br/>Set once at _build_skill_result<br/>Never mutated post-return<br/>Invariant: non-empty when Channel B has UUID"]
    end

    subgraph Consumers ["DOWNSTREAM CONSUMERS"]
        direction LR
        FlushLog["flush_session_log<br/>━━━━━━━━━━<br/>session_id=skill_result.session_id<br/>(previously: effective_session_id)"]
        ToolsGithub["tools_github.py<br/>━━━━━━━━━━<br/>propagated to caller<br/>& _read_session_diagnostics"]
        DebugLog["debug log<br/>━━━━━━━━━━<br/>session_id now accurate<br/>on all termination paths"]
    end

    ChannelA --> Resolver
    ChannelB --> Resolver
    Resolver --> StaleFailure
    Resolver --> TimeoutPath
    StaleSuccess --> SkillResultNode
    StaleFailure --> SkillResultNode
    TimeoutPath --> SkillResultNode
    NormalPath --> SkillResultNode
    AntiPattern -.->|"eliminated"| SkillResultNode
    SkillResultNode --> FlushLog
    SkillResultNode --> ToolsGithub
    SkillResultNode --> DebugLog

    class ChannelA,ChannelB cli;
    class Resolver newComponent;
    class StaleSuccess,NormalPath phase;
    class StaleFailure,TimeoutPath handler;
    class SkillResultNode stateNode;
    class FlushLog,ToolsGithub,DebugLog output;
    class AntiPattern gap;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | Source Fields | `ClaudeSessionResult.session_id` (Channel
A) and `SubprocessResult.channel_b_session_id` (Channel B) |
| Green | New Component | `★ _resolve_session_id` — new resolution
helper enforcing priority rule |
| Purple | Unchanged Path | Stale recovery success and normal paths
(unmodified) |
| Orange | Modified Path | `● Stale failure` and `● TIMED_OUT` paths now
use Channel B fallback |
| Teal | Contract Field | `● SkillResult.session_id` — INIT_ONLY field
with enforced contract |
| Dark Teal | Consumers | Downstream callers that now receive accurate
session UUID |
| Yellow/Orange | Eliminated | `effective_session_id` local variable —
anti-pattern removed |

### Process Flow Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 40, 'rankSpacing': 50, 'curve': 'basis'}}}%%
flowchart TB
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000;

    START([run_skill invoked])

    subgraph Subprocess ["SUBPROCESS EXECUTION"]
        direction TB
        Launch["run_headless_core<br/>━━━━━━━━━━<br/>Launch Claude subprocess<br/>Channel A (stdout) + Channel B (JSONL)"]
        RaceResolve["resolve_termination<br/>━━━━━━━━━━<br/>RaceAccumulator signals<br/>→ TerminationReason"]
        TermDecision{"Termination?<br/>━━━━━━━━━━<br/>STALE / TIMED_OUT / NATURAL"}
    end

    subgraph BuildResult ["● _build_skill_result (MODIFIED — session_id backfill)"]
        direction TB
        StaleRecovery{"● STALE<br/>━━━━━━━━━━<br/>stdout has valid result?"}
        StaleSuccess["Recovered from stale<br/>━━━━━━━━━━<br/>success=True<br/>retry_reason=NONE<br/>subtype=recovered_from_stale"]
        StaleFailPath["● Stale failure<br/>━━━━━━━━━━<br/>success=False<br/>needs_retry=True<br/>retry_reason=RESUME<br/>subtype=stale<br/>session_id=_resolve_session_id(None, result)"]
        TimeoutBranch["● TIMED_OUT<br/>━━━━━━━━━━<br/>empty stdout? → bare ClaudeSessionResult(<br/>    session_id=result.channel_b_session_id)<br/>non-empty? → parse + force subtype=TIMEOUT"]
        NormalBranch["Normal completion<br/>━━━━━━━━━━<br/>parse_session_result(stdout)<br/>→ ClaudeSessionResult"]
        ComputeOutcome["_compute_outcome<br/>━━━━━━━━━━<br/>SUCCEEDED / RETRIABLE / FAILED<br/>(recovery steps applied first)"]
    end

    subgraph Gates ["POST-OUTCOME GATES"]
        direction TB
        PathGate{"path_contamination?"}
        ContractGate{"CONTRACT_RECOVERY?<br/>━━━━━━━━━━<br/>write evidence + adjudicated_failure"}
        ZeroWriteGate{"zero_writes?<br/>━━━━━━━━━━<br/>success=True but write_count=0"}
        BudgetGuard["Budget guard<br/>━━━━━━━━━━<br/>retries exhausted?<br/>→ flip needs_retry=False<br/>   retry_reason=BUDGET_EXHAUSTED"]
    end

    SkillResultOut["SkillResult<br/>━━━━━━━━━━<br/>(success, needs_retry,<br/>retry_reason, subtype,<br/>session_id — now accurate)"]

    subgraph SousChef ["● SOUS-CHEF ROUTING (MODIFIED — 2D key: retry_reason × subtype)"]
        direction TB
        NeedsRetryDecision{"needs_retry=True?"}
        RetryReasonDecision{"● retry_reason?<br/>━━━━━━━━━━<br/>2D routing key"}
        ResumeStale["● resume + stale<br/>━━━━━━━━━━<br/>Watchdog kill (NOT context limit)<br/>→ RE-EXECUTE step<br/>   (decrement retries)"]
        ResumeContextLimit["resume + !stale<br/>━━━━━━━━━━<br/>Context limit hit<br/>→ on_context_limit<br/>   (or on_failure if none)"]
        DrainRace["drain_race<br/>━━━━━━━━━━<br/>→ on_context_limit<br/>   (or on_failure if none)"]
        OtherReasons["empty_output / path_contamination<br/>/ early_stop / zero_writes<br/>━━━━━━━━━━<br/>→ on_failure (never context limit)"]
        RetryExhausted{"Retries exhausted?"}
    end

    COMPLETE([COMPLETE — success])
    CONTEXT_LIMIT([on_context_limit route])
    FAILURE([on_failure route])
    EXHAUSTED([on_exhausted route])

    START --> Launch
    Launch --> RaceResolve
    RaceResolve --> TermDecision
    TermDecision -->|"STALE"| StaleRecovery
    TermDecision -->|"TIMED_OUT"| TimeoutBranch
    TermDecision -->|"NATURAL_EXIT"| NormalBranch
    StaleRecovery -->|"recovery OK"| StaleSuccess
    StaleRecovery -->|"no recovery"| StaleFailPath
    StaleSuccess --> SkillResultOut
    StaleFailPath --> BudgetGuard
    TimeoutBranch --> ComputeOutcome
    NormalBranch --> ComputeOutcome
    ComputeOutcome --> PathGate
    PathGate -->|"yes"| BudgetGuard
    PathGate -->|"no"| ContractGate
    ContractGate -->|"yes"| BudgetGuard
    ContractGate -->|"no"| ZeroWriteGate
    ZeroWriteGate -->|"yes"| BudgetGuard
    ZeroWriteGate -->|"no"| SkillResultOut
    BudgetGuard --> SkillResultOut
    SkillResultOut --> NeedsRetryDecision
    NeedsRetryDecision -->|"no"| COMPLETE
    NeedsRetryDecision -->|"yes"| RetryReasonDecision
    RetryReasonDecision -->|"resume"| ResumeStale
    RetryReasonDecision -->|"resume + !stale"| ResumeContextLimit
    RetryReasonDecision -->|"drain_race"| DrainRace
    RetryReasonDecision -->|"other"| OtherReasons
    ResumeStale --> RetryExhausted
    RetryExhausted -->|"no — re-execute"| Launch
    RetryExhausted -->|"yes"| EXHAUSTED
    ResumeContextLimit --> CONTEXT_LIMIT
    DrainRace --> CONTEXT_LIMIT
    OtherReasons --> FAILURE

    class START,COMPLETE,CONTEXT_LIMIT,FAILURE,EXHAUSTED terminal;
    class Launch,NormalBranch,StaleSuccess phase;
    class StaleRecovery,TermDecision,NeedsRetryDecision,RetryReasonDecision,PathGate,ContractGate,ZeroWriteGate,RetryExhausted stateNode;
    class StaleFailPath,TimeoutBranch handler;
    class ComputeOutcome,BudgetGuard detector;
    class ResumeStale,ResumeContextLimit,DrainRace,OtherReasons newComponent;
    class SkillResultOut output;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | Terminal | Start, complete, context-limit, failure, and
exhausted terminal states |
| Purple | Phase | Normal completion paths and recovery success |
| Teal | Decision | Routing decision points (termination, needs_retry,
retry_reason) |
| Orange | Modified Path | `● Stale failure` and `● TIMED_OUT` paths
with session_id backfill |
| Red | Gate | `_compute_outcome` and `Budget guard` validation gates |
| Green | Routing Rule | Sous-chef dispatch rules (2D key: retry_reason
× subtype) |
| Dark Teal | Output | `SkillResult` produced from `_build_skill_result`
|

### Operational Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000;

    subgraph CLI ["CLI ENTRY POINTS"]
        direction LR
        OrderCmd["autoskillit order<br/>━━━━━━━━━━<br/>[recipe] — recipe name or picker<br/>app.py:order command"]
        CookCmd["autoskillit cook<br/>━━━━━━━━━━<br/>Free-form interactive session<br/>(no _build_orchestrator_prompt)"]
    end

    subgraph OrderFlow ["ORDER COMMAND WORKFLOW"]
        direction TB
        RecipeResolve["Recipe resolution<br/>━━━━━━━━━━<br/>load_recipe + validate_recipe<br/>user picker if no recipe given"]
        SubsetGate["Subset gate<br/>━━━━━━━━━━<br/>show disabled subsets<br/>user opt-in prompt"]
        PreviewRender["show_cook_preview<br/>━━━━━━━━━━<br/>flow diagram + ingredients table<br/>rendered to terminal"]
        UserConfirm{"[Enter/n]<br/>━━━━━━━━━━<br/>launch confirm?"}
    end

    subgraph PromptBuild ["● PROMPT CONSTRUCTION (_build_orchestrator_prompt MODIFIED)"]
        direction TB
        PromptFn["● _build_orchestrator_prompt(recipe_name)<br/>━━━━━━━━━━<br/>Reads sous-chef/SKILL.md (bundled)<br/>Builds --append-system-prompt string"]
        OpenKitchenLine["● Mandatory first-action line<br/>━━━━━━━━━━<br/>open_kitchen(name='{recipe_name}')<br/>keyword arg form — FIXED<br/>(was: positional → Claude guessed param name)"]
        OrchestratorRules["Orchestrator rules injected<br/>━━━━━━━━━━<br/>tool restrictions (AskUserQuestion only)<br/>routing rules, failure predicates<br/>context-limit + stale retry routing"]
    end

    subgraph SessionLaunch ["SESSION LAUNCH"]
        direction TB
        LaunchCook["_launch_cook_session<br/>━━━━━━━━━━<br/>claude --plugin-dir {pkg_root}<br/>--tools AskUserQuestion<br/>--append-system-prompt {prompt}"]
        ClaudeSession["Claude Code interactive session<br/>━━━━━━━━━━<br/>MCP server: autoskillit<br/>Kitchen gated until open_kitchen(name=...) called"]
    end

    subgraph KitchenActivation ["MCP KITCHEN — open_kitchen tool"]
        direction TB
        OpenKitchenTool["open_kitchen(name=...)<br/>━━━━━━━━━━<br/>Reveals 40 kitchen MCP tools<br/>Loads recipe from recipes/ directory<br/>name= kwarg — unambiguous param"]
        PreviousGap["open_kitchen('{recipe_name}') [OLD]<br/>━━━━━━━━━━<br/>Positional arg → Claude infers param<br/>Sometimes guesses 'recipe_name' not 'name'<br/>→ tool call fails, wastes retry"]
    end

    subgraph Monitoring ["OBSERVABILITY"]
        direction TB
        SessionLogs["Session diagnostics logs<br/>━━━━━━━━━━<br/>~/.local/share/autoskillit/logs/<br/>sessions/{session_id}/"]
        TelemetryLogs[".autoskillit/temp/<br/>━━━━━━━━━━<br/>Token/timing summaries<br/>Audit logs, PR bodies"]
    end

    OrderCmd --> RecipeResolve
    RecipeResolve --> SubsetGate
    SubsetGate --> PreviewRender
    PreviewRender --> UserConfirm
    UserConfirm -->|"confirmed"| PromptFn
    UserConfirm -->|"abort"| ABORT([ABORT])
    PromptFn --> OpenKitchenLine
    PromptFn --> OrchestratorRules
    OpenKitchenLine --> LaunchCook
    OrchestratorRules --> LaunchCook
    LaunchCook --> ClaudeSession
    ClaudeSession --> OpenKitchenTool
    PreviousGap -.->|"eliminated"| OpenKitchenTool
    ClaudeSession --> SessionLogs
    ClaudeSession --> TelemetryLogs
    CookCmd -.->|"no prompt injection"| ClaudeSession

    class OrderCmd,CookCmd cli;
    class RecipeResolve,SubsetGate,PreviewRender phase;
    class UserConfirm stateNode;
    class PromptFn handler;
    class OpenKitchenLine newComponent;
    class OrchestratorRules phase;
    class LaunchCook handler;
    class ClaudeSession stateNode;
    class OpenKitchenTool output;
    class PreviousGap gap;
    class SessionLogs,TelemetryLogs output;
    class ABORT detector;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | CLI | `autoskillit order` and `cook` entry points |
| Purple | Phase | Recipe resolution, subset gating, preview render,
orchestrator rules |
| Orange | Handler | `_build_orchestrator_prompt` and
`_launch_cook_session` |
| Green | Modified | `● Mandatory first-action line` — keyword argument
form fix |
| Teal | Decision/State | User confirm gate and Claude session state |
| Dark Teal | Output | `open_kitchen` tool and observability logs |
| Yellow/Orange | Eliminated | Old positional-argument form — ambiguous
param guess |
| Red | Terminal | Abort path |

Closes #527

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/remediation-20260326-210914-908214/.autoskillit/temp/rectify/rectify_session_id_channel_b_backfill_2026-03-26_210914_part_a.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
…#542)

## Summary

The orchestrator prompt builders (`_build_orchestrator_prompt`,
`_build_open_kitchen_prompt`) emit bare `open_kitchen` tool names with
no MCP prefix. When autoskillit is marketplace-installed AND a session
is launched via `--plugin-dir`, the spawned session registers tools
under the marketplace prefix (`mcp__plugin_autoskillit_autoskillit__`),
not the direct prefix (`mcp__autoskillit__`). The LLM receives an
ambiguous bare name, guesses the wrong prefix, and gets a "No such tool"
error before recovering on retry. The architectural fix is to make the
MCP prefix an **explicit parameter** of the prompt builders, resolved at
session-launch time from a single canonical detection function
(`cli/_mcp_names.py`). This eliminates the LLM's need to guess and makes
the prefix contract testable in isolation for both install modes. The
structural solution also adds a hook-matcher cross-validation test that
proves the detected name is consistent with what the hook registry will
recognize.

## Architecture Impact

### Module Dependency Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 70, 'curve': 'basis'}}}%%
graph TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef integration fill:#c62828,stroke:#ef9a9a,stroke-width:2px,color:#fff;

    subgraph L3_CLI ["L3 — CLI Layer (changed files)"]
        direction TB
        APP["● cli/app.py<br/>━━━━━━━━━━<br/>order() detects prefix<br/>passes mcp_prefix to builders"]
        MCP_NAMES["★ cli/_mcp_names.py<br/>━━━━━━━━━━<br/>detect_autoskillit_mcp_prefix()<br/>DIRECT_PREFIX / MARKETPLACE_PREFIX<br/>resolve_tool_name()"]
        PROMPTS["● cli/_prompts.py<br/>━━━━━━━━━━<br/>_build_orchestrator_prompt(recipe, mcp_prefix)<br/>_build_open_kitchen_prompt(mcp_prefix)<br/>emits fully-qualified tool name"]
    end

    subgraph L1_CORE ["L1 — Core Layer"]
        direction LR
        CORE["core/<br/>━━━━━━━━━━<br/>ClaudeFlags, get_logger<br/>pkg_root, PIPELINE_FORBIDDEN_TOOLS"]
    end

    subgraph L0_EXT ["L0 — External (stdlib + filesystem)"]
        direction LR
        STDLIB["json, pathlib<br/>━━━━━━━━━━<br/>stdlib only"]
        PLUGINS_JSON["~/.claude/plugins/<br/>installed_plugins.json<br/>━━━━━━━━━━<br/>marketplace install registry<br/>(read at runtime)"]
    end

    subgraph TESTS ["★ New / ● Modified Tests"]
        direction LR
        TEST_MCP["★ tests/cli/test_mcp_names.py<br/>━━━━━━━━━━<br/>prefix detection unit tests"]
        TEST_PROMPTS["● tests/cli/test_cli_prompts.py<br/>━━━━━━━━━━<br/>prefix-parametrised assertions"]
        TEST_CONTRACT["● tests/contracts/<br/>test_instruction_surface.py<br/>━━━━━━━━━━<br/>hook-matcher cross-validation"]
        TEST_COOK["● tests/cli/test_cook.py<br/>━━━━━━━━━━<br/>deploy-mode integration tests"]
    end

    APP -->|"imports detect_autoskillit_mcp_prefix<br/>(NEW dependency)"| MCP_NAMES
    APP -->|"passes mcp_prefix=<br/>calls _build_*_prompt()"| PROMPTS
    APP -->|"imports ClaudeFlags,<br/>atomic_write, pkg_root"| CORE
    PROMPTS -->|"imports PIPELINE_FORBIDDEN_TOOLS,<br/>get_logger, pkg_root"| CORE
    MCP_NAMES -->|"imports json, pathlib"| STDLIB
    MCP_NAMES -->|"reads at runtime"| PLUGINS_JSON

    TEST_MCP -->|"imports"| MCP_NAMES
    TEST_PROMPTS -->|"imports DIRECT_PREFIX,<br/>MARKETPLACE_PREFIX"| MCP_NAMES
    TEST_PROMPTS -->|"imports _build_*_prompt"| PROMPTS
    TEST_CONTRACT -->|"imports"| PROMPTS
    TEST_CONTRACT -->|"imports"| MCP_NAMES
    TEST_COOK -->|"imports cli.order()"| APP

    class APP cli;
    class PROMPTS handler;
    class MCP_NAMES newComponent;
    class CORE stateNode;
    class STDLIB phase;
    class PLUGINS_JSON integration;
    class TEST_MCP,TEST_PROMPTS,TEST_CONTRACT,TEST_COOK newComponent;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | CLI (modified) | `app.py` — modified to detect and pass
prefix |
| Orange | Handler (modified) | `_prompts.py` — accepts prefix as
explicit parameter |
| Green | New Component | ★ `_mcp_names.py` + new/extended test modules
|
| Teal | Core (stable) | L1 core types and utilities (unchanged) |
| Purple | Phase / stdlib | Pure stdlib imports (json, pathlib) |
| Red | External | `installed_plugins.json` — filesystem dependency read
at runtime |

### Operational Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef integration fill:#c62828,stroke:#ef9a9a,stroke-width:2px,color:#fff;

    subgraph CLI ["● CLI ENTRY POINT — app.py::order()"]
        direction TB
        ORDER["● autoskillit order recipe<br/>━━━━━━━━━━<br/>Launches interactive Claude session<br/>for recipe orchestration"]
        ORDER_OPEN["● autoskillit order (no recipe)<br/>━━━━━━━━━━<br/>Launches open-kitchen<br/>session for tool reveal"]
    end

    subgraph PREFIX_DETECT ["★ PREFIX DETECTION — _mcp_names.py"]
        direction TB
        DETECT["★ detect_autoskillit_mcp_prefix()<br/>━━━━━━━━━━<br/>Reads installed_plugins.json<br/>Returns DIRECT or MARKETPLACE prefix"]
        INSTALLED_JSON["~/.claude/plugins/installed_plugins.json<br/>━━━━━━━━━━<br/>marketplace install registry<br/>(read-only at runtime)"]
    end

    subgraph PROMPT_BUILD ["● PROMPT BUILDING — _prompts.py"]
        direction TB
        BUILD_ORCH["● _build_orchestrator_prompt(recipe, mcp_prefix)<br/>━━━━━━━━━━<br/>Emits: {mcp_prefix}open_kitchen(name='...')<br/>fully-qualified tool name in system prompt"]
        BUILD_OPEN["● _build_open_kitchen_prompt(mcp_prefix)<br/>━━━━━━━━━━<br/>Emits: Call the {mcp_prefix}open_kitchen tool<br/>fully-qualified tool name in system prompt"]
    end

    subgraph SESSION_LAUNCH ["SESSION LAUNCH"]
        direction TB
        LAUNCH["_launch_cook_session(system_prompt)<br/>━━━━━━━━━━<br/>claude --plugin-dir --append-system-prompt"]
        SESSION["Claude Code Headless Session<br/>━━━━━━━━━━<br/>Receives qualified tool name<br/>Calls open_kitchen on first attempt — no retry"]
    end

    subgraph PREFIX_OUTCOMES ["PREFIX RESOLUTION OUTCOMES"]
        direction LR
        DIRECT["DIRECT_PREFIX<br/>━━━━━━━━━━<br/>mcp__autoskillit__<br/>(plugin-dir only install)"]
        MARKETPLACE["MARKETPLACE_PREFIX<br/>━━━━━━━━━━<br/>mcp__plugin_autoskillit_autoskillit__<br/>(marketplace install present)"]
    end

    ORDER -->|"calls detect prefix first"| DETECT
    ORDER_OPEN -->|"calls detect prefix first"| DETECT
    DETECT -->|"reads"| INSTALLED_JSON
    INSTALLED_JSON -->|"key absent or file missing"| DIRECT
    INSTALLED_JSON -->|"autoskillit@autoskillit-local key present"| MARKETPLACE
    DIRECT -->|"mcp_prefix="| BUILD_ORCH
    MARKETPLACE -->|"mcp_prefix="| BUILD_ORCH
    DIRECT -->|"mcp_prefix="| BUILD_OPEN
    MARKETPLACE -->|"mcp_prefix="| BUILD_OPEN
    BUILD_ORCH -->|"system_prompt"| LAUNCH
    BUILD_OPEN -->|"system_prompt"| LAUNCH
    LAUNCH -->|"spawns"| SESSION

    class ORDER,ORDER_OPEN cli;
    class DETECT,DIRECT,MARKETPLACE newComponent;
    class INSTALLED_JSON integration;
    class BUILD_ORCH,BUILD_OPEN handler;
    class LAUNCH phase;
    class SESSION output;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | CLI (modified) | `autoskillit order` entry point |
| Green | New / Modified | ★ prefix detection; resolved prefix constants
|
| Red | External | `installed_plugins.json` — filesystem read |
| Orange | Handler (modified) | Prompt builders accepting `mcp_prefix`
param |
| Purple | Phase | Session launcher (`_launch_cook_session`) |
| Dark Teal | Output | Spawned Claude Code session |

Closes #541

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/remediation-20260327-080819-703947/.autoskillit/temp/rectify/rectify_mcp_prefix_non_determinism_2026-03-27_081500.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Trecek and others added 20 commits March 28, 2026 17:35
#564)

## Summary

This PR resolves six validated architectural violations spanning
documentation accuracy, import hygiene, structural contract coverage,
code duplication, and runtime safety. The changes tighten the codebase's
internal contracts by fixing stale references, canonicalizing public API
import paths, eliminating triplicated header construction in GitHub API
clients, and introducing type-validated deserialization for
FailureRecord. Supporting improvements include a root-module inventory
gate test, a truncation bug fix in token formatting, and a naming
convention alignment that also corrects a composition root wiring gap
where the audit log was not reliably injected into the background
supervisor.

<details>
<summary>Individual Group Plans</summary>

### Group 1: Documentation and Import Path Fixes (Group A)
Fix four validated architectural violations from the 2026-03-28 audit:

- **P2-5:** Remove a stale `pipeline/fidelity.py` entry from CLAUDE.md
line 133. The module was folded into `execution/pr_analysis.py` during
the `bcafe54f` refactor; the documentation was not updated.
- **P14-1:** `hooks/pretty_output.py:21` imports `ListRecipesResult` and
`LoadRecipeResult` from `autoskillit.recipe._api` (private sub-module)
inside a `TYPE_CHECKING` guard. Changed to canonical
`autoskillit.recipe` surface.
- **P14-3:** `server/helpers.py:34` imports `SubprocessResult` from
`autoskillit.execution.process` (internal sub-module). Changed to
canonical `autoskillit.core` surface.
- **P14-4:** `workspace/session_skills.py:30` imports `AutomationConfig`
from `autoskillit.config.settings` (internal sub-module). Changed to
canonical `autoskillit.config` surface.

### Group 2: Test Contract Strengthening (groupB)
Two gaps in structural contract tests:

1. **P13-2** — Add `test_root_module_allowlist`: a frozen-frozenset gate
that enumerates `src/autoskillit/*.py` (root level, non-recursive) and
asserts the result matches exactly the expected inventory.
2. **P13-6** — Add `"hooks"` to the `PACKAGES_WITH_ALL` list inside
`test_package_all_matches_exports`. The `hooks` package declares
`__all__ = ["HOOK_REGISTRY", "HookDef", "generate_hooks_json"]` but was
omitted from coverage.

### Group 3: Terminal Table Deduplication and Token Formatting Bug Fix
Two focused changes:

1. **P6-8** — Extract shared helpers `_compute_col_widths` and `_cell`
in `core/_terminal_table.py`. Both render functions
(`_render_terminal_table` and `_render_gfm_table`) duplicated this logic
verbatim. No behavioral change.
2. **P6-2** — Fix `_humanize` truncation in
`hooks/token_summary_appender.py`: `str(int(n))` silently truncated
decimal portions. Changed to `str(n)` to align with the canonical
`TelemetryFormatter._humanize`.

### Group 4: GitHub API Headers Consolidation
Eliminate triplicated GitHub REST API header construction across
`execution/github.py`, `execution/ci.py`, and `execution/merge_queue.py`
by extracting a single module-level `_github_headers(token: str | None)
-> dict[str, str]` function. This simultaneously fixes the silent bug in
`merge_queue.py` where `"User-Agent": "autoskillit"` was omitted from
the `httpx.AsyncClient` base headers.

### Group 5: BackgroundTaskSupervisor Rename and Composition Root Fix
Two coupled fixes:

1. **P12-4** — Rename `BackgroundTaskSupervisor` →
`DefaultBackgroundSupervisor` across the class definition, all
re-exports, all import sites, all test references, and architecture
documentation. Aligns with the project-wide `Default*` naming
convention.
2. **P12-2** — Replace
`field(default_factory=DefaultBackgroundSupervisor)` in
`pipeline/context.py` with `field(default=None)` + `__post_init__` that
constructs `DefaultBackgroundSupervisor(audit=self.audit)`. This ensures
any `ToolContext` constructed outside `make_context()` still routes
background task failures to the audit store.

### Group 6: FailureRecord Type Validation in load_from_log_dir
Add `_validate_failure_record_dict` helper to `pipeline/audit.py` that
validates field presence and concrete-type correctness before
`FailureRecord(**record_dict)` is called in `load_from_log_dir`. Uses
`dataclasses.fields(FailureRecord)` + `typing.get_type_hints()`
(required due to `from __future__ import annotations`) to validate all 7
fields (`str` × 5, `int` × 1, `bool` × 1).

</details>

## Architecture Impact

### Module Dependency Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 70, 'curve': 'basis'}}}%%
graph TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;

    subgraph L3 ["L3 — Composition Root / Server"]
        direction LR
        FACTORY["● server/_factory.py<br/>━━━━━━━━━━<br/>Composition Root<br/>Updated: DefaultBackgroundSupervisor import"]
        HELPERS["● server/helpers.py<br/>━━━━━━━━━━<br/>Server utilities<br/>Fixed: SubprocessResult → core (canonical)"]
    end

    subgraph L2 ["L2 — Recipe / Migration"]
        direction LR
        RECIPE["recipe/<br/>━━━━━━━━━━<br/>Canonical public surface<br/>ListRecipesResult, LoadRecipeResult"]
    end

    subgraph L1_PIPELINE ["L1 — Pipeline"]
        direction TB
        CONTEXT["● pipeline/context.py<br/>━━━━━━━━━━<br/>ToolContext DI container<br/>Fixed: default_factory → __post_init__"]
        BG["● pipeline/background.py<br/>━━━━━━━━━━<br/>DefaultBackgroundSupervisor<br/>Renamed from BackgroundTaskSupervisor"]
        AUDIT["● pipeline/audit.py<br/>━━━━━━━━━━<br/>DefaultAuditLog<br/>Added _validate_failure_record_dict"]
    end

    subgraph L1_EXEC ["L1 — Execution"]
        direction TB
        GITHUB["● execution/github.py<br/>━━━━━━━━━━<br/>GitHub fetcher<br/>+ _github_headers helper extracted"]
        CI["● execution/ci.py<br/>━━━━━━━━━━<br/>CI watcher<br/>Fixed: delegates to _github_headers"]
        MQ["● execution/merge_queue.py<br/>━━━━━━━━━━<br/>Merge queue watcher<br/>Fixed: delegates to _github_headers<br/>+ User-Agent header restored"]
    end

    subgraph L1_WS ["L1 — Workspace / Config"]
        direction LR
        SESSION_SKILLS["● workspace/session_skills.py<br/>━━━━━━━━━━<br/>SessionSkillManager<br/>Fixed: AutomationConfig → config (canonical)"]
        CONFIG["config/<br/>━━━━━━━━━━<br/>AutomationConfig<br/>Canonical config surface"]
    end

    subgraph L0 ["L0 — Core Foundation"]
        direction LR
        CORE["core/<br/>━━━━━━━━━━<br/>SubprocessResult, FailureRecord<br/>get_logger, atomic_write"]
        TERM_TABLE["● core/_terminal_table.py<br/>━━━━━━━━━━<br/>Extracted: _compute_col_widths<br/>Extracted: _cell helper"]
    end

    subgraph HOOKS ["Hooks (Hybrid — stdlib runtime)"]
        direction LR
        PRETTY["● hooks/pretty_output.py<br/>━━━━━━━━━━<br/>TYPE_CHECKING import fixed<br/>→ autoskillit.recipe (canonical)"]
        TOKEN_APP["● hooks/token_summary_appender.py<br/>━━━━━━━━━━<br/>Fixed: str(int(n)) → str(n)<br/>No internal imports at runtime"]
    end

    subgraph TESTS ["Tests (New/Modified)"]
        direction LR
        NEW_TEST["★ tests/execution/test_github_headers.py<br/>━━━━━━━━━━<br/>Immunity suite for _github_headers"]
        MOD_TESTS["● tests/pipeline/*, tests/contracts/*<br/>━━━━━━━━━━<br/>Updated for renamed/new symbols"]
    end

    %% L3 → L2 %%
    FACTORY -->|"imports recipe/"| RECIPE
    HELPERS -->|"imports recipe/"| RECIPE

    %% L3 → L1 %%
    FACTORY -->|"imports pipeline/"| CONTEXT
    FACTORY -->|"imports pipeline/"| AUDIT
    FACTORY -->|"imports execution/"| GITHUB

    %% L3 → L0 %%
    HELPERS -->|"● SubprocessResult<br/>via core canonical"| CORE

    %% L1 Pipeline internal %%
    CONTEXT -->|"● imports renamed<br/>DefaultBackgroundSupervisor"| BG
    BG -->|"imports"| CORE
    AUDIT -->|"imports FailureRecord"| CORE
    CONTEXT -->|"imports"| CONFIG

    %% L1 Execution internal — consolidated headers %%
    CI -->|"● _github_headers<br/>consolidated"| GITHUB
    MQ -->|"● _github_headers<br/>consolidated"| GITHUB
    GITHUB -->|"imports core"| CORE

    %% L1 Workspace %%
    SESSION_SKILLS -->|"● AutomationConfig<br/>via config canonical"| CONFIG

    %% Hooks TYPE_CHECKING %%
    PRETTY -.->|"TYPE_CHECKING only<br/>● canonical: recipe"| RECIPE

    %% Tests %%
    NEW_TEST -.->|"tests"| GITHUB
    MOD_TESTS -.->|"tests"| CONTEXT
    MOD_TESTS -.->|"tests"| AUDIT
    MOD_TESTS -.->|"tests"| BG

    %% CLASS ASSIGNMENTS %%
    class FACTORY,HELPERS cli;
    class RECIPE,CONFIG phase;
    class CONTEXT,BG,AUDIT handler;
    class GITHUB,CI,MQ handler;
    class SESSION_SKILLS handler;
    class CORE,TERM_TABLE stateNode;
    class PRETTY,TOKEN_APP output;
    class NEW_TEST newComponent;
    class MOD_TESTS output;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | Composition Root | L3 server entrypoints (_factory,
helpers) |
| Purple | Public Surfaces | Canonical module surfaces (recipe/,
config/) |
| Orange | Services | L1 service modules (pipeline, execution,
workspace) |
| Teal | Foundation | L0 core modules |
| Dark Teal | Hooks/Tests | Hook scripts and test artifacts |
| Green | New | Newly added files (★) |
| Dashed Lines | TYPE_CHECKING | Import-time only — zero runtime impact
|

### State Lifecycle Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000;
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;

    START([ToolContext construction])

    subgraph REQUIRED ["INIT_ONLY — Required Fields (fail-fast if missing)"]
        direction LR
        AUDIT_FIELD["audit: AuditStore<br/>━━━━━━━━━━<br/>DefaultAuditLog instance<br/>Required, never None"]
        CONFIG_FIELD["config: AutomationConfig<br/>━━━━━━━━━━<br/>Layered config<br/>Required, immutable"]
        STORES["token_log / timing_log / gate<br/>━━━━━━━━━━<br/>Required pipeline stores<br/>plugin_dir: str, runner: ... | None"]
    end

    subgraph AUTOWIRE ["● AUTO_WIRED — __post_init__ Composition Gate"]
        direction TB
        POST_INIT["● ToolContext.__post_init__<br/>━━━━━━━━━━<br/>if self.background is None:<br/>    self.background = DefaultBackgroundSupervisor(audit=self.audit)<br/>Guarantees audit is always injected"]
        BG_SUPERVISOR["● DefaultBackgroundSupervisor<br/>━━━━━━━━━━<br/>_audit = self.audit  ← always set<br/>_tasks: set[asyncio.Task]"]
    end

    subgraph TASK_LIFECYCLE ["● DefaultBackgroundSupervisor Task Lifecycle"]
        direction TB
        SUBMIT["submit(coro, on_exception, label)<br/>━━━━━━━━━━<br/>Wraps in _supervise_task<br/>Adds to _tasks set"]
        SUPERVISE["_supervise_task()<br/>━━━━━━━━━━<br/>Exception boundary<br/>CancelledError → status=cancelled<br/>Exception → status=failed"]
        AUDIT_WRITE["self._audit.record_failure(FailureRecord)<br/>━━━━━━━━━━<br/>subtype=background_exception<br/>exit_code=-1, needs_retry=False<br/>stderr=str(exc)[:500]"]
    end

    subgraph DESERIALIZATION ["● FailureRecord Deserialization Guard"]
        direction TB
        LOAD_DIR["DefaultAuditLog.load_from_log_dir()<br/>━━━━━━━━━━<br/>Reads .jsonl files from disk<br/>Reconstructs FailureRecord objects"]
        VALIDATE["● _validate_failure_record_dict(record_dict)<br/>━━━━━━━━━━<br/>Phase 1: field presence check<br/>   dataclasses.fields(FailureRecord)<br/>Phase 2: concrete type check<br/>   get_type_hints() → isinstance()<br/>Returns False → skip record"]
        SAFE_BUILD["FailureRecord(**record_dict)<br/>━━━━━━━━━━<br/>Only reached for valid records<br/>str×5, int×1, bool×1 fields"]
    end

    subgraph AUDIT_STORE ["APPEND_ONLY — AuditStore (DefaultAuditLog)"]
        direction LR
        FAILURES["failures: list[FailureRecord]<br/>━━━━━━━━━━<br/>Only grows via record_failure()<br/>Never mutated after append"]
        PERSIST["JSONL persistence<br/>━━━━━━━━━━<br/>atomic_write() per record<br/>Survives process crash"]
    end

    MAKE_CTX([make_context() — Composition Root])

    %% FLOW %%
    MAKE_CTX --> START
    START --> AUDIT_FIELD
    START --> CONFIG_FIELD
    START --> STORES
    AUDIT_FIELD --> POST_INIT
    POST_INIT -->|"auto-wires audit"| BG_SUPERVISOR
    BG_SUPERVISOR --> SUBMIT
    SUBMIT --> SUPERVISE
    SUPERVISE -->|"on Exception"| AUDIT_WRITE
    AUDIT_WRITE --> FAILURES
    FAILURES --> PERSIST
    PERSIST --> LOAD_DIR
    LOAD_DIR --> VALIDATE
    VALIDATE -->|"valid dict"| SAFE_BUILD
    VALIDATE -->|"invalid → skip"| DISCARD([discard record])

    %% CLASS ASSIGNMENTS %%
    class START,MAKE_CTX,DISCARD terminal;
    class AUDIT_FIELD,CONFIG_FIELD,STORES detector;
    class POST_INIT,BG_SUPERVISOR phase;
    class SUBMIT,SUPERVISE handler;
    class AUDIT_WRITE,VALIDATE output;
    class FAILURES,PERSIST stateNode;
    class LOAD_DIR,SAFE_BUILD handler;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | Terminal | Entry/exit points |
| Red | INIT_ONLY | Required fields — fail-fast if missing |
| Purple | Auto-Wire | __post_init__ composition gate (● modified) |
| Orange | Task Runtime | Background task submission and supervision |
| Dark Teal | Guard/Output | Validation gate and audit write |
| Teal | Audit Store | Append-only failure persistence |

Closes #554

## Implementation Plan

Plan files:
-
`.autoskillit/temp/make-plan/groupA_doc_import_fixes_plan_2026-03-28_085530.md`
-
`.autoskillit/temp/make-plan/test_contract_strengthening_groupB_plan_2026-03-28_085300.md`
-
`.autoskillit/temp/make-plan/terminal_table_dedup_and_humanize_fix_plan_2026-03-28_085500.md`
-
`.autoskillit/temp/make-plan/github_headers_consolidation_plan_2026-03-28_090000.md`
-
`.autoskillit/temp/make-plan/background_supervisor_rename_plan_2026-03-28_103015.md`
-
`.autoskillit/temp/make-plan/failure_record_type_validation_plan_2026-03-28_084500.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

## Token Usage Summary

| Step | input | output | cached | count | time |
|------|-------|--------|--------|-------|------|
| group | 2.7k | 25.0k | 721.4k | 1 | 9m 3s |
| plan | 462 | 84.7k | 14.8M | 9 | 41m 2s |
| verify | 98 | 55.7k | 3.3M | 6 | 18m 12s |
| implement | 536 | 45.2k | 10.3M | 9 | 25m 25s |
| fix | 60 | 10.0k | 1.6M | 2 | 11m 53s |
| audit_impl | 23 | 15.7k | 1.0M | 1 | 6m 9s |
| open_pr | 41 | 24.9k | 1.7M | 1 | 8m 38s |
| **Total** | 3.9k | 261.3k | 33.5M | | 2h 0m |

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
## Summary

Four targeted test-quality improvements across three test files:

1. **Req 2.2** — Delete the duplicate
`test_model_default_consistent_with_yaml` test in
`TestReleaseReadinessConfig` (`tests/config/test_config.py:653`). The
identical assertion (`ModelConfig().default == "sonnet"`) is already
covered by `TestDefaultConfig.test_default_model_config` (line 35). The
`load_config` round-trip variant at line 204 is kept as it exercises a
distinct code path.

2. **Req 3.1** — Strengthen the `test_returns_bound_logger` test in
`tests/core/test_logging.py`. Replace the three `callable(logger.*)`
assertions with a structural `isinstance(logger, BoundLoggerLazyProxy)`
check plus a clarifying comment. `callable()` returns `True` for any
structlog lazy proxy attribute via `__getattr__`—it does not confirm
that `logger` is the expected type.

3. **Req 3.2** — Remove two `hasattr` guards in
`tests/config/test_config.py`. `if hasattr(cfg, "field"):` before
`assert cfg.field == ...` is a weaker assertion: it passes silently when
the field is absent. Replace with direct attribute access so a missing
field raises `AttributeError` and fails the test rather than silently
passing.

4. **Req 3.8** — Rename the local `_make_result` helper in
`tests/execution/test_session.py` to `_make_session_result`. The local
helper shadows the conftest-level `_make_result` with different default
parameters. Renaming removes the ambiguity.

## Architecture Impact

### Operational Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;

    subgraph Tasks ["TASK AUTOMATION"]
        TA["task test-all<br/>━━━━━━━━━━<br/>lint + pytest -n 4<br/>quality gate"]
        TC_CMD["task test-check<br/>━━━━━━━━━━<br/>TEST_RESULT=PASS/FAIL<br/>automation gate"]
    end

    subgraph TestSuite ["MODIFIED TEST FILES"]
        TC["● tests/config/test_config.py<br/>━━━━━━━━━━<br/>AutomationConfig fields<br/>LoggingConfig, LinuxTracingConfig"]
        TL["● tests/core/test_logging.py<br/>━━━━━━━━━━<br/>get_logger() type contract<br/>BoundLoggerLazyProxy assertion"]
        TS["● tests/execution/test_session.py<br/>━━━━━━━━━━<br/>ClaudeSessionResult extraction<br/>_make_session_result helper"]
    end

    subgraph Config ["CONFIGURATION (read-only at runtime)"]
        AC["AutomationConfig<br/>━━━━━━━━━━<br/>Root config aggregate<br/>dynaconf-backed"]
        LC["LoggingConfig<br/>━━━━━━━━━━<br/>level: INFO<br/>json_output: null"]
        LTC["LinuxTracingConfig<br/>━━━━━━━━━━<br/>enabled: true<br/>proc_interval: 5.0"]
        MC["ModelConfig<br/>━━━━━━━━━━<br/>default: sonnet"]
    end

    subgraph Logging ["LOGGING SYSTEM"]
        GL["get_logger(name)<br/>━━━━━━━━━━<br/>→ BoundLoggerLazyProxy<br/>lazy structlog binding"]
        CL["configure_logging()<br/>━━━━━━━━━━<br/>level + json_output<br/>routes to stderr only"]
    end

    subgraph ConfigSources ["CONFIGURATION HIERARCHY (lowest → highest)"]
        D["defaults.yaml<br/>━━━━━━━━━━<br/>bundled package defaults"]
        U["~/.autoskillit/config.yaml<br/>━━━━━━━━━━<br/>user-level overrides"]
        P[".autoskillit/config.yaml<br/>━━━━━━━━━━<br/>project-level overrides"]
        S[".autoskillit/.secrets.yaml<br/>━━━━━━━━━━<br/>github.token only"]
        E["AUTOSKILLIT_SECTION__KEY<br/>━━━━━━━━━━<br/>env vars (highest priority)"]
    end

    D --> U --> P --> S --> E --> AC
    AC --> LC
    AC --> LTC
    AC --> MC
    LC -.->|"configures"| CL
    GL --> CL
    TA --> TC
    TA --> TL
    TA --> TS
    TC -.->|"asserts fields"| AC
    TL -.->|"asserts type"| GL
    TC_CMD --> TC

    class TA,TC_CMD cli;
    class TC,TL,TS handler;
    class AC,LC,LTC,MC stateNode;
    class GL,CL phase;
    class D,U,P,S,E output;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | CLI | Task automation commands |
| Orange | Handler (●) | Modified test files |
| Teal | State | Configuration dataclasses |
| Purple | Phase | Logging system components |
| Dark Teal | Config Sources | Configuration resolution layers |

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/impl-groupH-20260328-084625-409744/.autoskillit/temp/make-plan/groupH_low_severity_fixes_plan_2026-03-28_084625.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

## Token Usage Summary

| Step | input | output | cached | count | time |
|------|-------|--------|--------|-------|------|
| group | 2.7k | 25.0k | 721.4k | 1 | 9m 3s |
| plan | 462 | 84.7k | 14.8M | 9 | 41m 2s |
| verify | 98 | 55.7k | 3.3M | 6 | 18m 12s |
| implement | 536 | 45.2k | 10.3M | 9 | 25m 25s |
| fix | 60 | 10.0k | 1.6M | 2 | 11m 53s |
| **Total** | 3.8k | 220.7k | 30.7M | | 1h 45m |

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
## Summary

Eight targeted fixes across seven test files: four test/class renames
that resolve name–assertion mismatches (2.19, 2.20, 2.21, 2.23), a
rewrite of `SmokeExecutor._run_with_retry` and its routing logic to use
the current flat `retries:` / `on_exhausted:` schema (2.24/2.30) along
with updates to the two tests that exercised the old schema, deletion of
a single stale set-equality assertion (2.25), and strengthening of two
contract-test assertions that use overly permissive string matching
(2.27, 2.28). No production code changes; only test code.

## Architecture Impact

### Process Flow Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 40, 'rankSpacing': 50, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;

    START([SmokeExecutor.run])

    subgraph Loop ["Step Execution Loop (max_steps=30)"]
        direction TB
        ACTION{"action?<br/>━━━━━━━━━━<br/>stop / route / python / default"}
        STOP["stop<br/>━━━━━━━━━━<br/>return terminal_step + message"]
        ROUTE_ACTION["route (action)<br/>━━━━━━━━━━<br/>jump to on_success"]
        PYTHON["python:<br/>━━━━━━━━━━<br/>_execute_python → run_python MCP"]
    end

    subgraph Dispatch ["● _execute (test_smoke_pipeline.py)"]
        direction TB
        HAS_RETRIES{"retries in step_def?<br/>━━━━━━━━━━<br/>flat schema check"}
        DIRECT_CALL["direct call<br/>━━━━━━━━━━<br/>_TOOL_MAP[tool](**args)"]
        DELEGATE["delegate<br/>━━━━━━━━━━<br/>→ _run_with_retry"]
    end

    subgraph Retry ["● _run_with_retry (test_smoke_pipeline.py)"]
        direction TB
        FIRST_CALL["initial attempt<br/>━━━━━━━━━━<br/>tool_fn(**args)"]
        SUCCESS_CHECK{"● _is_success?<br/>━━━━━━━━━━<br/>tool-specific check"}
        RETRY_LOOP["retry loop<br/>━━━━━━━━━━<br/>for _ in range(max_retries)"]
        RETRY_SUCCESS{"_is_success?<br/>━━━━━━━━━━<br/>after re-attempt"}
        EXHAUSTED["● _retries_exhausted<br/>━━━━━━━━━━<br/>result[_retries_exhausted]=True"]
    end

    subgraph Routing ["● _route (test_smoke_pipeline.py)"]
        direction TB
        ON_RESULT{"on_result block?<br/>━━━━━━━━━━<br/>field-value dispatch"}
        EXHAUSTION{"● on_exhausted<br/>━━━━━━━━━━<br/>_retries_exhausted flagged?"}
        SF_CHECK{"_is_success?<br/>━━━━━━━━━━<br/>success / failure"}
    end

    CAPTURE["_capture<br/>━━━━━━━━━━<br/>extract key=value into context"]
    NEXT_STEP["advance to next_step<br/>━━━━━━━━━━<br/>loop iteration"]

    DONE([DONE / terminal_step])

    START --> ACTION
    ACTION -->|"stop"| STOP
    ACTION -->|"route"| ROUTE_ACTION
    ACTION -->|"python:"| PYTHON
    ACTION -->|"default"| HAS_RETRIES
    STOP --> DONE
    ROUTE_ACTION --> NEXT_STEP
    PYTHON --> CAPTURE

    HAS_RETRIES -->|"no"| DIRECT_CALL
    HAS_RETRIES -->|"yes"| DELEGATE
    DIRECT_CALL --> CAPTURE
    DELEGATE --> FIRST_CALL

    FIRST_CALL --> SUCCESS_CHECK
    SUCCESS_CHECK -->|"pass"| CAPTURE
    SUCCESS_CHECK -->|"fail"| RETRY_LOOP
    RETRY_LOOP --> RETRY_SUCCESS
    RETRY_SUCCESS -->|"pass"| CAPTURE
    RETRY_SUCCESS -->|"fail → loop"| RETRY_LOOP
    RETRY_LOOP -->|"exhausted"| EXHAUSTED
    EXHAUSTED --> CAPTURE

    CAPTURE --> ON_RESULT
    ON_RESULT -->|"match → target step"| NEXT_STEP
    ON_RESULT -->|"no match"| EXHAUSTION
    EXHAUSTION -->|"yes → on_exhausted"| NEXT_STEP
    EXHAUSTION -->|"no"| SF_CHECK
    SF_CHECK -->|"pass → on_success"| NEXT_STEP
    SF_CHECK -->|"fail → on_failure"| NEXT_STEP
    NEXT_STEP --> ACTION

    class START,DONE terminal;
    class ACTION,HAS_RETRIES,SUCCESS_CHECK,RETRY_SUCCESS,ON_RESULT,EXHAUSTION,SF_CHECK stateNode;
    class STOP,ROUTE_ACTION,PYTHON,DIRECT_CALL,DELEGATE,FIRST_CALL,RETRY_LOOP,NEXT_STEP handler;
    class EXHAUSTED,CAPTURE phase;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | Terminal | Start and completion states |
| Teal | Decision | Routing and branching decisions |
| Orange | Handler | Tool invocation and step execution |
| Purple | Phase | State mutation (capture, exhaustion sentinel) |

### Scenarios Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 40, 'rankSpacing': 50, 'curve': 'basis'}}}%%
flowchart LR
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;

    subgraph S1 ["SCENARIO 1: Test Name Accuracy (REQ 2.19–2.23)"]
        direction LR
        S1A["● test_core.py<br/>━━━━━━━━━━<br/>test_atomic_write_<br/>docstring_contains_<br/>atomic_keyword"]
        S1B["● test_config.py<br/>━━━━━━━━━━<br/>class TestRunSkill<br/>ConfigFields"]
        S1C["● test_skills.py<br/>━━━━━━━━━━<br/>test_58_skills_in_<br/>skills_extended"]
        S1D["● test_headless_add_dirs.py<br/>━━━━━━━━━━<br/>test_raw_skills_extended_<br/>excluded_from_run_skill_<br/>add_dirs"]
        S1E["pytest assertion<br/>━━━━━━━━━━<br/>name == assertion content"]
    end

    subgraph S2 ["SCENARIO 2: SmokeExecutor Retry — Flat Schema (REQ 2.24, 2.25, 2.30)"]
        direction LR
        S2A["step_def<br/>━━━━━━━━━━<br/>retries: 3<br/>on_exhausted: escalate"]
        S2B["● _execute<br/>━━━━━━━━━━<br/>checks 'retries'<br/>in step_def"]
        S2C["● _run_with_retry<br/>━━━━━━━━━━<br/>initial attempt<br/>+ retry loop"]
        S2D["● _is_success<br/>━━━━━━━━━━<br/>tool-specific<br/>pass check"]
        S2E["● _retries_exhausted<br/>━━━━━━━━━━<br/>sentinel flag<br/>in result"]
        S2F["● _route<br/>━━━━━━━━━━<br/>on_exhausted path<br/>or on_success/failure"]
    end

    subgraph S3 ["SCENARIO 3: Contract Assertion Strength (REQ 2.27, 2.28)"]
        direction LR
        S3A["● test_pr_traceability<br/>_contracts.py<br/>━━━━━━━━━━<br/>reads SKILL.md text"]
        S3B["● heading check<br/>━━━━━━━━━━<br/>'## requirements'<br/>in normalized"]
        S3C["● test_triage<br/>_contracts.py<br/>━━━━━━━━━━<br/>reads SKILL.md text"]
        S3D["● scoped bypass<br/>━━━━━━━━━━<br/>'already has' AND<br/>'## requirements' in lower"]
        S3E["assert has_req<br/>━━━━━━━━━━<br/>heading-structure<br/>validated"]
    end

    %% SCENARIO 1 FLOW %%
    S1A --> S1E
    S1B --> S1E
    S1C --> S1E
    S1D --> S1E

    %% SCENARIO 2 FLOW %%
    S2A --> S2B
    S2B -->|"yes"| S2C
    S2C --> S2D
    S2D -->|"fail"| S2C
    S2D -->|"exhausted"| S2E
    S2D -->|"pass"| S2F
    S2E --> S2F

    %% SCENARIO 3 FLOW %%
    S3A --> S3B
    S3B --> S3E
    S3C --> S3D
    S3D --> S3E

    %% CLASS ASSIGNMENTS %%
    class S1A,S1B,S1C,S1D handler;
    class S1E output;
    class S2A cli;
    class S2B,S2C phase;
    class S2D stateNode;
    class S2E detector;
    class S2F output;
    class S3A,S3C handler;
    class S3B,S3D phase;
    class S3E output;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | Entry | Step definition inputs |
| Orange | Handler | Modified test files |
| Purple | Process | Modified execution/assertion logic |
| Teal | Decision | Success/state checks |
| Red | Sentinel | Exhaustion detection |
| Dark Teal | Output | Assertion outcomes |

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/impl-groupF-20260328-084624-134986/.autoskillit/temp/make-plan/fix_misleading_tests_groupF_plan_2026-03-28_084900.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

## Token Usage Summary

| Step | input | output | cached | count | time |
|------|-------|--------|--------|-------|------|
| group | 2.7k | 25.0k | 721.4k | 1 | 9m 3s |
| plan | 462 | 84.7k | 14.8M | 9 | 41m 2s |
| verify | 98 | 55.7k | 3.3M | 6 | 18m 12s |
| implement | 536 | 45.2k | 10.3M | 9 | 25m 25s |
| fix | 60 | 10.0k | 1.6M | 2 | 11m 53s |
| **Total** | 3.8k | 220.7k | 30.7M | | 1h 45m |
…tract Breach (#568)

## Summary

The session adjudication pipeline in `_build_skill_result` contains a
class of bug where
**recovery functions that mutate `session.result` run without checking
whether the session
completed**, and the CHANNEL_B success bypass in `_compute_success` then
accepts the mutated
state as authoritative — bypassing all completion-status guards that
protect the CHANNEL_A
path. The result is `success=True` for sessions that never completed
their task.

The immune architecture enforces one invariant: **all recovery
operations, and the CHANNEL_B
bypass, require `session.session_complete` to be true.** Session
completion becomes a
first-class property with a single, canonical, tested definition.
Additionally, synthesis
(`_synthesize_from_write_artifacts`) is architecturally restricted to
UNMONITORED sessions
only — the one channel type for which
`_recover_block_from_assistant_messages` is unavailable.
For CHANNEL_A/B sessions, if the pattern was not found in
`assistant_messages`, the agent
never emitted it, and synthesis would fabricate it from write evidence.

## Architecture Impact

### State Lifecycle Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000;
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;

    START([parse_session_result])

    subgraph SessionState ["● ClaudeSessionResult  —  session.py"]
        direction TB
        INIT_FIELDS["INIT_ONLY fields<br/>━━━━━━━━━━<br/>subtype · is_error · session_id<br/>assistant_messages · tool_uses<br/>jsonl_context_exhausted<br/>Set once during parse, never overwritten"]
        RESULT_FIELD["MUTABLE field<br/>━━━━━━━━━━<br/>result: str<br/>May be replaced by recovery<br/>via dataclasses.replace()"]
        ERRORS_FIELD["APPEND_ONLY field<br/>━━━━━━━━━━<br/>errors: list<br/>Accumulated, never cleared"]
        SESSION_COMPLETE["★ session_complete: bool<br/>━━━━━━━━━━<br/>DERIVED property<br/>not is_error AND<br/>subtype not in FAILURE_SUBTYPES"]
    end

    subgraph FailureSet ["● FAILURE_SUBTYPES  —  session.py"]
        FTYPES["● FAILURE_SUBTYPES (was _FAILURE_SUBTYPES)<br/>━━━━━━━━━━<br/>UNKNOWN · EMPTY_OUTPUT<br/>UNPARSEABLE · TIMEOUT<br/>Authoritative failure set"]
    end

    subgraph RecoveryPhase ["● Recovery Phase  —  headless.py  _build_skill_result"]
        direction TB
        COMPLETION_GATE{"★ session.session_complete?<br/>━━━━━━━━━━<br/>Contract A: only mutate<br/>result for complete sessions"}
        SKIP_RECOVERY["SKIP all recovery<br/>━━━━━━━━━━<br/>Incomplete session — Write calls<br/>were intermediate artifacts"]
        RECOVER_MARKER["_recover_from_separate_marker<br/>━━━━━━━━━━<br/>mutates: result<br/>source: assistant_messages"]
        RECOVER_MESSAGES["_recover_block_from_assistant_messages<br/>━━━━━━━━━━<br/>mutates: result<br/>CHANNEL_A / CHANNEL_B only"]
        CHANNEL_GATE{"channel == UNMONITORED?<br/>━━━━━━━━━━<br/>assistant_messages recovery<br/>unavailable for UNMONITORED"}
        SYNTHESIZE["● _synthesize_from_write_artifacts<br/>━━━━━━━━━━<br/>mutates: result<br/>★ UNMONITORED only<br/>★ uses LAST write path"]
        SKIP_SYNTH["skip synthesis<br/>━━━━━━━━━━<br/>Pattern absent from messages<br/>= agent never emitted it"]
    end

    subgraph AdjudicationPhase ["● Adjudication Phase  —  session.py  _compute_success"]
        direction TB
        CB_GATE{"★ CHANNEL_B:<br/>session.session_complete?<br/>━━━━━━━━━━<br/>Contract B: drain-race bypass<br/>only for complete sessions"}
        CB_PATTERN["_check_expected_patterns<br/>━━━━━━━━━━<br/>reads: result (final state)<br/>pattern match → success"]
        CA_PATH["CHANNEL_A / UNMONITORED<br/>━━━━━━━━━━<br/>termination dispatch →<br/>_check_session_content<br/>guards is_error + FAILURE_SUBTYPES"]
        CB_FALLTHROUGH["fall through to<br/>CHANNEL_A path<br/>━━━━━━━━━━<br/>standard content validation"]
    end

    SUCCESS([success = True])
    FAILURE([success = False])

    START --> INIT_FIELDS
    START --> RESULT_FIELD
    START --> ERRORS_FIELD
    INIT_FIELDS --> SESSION_COMPLETE
    FTYPES --> SESSION_COMPLETE

    SESSION_COMPLETE --> COMPLETION_GATE
    COMPLETION_GATE -->|"not complete"| SKIP_RECOVERY
    COMPLETION_GATE -->|"complete"| RECOVER_MARKER
    RECOVER_MARKER --> RECOVER_MESSAGES
    RECOVER_MESSAGES --> CHANNEL_GATE
    CHANNEL_GATE -->|"UNMONITORED"| SYNTHESIZE
    CHANNEL_GATE -->|"CHANNEL_A/B"| SKIP_SYNTH
    SYNTHESIZE --> CB_GATE
    SKIP_SYNTH --> CB_GATE
    SKIP_RECOVERY --> CB_GATE

    CB_GATE -->|"not complete"| CB_FALLTHROUGH
    CB_GATE -->|"complete"| CB_PATTERN
    CB_PATTERN -->|"match"| SUCCESS
    CB_PATTERN -->|"no match"| FAILURE
    CB_FALLTHROUGH --> CA_PATH
    CA_PATH --> SUCCESS
    CA_PATH --> FAILURE

    class START terminal;
    class SUCCESS,FAILURE terminal;
    class INIT_FIELDS detector;
    class RESULT_FIELD phase;
    class ERRORS_FIELD handler;
    class SESSION_COMPLETE newComponent;
    class FTYPES gap;
    class COMPLETION_GATE,CB_GATE newComponent;
    class SKIP_RECOVERY,SKIP_SYNTH detector;
    class RECOVER_MARKER,RECOVER_MESSAGES,SYNTHESIZE handler;
    class CHANNEL_GATE stateNode;
    class CB_PATTERN,CA_PATH,CB_FALLTHROUGH output;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | Terminal | Start and end states |
| Red | INIT_ONLY | Fields frozen after parse |
| Purple | MUTABLE | `result` field — mutated by recovery |
| Orange | Handler | Recovery functions that mutate `result` |
| Green | New Component | ★ New `session_complete` property and guards |
| Yellow/Orange | Warning | `FAILURE_SUBTYPES` set (renamed public) |
| Teal | State | Channel dispatch and pattern check |
| Dark Teal | Output | Adjudication path nodes |
| Dark Red | Blocked | Skip paths — mutation blocked |

### Error Resilience Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000;

    START([_build_skill_result])

    subgraph CompletionGateGroup ["★ Completion Gate  —  headless.py"]
        COMPLETE_GATE{"★ session.session_complete?<br/>━━━━━━━━━━<br/>not is_error AND<br/>subtype not in FAILURE_SUBTYPES"}
        BLOCKED_INCOMPLETE["BLOCKED: Incomplete session<br/>━━━━━━━━━━<br/>UNPARSEABLE / TIMEOUT / UNKNOWN<br/>/ EMPTY_OUTPUT<br/>Recovery skipped entirely"]
    end

    subgraph RecoveryGroup ["Recovery Mechanisms  —  headless.py"]
        RECOVER_MARKER["_recover_from_separate_marker<br/>━━━━━━━━━━<br/>Trigger: completion_marker set<br/>Action: rebuild result from<br/>assistant_messages"]
        RECOVER_MESSAGES["_recover_block_from_assistant_messages<br/>━━━━━━━━━━<br/>Trigger: CHANNEL_A/B + pattern unmet<br/>Action: prepend messages to result"]
        CHANNEL_CHECK{"channel == UNMONITORED?"}
        SYNTHESIZE["● _synthesize_from_write_artifacts<br/>━━━━━━━━━━<br/>★ Trigger: UNMONITORED only<br/>+ write_count≥1 + pattern unmet<br/>★ Uses LAST write path (not first)"]
        SKIP_SYNTH["skip synthesis<br/>━━━━━━━━━━<br/>CHANNEL_A/B: pattern absent from<br/>assistant_messages = never emitted"]
    end

    subgraph AdjudicationGroup ["● Adjudication Gates  —  session.py  _compute_success"]
        CB_GATE{"★ CHANNEL_B:<br/>session.session_complete?<br/>━━━━━━━━━━<br/>Drain-race bypass only valid<br/>for completed sessions"}
        CB_PATTERN{"_check_expected_patterns<br/>━━━━━━━━━━<br/>Pattern match in result?"}
        CA_CONTENT{"CHANNEL_A / UNMONITORED<br/>_check_session_content<br/>━━━━━━━━━━<br/>termination dispatch<br/>is_error + FAILURE_SUBTYPES guard"}
        CB_FALLTHROUGH["fall through to<br/>CHANNEL_A path<br/>━━━━━━━━━━<br/>No bypass for incomplete<br/>CHANNEL_B sessions"]
    end

    subgraph PostOutcomeGroup ["Post-Outcome Gates  —  headless.py"]
        CONTRACT_GATE["CONTRACT_RECOVERY gate<br/>━━━━━━━━━━<br/>Trigger: adjudicated_failure + writes≥1<br/>Result: RETRIABLE(CONTRACT_RECOVERY)"]
        ZERO_WRITE_GATE["zero-write gate<br/>━━━━━━━━━━<br/>Trigger: success + 0 writes<br/>+ write_behavior=always<br/>Result: RETRIABLE(ZERO_WRITES)"]
    end

    SUCCESS([● success = True])
    FAILURE_RETRIABLE([FAILED — RETRIABLE])
    FAILURE_FINAL([FAILED — final])

    START --> COMPLETE_GATE

    COMPLETE_GATE -->|"● not complete"| BLOCKED_INCOMPLETE
    COMPLETE_GATE -->|"complete"| RECOVER_MARKER
    BLOCKED_INCOMPLETE --> CB_GATE

    RECOVER_MARKER --> RECOVER_MESSAGES
    RECOVER_MESSAGES --> CHANNEL_CHECK
    CHANNEL_CHECK -->|"UNMONITORED"| SYNTHESIZE
    CHANNEL_CHECK -->|"CHANNEL_A or CHANNEL_B"| SKIP_SYNTH
    SYNTHESIZE --> CB_GATE
    SKIP_SYNTH --> CB_GATE

    CB_GATE -->|"★ not complete — fallthrough"| CB_FALLTHROUGH
    CB_GATE -->|"complete"| CB_PATTERN
    CB_PATTERN -->|"match"| SUCCESS
    CB_PATTERN -->|"no match"| CA_CONTENT
    CB_FALLTHROUGH --> CA_CONTENT

    CA_CONTENT -->|"content valid"| SUCCESS
    CA_CONTENT -->|"content invalid"| CONTRACT_GATE

    SUCCESS --> ZERO_WRITE_GATE
    ZERO_WRITE_GATE -->|"writes OK"| SUCCESS
    ZERO_WRITE_GATE -->|"0 writes, always-write contract"| FAILURE_RETRIABLE

    CONTRACT_GATE -->|"no writes"| FAILURE_FINAL
    CONTRACT_GATE -->|"writes present"| FAILURE_RETRIABLE

    class START terminal;
    class SUCCESS,FAILURE_RETRIABLE,FAILURE_FINAL terminal;
    class COMPLETE_GATE,CB_GATE newComponent;
    class BLOCKED_INCOMPLETE,SKIP_SYNTH detector;
    class RECOVER_MARKER,RECOVER_MESSAGES,SYNTHESIZE handler;
    class CHANNEL_CHECK,CB_PATTERN,CA_CONTENT stateNode;
    class CB_FALLTHROUGH gap;
    class CONTRACT_GATE,ZERO_WRITE_GATE phase;
    class SUCCESS output;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | Terminal | Start and final outcome states |
| Green | New Gate | ★ New `session_complete` guards |
| Red | Blocked | Skip/block paths for failure subtypes |
| Orange | Recovery | Recovery functions that mutate `result` |
| Teal | Decision | Channel and pattern check decisions |
| Yellow | Warning | Fallthrough path (CHANNEL_B bypass denied) |
| Purple | Post-Gate | Post-outcome gates (CONTRACT_RECOVERY,
ZERO_WRITES) |
| Dark Teal | Output | Success state |

Closes #565

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/remediation-20260329-103423-167215/.autoskillit/temp/rectify/rectify_run-skill-false-positive-success_2026-03-29_000000.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

## Token Usage Summary

| Step | input | output | cached | count | time |
|------|-------|--------|--------|-------|------|
| group | 204 | 31.2k | 1.3M | 2 | 10m 37s |
| plan | 1.9k | 113.5k | 7.8M | 5 | 37m 29s |
| verify | 1.9k | 68.2k | 8.6M | 7 | 28m 50s |
| implement | 4.5k | 97.9k | 17.2M | 5 | 40m 22s |
| fix | 22 | 4.3k | 473.8k | 1 | 5m 53s |
| **Total** | 8.6k | 315.1k | 35.4M | | 2h 3m |

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
…ees (#569)

## Summary

Two subsystems independently manage workspace artifacts — git clones
(`workspace/clone.py` →
`../autoskillit-runs/`) and git worktrees (`server/git.py` inline →
`../worktrees/`) — but
`workspace clean` only knows about clones. The architectural weakness is
a **wrong-layer
ownership violation**: `server/git.py` (L3) contains worktree lifecycle
logic that belongs in
`workspace/` (L1). There is also no canonical constant for the worktrees
directory name, and no
config section governing workspace artifact paths.

Part A establishes the **foundation layer**: promotes directory name
constants to a shared
location, adds a `WorkspaceConfig` section to the config system, and
creates
`workspace/worktree.py` — the new L1 module that owns all git worktree
lifecycle operations.
Part B (separate task) wires these into `workspace clean` and
`perform_merge`.

## Architecture Impact

### Module Dependency Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 70, 'curve': 'basis'}}}%%
graph TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;

    subgraph L0 ["L0 — CORE (foundation, zero autoskillit imports)"]
        CR["core/_type_results.py<br/>━━━━━━━━━━<br/>CleanupResult"]
        SP["core/_type_subprocess.py<br/>━━━━━━━━━━<br/>SubprocessRunner Protocol"]
    end

    subgraph L1_WS ["L1 — WORKSPACE SERVICES"]
        WT["★ workspace/worktree.py<br/>━━━━━━━━━━<br/>list_git_worktrees()<br/>remove_git_worktree()<br/>remove_worktree_sidecar()"]
        CL["● workspace/clone.py<br/>━━━━━━━━━━<br/>RUNS_DIR<br/>★ WORKTREES_DIR"]
        CU["● workspace/cleanup.py<br/>━━━━━━━━━━<br/>docstring corrected"]
        WI["● workspace/__init__.py<br/>━━━━━━━━━━<br/>re-exports worktree fns<br/>RUNS_DIR, WORKTREES_DIR"]
    end

    subgraph L1_CFG ["L1 — CONFIG"]
        CS["● config/settings.py<br/>━━━━━━━━━━<br/>AutomationConfig<br/>★ WorkspaceConfig<br/>worktree_root / runs_root"]
        CI["● config/__init__.py<br/>━━━━━━━━━━<br/>exports WorkspaceConfig"]
        DY["● config/defaults.yaml<br/>━━━━━━━━━━<br/>workspace:<br/>  worktree_root: null<br/>  runs_root: null"]
    end

    subgraph L3_CLI ["L3 — CLI"]
        WS["● cli/_workspace.py<br/>━━━━━━━━━━<br/>run_workspace_clean()<br/>discovers + removes worktrees"]
        AP["● cli/app.py<br/>━━━━━━━━━━<br/>workspace clean command"]
    end

    subgraph L3_SRV ["L3 — SERVER"]
        GIT["● server/git.py<br/>━━━━━━━━━━<br/>perform_merge()<br/>delegates cleanup to workspace/"]
    end

    %% VALID L1→L0 DEPENDENCIES %%
    WT -->|"imports CleanupResult<br/>SubprocessRunner"| CR
    WT -->|"imports SubprocessRunner"| SP
    CL -->|"imports core"| CR
    CU -->|"imports CleanupResult"| CR
    CS -->|"imports from core"| CR

    %% WORKSPACE AGGREGATION %%
    CL --> WI
    CU --> WI
    WT --> WI

    %% CONFIG AGGREGATION %%
    CS -->|"reads"| DY
    CS --> CI

    %% VALID L3→L1 DEPENDENCIES %%
    WI -->|"RUNS_DIR, WORKTREES_DIR<br/>list/remove_git_worktree<br/>remove_worktree_sidecar"| WS
    CI -->|"load_config → workspace field"| WS
    WI -->|"remove_git_worktree<br/>remove_worktree_sidecar"| GIT

    AP -->|"delegates to"| WS

    %% CLASS ASSIGNMENTS %%
    class WS,AP,GIT cli;
    class CR,SP stateNode;
    class CL,CU handler;
    class WT newComponent;
    class WI,CI phase;
    class CS,DY output;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue (●) | L3 Application | CLI commands and server tool handlers
|
| Teal | L0 Core | Foundation types: CleanupResult, SubprocessRunner |
| Orange (●) | L1 Workspace | Existing workspace service modules |
| Green (★) | New Component | `workspace/worktree.py` — new L1 module;
WORKTREES_DIR constant |
| Purple | L1 Aggregator | Package `__init__.py` re-export hubs |
| Dark Teal | L1 Config | Config settings and defaults YAML |

### Operational Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;

    subgraph CLI ["● CLI ENTRY POINTS"]
        direction LR
        WC["● autoskillit workspace clean<br/>━━━━━━━━━━<br/>--dir DIR (base search path)<br/>--force / -f (skip confirmation)"]
    end

    subgraph CFG ["★ CONFIGURATION (workspace section)"]
        direction TB
        WCR["★ workspace.worktree_root<br/>━━━━━━━━━━<br/>null → auto ../worktrees/<br/>Overridable via config layer"]
        RR["★ workspace.runs_root<br/>━━━━━━━━━━<br/>null → auto ../autoskillit-runs/<br/>Overridable via config layer"]
        YAML["● config/defaults.yaml<br/>━━━━━━━━━━<br/>workspace:<br/>  worktree_root: null<br/>  runs_root: null"]
    end

    subgraph SCAN ["● SCAN PHASE — Directory Discovery"]
        direction TB
        RS["● Runs Scan<br/>━━━━━━━━━━<br/>autoskillit-runs/<br/>filesystem ls → age partition"]
        WTS["● Worktree Scan<br/>━━━━━━━━━━<br/>git worktree list --porcelain<br/>+ filesystem union → age partition"]
    end

    subgraph REMOVE ["★ REMOVAL PHASE — Cleanup Execution"]
        direction TB
        RD["Runs Delete<br/>━━━━━━━━━━<br/>shutil.rmtree(path)<br/>for each stale run dir"]
        WTR["★ remove_git_worktree()<br/>━━━━━━━━━━<br/>git worktree remove --force<br/>→ shutil.rmtree fallback"]
        SC["★ remove_worktree_sidecar()<br/>━━━━━━━━━━<br/>.autoskillit/temp/worktrees/<br/><name>/ metadata cleanup"]
    end

    subgraph OUT ["OUTPUT / OBSERVABILITY"]
        direction TB
        CONSOLE["Console Summary<br/>━━━━━━━━━━<br/>Skipped (modified < 5h ago): N<br/>Will remove: N<br/>Cleaned N (M error(s))"]
        CR["CleanupResult<br/>━━━━━━━━━━<br/>deleted: [paths]<br/>skipped: [paths]<br/>failed: [(path, reason)]"]
    end

    %% FLOWS %%
    WC -->|"reads cfg.workspace.*"| WCR
    WC -->|"reads cfg.workspace.*"| RR
    YAML -->|"dynaconf layer"| WCR
    YAML -->|"dynaconf layer"| RR

    WCR -->|"resolves path for"| WTS
    RR -->|"resolves path for"| RS

    WC -->|"triggers"| RS
    WC -->|"triggers"| WTS

    RS -->|"stale entries"| RD
    WTS -->|"stale worktrees"| WTR
    WTR -->|"after git removal"| SC

    RD --> CR
    WTR --> CR
    SC --> CR
    CR --> CONSOLE

    %% CLASS ASSIGNMENTS %%
    class WC cli;
    class WCR,RR newComponent;
    class YAML phase;
    class RS,WTS handler;
    class RD handler;
    class WTR,SC newComponent;
    class CONSOLE,CR output;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue (●) | CLI | `workspace clean` command entry point |
| Green (★) | New Capability | New config keys, worktree removal
functions |
| Purple | Config Layer | defaults.yaml driving dynaconf resolution |
| Orange (●) | Scan Phase | Directory discovery and age partitioning |
| Dark Teal | Output | CleanupResult accumulator and console summary |

Closes #567

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/remediation-20260329-101738-520948/.autoskillit/temp/rectify/rectify_workspace-clean-worktrees_2026-03-29_120000_part_a.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

## Token Usage Summary

| Step | input | output | cached | count | time |
|------|-------|--------|--------|-------|------|
| group | 204 | 31.2k | 1.3M | 2 | 10m 37s |
| plan | 2.0k | 146.1k | 10.6M | 7 | 48m 30s |
| verify | 1.9k | 88.7k | 9.8M | 9 | 35m 16s |
| implement | 4.6k | 110.6k | 19.1M | 7 | 45m 55s |
| fix | 54 | 13.3k | 1.4M | 2 | 13m 1s |
| audit_impl | 3.0k | 24.7k | 876.9k | 1 | 23m 16s |
| **Total** | 11.8k | 414.7k | 43.1M | | 2h 56m |

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
…570)

## Summary

Addresses five cohesion audit findings (Issue #566): server-layer
correctness fixes (exception handling in CI watchers, MCP annotations on
clone tools, spurious `__all__` export), hook registry and skill
frontmatter alignment, CLAUDE.md documentation accuracy, and expanded
test coverage. Seven new test files and two structural realignments
close coverage gaps in the server, execution, recipe, and migration
layers. The `hooks.json` plugin manifest is regenerated and a CI step
added to keep it permanently current.

<details>
<summary>Individual Group Plans</summary>

### Group 1: Server-Layer Correctness Fixes (groupA)
Four targeted fixes in `src/autoskillit/server/` to eliminate structural
inconsistencies that compromise runtime reliability:

- **C1-2 / C1-3**: Add `annotations={"readOnlyHint": False}` to
`register_clone_status` and `batch_cleanup_clones` decorators in
`tools_clone.py` — both tools write to the clone registry or delete
directories; missing the annotation misleads MCP clients about
mutability.
- **C9-1**: Replace bare `raise` statements in `wait_for_ci` and
`wait_for_merge_queue` with explicit `return json.dumps({"success":
False, "error": str(exc)})`. Bare re-raises propagate through the
`finally` timing block to the `track_response_size` decorator, which
wraps them in `{"subtype": "tool_exception", "exit_code": -1}` — a
format inconsistent with these tools' own error schema.
- **C1-5**: Remove the `__all__` list from `tools_execution.py`. It is
the only `tools_*.py` file that defines `__all__`; the constant it
re-exports (`PIPELINE_FORBIDDEN_TOOLS`) is universally imported from
`autoskillit.core`, not from this module.

### Group 2: Hook Registry Sync and Skill Frontmatter (groupB)
Two cohesion fixes with no logic changes:

1. **C6-1**: Regenerate `src/autoskillit/hooks/hooks.json` from
`HOOK_REGISTRY`. The registry has grown to 10 entries (including
`unsafe_install_guard`, `token_summary_appender`,
`session_start_reminder`) but the previously-generated file was absent.
Re-running `generate_hooks_json()` creates a complete, up-to-date
manifest for Claude Code plugin auto-discovery.

2. **C1-11**: Add `hooks:` frontmatter to 16 `skills_extended/` SKILL.md
files that omit it, matching the echo-announcement pattern used by the
other 42 skills.

### Group 3: CLAUDE.md Documentation Accuracy Fixes (groupC)
Fix nine factual inaccuracies in `CLAUDE.md`: stale counts (StrEnums,
Protocols, doctor checks), wrong export name (`SessionSkillManager` →
`DefaultSessionSkillManager`), four missing architecture-tree entries,
an incomplete `tools_clone.py` description, two missing CLI commands,
and abbreviated public-surface summaries for `pipeline/` and
`migration/`. All changes are documentation-only; no source code is
modified.

### Group 4: Test Coverage and Structural Alignment (groupD)
Three coordinated changes close test gaps and fix two structural test
misplacements:

- **C5-3** — Move two misplaced test files (`test_llm_triage.py`,
`test_smoke_utils.py`) to match their source module locations and fix
one stale docstring.
- **C5-2** — Add behavioral tests for
`migration/_api.py::check_and_migrate` (previously zero behavioral
coverage).
- **C5-1** — Create seven dedicated test files for source modules that
had none.

### Group 5: Generate hooks.json from HOOK_REGISTRY (C6-1 Remediation)
`src/autoskillit/hooks/hooks.json` was absent from disk. The groupB
commit added `hooks:` frontmatter to 16 SKILL.md files but never ran the
generation step. Fix has three parts:
1. **Regression test** — `test_hooks_json_on_disk_exists_and_matches`
reads the on-disk file and asserts it matches `generate_hooks_json()`.
2. **CI generation step** — Added to `.github/workflows/tests.yml`
before `task test-all` so CI generates the file on every run.
3. **Immediate generation** — The file is produced on disk.

</details>

## Architecture Impact

### Operational Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000;

    RECIPE([Recipe Orchestrator])

    subgraph Gate ["GATE + DECORATOR LAYER"]
        GATE["_require_enabled()<br/>━━━━━━━━━━<br/>kitchen gate — blocks until<br/>open_kitchen called"]
        HEADLESS["_require_not_headless()<br/>━━━━━━━━━━<br/>blocks run_cmd / run_skill<br/>from headless sessions"]
        DEC["@track_response_size<br/>━━━━━━━━━━<br/>records size per tool call<br/>catches unhandled exceptions<br/>→ {subtype: tool_exception}"]
    end

    subgraph CI ["● tools_ci.py — CI Polling Tools"]
        WCI["● wait_for_ci<br/>━━━━━━━━━━<br/>readOnlyHint: True<br/>tags: kitchen, ci"]
        WMQ["● wait_for_merge_queue<br/>━━━━━━━━━━<br/>readOnlyHint: False<br/>tags: kitchen, ci"]
        GCS["get_ci_status<br/>━━━━━━━━━━<br/>readOnlyHint: True"]
        SCS["set_commit_status<br/>━━━━━━━━━━<br/>readOnlyHint: True"]
        TAM["toggle_auto_merge<br/>━━━━━━━━━━<br/>readOnlyHint: False"]
    end

    subgraph CIErr ["★ C9-1: Error Boundary Fix"]
        ERRFIX["★ return json.dumps<br/>━━━━━━━━━━<br/>{success: false, error: str(exc)}<br/>replaces bare raise in<br/>wait_for_ci + wait_for_merge_queue"]
    end

    subgraph Clone ["● tools_clone.py — Clone Lifecycle"]
        CR["clone_repo"]
        RC["remove_clone"]
        PT["push_to_remote"]
        RCS["● register_clone_status<br/>━━━━━━━━━━<br/>★ readOnlyHint: False<br/>(C1-2: corrected annotation)"]
        BCC["● batch_cleanup_clones<br/>━━━━━━━━━━<br/>★ readOnlyHint: False<br/>(C1-3: corrected annotation)"]
    end

    subgraph Exec ["● tools_execution.py — Execution Tools"]
        RCMD["run_cmd<br/>━━━━━━━━━━<br/>bash -c in cwd<br/>headless-blocked"]
        RPY["run_python<br/>━━━━━━━━━━<br/>dotted-path import + call<br/>sync/async"]
        RSK["run_skill<br/>━━━━━━━━━━<br/>headless session launcher<br/>headless-blocked"]
        NOALL["● __all__ removed (C1-5)<br/>━━━━━━━━━━<br/>PIPELINE_FORBIDDEN_TOOLS<br/>imported from core/ only"]
    end

    RECIPE --> GATE
    GATE --> WCI & WMQ & GCS & SCS & TAM
    GATE --> RCS & BCC & CR & RC & PT
    GATE --> HEADLESS
    HEADLESS --> RCMD & RSK & RPY
    WCI --> CIErr
    WMQ --> CIErr
    DEC -.->|wraps all| GATE

    class RECIPE cli;
    class GATE,HEADLESS detector;
    class DEC phase;
    class WCI,WMQ,GCS,SCS,TAM handler;
    class CR,RC,PT,RCS,BCC handler;
    class RCMD,RPY,RSK handler;
    class ERRFIX newComponent;
    class NOALL output;
```

### Development Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000;

    subgraph CI ["● .github/workflows/tests.yml — CI Pipeline"]
        INSTALL["uv sync<br/>━━━━━━━━━━<br/>install dependencies"]
        GENHOOKS["★ Generate hooks.json<br/>━━━━━━━━━━<br/>uv run python -c<br/>generate_hooks_json() → atomic_write<br/>(C6-1: new CI step)"]
        GENDIAG["generate recipe diagrams"]
        TESTALL["task test-all<br/>━━━━━━━━━━<br/>lint + full test suite"]
        INSTALL --> GENHOOKS --> GENDIAG --> TESTALL
    end

    subgraph Infra ["● tests/infra/ — Hook Registry Guards"]
        HEXEC["test_hook_executability<br/>test_hook_registry_matches_generated<br/>test_hook_scripts_exist_on_disk"]
        HNEW["★ test_hooks_json_on_disk_exists_and_matches<br/>━━━━━━━━━━<br/>reads hooks/hooks.json<br/>asserts == generate_hooks_json()"]
        HEXEC --> HNEW
    end

    subgraph MigrationTests ["● tests/migration/test_api.py — check_and_migrate"]
        TMIG["● behavioral tests (C5-2)<br/>━━━━━━━━━━<br/>recipe-not-found · up-to-date<br/>migration-success · migration-failed<br/>llm-blocked · version-passthrough"]
    end

    subgraph ServerTests ["● tests/server/ — Server Layer Coverage"]
        TCCI["● test_tools_ci.py<br/>━━━━━━━━━━<br/>● C9-1: exception-boundary tests<br/>wait_for_ci / wait_for_merge_queue<br/>structured JSON vs bare raise"]
        TGIT["★ test_tools_github.py<br/>━━━━━━━━━━<br/>fetch_github_issue<br/>get_issue_title"]
        TISS["★ test_tools_issue_lifecycle.py<br/>━━━━━━━━━━<br/>prepare_issue · enrich_issues<br/>claim_issue · release_issue"]
        TPRO["★ test_tools_pr_ops.py<br/>━━━━━━━━━━<br/>get_pr_reviews<br/>bulk_close_issues"]
    end

    subgraph NewTests ["★ New Test Files — Coverage Gaps Closed"]
        TPRA["★ tests/execution/test_pr_analysis.py<br/>━━━━━━━━━━<br/>extract_linked_issues<br/>is_valid_fidelity_finding<br/>partition_files_by_domain"]
        TRG["★ tests/recipe/test_rules_graph.py<br/>━━━━━━━━━━<br/>unbounded-cycle · on-result-missing-failure-route<br/>push-before-audit · clone-root-as-worktree<br/>merge-base-unpublished"]
        TRM["★ tests/recipe/test_rules_merge.py<br/>━━━━━━━━━━<br/>merge-routing-incomplete"]
        TRR["★ tests/recipe/test_repository.py<br/>━━━━━━━━━━<br/>DefaultRecipeRepository<br/>mtime caching · delegation"]
    end

    subgraph Moved ["● Renamed Tests — Structural Alignment (C5-3)"]
        TLT["● tests/test_llm_triage.py<br/>━━━━━━━━━━<br/>moved from tests/execution/<br/>→ matches src/autoskillit/_llm_triage.py"]
        TSU["● tests/test_smoke_utils.py<br/>━━━━━━━━━━<br/>moved from tests/recipe/<br/>→ matches src/autoskillit/smoke_utils.py"]
    end

    TESTALL --> Infra
    TESTALL --> MigrationTests
    TESTALL --> ServerTests
    TESTALL --> NewTests
    TESTALL --> Moved

    class INSTALL,GENDIAG phase;
    class GENHOOKS newComponent;
    class TESTALL handler;
    class HEXEC handler;
    class HNEW newComponent;
    class TMIG handler;
    class TCCI handler;
    class TGIT,TISS,TPRO newComponent;
    class TPRA,TRG,TRM,TRR newComponent;
    class TLT,TSU output;
```

### Module Dependency Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 70, 'curve': 'basis'}}}%%
graph TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef integration fill:#c62828,stroke:#ef9a9a,stroke-width:2px,color:#fff;

    subgraph L3 ["L3 — SERVER (changed)"]
        direction LR
        TCI["● server/tools_ci.py<br/>━━━━━━━━━━<br/>wait_for_ci<br/>wait_for_merge_queue<br/>C9-1: error boundary"]
        TCL["● server/tools_clone.py<br/>━━━━━━━━━━<br/>register_clone_status<br/>batch_cleanup_clones<br/>C1-2/C1-3: readOnlyHint"]
        TEX["● server/tools_execution.py<br/>━━━━━━━━━━<br/>run_cmd · run_python · run_skill<br/>C1-5: __all__ removed"]
    end

    subgraph L2 ["L2 — DOMAIN"]
        direction LR
        RECIPE["recipe/<br/>━━━━━━━━━━<br/>schema · validation<br/>semantic rules"]
        MIGRATION["migration/<br/>━━━━━━━━━━<br/>MigrationEngine<br/>check_and_migrate"]
    end

    subgraph L1 ["L1 — SERVICES"]
        direction LR
        EXEC["execution/<br/>━━━━━━━━━━<br/>ci.py · merge_queue.py<br/>headless.py · pr_analysis.py"]
        PIPE["pipeline/<br/>━━━━━━━━━━<br/>context · gate<br/>timings · tokens"]
        WORK["workspace/<br/>━━━━━━━━━━<br/>clone_registry<br/>session_skills"]
    end

    subgraph L0 ["L0 — FOUNDATION (high fan-in)"]
        CORE["core/<br/>━━━━━━━━━━<br/>types · protocols<br/>PIPELINE_FORBIDDEN_TOOLS<br/>★ C1-5: tools_execution imports<br/>PIPELINE_FORBIDDEN_TOOLS from here"]
    end

    subgraph Tests ["TEST SUITE (new coverage — ★)"]
        direction LR
        T_SERVER["★ tests/server/<br/>━━━━━━━━━━<br/>★ test_tools_github.py<br/>★ test_tools_issue_lifecycle.py<br/>★ test_tools_pr_ops.py<br/>● test_tools_ci.py"]
        T_EXEC["★ tests/execution/<br/>━━━━━━━━━━<br/>★ test_pr_analysis.py"]
        T_RECIPE["★ tests/recipe/<br/>━━━━━━━━━━<br/>★ test_rules_graph.py<br/>★ test_rules_merge.py<br/>★ test_repository.py"]
        T_MIG["tests/migration/<br/>━━━━━━━━━━<br/>● test_api.py<br/>(C5-2 behavioral tests)"]
        T_TOP["● tests/ (top-level)<br/>━━━━━━━━━━<br/>● test_llm_triage.py<br/>● test_smoke_utils.py<br/>(C5-3: moved to match src)"]
    end

    %% VALID L3 → L1 DEPENDENCIES %%
    TCI -->|"imports ci.py<br/>merge_queue.py"| EXEC
    TCI -->|"imports gate<br/>timings"| PIPE
    TCL -->|"imports clone_registry"| WORK
    TCL -->|"imports gate · timings"| PIPE
    TEX -->|"imports headless.py"| EXEC
    TEX -->|"imports gate · timings"| PIPE

    %% VALID L3 → L0 DEPENDENCIES %%
    TEX -->|"★ PIPELINE_FORBIDDEN_TOOLS<br/>imported directly from core/"| CORE

    %% VALID L2 DEPENDENCIES %%
    RECIPE --> CORE
    MIGRATION --> CORE

    %% VALID L1 → L0 DEPENDENCIES %%
    EXEC --> CORE
    PIPE --> CORE
    WORK --> CORE

    %% TEST COVERAGE %%
    T_SERVER -.->|"tests"| TCI & TCL & TEX
    T_EXEC -.->|"tests"| EXEC
    T_RECIPE -.->|"tests"| RECIPE
    T_MIG -.->|"tests"| MIGRATION

    %% CLASS ASSIGNMENTS %%
    class TCI,TCL,TEX cli;
    class RECIPE,MIGRATION phase;
    class EXEC,PIPE,WORK handler;
    class CORE stateNode;
    class T_SERVER,T_EXEC,T_RECIPE newComponent;
    class T_MIG,T_TOP output;
```

Closes #566

## Implementation Plan

Plan files:
-
`.autoskillit/temp/make-plan/server_layer_correctness_plan_2026-03-29_103500.md`
-
`.autoskillit/temp/make-plan/hook_registry_skill_frontmatter_plan_2026-03-29_103500.md`
-
`.autoskillit/temp/make-plan/claude_md_accuracy_fixes_plan_2026-03-29_103500.md`
-
`.autoskillit/temp/make-plan/groupD_test_coverage_structural_alignment_plan_2026-03-29_120000.md`
-
`.autoskillit/temp/make-plan/hooks_json_generation_plan_2026-03-29_133000.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

## Token Usage Summary

| Step | input | output | cached | count | time |
|------|-------|--------|--------|-------|------|
| group | 204 | 31.2k | 1.3M | 2 | 10m 37s |
| plan | 2.0k | 146.1k | 10.6M | 7 | 48m 30s |
| verify | 1.9k | 88.7k | 9.8M | 9 | 35m 16s |
| implement | 4.6k | 110.6k | 19.1M | 7 | 45m 55s |
| fix | 54 | 13.3k | 1.4M | 2 | 13m 1s |
| audit_impl | 4.3k | 61.8k | 2.0M | 3 | 37m 55s |
| open_pr | 40 | 29.0k | 1.7M | 1 | 10m 12s |
| **Total** | 13.1k | 480.7k | 45.8M | | 3h 21m |

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
…ates (#571)

## Summary

Adds two mandatory quality gates to the audit-arch skill's workflow to
address the 31% false-positive rate identified in GitHub issue #555. A
pre-flight verification checklist (IMP-001–IMP-005) requires auditors to
complete concrete tool-call checks before raising findings in five
false-positive-prone categories, and a self-validation pass (IMP-006)
mandates re-reading every HIGH/CRITICAL cited location and confirming or
revising each finding before the report is finalized. Contract tests
covering both gates are added in the test suite.

<details>
<summary>Individual Group Plans</summary>

### Group 1: Pre-Flight Verification Checklist for audit-arch (groupA)
Add a mandatory pre-flight verification checklist as step 1 of the
`audit-arch` skill's Audit Workflow in
`src/autoskillit/skills_extended/audit-arch/SKILL.md`. The checklist
installs five read-before-report gates (IMP-001 through IMP-005) that
auditors must complete before raising a finding in any of five
false-positive-prone categories identified in the 2026-03-28 audit
validation (31% false positive rate, GitHub issue #555). Each gate
specifies a trigger condition and a concrete tool call. The existing
steps 1–6 are renumbered 2–7. No files outside
`skills_extended/audit-arch/SKILL.md` are modified.

### Group 2: Self-Validation Pass for audit-arch (IMP-006)
Add a **Self-Validation Pass** as a new numbered workflow step in
`src/autoskillit/skills_extended/audit-arch/SKILL.md`. The pass is
inserted after the cross-reference step and the optional
principle-suggestion step, just before "Write report" — making it the
final quality gate before the report is finalized. The pass mandates
four concrete spot-checks: (a) re-read every HIGH/CRITICAL finding's
cited code location, (b) read the concrete class body (not just the
Protocol) for resource-leak and data-loss findings, (c) confirm
enforcement-gap findings had their `tests/` Grep actually performed, and
(d) record an internal `CONFIRMED` or `REVISED` note per reviewed
finding. Contract tests T-AA-011 through T-AA-016 are added to
`tests/skills/test_audit_arch_selfvalidation_contracts.py`.

</details>

## Architecture Impact

### Process Flow Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 40, 'rankSpacing': 50, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;

    %% TERMINALS %%
    START([START])
    END([END])

    %% STEP 1: PRE-FLIGHT %%
    subgraph PF ["★ Step 1 — Pre-Flight Verification Checklist (IMP-001–005)"]
        direction LR
        G1["★ IMP-001 Missing Export<br/>━━━━━━━━━━<br/>Read __init__.py + __all__<br/>Discard if symbol present"]
        G2["★ IMP-002 Missing Decorator<br/>━━━━━━━━━━<br/>Read class def (3–5 lines pre-class)<br/>Discard if decorator present"]
        G3["★ IMP-003 Enforcement Gap<br/>━━━━━━━━━━<br/>Grep tests/ for symbol<br/>Discard if test found"]
        G4["★ IMP-004 Code Duplication<br/>━━━━━━━━━━<br/>Read full bodies, compare logic<br/>Discard if logically distinct"]
        G5["★ IMP-005 Misplaced File<br/>━━━━━━━━━━<br/>Bash: git log -- file_path<br/>Discard if commit explains placement"]
    end

    %% STEP 2–4: EXECUTION %%
    subgraph Exec ["● Steps 2–4 — Parallel Audit & Consolidation"]
        direction TB
        LA["● Launch Parallel Subagents<br/>━━━━━━━━━━<br/>11 principles in parallel<br/>Pre-flight constraints carried"]
        CF["● Consolidate Findings<br/>━━━━━━━━━━<br/>Group by principle + severity<br/>Cross-principle re-routing"]
        XR["● Cross-Reference<br/>━━━━━━━━━━<br/>Re-categorize by violated principle<br/>(e.g., P1 file-first loading)"]
    end

    %% STEP 5: OPTIONAL SUGGESTION %%
    subgraph Suggest ["● Step 5 — Optional Principle Suggestion"]
        SP{"● All 4 criteria met?<br/>━━━━━━━━━━<br/>non-one-off · uncovered ·<br/>prevents debt · HIGH/CRIT"}
        NS["● Suggest New Principle<br/>━━━━━━━━━━<br/>1-sentence rule +<br/>2–3 motivating locations"]
    end

    %% STEP 6: SELF-VALIDATION %%
    subgraph SV ["★ Step 6 — Self-Validation Pass (IMP-006)"]
        direction TB
        SVA["★ (a) HIGH/CRIT Re-Read<br/>━━━━━━━━━━<br/>Read exact file:line cited<br/>Downgrade/remove if no evidence"]
        SVB["★ (b) Concrete-Class Check<br/>━━━━━━━━━━<br/>Read concrete body not Protocol<br/>for resource-leak / data-loss"]
        SVC["★ (c) Enforcement Search<br/>━━━━━━━━━━<br/>Grep tests/ if not yet done<br/>Discard if matching test exists"]
        SVD["★ (d) Validation Notes<br/>━━━━━━━━━━<br/>CONFIRMED or REVISED<br/>per reviewed finding (internal)"]
    end

    %% STEP 7–8: OUTPUT %%
    subgraph ReportOut ["● Steps 7–8 — Report Output"]
        WR["● Write Report<br/>━━━━━━━━━━<br/>.autoskillit/temp/audit-arch/<br/>arch_audit_YYYY-MM-DD_HHMMSS.md"]
        OS["● Output Summary<br/>━━━━━━━━━━<br/>Print to terminal"]
    end

    %% NEW TEST FILES %%
    subgraph Tests ["★ New Contract Tests"]
        direction LR
        TC1["★ test_audit_arch_preflight_contracts.py<br/>━━━━━━━━━━<br/>T-AA-001 through T-AA-010<br/>Pre-flight gate contracts"]
        TC2["★ test_audit_arch_selfvalidation_contracts.py<br/>━━━━━━━━━━<br/>T-AA-011 through T-AA-016<br/>Self-validation pass contracts"]
    end

    %% FLOW %%
    START --> G1
    START --> G2
    START --> G3
    START --> G4
    START --> G5
    G1 --> LA
    G2 --> LA
    G3 --> LA
    G4 --> LA
    G5 --> LA
    LA --> CF
    CF --> XR
    XR --> SP
    SP -->|"Yes"| NS
    SP -->|"No / After"| SVA
    NS --> SVA
    SVA --> SVB
    SVB --> SVC
    SVC --> SVD
    SVD --> WR
    WR --> OS
    OS --> END

    TC1 -.->|"contracts"| G1
    TC1 -.->|"contracts"| G2
    TC1 -.->|"contracts"| G3
    TC1 -.->|"contracts"| G4
    TC1 -.->|"contracts"| G5
    TC2 -.->|"contracts"| SVA
    TC2 -.->|"contracts"| SVB
    TC2 -.->|"contracts"| SVC
    TC2 -.->|"contracts"| SVD

    %% CLASS ASSIGNMENTS %%
    class START,END terminal;
    class G1,G2,G3,G4,G5 newComponent;
    class SVA,SVB,SVC,SVD newComponent;
    class TC1,TC2 newComponent;
    class LA,CF,XR phase;
    class NS handler;
    class SP stateNode;
    class WR stateNode;
    class OS output;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | Terminal | START and END states |
| Green (★) | New Component | New workflow gates and test files added by
this PR |
| Purple | Phase | Existing audit execution and consolidation steps (●)
|
| Orange | Handler | Principle suggestion handler (●) |
| Teal (dark) | State | Decision point and report write step (●) |
| Dark Teal | Output | Terminal summary output |

Closes #555

## Implementation Plan

Plan files:
-
`/home/talon/projects/autoskillit-runs/impl-20260329-104328-317272/.autoskillit/temp/make-plan/groupA_preflight_checklist_plan_2026-03-29_110100.md`
-
`/home/talon/projects/autoskillit-runs/impl-20260329-104328-317272/.autoskillit/temp/make-plan/groupB_selfvalidation_pass_plan_2026-03-29_110500.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

## Token Usage Summary

| Step | input | output | cached | count | time |
|------|-------|--------|--------|-------|------|
| group | 204 | 31.2k | 1.3M | 2 | 10m 37s |
| plan | 2.0k | 146.1k | 10.6M | 7 | 48m 30s |
| verify | 1.9k | 88.7k | 9.8M | 9 | 35m 16s |
| implement | 4.6k | 110.6k | 19.1M | 7 | 45m 55s |
| fix | 54 | 13.3k | 1.4M | 2 | 13m 1s |
| audit_impl | 4.3k | 61.8k | 2.0M | 3 | 37m 55s |
| open_pr | 64 | 43.0k | 2.4M | 2 | 15m 18s |
| **Total** | 13.2k | 494.7k | 46.5M | | 3h 26m |

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
… Validated Report (#573)

## Summary

`prepare-issue` treats all input identically: it summarizes the input
into a structured body
and then (for `recipe:implementation` issues) appends a `##
Requirements` section. When the
input is a validated audit report (a file beginning with `validated:
true`), this behavior is
wrong on two counts:

1. The full finding details (file:line, verdicts, severity adjustments,
exception notes) are
   replaced by a condensed summary.
2. A `## Requirements` section is generated and appended — but a
validated report IS the
   specification; requirements are redundant and clutter the issue.

The fix adds validated report detection at Step 1b, a new body
construction path in Step 5
that preserves full findings while stripping artifact paths and
contested findings references,
and an explicit skip gate at Step 7a. Contract tests enforce all new
contracts. No Python
code changes are required — the fix is entirely within the
`prepare-issue` SKILL.md.

## Architecture Impact

### Process Flow Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 40, 'rankSpacing': 50, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;

    START([START])
    COMPLETE([COMPLETE])
    ABORT([ABORT])

    subgraph S1 ["Step 1 — Argument Parsing"]
        ParseArgs["ParseArgs<br/>━━━━━━━━━━<br/>flags, description,<br/>repo, issue_number"]
    end

    subgraph S1b ["● Step 1b — Validated Report Detection"]
        DetectReport{"● Input is validated<br/>audit report?<br/>━━━━━━━━━━<br/>first line == 'validated: true'"}
    end

    subgraph S23 ["Steps 2–3 — Auth & Repo"]
        Auth["gh auth status<br/>Resolve repo"]
    end

    subgraph S4 ["Step 4 — Dedup"]
        Dedup["Keyword search<br/>Collect candidates"]
        DedupChoice{"Extend existing<br/>or create new?"}
    end

    subgraph S4a ["Step 4a — Draft & Confirm"]
        Draft["Display draft issue<br/>Wait for Y/n/edit"]
        DraftChoice{"Y / n / edit?"}
    end

    subgraph S5val ["● Step 5 — Validated Report Body"]
        ReadReport["● Read full report<br/>━━━━━━━━━━<br/>from report_path"]
        StripArtifacts["● Strip artifact paths<br/>━━━━━━━━━━<br/>Remove: 'validated: true'<br/>Remove: 'Original report:' line<br/>Remove: contested findings ref<br/>Remove: Contested count"]
        BuildBody["● Build issue body<br/>━━━━━━━━━━<br/>Keep: Validation Status<br/>Keep: Validated Findings<br/>Keep: Findings w/ Exceptions"]
    end

    subgraph S5std ["Step 5 — Standard Body"]
        StandardBody["Derive title + body<br/>from description"]
    end

    subgraph S5c ["Step 5c — Create Issue"]
        CreateIssue["gh issue create<br/>capture URL + number"]
    end

    subgraph S6 ["Step 6 — LLM Classification"]
        Classify["Classify: route + issue_type<br/>confidence"]
        ConfGate{"confidence == low?"}
        UserConfirm["Present classification<br/>await user override"]
    end

    subgraph S7a ["● Step 7a — Requirement Generation Gate"]
        ReqGate{"● is_validated_report?"}
        SkipReq["● Skip requirements<br/>━━━━━━━━━━<br/>validated report IS<br/>the specification<br/>requirements_generated: false"]
        GenReq["Generate REQ-* groups<br/>Append ## Requirements"]
    end

    subgraph S89 ["Steps 8–9 — Mixed Concern & Labels"]
        MixedConcern["Mixed-concern detection"]
        Labels["Apply recipe + type labels"]
    end

    Result["Emit prepare-issue-result<br/>━━━━━━━━━━<br/>issue_url, route, labels,<br/>requirements_generated"]

    START --> ParseArgs
    ParseArgs --> DetectReport

    DetectReport -->|"YES: is_validated_report=true"| ReadReport
    DetectReport -->|"NO: standard input"| Auth

    ReadReport --> StripArtifacts --> BuildBody
    BuildBody --> Auth

    Auth --> Dedup
    Dedup --> DedupChoice
    DedupChoice -->|"extend existing"| CreateIssue
    DedupChoice -->|"create new"| Draft

    Draft --> DraftChoice
    DraftChoice -->|"n"| ABORT
    DraftChoice -->|"edit"| Draft
    DraftChoice -->|"Y"| StandardBody
    StandardBody --> CreateIssue

    CreateIssue --> Classify
    Classify --> ConfGate
    ConfGate -->|"yes"| UserConfirm
    ConfGate -->|"no"| ReqGate
    UserConfirm --> ReqGate

    ReqGate -->|"is_validated_report=true"| SkipReq
    ReqGate -->|"route=implementation"| GenReq
    ReqGate -->|"route=remediation"| MixedConcern

    SkipReq --> MixedConcern
    GenReq --> MixedConcern

    MixedConcern --> Labels --> Result --> COMPLETE

    %% CLASS ASSIGNMENTS %%
    class START,COMPLETE,ABORT terminal;
    class ParseArgs,Auth,Dedup,Draft,CreateIssue,Classify,UserConfirm,MixedConcern,Labels,Result handler;
    class DedupChoice,DraftChoice,ConfGate stateNode;
    class DetectReport,ReqGate detector;
    class ReadReport,StripArtifacts,BuildBody,SkipReq newComponent;
    class StandardBody,GenReq phase;
```

### State Lifecycle Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;

    subgraph Lifecycles ["FIELD LIFECYCLE CATEGORIES"]
        direction LR
        INIT_ONLY["INIT_ONLY<br/>━━━━━━━━━━<br/>● is_validated_report<br/>dry_run, split<br/>● report_path<br/>Set once — never modify"]
        INIT_PRESERVE["INIT_PRESERVE<br/>━━━━━━━━━━<br/>route, issue_type<br/>confidence, rationale<br/>Set at classification<br/>preserved to result"]
        MUTABLE["MUTABLE<br/>━━━━━━━━━━<br/>● requirements_generated<br/>requirements_appended<br/>issue_number<br/>Updated by step outcome"]
        APPEND_ONLY["APPEND_ONLY<br/>━━━━━━━━━━<br/>sub_issues<br/>labels_applied<br/>Can only grow"]
    end

    subgraph Gates ["VALIDATION GATES (● test_prepare_issue_contracts.py)"]
        direction TB
        GATE_DETECT["● Detection Gate<br/>━━━━━━━━━━<br/>test_detects_validated_audit_report_input<br/>MUST: 'validated: true' in SKILL.md<br/>MUST: 'is_validated_report' in SKILL.md"]
        GATE_SKIP["● Skip-Req Gate<br/>━━━━━━━━━━<br/>test_skips_requirements_for_validated_report<br/>MUST: Step 7a references is_validated_report<br/>MUST: 'skip' keyword present in Step 7a"]
        GATE_STRIP["● Strip Gate<br/>━━━━━━━━━━<br/>test_excludes_contested_refs<br/>test_strips_artifact_paths<br/>MUST: 'contested_findings_' in body rules<br/>MUST: 'Original report' stripped"]
        GATE_RESULT["Result Schema Gate<br/>━━━━━━━━━━<br/>test_result_block_includes_requirements_generated<br/>MUST: requirements_generated in result block"]
        GATE_ROUTE["Route Gate<br/>━━━━━━━━━━<br/>test_generates_requirements_on_implementation_route<br/>test_skips_requirements_on_remediation<br/>MUST: req gen after implementation route ref"]
    end

    subgraph Contracts ["CONTRACT ENFORCEMENT STRATEGY"]
        direction TB
        STATIC_READ["Static Text Analysis<br/>━━━━━━━━━━<br/>SKILL_MD.read_text()<br/>String/position assertions<br/>Structural ordering"]
        YAML_PARSE["YAML Frontmatter Parse<br/>━━━━━━━━━━<br/>yaml.safe_load(parts[1])<br/>Trigger phrase validation"]
        SECTION_ANCHOR["Section Anchoring<br/>━━━━━━━━━━<br/>text.find('### Step N')<br/>Scoped substring checks<br/>Prevents false positives"]
    end

    subgraph Result ["RESULT BLOCK (write-only output)"]
        direction TB
        ResultBlock["---prepare-issue-result---<br/>━━━━━━━━━━<br/>issue_url, issue_number<br/>route, issue_type<br/>● requirements_generated<br/>● requirements_appended<br/>labels_applied, dry_run"]
    end

    INIT_ONLY -->|"is_validated_report gates"| GATE_DETECT
    INIT_ONLY -->|"report_path gates"| GATE_STRIP
    INIT_PRESERVE -->|"route gates"| GATE_ROUTE
    MUTABLE -->|"requirements_generated in"| GATE_RESULT

    GATE_DETECT --> STATIC_READ
    GATE_SKIP --> SECTION_ANCHOR
    GATE_STRIP --> STATIC_READ
    GATE_RESULT --> STATIC_READ
    GATE_ROUTE --> STATIC_READ

    STATIC_READ --> ResultBlock
    YAML_PARSE --> ResultBlock
    SECTION_ANCHOR --> ResultBlock

    APPEND_ONLY -->|"labels_applied in"| ResultBlock

    %% CLASS ASSIGNMENTS %%
    class INIT_ONLY detector;
    class INIT_PRESERVE gap;
    class MUTABLE phase;
    class APPEND_ONLY handler;
    class GATE_DETECT,GATE_SKIP,GATE_STRIP newComponent;
    class GATE_RESULT,GATE_ROUTE stateNode;
    class STATIC_READ,YAML_PARSE,SECTION_ANCHOR output;
    class ResultBlock cli;
```

Closes #553

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/impl-20260329-215040-085783/.autoskillit/temp/make-plan/bug_prepare_issue_validated_report_plan_2026-03-29_000000.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

## Token Usage Summary

| Step | input | output | cached | count | time |
|------|-------|--------|--------|-------|------|
| plan | 97 | 47.1k | 5.1M | 2 | 15m 35s |
| verify | 58 | 43.6k | 4.0M | 2 | 12m 52s |
| implement | 171 | 65.0k | 14.0M | 2 | 22m 11s |
| fix | 59 | 14.3k | 1.7M | 2 | 10m 31s |
| audit_impl | 77 | 32.4k | 1.3M | 2 | 10m 37s |
| open_pr | 33 | 16.8k | 1.1M | 1 | 5m 21s |
| **Total** | 495 | 219.3k | 27.1M | | 1h 17m |

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
## Summary

Token telemetry aggregates across all issues processed in a single
kitchen session because
`kitchen_id` (the only scoping identifier) covers the entire kitchen
lifetime. When an
orchestrator processes issues #185, #186, and #189 sequentially, all
three share one
`kitchen_id`; the `token_summary_appender` hook and the in-memory
`DefaultTokenLog` therefore
aggregate all three into every PR's token table.

The fix introduces `order_id` — a caller-supplied per-issue identifier —
and propagates it
through both telemetry data paths: the in-memory
`DefaultTokenLog`/`DefaultTimingLog` (keyed
by `(order_id, step_name)` instead of just `step_name`) and the
disk-based `sessions.jsonl`
(with `order_id` written to each entry). Additionally, `pipeline_id` is
renamed to `kitchen_id`
throughout to clarify the scoping hierarchy.

## Requirements

### ID — Order Identity

- **REQ-ID-001:** `run_skill` must accept an optional `order_id`
parameter that identifies which order (issue) a step belongs to.
- **REQ-ID-002:** The `order_id` must be distinct from `kitchen_id` —
`kitchen_id` scopes to the kitchen session, `order_id` scopes to a
single issue being processed.
- **REQ-ID-003:** The `order_id` must be caller-supplied (e.g., issue
number, issue URL, or orchestrator-chosen identifier) — not
auto-generated internally.

### PROP — Propagation

- **REQ-PROP-001:** `run_skill` must propagate `order_id` through
`run_headless_core` to `flush_session_log`.
- **REQ-PROP-002:** `flush_session_log` must write `order_id` to the
`sessions.jsonl` index entry alongside `kitchen_id`.
- **REQ-PROP-003:** The `order_id` must be available to the
`token_summary_appender` hook — either via `hook_config.json`, the
`run_skill` tool response, or the `sessions.jsonl` entry associated with
the PR-producing session.

### LOG — In-Memory Log Scoping

- **REQ-LOG-001:** `DefaultTokenLog` must key entries by `(order_id,
step_name)` instead of just `step_name`, so that two orders with the
same step names accumulate independently.
- **REQ-LOG-002:** `DefaultTimingLog` must apply the same `(order_id,
step_name)` keying.
- **REQ-LOG-003:** `DefaultTokenLog.record()` must accept and store the
`order_id` associated with each entry.
- **REQ-LOG-004:** `DefaultTokenLog` must support querying entries
filtered by `order_id`.
- **REQ-LOG-005:** `DefaultTimingLog` must support querying entries
filtered by `order_id`.

### TOOL — MCP Tool Interface

- **REQ-TOOL-001:** `get_token_summary` must accept an optional
`order_id` parameter to scope results to a single order.
- **REQ-TOOL-002:** `get_timing_summary` must accept an optional
`order_id` parameter to scope results to a single order.
- **REQ-TOOL-003:** When `order_id` is not provided, the tools must
return data for all orders (backward-compatible default).

### HOOK — Token Summary Appender

- **REQ-HOOK-001:** `token_summary_appender` must filter
`sessions.jsonl` by `order_id` (not just `kitchen_id`).
- **REQ-HOOK-002:** The hook must produce accurate per-issue token
summaries when multiple issues are processed within a single kitchen
session.
- **REQ-HOOK-003:** The hook must produce correct summaries for parallel
pipeline executions (e.g., #185 and #186 running concurrently).

### COMPAT — Backward Compatibility

- **REQ-COMPAT-001:** Sessions logged before `order_id` support must not
cause errors — the system must gracefully handle missing `order_id` in
`sessions.jsonl` entries.
- **REQ-COMPAT-002:** `kitchen_id` must continue to function for
session-level correlation independent of `order_id`.
- **REQ-COMPAT-003:** `run_skill` calls without `order_id` must continue
to work (parameter is optional).

## Architecture Impact

### Data Lineage Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 70, 'curve': 'basis'}}}%%
flowchart LR
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef integration fill:#c62828,stroke:#ef9a9a,stroke-width:2px,color:#fff;

    subgraph Input ["Data Origins"]
        ORCH["● run_skill MCP tool<br/>━━━━━━━━━━<br/>order_id (caller-supplied)<br/>step_name, skill_command"]
        CTX["ToolContext<br/>━━━━━━━━━━<br/>kitchen_id (server-level)<br/>token_log, timing_log"]
    end

    subgraph Exec ["Execution Layer"]
        CORE["● run_headless_core<br/>━━━━━━━━━━<br/>receives (kitchen_id, order_id)<br/>routes to both sinks"]
    end

    subgraph MemStore ["In-Memory Storage (primary)"]
        direction TB
        TLOG["● DefaultTokenLog<br/>━━━━━━━━━━<br/>key: (order_id, step_name)<br/>was: key: step_name"]
        TIMLOG["● DefaultTimingLog<br/>━━━━━━━━━━<br/>key: (order_id, step_name)<br/>was: key: step_name"]
    end

    subgraph DiskStore ["Disk Storage (primary)"]
        direction TB
        SESS[("● sessions.jsonl<br/>━━━━━━━━━━<br/>+kitchen_id<br/>+order_id per entry")]
        TU[("token_usage.json<br/>━━━━━━━━━━<br/>+order_id field<br/>per session dir")]
    end

    subgraph Query ["Retrieval / Output"]
        direction TB
        GTOK["● get_token_summary<br/>━━━━━━━━━━<br/>order_id filter param<br/>→ scoped or all-orders"]
        GTIM["● get_timing_summary<br/>━━━━━━━━━━<br/>order_id filter param<br/>→ scoped or all-orders"]
        HOOK["● token_summary_appender<br/>━━━━━━━━━━<br/>extracts order_id from result<br/>filters sessions.jsonl by it"]
    end

    subgraph Artifact ["Write-Only Artifacts"]
        PR["GitHub PR body<br/>━━━━━━━━━━<br/>## Token Usage Summary<br/>(per-issue, accurate)"]
    end

    ORCH -->|"order_id + kitchen_id"| CORE
    CTX -->|"kitchen_id"| CORE
    CORE -->|"record(step, usage, order_id=)"| TLOG
    CORE -->|"record(step, secs, order_id=)"| TIMLOG
    CORE -->|"flush(kitchen_id, order_id)"| SESS
    CORE -->|"flush(kitchen_id, order_id)"| TU
    TLOG -->|"get_report(order_id=)"| GTOK
    TIMLOG -->|"get_report(order_id=)"| GTIM
    SESS -->|"filter by order_id"| HOOK
    TU -->|"read per matching session"| HOOK
    ORCH -->|"result JSON +order_id"| HOOK
    HOOK -.->|"gh api PATCH"| PR

    class ORCH handler;
    class CTX cli;
    class CORE handler;
    class TLOG,TIMLOG newComponent;
    class SESS,TU stateNode;
    class GTOK,GTIM handler;
    class HOOK integration;
    class PR output;
```

### State Lifecycle Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 65, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000;

    subgraph Protocols ["● Updated Protocol Contracts"]
        direction TB
        TSPROT["● TokenStore Protocol<br/>━━━━━━━━━━<br/>record(*, order_id: str = '')<br/>get_report(*, order_id: str = '')<br/>compute_total(*, order_id: str = '')"]
        TIMPROT["● TimingStore Protocol<br/>━━━━━━━━━━<br/>record(*, order_id: str = '')<br/>get_report(*, order_id: str = '')<br/>compute_total(*, order_id: str = '')"]
    end

    subgraph EntryKey ["● Composite Key Structure (INIT_ONLY per entry)"]
        direction LR
        KEY["● Composite Key: tuple[str, str]<br/>━━━━━━━━━━<br/>(order_id, canonical_step_name)<br/>was: str (step_name only)"]
        CANON["canonical_step_name()<br/>━━━━━━━━━━<br/>strips trailing -N suffix<br/>lossy / irreversible"]
    end

    subgraph Guards ["Validation Gates on record()"]
        direction LR
        GUARD1["Guard: step_name falsy?<br/>━━━━━━━━━━<br/>→ return early (no-op)"]
        GUARD2["Guard: token_usage None/empty?<br/>━━━━━━━━━━<br/>→ return early (no-op)"]
        GUARD3["Duration clamp<br/>━━━━━━━━━━<br/>max(0.0, duration_seconds)"]
    end

    subgraph Store ["● APPEND_ONLY State: _entries dict"]
        direction TB
        BUCKET_A["Bucket (order-A, plan)<br/>━━━━━━━━━━<br/>input_tokens += ...<br/>invocation_count += 1"]
        BUCKET_B["Bucket (order-B, plan)<br/>━━━━━━━━━━<br/>input_tokens += ...<br/>invocation_count += 1 (isolated)"]
        BUCKET_NONE["Bucket ('', plan)<br/>━━━━━━━━━━<br/>unscoped / legacy entries<br/>backward-compat bucket"]
    end

    subgraph Query ["Query Contracts (DERIVED)"]
        direction TB
        FILTER["get_report(order_id='X')<br/>━━━━━━━━━━<br/>returns only bucket X<br/>no cross-order leakage"]
        AGGS["get_report(order_id='')<br/>━━━━━━━━━━<br/>re-aggregates ALL buckets<br/>by step_name (backward compat)"]
    end

    subgraph Context ["● ToolContext State"]
        direction TB
        KID["● kitchen_id: str<br/>━━━━━━━━━━<br/>renamed from pipeline_id<br/>set by open_kitchen → uuid4()"]
        LOGS["token_log + timing_log<br/>━━━━━━━━━━<br/>held as TokenStore / TimingStore<br/>Protocol references"]
    end

    TSPROT --> GUARD1
    TIMPROT --> GUARD3
    GUARD1 --> GUARD2
    GUARD2 --> KEY
    GUARD3 --> KEY
    KEY --> CANON
    CANON --> BUCKET_A
    CANON --> BUCKET_B
    CANON --> BUCKET_NONE
    BUCKET_A --> FILTER
    BUCKET_B --> FILTER
    BUCKET_A --> AGGS
    BUCKET_B --> AGGS
    BUCKET_NONE --> AGGS
    KID --> LOGS
    LOGS --> TSPROT
    LOGS --> TIMPROT

    class TSPROT,TIMPROT phase;
    class KEY newComponent;
    class CANON handler;
    class GUARD1,GUARD2 detector;
    class GUARD3 gap;
    class BUCKET_A,BUCKET_B,BUCKET_NONE stateNode;
    class FILTER output;
    class AGGS output;
    class KID cli;
    class LOGS handler;
```

### Process Flow Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 45, 'rankSpacing': 60, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef integration fill:#c62828,stroke:#ef9a9a,stroke-width:2px,color:#fff;

    START(["MCP caller invokes run_skill"])

    subgraph MCP ["● MCP Entry (tools_execution.py)"]
        direction TB
        RUNSK["● run_skill()<br/>━━━━━━━━━━<br/>order_id param (new)<br/>kitchen_id from ctx"]
        CHKOID{"order_id<br/>present?"}
        INJECT["inject order_id<br/>into result JSON<br/>(for hook)"]
    end

    subgraph Exec ["● Execution (headless.py)"]
        direction TB
        CORE["● run_headless_core()<br/>━━━━━━━━━━<br/>kitchen_id + order_id<br/>both passed as params"]
        CHKCRASH{"crash path?"}
        FLUSH_CRASH["flush_session_log()<br/>━━━━━━━━━━<br/>kitchen_id, order_id<br/>(crash recovery)"]
        FLUSH_OK["flush_session_log()<br/>━━━━━━━━━━<br/>kitchen_id, order_id<br/>(normal completion)"]
        TOKREC["token_log.record()<br/>━━━━━━━━━━<br/>step_name + tokens<br/>order_id=order_id"]
        TIMREC["● timing_log.record()<br/>━━━━━━━━━━<br/>step_name + elapsed<br/>order_id=order_id"]
    end

    subgraph Disk ["● Disk Flush (session_log.py)"]
        direction TB
        CHKSTEP{"step_name<br/>set?"}
        WRITETU["write token_usage.json<br/>━━━━━━━━━━<br/>+order_id field"]
        WRITEJSONL["● append sessions.jsonl<br/>━━━━━━━━━━<br/>+kitchen_id, +order_id<br/>(renamed from pipeline_id)"]
    end

    subgraph Hook ["● PostToolUse Hook (token_summary_appender.py)"]
        direction TB
        CHKPR{"PR URL in<br/>result?"}
        EXTOID["● _extract_order_id()<br/>━━━━━━━━━━<br/>parse order_id from<br/>run_skill result JSON"]
        CHKOID2{"order_id<br/>non-empty?"}
        FILORD["● filter sessions.jsonl<br/>━━━━━━━━━━<br/>by order_id<br/>(per-issue precision)"]
        FILKID["filter sessions.jsonl<br/>━━━━━━━━━━<br/>by kitchen_id<br/>(backward-compat fallback)"]
        PATCH["gh api PATCH<br/>━━━━━━━━━━<br/>## Token Usage Summary<br/>appended to PR body"]
    end

    DONE(["return result_json_str"])

    START --> RUNSK
    RUNSK -->|"executor.run(kitchen_id, order_id)"| CORE
    RUNSK --> CHKOID
    CHKOID -->|"yes"| INJECT
    CHKOID -->|"no"| DONE
    INJECT --> DONE

    CORE --> CHKCRASH
    CHKCRASH -->|"crash"| FLUSH_CRASH
    CHKCRASH -->|"normal"| FLUSH_OK
    FLUSH_CRASH --> WRITEJSONL
    FLUSH_OK --> WRITEJSONL
    FLUSH_OK --> CHKSTEP
    CHKSTEP -->|"yes"| WRITETU
    CHKSTEP -->|"yes"| TOKREC
    CHKSTEP -->|"yes"| TIMREC
    WRITETU --> WRITEJSONL

    DONE -->|"PostToolUse fires"| CHKPR
    CHKPR -->|"no"| SKIP(["skip (no-op)"])
    CHKPR -->|"yes"| EXTOID
    EXTOID --> CHKOID2
    CHKOID2 -->|"yes"| FILORD
    CHKOID2 -->|"no"| FILKID
    FILORD --> PATCH
    FILKID --> PATCH

    class START,DONE,SKIP terminal;
    class RUNSK,CORE,INJECT,FLUSH_CRASH,FLUSH_OK,TOKREC handler;
    class TIMREC,EXTOID,FILORD handler;
    class WRITEJSONL,WRITETU stateNode;
    class CHKOID,CHKOID2,CHKCRASH,CHKSTEP,CHKPR phase;
    class PATCH integration;
    class FILKID output;
```

Closes #572

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/impl-20260329-215040-774677/.autoskillit/temp/make-plan/token_telemetry_cross_contamination_plan_2026-03-29_215850.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
#577)

## Summary

The `promote-to-main` skill (`.claude/skills/promote-to-main/SKILL.md`)
is a monolith that
conflates two distinct concerns: (1) generating a PR body that documents
what changed
(changelog, release notes, architecture diagrams) and (2)
reviewer-facing deep analysis
(domain risk scoring, breaking change audit, regression hotspots,
quality assessment).

This plan splits it into two focused bundled skills:

1. **Streamlined `promote-to-main`** — promoted from project-local
(`.claude/skills/`) to
bundled (`skills_extended/`). Retains Phases 0–2 (setup, pre-flight,
change inventory)
unchanged. Adds a condensed Phase 3 for architecture diagrams and a new
Phase 4 for
release notes synthesis + PR creation. Removes all domain analysis and
quality assessment.

2. **New `review-promotion`** — a new bundled skill in
`skills_extended/`. Takes the domain
analysis (old Phase 3), quality assessment (old Phase 4), and a
reviewer-focused summary
synthesis. Optionally posts as a GitHub PR review comment via
`--post-to-pr`.

The local override `.claude/skills/promote-to-main/` is deleted; the
bundled skill replaces it.

## Requirements

### PROMOTE — Streamlined promote-to-main Skill

- **REQ-PROMOTE-001:** The promote-to-main skill must produce a PR body
containing only changelog content: executive summary, release notes,
merged PR table, linked issues table, architecture diagrams, and closing
references.
- **REQ-PROMOTE-002:** The promote-to-main skill must not include domain
risk scores, review guidance, breaking change audit tables, regression
hotspot analysis, or test coverage deltas in the PR body or promotion
report.
- **REQ-PROMOTE-003:** The promote-to-main skill must invoke arch-lens
skills via the Skill tool (not just write context files) and embed
validated diagrams in the PR body.
- **REQ-PROMOTE-004:** The promote-to-main skill must complete in 5
phases or fewer: Setup, Pre-flight, Change Inventory, Executive Summary
+ Release Notes, Architecture Diagrams, and Compose Report + Create PR.
- **REQ-PROMOTE-005:** The promote-to-main skill must preserve existing
pre-flight gate behavior (CI status, version consistency, outstanding
reviews must all pass before proceeding).
- **REQ-PROMOTE-006:** The promote-to-main skill must carry forward all
`Closes #N`, `Fixes #N`, and `Resolves #N` references from merged PR
bodies.

### REVIEW — New review-promotion Skill

- **REQ-REVIEW-001:** The review-promotion skill must accept an optional
PR number or branch range as input for standalone or pipeline use.
- **REQ-REVIEW-002:** The review-promotion skill must produce per-domain
risk analysis with risk scores, key changes, and review guidance.
- **REQ-REVIEW-003:** The review-promotion skill must produce a breaking
change audit with severity ratings and affected downstream consumers.
- **REQ-REVIEW-004:** The review-promotion skill must produce a
regression risk assessment including conflict hotspots and rectify
chains.
- **REQ-REVIEW-005:** The review-promotion skill must produce a test
coverage delta analysis.
- **REQ-REVIEW-006:** The review-promotion skill must produce a
cross-domain dependency analysis with integration confidence rating.
- **REQ-REVIEW-007:** The review-promotion skill must write its output
report to `.autoskillit/temp/review-promotion/`.

### CONV — Skill Conventions

- **REQ-CONV-001:** Both skills must follow the existing Tier 2/3
SKILL.md structural conventions used by other skills in
`src/autoskillit/skills_extended/`.
- **REQ-CONV-002:** Both skills must emit structured output tokens as
their final lines for pipeline capture.
- **REQ-CONV-003:** Both skills must use Task tool (model: sonnet) for
all subagent spawning with the Subagent Autonomy Grant.

## Architecture Impact

### Process Flow Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 40, 'rankSpacing': 55, 'curve': 'basis'}}}%%
flowchart TB
    %% CLASS DEFINITIONS %%
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;

    START_P2M([● promote-to-main START])
    END_P2M([● promote-to-main END])
    START_RP([★ review-promotion START])
    END_RP([★ review-promotion END])
    ERR_PREFLIGHT([ERROR: preflight failed])

    subgraph P2M ["● promote-to-main  (bundled — skills_extended/)"]
        direction TB

        subgraph P0 ["● Phase 0: Setup"]
            direction LR
            P0A["● Parse Args<br/>━━━━━━━━━━<br/>integration_branch<br/>base_branch · dry_run"]
            P0B["● Divergence Point<br/>━━━━━━━━━━<br/>merge_base_sha<br/>commit_count · date"]
            P0C["● Token Summary<br/>━━━━━━━━━━<br/>load from session logs<br/>kitchen_id filter"]
        end

        subgraph P1 ["● Phase 1: Pre-flight (parallel, blocking)"]
            direction LR
            P1A["● 1A: CI & Branch<br/>━━━━━━━━━━<br/>gh pr checks<br/>behind_base_by"]
            P1B["● 1B: Version Consistency<br/>━━━━━━━━━━<br/>pyproject vs plugin.json<br/>uv lock --check"]
            P1C["● 1C: Review Items<br/>━━━━━━━━━━<br/>CHANGES_REQUESTED PRs<br/>in-progress issues"]
        end

        GATE{"● all pass?"}

        subgraph P2 ["● Phase 2: Change Inventory (parallel)"]
            direction LR
            P2A["● 2A: Commit Categorization<br/>━━━━━━━━━━<br/>rectify · feature<br/>infra · test · docs"]
            P2B["● 2B: PR + Issue Linkage<br/>━━━━━━━━━━<br/>Closes/Fixes/Resolves<br/>traceability matrix"]
            P2C["● 2C: File Lifecycle<br/>━━━━━━━━━━<br/>added · modified<br/>deleted · renamed"]
            P2D["● 2D: Migration Detection<br/>━━━━━━━━━━<br/>schema · deps<br/>hooks · CI"]
        end

        subgraph P3 ["★ Phase 3: Architecture Diagrams"]
            direction LR
            P3A["★ Lens Selection<br/>━━━━━━━━━━<br/>1–3 lenses via subagent<br/>dev lens guard"]
            P3B["★ Diagram Generation<br/>━━━━━━━━━━<br/>Write context → Skill<br/>(anti-prose guard loop)"]
        end

        subgraph P4 ["★ Phase 4: Compose PR + Create PR"]
            direction TB
            P4A["★ Release Notes Synthesis<br/>━━━━━━━━━━<br/>Phase 2 data only<br/>exec summary · highlights"]
            P4B["★ Write PR Body<br/>━━━━━━━━━━<br/>changelog · release notes<br/>merged PRs · arch diagrams"]
            DRY{"dry_run?"}
            GH_AUTH{"gh auth ok?"}
            P4C["● Create PR<br/>━━━━━━━━━━<br/>gh pr create --body-file<br/>add 'promotion' label"]
        end

        OUT_P2M["● report_path · pr_url<br/>verdict · category_summary"]
    end

    subgraph RP ["★ review-promotion  (new skill — skills_extended/)"]
        direction TB

        subgraph RP0 ["★ Phase 0: Setup"]
            direction LR
            RP0A["★ Parse Args<br/>━━━━━━━━━━<br/>integration_branch<br/>base_branch · --post-to-pr"]
            RP0B["★ Divergence + Files<br/>━━━━━━━━━━<br/>merge_base_sha<br/>changed_files"]
            RP0C["★ Find PR (opt)<br/>━━━━━━━━━━<br/>gh pr list --head<br/>store pr_number"]
        end

        subgraph RP1 ["★ Phase 1: Domain Analysis"]
            direction TB
            RP1A["★ Partition by Domain<br/>━━━━━━━━━━<br/>partition_files_by_domain<br/>(autoskillit.execution.pr_analysis)"]
            RP1B["★ Domain Diffs + Commits<br/>━━━━━━━━━━<br/>git diff per domain (≤12k)<br/>git log per domain"]
            RP1C["★ Parallel Domain Agents<br/>━━━━━━━━━━<br/>risk_score · review_guidance<br/>breaking_changes · key_changes"]
            RP1D["★ Cross-Domain Analysis<br/>━━━━━━━━━━<br/>alignment · risks<br/>integration_confidence"]
        end

        subgraph RP2 ["★ Phase 2: Quality Assessment (parallel)"]
            direction LR
            RP2A["★ 2A: Test Coverage Delta<br/>━━━━━━━━━━<br/>new source vs test files<br/>coverage_assessment"]
            RP2B["★ 2B: Breaking Change Audit<br/>━━━━━━━━━━<br/>removed fns · sig changes<br/>Protocol/ABC mods"]
            RP2C["★ 2C: Regression Risk<br/>━━━━━━━━━━<br/>hotspot_files<br/>rectify_chains · overall_risk"]
        end

        subgraph RP3 ["★ Phase 3: Review Synthesis"]
            RP3A["★ Verdict Subagent<br/>━━━━━━━━━━<br/>review_ready · needs_attention<br/>blocking_issues"]
        end

        subgraph RP4_WRITE ["★ Phase 4: Write Review Report"]
            RP4["★ Write Report<br/>━━━━━━━━━━<br/>.autoskillit/temp/review-promotion/<br/>review_report_{timestamp}.md"]
        end

        POST_Q{"★ --post-to-pr<br/>AND pr_number?"}
        RP5["★ Post PR Comment<br/>━━━━━━━━━━<br/>gh pr comment --body-file<br/>(graceful fail)"]
        OUT_RP["★ report_path · verdict"]
    end

    %% PROMOTE-TO-MAIN FLOW
    START_P2M --> P0A --> P0B --> P0C
    P0C --> P1A & P1B & P1C
    P1A & P1B & P1C --> GATE
    GATE -->|"any fail"| ERR_PREFLIGHT
    GATE -->|"all pass"| P2A & P2B & P2C & P2D
    P2A & P2B & P2C & P2D --> P3A --> P3B
    P3B --> P4A --> P4B --> DRY
    DRY -->|"yes"| OUT_P2M
    DRY -->|"no"| GH_AUTH
    GH_AUTH -->|"fail"| OUT_P2M
    GH_AUTH -->|"pass"| P4C --> OUT_P2M --> END_P2M

    %% REVIEW-PROMOTION FLOW
    START_RP --> RP0A --> RP0B --> RP0C
    RP0C --> RP1A --> RP1B --> RP1C --> RP1D
    RP1D --> RP2A & RP2B & RP2C
    RP2A & RP2B & RP2C --> RP3A --> RP4
    RP4 --> POST_Q
    POST_Q -->|"yes"| RP5 --> OUT_RP --> END_RP
    POST_Q -->|"no"| OUT_RP

    %% CLASS ASSIGNMENTS
    class START_P2M,END_P2M,START_RP,END_RP terminal;
    class ERR_PREFLIGHT detector;
    class P0A,P0B,P0C,P1A,P1B,P1C,P2A,P2B,P2C,P2D handler;
    class P3A,P3B,P4A,P4B,P4C newComponent;
    class RP0A,RP0B,RP0C,RP1A,RP1B,RP1C,RP1D,RP2A,RP2B,RP2C,RP3A,RP4,RP5 newComponent;
    class GATE,DRY,GH_AUTH,POST_Q stateNode;
    class OUT_P2M,OUT_RP output;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | Terminal | START and END states |
| Orange | Handler | Unchanged phase nodes carried forward from original
promote-to-main |
| Green | New Component | ★ New phases / nodes introduced by this PR |
| Teal | State | Decision points (gates, flags, auth checks) |
| Dark Teal | Output | Structured output tokens emitted |
| Red | Detector | Error terminal (preflight failure) |

### Module Dependency Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 70, 'curve': 'basis'}}}%%
graph TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef integration fill:#c62828,stroke:#ef9a9a,stroke-width:2px,color:#fff;
    classDef terminal fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;

    subgraph L0 ["L0 — CORE (zero autoskillit imports)"]
        direction LR
        PATHS["core/paths.py<br/>━━━━━━━━━━<br/>pkg_root()<br/>importlib.resources"]
        TYPES["core/types.py<br/>━━━━━━━━━━<br/>SkillSource · SkillInfo<br/>re-export hub"]
        YAML_IO["core/io.py<br/>━━━━━━━━━━<br/>load_yaml · atomic_write<br/>YAMLError"]
    end

    subgraph L1_WS ["L1 — WORKSPACE"]
        direction TB
        SKILLS_PY["workspace/skills.py<br/>━━━━━━━━━━<br/>SkillResolver · bundled_skills_dir<br/>bundled_skills_extended_dir<br/>detect_project_local_overrides"]
        SESSION_SKILLS["workspace/session_skills.py<br/>━━━━━━━━━━<br/>DefaultSessionSkillManager<br/>SkillsDirectoryProvider"]
    end

    subgraph L1_EX ["L1 — EXECUTION"]
        PR_ANALYSIS["execution/pr_analysis.py<br/>━━━━━━━━━━<br/>partition_files_by_domain<br/>DOMAIN_PATHS"]
    end

    subgraph L2_DATA ["L2 — SKILLS DATA (filesystem scan — not Python imports)"]
        direction LR
        PTM["★ skills_extended/<br/>promote-to-main/SKILL.md<br/>━━━━━━━━━━<br/>5 phases · bundled<br/>(renamed from .claude/skills/)"]
        RP["★ skills_extended/<br/>review-promotion/SKILL.md<br/>━━━━━━━━━━<br/>5 phases + post-to-pr<br/>(new skill)"]
        WR["● skills_extended/<br/>write-recipe/SKILL.md<br/>━━━━━━━━━━<br/>bundled skills list updated<br/>(modified)"]
    end

    subgraph L3_TESTS ["L3 — TEST SUITE"]
        direction LR
        T_SKILLS["● tests/workspace/test_skills.py<br/>━━━━━━━━━━<br/>BUNDLED_SKILLS contract<br/>count assertions updated"]
        T_PROMOTE["★ tests/skills/<br/>test_promote_split_contracts.py<br/>━━━━━━━━━━<br/>promote-to-main · review-promotion<br/>structural contracts"]
        T_PLACEHOLDER["● tests/skills/<br/>test_skill_placeholder_contracts.py<br/>━━━━━━━━━━<br/>allowlist entries added<br/>(modified)"]
    end

    %% DISCOVERY (filesystem scan — not Python import)
    SKILLS_PY -.->|"iterdir() scan<br/>pkg_root()/skills_extended/"| PTM
    SKILLS_PY -.->|"iterdir() scan"| RP
    SKILLS_PY -.->|"iterdir() scan"| WR

    %% RUNTIME INVOCATION from SKILL.md (shell python3 -c)
    RP -.->|"python3 -c runtime<br/>shell invocation"| PR_ANALYSIS

    %% WORKSPACE → CORE
    SKILLS_PY -->|"imports pkg_root<br/>SkillSource · YAMLError · load_yaml"| PATHS
    SKILLS_PY -->|"imports SkillSource"| TYPES
    SKILLS_PY -->|"imports load_yaml · YAMLError"| YAML_IO
    SESSION_SKILLS -->|"imports SkillInfo<br/>SkillResolver"| SKILLS_PY

    %% TESTS → WORKSPACE
    T_SKILLS -->|"imports SkillResolver<br/>bundled_skills_dir<br/>bundled_skills_extended_dir"| SKILLS_PY
    T_SKILLS -->|"imports SkillSource"| TYPES
    T_PROMOTE -->|"imports pkg_root (deferred)"| PATHS

    %% HIGH FAN-IN: pkg_root
    HI_FAN["HIGH FAN-IN: pkg_root()<br/>━━━━━━━━━━<br/>imported by workspace/skills.py<br/>and tests/skills/test_promote_split_contracts.py<br/>importlib.resources.files('autoskillit')"]

    PATHS --- HI_FAN

    %% CLASS ASSIGNMENTS
    class PATHS,TYPES,YAML_IO stateNode;
    class SKILLS_PY,SESSION_SKILLS phase;
    class PR_ANALYSIS handler;
    class PTM,RP newComponent;
    class WR,T_SKILLS,T_PLACEHOLDER output;
    class T_PROMOTE newComponent;
    class HI_FAN integration;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Teal | L0 Core | Foundation modules — high fan-in, zero autoskillit
imports |
| Purple | L1 Workspace | Skill discovery and session management |
| Orange | L1 Execution | Runtime utilities
(`partition_files_by_domain`) |
| Green | New Components | ★ New skills and new test contracts |
| Dark Teal | Modified | ● Modified files (write-recipe, test_skills,
placeholder tests) |
| Red | High Fan-In | `pkg_root()` — anchor for all skills_extended
discovery |
| Dashed Lines | Non-import | Filesystem scan (SkillResolver) and
runtime shell invocation (SKILL.md) |

Closes #576

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/impl-20260402-152802-966153/.autoskillit/temp/make-plan/promote_split_plan_2026-04-02_120000.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

## Token Usage Summary

| Step | input | output | cached | count | time |
|------|-------|--------|--------|-------|------|
| plan | 41 | 28.5k | 1.8M | 1 | 8m 12s |
| verify | 40 | 19.5k | 2.5M | 1 | 5m 54s |
| implement | 64 | 23.0k | 3.9M | 1 | 8m 2s |
| fix | 32 | 12.1k | 1.4M | 1 | 6m 22s |
| audit_impl | 288 | 13.0k | 304.1k | 1 | 12m 38s |
| open_pr | 36 | 32.1k | 1.8M | 1 | 15m 51s |
| **Total** | 501 | 128.2k | 11.6M | | 57m 1s |

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>

@Trecek Trecek left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AutoSkillit PR Review — Verdict: changes_requested

50 findings (3 critical, 32 warning, 15 info) across 6 audit dimensions.

Note: Cannot REQUEST_CHANGES on own PR — posting as COMMENT.

# CWA: no summary line found — cannot confirm pass.
return False
# No pytest summary detected — runner is not pytest; trust exit code.
return True

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[warning] tests: check_test_passed() now returns True when no pytest summary is found. Previous closed-world assumption returned False, providing defense against pytest crashes with exit 0.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Investigated — this rename was the explicit goal of PR #517 ('Replace Reverse-Sync with Minor-Bump-on-Promote Strategy'). Commit message and REQ-PROMO-001 document the intentional strategy change.

Comment thread src/autoskillit/execution/testing.py Resolved
"""

async def run(self, cwd: Path) -> tuple[bool, str]: ...
async def run(self, cwd: Path) -> TestResult: ...

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[warning] tests: TestRunner Protocol: async run(cwd) now returns TestResult instead of tuple[bool, str]. Test stubs returning old two-tuple will pass isinstance() but fail on .passed/.stdout/.stderr access.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Investigated — force-push removal is intentional per PR #517. REQ-PROMO-002 specifies integration gets patch=1 via normal commit, not force-push. Integration correctly diverges from main by design.

Comment thread tests/cli/test_terminal.py Resolved
@@ -0,0 +1,52 @@
"""Test that _merge_sub_recipe skips hidden sub-recipe ingredients."""

from autoskillit.recipe._api import _merge_sub_recipe

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[warning] arch: Imports _merge_sub_recipe from autoskillit.recipe._api (private submodule), bypassing canonical public surface.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Investigated — the 'deferred: avoids scan overhead' comment is in app.py line 361, not in _workspace.py. The module-level imports in _workspace.py are real, but _workspace.py itself is lazily imported from app.py. The comment remains accurate.

Comment thread tests/pipeline/test_audit.py Resolved
@@ -0,0 +1,475 @@
---
name: promote-to-main
categories: [github]

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[warning] cohesion: New skill missing hooks: PreToolUse section. All other skills_extended skills have it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Investigated — unsafe_install_guard.main() always calls sys.exit(0) regardless of deny/allow. The guard communicates via stdout JSON (hookSpecificOutput.permissionDecision), not exit codes. _is_denied correctly reads JSON output.

Comment thread .claude/skills/promote-to-main/SKILL.md Resolved
files outside its working directory. This is a CWD boundary violation, not a context limit.
Do NOT route to `on_context_limit` even if defined.
- **If `retry_reason: early_stop` or `zero_writes`** → fall through to `on_failure`.
- **If `retry_reason: stale`** → decrement the `retries` counter for this step.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[warning] cohesion: Asymmetric retry-exhaustion routing: resume+stale routes to on_exhausted, standalone stale routes to on_failure. Same root cause, different routes.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Investigated — TestValidateFailureRecordDict._valid_dict() and TestLoadFromLogDirTypeValidation._valid_record() serve different test classes testing different behaviors. Structural similarity is incidental.

Trecek and others added 7 commits April 3, 2026 01:30
…ctly in Bundled Skills (#582)

## Summary

PR #577 placed `promote-to-main` and `review-promotion` in
`src/autoskillit/skills_extended/` (bundled package skills) instead of
`.claude/skills/` (project-local skills). These skills are specific to
the AutoSkillit repository itself and have no value when shipped to
external users.

The fix is a file relocation and accompanying count revert:
1. Move both SKILL.md files from `skills_extended/` to `.claude/skills/`
2. Delete the now-empty skill directories from `skills_extended/`
3. Delete `tests/skills/test_promote_split_contracts.py` (tests the
wrong invariant)
4. Revert all bundled skill counts: CLAUDE.md, docs, test assertions,
and write-recipe list

## Architecture Impact

### Module Dependency Diagram

```mermaid
%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 70, 'curve': 'basis'}}}%%
graph TB
    %% CLASS DEFINITIONS %%
    classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff;
    classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff;
    classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff;
    classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff;
    classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff;
    classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff;
    classDef integration fill:#c62828,stroke:#ef9a9a,stroke-width:2px,color:#fff;

    subgraph Consumers ["L3 — Consumers (server / cli / recipe)"]
        direction LR
        CLI["cli/app.py<br/>━━━━━━━━━━<br/>skills command"]
        Recipe["recipe/rules_skills.py<br/>━━━━━━━━━━<br/>skill resolvability rules"]
        Server["server/tools_execution.py<br/>━━━━━━━━━━<br/>run_skill handler"]
    end

    subgraph Workspace ["L2 — workspace/ (skill discovery)"]
        direction LR
        Resolver["● workspace/skills.py<br/>━━━━━━━━━━<br/>SkillResolver.list_all() → 60<br/>detect_project_local_overrides()"]
        SessionMgr["workspace/session_skills.py<br/>━━━━━━━━━━<br/>DefaultSessionSkillManager<br/>writes ephemeral skill dirs"]
    end

    subgraph Core ["L1 — core/ (types & paths)"]
        direction LR
        Enums["core/_type_enums.py<br/>━━━━━━━━━━<br/>SkillSource.BUNDLED<br/>SkillSource.BUNDLED_EXTENDED"]
        Paths["core/paths.py<br/>━━━━━━━━━━<br/>pkg_root()"]
    end

    subgraph Tier1 ["Tier 1 — skills/ (BUNDLED, 3 skills)"]
        direction LR
        T1["skills/<br/>━━━━━━━━━━<br/>open-kitchen<br/>close-kitchen<br/>sous-chef"]
    end

    subgraph Tier23 ["Tier 2+3 — skills_extended/ (BUNDLED_EXTENDED, 58 skills)"]
        direction LR
        T23["skills_extended/<br/>━━━━━━━━━━<br/>● write-recipe + 57 others<br/>(promote-to-main removed)<br/>(review-promotion removed)"]
    end

    subgraph ProjLocal ["Project-Local — .claude/skills/ (18 skills, not shipped)"]
        direction LR
        PTM["★ .claude/skills/promote-to-main/<br/>━━━━━━━━━━<br/>SKILL.md relocated here"]
        RP["★ .claude/skills/review-promotion/<br/>━━━━━━━━━━<br/>SKILL.md relocated here"]
        PLOther[".claude/skills/16 others<br/>━━━━━━━━━━<br/>audit-arch, make-req, etc."]
    end

    subgraph Tests ["Tests (● updated)"]
        direction LR
        TSkills["● tests/workspace/test_skills.py<br/>━━━━━━━━━━<br/>list_all() == 60<br/>skills_extended count == 58"]
        TContracts["● tests/skills/test_skill_placeholder_contracts.py<br/>━━━━━━━━━━<br/>allowlist entries removed"]
    end

    %% CONSUMER → WORKSPACE %%
    CLI -->|"imports SkillResolver"| Resolver
    Recipe -->|"imports SkillResolver"| Resolver
    Server -->|"imports DefaultSessionSkillManager"| SessionMgr

    %% WORKSPACE INTERNAL %%
    SessionMgr -->|"uses"| Resolver

    %% WORKSPACE → CORE %%
    Resolver -->|"imports SkillSource, pkg_root"| Enums
    Resolver -->|"imports"| Paths
    SessionMgr -->|"imports SkillSource"| Enums

    %% RESOLVER → SKILL DIRS %%
    Resolver -->|"scans BUNDLED"| T1
    Resolver -->|"scans BUNDLED_EXTENDED"| T23
    Resolver -.->|"detect_project_local_overrides()"| PTM
    Resolver -.->|"detect_project_local_overrides()"| RP
    Resolver -.->|"detect_project_local_overrides()"| PLOther

    %% SESSION MGR → EPHEMERAL %%
    SessionMgr -->|"skips BUNDLED<br/>(plugin-dir channel)"| T1
    SessionMgr -->|"writes Tier 2+3<br/>to /dev/shm/"| T23
    SessionMgr -.->|"skips when name<br/>in overrides"| PTM
    SessionMgr -.->|"skips when name<br/>in overrides"| RP

    %% CLASS ASSIGNMENTS %%
    class CLI,Recipe cli;
    class Server handler;
    class Resolver phase;
    class SessionMgr handler;
    class Enums,Paths stateNode;
    class T1,T23 output;
    class PTM,RP newComponent;
    class PLOther output;
    class TSkills,TContracts detector;
```

**Color Legend:**
| Color | Category | Description |
|-------|----------|-------------|
| Dark Blue | CLI/Recipe | Consumer layer — imports SkillResolver |
| Orange | Handler | Session manager, server tools |
| Purple | Phase/Resolver | SkillResolver — skill discovery and
resolution |
| Teal | State | Core types: SkillSource enum, pkg_root() |
| Dark Teal | Output | Skill directory tiers (Tier 1, Tier 2+3, other
project-local) |
| Green | ★ New Location | promote-to-main and review-promotion
relocated to .claude/skills/ |
| Red | Tests | Updated test assertions for new counts |
| Dashed Lines | Detection | detect_project_local_overrides() — override
scanning path |

Closes #579

## Implementation Plan

Plan file:
`/home/talon/projects/autoskillit-runs/impl-20260402-173309-328308/.autoskillit/temp/make-plan/bug_promote_review_relocation_plan_2026-04-02_000000.md`

🤖 Generated with [Claude Code](https://claude.com/claude-code) via
AutoSkillit

## Token Usage Summary

| Step | input | output | cached | count | time |
|------|-------|--------|--------|-------|------|
| plan | 31 | 16.3k | 1.3M | 1 | 5m 56s |
| verify | 28 | 10.0k | 1.1M | 1 | 3m 11s |
| implement | 55 | 14.0k | 2.6M | 1 | 11m 17s |
| audit_impl | 294 | 19.5k | 535.7k | 1 | 7m 54s |
| open_pr | 36 | 18.9k | 1.4M | 1 | 6m 39s |
| **Total** | 444 | 78.7k | 7.0M | | 35m 0s |

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
…p.yml

Parity with patch-bump-integration.yml which already validates the version
format. Prevents silent arithmetic misbehavior if the version string is
malformed or empty.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…e paths

git-registered worktrees may not exist on disk (stale registrations).
Calling stat().st_mtime on such paths raises FileNotFoundError. Now
filters out non-existent paths before age partitioning.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…ssion_id

Disambiguates from execution/process.py's _resolve_session_id which has
a different signature and operates at a lower layer.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
A provided-but-missing file path likely indicates a pipeline
misconfiguration rather than intentional standalone invocation.
Now emits a warning before falling back to no-queue mode.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Fix inverted branch logic in test_subpackage_isolation (days unreachable)
- Remove dead applicable_migrations patch in test_api
- Add missing project_dir assertion in test_repository
- Narrow bare except to (OSError, TypeError, SyntaxError) in test_registry
- Deduplicate _NO_AUTOSKILLIT_IMPORT constant to tests/recipe/conftest.py
- Remove redundant inline unittest.mock import in test_cook
- Replace module-level cross-layer import with string-based patch in test_terminal

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@Trecek
Trecek merged commit abc53c0 into main Apr 3, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment