---
model: sonnet
---

# /tas-dev $ARGUMENTS

Role: SE - Software Engineer
Implement a Feature per the approved Technical Plan (`Feature-{NNN}-Technical.md`).

`$ARGUMENTS` may include `--autonomous=true|false` (overrides `autonomy_mode` in `tas.yaml`).

## Always / Ask / Never

| | Action |
|---|---|
| **Always** | Check Feature `plan_status` before implementing |
| **Always** | Follow Tasks list in `Feature-{NNN}-Technical.md` |
| **Always** | Tick `- [x]` each task in Technical `## Tasks` immediately after task done — before next task |
| **Always** | Launch independent review agent after implement — no review in same session |
| **Ask** | When discover the plan needs significant changes during coding (manual mode) |
| **Ask** | When need to read files outside the plan's scope (manual mode) |
| **Never** | Implement outside Feature scope |
| **Never** | Skip review step after implement |
| **Never** | Auto-mark Done when post-impl review returns Critical/High — even in autonomous mode |

## Autonomous Mode

Resolve `autonomous` flag at start (CLI flag wins over yaml):
1. Parse `--autonomous=true|false` from `$ARGUMENTS`
2. If absent → read `autonomy_mode` from `tas.yaml` (`manual` | `full`, default `manual`)
3. Final value: `autonomous = true` iff CLI `true` OR (CLI absent AND `autonomy_mode: full`)

When `autonomous = true`:
- Step 1.5: if `plan_status: pending` → invoke `/tas-plan {Feature-ID} --autonomous=true` inline, wait completion, then continue. Do NOT stop on `require_plan: true`.
- Step 3: skip "ask user before changing direction". Auto-decide deviation, log to Feature `## Autonomous Decisions Log` with rationale.
- Step 4 (review): unchanged — review still runs in isolated agent.
- Step 6: if review returns NO Critical/High AND tests pass → auto-Done. If Critical/High → revert status to `In Development`, do NOT mark Done, surface findings to user.

Mandatory audit trail in autonomous mode:
- Set Feature frontmatter: `autonomous_run: true`, `autonomous_run_date: {datetime}`
- Append every skipped gate + chosen path to Feature `## Autonomous Decisions Log`
- Tag commit message: `feat(autonomous): ...`

## IMPORTANT — File Reading Rules
- Read Feature file (business context) + Feature-Technical file (implementation context) — that's enough.
- **Never read full PRD/SAD/ADR/Design-Spec.** If you need a specific upstream detail, use the **Context Refs** table in the Technical file: grep that exact heading in the named doc and Read only that section by line range. No Context Refs row for it → don't read it (ask user if truly blocked).
- Don't list directories, don't scan project structure.
- Don't read `.tas/rules/common/feature-done.md` at first step (only at final step).

## Stack Detection
Read `.tas/rules/common/stack-detection.md`. Cross-check with Feature frontmatter `stack:` field.

## Actions

### Step 1 — Identify Feature

`$ARGUMENTS` is Feature ID or file path.
If none: read `project-status.yaml`, find features with `status: In Design` or `status: In Development`. If more than one, list for user to choose.

Read both files:
- `docs/features/{CODE}-Feature-{NNN}-{slug}/{CODE}-Feature-{NNN}-{slug}.md`
- `docs/features/{CODE}-Feature-{NNN}-{slug}/{CODE}-Feature-{NNN}-{slug}-Technical.md`

### Step 1.5 — Gate: Check plan_status

**Approval gate:** If `workflow.gate_enforcement: true` in `tas.yaml` (default true): require the Technical file frontmatter `artifact-status: approved` (in addition to the `plan_status` flow below). `draft` or missing → **STOP**: "🚫 Gate: /tas-dev needs the Technical plan approved (artifact-status = {value}). Set it to `approved`, or set `workflow.gate_enforcement: false`." If `false` → skip. In autonomous mode a failing gate still stops the run and surfaces the reason.

**Definition of Ready (DoR):** before coding, confirm the Feature is ready — Feature Spec approved, Design Reference complete (or `N/A`), and every `depends_on_features` entry is Done. Read those from the Feature frontmatter; if a dependency is not Done, warn (autonomous: log and continue only if `gate_enforcement: false`, else stop). For a full audit, run the `coverage-auditor` agent (Coding/DoR gate).

Read `plan_status` from Feature frontmatter.

**If `plan_status: pending`:**
- **If `autonomous = true`:** Execute `/tas-plan {Feature-ID} --autonomous=true` inline — run all tas-plan steps in sequence, **no text output, no stop, no user prompt**. When tas-plan file writes finish (`plan_status: completed`), immediately re-read Feature + Technical files and continue Step 2 without pausing.
- **Else** read `require_plan` from root/`tas.yaml`:
  - `require_plan: true` (or field absent) → **STOP**:
    > "Feature has no Technical Plan. Run `/tas-plan {Feature-ID}` before implementing."
  - `require_plan: false` → continue, show warning:
    > "⚠️ Quick mode: Feature has no Technical Plan. Continue?"

**If `plan_status: completed`:** continue normally. If Technical file missing → STOP, advise re-run `/tas-plan`.

### Step 2 — Read Technical Plan

From `Feature-{NNN}-Technical.md`, absorb:
- Context Refs (the only sanctioned pointers into PRD/SAD/Design-Spec — read those sections on demand, never the full doc)
- Context Diagram + Logic Flow + Data Flow
- ERD + File Changes (Modify / Create / Delete)
- Config (env vars, flags, dependencies)
- Unit Test Cases (Happy / Edge / Negative tables)
- Tasks list (checklist to follow in order)

If quick mode (no Technical file) → analyze Feature AC and implement directly.

### Step 3 — Implement

**Start the AI-time timer:** record the current system clock now (e.g. `Get-Date`). `metrics.ai_time` accumulates the hours from here until this `/tas-dev` invocation ends (Done or stop) — per `.tas/rules/common/metrics.md`.

**If stack is Node.js/Express/Next.js** → Read `.tas/rules/typescript/patterns.md` and `.tas/rules/typescript/security.md` for repository pattern, N+1 prevention, error handler, caching, JWT/RBAC before coding.

**If stack is .NET / C# AND target dir has no `*.sln`** → Read `.tas/rules/csharp/torus-core-framework.md`. Run the pinned `torus-bootstrap create ...` command from the Technical Plan FIRST (before any application code), then continue with regular Tasks.

**If building UI (web/app stack with a frontend)** → First read the Technical file's `## UI Binding`. For each `SCR-NNN`:
- **Reuse `pixel-perfect`** → copy the referenced Generated Screen file (`docs/ui/*.html`) as the starting point; wire data / state / behaviour only; **do NOT redraw** the layout.
- **Build** → construct from the Design-Spec **token system + Component specs** listed in `## Context Refs`.
In both cases: implement each `{token.ref}` (colors, typography, layout/spacing, elevation, shapes) ONCE as a CSS variable / theme constant and reference it everywhere — **never inline a raw hex / px / font literal**. Build each component to its `{component.*}` spec (token composition + default/active states). **Don't introduce any color, size, font, or radius outside the token set.** If a needed token or component spec is missing (check the Design-Spec **Known Gaps**), STOP and flag it (ask PE to add it via `/tas-design-spec`) instead of improvising.

**Locator injection (UI stacks) — Read `.tas/rules/common/locator-naming.md` + the stack's `### Locator Map` from the Technical file.** As you build each interactive element, attach its testid to the rendered element: web → `data-testid="{testid}"`, mobile (RN) → `testID="{testid}"`. The Locator Map is the SSoT consumed downstream by `/tas-functest*`, so handle gaps instead of skipping:

| Situation | Action |
|---|---|
| **Missing** — element is real but absent from the Map | Generate a testid per the convention → attach to source → **back-fill one row into the Technical file's `### Locator Map`** with `Origin: dev`. Never leave an interactive element without a testid. |
| **Wrong convention** — Map has e.g. `input_email` instead of `ipt_auth_email` | Use the convention-correct testid in source, update that Map cell, note the correction. |
| **Ambiguous / conflicting** — business meaning or domain unclear, or two rows collide | **Manual mode:** STOP and ask. **Autonomous mode:** pick the convention-correct testid and log to Feature `## Autonomous Decisions Log`. |

This Map back-fill mirrors the architecture-map write-back pattern (Step 6). **Mobile only:** if `apps/mobile/e2e/test-ids.ts` exists, sync this Feature's testids into it (mobile tests import from there) — it is a *derived* registry, not a second SSoT; the Locator Map stays authoritative.

#### If `use_tdd = true` in `tas.yaml`:

Read `.tas/rules/common/tdd.md` for Red-Green-Refactor + Test Naming Convention.

Platform-specific test stacks (from stack detection + Feature `stack:` field):
- **Mobile (React Native)**: Jest + React Testing Library — Components (`render`, `fireEvent`, `screen`), Hooks (`renderHook`), Services/API (Jest mocks + MSW), Utils, Zustand stores. File: `src/**/*.test.ts(x)`
- **Web (React + Node)**: Vitest/Jest + React Testing Library — Components, Hooks, Services (MSW/Nock), Backend services. File: `src/**/*.test.ts(x)`
- **Backend (.NET)**: xUnit — Unit (services, repositories), Integration (TestServer), API (WebApplicationFactory). File: `tests/Unit/`, `tests/Integration/`, `tests/Api/`

#### If `use_tdd = false`:
a. Implement code per AC + Tasks in Technical Plan
b. Write unit tests covering rows in `## Unit Test Cases`
c. Run tests, fix if fail
→ If tests still fail after 1 self-fix: launch `build-resolver` agent with error output.

**Task checklist sync (mandatory):**
- After finishing each task in `## Tasks`, immediately `Edit` the Technical file to flip `- [ ]` → `- [x]` for that exact line. Do not batch — tick per task.
- If task partial (e.g. file created but not wired) leave `- [ ]` and add `- [ ] {task} — partial: {what's left}` note.
- Before Step 4 review, re-read Technical file and confirm every completed task is `- [x]`. Any `- [ ]` left must match an actual gap.

If discover plan needs significant changes:
- **Manual mode:** notify user before changing direction.
- **Autonomous mode:** auto-decide (prefer simplest path that satisfies AC), log entry to Feature `## Autonomous Decisions Log`:
  > `- {timestamp} | Step 3 deviation | original: {plan path} | chosen: {new path} | reason: {why}`

### Step 3.5 — Build & Verify Loop

Read `.tas/rules/common/build-debug-loop.md`.

Run **after each stack is fully implemented** (not after every task — after the stack's task group is complete).

```
max_attempts = tas.yaml[build_debug_attempts] ?? 3
attempt = 0

while attempt < max_attempts:
  1. Start dev server for current stack (command + ready signal from rule table)
     Run as background process, timeout 60s waiting for ready signal
  2. Capture stdout + stderr for 30s after ready (or until crash)
  3. Evaluate:
     a. Crash / no ready signal → extract errors → call build-resolver agent
        Apply fix → kill process → attempt++ → retry
     b. Ready but error pattern in log → same as (a)
     c. Ready, no errors → if frontend stack: run Browser Check (per rule)
        Browser check pass → log PASS → exit loop
        Browser check fail → call build-resolver with browser error context
        Apply fix → kill process → attempt++ → retry
     d. Ready, no errors, not frontend → log PASS → exit loop

if attempt >= max_attempts:
  Output warning block (format in rule) → STOP
  Do NOT proceed to Step 4 until user resolves
```

**build-resolver call context**: stack, command, attempt N/max, exit code, last 50 lines stdout+stderr, browser errors (if any), AC text being verified (if functional check), changed files list.

**After loop**: append to Feature Technical file `## Build Debug Log` (create section if absent).

**Skip condition**: if `tas.yaml[skip_build_verify: true]` → skip Step 3.5, log skip reason.

### Step 4 — Post-Implementation Review (Isolated Agent)

**Pre-review gate:** Re-read Technical file. All implemented tasks must be `- [x]`. If any done task still `- [ ]` → tick now, then proceed.

Follow `.tas/rules/common/post-implementation-review.md`.
Pass in: Feature file path, Technical file path, changed files list, stack (from Feature.stack + CLAUDE.md), lang_agent.

### Step 5 — Definition of Done

Read `.tas/rules/common/feature-done.md`, verify each item, tick in Feature's `## Definition of Done`:
- `- [x] Technical plan completed` — if plan_status: completed (or quick mode confirmed)
- `- [x] Code implemented per all AC`
- `- [x] Unit tests pass (happy + edge + negative)`
- `- [x] No regression on existing tests`
- `- [x] Documentation updated (if API/schema changed)`
- `- [x] Code review passed` — if review gate passed (no Critical/High)
- `- [ ] Functional tests pass (per /tas-functest)` — DO NOT tick if FT not run yet
- `- [ ] Acceptance criteria verified by PE` — DO NOT tick, let PE verify
- `- [ ] Ready for production release` — DO NOT tick, gated by PE

**SAD update (mandatory if matrix says so):**
Read Technical-file frontmatter `sad_impact`.
- If `sad_impact: true` → auto-invoke `/tas-sad "Feature-{NNN}: {one-line summary aggregated from SAD Impact Matrix Yes rows}" --autonomous={autonomous}` inline. `/tas-sad` UPDATE mode writes Changelog entry to `docs/sad.md`. Verify Changelog entry contains `Feature-{NNN}` ref before continuing.
- If `sad_impact: false` → skip.

**Optional — broader docs sync (API contracts, README, etc.):**
Launch `doc-updater` agent if Feature changes public API, schema, or setup beyond what `/tas-sad` covers.
> Scope: [changed files list]. Feature: [Feature ID + title].
> Only update outdated docs — don't rewrite from scratch.

### Step 6 — Wrap up

Update Feature status → `In Development` (if not already).
Create commit message per conventions in `CLAUDE.md`. Prefix with `feat(autonomous):` if autonomous run.
**The commit / PR must name the Feature ID** (e.g. `feat: Feature-005 Order Checkout (FR-005)`) — this is the trace link across the Git boundary: PR → Feature Spec → FR → BR, and BRU via the ACs. A PR with no Feature ID breaks reverse-trace from code back to requirement.

**How to verify (generated — output only, not saved):**
Before the manual question (autonomous: inside the surfaced summary), print a short setup+test block so a human can try it now. A regenerable smoke-check, not a test artifact (`/tas-functest` is the persisted layer). **Summarize — not per-AC.** Reuse the run command + dev URL from Step 3.5 (already stack-correct — don't assume npm); prepend any migration / env from `## Config`.

> **How to verify** _(generated, not saved)_
> **Setup:** {migration + env from `## Config`, if any} → {run cmd from Step 3.5}
> **Open:** {dev URL}  *(backend-only → key endpoint(s) to `curl`)*
> **Check:** {one line per Feature goal — what should work}

**Manual mode:**
Ask: "Ran the verify steps above — all Feature goals work? Move to `Done` and release?"

If Yes:
- Update Feature frontmatter `status: Done`, set `done_date`
- Add Changelog entry
- Accumulate `metrics.ai_time` (per `.tas/rules/common/metrics.md`): add the hours elapsed since the Step 3 timer (decimal, 0.1) to Feature frontmatter `metrics.ai_time` + mirror to `project-status.yaml` `features.{FEATURE_ID}.metrics`. Automatic — do not ask the human.
- Update `project-status.yaml`: `features.{FEATURE_ID}.status: Done`
- Suggest: `/ado-update feature {ado-id} --status "Done"` if using ADO

**SAD Done Gate (manual + autonomous):** If Technical-file frontmatter `sad_impact: true` → grep `docs/sad.md` Changelog for `Feature-{NNN}` ref. No match → BLOCK Done, surface: "SAD impact flagged but `docs/sad.md` Changelog missing Feature-{NNN} ref. Re-run `/tas-sad` before marking Done."

**Architecture-map write-back (on Done, manual + autonomous):** If `docs/architecture-map.yaml` exists, update it per `.tas/rules/common/architecture-map.md` for every design item this Feature claimed in its `## Modules` block:
- **Components** (`MOD-NN.C#` in `Builds`): `status: built`, `code_anchor: [actual paths/namespaces created]` (list), `tests: [AC test IDs]`, `last_built: {date}`, ensure this Feature is in the component's `built_by`.
- **Module roll-up:** set actual `provides`; roll `status` up (a module is `built` only when all its components are); ensure the module's `built_by` reflects the union of its components'.
- **Entities** (`E-NNN` in `Entities (owns)`): set the entity's `status: built` + actual `code_anchor`.
- **Contracts** (`IC-NN` in `Contracts (produces)`): set the contract's `status: built`.
- **NFRs** (`NFR-NNN` in `NFRs`): set the NFR's `status: enforced`.
- **Security** (`SEC-NN` in `Security`): set the control's `status: implemented`.
- If reality diverged from SAD §7/§8/§9.2/§10/§11 (different provides/deps, extra component, entity not actually persisted, etc.): set `drift: "{what diverged}"`. This is as-built sync — it does NOT edit the SAD. Only a genuine *design* change escalates via the SAD Impact heuristic above → `/tas-sad` (which keeps the SAD's approval gate intact).

**Autonomous mode:**
Read post-impl review result.
- **No Critical/High AND tests pass** → auto-Done:
  - Update frontmatter `status: Done`, set `done_date`
  - Add Changelog entry tagged `[autonomous]`
  - Accumulate `metrics.ai_time` (per `.tas/rules/common/metrics.md`): add hours elapsed since the Step 3 timer (0.1) to frontmatter + mirror. (`metrics.human_time` stays N/A — no human baseline)
  - Update `project-status.yaml`: `features.{FEATURE_ID}.status: Done`
  - Surface summary to user: Feature ID, autonomous decisions count, files changed, review verdict, and the **How to verify** block above (so the user can spot-check).
- **Any Critical/High finding OR tests fail** → revert/hold:
  - Status stays `In Development`
  - Append to `## Autonomous Decisions Log`: `- {timestamp} | auto-Done blocked | reason: {Critical/High count or test failures}`
  - Surface findings to user, await manual fix.
- **ADR creation:** never auto-run `/tas-adr` — log candidates only (per current rule).

## Principles
- DO NOT implement outside Feature scope
- Each public method MUST have XML doc (C#) / JSDoc (TS) / docstring (Python)
- Review must run through independent Agent — not inline in current session
- **When to create ADR** (if Technical Plan didn't mention):
  - Architecture changes affecting multiple components
  - New design pattern or framework
  - Important technical trade-off decisions

## Final Step — Token Log

Follow `.tas/rules/common/token-logging.md`: write AI Usage Log to working Feature file.
