# KnowzCode - Development Methodology & Operational Protocol

**Target Audience:** Any AI coding assistant (Claude Code, Codex, Gemini, Cursor, Copilot, etc.)
**Purpose:** This is your primary operational guide for structured, test-driven development using KnowzCode. Follow these phases precisely when working on any feature or change.

## 1. Core Principles

* **Change Set-Driven Development**: Work is performed on a "Change Set" — a group of NodeIDs (new capabilities) and affected files. This ensures system-wide consistency.
* **Spec-Driven Development**: `knowzcode/specs/[NodeID].md` files define what to build. They are drafted, approved, implemented against, then finalized to "as-built" state.
* **Mandatory TDD**: Every feature must follow Red-Green-Refactor. No production code without a failing test first.
* **Quality Gates**: You MUST pause at defined checkpoints for user approval. Never skip phases.
* **Integrated Version Control**: Strategic commits mark phase transitions.
* **Proactive Debt Management**: Technical debt is formally tracked, not ignored.

## 2. Core Files Reference

* **`knowzcode/knowzcode_project.md`**: Read-only project context.
* **`knowzcode/knowzcode_architecture.md`**: Architecture docs. Update for simple consistency changes.
* **`knowzcode/knowzcode_tracker.md`**: Track NodeID statuses and WorkGroup assignments.
* **`knowzcode/knowzcode_log.md`**: Prepend log entries. Read reference quality criteria.
* **`knowzcode/specs/[NodeID].md`**: Create, read, and finalize specifications.
* **`knowzcode/workgroups/<WorkGroupID>.md`**: Session todo list. Every entry must begin with `KnowzCode:`.
* **This document (`knowzcode/knowzcode_loop.md`)**: Your primary workflow reference.

## 3. The Main Operational Loop

### 3.1 Phase 1A: Impact Analysis

Receive the goal from the user. Identify the **Change Set** — all components affected by this change.

**NodeID Granularity**: Create NodeIDs only for NEW capabilities being built, not for every file touched. Files that integrate a new capability are "affected files" — they don't need separate NodeIDs or specs.

**Change Set Format:**
```markdown
## Change Set for WorkGroup [ID]

### New Capabilities (NodeIDs)
| NodeID | Description |
|--------|-------------|
| LIB_DateTimeFormat | Timezone formatting utility |

### Affected Files (no NodeIDs needed)
- JobsPage.tsx - integrate formatDateTime
- IntakeJobsPage.tsx - integrate formatDateTime

**Specs Required**: 1
```

**NodeID Naming Convention:**
NodeIDs must be **domain concepts**, not tasks.

1. **Domain-Area NodeIDs** (default): PascalCase covering cohesive areas
   - Examples: `Authentication`, `FileManagement`, `Checkout`, `UserProfile`
   - Covers multiple components: `Authentication` = login form + auth endpoint + token service
   - Sub-areas when a domain grows large: `Authentication_OAuth`, `Payments_Stripe`

2. **Utility NodeIDs** (exception): For genuinely isolated utilities
   - `LIB_` prefix: `LIB_DateFormat`, `LIB_Validation`
   - `CONFIG_` prefix: `CONFIG_FeatureFlags`

3. **Use Case NodeIDs** (optional): `UC_` for cross-domain workflows
   - Only when genuinely spanning multiple unrelated domains

**Never use task-oriented names**: `FIX-001`, `TASK-X`, `FEATURE-Y`. Tasks belong in WorkGroup files.

**Consolidation Rule:** Before creating a new NodeID, check existing specs. If >50% domain overlap exists with an existing spec, UPDATE that spec instead. Target <20 specs per project.

**Historical Context:** Before proposing the Change Set, scan `knowzcode/workgroups/` for completed WorkGroups that touched similar components. Reference relevant context in your proposal.

#### Quality Gate: Change Set Approval
Present the proposed Change Set to the user. **PAUSE and await user approval.** Do NOT proceed to Phase 1B until the user explicitly approves. In autonomous mode, auto-approve and proceed immediately (see Section 5).

Upon approval, generate a unique WorkGroupID and update `knowzcode_tracker.md` for all nodes to `[WIP]`.

**WorkGroupID Format**: `kc-{type}-{slug}-YYYYMMDD-HHMMSS`
- Valid types: `feat`, `fix`, `refactor`, `issue`
- Slug: 2-4 word kebab-case descriptor from the goal
- Example: `kc-feat-user-auth-jwt-20250115-143022`

---

### 3.2 Phase 1B: Specification

Draft or refine `knowzcode/specs/[NodeID].md` for all nodes in the Change Set.

**Spec Template (4-section format):**
```markdown
# [NodeID]: [Human-Readable Name]

**Updated:** [timestamp]
**Status:** Draft | Approved | As-Built
**KnowledgeId:** [optional — set automatically when synced to vault]

## Rules & Decisions
Key architectural decisions, business rules, constraints, and purpose.
- Decision: chose X over Y because Z
- Rule: must always validate before persisting

## Interfaces
Public contracts: inputs, outputs, API signatures, dependencies, events.
- POST /api/users -> { id, email }
- Depends on: AuthService for token validation

## Verification Criteria
Testable assertions for implementation and auditing.
- VERIFY: when valid credentials, returns JWT token
- VERIFY: when email exists, returns 409

## Debt & Gaps
Known limitations and future work.
- TODO: add rate limiting
```

**Minimum valid spec:** 1+ Rules item, 1+ Interface item, 2+ `VERIFY:` statements.

> **KnowledgeId** is optional and managed automatically by vault sync. Do not set manually. When present, vault captures update the existing cloud item instead of creating duplicates. If the cloud item is deleted, the field is automatically removed.

**Backward compatibility:** Old numbered-section specs remain valid until naturally touched. When finalizing, rewrite in the new format.

#### Quality Gate: Spec Approval
Present drafted specs to the user. **PAUSE and await user approval.** Log "SpecApproved" events. In autonomous mode, auto-approve and proceed immediately (see Section 5).

**Pre-Implementation Commit:** After specs are approved, inspect status and scoped diffs, then stage only the active WorkGroup file, tracker row changes, and explicit approved spec paths. Verify `git diff --cached --check` and the exact staged name list before committing. Abort if any unrelated path is staged; never stage the `knowzcode/` directory wholesale.

---

### 3.3 Phase 2A: Implementation (TDD MANDATORY)

For each NodeID in the approved Change Set:

```
FOR each feature/criterion in the spec:

    # RED Phase
    1. Write a failing test that defines expected behavior
    2. Run test → Confirm it FAILS
       - If test passes without code, the test is wrong — fix it

    # GREEN Phase
    3. Write MINIMAL code to make the test pass
    4. Run test → Confirm it PASSES
       - If fails, fix code (not test)

    # REFACTOR Phase
    5. Review code for improvements
    6. If refactoring: make change, rerun the targeted checks; expand to the
       affected package/surface when the refactor crosses the original unit
```

**Scoped Verification Loop (must pass before claiming the microtask complete):**
```
WHILE verification not complete:
    1. Run the narrow deterministic test(s) for the failing/changed criterion
       → If FAIL: store raw output as an artifact, pass a bounded failure
         delta to the fix loop, fix, and restart
    2. Run affected-package/surface tests and targeted static checks
       → If issues: fix and restart
    3. Verify assigned acceptance criteria for the current NodeID or microtask
       → If unmet: implement and restart
    4. Scoped checks pass → report the microtask complete
```

**Consolidated Gate 3 verification (mandatory):** after all implementation
waves, run the repository's full test suite, static analysis, build, packaging,
and install smoke checks that exist. Repeat this consolidated gate after any
production or integration change made during an audit/fix round. Never skip the
independent audit or consolidated gate to meet an efficiency budget.

For microtask implementation, "complete" means the assigned acceptance criteria are met, not every criterion in the parent NodeID. The lead is responsible for tracking criteria coverage across microtasks and must not mark the parent NodeID complete until all required `VERIFY:` criteria and cross-microtask integration criteria are covered.

**Maximum iterations**: 10. If exceeded, pause and report blocker.

#### Quality Gate: Implementation Complete
Report implementation results including test counts, verification iterations, and criteria status. **PAUSE — the user or an auditor will verify completeness.**

---

### 3.4 Phase 2B: Completeness Audit + Smoke Testing

An independent, READ-ONLY audit verifying what percentage of specifications were actually implemented, plus optional runtime smoke testing.

**Process:**
- Compare implementation against specifications for all assigned NodeIDs or microtask acceptance criteria
- Calculate objective completion percentage
- Report gaps, orphan code, and risk assessment
- **Smoke testing** (Tier 3: recommended, Tier 2: opt-in): boot the application and verify runtime behavior against specs
- Do NOT modify any code during this phase

**Outcomes** (user decides):
- Return to Phase 2A to complete missing requirements
- Accept current implementation and proceed to finalization
- Modify specs to match implementation
- Cancel the WorkGroup

#### Quality Gate: Audit Approval
Present audit results to the user. **PAUSE for decision.** Only proceed to Phase 3 when the user approves. In autonomous mode, auto-approve and proceed immediately unless safety exceptions apply (see Section 5).

---

### 3.5 Phase 3: Atomic Finalization

Once implementation is verified and approved, execute finalization:

**Step 7: Finalize Specifications**
Update each `knowzcode/specs/[NodeID].md` to match the verified "as-built" implementation. Always use the 4-section format.

**Step 8: Architecture Check**
Review `knowzcode/knowzcode_architecture.md` against the Change Set.
- Simple discrepancies: fix directly and note in log
- Complex discrepancies: document for user review

**Step 9: Log Entry**
Prepend a comprehensive `ARC-Completion` entry to `knowzcode/knowzcode_log.md`:
```markdown
---
**Type:** ARC-Completion
**Timestamp:** [timestamp]
**WorkGroupID:** [ID]
**NodeID(s):** [list all]
**Logged By:** AI-Agent
**Details:**
Successfully implemented and verified the Change Set for [goal].
- **Verification Summary:** [key checks]
- **Architectural Learnings:** [discoveries]
- **Unforeseen Ripple Effects:** [affected nodes outside this WorkGroup, or None]
- **Specification Finalization:** All specs updated to "as-built" state.
- **Architecture Check Outcome:** [outcome]
---
```

**Step 10: Update Tracker & Schedule Debt**
- Change each NodeID status from `[WIP]` to `[VERIFIED]`, clear WorkGroupID
- If significant tech debt documented, create `REFACTOR_[NodeID]` tasks
- Check if changes impact `knowzcode_project.md` (new features, stack changes)

**Step 11: Final Commit**
Inspect `git status --short` and scoped diffs. Resolve an explicit reviewed list containing only active WorkGroup artifacts and approved implementation paths, stage it with `git add -- {explicit-paths}`, then verify `git diff --cached --check` and the exact `git diff --cached --name-only` list before committing. Abort on unrelated or ambiguous paths; never use broad directory staging, `git add -A`, or `git add .`.

**Step 12: Report & Close**
Report completion, mention any `REFACTOR_` tasks created. WorkGroup is closed.

---

## 4. Micro-Fix Protocol

For single-file, no-ripple-effect changes (results in a single `fix:` commit):

1. Implement the small change
2. Quick focused verification
3. Log a `MicroFix` entry:
```markdown
---
**Type:** MicroFix
**Timestamp:** [timestamp]
**NodeID(s)/File:** [target]
**Logged By:** AI-Agent
**Details:**
- **User Request:** [description]
- **Action Taken:** [change made]
- **Verification:** [method/outcome]
---
```
4. Commit with `fix: [description]`

---

## 5. When to Pause (Quality Gates)

You **MUST** pause and await explicit user approval at:
* After proposing a Change Set (Phase 1A)
* After presenting specs for approval (Phase 1B)
* After reporting implementation complete (Phase 2A) — awaiting audit
* After audit results — awaiting decision on gaps (Phase 2B)
* If you encounter a critical, unresolvable issue
* If an architecture discrepancy is too complex to fix autonomously

### Autonomous Mode Override

When the user conveys intent for autonomous operation — through natural language (e.g., "approve all", "preapprove", "autonomous mode", "just run through", "I trust your judgement") or the `--autonomous` flag — quality gates above are still **presented** for transparency but **auto-approved** without waiting for user input. The workflow runs from start to finalization uninterrupted.

The lead should interpret the **spirit** of the user's instruction, not just exact keyword matches. If the user clearly wants the workflow to proceed without stopping, that constitutes autonomous mode activation.

**Safety exceptions** — ALWAYS pause even in autonomous mode:
* Critical, unresolvable blockers (Section 11)
* Security vulnerabilities rated HIGH or CRITICAL
* >3 failures on the same phase
* Architecture discrepancies too complex to fix autonomously
* >3 gap-fix iterations per builder scope without resolution

Autonomous mode is per-WorkGroup and does not carry over.

---

## 6. MCP Integration (Optional but Recommended)

If MCP is configured, agents can leverage vault queries to enhance every phase. Vault configuration lives in `knowz-vaults.md` at the project root — created via `/knowz setup`.

**Cross-platform config**: Set `KNOWZ_API_KEY` as an environment variable to enable automatic MCP authentication on any platform.

**Before using MCP, read `knowz-vaults.md` (project root) to discover vault IDs, descriptions, and routing rules.** Use each vault's description and "When to query"/"When to save" rules to confirm the query is appropriate for that vault. If a single vault is configured, use it for everything. If no vault file exists, fall back to `list_vaults()`. Never hardcode vault names — always resolve from config.

### Vault Routing

Vault routing is driven by `knowz-vaults.md` — each vault entry has "When to query" and "When to save" rules that determine which vault handles which content. A project may configure one vault covering everything (common for small teams) or multiple specialized vaults. `knowz:writer` (or direct MCP calls) writes to vaults; `knowz:reader` has read-only access. Gate deltas are classified first; a writer is dispatched only for `amend`, `update`, or `flush` and then routes the mutation by vault descriptions and save rules.

### Phase-Specific Usage

| Phase | MCP Tool | Purpose |
|-------|----------|---------|
| **1A (Analysis)** | `search_knowledge({vault_id}, "past decisions about {domain}")` | Find prior decisions affecting components |
| **1B (Spec)** | `ask_question({vault_id}, "conventions for {component_type}?")` | Check team conventions before drafting |
| **2A (Build)** | `search_knowledge({vault_id}, "{similar_feature} implementation")` | Find reference implementations |
| **2B (Audit)** | `ask_question({vault_id}, "standards for {domain}", researchMode=true)` | Comprehensive standards check |
| **3 (Close)** | Lead classifies `FinalCaptureDelta`; apply one returned writer/direct mutation | Capture patterns, decisions, workarounds |

### Knowz Vault Agents (Multi-Agent Platforms)

On platforms with multi-agent orchestration (e.g., Claude Code Agent Teams), **`knowz:reader`** has read-only access to MCP vaults, and **`knowz:writer`** has full read/write access to MCP vaults. Both have read/write access to local knowzcode files:

- **`knowz:reader`** is dispatched only for a bounded Stage 0 gap — queries vaults for business context, conventions, and past decisions, then returns one bounded result to the lead. The lead routes findings to analyst and architect directly; in Team mode it uses one targeted `SendMessage` per recipient because no broadcast primitive exists.
- **`knowz:writer`** is dispatched only after `vault-delta` returns `amend`, `update`, or `flush`. It receives the explicit mutation plan, content-bound parent identity/key, one distinct deterministic child key per logical mutation, exact `KnowledgeId` values for amend/update, phase, WorkGroup ID, and consolidated content; normal `skip`/`batch` gates create no writer.
- Writers are short-lived and action-triggered; readers are dispatched only for named unresolved questions rather than automatic Stage 0 hydration.

On platforms without multi-agent orchestration, the current lead executes the same classified mutation plan directly (see Section 7); a separately dispatched closer never owns vault mutation authority.

### Enterprise: Team Standards

At workflow start, if an enterprise vault is configured (read `knowz-vaults.md` to find a vault whose description mentions "enterprise", "compliance", or "audit", then check `knowzcode/enterprise/compliance_manifest.md` for `mcp_compliance_enabled: true`):
- When `pull_standards_at_start: true` (default), pull team-wide standards and merge into quality gate criteria
- Fetch explicit guideline KnowledgeIds from `guideline_knowledge_ids` or user/workflow input with `get_knowledge_item(id)`
- Search configured guideline vault sources for active standards, policies, enterprise guidelines, and compliance requirements
- When `preserve_guideline_provenance: true` (default), preserve provenance for vault-sourced rules: vault ID/name, KnowledgeId, title, created/updated date when available, retrieval date, applies-to scope, and enforcement level
- Convert active local/vault/KnowledgeId guidelines into Phase 1A NodeID mappings, Phase 1B spec VERIFY criteria, Phase 2A builder guidance, and Phase 2B audit checks
- When `push_audit_results: true` (default), classify the Phase 2B enterprise audit delta and push only on `amend`, `update`, or `flush`; retain `batch` for final consolidation
- When `push_completion_records: true` (default), push completion records to the resolved enterprise vault after Phase 3

Enterprise guidelines may also live in `knowzcode/enterprise.md` or `knowzcode/enterprise/guidelines/**/*.md`. When the user, manifest, or workflow marks vault/KnowledgeId rules as active, they are enforcement inputs, not optional background context. If guideline sources conflict, surface the conflict at the next gate; blocking-tier conflicts pause autonomous mode until resolved.

### Graceful Degradation

All phases work without MCP. MCP enhances analysis depth and organizational learning but never blocks workflow progression. When MCP is unavailable, agents use standard file search tools (grep, glob) as fallback.

---

## 7. Learning Capture (Optional)

> **Content Detail Principle:** Vault entries live in a vector search index — they are chunked and retrieved via semantic search. Unlike local files (specs, workgroups, logs) which are read directly and benefit from being scannable, vault entries must be **self-contained, detailed, and keyword-rich** because they are discovered by meaning, not by file path.
>
> **Include in every vault entry:**
> - Full reasoning and context — why, not just what
> - Specific technology names, library versions, framework details
> - Code examples, file paths, error messages where relevant
> - Consequences and alternatives considered
> - Freshness/provenance: date observed, created/updated date when known, source, and whether this supersedes older guidance
>
> Write vault content as if the reader has no project context — they will find this entry via a search query months from now.

### Minimum Capture Requirements

Agents MUST classify and retain these categories at quality gates. Normal `batch` entries remain in the WorkGroup journal until final consolidation; the table does not itself authorize a per-gate write:

| Category | When | What |
|----------|------|------|
| Scope | Phase 1A gate | What included/excluded, risk reasoning |
| Spec | Phase 1B gate and Phase 3 | Approved and as-built NodeID specs, VERIFY criteria, constraints |
| Component | Phase 1B and Phase 3 | Purpose, boundaries, dependencies, data flow, config, files |
| System Boundary | Phase 1B and Phase 3 | Ownership, dependency direction, forbidden coupling |
| Diagram | Phase 1B and Phase 3 | Mermaid/data-flow/architecture sketches that document real structure |
| Integration Contract | Phase 1B and Phase 2A | APIs, events, schemas, queues, MCP/tool surfaces |
| Implementation patterns | Phase 2A | Patterns, workarounds, performance from TDD |
| Security & audit findings | Phase 2B gate | Vulnerabilities, audit gaps, remediation |
| Conventions established | Phase 3 | New conventions with rationale and examples |
| Architecture discoveries | Phase 3 | Structural insights, component relationships |
| Lesson Learned | Any phase | Durable insight, pitfall, or proven workaround discovered during execution |
| Correction/Deprecation | Any phase | Older vault guidance that is stale, contradicted, or superseded |
| Completion | Phase 3 | Goal, outcome, NodeIDs, duration, learnings |

### Mid-Work Discovery Signals

Agents should watch for these during any phase and submit candidates to the lead (`"Consider: {description}"`). The lead runs `vault-delta`; `skip` is discarded, `batch` remains in the coordinator journal, and only `amend`, `update`, or `flush` is sent to the knowledge liaison or direct-write path:

| Signal | Examples |
|--------|----------|
| Corrected assumption | "It turns out...", unexpected behavior |
| Undocumented dependency | Hidden coupling, implicit ordering |
| Workaround applied | Limitation-driven alternatives |
| Configuration gotcha | Non-obvious defaults, env-specific settings |
| Performance finding | Before/after measurements |
| API quirk | Undocumented behavior, version differences |
| Stale vault guidance | Retrieved knowledge contradicted by live code/tests/docs |

When detected, capture immediately — do not defer to finalization. Sessions can end unexpectedly.

### Architecture Documentation Depth

When capturing architectural knowledge, include:
1. **Component relationships** — how modules interact, dependency direction, data flow
2. **Design rationale** — why this structure was chosen over alternatives
3. **Boundary definitions** — what belongs in each layer/module, what does not
4. **Integration contracts** — API surfaces, event schemas, shared data structures
5. **Error propagation** — how failures cascade, circuit breaker locations
6. **Configuration surface** — what is configurable, default values, environment differences

Each architectural entry should include file paths, code references, and enough context to be understood without access to the codebase.

### Signal Types

During finalization, scan the WorkGroup for insight-worthy patterns:

| Signal Type | Examples |
|-------------|----------|
| Pattern | "created utility for", "reusable", "abstracted" |
| Decision | "chose X over Y", "opted for", "trade-off" |
| Workaround | "workaround", "limitation", "can't do X so" |
| Performance | "optimized", "reduced from X to Y", "cache" |
| Security | "vulnerability", "sanitize", "authentication fix" |
| Convention | "established convention", "team standard", "naming pattern", "agreed to always" |
| Integration | "API integration", "upstream API changed", "service dependency", "webhook" |
| Scope | "included because", "excluded because", "out of scope", "deferred to" |
| Spec | "approved spec", "VERIFY criteria", "as-built", "interface contract" |
| Component | "new component", "boundary", "responsibility", "data flow" |
| Diagram | "Mermaid", "architecture diagram", "flowchart", "sequence" |
| Correction/Deprecation | "stale", "superseded", "no longer applies", "replaced by" |

### Auto-Capture Triggers

Learning candidates are detected at each quality gate. **The lead/outer orchestrator is responsible for classifying each delta** with `node knowzcode/context_efficiency_runtime.mjs vault-delta`. A normal `batch` result stays in the coordinator-owned WorkGroup journal; it does not dispatch a writer or create a pending-capture entry at that gate. The lead routes `amend`, `update`, and `flush` results through the knowledge liaison on multi-agent platforms or the direct-write fallback on single-agent/sequential platforms. `skip` produces no write.

Maintain an append-only local knowledge delta for the WorkGroup. Before a
writer dispatch, resolve the complete ordered mutation plan, compare it with
already queued/saved content, and reject empty, conflicting, or ambiguous
identities. Give every logical mutation a distinct deterministic child key from
the content-bound parent classification key. Use one bounded writer dispatch for
each classified operation or consolidated batch; writers are non-persistent, so
do not advertise cross-gate writer resume. Flush immediately for explicit user saves,
corrections/deprecations, HIGH/CRITICAL security or compliance findings, and
interruption-sensitive decisions. Tier 2 has exactly one completion capture
path; liaison and direct-capture paths must not both write the same outcome.

**Multi-agent platforms (knowledge-liaison prepares requests):**

For a classified `amend`, `update`, or `flush`, the lead sends the knowledge-liaison the action, complete mutation plan, stable parent identity/key, exact `KnowledgeId` values, phase, WorkGroup ID, and any coordinated-team task ID. The liaison prepares exactly one self-contained `WriterRequest` with one distinct deterministic child key per logical mutation; missing amend/update identity returns `MISSING_AMEND_IDENTITY` or `MISSING_UPDATE_IDENTITY` and never becomes create. The lead dispatches `knowz:writer` and owns its task state. At Phase 3, the closer returns the consolidated journal delta to the lead; the lead classifies with `explicit_save: true`, obtains one request, and dispatches one writer. Normal per-gate `batch` results do not create liaison/writer tasks.

The knowledge-liaison owns bounded request preparation and vault-routing advice. The lead alone dispatches `knowz:reader`/`knowz:writer`; the writer owns any post-dispatch failure queue entry. No other agent calls `create_knowledge` directly.

**Ad-hoc captures (any agent, any time):**

Any agent can send the lead a capture candidate:
- `"Log: {description}"` — the lead classifies with `explicit_save: true` and routes the resulting flush
- `"Consider: {description}"` — the lead runs `vault-delta`; `skip`/`batch` create no writer and persistence actions route to the liaison/direct path

The knowledge-liaison handles only lead-classified request preparation. If MCP is unavailable before writer dispatch, the lead queues only a required consolidated flush to project-root `knowz-pending.md` for later sync. The writer alone queues failures after an MCP mutation was dispatched. Every block uses the canonical idempotent queue schema; `/knowz flush` migrates the legacy `knowzcode/pending_captures.md` queue before replay.

**Single-agent / no writer (direct MCP writes):**

If MCP is available but no `knowz:writer`, resolve vault IDs from `knowz-vaults.md` (project root) before writing. Apply the following phase payload templates only when `vault-delta` returned `amend`, `update`, or `flush`; retain `batch` payloads for final consolidation:

- After Phase 1A: return a Scope/Decision candidate containing the problem, constraints, included/excluded scope, risk reasoning, affected files, and mitigation; the lead classifies and routes it
- After Phase 1B: Capture approved specs, component/system boundaries, integration contracts, diagrams, and spec decisions — include NodeIDs, spec paths, VERIFY criteria, source files, and enterprise guideline provenance when applicable
- After Phase 2A: Capture implementation patterns and workarounds discovered during TDD cycles — include specific file paths, code examples, and the problem each pattern solves
- After Phase 2B: return an Audit candidate containing the audited scope, score, findings with file/line evidence, security severity, and gap-resolution rationale; the lead classifies and routes it
- After Phase 2B (enterprise): If `mcp_compliance_enabled: true`, an enterprise vault is configured, and `push_audit_results: true` (default), classify the audit delta and persist only `amend`, `update`, or `flush`; retain `batch` for final consolidation
- After Phase 3: Capture architectural learnings and consolidation decisions (handled by closer agent)

### Capture Protocol

**When knowz:writer is available (multi-agent platforms), after `vault-delta` returns `amend`, `update`, or `flush`:**
1. The lead dispatches `knowz:writer` with the liaison's self-contained request including explicit per-item operations, parent identity/key, distinct mutation keys, exact amend/update `KnowledgeId` values, phase identifier, and WorkGroup ID
2. The writer resolves vault IDs, preflights the exact target/identity, reconciles already-applied content, and executes each eligible logical mutation at most once. It does not reinterpret or prompt to change the lead-classified operation.
3. No other agent should call `create_knowledge` directly

**When no knowz:writer (single-agent / sequential), after a persistence action:**
1. Read `knowz-vaults.md` (project root) to resolve vault IDs and routing rules
2. Detect learning candidates from WorkGroup file content
3. Resolve the complete ordered mutation plan and one distinct deterministic key per logical mutation from the content-bound classification identity. Require an exact non-empty `KnowledgeId` for every amend/update; missing identity fails explicitly and never becomes create.
4. Preflight each exact target. For create, one materially equivalent match reconciles success, no match permits create, and conflicts/multiple matches stop. For amend/update, fetch the exact `KnowledgeId`, reconcile already-applied content, and leave a missing or ambiguous target unchanged.
5. Execute only the classified operation with the matching MCP tool and only in an unambiguously configured target vault. Never reinterpret amend/update as create.
6. On MCP failure, read canonical project-root `knowz-pending.md` first and append one block per failed logical mutation using its exact operation and distinct key. Identical key/content is already queued; a key/content collision fails closed. Never queue amend/update without its exact `KnowledgeId`.

### Audit Trail (Enterprise)

After Phase 3:
1. Read `knowz-vaults.md` to find a vault whose description mentions "enterprise", "compliance", or "audit"
2. Only push if `mcp_compliance_enabled: true`, an enterprise vault is configured, and `push_completion_records: true` (default)
- Push WorkGroup completion record with goal, NodeIDs, audit score, and decisions
- Push architecture drift findings if any detected during finalization

If MCP is not available, queue each eligible durable learning mutation exactly
once under its distinct key when required; missing-identity amend/update entries
remain errors and are not queued or recreated. Skip the remote audit trail only
after reporting the exact confirmed queue keys — all other phases work normally.

---

## 8. Multi-Agent Execution (Platform-Specific)

Phases can be executed by a single AI sequentially or by specialized agents coordinated by a lead. Quality gates and phase sequence remain the same regardless of execution model.

### Agent-to-Phase Mapping

| Phase | Specialist Agent | Expertise |
|-------|-----------------|-----------|
| 1A | analyst | Impact analysis, Change Set proposals |
| 1B | architect | Specification drafting, architecture review |
| 2A | builder | TDD implementation, verification loops |
| 2B | reviewer | Quality audit, security review |
| 2B | smoke-tester | Runtime smoke testing (parallel with reviewer) |
| 3 | closer | Finalization, learning capture |

### Execution Rules

When using multi-agent execution:
- Each phase maps to a specialist agent
- Phase dependencies enforce quality gates (1A must complete before 1B, etc.)
- User approves transitions between phases at quality gates
- Agents can communicate about gaps and blockers
- The lead agent coordinates but does not modify code directly
- Agents read context files independently — do not duplicate context across agents

### Single-Agent Execution

When a single AI handles all phases sequentially:
- Follow the same phase sequence and quality gates
- Pause at each gate for user approval
- All quality standards apply identically

### Parallel Execution (Multi-Agent Platforms)

On platforms supporting concurrent agents (Claude Code Agent Teams, future multi-agent runtimes):

#### Parallelism Boundaries
- **Between phases**: Phase 1A must produce Change Set before 1B drafts specs (scope must be approved first)
- **Within phases**: Independent NodeIDs can be implemented/audited in parallel
- **Across phases**: Incremental review can start on completed components while other components are still being implemented
- **Agent persistence**: Agents can stay alive across sub-phases to avoid cold-start overhead (e.g., builder persists through audit gap loop)

#### Dependency Map
The analyst produces a dependency map alongside the Change Set, identifying:
- Which NodeIDs share affected files (must be implemented sequentially or by same agent)
- Which NodeIDs are independent (can be implemented in parallel)
- Sequential dependencies (NodeID-B requires NodeID-A's output)

#### Incremental Review
The reviewer can audit completed NodeIDs before all implementation finishes. Gap findings are routed back to the implementer for targeted fixes, then re-audited. Agents persist through this gap loop — no respawning.

#### Context Gathering
Begin with a deterministic repository inventory and one analyst. Add a scanner
only for a named independent slice or material unknown. Add an architect after
the Change Set unless architectural ambiguity blocks scoping. Activate a
knowledge liaison only when a relevant vault/history question, pending capture,
or explicit save requirement exists; a deep vault query must answer a named
unresolved question. Do not spawn readers merely because a vault or worker slot
exists.

### Sequential Execution Protocol (for platforms without orchestration)

For platforms like Cursor, Copilot, or Windsurf where there is no agent orchestration.

**Copilot users:** Instead of manually reading phase prompts, use `#prompt:knowzcode-*` prompt files in VS Code Copilot Chat (e.g., `#prompt:knowzcode-work`, `#prompt:knowzcode-specify`). These prompt files encode the sequential protocol below with `#file:` references for context. See `knowzcode/copilot_execution.md` for the full Copilot execution guide.

```
FOR each phase in [1A, 1B, 2A, 2B, 3]:

    1. Read the phase prompt: knowzcode/prompts/[LOOP_{phase}]__*.md
    2. Read the WorkGroup file: knowzcode/workgroups/{WorkGroupID}.md
    3. Execute the phase instructions
    4. Write output to the WorkGroup file (prefix entries with "KnowzCode:")
    5. STOP at quality gate — present results to user
    6. Wait for user approval before reading the next phase prompt
```

**Key differences from orchestrated execution:**
- The user manually triggers each phase transition
- Context is carried via WorkGroup files, not inter-agent messaging
- All phase prompts are self-contained — they read context from knowzcode/ files
- Quality gates work identically (user approval required at each gate)

**Minimal viable execution** (no platform adapter needed):
1. Copy `knowzcode/` directory to your project
2. Give your AI the Phase 1A prompt with your goal
3. When the AI pauses, review output and give the next phase prompt
4. Repeat until Phase 3 completes

See your platform's adapter file for agent configuration details.

---

## 9. Context Handoff Protocol

When phases transition (whether via agents or sequentially), the following data MUST be communicated to the next phase:

### 1A → 1B Handoff
- WorkGroupID
- Approved Change Set (NodeIDs + affected files)
- Risk assessment and classification
- Historical context from prior WorkGroups
- User-approved scope boundaries

### 1B → 2A Handoff
- WorkGroupID
- Approved specifications (file paths)
- Tracker state (all NodeIDs marked `[WIP]`)
- Compliance constraints (if enterprise enabled)
- Pre-implementation commit hash

### 2A → 2B Handoff
- WorkGroupID
- Implementation artifacts (changed files list)
- Test results (pass counts, coverage)
- Verification iteration count
- Any `[SPEC_ISSUE]` tags (see below)

### 2B → 3 Handoff
- WorkGroupID
- Audit report with completion percentage
- Gap list with severity assessment
- User decision (proceed / return to 2A / modify specs)
- Security findings summary

On platforms with multi-agent orchestration, the lead agent manages this context. On platforms without orchestration, the user carries context by referencing WorkGroup files between phases.

---

## 10. Spec Issues During Implementation

If the builder discovers a spec is incorrect or incomplete during Phase 2A:

1. **Tag the issue**: Add `[SPEC_ISSUE]` comment in the WorkGroup file with details
2. **Continue implementing**: Use best judgment for the affected criterion
3. **Report in completion**: Include spec issues in the Phase 2A completion report
4. **Phase 2B catches it**: The auditor flags spec-vs-implementation divergences
5. **User decides**: At the 2B quality gate, the user can update specs or accept the deviation

Builders MUST NOT silently deviate from specs. Every deviation must be tagged and reported.

---

## 11. Blocker Escalation Protocol

When the verification loop reaches the maximum iteration count (10 for implementation, 5 for micro-fix):

### Blocker Report Format

```markdown
## Blocker Report: {WorkGroupID}

**Phase:** 2A Implementation
**Iteration Count:** 10 (maximum reached)
**NodeID(s) Affected:** [list]

### Root Cause Analysis
- **Failing Check:** [test name / build error / lint issue]
- **Error Message:** [exact message]
- **Attempts Made:** [summary of fix attempts]

### Recommended Recovery Options
1. **Modify spec**: Relax or adjust the criterion that cannot be met
2. **Change approach**: Use a different implementation strategy
3. **Split WorkGroup**: Extract the blocked NodeID into a separate WorkGroup
4. **Accept partial**: Proceed with documented gap (debt item)
5. **Cancel**: Abandon this WorkGroup

### Files Involved
- [list of files with the issue]
```

The user MUST select a recovery option before work continues.

---

## 12. Workflow Abandonment Protocol

If a WorkGroup needs to be abandoned mid-workflow:

1. **Preserve user state and unwind only proven workflow-owned changes**: Compare the pre-WorkGroup checkpoint, `git status --short`, and the explicit writer-owned path list. Never run a blanket revert, reset, checkout, clean, or stash. Restore a path only when the workflow created its current delta, the prior state is known, and restoration cannot overwrite unrelated user work; otherwise preserve the delta and list it in the abandonment record for user direction.
2. **Update tracker**: Set all affected NodeIDs back to their pre-WorkGroup status
3. **Log abandonment**: Create a log entry with type `WorkGroup-Abandoned` including the reason
4. **Close WorkGroup file**: Mark the WorkGroup file as abandoned with reason
5. **Preserve learnings**: If any useful patterns were discovered, capture them before closing

```markdown
---
**Type:** WorkGroup-Abandoned
**Timestamp:** [timestamp]
**WorkGroupID:** [ID]
**Phase At Abandonment:** [1A/1B/2A/2B/3]
**Reason:** [user decision / blocker / scope change]
**NodeID(s) Affected:** [list with their reverted statuses]
**Learnings Preserved:** [any useful insights, or None]
---
```
