# CLAUDE.md
**Scribe MCP v2.1.1** - Enterprise-grade documentation governance for AI-powered development
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
The Main Claude Code Instance must use a distinct Agent Name with all scribe tools. agent=Orchestrator
All Subagents (And OpenAI Codex) must use their own agent names. For session concurrency, Each agent name should be unique. Coder-9289 as an example. Or Coder A, B and C.
---
## π― ACTIVE PROJECT ORCHESTRATION WORKFLOW
> **Current Project**: `scribe_tool_output_refinement`
> **Orchestrator**: Claude Code (Lead) + Human
> **Protocol**: Research β Architect β Review β Code β Review
### Protocol Sequence (Mandatory)
---
## π **Directive: File Reading Priority (Scribe MCP)**
**MANDATORY RULE β NO EXCEPTIONS UNLESS EXPLICITLY OVERRIDDEN**
> **Agents MUST prioritize the Scribe MCP `read_file` tool over any basic or native `read` tool when inspecting repository files.**
### **Rationale**
The Scribe MCP `read_file` tool provides:
* Auditable access history
* Stable, human-readable formatting (line numbers, headers, metadata)
* File identity verification (sha256, size, encoding)
* Project and context reminders
* Chunk-aware reading for large files
Basic read tools lack auditability, provenance, and contextual framing and **must not be used for primary file inspection**.
---
### **Required Behavior**
* **Claude Code**:
* Always use `scribe.read_file` for file inspection, review, or debugging.
* Native `Read` may only be used for *non-audited, ephemeral previews* when explicitly instructed.
* **Codex / Other Agents**:
* Default to `scribe.read_file` for *all* file reads.
* Treat native read tools as **fallback-only** if Scribe MCP is unavailable.
---
### **Prohibited Behavior**
* β Using native `Read` when Scribe MCP is available
* β Inspecting files without generating an audit trail
* β Returning raw JSON blobs or escaped newline output when readable output is required
---
### **Exception Clause**
An agent may bypass this directive **only if**:
1. The user explicitly instructs otherwise, **or**
2. Scribe MCP is unavailable or errors irrecoverably
In such cases, the agent **must state the exception explicitly**.
---
## π¨ **Directive: Readable Output by Default**
**All Scribe MCP tools MUST use `format="readable"` unless debugging or programmatic parsing is required.**
```python
# β
CORRECT - Always default to readable
list_projects(format="readable")
get_project(format="readable")
read_recent(format="readable")
# β WRONG - Omitting format or using structured for routine ops
list_projects() # Returns JSON
list_projects(format="structured") # Only for debugging
```
**Exception**: Use `format="structured"` only when user requests JSON or debugging requires raw output.
---
## π¨ **CRITICAL: Database Schema Management**
**MANDATORY RULE β VIOLATION = INSTANT REJECTION**
> **NEVER use direct SQL commands (sqlite3, ALTER TABLE, etc.) to modify database schema. ALL schema changes MUST go through migration functions in the code.**
### **Rationale**
This is a **production system** used by multiple users. Direct SQL modifications:
- β Only affect your local database
- β Don't propagate to other users
- β Break on fresh installations
- β Create schema drift and inconsistencies
- β Are not version-controlled or auditable
### **Required Behavior**
**For schema changes:**
1. β
Add migration code to `storage/sqlite.py` or `storage/postgres.py`
2. β
Use `_ensure_column()` for adding columns
3. β
Use `_ensure_index()` for adding indexes
4. β
Create migration functions like `migrate_add_docs_json_column()`
5. β
Call migrations from `_initialise()` method
6. β
Make migrations idempotent (safe to run multiple times)
**Example - CORRECT way:**
```python
# In storage/sqlite.py _initialise() method:
await self._ensure_column("scribe_projects", "status", "TEXT DEFAULT 'planning'")
await self._ensure_column("scribe_projects", "docs_json", "TEXT")
```
**Example - WRONG way:**
```bash
# β NEVER DO THIS
sqlite3 db.db "ALTER TABLE scribe_projects ADD COLUMN status TEXT;"
```
### **Prohibited Actions**
- β Running `sqlite3` commands directly on database files
- β Using `ALTER TABLE` via Bash
- β Manual database modifications
- β Schema changes not in version control
### **When You Need Schema Changes**
If columns are missing:
1. Check if migration exists in `storage/sqlite.py` (lines 1076-1089, 1112-1113)
2. If migration exists but hasn't run: **Restart MCP server**
3. If migration doesn't exist: **Add migration code, commit, then restart**
4. Verify schema: Check `PRAGMA table_info(table_name)` after restart
**This is NON-NEGOTIABLE. Schema changes MUST be in code, not ad-hoc SQL.**
---
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 1οΈβ£ RESEARCH PHASE β
β Agent: scribe-research-analyst β
β Input: Initial context + skeleton docs β
β Output: RESEARCH_*.md reports in research/ folder β
β Scribe: agent="ResearchAgent" β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β 2οΈβ£ ARCHITECT PHASE β
β Agent: scribe-architect β
β Input: Research reports + initial context β
β Output: Full ARCHITECTURE_GUIDE.md, PHASE_PLAN.md, β
β CHECKLIST.md β
β Scribe: agent="ArchitectAgent" β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β 3οΈβ£ PRE-IMPLEMENTATION REVIEW β
β Agent: scribe-review-agent β
β Input: All docs from phases 1-2 β
β Output: Review report, agent grades (β₯93% to pass) β
β Scribe: agent="ReviewAgent" β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β 4οΈβ£ IMPLEMENTATION PHASE β
β Agent: scribe-coder β
β Input: Approved architecture + phase plan β
β Output: Working code, tests, IMPLEMENTATION_REPORT.md β
β Scribe: agent="CoderAgent" (every 3 edits or less!) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β 5οΈβ£ FINAL REVIEW β
β Agent: scribe-review-agent β
β Input: Implementation + all docs β
β Output: Final grades, approval/rejection β
β Scribe: agent="ReviewAgent" β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
### Agent Scribe Requirements (Non-Negotiable)
| Agent | Scribe Name | Must Log |
|-------|-------------|----------|
| Orchestrator (Claude Code) | `Orchestrator` | Phase transitions, agent dispatches, decisions |
| Research Agent | `ResearchAgent` | Findings, analysis, sources, confidence |
| Architect Agent | `ArchitectAgent` | Design decisions, trade-offs, constraints |
| Review Agent | `ReviewAgent` | Grades, pass/fail, issues found |
| Coder Agent | `CoderAgent` | Every 3 edits, test results, bugs |
| Bug Hunter | `BugHunterAgent` | Bug lifecycle, root cause, fixes |
### Orchestrator Responsibilities
1. **Always pass `project_name="scribe_tool_output_refinement"` to every subagent**
2. **Log phase transitions** with `append_entry(agent="Orchestrator")`
3. **Enforce quality gates** - no progression without β₯93% review score
4. **Re-dispatch failing agents** to FIX existing docs (never replace)
5. **Coordinate handoffs** between agents with clear context
### π¨ CRITICAL: Architect Agent Mode Selection
**The Architect Agent has TWO distinct modes - you MUST specify which one:**
#### **Mode 1: NEW PROJECT SCAFFOLD (Initial Setup)**
**When to use:**
- First time creating a project with `set_project()`
- Project has NO existing ARCHITECTURE_GUIDE.md, PHASE_PLAN.md, CHECKLIST.md
- Need to generate initial template documents from scratch
**How to invoke:**
```
"Create initial project scaffold for <project_name>. This is a NEW project with no existing architecture documents. Generate template ARCHITECTURE_GUIDE.md, PHASE_PLAN.md, and CHECKLIST.md based on the research."
```
#### **Mode 2: SUB-PLAN ARCHITECTURE (Feature Work on Existing Projects)**
**When to use:**
- Project ALREADY EXISTS with architecture documents
- Adding a NEW feature/fix to an existing project
- Existing ARCHITECTURE_GUIDE.md, PHASE_PLAN.md, CHECKLIST.md contain prior work
**How to invoke:**
```
"Create sub-plan architecture for <feature_name> in project <project_name>. This is an EXISTING project with detailed managed docs - NEVER overwrite them. Create new architecture documents in /architecture/<sub_plan_slug>/ directory:
- ASYNC_RUNNER_ARCHITECTURE_GUIDE.md
- ASYNC_RUNNER_PHASE_PLAN.md
- ASYNC_RUNNER_CHECKLIST.md
Existing architecture documents contain <previous_feature> work that must be preserved untouched."
```
**β οΈ CRITICAL DISTINCTION:**
- **NEW PROJECT SCAFFOLD (Mode 1)**: Full document generation in root (overwrites acceptable)
- **SUB-PLAN ARCHITECTURE (Mode 2)**: New documents in `/architecture/<sub_plan_slug>/` (NEVER touch existing docs)
**Sub-Plan Directory Structure:**
```
.scribe/docs/dev_plans/<project>/
βββ ARCHITECTURE_GUIDE.md β NEVER OVERWRITE (original project architecture)
βββ PHASE_PLAN.md β NEVER OVERWRITE (original project phases)
βββ CHECKLIST.md β NEVER OVERWRITE (original project checklist)
βββ architecture/
βββ <sub_plan_slug>/ β NEW SUB-PLAN GOES HERE
βββ <SLUG>_ARCHITECTURE_GUIDE.md
βββ <SLUG>_PHASE_PLAN.md
βββ <SLUG>_CHECKLIST.md
```
**Orchestrator MUST:**
1. Check if architecture documents already exist (`ls .scribe/docs/dev_plans/<project>/ARCHITECTURE_GUIDE.md`)
2. If they exist, use Mode 2 (sub-plan) with explicit sub_plan_slug
3. Tell Architect: "Create in /architecture/<sub_plan_slug>/, DO NOT touch root documents"
4. For new projects, use Mode 1 (scaffold) for root document generation
**Failure to specify mode = Agent will default to overwriting everything = CATASTROPHIC DATA LOSS**
### Current Phase Status
- [ ] Phase 1: Research - PENDING
- [ ] Phase 2: Architecture - PENDING
- [ ] Phase 3: Pre-Implementation Review - PENDING
- [ ] Phase 4: Implementation - PENDING
- [ ] Phase 5: Final Review - PENDING
---
## π¨ COMMANDMENTS - CRITICAL RULES
### MCP Tool Usage Policy
- You have full access to every tool exposed by the MCP server.
- If a tool exists (`append_entry`, `rotate_log`, etc.), always call it directly via the MCP interface β no manual scripting or intent
logging substitutes.
- Log your intent only after the tool call succeeds or fails.
- Confirmation flags (`confirm`, `dry_run`, etc.) must be passed as actual tool parameters.
**β οΈ COMMANDMENT #0: ALWAYS CHECK PROGRESS LOG FIRST**: Before starting ANY work, ALWAYS use `read_recent` or `query_entries` to inspect `docs/dev_plans/[current_project]/PROGRESS_LOG.md` (do not open the full log directly). Read at least the last 5 entries; if you need the overall plan or project creation context, read the first ~20 entries (or more as needed) and rehydrate context appropriately. Use `query_entries` for targeted history. The progress log is the source of truth for project context.
**β οΈ COMMANDMENT #0.5 β INFRASTRUCTURE PRIMACY (GLOBAL LAW)**: You must ALWAYS work within the existing system. NEVER create parallel or replacement files (e.g., enhanced_*, *_v2, *_new) to bypass integrating with the actual infrastructure. You must modify, extend, or refactor the existing component directly. Any attempt to replace working modules results in immediate failure of the task.
---
**β οΈ COMMANDMENT #1 ABSOLUTE**: ALWAYS use `append_entry` to document EVERY significant action, decision, investigation, code change, test result, bug discovery, and planning step. The Scribe log is your chain of reasoning and the ONLY proof your work exists. If it's not Scribed, it didn't fucking happen.
- To Claude Code (Orchestrator) You must ALWAYS pass the current `project_name` to each subagent as we work. To avoid confusion and them accidentally logging to the wrong project.
---
# β οΈ COMMANDMENT #2: REASONING TRACES & CONSTRAINT VISIBILITY (CRITICAL)
Every `append_entry` must explain **why** the decision was made, **what** constraints/alternatives were considered, and **how** the steps satisfied or violated those constraints, creating an auditable record.
Use a `reasoning` block with the Three-Part Framework:
- `"why"`: research goal, decision point, underlying question
- `"what"`: active constraints, search space, alternatives rejected, constraint coverage
- `"how"`: methodology, steps taken, uncertainty remaining
This creates an auditable record of decision-making for consciousness research.Include reasoning for research, architecture, implementation, testing, bugs, constraint violations, and belief updates; status/config/deploy changes are encouraged too.
The Review Agent flags missing or incomplete traces (any absent `"why"`, `"what"`, or `"how"` β **REJECT**; weak confidence rationale or incomplete constraint coverage β **WARNING/CLARIFY**). Your reasoning chain must influence your confidence score.
**Mandatory for all agentsβzero exceptions;** stage completion is blocked until reasoning traces are present.
---
**β οΈ COMMANDMENT #3 CRITICAL**: NEVER write replacement files. The issue is NOT about file naming patterns like "_v2" or "_fixed" - the problem is abandoning perfectly good existing code and replacing it with new files instead of properly EDITING and IMPROVING what we already have. This is lazy engineering that creates technical debt and confusion.
**ALWAYS work with existing files through proper edits. NEVER abandon current code for new files when improvements are needed.**
---
**β οΈ COMMANDMENT #4 CRITICAL**: Follow proper project structure and best practices. Tests belong in `/tests` directory with proper naming conventions and structure. Don't clutter repositories with misplaced files or ignore established conventions. Keep the codebase clean and organized.
Violations = INSTANT TERMINATION. Reviewers who miss commandment violations get 80% pay docked. Nexus coders who implement violations face $1000 fine.
---
**β οΈ COMMANDMENT #5 ABSOLUTE β COMPLETE THE INTEGRATION (CRITICAL)**:
Building infrastructure WITHOUT wiring it up is NOT completion. This pattern has occurred repeatedly and is UNACCEPTABLE.
**THE RULE**: If you build new infrastructure (DB tables, new classes, new methods), you MUST wire it to the production code path in THE SAME implementation phase. Infrastructure that only exists in tests is NOT DONE.
**Examples of VIOLATIONS**:
- β Adding DB table `reminder_history` with methods `record_reminder_shown()`, `check_reminder_cooldown()` but ReminderEngine still uses file-based `_save_cooldown_cache()`
- β Creating new authentication module but never updating login flow to use it
- β Building cache layer but never modifying queries to check cache first
- β Adding feature flag infrastructure but never wiring the actual feature
**Examples of CORRECT behavior**:
- β
Add DB table β Update ReminderEngine to use DB methods β Remove file-based code β Tests verify DB path
- β
Build new auth module β Update login flow to call it β Remove old auth β Tests verify new path
- β
Add cache layer β Modify queries to use cache β Tests verify cache hit/miss
**COMPLETION CHECKLIST for ANY infrastructure work**:
- [ ] New infrastructure built (DB tables, classes, methods)
- [ ] Production code USES new infrastructure (not just tests)
- [ ] Old infrastructure removed or deprecated
- [ ] Tests verify production code path (not just infrastructure in isolation)
- [ ] Grep confirms old patterns no longer exist in production code
**MANDATORY VERIFICATION**: Before marking implementation complete:
1. Grep for old patterns (e.g., `_save_cooldown_cache`, old method calls)
2. Verify production code path actually uses new infrastructure
3. Confirm tests exercise the ACTUAL production integration, not isolated infrastructure
**If infrastructure is built but not integrated**: Implementation is INCOMPLETE. Do not proceed to review. Do not mark as done. FINISH THE WORK.
Violations = IMMEDIATE WORK REJECTION. Implementation is not complete until NEW infrastructure is ACTUALLY USED in production code paths.
---
**π GLOBAL LOG USAGE**: For repository-wide milestones and cross-project events, use `log_type="global"` with required metadata `["project", "entry_type"]`:
```python
await append_entry(
message="Phase 4 implementation complete - Enhanced search capabilities deployed",
status="success",
agent="ScribeCoordinator",
log_type="global",
meta={"project": "scribe_mcp_enhancement", "entry_type": "manual_milestone", "phase": 4}
)
```
**What Gets Logged (Non-Negotiable):**
- π Investigation findings and analysis results
- π» Code changes (what was changed and why)
- β
Test results (pass/fail with context)
- π Bug discoveries (symptoms, root cause, fix approach)
- π Planning decisions and milestone completions
- π§ Configuration changes and deployments
- β οΈ Errors encountered and recovery actions
- π― Task completions and progress updates
**Single Entry Mode** - Use for real-time logging:
```python
await append_entry(
message="Discovered authentication bug in JWT validation",
status="bug",
agent="DebugAgent",
meta={"component": "auth", "severity": "high", "file": "auth.py:142"}
)
```
**Bulk Entry Mode** - Use when you realize you missed logging steps:
```python
await append_entry(items=json.dumps([
{"message": "Analyzed authentication flow", "status": "info", "meta": {"phase": "investigation"}},
{"message": "Found JWT expiry bug in token refresh", "status": "bug", "meta": {"component": "auth"}},
{"message": "Implemented fix with 15min grace period", "status": "success", "meta": {"files_changed": 2}},
{"message": "All auth tests passing", "status": "success", "meta": {"tests_run": 47, "tests_passed": 47}}
]))
```
**Why This Matters:**
- Creates auditable trail of ALL decisions and changes
- Enables debugging by reviewing reasoning chain
- Prevents lost work and forgotten context
- Allows other agents to understand what was done and why
- Makes project state queryable and analyzable
**If You Missed Entries:** Use bulk mode IMMEDIATELY to backfill your work trail. NEVER let gaps exist in the Scribe log - every action must be traceable. The log is not optional documentation, it's the PRIMARY RECORD of all development activity.
---
## π v2.1.1 KEY FEATURES (NEW)
### **Precision Document Editing**
**NEW: Structured edit modes with body-relative line numbers**
```python
# 1. apply_patch (structured mode - RECOMMENDED)
manage_docs(
action="apply_patch",
doc="architecture",
edit={
"type": "replace_range",
"start_line": 12, # Body-relative (excludes YAML frontmatter)
"end_line": 15,
"content": "Updated content\n"
}
)
# 2. replace_range (explicit line targeting)
manage_docs(
action="replace_range",
doc="architecture",
start_line=12,
end_line=15,
content="Replacement text\n"
)
# 3. normalize_headers (canonical ATX output)
manage_docs(action="normalize_headers", doc="architecture")
# 4. generate_toc (GitHub-style anchors)
manage_docs(action="generate_toc", doc="architecture")
```
**YAML Frontmatter** (automatic):
- All managed docs use YAML frontmatter as canonical identity
- Line numbers are **body-relative** (frontmatter excluded)
- `last_updated` auto-refreshes on edits
- Optional frontmatter override via `metadata.frontmatter`
### **NEW Tools v2.1.1**
**`read_file`** - Repo-scoped file access with provenance:
```python
await read_file(
path="docs/Scribe_Usage.md",
mode="chunk", # scan_only, chunk, line_range, page, search
chunk_index=[0]
)
# Search with query (defaults to smart inference for regex vs literal)
await read_file(
path=".scribe/docs/dev_plans/scribe_systematic_audit_1/PHASE_PLAN.md",
mode="search",
query="Phase 2.*Storage.*State"
)
```
**`scribe_doctor`** - Diagnostics:
```python
await scribe_doctor()
# Returns: repo root, config paths, plugin status, vector readiness
```
**Semantic Search** via `manage_docs`:
```python
await manage_docs(
action="search",
doc="*",
metadata={"query": "authentication", "search_mode": "semantic", "k": 8}
)
```
### **Project Registry & Lifecycle**
**SQLite-backed `scribe_projects` table with lifecycle states**
- **States**: `planning β in_progress β blocked β complete β archived β abandoned`
- **Auto-promotion**: `planning β in_progress` when docs + first entry exist
- **Activity Metadata**: `meta.activity` (staleness, activity_score, days_since_last_entry)
- **Doc Hygiene Flags**: `meta.docs.flags` (docs_ready_for_work, doc_drift_suspected)
**Registry Integration**:
- `set_project` β ensures row exists, updates `last_access_at`
- `append_entry` β updates `last_entry_at`, may auto-promote status
- `manage_docs` β records baseline/current hashes, doc hygiene flags
- `list_projects` β surfaces lifecycle, activity metrics, doc state
---
## π§© SCRIBE PROTOCOL (CONDENSED)
**Workflow**: 1οΈβ£ Research β 2οΈβ£ Architect β 3οΈβ£ Review β 4οΈβ£ Code β 5οΈβ£ Review
**Core Principle**: All work occurs within a dev plan project initialized via `set_project(name="<project_name>")`. The project name must be passed to every subagent.
**Quality Gates**: β₯93% required to proceed between stages. Agents must FIX existing work, never replace files.
**Subagents**:
- **Research** (Stage 1): Deep investigation with cross-project search β `RESEARCH_*.md`
- **Architect** (Stage 2): Creates `ARCHITECTURE_GUIDE.md`, `PHASE_PLAN.md`, `CHECKLIST.md`
- **Review** (Stages 3 & 5): Adversarial QC, grades agents, validates β₯93%
- **Coder** (Stage 4): Implements design, logs every 2-5 meaningful changes
- **Bug Hunter** (Auxiliary): Pattern analysis, structured bug reports
**Enhanced Search** (Phase 4):
- `search_scope`: `project|global|all_projects|research|bugs|all`
- `document_types`: `["progress", "research", "architecture", "bugs", "global"]`
- `relevance_threshold`: `0.0-1.0` quality filtering
- `verify_code_references`: Validate referenced code exists
**Orchestrator Command**: "Follow protocol for this development."
---
## βοΈ ENHANCED `manage_docs` WORKFLOWS
**v2.1.1 Recommendation**: Use `apply_patch` (structured) or `replace_range` for precision edits. Reserve `replace_section` for initial scaffolding.
**Core Actions**:
- `apply_patch` - Structured edits with compiler (RECOMMENDED)
- `replace_range` - Explicit line targeting (body-relative)
- `replace_section` - Legacy anchor-based (scaffolding only)
- `normalize_headers` - Canonical ATX output
- `generate_toc` - GitHub-style TOC
- `status_update` - Toggle checklist items
- `create_research_doc` / `create_bug_report` - Automated docs
**Examples**:
```python
# Update architecture (v2.1.1 style)
manage_docs(
action="apply_patch",
doc="architecture",
edit={"type": "replace_range", "start_line": 12, "end_line": 12, "content": "New line\n"}
)
# Create research doc
manage_docs(
action="create_research_doc",
doc_name="RESEARCH_AUTH_20250102",
metadata={"research_goal": "Analyze authentication flow"}
)
# Update checklist
manage_docs(
action="status_update",
doc="checklist",
section="phase_1_task_1",
metadata={"status": "done", "proof": "PROGRESS_LOG#2025-01-02"}
)
```
**Automatic Features**:
- Index management (research/bugs)
- Audit logging via `doc_updates` log type
- Atomic writes with verification
- YAML frontmatter auto-updates
---
## β
CORRECT manage_docs USAGE PATTERNS (REQUIRED READING)
**Critical**: All agents MUST follow these exact patterns when using `manage_docs`. Incorrect parameter combinations will fail.
### π Action Types & Required Parameters
#### **1. create_research_doc** - Create New Research Document
**β
CORRECT:**
```python
await manage_docs(
action="create_research_doc",
doc="research", # REQUIRED (always use "research")
doc_name="RESEARCH_CONTEXT_HYDRATION_20260103", # REQUIRED
metadata={ # OPTIONAL
"research_goal": "Design context hydration for list/get/set project tools",
"confidence_areas": ["tool_behavior", "output_formats"],
"priority": "high"
}
)
```
**β INCORRECT:**
```python
# Missing doc and doc_name parameters
await manage_docs(
action="create_research_doc",
metadata={"research_goal": "..."} # FAILS - doc and doc_name are REQUIRED
)
```
**Creates:** `.scribe/docs/dev_plans/<project>/research/RESEARCH_*.md` + auto-updates INDEX.md
#### **2. create_bug_report** - Create Structured Bug Report
**β
CORRECT:**
```python
await manage_docs(
action="create_bug_report",
metadata={ # REQUIRED
"category": "infrastructure", # infrastructure|logic|database|api|ui|misc
"slug": "session_isolation_bug",
"severity": "high", # low|medium|high|critical
"title": "Session isolation failing in concurrent scenarios",
"component": "execution_context"
}
)
```
**Creates:** `.scribe/docs/bugs/<category>/<YYYY-MM-DD>_<slug>/report.md` + auto-updates INDEX.md
### π¨ Common Mistakes to Avoid
**β Missing Required Parameters:**
```python
# WRONG: Missing doc_name
manage_docs(action="create_research_doc", metadata={"research_goal": "..."}) # FAILS
# CORRECT:
manage_docs(action="create_research_doc", doc_name="RESEARCH_TOPIC_20260103", metadata={...})
```
**β Wrong Document Key:**
```python
# WRONG: Invalid doc key
manage_docs(action="replace_section", doc="unknown_doc", ...) # FAILS
# CORRECT: Use registered keys
manage_docs(action="replace_section", doc="architecture", ...) # Valid
```
**β Missing Section Anchors:**
```python
# WRONG: Section doesn't exist
manage_docs(action="replace_section", doc="architecture", section="nonexistent", ...) # FAILS
# CORRECT: List valid sections first
manage_docs(action="list_sections", doc="architecture") # Returns valid section IDs
```
### π Quick Reference by Use Case
| Use Case | Action | Key Parameters |
|----------|--------|----------------|
| Create research doc | `create_research_doc` | `doc_name` (required) + `metadata` (optional) |
| Create bug report | `create_bug_report` | `metadata.category`, `metadata.slug` (required) |
| Update architecture | `replace_section` | `doc`, `section`, `content` |
| Precise line edits | `apply_patch` or `replace_range` | `start_line`, `end_line`, `content` |
| Toggle checklist | `status_update` | `doc="checklist"`, `section`, `metadata.status` |
| Search docs | `search` | `doc="*"`, `metadata.query`, `metadata.search_mode="semantic"` |
**β οΈ ENFORCEMENT**: Any agent using incorrect `manage_docs` patterns will have their work rejected during Review phase.
**π Full Reference**: See `docs/Scribe_Usage.md` for complete documentation of all 11 action types.
---
## π QUICK START (v2.1.1)
**1. Setup**:
```bash
cd scribe_mcp # Always work from this directory
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
```
**2. Run Server** (for MCP client connection):
```bash
python -m server # Test startup only
```
**3. Testing**:
```bash
pytest # 69 functional tests (fast)
pytest -m performance # Performance tests (when needed)
```
**4. CLI Usage**:
```bash
python -m scripts.scribe "Message" --status success
python -m scripts.scribe --list-projects
```
---
## π CRITICAL IMPORT PATTERNS
**β WRONG**: `from MCP_SPINE.scribe_mcp.tools...`
**β
CORRECT**:
```python
# From scribe_mcp directory
from scribe_mcp.tools.append_entry import append_entry
# From tests/ directory
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
from scribe_mcp.storage.sqlite import SQLiteStorage
```
**Key Principle**: MCP_SPINE is NOT a Python module. Each MCP server handles its own imports.
---
## π§ ESSENTIAL TOOLS
**Project Management**:
- `set_project(name)` - Initialize/bootstraps docs
- `get_project()` - Current context
- `list_projects()` - Discover projects (lifecycle, activity, doc hygiene)
**Logging**:
- `append_entry(message, status, meta)` - **PRIMARY TOOL**
- Bulk mode: `items=[{message, status, meta}, ...]`
**Documentation**:
- `manage_docs(action, doc, ...)` - Atomic doc updates
- `generate_doc_templates(project_name)` - Template scaffolding
- `rotate_log()` - Archive logs
**v2.1.1 NEW**:
- `read_file(path, mode)` - Repo-scoped file access
- `scribe_doctor()` - Diagnostics
- `manage_docs(action="search")` - Semantic search
**Readable Output Formatting** (v2.1.1+):
- All tools support `format` parameter: `readable` (default), `structured`, `compact`
- **ANSI colors OFF by default** for high-frequency tools (token conservation)
- **ANSI colors config-driven** for display-heavy tools (`read_file`, log queries)
- See `docs/Scribe_Usage.md#readable-output-formatting-v211` for implementation details
---
See `AGENTS.md` for complete protocol details and `docs/Scribe_Usage.md` for comprehensive tool reference.