---
title: "Assess"
description: "Assesses and rates quality 0-10 across multiple dimensions (correctness, maintainability, security, performance, testability, simplicity) with pros/cons analysis. Compares against project conventions and prior decisions from memory. Produces structured evaluation reports with actionable improvement suggestions. Use when evaluating code, designs, architectures, or comparing alternative approaches."
canonical: "https://orchestkit.yonyon.ai/docs/reference/skills/assess"
---

# Assess

Assesses and rates quality 0-10 across multiple dimensions (correctness, maintainability, security, performance, testability, simplicity) with pros/cons analysis. Compares against project conventions and prior decisions from memory. Produces structured evaluation reports with actionable improvement suggestions. Use when evaluating code, designs, architectures, or comparing alternative approaches.

<span className="badge badge-blue">Command</span> <span className="badge badge-orange">high</span>

```bash title="Invoke"
/ork:assess
```

<ContextualSkillSidebar slug="assess" />

> **Assess** Assesses and rates quality 0-10 across multiple dimensions (correctness, maintainability, security, performance, testability, simplicity) with pros/cons analysis. Compares against project conventions and prior decisions from memory. Produces structured evaluation reports with actionable improvement suggestions. Use when evaluating code, designs, architectures, or comparing alternative approaches.


# Assess

Comprehensive assessment skill for answering "is this good?" with structured evaluation, scoring, and actionable recommendations.

## 🎯 Quick Start

```bash
/ork:assess backend/app/services/auth.py
/ork:assess our caching strategy
/ork:assess --model=opus the current database schema
/ork:assess frontend/src/components/Dashboard
```

### Effort levels (CC 2.1.111+ adds `xhigh`)

| Effort | Behavior |
|---|---|
| `low` / `medium` | Subset of dimensions, faster turnaround |
| `high` (default) | All six dimensions with pros/cons |
| `xhigh` | All six dimensions + one additional assessor pass focused on uncertainty/caveats; emits `confidence` per dimension |

> `xhigh` silently falls back to `high` on a model that does not implement it: no error, no log line. `/ork:doctor` Category 14 reports this, and only when it can positively prove the active model lacks the tier.

---

## Argument Resolution

### Step 0: resolve a conversational reference first

`$ARGUMENTS` is often not a path. For a bare pronoun or deictic (`them`, `this`, `that`,
`these`, `they`, `same`, `the above`, `the last one`, `what we just did`) or an empty target
after flags are stripped, the subject is in the conversation. Read back for the NEAREST
concrete one (a file just discussed, a diff or PR just opened, a component just investigated)
and announce the resolution in one line, so a wrong guess costs a correction rather than a
turn: *"Reading 'them' as the 3 pretool guards we just probed; say otherwise and I'll switch."*

**Refusing is the bug, not the safe option.** Asking "what does this refer to?" when the
previous turn named the subject burns a round-trip re-deriving what is already on screen.
Measured 2026-08-28: the operator sent `/ork:assess them throguhly` one message after "bug in
orchestkit hooks", mid-investigation of `pretool/bash/dangerous-command-blocker`, and this
skill replied that "them" had "no antecedent anywhere in this conversation". It had two.

Ask only when the conversation is genuinely empty (a fresh session opening with a bare
pronoun). Every other case: resolve and announce.

> Not unique to this skill: `verify`, `cover`, `fix-issue`, `review-pr` and `implement` all
> read `$ARGUMENTS` as a literal path or topic, and no skill mentions resolving a reference.
> Tracked separately; this one fixes its own door.

```python
TARGET = "$ARGUMENTS"  # Full argument string, e.g., "backend/app/services/auth.py"
# $ARGUMENTS[0] is the first token (CC 2.1.59 indexed access)

# Model override detection (CC 2.1.72)
MODEL_OVERRIDE = None
for token in "$ARGUMENTS".split():
    if token.startswith("--model="):
        MODEL_OVERRIDE = token.split("=", 1)[1]  # "opus", "sonnet", "haiku", "fable"
        TARGET = TARGET.replace(token, "").strip()
```

Pass `MODEL_OVERRIDE` to all Agent() calls via `model=MODEL_OVERRIDE` when set. Accepts symbolic names (`opus`, `sonnet`, `haiku`, `fable` on harnesses whose Agent tool lists it; note fable is premium API spend after 2026-07-12) or full IDs (`claude-opus-4-8`) per CC 2.1.74.

> **Switching to Opus via `/model` (CC 2.1.144+):** `/model` now changes the model for the current session only, so picking Opus for an assess run no longer persists past it. Press `d` in the picker only to set a default for new sessions.

### Effort detection (CC 2.1.120+)

`$CLAUDE_EFFORT` is the primary signal. CC 2.1.120 sets this env var from `/effort` or the model picker. `--effort=` token in `$ARGUMENTS` is the explicit override fallback (also covers older CC).

```python
# Read env first (CC 2.1.120+), then check explicit override
EFFORT = os.environ.get("CLAUDE_EFFORT")  # "low" | "medium" | "high" | "xhigh" | None
for token in "$ARGUMENTS".split():
    if token.startswith("--effort="):
        EFFORT = token.split("=", 1)[1]   # explicit override wins
        TARGET = TARGET.replace(token, "").strip()
EFFORT = EFFORT or "high"  # default when CC < 2.1.120 and no flag
```

Use `EFFORT` to gate dimension count, agent count, and the optional `xhigh` uncertainty pass — see "Effort levels" table above. On CC &lt; 2.1.120 the env var is unset; the explicit `--effort=` override is the only path. `/ork:doctor` Category 14 reports a provably unsupported `xhigh` request.

---

## STEP -1: MCP Probe + Resume Check

> Load: `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/chain-patterns/references/mcp-detection.md")`

```python
# 1. Probe MCP servers (once at skill start)
# memory is alwaysLoad in .mcp.json (CC 2.1.121+, #1541) — probe below kept as fallback for older CC:
ToolSearch(query="select:mcp__memory__search_nodes")

# 2. Store capabilities
Write(".claude/chain/capabilities.json", {
  "memory": probe_memory.found,
  "skill": "assess",
  "timestamp": now()
})

# 3. Check for resume
state = Read(".claude/chain/state.json")  # may not exist
if state.skill == "assess" and state.status == "in_progress":
    last_handoff = Read(f".claude/chain/{state.last_handoff}")
```

### Phase Handoffs

| Phase | Handoff File | Contents |
|-------|-------------|----------|
| 0 | `00-intent.json` | Dimensions, target, mode |
| 1 | `01-baseline.json` | Initial codebase scan results |
| 2 | `02-evaluation.json` | Per-dimension scores + evidence |
| 3 | `03-report.json` | Final report, grade, recommendations |

---

## STEP 0: Verify User Intent with AskUserQuestion

**BEFORE creating tasks**, clarify assessment dimensions:

```python
AskUserQuestion(
  questions=[{
    "question": "What dimensions to assess?",
    "header": "Dimensions",
    "options": [
      {"label": "Full assessment (Recommended)", "description": "All dimensions: quality, maintainability, security, performance"},
      {"label": "Code quality only", "description": "Readability, complexity, best practices"},
      {"label": "Security focus", "description": "Vulnerabilities, attack surface, compliance"},
      {"label": "Quick score", "description": "Just give me a 0-10 score with brief notes"}
    ],
    "multiSelect": false
  }]
)
```

**Based on answer, adjust workflow:**
- **Full assessment**: All 7 phases, parallel agents
- **Code quality only**: Skip security and performance phases
- **Security focus**: Prioritize security-auditor agent
- **Quick score**: Single pass, brief output

---

## STEP 0b: Select Orchestration Mode

Load details: `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/assess/references/orchestration-mode.md")` for env var check logic, Agent Teams vs Task Tool comparison, and mode selection rules.

---

## 🚨 Task Management (CC 2.1.16)

```python
# 1. Create main task IMMEDIATELY
TaskCreate(
  subject="Assess: {target}",
  description="Comprehensive evaluation with quality scores and recommendations",
  activeForm="Assessing {target}"
)

# 2. Create subtasks for each assessment phase
TaskCreate(subject="Understand target and gather context", activeForm="Understanding target")   # id=2
TaskCreate(subject="Discover scope and build file list", activeForm="Discovering scope")        # id=3
TaskCreate(subject="Rate quality across 6 dimensions", activeForm="Rating quality")             # id=4
TaskCreate(subject="Analyze pros and cons", activeForm="Analyzing pros/cons")                   # id=5
TaskCreate(subject="Compare alternatives", activeForm="Comparing alternatives")                 # id=6
TaskCreate(subject="Generate improvement suggestions", activeForm="Generating suggestions")     # id=7
TaskCreate(subject="Compile assessment report", activeForm="Compiling report")                  # id=8

# 3. Set dependencies for sequential phases
TaskUpdate(taskId="3", addBlockedBy=["2"])  # Scope needs target understanding
TaskUpdate(taskId="4", addBlockedBy=["3"])  # Rating needs scoped file list
TaskUpdate(taskId="5", addBlockedBy=["4"])  # Pros/cons needs quality scores
TaskUpdate(taskId="6", addBlockedBy=["4"])  # Alternatives need quality scores
TaskUpdate(taskId="7", addBlockedBy=["5", "6"])  # Suggestions need analysis
TaskUpdate(taskId="8", addBlockedBy=["7"])  # Report needs suggestions

# 4. Update status as you progress
TaskUpdate(taskId="2", status="in_progress")  # When starting
TaskUpdate(taskId="2", status="completed")    # When done — repeat for each subtask
```

---

## What This Skill Answers

| Question | How It's Answered |
|----------|-------------------|
| "Is this good?" | Quality score 0-10 with reasoning |
| "What are the trade-offs?" | Structured pros/cons list |
| "Should we change this?" | Improvement suggestions with effort |
| "What are the alternatives?" | Comparison with scores |
| "Where should we focus?" | Prioritized recommendations |

---

## 🔄 Workflow Overview

| Phase | Activities | Output |
|-------|------------|--------|
| **1. Target Understanding** | Read code/design, identify scope | Context summary |
| **1.5. Scope Discovery** | Build bounded file list | Scoped file list |
| **2. Quality Rating** | 6-dimension scoring (0-10) | Scores with reasoning |
| **3. Pros/Cons Analysis** | Strengths and weaknesses | Balanced evaluation |
| **4. Alternative Comparison** | Score alternatives | Comparison matrix |
| **5. Improvement Suggestions** | Actionable recommendations | Prioritized list |
| **6. Effort Estimation** | Time and complexity estimates | Effort breakdown |
| **7. Assessment Report** | Compile findings | Final report |

---

## Phase 1: Target Understanding

Identify what's being assessed and gather context. `TARGET` here is the value Step 0 already
resolved, which is not necessarily what the user typed.

```python
# PARALLEL - Gather context
Read(file_path=TARGET)                                   # only when TARGET is a path
Grep(pattern=TARGET, output_mode="files_with_matches")   # topic or symbol
mcp__memory__search_nodes(query=TARGET)                  # past decisions
```

`Read` failing is NOT a reason to stop. A target resolved from the conversation is usually a
subject rather than a filename ("the three pretool guards", "today's hook fixes"), so the Read
misses and the Grep plus the conversation carry the context. Treat a failed Read as "this is a
topic, not a path" and continue to Phase 1.5, which discovers the real file list anyway.

---

## Phase 1.5: Scope Discovery

Load `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/assess/references/scope-discovery.md")` for the full file discovery, limit application (MAX 30 files), and sampling priority logic. **Always include the scoped file list** in every agent prompt.

### Progressive Output (CC 2.1.76)

Output results **incrementally** as each evaluation phase completes:

| After Phase | Show User |
|-------------|-----------|
| 1. Target Understanding | Scope summary, file list, context |
| 1.5. Scope Discovery | Bounded file list (max 30 files) |
| 2. Quality Rating | Each dimension's score as the evaluating agent returns |
| 3. Pros/Cons | Balanced evaluation summary |

For Phase 2 parallel agents, show each dimension's score **as soon as the evaluating agent returns** — don't wait for all 4 agents. If any dimension scores below 4/10, flag it immediately as a priority concern requiring user attention.

---

## Phase 2: Quality Rating (6 Dimensions)

Rate each dimension 0-10 with weighted composite score. Load `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/quality-gates/references/unified-scoring-framework.md")` for dimensions, weights, grade interpretation, and per-dimension criteria. Load `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/assess/references/quality-model.md")` for assess-specific overrides.

Load `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/assess/references/agent-spawn-definitions.md")` for Task Tool mode spawn patterns and Agent Teams alternative.

**Composite Score:** Weighted average of all 6 dimensions (see quality-model.md).

---

## Phase 2.5: Adversarial Refutation (effort-gated)

The assessor that scores a dimension is also its only judge — self-preferential bias.
A separate **blind refuter** verifies decision-bearing scores before they reach the
composite. **Effort gate:** `low`/`medium` skip this phase entirely; `high` runs up-to-4
single refuters (advisory, no auto-swing); `xhigh` runs 3-refuter majority with auto-revise.

Load the protocol + assess bindings: `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/assess/references/adversarial-refutation.md")`
(which loads the shared engine `$\{CLAUDE_PLUGIN_ROOT\}/shared/rules/adversarial-refutation.md`).
Producer findings must first pass the evidence-replay gate before entering any score or verdict: `Read("$\{CLAUDE_PLUGIN_ROOT\}/shared/rules/evidence-replay.md")`.

### Cross-model refuter (optional, provenance-labeled, cost-gated)

When `ORK_ALT_MODEL_CMD` is configured and effort is `high`/`xhigh`, one quorum slot per high-weight or boundary-adjacent dimension score can route to a non-Claude model (Codex/GPT) for diverse failure modes. Off by default; substitutes one same-model slot, stamps `refuter_model` for provenance, cannot silently raise the grade (engine §7), owns no credentials/egress (shells out via `ORK_ALT_MODEL_CMD`, matches the egress guard #2533), and degrades to same-model on an absent command. Shares the review-pr operational doc: `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/review-pr/references/cross-model-refuter.md")`.

Runs after Phase 2 returns, before the composite/grade and Phases 3-7. Refuters are ALWAYS
isolated `Agent(...)` Task spawns (never team members, even in Agent Teams mode) fed only the
serialized claim — no producer score, identity, or prose. Revised scores recompute the
composite; the refutation ledger (`02b-refutation.json`) records survived/killed/downgraded
so wrong scores are auditable. Keep the producer-basis score AND a labeled post-refutation
score — refutation never silently raises the grade.

---

## Phases 3-7: Analysis, Comparison & Report

Load `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/assess/references/phase-templates.md")` for output templates for pros/cons, alternatives, improvements, effort, and the final report.

See also: `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/assess/references/alternative-analysis.md")` | `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/assess/references/improvement-prioritization.md")`

---

## Phase 7b: Emit Dashboard Spec (json-render)

Parse `--render=` from `$ARGUMENTS`. Default is `both`.

| Mode | Behavior |
|------|----------|
| `markdown` | Current behavior — markdown assessment report only. No spec emitted. |
| `json-render` | Emit `.claude/chain/assess-dashboard.json` only. Skip markdown report. |
| `both` | Emit spec **and** markdown. Default — human reads the report, downstream skills parse the spec. |

When emitting a spec:

1. Load format and catalog: `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/assess/references/dashboard-spec.md")`. Example: `references/dashboard-example.json`.
2. Build the spec using only catalog types: `Card`, `StatGrid`, `DataTable`, `StatusBadge`, `BarMeter`, `Markdown`. Top-level fields `composite` (number) and `grade` (string) are required for assess specs.
3. One `BarMeter` per dimension scored. The `verdict` element is a `StatusBadge` with status `success`/`warning`/`error` mapped from grade (A/B → success, C → warning, D/F → error).
4. Write to `.claude/chain/assess-dashboard.json` with compact JSON.
5. Validate before declaring success:

```bash
node "${CLAUDE_PLUGIN_ROOT}/skills/assess/scripts/render-spec.mjs" .claude/chain/assess-dashboard.json --check
```

If validation fails, fall back to markdown-only and surface the error. Never write a partial spec.

6. For `--render=both`, render the markdown view from the spec:

```bash
node "${CLAUDE_PLUGIN_ROOT}/skills/assess/scripts/render-spec.mjs" .claude/chain/assess-dashboard.json
```

This guarantees JSON spec and markdown report stay in sync.

**xhigh effort:** when `effort=xhigh` is active, add a sibling `Markdown` element per dimension containing `confidence` and `caveats` from the uncertainty pass. Reference list it in the `dimensions` Card's children alongside the `BarMeter`. See `references/dashboard-spec.md` for the exact pattern.

**Downstream consumption:** `/ork:implement` reads `.claude/chain/assess-dashboard.json` and pulls the lowest-scoring dimension and high-priority improvements (effort ≤ 2 AND impact ≥ 4) without parsing markdown tables. Measured: assess spec ≈ 830 tokens vs ~3500 token markdown for the same content.

---

## Phase 7c: Memory Writeback (signal-fired, optional)

When the assessment lands with a composite score, optionally persist scores + summary to the memory MCP knowledge graph as a typed entity. Future `/ork:memory` queries can then surface assessment lineage (which decisions did this codebase score 9/10 on testability? when did security regress below 7.0?).

```bash
python3 ${CLAUDE_PLUGIN_ROOT}/skills/assess/scripts/memory_writeback.py "<assessment-dir>"
```

`&lt;assessment-dir&gt;` is the dir containing `assessment.json` (typically the session's `.claude/chain/`). The script writes a `memory-writeback.json` handoff alongside it.

Auto-skip conditions (all exit 0, all WARN-logged):

| Skip reason | Trigger |
|-------------|---------|
| `no composite score` | `assessment.json` has no top-level `composite` numeric field |
| `yg-mcp-core not importable` | `yg-mcp-core>=0.3.0` not installed (orchestkit is public; yg-mcp-core lives on private `pypi.yonyon.ai` — HQ-only) |
| `memory MCP unreachable` | memory MCP server down OR `.mcp.json` doesn't define `memory` |

The created entity has:
- `name`: `&lt;slug-or-dir&gt;@&lt;timestamp&gt;` (stable across re-runs — re-runs create new entities)
- `entityType`: `assessment` (override with `--entity-type &lt;type&gt;`)
- `observations`: `composite=X.XX`, one `&lt;dim&gt;=X.XX` per scored dimension, optional `summary: ...` and `topic: ...`

Mirrors `Yonatan-HQ/hq-ext-plugin#194` (audio_podcast handler) and orchestkit#1886 (post-synthesis podcast) pattern. Unblocked by `Yonatan-HQ/core#993` (yg-mcp-core 0.3.0).

---

## Phase 7d: Emit Chain Verdict (stop-gating)

After the composite and grade are final (post-refutation, Phase 2.5), ALWAYS write the machine-readable verdict — this is the stop-gate `/ork:implement` reads before Phase 1. Mirror the Phase 7b spec-emit pattern: build, write compact JSON, never write a partial file.

```json
// .claude/chain/assess-verdict.json
{
  "rubric": "ork-rubric/1.0",
  "skill": "assess",
  "verdict": "fail",
  "composite": 5.1,
  "dimension_scores": {"correctness": 7.0, "maintainability": 6.5, "performance": 5.5, "security": 3.2, "scalability": 6.0, "testability": 4.8, "compliance": 6.2},
  "blockers": [
    {"dimension": "security", "score": 3.2, "reason": "Unparameterized SQL in auth path (src/api/auth.ts:42)"}
  ],
  "feature": "<assessment topic, e.g. first non-flag token of $ARGUMENTS>"
}
```

Verdict rules — thresholds come from `$\{CLAUDE_PLUGIN_ROOT\}/skills/assess/rubric.json` (schema: `$\{CLAUDE_PLUGIN_ROOT\}/shared/rubric.schema.json`):

- `verdict = "fail"` when `composite &lt; min_pass` (5.5) **OR** any dimension scores below its `min_blocker`. Otherwise `"pass"`.
- Every dimension below its `min_blocker` gets a `blockers[]` entry — dimension, score, one evidence-backed reason. `blockers` is `[]` on pass.
- Scores are the post-refutation numbers — the same ones in the report. Refutation never silently flips a fail to pass.

Consumers: `/ork:implement` Step -0.5 blocks Phase 1 on `verdict == "fail"` (user must fix-first or explicitly override); Phase 7c memory writeback persists the verdict + dimension scores to the memory graph (add a `verdict=pass|fail` observation) for cross-session learning.

---

## Self-Reported Uncertainty (`xhigh` effort)

Current-generation models report their own limits far better than older tiers did. When `xhigh` effort is active, enrich each dimension's rating with a `confidence` level and a list of `caveats` — things the model couldn't verify, assumptions it relied on, or cases it didn't test.

Output schema per dimension (JSON):

```json
{
  "dimension": "security",
  "score": 7.2,
  "confidence": "medium",              // "low" | "medium" | "high"
  "caveats": [
    "Didn't execute the SQL queries against a real DB to confirm parameterization",
    "Assumed NODE_ENV=production in deployment; didn't verify CI config",
    "Reviewed 12 of 15 handlers; remaining 3 deferred by scope filter"
  ],
  "evidence": ["src/api/auth.ts:42", "src/middleware/guard.ts:88"]
}
```

Rules:
- **Do not use `confidence` as an auto-gate.** It's a signal for the human reader, not a pass/fail threshold.
- **`caveats` must be specific.** "Didn't check X" with file paths beats "uncertainty about security".
- **If a caveat is cheap to resolve, resolve it** instead of recording it. Caveats are for things that genuinely can't be verified within the skill's scope (e.g., production runtime behavior, future input patterns).
- **Composite score still computes from `score` only** — not weighted by confidence — to keep the number comparable across runs.

---

## 💡 Grade Interpretation

Load `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/quality-gates/references/unified-scoring-framework.md")` for grade thresholds and scoring criteria.

---

## Key Decisions

| Decision | Choice | Rationale |
|----------|--------|-----------|
| 6 dimensions | Comprehensive coverage | All quality aspects without overwhelming |
| 0-10 scale | Industry standard | Easy to understand and compare |
| Parallel assessment | 4 agents (6 dimensions) | Fast, thorough evaluation |
| Effort/Impact scoring | 1-5 scale | Simple prioritization math |

---

## Rules Quick Reference

| Rule | Impact | What It Covers |
|------|--------|----------------|
| complexity-metrics (load `$\{CLAUDE_PLUGIN_ROOT\}/skills/assess/rules/complexity-metrics.md`) | HIGH | 7-criterion scoring (1-5), complexity levels, thresholds |
| complexity-breakdown (load `$\{CLAUDE_PLUGIN_ROOT\}/skills/assess/rules/complexity-breakdown.md`) | HIGH | Task decomposition strategies, risk assessment |

## Quality Bar

Done means all of these hold:
- Every in-scope dimension scored 0-10 with evidence (file:line) backing the score, not vibes
- Composite is the weighted average of the scored dimensions and the grade maps from that composite
- At `high`/`xhigh` effort, decision-bearing scores passed the adversarial refutation lane before entering the composite
- `.claude/chain/assess-verdict.json` written with verdict pass/fail and a blockers[] entry for every dimension below its min_blocker
- Any dimension scoring below 4/10 is flagged immediately as a priority concern
- If a json-render spec is emitted, it passes `render-spec.mjs --check` and carries the required composite + grade fields

## 📜 Related Skills

- `ork:verify` - Post-implementation verification
- `ork:code-review-playbook` - Code review patterns
- `ork:quality-gates` - Task complexity assessment, gate patterns

---

**Version:** 1.8.0 (June 2026) — optional cross-model adversarial refuter lane (provenance + cost gate, #2542)


---

## Rules (2)

### Decompose complex tasks into isolated subtasks to reduce failure risk and enable parallelism — HIGH


## Task Decomposition Strategies

When a task scores Level 4-5 (Complex/Very Complex), decompose it into subtasks that each score Level 1-3.

### Decomposition Approach

1. **Identify independent axes** — separate concerns that can be worked on independently
2. **Isolate unknowns** — create a spike/research task for each unknown
3. **Reduce cross-cutting scope** — break into single-module changes
4. **Sequence by dependency** — order subtasks so blocked items come last

### Strategies by Complexity Driver

| High Criterion | Decomposition Strategy |
|---------------|----------------------|
| Lines of Code (4-5) | Split by component or layer |
| Files Affected (4-5) | Split by directory or module |
| Dependencies (4-5) | Isolate external integrations into adapter tasks |
| Unknowns (4-5) | Create spike tasks to resolve unknowns first |
| Cross-Cutting (4-5) | Split by layer (DB, API, UI) or by concern |
| Risk Level (4-5) | Add validation/testing tasks before implementation |

### Codebase Analysis for Decomposition

```bash
# Gather metrics to inform breakdown
./scripts/analyze-codebase.sh "$TARGET"

# Key signals:
# - File count > 10: split by directory
# - Import count > 5: isolate dependency interfaces
# - Test coverage < 50%: add test-first subtask
```

### Subtask Validation

Each subtask should score:
- **Average: 1.0-3.4** (Level 1-3) — manageable
- **Unknowns: &lt;= 2** — no major research needed
- **Cross-cutting: &lt;= 2** — limited to 2-3 modules

If any subtask still scores Level 4+, decompose it again.

### Risk Assessment Integration

| Risk Factor | Mitigation Task |
|-------------|-----------------|
| No test coverage | Add regression tests first |
| Complex business logic | Write specification/invariant tests |
| External API dependency | Create mock/adapter layer first |
| Database migration | Test migration on staging first |
| Multiple team coordination | Define interface contracts first |

### Key Rules

- Level 4-5 tasks are **never directly implemented** — decompose first
- Every subtask must score **Level 3 or below** individually
- Resolve **unknowns** before starting dependent implementation tasks
- Use **`TaskCreate` with `addBlockedBy`** to enforce subtask ordering
- Each subtask should be **independently verifiable** with its own tests
- Prefer **vertical slices** (end-to-end for one feature) over horizontal layers

**Incorrect — Starting Level 5 task without decomposition:**
```
Task: "Migrate authentication to OAuth2"
Complexity: 4.8 (Level 5)
Action: Start implementing directly
// High failure risk, scope creep likely
```

**Correct — Breaking into Level 1-3 subtasks:**
```
1. Research OAuth2 providers (Level 2, 1-2h)
2. Add OAuth library dependency (Level 1, 30m)
3. Implement OAuth callback handler (Level 2, 2-4h)
4. Migrate existing sessions (Level 3, 4-8h)
5. Add regression tests (Level 2, 2h)
```


### Score task complexity with structured frameworks to prevent scope creep and estimate drift — HIGH


## Complexity Scoring Frameworks

Score task complexity across 7 criteria (1-5 each) to determine if a task should proceed or be decomposed first.

### The 7 Criteria

| Criterion | 1 (Low) | 3 (Medium) | 5 (High) |
|-----------|---------|------------|----------|
| Lines of Code | &lt; 50 | 200-500 | 1500+ |
| Time Estimate | &lt; 30 min | 2-8 hours | 24+ hours |
| Files Affected | 1 file | 4-10 files | 26+ files |
| Dependencies | 0 deps | 2-3 deps | 7+ deps |
| Unknowns | None | Several, researchable | Unclear scope |
| Cross-Cutting | Single module | 4-5 modules | System-wide |
| Risk Level | Trivial | Testable complexity | Mission-critical |

### Complexity Levels

| Average Score | Level | Classification | Action |
|---------------|-------|----------------|--------|
| 1.0 - 1.4 | 1 | Trivial | Proceed immediately |
| 1.5 - 2.4 | 2 | Simple | Proceed |
| 2.5 - 3.4 | 3 | Moderate | Proceed with caution |
| 3.5 - 4.4 | 4 | Complex | Break down first |
| 4.5 - 5.0 | 5 | Very Complex | Decompose and reassess |

### Output Format

```markdown
## Complexity Assessment: [Target]

| Criterion | Score |
|-----------|-------|
| Lines of Code | X/5 |
| Time Estimate | X/5 |
| Files Affected | X/5 |
| Dependencies | X/5 |
| Unknowns | X/5 |
| Cross-Cutting | X/5 |
| Risk Level | X/5 |
| **Total** | **XX/35** |

**Average Score:** X.X
**Complexity Level:** X ([Classification])
**Can Proceed:** Yes/No
```

### Key Rules

- Score **all 7 criteria** even for seemingly simple tasks
- Total of **35 points** maximum, divide by 7 for average
- Level 4-5 tasks **must be decomposed** before starting implementation
- Unknowns (criterion 5) is the **highest variance** factor — resolve unknowns first
- Cross-cutting (criterion 6) indicates **coordination overhead** — account for it in estimates

**Incorrect — Skipping complexity assessment:**
```
Task: "Add real-time notifications"
Action: Start coding
// No idea of scope, likely 3-5x over estimate
```

**Correct — Scoring all 7 criteria first:**
```
| Criterion | Score |
|-----------|-------|
| Lines of Code | 4/5 (800+ lines) |
| Time Estimate | 4/5 (16+ hours) |
| Files Affected | 3/5 (8 files) |
| Dependencies | 4/5 (WebSockets, Redis) |
| Unknowns | 3/5 (some research needed) |
| Cross-Cutting | 4/5 (DB, API, UI, workers) |
| Risk Level | 3/5 (testable) |
| **Average** | **3.6 (Level 4 - Complex)** |

Action: Decompose into subtasks before starting
```



---

## References (11)

### Adversarial Refutation

# Adversarial Refutation — assess bindings

Thin adapter. Loads the shared engine, then binds it to assess's scoring model.

**Load the engine first:** `Read("$\{CLAUDE_PLUGIN_ROOT\}/shared/rules/adversarial-refutation.md")`
— the blindness contract, independent-score-first, citation-verify, quorum, cross-file
UPHELD-default, deterministic-exemption, no-auto-flip, spawn-ceiling, ledger schema, and
isolated-spawn rules. This file only supplies what's assess-specific.

## Bindings

| Engine concept | assess binding |
|----------------|----------------|
| "finding" | a per-dimension 0-10 score from Phase 2 (`02-evaluation.json`) |
| rubric | `quality-gates/references/unified-scoring-framework.md` + `references/quality-model.md` |
| refuter agent | the same `subagent_type` that scored the dimension (code-quality-reviewer / security-auditor / *-performance-engineer / test-generator), spawned blind |
| code artifact | the Phase 1.5 scoped file list (`references/scope-discovery.md`) + the ≤12-tool-call budget |
| ledger | `02b-refutation.json` (new Phase Handoffs row) |
| revised output | recomputed composite + a "Refuted?" note in the Phase 7 report; `refuted` + `original_score` fields on the Phase 7b dashboard dimension objects |

## Scope filter (which scores get a refuter)

A dimension score qualifies only if decision-bearing — ANY of:
- score **≥8** (praise-inflation: the assessor patting the subject on the back) or **≤4** (over-penalty)
- **high-weight** dimension (Security 0.20; Correctness/Maintainability/Compliance 0.15)
- within **±0.5 of a grade boundary** (refutation could flip the letter grade)
- a Phase 5 **Quick Win** (effort ≤2, impact ≥4) that `/ork:implement` will act on

Skip: mid-band (5-7) scores on low-weight dimensions (Scalability/Simplicity 0.10) not near a
boundary, and descriptive pros/cons with no score. Bounds spawns to ~2-4 per assessment.

## Effort gate (assess-specific)

- `low` / `medium` → **skip Phase 2.5 entirely**
- `high` → up-to-4 **single** refuters, advisory only (a single refuter never auto-swings a
  score; OVERTURNED-with-verified-citation is surfaced for the user, not auto-applied)
- `xhigh` → **3-refuter majority** per qualifying score; auto-revise to the near band edge only
  on ≥2-of-3 VERIFIED overturns; a 1-of-3 dissent writes the existing `confidence`/`caveats`
  channel and drops that dimension's confidence to "low"

## Isolation note

Even when Phase 2 ran in Agent Teams mode, Phase 2.5 refuters are ALWAYS standalone
`Agent(...)` Task spawns with **no `team_name`** — fed only the serialized claim from
`02-evaluation.json`. Joining the mesh would leak producer reasoning (engine rule 9).


### Agent Spawn Definitions

# Agent Spawn Definitions

Dimension-to-agent mapping and spawn patterns for Phase 2.

## Task Tool Mode (Default)

For each dimension, spawn a background agent with **scope constraints**:

```python
# Namespaced on purpose. A bare name is not in the registry and fails at
# dispatch with "Agent type not found" (#2371), which is what this default
# path did until 2026-08-04 while the Agent-Teams path below worked.
for dimension, agent_type in [
    ("CORRECTNESS + MAINTAINABILITY", "ork:code-quality-reviewer"),
    ("SECURITY", "ork:security-auditor"),
    ("PERFORMANCE + SCALABILITY", "ork:python-performance-engineer"),  # backend; use ork:frontend-performance-engineer for frontend
    ("TESTABILITY", "ork:test-generator"),
]:
    Agent(subagent_type=agent_type, run_in_background=True, max_turns=25,
         model=MODEL_OVERRIDE,  # None inherits default; "opus" for deep analysis (CC 2.1.72)
         prompt=f"""Assess {dimension} (0-10) for: {target}

## Scope Constraint
ONLY read and analyze the following {len(scope_files)} files -- do NOT explore beyond this list:
{file_list}

Budget: Use at most 15 tool calls. Read files from the list above, then produce your score
with reasoning, evidence, and 2-3 specific improvement suggestions.
Do NOT use Glob or Grep to discover additional files.""")
```

Then collect results from all agents and proceed to Phase 3.

## Agent Teams Alternative

See [agent-teams-mode.md](agent-teams-mode.md) for Agent Teams assessment workflow with cross-validation and team teardown.

## Context Window Note

For full codebase assessments (>20 files), use the 1M context window to avoid agent context exhaustion. On 200K context, the scope discovery in [scope-discovery.md](scope-discovery.md) limits files to prevent overflow.


### Agent Teams Mode

# Agent Teams Assessment Mode

In Agent Teams mode, form an assessment team where dimension assessors cross-validate scores and discuss disagreements:

```python
# CC 2.1.178+: one implicit team per session — no TeamCreate.
# Spawn teammates directly via Agent(name=...). Requires
# CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 (set in ork.settings.json).

# SCOPE CONSTRAINT (injected into every agent prompt):
SCOPE_INSTRUCTIONS = f"""
## Scope Constraint
ONLY read and analyze the following {len(scope_files)} files — do NOT explore beyond this list:
{file_list}

Budget: Use at most 15 tool calls. Read files from the list above, then score.
Do NOT use Glob or Grep to discover additional files.
"""

Agent(subagent_type="ork:code-quality-reviewer", name="correctness-assessor",
     team_name="assess-{target-slug}", max_turns=25, model=MODEL_OVERRIDE,
     prompt=f"""Assess CORRECTNESS (0-10) and MAINTAINABILITY (0-10) for: {target}
     {SCOPE_INSTRUCTIONS}
     When you find issues that affect security, message security-assessor.
     When you find issues that affect performance, message perf-assessor.
     Share your scores with all teammates for calibration — if scores diverge
     significantly (>2 points), discuss the disagreement.""")

Agent(subagent_type="ork:security-auditor", name="security-assessor",
     team_name="assess-{target-slug}", max_turns=25, model=MODEL_OVERRIDE,
     prompt=f"""Assess SECURITY (0-10) for: {target}
     {SCOPE_INSTRUCTIONS}
     When correctness-assessor flags security-relevant patterns, investigate deeper.
     When you find performance-impacting security measures, message perf-assessor.
     Share your score and flag any cross-dimension trade-offs.""")

Agent(subagent_type="ork:python-performance-engineer", name="perf-assessor",  # or frontend-performance-engineer for frontend
     team_name="assess-{target-slug}", max_turns=25, model=MODEL_OVERRIDE,
     prompt=f"""Assess PERFORMANCE (0-10) and SCALABILITY (0-10) for: {target}
     {SCOPE_INSTRUCTIONS}
     When security-assessor flags performance trade-offs, evaluate the impact.
     When you find testability issues (hard-to-benchmark code), message test-assessor.
     Share your scores with reasoning for the composite calculation.""")

Agent(subagent_type="ork:test-generator", name="test-assessor",
     team_name="assess-{target-slug}", max_turns=25, model=MODEL_OVERRIDE,
     prompt=f"""Assess TESTABILITY (0-10) for: {target}
     {SCOPE_INSTRUCTIONS}
     Evaluate test coverage, test quality, and ease of testing.
     When other assessors flag dimension-specific concerns, verify test coverage
     for those areas. Share your score and any coverage gaps found.""")
```

**Team teardown** after report compilation:
```python
# CC 2.1.178+: no TeamDelete — teammates wind down at turn end
# (press Ctrl+F twice to stop lingering background teammates).

# Worktree cleanup (CC 2.1.72)
ExitWorktree(action="keep")
```

> **Fallback — Team Formation Failure:** If team formation fails, use standard Phase 2 Task spawns.
>
> **Fallback — Context Exhaustion:** If agents hit "Context limit reached" before returning scores, collect whatever partial results were produced, then score remaining dimensions yourself using the scoped file list from Phase 1.5. Do NOT re-spawn agents — assess the remaining dimensions inline and proceed to Phase 3.


### Alternative Analysis

# Alternative Analysis Reference

How to identify, evaluate, and compare alternatives to the current approach.

## Identifying Alternatives

1. **Direct Substitutes**: Different implementations of the same solution
2. **Architectural Alternatives**: Different design patterns or approaches
3. **Technology Alternatives**: Different libraries, frameworks, or tools
4. **Hybrid Approaches**: Combinations of multiple alternatives

## Comparison Dimensions

| Dimension | Question | Weight |
|-----------|----------|--------|
| Score | How does it rate on 6 dimensions? | 0.30 |
| Effort | How hard to implement/migrate? | 0.25 |
| Risk | What could go wrong? | 0.25 |
| Benefit | What's the expected improvement? | 0.20 |

## Migration Effort Scale

| Level | Description | Time Estimate |
|-------|-------------|---------------|
| 1 | Drop-in replacement | &lt; 1 hour |
| 2 | Minor refactoring | 1-4 hours |
| 3 | Moderate changes | 1-2 days |
| 4 | Significant rework | 3-5 days |
| 5 | Major rewrite | 1+ weeks |

## Risk Categories

- **Technical**: Will it work? Compatibility issues?
- **Team**: Does team know this? Learning curve?
- **Timeline**: Can we afford the migration time?
- **Dependencies**: What else needs to change?

## Decision Criteria

**Switch if:**
- Score improvement >= 1.5 points AND effort &lt;= 3
- Current has critical security/correctness issues
- Alternative has significantly lower maintenance burden

**Stay if:**
- Score difference &lt; 1.0 point
- Migration effort >= 4 AND no critical issues
- Team familiarity strongly favors current

## Trade-off Documentation

```markdown
## Alternative: [Name]

**Score Delta:** +/-[N.N] points
**Migration Effort:** [1-5]
**Risk Level:** Low/Medium/High

### Why Consider
- [Benefit 1]
- [Benefit 2]

### Why Not
- [Drawback 1]
- [Drawback 2]

### Verdict: [Adopt/Defer/Reject]
```


### Assessment Dashboard Spec (json-render) — HIGH


# Assessment Dashboard Spec

When `--render=json-render` or `--render=both` is passed to `/ork:assess`, Phase 7 emits a json-render-compatible JSON spec to `.claude/chain/assess-dashboard.json` instead of (or in addition to) the markdown report.

The spec follows the **flat element-map format** documented in `ork:mcp-visual-output` — `\{ root, elements \}` with each element keyed by id and referencing children by id. This matches what `@json-render/mcp` 0.17+ consumes and what downstream skills can parse for structured handoff.

## Catalog

These are the only component types the spec is allowed to use. They map to `@json-render/shadcn` registry entries when rendered visually.

| Type | Purpose | Required Props |
|------|---------|----------------|
| `Card` | Section wrapper with optional title | `title?: string` |
| `StatGrid` | Composite score + grade at a glance | `items: \{ label, value, trend?, color? \}[]` |
| `DataTable` | Per-dimension scores, pros/cons, alternatives | `columns: \{ key, label \}[]`, `rows: Record&lt;string,string&gt;[]` |
| `StatusBadge` | Verdict (EXCELLENT, GOOD, ADEQUATE, NEEDS WORK, CRITICAL) | `label: string`, `status: success|warning|error|info|pending` |
| `BarMeter` | Per-dimension score 0-10 | `label: string`, `value: number` (0-10), `color?: string` |
| `Markdown` | Free-text reasoning, caveats | `content: string` |

`color` enum: `green | red | yellow | blue | gray`. Use `green` for ≥8, `yellow` for 5–7.9, `red` for &lt;5.

## Example

A complete spec for `/ork:assess backend/app/services/auth.py`:

```json
{
  "root": "report",
  "version": "1.0.0",
  "skill": "assess",
  "target": "backend/app/services/auth.py",
  "grade": "B+",
  "composite": 7.4,
  "elements": {
    "report": {
      "type": "Card",
      "props": { "title": "Assessment — backend/app/services/auth.py" },
      "children": ["headline", "verdict", "dimensions", "pros-cons", "improvements"]
    },
    "headline": {
      "type": "StatGrid",
      "props": {
        "items": [
          { "label": "Composite", "value": "7.4/10", "color": "green" },
          { "label": "Grade", "value": "B+", "color": "green" },
          { "label": "Effort to A", "value": "1 day" },
          { "label": "Lowest", "value": "Testability 5.5", "color": "yellow" }
        ]
      }
    },
    "verdict": {
      "type": "StatusBadge",
      "props": { "label": "GOOD — ship with two follow-ups", "status": "success" }
    },
    "dimensions": {
      "type": "Card",
      "props": { "title": "Per-Dimension Scores" },
      "children": ["dim-correctness", "dim-maintainability", "dim-security", "dim-performance", "dim-testability", "dim-architecture", "dim-documentation"]
    },
    "dim-correctness": { "type": "BarMeter", "props": { "label": "Correctness", "value": 8.5, "color": "green" } },
    "dim-maintainability": { "type": "BarMeter", "props": { "label": "Maintainability", "value": 7.0, "color": "green" } },
    "dim-security": { "type": "BarMeter", "props": { "label": "Security", "value": 8.0, "color": "green" } },
    "dim-performance": { "type": "BarMeter", "props": { "label": "Performance", "value": 7.5, "color": "green" } },
    "dim-testability": { "type": "BarMeter", "props": { "label": "Testability", "value": 5.5, "color": "yellow" } },
    "dim-architecture": { "type": "BarMeter", "props": { "label": "Architecture", "value": 8.0, "color": "green" } },
    "dim-documentation": { "type": "BarMeter", "props": { "label": "Documentation", "value": 6.0, "color": "yellow" } },
    "pros-cons": {
      "type": "DataTable",
      "props": {
        "columns": [
          { "key": "side", "label": "" },
          { "key": "item", "label": "Item" },
          { "key": "weight", "label": "Weight" }
        ],
        "rows": [
          { "side": "Pro", "item": "Token rotation correctly invalidates old refresh", "weight": "High" },
          { "side": "Pro", "item": "Pure functions for JWT verify — easy to test in isolation", "weight": "Med" },
          { "side": "Con", "item": "No tests for the rotation grace window", "weight": "High" },
          { "side": "Con", "item": "Session.refresh logs raw token on debug=True", "weight": "High" }
        ]
      }
    },
    "improvements": {
      "type": "DataTable",
      "props": {
        "columns": [
          { "key": "action", "label": "Action" },
          { "key": "effort", "label": "Effort" },
          { "key": "impact", "label": "Impact" },
          { "key": "priority", "label": "Priority" }
        ],
        "rows": [
          { "action": "Add rotation grace-window test", "effort": "1", "impact": "5", "priority": "5.0" },
          { "action": "Strip token from debug log line", "effort": "1", "impact": "4", "priority": "4.0" },
          { "action": "Document refresh contract", "effort": "2", "impact": "3", "priority": "1.5" }
        ]
      }
    }
  }
}
```

## Token cost (measured)

The example above serializes to **~900 tokens** of compact JSON. The equivalent markdown report (using `references/phase-templates.md` + `references/scoring-rubric.md`) for the same content is **~3500 tokens**.

The downstream win: `/ork:implement` reading this spec from `.claude/chain/assess-dashboard.json` knows the lowest-scoring dimension, the high-priority improvements, and the verdict — without re-parsing markdown tables.

## xhigh effort additions

When `effort=xhigh` is active, each `BarMeter` element gains a sibling `Markdown` element with caveats:

```json
"dim-security-caveats": {
  "type": "Markdown",
  "props": { "content": "**Confidence:** medium\n\n- Didn't execute SQL against a real DB to confirm parameterization\n- Reviewed 12 of 15 handlers; 3 deferred by scope filter" }
}
```

The `dimensions` Card lists both `dim-security` and `dim-security-caveats` as children. This is opt-in via `--render=json-render --effort=xhigh`.

## Validation

`scripts/render-spec.mjs` validates the spec on emission:

- All children ids resolve in `elements`
- Component types are in the catalog
- BarMeter values in [0, 10]
- DataTable rows match column keys
- Composite is in [0, 10]; grade matches grade interpretation thresholds

Invalid spec → fallback to markdown, never emit a partial spec.


### Improvement Prioritization

# Improvement Prioritization Reference

Systematic approach to ranking improvements by value delivered per effort invested.

## Impact/Effort Scoring

### Impact Scale (1-5)

| Score | Label | Effect on Quality |
|-------|-------|-------------------|
| 5 | Critical | Fixes blocker, +2.0+ points |
| 4 | High | Major improvement, +1.0-2.0 |
| 3 | Medium | Notable improvement, +0.5-1.0 |
| 2 | Low | Minor improvement, +0.2-0.5 |
| 1 | Minimal | Cosmetic, +0.1-0.2 |

### Effort Scale (1-5)

| Score | Label | Time Required |
|-------|-------|---------------|
| 1 | Trivial | &lt; 15 minutes |
| 2 | Easy | 15-60 minutes |
| 3 | Medium | 1-4 hours |
| 4 | Hard | 4-8 hours |
| 5 | Very Hard | 1+ days |

## Priority Formula

```
Priority = Impact / Effort
```

Higher priority = do first. At equal priority, prefer lower effort.

## Improvement Categories

| Category | Impact | Effort | Action |
|----------|--------|--------|--------|
| **Quick Wins** | High (4-5) | Low (1-2) | Do immediately |
| **Strategic** | High (4-5) | High (4-5) | Plan carefully |
| **Fill-ins** | Low (1-2) | Low (1-2) | Do when idle |
| **Avoid** | Low (1-2) | High (4-5) | Skip or defer |

## Time Estimation Guidelines

- **Add buffer**: Estimate x1.5 for unknowns
- **Include testing**: Add 30% for test updates
- **Account for review**: Add time for PR process
- **Consider dependencies**: Chain effects on other work

## Sequencing Dependencies

1. **Blockers first**: Changes that unblock other work
2. **Foundation changes**: Structural changes before features
3. **Shared code**: Common utilities before consumers
4. **Leaf nodes last**: Isolated changes can wait

## Quick Reference

```
Priority 5.0+  = Do NOW (high impact, trivial effort)
Priority 2.0+  = Do soon (good ROI)
Priority 1.0+  = Schedule it
Priority <1.0  = Backlog or skip
```


### Orchestration Mode

&lt;!-- SHARED: keep in sync with ../../../verify/references/orchestration-mode.md --&gt;
# Orchestration Mode Selection

Shared logic for choosing between Agent Teams and Task tool orchestration in assess/verify skills.

## Environment Check

```python
# Agent Teams is GA since CC 2.1.33
import os
force_task_tool = os.environ.get("ORCHESTKIT_FORCE_TASK_TOOL") == "1"

if force_task_tool:
    mode = "task_tool"
else:
    # Teams available by default — use for full multi-dimensional work
    mode = "agent_teams" if scope == "full" else "task_tool"
```

## Decision Rules

1. Full assessment/verification scope --> **Agent Teams mode** (GA since CC 2.1.33)
2. Quick/single-dimension scope --> **Task tool mode**
3. `ORCHESTKIT_FORCE_TASK_TOOL=1` --> **Task tool** (override)

## Agent Teams vs Task Tool

| Aspect | Task Tool (Star) | Agent Teams (Mesh) |
|--------|------------------|-------------------|
| Topology | All agents report to lead | Agents communicate with each other |
| Finding correlation | Lead cross-references after completion | Agents share findings in real-time |
| Cross-domain overlap | Independent scoring | Agents alert each other about overlapping concerns |
| Cost | ~200K tokens | ~500K tokens |
| Best for | Focused/single-dimension work | Full multi-dimensional assessment/verification |

## Fallback

If Agent Teams encounters issues mid-execution, fall back to Task tool for remaining work. This is safe because both modes produce the same output format (dimensional scores 0-10).

## Context Window Note

For full codebase work (>20 files), use the 1M context window to avoid agent context exhaustion. On 200K context, scope discovery should limit files to prevent overflow.


### Phase Templates

# Phase Output Templates

Markdown templates for assessment phases 3-7.

## Phase 3: Pros/Cons Analysis

```markdown
## Pros (Strengths)
| # | Strength | Impact | Evidence |
|---|----------|--------|----------|
| 1 | [strength] | High/Med/Low | [example] |

## Cons (Weaknesses)
| # | Weakness | Severity | Evidence |
|---|----------|----------|----------|
| 1 | [weakness] | High/Med/Low | [example] |

**Net Assessment:** [Strengths outweigh / Balanced / Weaknesses dominate]
**Recommended action:** [Keep as-is / Improve / Reconsider / Rewrite]
```

## Phase 4: Alternative Comparison

See [alternative-analysis.md](alternative-analysis.md) for full comparison template.

| Criteria | Current | Alternative A | Alternative B |
|----------|---------|---------------|---------------|
| Composite | [N.N] | [N.N] | [N.N] |
| Migration Effort | N/A | [1-5] | [1-5] |

## Phase 5: Improvement Suggestions

See [improvement-prioritization.md](improvement-prioritization.md) for effort/impact guidelines.

| Suggestion | Effort (1-5) | Impact (1-5) | Priority (I/E) |
|------------|--------------|--------------|----------------|
| [action] | [N] | [N] | [ratio] |

**Quick Wins** = Effort &lt;= 2 AND Impact &gt;= 4. Always highlight these first.

## Phase 6: Effort Estimation

| Timeframe | Tasks | Total |
|-----------|-------|-------|
| Quick wins (&lt; 1hr) | [list] | X min |
| Short-term (&lt; 1 day) | [list] | X hrs |
| Medium-term (1-3 days) | [list] | X days |

## Phase 7: Assessment Report

See [scoring-rubric.md](scoring-rubric.md) for full report template.

```markdown
# Assessment Report: $ARGUMENTS

**Overall Score: [N.N]/10** (Grade: [A+/A/B/C/D/F])

**Verdict:** [EXCELLENT | GOOD | ADEQUATE | NEEDS WORK | CRITICAL]

## Answer: Is This Good?
**[YES / MOSTLY / SOMEWHAT / NO]**
[Reasoning]
```


### Quality Model

# Quality Model (assess)

Uses the unified scoring framework with 7 base dimensions (no Visual).

> **Canonical source**: `quality-gates/references/unified-scoring-framework.md`
> Load: `Read("$\{CLAUDE_PLUGIN_ROOT\}/skills/quality-gates/references/unified-scoring-framework.md")`

## assess-Specific Overrides

**Simplicity dimension:** Activate when the user is comparing alternatives, evaluating design options, or assessing refactoring approaches. Skip for single-implementation reviews where there's nothing to compare against.

## Dimensions Used

### Default Mode (single implementation review)

| Dimension | Weight |
|-----------|--------|
| Correctness | 0.15 |
| Maintainability | 0.15 |
| Performance | 0.12 |
| Security | 0.20 |
| Scalability | 0.10 |
| Testability | 0.13 |
| Compliance | 0.15 |

### Comparison Mode (design alternatives, refactoring options)

| Dimension | Weight |
|-----------|--------|
| Correctness | 0.14 |
| Maintainability | 0.14 |
| Performance | 0.11 |
| Security | 0.18 |
| Scalability | 0.09 |
| Testability | 0.12 |
| Compliance | 0.12 |
| **Simplicity** | **0.10** |

Activate Comparison Mode when the user asks "which is better", "compare these", "should we refactor", or is evaluating multiple approaches. See unified framework for Simplicity scoring guide.

See unified framework for grade thresholds, improvement prioritization, effort/impact scales, and blocking rules.


### Scope Discovery

# Phase 1.5: Scope Discovery (CRITICAL -- prevents context exhaustion)

**Before spawning any agents**, build a bounded file list. Agents that receive unbounded targets will exhaust their context windows reading the entire codebase.

```python
# 1. Discover target files
if is_file(target):
    scope_files = [target]
elif is_directory(target):
    scope_files = Glob(f"{target}/**/*.{{py,ts,tsx,js,jsx,go,rs,java}}")
else:
    # Concept/topic -- search for relevant files
    scope_files = Grep(pattern=target, output_mode="files_with_matches", head_limit=50)

# 2. Apply limits -- MAX 30 files for agent assessment
MAX_FILES = 30
if len(scope_files) > MAX_FILES:
    # Prioritize: entry points, configs, security-critical, then sample rest
    # Skip: test files (except for testability agent), generated files, vendor/
    prioritized = prioritize_files(scope_files)  # entry points first
    scope_files = prioritized[:MAX_FILES]
    # Tell user about sampling
    print(f"Target has {len(scope_files)} files. Sampling {MAX_FILES} representative files.")

# 3. Format as file list string for agent prompts
file_list = "\n".join(f"- {f}" for f in scope_files)
```

## Sampling Priorities (when >30 files)

1. Entry points (main, index, app, server)
2. Config files (settings, env, config)
3. Security-sensitive (auth, middleware, api routes)
4. Core business logic (services, models, domain)
5. Representative samples from remaining directories


### Scoring Rubric

# Scoring Rubric Reference

Detailed scoring guidelines for each quality dimension.

## Correctness (Weight: 0.20)

### Score 9-10: Excellent
- All functionality works as documented
- All edge cases handled gracefully
- Comprehensive error handling
- No known bugs
- Types are accurate and complete

### Score 7-8: Good
- Core functionality works correctly
- Most edge cases handled
- Good error handling
- Minor edge cases might be missing
- Types mostly accurate

### Score 5-6: Adequate
- Main happy path works
- Some edge cases unhandled
- Basic error handling
- Known minor bugs exist
- Some type inaccuracies

### Score 3-4: Poor
- Functionality partially works
- Many edge cases fail
- Minimal error handling
- Multiple bugs present
- Significant type issues

### Score 1-2: Critical
- Core functionality broken
- No edge case handling
- Errors cause crashes
- Critical bugs
- Types unreliable

### Score 0: Broken
- Does not function at all
- Cannot be used

---

## Maintainability (Weight: 0.20)

### Score 9-10: Excellent
- Crystal clear code, self-documenting
- Perfect naming conventions
- Single responsibility everywhere
- Cyclomatic complexity &lt; 5
- Any developer can understand immediately

### Score 7-8: Good
- Clear code with minor clarifications needed
- Good naming, occasional ambiguity
- Mostly single responsibility
- Cyclomatic complexity &lt; 10
- Reasonable onboarding time

### Score 5-6: Adequate
- Understandable with effort
- Mixed naming quality
- Some large functions
- Cyclomatic complexity &lt; 15
- Requires context to understand

### Score 3-4: Poor
- Difficult to understand
- Poor naming choices
- Multiple responsibilities mixed
- Cyclomatic complexity 15-20
- Requires original author to explain

### Score 1-2: Critical
- Incomprehensible
- Meaningless names
- Massive functions
- Cyclomatic complexity > 20
- "Here be dragons"

### Score 0: Broken
- Cannot be maintained at all

---

## Performance (Weight: 0.15)

### Score 9-10: Excellent
- Optimal algorithm choices
- No unnecessary operations
- Proper caching
- Async where beneficial
- Measured and optimized

### Score 7-8: Good
- Good algorithm choices
- Minor inefficiencies
- Some caching
- Async used appropriately
- No major bottlenecks

### Score 5-6: Adequate
- Acceptable algorithms
- Some unnecessary operations
- Limited caching
- Missing async opportunities
- Noticeable but tolerable delays

### Score 3-4: Poor
- Suboptimal algorithms (O(n^2) in hot paths)
- Many unnecessary operations
- No caching strategy
- Blocking where should be async
- Noticeable performance issues

### Score 1-2: Critical
- Wrong algorithm choices
- Excessive operations
- Performance blockers
- User-impacting delays

### Score 0: Broken
- Unusable due to performance

---

## Security (Weight: 0.15)

### Score 9-10: Excellent
- All OWASP Top 10 addressed
- Input validation everywhere
- Proper authentication/authorization
- Secrets managed correctly
- Security reviewed

### Score 7-8: Good
- Most security concerns addressed
- Good input validation
- Proper auth patterns
- No obvious vulnerabilities
- Minor improvements possible

### Score 5-6: Adequate
- Basic security in place
- Some validation gaps
- Auth works but could be tighter
- No critical vulnerabilities
- Needs security review

### Score 3-4: Poor
- Security gaps present
- Missing input validation
- Auth issues
- Potential vulnerabilities
- Should not be in production

### Score 1-2: Critical
- Security vulnerabilities present
- No input validation
- Broken auth
- Active exploit potential

### Score 0: Broken
- Actively exploitable

---

## Scalability (Weight: 0.15)

### Score 9-10: Excellent
- Horizontally scalable
- Stateless design
- Proper queuing/caching
- Handles 10x growth easily
- Load tested

### Score 7-8: Good
- Mostly scalable
- Minimal state
- Some bottlenecks identified
- Handles 5x growth
- Scaling path clear

### Score 5-6: Adequate
- Scales with limitations
- Some state management
- Known bottlenecks
- Handles 2x growth
- Scaling requires work

### Score 3-4: Poor
- Limited scalability
- Stateful design
- Multiple bottlenecks
- Near capacity
- Scaling is a project

### Score 1-2: Critical
- Does not scale
- Single point of failure
- Already at capacity

### Score 0: Broken
- Cannot handle current load

---

## Testability (Weight: 0.15)

### Score 9-10: Excellent
- >90% coverage
- Meaningful assertions
- Edge cases tested
- Fast, deterministic tests
- Easy to add new tests

### Score 7-8: Good
- >80% coverage
- Good assertions
- Main paths tested
- Mostly fast tests
- Reasonable to add tests

### Score 5-6: Adequate
- >70% coverage
- Basic assertions
- Happy path tested
- Some slow tests
- Tests can be added

### Score 3-4: Poor
- >50% coverage
- Weak assertions
- Coverage gaps
- Flaky tests
- Hard to test

### Score 1-2: Critical
- &lt;50% coverage
- Minimal assertions
- Critical paths untested
- Many flaky tests

### Score 0: Broken
- No tests or tests don't run



---

## Checklists (1)

### Assessment Checklist

# Assessment Checklist

Pre-completion validation for comprehensive assessments.

## Quality Rating
- [ ] All 6 dimensions rated (Correctness, Maintainability, Performance, Security, Scalability, Testability)
- [ ] Each dimension has specific evidence cited
- [ ] Composite score calculated with correct weights
- [ ] Grade assigned matches score range

## Pros/Cons Analysis
- [ ] At least 3 pros identified
- [ ] At least 3 cons identified
- [ ] Pros and cons are balanced (not all positive or negative)
- [ ] Each item has impact/severity rating
- [ ] Evidence provided for each claim

## Alternative Comparison
- [ ] At least 2 alternatives considered
- [ ] Each alternative scored on same dimensions
- [ ] Migration effort estimated (1-5 scale)
- [ ] Clear recommendation with rationale
- [ ] Trade-offs documented

## Improvement Suggestions
- [ ] Suggestions prioritized by Impact/Effort
- [ ] Quick wins identified (high impact, low effort)
- [ ] Effort estimates provided for each
- [ ] Expected score improvement stated
- [ ] Dependencies between improvements noted

## Verdict
- [ ] Clear YES/NO/MOSTLY/SOMEWHAT answer
- [ ] Reasoning explains the verdict
- [ ] Actionable next steps provided
- [ ] Strongest and weakest dimensions highlighted

## Report Quality
- [ ] Executive summary is 2-3 sentences
- [ ] All sections completed
- [ ] No contradictions between sections
- [ ] Evidence is specific (file:line when applicable)
