diff --git a/.claude/skills/titan-close/SKILL.md b/.claude/skills/titan-close/SKILL.md index 57568d65..299bc447 100644 --- a/.claude/skills/titan-close/SKILL.md +++ b/.claude/skills/titan-close/SKILL.md @@ -58,13 +58,18 @@ Your goal: analyze all commits on the current branch, split them into focused PR 4. **Load artifacts.** Read: - `.codegraph/titan/titan-state.json` — session state, baseline metrics, progress - `.codegraph/titan/GLOBAL_ARCH.md` — architecture document - - `.codegraph/titan/gauntlet-summary.json` — audit results + - `.codegraph/titan/gauntlet.ndjson` — full per-target audit data (pillar verdicts, metrics, violations) + - `.codegraph/titan/gauntlet-summary.json` — audit result totals - `.codegraph/titan/sync.json` — execution plan (commit grouping) - - `.codegraph/titan/gate-log.ndjson` — validation history + - `.codegraph/titan/gate-log.ndjson` — validation history (may not exist if gate wasn't run) - `.codegraph/titan/issues.ndjson` — issue tracker from all phases + - `.codegraph/titan/arch-snapshot.json` — pre-forge architectural snapshot (communities, structure, drift). Use for before/after comparison in the Metrics section. May not exist if capture failed. + - `.codegraph/titan/drift-report.json` — cumulative drift reports from all phases. May not exist if no drift was detected. If `titan-state.json` is missing after the search, stop: "No Titan session found. Run `/titan-recon` first." + > **When called from `/titan-run`:** The orchestrator already ensured worktree isolation, synced with main, and all artifacts are in the current worktree. Steps 0.1–0.3 (worktree search, isolation check, main sync) can be skipped if the orchestrator tells you to skip them. + 5. **Detect version.** Extract from `package.json`: ```bash node -e "console.log(require('./package.json').version)" @@ -193,6 +198,10 @@ codegraph complexity --health --sort bugs -T --json --limit 10 codegraph complexity --health --sort mi -T --json --limit 10 ``` +### Architecture comparison (if arch-snapshot.json exists) + +If `.codegraph/titan/arch-snapshot.json` was captured before forge, compare its `structure` data against current `codegraph structure --depth 2 --json` output. Report cohesion changes per directory (improved / degraded / unchanged). Include in the "Metrics: Before & After" section of the report. + ### Compute deltas Compare final metrics against `titan-state.json` baseline: @@ -505,10 +514,7 @@ Write `.codegraph/titan/close-summary.json`: ``` Delete any remaining batch snapshots. -3. **Add report to .gitignore** if `generated/titan/` is not already ignored: - ```bash - grep -q "generated/titan/" .gitignore || echo "generated/titan/" >> .gitignore - ``` +3. **Titan reports are committed to the repo** (not gitignored). The `generated/titan/` directory is tracked so reports are preserved in git history. --- diff --git a/.claude/skills/titan-run/SKILL.md b/.claude/skills/titan-run/SKILL.md index 3ee9e68a..fefd96d9 100644 --- a/.claude/skills/titan-run/SKILL.md +++ b/.claude/skills/titan-run/SKILL.md @@ -28,7 +28,7 @@ You are the **orchestrator** for the full Titan Paradigm pipeline. Your job is t ```bash git rev-parse --show-toplevel && git worktree list ``` - If you are NOT in a worktree, **stop:** "Run `/worktree` first. The Titan pipeline writes artifacts and makes code changes — worktree isolation is required." + The Titan pipeline writes artifacts and makes code changes — worktree isolation is required. If you are NOT in a worktree, **create one automatically** using the `EnterWorktree` tool (fetch it via `ToolSearch` if needed) with name `titan-run`. Do NOT stop and ask the user — just enter the worktree and continue. 2. **Parse arguments.** Determine: - `targetPath` (default: `.`) @@ -58,7 +58,7 @@ You are the **orchestrator** for the full Titan Paradigm pipeline. Your job is t Forge requires explicit confirmation (analysis phases are safe to automate). ``` - If `--yes` is NOT set, ask user to confirm before proceeding. + Start immediately — do NOT ask for confirmation before analysis phases. The user invoked `/titan-run`; that is the confirmation. Analysis phases (recon, gauntlet, sync) are read-only and safe to automate. The forge checkpoint (Step 3.5b) still applies unless `--yes` is set. --- @@ -577,58 +577,27 @@ Print forge summary. --- -## Step 5 — Final Report +## Step 5 — CLOSE (report + PRs) -Read all artifacts and produce a summary: +After forge completes, dispatch `/titan-close` to produce the final report with before/after metrics and split commits into focused PRs. + +### 5a. Run Pre-Agent Gate (G1-G4) + +### 5b. Dispatch sub-agent ``` -============================================ - TITAN PIPELINE COMPLETE -============================================ - -Target: -Duration: - -RECON: - Files: , Symbols: , Domains: - Quality score: - -GAUNTLET: - Audited: / targets (% coverage) - Pass: | Warn: | Fail: | Decompose: - NDJSON integrity: / lines - -SYNC: - Execution phases: - Shared abstractions: - -FORGE: - Commits: - Targets completed: - Targets failed: - Diff review rejections: - Diff review warnings: - Gate verdicts: PASS, FAIL - Semantic assertion failures: - Architectural violations caught: - - Failed targets (if any): - - : - -Validation warnings (if any): - - - -Artifacts: - .codegraph/titan/titan-state.json - .codegraph/titan/GLOBAL_ARCH.md - .codegraph/titan/gauntlet.ndjson - .codegraph/titan/gauntlet-summary.json - .codegraph/titan/sync.json - .codegraph/titan/arch-snapshot.json - .codegraph/titan/gate-log.ndjson -============================================ +Agent → "Run /titan-close. Read .claude/skills/titan-close/SKILL.md and follow it exactly. + Skip worktree check and main sync — already handled." ``` +### 5c. Post-phase validation + +After the agent returns, verify: +- `.codegraph/titan/TITAN_REPORT.md` or `generated/titan/titan-report-*.md` exists and has content (> 20 lines) +- Print: "CLOSE complete. Report: " + +If the agent created PRs, print the PR URLs. + --- ## Error Handling diff --git a/.gitignore b/.gitignore index 9acd21d6..4f78ca5a 100644 --- a/.gitignore +++ b/.gitignore @@ -9,8 +9,5 @@ grammars/*.wasm .claude/session-edits.log generated/DEPENDENCIES.md generated/DEPENDENCIES.json -generated/titan/ artifacts/ pkg/ -generated/DEPENDENCIES.md -generated/DEPENDENCIES.json diff --git a/docs/examples/claude-code-skills/README.md b/docs/examples/claude-code-skills/README.md index 5c37d429..63fce698 100644 --- a/docs/examples/claude-code-skills/README.md +++ b/docs/examples/claude-code-skills/README.md @@ -21,9 +21,11 @@ A single AI agent cannot hold an entire large codebase in context. The Titan Par │ ├─→ /titan-sync → sync.json (execution plan) │ - └─→ /titan-forge → code changes + commits (loops phases) - │ - └─→ /titan-gate (validates each commit) + ├─→ /titan-forge → code changes + commits (loops phases) + │ │ + │ └─→ /titan-gate (validates each commit) + │ + └─→ /titan-close → PRs + titan-report.md /titan-reset (escape hatch: clean up everything) ``` @@ -38,6 +40,7 @@ A single AI agent cannot hold an entire large codebase in context. The Titan Par | `/titan-sync` | GLOBAL SYNC | Dependency clusters, code ownership, shared abstractions, ordered execution plan with logical commits | `sync.json` | | `/titan-forge` | FORGE | Executes the sync plan — makes code changes, validates with `/titan-gate`, commits, advances state. One phase per invocation | `titan-state.json` | | `/titan-gate` | STATE MACHINE | `codegraph check --staged --cycles --blast-radius 30 --boundaries` + lint/build/test. Snapshot restore on failure | `gate-log.ndjson` | +| `/titan-close` | CLOSE | Splits branch commits into focused PRs, captures final metrics, generates comprehensive audit report with before/after comparison | `titan-report-*.md` | | `/titan-reset` | ESCAPE HATCH | Restores baseline snapshot, deletes all artifacts and snapshots, rebuilds graph | — | ## Installation @@ -118,11 +121,14 @@ All artifacts are written to `.codegraph/titan/` (6 files, no redundancy): | `gauntlet-summary.json` | JSON | GAUNTLET | RUN, SYNC, GATE | | `sync.json` | JSON | SYNC | RUN, FORGE (diff review), GATE | | `arch-snapshot.json` | JSON | RUN (pre-forge) | GATE (architectural comparison) | -| `gate-log.ndjson` | NDJSON | GATE | RUN, Audit trail | +| `gate-log.ndjson` | NDJSON | GATE | RUN, CLOSE, Audit trail | +| `drift-report.json` | JSON | GAUNTLET, SYNC, CLOSE | RUN, CLOSE | +| `close-summary.json` | JSON | CLOSE | — | +| `generated/titan/titan-report-*.md` | Markdown | CLOSE | — (committed to repo) | NDJSON format (one JSON object per line) means partial results survive crashes mid-batch. -**Tip:** Add `.codegraph/titan/` to `.gitignore` — these are ephemeral analysis artifacts, not source code. +**Tip:** Add `.codegraph/titan/` to `.gitignore` — these are ephemeral analysis artifacts. The final report (`generated/titan/`) is tracked in git. ## Snapshots diff --git a/docs/examples/claude-code-skills/titan-close/SKILL.md b/docs/examples/claude-code-skills/titan-close/SKILL.md new file mode 100644 index 00000000..299bc447 --- /dev/null +++ b/docs/examples/claude-code-skills/titan-close/SKILL.md @@ -0,0 +1,564 @@ +--- +name: titan-close +description: Split branch commits into focused PRs, compile issue tracker, generate final report with before/after metrics (Titan Paradigm Phase 5) +argument-hint: <--dry-run to preview without creating PRs> +allowed-tools: Bash, Read, Write, Glob, Grep, Edit +--- + +# Titan CLOSE — PR Splitting & Final Report + +You are running the **CLOSE** phase of the Titan Paradigm. + +Your goal: analyze all commits on the current branch, split them into focused PRs for easier review, compile the issue tracker from all phases, capture final metrics, and generate a comprehensive audit report. + +> **Context budget:** This phase reads artifacts and git history. Keep codegraph queries targeted — only for final metrics comparison. + +**Dry-run mode:** If `$ARGUMENTS` contains `--dry-run`, preview the PR split plan and report without creating PRs or pushing branches. + +--- + +## Step 0 — Pre-flight: find and consolidate the Titan session + +1. **Locate the Titan session.** All prior phases (RECON → GAUNTLET → SYNC → GATE) may have run across different worktrees or branches. You need to consolidate their work. + + ```bash + git worktree list + ``` + + For each worktree, check for Titan artifacts: + ```bash + ls /.codegraph/titan/titan-state.json 2>/dev/null + ``` + + Also check branches (including remote): + ```bash + git branch -a --list '*titan*' + git branch -a --list '*refactor/*' + ``` + + **Decision logic:** + - **Found exactly one worktree/branch with `titan-state.json`:** Read its `currentPhase`. If it's `"sync"` or later, this is the right session. Merge its branch into your worktree. + - **Found a worktree but `currentPhase` is earlier than expected (e.g., `"recon"` or `"gauntlet"`):** The pipeline may not be complete. Keep searching — there may be a more advanced worktree. If nothing better found, ask the user: "Found Titan state at `` with phase ``. The pipeline appears incomplete. Continue anyway, or should I look elsewhere?" + - **Found multiple worktrees with `titan-state.json`:** List them all with `currentPhase`, `lastUpdated`, and branch name. The Titan pipeline may have been split across worktrees (RECON in one, GAUNTLET in another). Merge them in phase order into your worktree. If there's ambiguity (e.g., two worktrees at the same phase), ask the user. + - **Found branches but no worktrees:** Merge the titan branch(es) in phase order: `git merge --no-edit` + - **Found nothing:** Stop: "No Titan session found in any worktree or branch. Run `/titan-recon` first." + +2. **Ensure worktree isolation:** + ```bash + git rev-parse --show-toplevel && git worktree list + ``` + If not in a worktree, stop: "Run `/worktree` first." + +3. **Sync with main:** + ```bash + git fetch origin main && git merge origin/main --no-edit + ``` + If there are merge conflicts, stop: "Merge conflict detected. Resolve conflicts and re-run `/titan-close`." + +4. **Load artifacts.** Read: + - `.codegraph/titan/titan-state.json` — session state, baseline metrics, progress + - `.codegraph/titan/GLOBAL_ARCH.md` — architecture document + - `.codegraph/titan/gauntlet.ndjson` — full per-target audit data (pillar verdicts, metrics, violations) + - `.codegraph/titan/gauntlet-summary.json` — audit result totals + - `.codegraph/titan/sync.json` — execution plan (commit grouping) + - `.codegraph/titan/gate-log.ndjson` — validation history (may not exist if gate wasn't run) + - `.codegraph/titan/issues.ndjson` — issue tracker from all phases + - `.codegraph/titan/arch-snapshot.json` — pre-forge architectural snapshot (communities, structure, drift). Use for before/after comparison in the Metrics section. May not exist if capture failed. + - `.codegraph/titan/drift-report.json` — cumulative drift reports from all phases. May not exist if no drift was detected. + + If `titan-state.json` is missing after the search, stop: "No Titan session found. Run `/titan-recon` first." + + > **When called from `/titan-run`:** The orchestrator already ensured worktree isolation, synced with main, and all artifacts are in the current worktree. Steps 0.1–0.3 (worktree search, isolation check, main sync) can be skipped if the orchestrator tells you to skip them. + +5. **Detect version.** Extract from `package.json`: + ```bash + node -e "console.log(require('./package.json').version)" + ``` + +--- + +## Step 1 — Drift detection: final staleness assessment + +CLOSE is the last phase — it must assess the full pipeline's freshness before generating the report. + +1. **Compare main SHA:** + ```bash + git rev-parse origin/main + ``` + Compare against `titan-state.json → mainSHA`. + +2. **If main has advanced**, calculate full drift: + ```bash + git rev-list --count ..origin/main + git diff --name-only ..origin/main + ``` + +3. **Read all prior drift reports** from `.codegraph/titan/drift-report.json` (a JSON array of entries, one per phase that detected drift). This shows the cumulative drift across the pipeline. + +4. **Assess overall pipeline freshness:** + + | Level | Condition | Action | + |-------|-----------|--------| + | **fresh** | mainSHA matches current main, no drift reports with severity > low | Generate report normally | + | **acceptable** | Some drift detected but phases handled it (re-audited stale targets) | Generate report — note drift in Executive Summary | + | **stale** | Significant unaddressed drift: >10 commits behind, >20% of audited targets changed on main since audit | **Warn user:** "Pipeline results are partially stale. N targets were modified on main after being audited. The report will flag these. Consider re-running `/titan-gauntlet` for affected targets before finalizing." | + | **expired** | >50 commits behind OR >50% of targets changed OR architecture-level changes (new directories in src/) | **Stop:** "Pipeline results are too stale to produce a reliable report. Run `/titan-recon` for a fresh baseline." | + +5. **Write final drift assessment** to the drift report (same schema, `"detectedBy": "close"`). + +6. **Include drift summary in the report.** The final report's Executive Summary and Recommendations sections must reflect any staleness. Stale targets should be called out in a "Staleness Warnings" subsection. + +--- + +## Step 2 — Collect branch commit history + +```bash +git log main..HEAD --oneline --no-merges +git log main..HEAD --format="%H %s" --no-merges +``` + +Extract: total commit count, commit messages, SHAs. If zero commits, stop: "No commits on this branch. Nothing to close." + +For each commit, get the files changed: +```bash +git diff-tree --no-commit-id --name-only -r +``` + +--- + +## Step 3 — Classify commits into PR groups + +Analyze commit messages and changed files to group commits into **focused PRs**. Each PR should address a single concern for easier review. + +### Grouping strategy (in priority order) + +Use `sync.json` execution phases as the primary guide if available: + +1. **Dead code cleanup** — commits removing dead symbols + - PR title: `chore: remove dead code identified by Titan audit` +2. **Shared abstractions** — commits extracting interfaces/utilities + - PR title: `refactor: extract from ` +3. **Cycle breaks** — commits resolving circular dependencies + - PR title: `refactor: break circular dependency in ` +4. **Decompositions** — commits splitting complex functions/files + - PR title: `refactor: decompose in ` +5. **Quality fixes** — commits addressing fail-level violations + - Group by domain: `fix: address quality issues in ` +6. **Warning improvements** — commits addressing warn-level issues + - Group by domain: `refactor: improve code quality in ` + +### Fallback grouping (if no sync.json) + +Group by changed file paths — commits touching the same directory/domain go together. Use commit message prefixes (`fix:`, `refactor:`, `chore:`) as secondary signals. + +### Rules for grouping +- A PR should touch **one domain** where possible +- A PR should address **one concern** (don't mix dead code removal with refactors) +- Order PRs so dependencies come first (if PR B depends on PR A's changes, A merges first) +- Each PR must be independently reviewable — no PR should break the build alone +- If a commit touches files across multiple concerns, assign it to the primary concern and note the cross-cutting nature in the PR description + +Record the grouping plan: +```json +[ + { + "pr": 1, + "title": "...", + "concern": "dead_code|abstraction|cycle_break|decomposition|quality_fix|warning", + "domain": "", + "commits": ["", ""], + "files": ["", ""], + "dependsOn": [], + "description": "..." + } +] +``` + +--- + +## Step 4 — Capture final metrics + +Rebuild the graph and collect current metrics: + +```bash +codegraph build +codegraph stats --json +codegraph complexity --health --above-threshold -T --json --limit 50 +codegraph roles --role dead -T --json +codegraph roles --role core -T --json +codegraph cycles --json +``` + +Extract: `totalNodes`, `totalEdges`, `totalFiles`, `qualityScore`, functions above threshold, dead symbol count, core symbol count, cycle count. + +Also get the worst offenders for comparison: +```bash +codegraph complexity --health --sort effort -T --json --limit 10 +codegraph complexity --health --sort bugs -T --json --limit 10 +codegraph complexity --health --sort mi -T --json --limit 10 +``` + +### Architecture comparison (if arch-snapshot.json exists) + +If `.codegraph/titan/arch-snapshot.json` was captured before forge, compare its `structure` data against current `codegraph structure --depth 2 --json` output. Report cohesion changes per directory (improved / degraded / unchanged). Include in the "Metrics: Before & After" section of the report. + +### Compute deltas + +Compare final metrics against `titan-state.json` baseline: + +| Metric | Baseline | Final | Delta | +|--------|----------|-------|-------| +| Quality Score | from state | from stats | +/- | +| Functions above threshold | from state | from complexity | +/- | +| Dead symbols | from state | from roles | +/- | +| Cycles | from state | from cycles | +/- | +| Total nodes | from state | from stats | +/- | + +--- + +## Step 5 — Compile the issue tracker + +Read `.codegraph/titan/issues.ndjson`. Each line is a JSON object: + +```json +{"phase": "recon|gauntlet|sync|gate", "timestamp": "ISO 8601", "severity": "bug|limitation|suggestion", "category": "codegraph|tooling|process|codebase", "description": "...", "context": "optional detail"} +``` + +Group issues by category and severity. Summarize: +- **Codegraph bugs:** issues with codegraph itself (wrong output, crashes, missing features) +- **Tooling issues:** problems with the Titan pipeline or other tools +- **Process notes:** suggestions for improving the Titan workflow +- **Codebase observations:** structural concerns beyond what the audit covered + +--- + +## Step 6 — Compile the gate log + +Read `.codegraph/titan/gate-log.ndjson`. Summarize: +- Total gate runs +- Pass / Warn / Fail counts +- Rollbacks triggered +- Most common failure reasons + +--- + +## Step 7 — Generate the report + +### Report path + +``` +generated/titan/titan-report-v-T