# Unfamiliar — MVP Requirements

> **Status:** Complete — ready for `/plan:init`. v1.1 features are documented separately in `v1.1-requirements.md`.

```
Checklist:
[x] 1. Problem & Purpose
[x] 2. User Stories
[x] 3. Tech Stack
[x] 4. Data Model
[x] 5. Future Features
[x] 6. Business Rules & Validation
[x] 7. UI/UX
[x] 8. Non-Functional Requirements
[x] 9. Out of Scope
[x] 10. Coverage Confirmation
```

---

## 1. Overview

**Project Name:** Unfamiliar

### Problem

Developers joining a new team or codebase face a disorienting ramp-up period. Common frustrations:

- **No clear starting point** — the codebase is large and there's no guided path through it
- **Attention decay** — reading unfamiliar code is cognitively expensive; focus drops off after ~20 minutes, especially for developers with ADHD
- **No big-picture visibility** — it's easy to get lost in details without understanding how modules connect, where the debt is, or what the testing situation looks like
- **Passive onboarding** — most onboarding is "read the code and ask questions," which provides no structure, no feedback, and no sense of progress

### Purpose

Unfamiliar is an AI-powered codebase onboarding tool that generates structured, gamified missions to guide a developer through understanding an unfamiliar codebase. It analyzes the code across seven investigation categories, then produces a themed campaign of time-boxed tasks — progressing from orientation through exploration to mastery.

### Investigation Categories

| Category | Focus | Noir Metaphor |
|---|---|---|
| Architecture | Module structure, entry points, how components connect | "Map the territory" |
| Domain & Business Logic | Core workflows, business rules, what the app does and why, failure modes and error handling | "The motive" |
| Data Flow | Schema, state management, how data moves through the system | "Follow the money" |
| Dependencies | External services, APIs, key libraries, boundary points, configuration & environment | "Known associates" |
| Conventions | Patterns, idioms, error handling style, naming | "The local rules" |
| Testing | Coverage, test quality, untested paths | "Examine the evidence" |
| Technical Debt | Code smells, violations, structural risks | "Where the bodies are buried" |

**Security** is a cross-cutting tag, not a separate category. Missions across all categories can be flagged as security-relevant when they touch auth flows, data boundaries, input validation, sensitive data handling, or dependency vulnerabilities.

### Who is it for?

- **Primary user:** A developer (likely with ADHD or gamification affinity) who has just been dropped into an unfamiliar codebase and needs to get productive
- **Secondary user:** A developer revisiting their own codebase after time away, or wanting a structured audit of code they know but haven't systematically reviewed

### Why not an existing tool?

- Static analysis tools (SonarQube, CodeClimate) report issues but don't teach you the codebase
- AI coding assistants (Copilot, Cursor) answer questions but don't provide structure or progression
- Documentation generators (Sphinx, JSDoc) describe the API but not the architecture or intent
- Unfamiliar combines analysis with guided learning and gamified engagement — no existing tool does this

### Usage pattern

This is an onboarding accelerator, not a daily-driver tool. A developer would use it on 2-3 codebases per job, running focused sessions over a few days to a few weeks until they reach competence. The campaign has a clear win state: "You understand this codebase."

### Distribution & goals

- Open source on GitHub with donation link
- Portfolio piece demonstrating AI agent architecture
- Learning vehicle for LangGraph/LangChain and agentic AI patterns

---

## 2. User Stories

### US-1: Codebase Briefing

**As a** developer new to a codebase, **I want to** point the tool at a repo and receive a structured briefing on what it does and how it's organized, **so that** I have a mental map before I start exploring.

**Acceptance criteria:**

- User provides a path to a local repository
- System analyzes the codebase and produces a briefing covering: purpose/domain, tech stack, module structure, entry points, and key external dependencies
- Briefing is plain language — no theme applied. Clarity and accuracy over entertainment
- Analysis runs without requiring user configuration or input beyond the repo path
- Briefing identifies the seven investigation categories and notes relative complexity/size of each (e.g., "testing is sparse" or "heavy external dependency surface")
- Briefing includes a security posture summary: authentication approach, sensitive data flows, input validation patterns, known dependency vulnerabilities

### US-2: Campaign Reveal & Mission Chains

**As a** developer who has received a briefing, **I want to** see a small set of starting missions that build on each other, **so that** I'm not overwhelmed and each mission adds to what I already know.

**Acceptance criteria:**

- User sees 3-5 mission chain starting points (not a flat list of all missions)
- Each chain is a sequence where later missions build on knowledge from earlier ones
- Each mission displays: title (themed), category, estimated time, difficulty tier, and a 1-2 sentence description of what the user will investigate
- Completing missions unlocks new chain starting points

### US-3: Mission Execution

**As a** developer working through a mission, **I want to** receive specific, time-boxed instructions about what to investigate in the codebase, **so that** I stay focused and make progress without getting lost.

**Acceptance criteria:**

- Each mission specifies: what files/modules to look at (with file paths and line numbers), what to look for, what question to answer or what to verify
- User investigates in their own IDE/editor — the tool directs, it does not display code
- Missions are time-boxed (10-15 min, 20-30 min, or 30-45 min)
- Missions have a clear completion condition — the user knows when they're done
- Themed narrative wraps the instructions without obscuring the technical content
- **Mission completion:** Self-report — user marks the mission complete. Always available, no LLM call required
- On completion, the user receives a brief summary of what they learned and how it connects to the bigger picture

> **v1.1** adds annotation and field report completion methods with LLM feedback, plus staleness detection. See `v1.1-requirements.md`.

### US-4: Progress Tracking

**As a** developer working through a campaign over multiple sessions, **I want to** see what I've accomplished and what's ahead, **so that** I feel a sense of progress and can resume without losing context.

**Acceptance criteria:**

- System tracks which missions have been completed or are in progress
- User can see an overview of their campaign: completed missions, available next missions, and locked future content
- Progress persists across sessions (user can close the tool and come back)
- Summary stats are available: missions completed, categories explored, estimated coverage of the codebase

### US-5: Campaign Completion

**As a** developer who has worked through the campaign, **I want to** know when I've reached sufficient understanding of the codebase, **so that** I have confidence I'm ready to work in it.

**Acceptance criteria:**

- System defines a "case closed" state: coverage across all seven investigation categories
- User receives a final briefing summarizing: what they learned, key architectural patterns, known risks/debt areas, and any areas that were skipped or deferred
- Campaign can be "closed" early by the user if they feel they've learned enough
- Completion status is visible (category-level progress, not a single number)

> **v1.1** adds assessment mode with different completion criteria. See `v1.1-requirements.md`.

### US-6: Notebook *(v1.1)*

> **Deferred to v1.1.** See `v1.1-requirements.md` for full acceptance criteria. The notebook is a companion artifact outside the core investigation loop.

---

## 3. Tech Stack

### Language & Runtime

- **Python 3.11+** — core application language

### Agent Framework

- **LangGraph** — orchestrates the multi-step analysis pipeline (codebase scan → structural mapping → LLM analysis → mission generation). Provides checkpointing for campaign state and graph-based workflow modeling
- **LangChain** — LLM provider abstraction layer. Enables model-agnostic design so users can swap between Claude, GPT, GLM, or other providers via configuration

### LLM Integration

- **Model-agnostic architecture** — LangChain abstracts provider differences, making it simple to add new providers. MVP ships with support for:
  - **Anthropic Claude** (required)
  - **Zhipu GLM** (required)
  - Additional providers (OpenAI, local models via Ollama, etc.) can be added by implementing LangChain's chat model interface
- **Configuration** — user specifies provider and API key in `~/.unfamiliar/config.toml`. The provider field accepts: `anthropic`, `glm`, or any registered provider ID
- **Hybrid analysis strategy** to minimize token usage:
  1. **Static analysis pass (no LLM):** Python AST parsing, import tracing, directory walking, test file mapping, git history analysis. Produces a structural map of the codebase
  2. **Targeted LLM pass:** Sends the structural map + contents of key files (not the entire repo) to the LLM for briefing generation, deeper analysis — architecture reasoning, pattern identification — and mission generation
  3. **Front-loaded generation:** Briefing and all mission content are generated up front and persisted locally. Character selection (which happens after generation) only affects mission sort order. Day-to-day usage does not hit the LLM
  4. **On-demand refresh:** LLM is called again only for stale mission regeneration (when files change) and campaign completion summary
- **Key file selection** determines analysis depth. The LLM receives full contents of prioritized files, not the entire repo. Selection uses a **priority queue with configurable token budget**:
  - Files are ranked by score: entry points = 100, high centrality (imported by many) = 50, high complexity = 30, test files = 20
  - Files are added in priority order until token budget exhausted (default: ~50k tokens for key files)
  - Remaining files are represented by signatures and structure only
  - Token budget is user-configurable via `~/.unfamiliar/config.toml` for deeper/shallower analysis
  - Priority criteria:
    - **Entry points:** MVP uses AST heuristics to detect entry points (`if __name__ == "__main__"`, Flask/FastAPI app instances, CLI entry functions, async event handlers). v1.1 uses the structured Entry Point entity
    - **High-connectivity files:** Hubs in the import graph (files imported by many others)
    - **Complex files:** Large files or high cyclomatic complexity flagged by static analysis
    - **Test files:** Files matching test patterns (`test_*.py`, `*_test.py`, `*.spec.ts`)
- **Standards-aware analysis:** The LLM pass receives coding standards from `~/.unfamiliar/standards/` as context alongside the structural map and key files. Only relevant standards are sent: universal standards always, language-specific standards only for languages detected in the codebase. Missions generated from this context are tagged with which standard they evaluate (string tag, not a DB relationship), enabling display and filtering by standard
- **Context window adaptation:** Smaller-context models analyze fewer files per pass with a synthesis step; larger-context models can process more in one shot
- **Failure handling & resumability:**
  - **Chunked processing:** Mission generation is split into 7 category-level LLM calls (Architecture, Domain & Business Logic, Data Flow, Dependencies, Conventions, Testing, Technical Debt) rather than one monolithic call. Each completed category is checkpointed via LangGraph
  - **Checkpointing:** LangGraph's built-in checkpointing persists state after each pipeline step. If the process fails, it resumes from the last checkpoint — completed steps are never repeated. Checkpoints are at category boundaries
  - **Retry logic:** Transient failures (rate limits 429, network errors, 5xx errors) trigger exponential backoff retry with jitter. Max 5 retries per step before giving up
  - **Resume on restart:** If the user restarts after a failure, `unfamiliar resume` detects incomplete initialization and continues from the first incomplete category automatically. No separate "retry failed category" step needed
  - **Partial campaign usability:** Missions from completed categories are available while initialization is pending. The user can proceed with what's ready
  - **User notification of partial progress:**
    - During initialization, show progress indicator with category names ("Generating Architecture missions... 3 of 7 categories complete")
    - If initialization fails, display clear summary: what completed successfully, what failed, and why. Instruct user to run `unfamiliar resume` when ready to continue
    - If a campaign has incomplete data (e.g., only 4 of 7 categories generated), the user is warned on session start that the campaign is incomplete and offered to continue initialization
    - The tool must not present a partial campaign as fully usable — incomplete categories are clearly marked as "unavailable" in the UI
  - **Non-recoverable failures:** Auth errors (401/403) stop immediately with clear message to check API key. No retry. After max retries exceeded on transient failures, display a message instructing the user to run `unfamiliar resume` later when the issue is resolved
- **Mission validation (programmatic):**
  - After mission generation, a validation pass checks for common LLM hallucinations:
    - **File path validation:** Verify referenced files exist at generation time
    - **Line range validation:** Clamp line numbers to actual file bounds
    - **Prerequisite graph validation:** Detect cycles, verify all referenced mission IDs exist, enforce max depth of 3, ensure every mission is reachable from a root mission
    - **Root mission validation:** Each category must have at least 1-2 missions with zero prerequisites
    - **Schema validation:** All required fields present, valid enum values for category/difficulty/status
  - **Auto-fix where safe:** Line ranges are clamped, circular prerequisites are broken by removing one edge, missing prerequisites are removed
  - **MVP handling for deleted files:** Missions referencing non-existent files are hidden from the available list (cannot be explored). v1.1 staleness checking will handle this more gracefully with refresh options
  - **User visibility:** On session start, display a dismissable banner summarizing validation status: "23 missions generated, 2 have warnings (files not found). These missions can still be completed."
  - **No LLM calls for validation** — all checks are programmatic (filesystem, graph algorithms, schema checks)

- **Typer** — CLI framework for entry-point commands (e.g., `unfamiliar investigate /path/to/repo`, `unfamiliar resume`)
- **Textual** — TUI application framework (built on Rich). Provides persistent multi-pane layouts, styled widgets, and an interactive session experience. The main interface is a Textual app, not a scrolling terminal
- **Rich** — included via Textual. Used for styled text rendering within the TUI (panels, tables, syntax highlighting, progress bars)
- **Textual CSS (TCSS)** — per-theme stylesheets that control the visual presentation. Themes swap the stylesheet at runtime to change the entire look and feel
- The CLI experience should feel like a retro text-adventure game — persistent layout, command input, narrative responses — not a utilitarian task runner

### Data Storage

- **SQLite** — internal campaign state (missions, chains, progress, prerequisites, file hashes for staleness detection). Ships with Python stdlib, no external dependency
- **Markdown files** — user-facing artifacts (briefing, detective's notebook, campaign completion summary). Readable and editable outside the tool

### Static Analysis (no-LLM layer)

- **Python `ast` module** — parse Python source files for structure, imports, function/class definitions
- **Tree-sitter** (or equivalent) — multi-language parsing for non-Python codebases
- **Language adapters** — semantic analysis layer with per-language implementations. v1 ships with Python, TypeScript, and JavaScript (JS adapter is near-zero additional effort over TS). Well-documented adapter interface for community contributions of additional languages
- **Unsupported language fallback** — for codebases in languages without an adapter, the static analysis layer falls back to directory walking and file listing only (no AST parsing, no import tracing, no function/class mapping). The LLM pass receives raw file contents of key files and does its best. Results are shallower but still useful. The user sees a notification at campaign start that their language doesn't have full adapter support and that analysis depth will be limited
- **Git integration** — commit history for understanding evolution. *(v1.1 adds file change detection for staleness)*
- **Dependency scanning** — parse requirements.txt/pyproject.toml/package.json for dependency mapping and known vulnerability flags
- **Test coverage detection** — progressive enhancement approach:
  - **Tier 1 (always available):** Static analysis identifies test files via naming conventions (`test_*.py`, `*.spec.ts`, `*_test.py`). Import analysis maps tests to source files. Detects untested source files. No external tools required
  - **Tier 2 (enhanced):** Auto-detect coverage reports at common paths (`.coverage`, `coverage.xml`, `htmlcov/`). If found, parse for actual line/branch coverage percentages. Enables coverage-aware missions ("This function has 0% coverage")
  - **User notification:** At campaign start, show testing analysis level: "Testing analysis: Enhanced (coverage.xml found) — 73% coverage across 47 files" or "Testing analysis: Basic — for enhanced analysis, run `pytest --cov --cov-report=xml`"
  - **Unsupported languages:** Fall back to Tier 1 (test file detection via naming conventions)
- **Module boundary detection** — programmatic identification of logical code units using **clustering-primary approach**:
  - **Import graph is the primary signal** — files that import each other form clusters
  - **Directory structure is a weight, not a boundary** — files in the same directory get a slight boost to connection strength, but won't override strong import relationships
  - **Language-agnostic approach** — no reliance on language-specific markers like `__init__.py`
  - Language adapters can enhance detection with language-specific heuristics (e.g., Python adapter knows `auth/` and `tests/test_auth/` are related), but the core algorithm works without them
  - **Mitigations for clustering unpredictability:**
    - **Transparent membership** — user can always see which files belong to a detected module
    - **LLM-generated names** — instead of "Module 3", the LLM suggests a name based on contents (e.g., "Authentication & Sessions")
    - **Confidence indicator** — modules with weak clustering show a confidence badge; user knows the boundary is tentative
    - **No user correction in MVP** — algorithm does its best; manual adjustment deferred to v1.1+
  - Future feature: LLM boundary verification for higher accuracy (optional, costs tokens)

### Security Analysis

- Security is a **cross-cutting tag**, not a separate investigation category
- Missions across all categories can be tagged "security-relevant" when they touch: auth flows, data boundaries, input validation, sensitive data handling, dependency vulnerabilities
- The briefing includes a dedicated security posture summary
- Static analysis layer checks for: hardcoded secrets, missing input validation at boundaries, known CVEs in dependencies
- **Secret detection:** Uses `detect-secrets` library (Apache-licensed, well-maintained, plugin support)
- **CVE scanning:** Uses language-native tools via adapter interface — `pip-audit` for Python, `npm audit` for JS/TS. No external API dependency

### Installation & Storage

- **Global install** — installed once on the user's machine, not per-codebase. pip-installable via `pip install unfamiliar` (or from GitHub)
- **No Docker required** — runs directly on the user's machine
- **Central storage** — all campaign data lives in `~/.unfamiliar/`:
  - `~/.unfamiliar/config.toml` — LLM provider, preferences (NOT API keys)
  - `~/.unfamiliar/standards/` — coding standards used by the analysis pipeline (especially Technical Debt and Conventions categories). Ships with universal defaults; user can override or extend
    - `universal/` — language-agnostic principles (dependency injection, error handling, complexity signals, naming, testing, etc.). Defaults ship with the tool and can be overridden
    - `languages/` — per-language standards (Python, TypeScript, SQL, etc.). User adds files matching the languages they work in
  - `~/.unfamiliar/campaigns/<repo-name>-<hash>/` — per-codebase campaign DB, briefing, notebook, and generated artifacts. Directory name format: repo folder name + first 6 characters of SHA-256 hash of the absolute path (e.g., `backend-a3f2c1`, `unfamiliar-7b2d9e`). If directory exists with different repo path (hash collision), append `-1`, `-2`, etc.
- **Target repo stays untouched** — no files are added to the codebase being investigated

### API Key Security

API keys are resolved exclusively from environment variables. Config file storage was removed to reduce attack surface.

**Supported environment variables:**
- `ANTHROPIC_API_KEY` for Anthropic Claude
- `ZHIPUAI_API_KEY` for Zhipu GLM
- `UNFAMILIAR_API_KEY` as a generic fallback (used if provider-specific env var is not set)

**Lookup order:**
1. Provider-specific environment variable (e.g., `ANTHROPIC_API_KEY`, `ZHIPUAI_API_KEY`)
2. Generic environment variable (`UNFAMILIAR_API_KEY`)

> **Note:** Config file key storage (`[api_keys]` in `~/.unfamiliar/config.toml`) was removed in MVP development. If you have an older config file with an `[api_keys]` section, it will be ignored.

---

## 4. Data Model

> Domain fields only. The implementation will add id, timestamps, foreign keys, and indexes as appropriate.

### Entities

#### Campaign

The top-level container. **One campaign per codebase** (one-to-one). If the user wants a fresh investigation, they start a new campaign which replaces the old one.

- repo_path — absolute path to the target repository
- schema_version — version of the schema at campaign creation (e.g., "1.0", "1.1"). Used to detect campaigns that may need upgrading
- mode — *(v1.1)* (onboarding | assessment). Determines which missions are required for campaign completion. MVP defaults to onboarding
- character — *(v1.1)* chosen archetype (detective | forensic_analyst | fixer). Determines mission sort order within the mode's pool. MVP uses balanced default order
- status — (initializing | active | closed). MVP simplifies to three states: `initializing` = static analysis + LLM generation in progress, `active` = campaign ready for use, `closed` = campaign complete. *(v1.1 adds `ready` state between initialization and mode/character selection)*
- theme — locked to "film_noir" in v1

#### Briefing

Structured analysis results for a campaign. Source of truth for the analysis — the Markdown "case file" is a rendered view of this data.

- summary — plain-language overview of what the codebase does
- tech_stack — languages, frameworks, tools detected
- security_posture — auth approach, sensitive data flows, input validation, dependency vulnerabilities

#### Module

A logical unit of the codebase identified during analysis. Could be a directory, a package, or a feature area depending on codebase structure. Boundaries are detected programmatically via directory structure and import graph clustering (see Static Analysis section).

- name
- path — directory or file path
- description — what this module does (LLM-generated). In MVP, this also includes entry point and dependency information that becomes structured data in v1.1
- file_count
- category_relevance — which investigation categories this module is relevant to (can be multiple)
- security_relevant — boolean flag

#### Entry Point *(v1.1)*

> **Not in MVP.** Entry points are inferred during analysis but stored as Module descriptions in v1.0. Promoted to a full entity in v1.1 to enable entry point coverage gamification.

A file or location that serves as a "door into" the codebase. Tracked as structured data so progress can be measured against entry point coverage ("You've traced 4 of 7 entry points").

- file_path
- entry_type — (cli | api_route | event_handler | main | scheduled_task)
- description — what this entry point does

#### Dependency *(v1.1)*

> **Not in MVP.** Dependencies are inferred during analysis but stored as Module descriptions in v1.0. Promoted to a full entity in v1.1 to enable dependency coverage gamification.

An external library, service, or API the codebase relies on. Tracked as structured data so missions can be linked to specific dependencies and coverage measured ("You've investigated 6 of 15 external dependencies").

- name
- version_spec — version declared in manifest (nullable, for unversioned services)
- dep_type — (library | service | api | database)
- manifest_source — which file declared it (requirements.txt, package.json, etc.)
- security_relevant — boolean

#### Module-Dependency Link (junction) *(v1.1)*

> **Not in MVP.** Required only when Dependency becomes a full entity in v1.1.

Many-to-many relationship between modules and dependencies. A module can use multiple dependencies, and a dependency can be used across multiple modules.

#### Mission

The atomic unit of investigation. A specific, time-boxed task that teaches the user something about the codebase. **Missions are unique** — completing one counts everywhere it appears.

- title — themed (Film Noir) title
- title_plain — unthemed title for clarity
- description — what to investigate and why
- category — one of the seven investigation categories
- difficulty — (quick | medium | deep_dive). Maps 1:1 to time: quick = 10-15 min, medium = 20-30 min, deep_dive = 30-45 min
- time_estimate_minutes — derived from difficulty tier
- completion_condition — clear statement of when this mission is done
- security_tag — boolean, true if security-relevant
- standard_tag — string, which coding standard this mission evaluates (e.g., "no-invisible-dependencies", "type-safety"). Nullable — not all missions evaluate a standard
- status — (locked | available | in_progress | completed)
- completion_method — (annotation | field_report | self_report | null)
- narrative_intro — themed flavor text for mission start
- narrative_outro — themed summary for mission completion, connecting what was learned to the bigger picture

#### Module-Mission Link (junction)

Many-to-many relationship between modules and missions. A mission can investigate multiple modules (e.g., tracing a request across layers), and a module can be investigated by multiple missions.

- is_primary — boolean, exactly one module per mission is marked primary (used for display and default grouping)

#### Mission File Reference

Links a mission to specific files and line ranges the user should investigate.

- file_path
- line_start — (nullable, for whole-file references)
- line_end — (nullable)
- description — what to look for in this file
- file_hash — hash at time of generation, for staleness detection

#### Mission Chain

A suggested path through a set of missions. Represents a coherent learning sequence within or across categories. Chains **do not own** missions — they reference them.

- name — themed chain name
- name_plain — unthemed name
- description — what this chain teaches overall
- category — primary category (a chain can span categories but has a primary one)
- sort_order — display order within the campaign

#### Chain-Mission Link (junction)

Many-to-many relationship between chains and missions. A mission can appear in multiple chains.

- position — order of this mission within this chain

#### Mission Prerequisite (junction)

Many-to-many self-referential relationship on Mission. Defines what missions must be completed before a mission becomes available.

- prerequisite mission
- dependent mission

#### File Snapshot

Tracks the state of analyzed files. Populated at generation time; used for staleness detection in v1.1. MVP stores the data but does not check it at runtime.

- file_path
- file_hash — content hash at time of analysis
- last_analyzed — when this file was last included in an LLM analysis pass

### Relationships

**MVP (v1.0):**

```
Campaign 1──1 Briefing
Campaign 1──* Module
Campaign 1──* Mission
Campaign 1──* Mission Chain
Campaign 1──* File Snapshot

Mission *──* Mission Chain    (via Chain-Mission Link)
Mission *──* Mission          (via Mission Prerequisite — self-referential)
Mission 1──* Mission File Reference

Module  *──* Mission          (via Module-Mission Link — many-to-many,
                               one module marked primary per mission)
```

**v1.1 additions:**

```
Module   1──* Entry Point
Module   *──* Dependency       (via Module-Dependency Link)
```

### Notes

- **Briefing entity stays lean.** Entry points, dependencies, and module structure are their own entities (in v1.1). In MVP, entry points and dependencies are described within Module descriptions and the Briefing summary — no separate tables. The rendered briefing Markdown pulls from Briefing + Module data at render time.
- **Gamification queries flow through Module.** In v1.1: Entry point coverage = entry points whose module has completed missions with file references matching the entry point's file. Dependency coverage = dependencies linked to modules that have completed missions. In MVP: coverage is module-based only, no entry point or dependency tracking.
- **No user table.** This is single-user per installation. Multi-user would require a User entity linked to Campaign — noted as a future consideration but not designed for v1.
- **Character is a field on Campaign**, not a separate entity. The three archetypes are fixed in v1 and only affect mission ordering, not content.
- **Category is an enum**, not a table. The seven categories are fixed. If they need to become extensible later, promoting to a table is a simple migration.
- **Theme is a field on Campaign**, not a separate entity. Fixed to Film Noir in v1. Extensible themes would require a Theme entity with narrative templates — deferred.

### Forward-Compatible Schema Design

The schema is designed to support non-destructive upgrades between versions:

- **Include future fields in MVP schema** — fields like `mode` and `character` are present in MVP even though they're not exposed in the UI. This avoids ALTER TABLE migrations later
- **New entities are additive** — v1.1 adds Entry Point, Dependency, and Module-Dependency junction as new tables. No existing tables are modified
- **New columns are nullable or have defaults** — any future column additions use NULL or default values so existing rows remain valid
- **`schema_version` tracks campaign age** — on session start, campaigns with older schema versions show a dismissable banner offering new features
- **`unfamiliar upgrade` command** — populates new entities via static analysis (no LLM) without affecting existing mission progress. User opts in per campaign
- **Older campaigns work without upgrading** — they simply don't get new features until the user runs upgrade

---

## 5. Future Features

> These are not in v1 scope. They are documented here to confirm the data model and architecture can support them without structural changes.

### Selectable Themes

Users pick from a set of pre-built themes (Film Noir, post-apocalyptic, steampunk, heist, etc.) or describe a custom theme and let the AI generate narrative language for it. Requires externalizing narrative templates — mission `narrative_intro`/`narrative_outro` would be generated per-theme rather than hardcoded. **Data model supports this:** theme is already a field on Campaign; mission generation pipeline takes theme as input.

### Additional Language Adapters

Community-contributed semantic analyzers for Go, Rust, Java, Ruby, C#, etc. The v1 adapter interface (Python + TypeScript) needs to be well-defined and documented so contributors can add languages without touching core logic. **No data model impact** — Module and File Snapshot are language-agnostic.

### Cross-Codebase Reporting

Career-level stats across all investigations: codebases explored, missions completed, categories mastered, time invested. Requires reading across multiple campaign databases. **Supported by central storage architecture** (`~/.unfamiliar/campaigns/`). No structural change — reporting layer queries multiple SQLite DBs.

### AI Sidekick

During mission execution, the user can ask the AI questions about what they're looking at — explain a function, clarify a pattern, confirm their understanding. **Sidekick persona is themed per investigation category:**

| Category | Sidekick Persona |
|---|---|
| Architecture | The Informant — knows how the territory is laid out |
| Domain & Business Logic | The Client — knows why the case matters and what's at stake |
| Data Flow | The Accountant — follows the money, traces transactions |
| Dependencies | The Fence — knows all the known associates |
| Conventions | The Old-Timer — knows how things work around here |
| Testing | The Lab Tech — examines and interprets the evidence |
| Technical Debt | The Coroner — knows where the bodies are buried |

**No data model impact** — this is a runtime LLM call using current mission, module, and persona as context. Costs tokens per interaction, so should be opt-in.

### Export & Reporting

Generate a summary document of what was learned about the codebase. Could be handed to a team lead as an onboarding artifact, kept as personal reference, or included in handoff documentation. **Data model already supports this** — campaign status, completed missions, briefing data, and category coverage are all queryable.

### User-Controlled Analysis Depth

At campaign start, let the user choose how deeply the LLM analyzes the codebase — a "token budget" slider or tier selection (light / standard / deep). Higher depth sends more files as full content to the LLM, producing richer missions at the cost of more tokens. **No structural change required** — depth lives entirely in the key file selection step. The pipeline, data model, and mission schema are identical regardless of depth level.

### Scoped Investigation Mode

A third campaign mode: "I need to add a feature that touches these modules." The user describes a proposed feature or names specific modules, and the system generates a targeted mission set focused on those modules, their connections, and quality assessment of the affected area. Campaign completion = understanding the targeted scope, not the whole codebase. **Architecture supports this** — modes are already a concept, modules are entities, mission generation is LLM-driven. Adding "generate missions for these specific modules" is a constraint on the existing pipeline. Would require: a scope input step at campaign start, module-aware mission filtering, and scoped completion criteria.

### Web UI

Browser-based frontend with visual card animations, interactive progress maps, and richer reporting than the terminal can provide. Would connect to the same SQLite backend. **Deferred** — CLI-first approach is lighter weight and easier to distribute. Web UI is an enhancement, not a replacement.

### Mission Validation Agent

An optional LLM-powered validation pass that assesses mission quality beyond what programmatic validation can check. For users willing to spend extra tokens for higher-quality missions:

- **Quality assessment:** Are the investigation questions well-formed? Is the difficulty appropriate for the content? Does the narrative match the technical content?
- **Coverage analysis:** Are there gaps in the mission set? Are important files/modules under-represented? Is the prerequisite ordering logical?
- **Hallucination repair:** Attempt to fix missions that reference non-existent files by finding the correct file or regenerating the mission with better context
- **Opt-in via config:** `validation_agent = true` in config.toml, or `--validate` flag at campaign start
- **Runs after generation:** Once all categories are generated, the validation agent reviews the full mission set in one pass
- **No data model impact** — validation results are metadata on the Mission entity (validation_score, validation_notes fields) or campaign-level summary

### Module Boundary Verification

An optional LLM-powered pass that reviews and refines the module boundaries detected by programmatic analysis. For users who want more accurate module groupings:

- **Boundary review:** Assess whether detected modules are over-fragmented (should be merged) or under-segmented (should be split)
- **Confidence scoring:** Add `boundary_confidence` field to Module entity (low/medium/high) based on how certain the detection algorithm is
- **Refinement:** LLM can suggest boundary adjustments based on understanding of the codebase's domain and architecture
- **Opt-in via config:** `boundary_verification = true` in config.toml
- **Runs after static analysis:** Before mission generation, so missions reflect refined boundaries
- **No structural data model changes** — adds optional confidence field to Module, boundary suggestions stored as metadata

### Data Model Validation

All future features were checked against the v1 data model:

| Feature | Structural change needed? |
|---|---|
| Selectable themes | No — theme field exists; generation pipeline parameterized |
| Language adapters | No — entities are language-agnostic |
| Cross-codebase reporting | No — central storage enables multi-DB queries |
| AI sidekick | No — runtime feature, no persistent state required |
| Export & reporting | No — all necessary data already captured |
| User-controlled analysis depth | No — depth lives in file selection step, not data model |
| Scoped investigation mode | No — mode field exists on Campaign; mission generation accepts scope constraints |
| Web UI | No — same SQLite backend, different render layer |
| Mission validation agent | No — optional metadata fields on Mission, no structural changes |
| Module boundary verification | No — optional confidence field on Module, no structural changes |

---

## 6. Business Rules & Validation

> Standard validation (required fields, valid file paths, enum constraints) is assumed. Only domain-specific rules are documented here.

### Campaign Lifecycle

- **Campaign identity is tied to `repo_path`.** If the repo moves or is renamed, the campaign is orphaned. `unfamiliar campaigns` shows orphaned campaigns with a "path not found" warning. `unfamiliar reconnect <campaign> /new/path/to/repo` re-links an orphaned campaign to a new location
- **One campaign per codebase.** If a user runs `unfamiliar investigate` on a repo that already has a campaign:
  1. Warn them that an existing campaign was found
  2. Offer to continue where they left off (with a staleness check on analyzed files)
  3. If they insist on starting fresh, wipe the existing campaign DB and start over. No archiving
- **Mode and character selection are permanent** for the duration of a campaign. Mode determines which missions are required for completion. Character affects mission ordering within the mode's pool. The user can access all missions regardless of either choice
- **Campaign status progresses forward only:** initializing → ready → active → closed. No reverting to earlier states

### Mission Rules

- **Prerequisite system** — hybrid approach with algorithmic skeleton + LLM refinement:
  - **Algorithmic baseline** (language-agnostic, computed by adapters):
    - Entry point missions first (detected per-language)
    - High-centrality modules before leaf modules (import graph)
    - Category ordering: Architecture → Data Flow → Domain & Business Logic; Dependencies and Conventions parallel; Testing and Technical Debt last
  - **LLM can add prerequisites** within same chain, across chains in same category, or across categories — subject to validation rules
  - **Philosophy:** Prerequisites prevent overwhelm, not create obstacles. When in doubt, prefer accessibility over strictness
- **Prerequisite validation rules:**
  - No circular dependencies
  - No prerequisite on non-existent mission ID
  - No prerequisite on mission from failed category (those missions become immediately available)
  - **Max prerequisite depth: 3** — validation rejects chains deeper than 3
  - **Every mission must be reachable** from at least one root mission (zero prerequisites) within its category
  - **Root missions per category** — each category generates at least 1-2 missions with zero prerequisites
- **Prerequisite enforcement is strict.** A mission with unmet prerequisites stays in `locked` status and cannot be started. The UI should show what needs to be completed first
- **User escape hatch:** `unlock <mission>` command forces a mission to available status. Documented as "for when the system gets it wrong"
- **MVP completion method: self-report.** User marks a mission complete. Always available, no LLM call required
- **No skip status.** If a user wants to move past a mission, they mark it complete (self-report). This keeps the prerequisite system simple — completed is the only status that satisfies prerequisites
- **A completed mission counts across all chains.** If mission X appears in chains A and B, completing it in chain A marks it complete in chain B as well
- *(v1.1)* **Two additional completion methods** — user chooses per mission:
  1. **Code annotation** — user adds comments/documentation to the codebase. AI gives lightweight feedback if annotation is misleading or incomplete. This is a service to the team and to AI agents working in the codebase
  2. **Field report** — user answers a targeted question about what they found. AI gives lightweight feedback on completeness. Fallback when code is already well-documented
- *(v1.1)* AI feedback on annotations/reports is lightweight, not blocking. The AI may flag misleading information but does not prevent completion

### Token Economy

- **No LLM calls for mission presentation.** Viewing missions, checking status, tracking progress — all served from local SQLite and Markdown. The LLM is called only at:
  1. Campaign initialization (codebase analysis + briefing + mission generation — all in 1-2 LLM calls)
  2. Campaign completion summary
  3. *(v1.1)* Staleness refresh (targeted, only for changed files)
  4. *(v1.1)* Completion feedback (annotation review or field report evaluation) — opt-in, only when the user chooses annotation or field report over self-report
  5. *(future)* AI sidekick interactions (opt-in)
- **MVP completion is always zero-token.** Self-report is the only completion method; no LLM call on mission complete
- **All generated content is persisted locally.** If the tool can serve a response from the DB or Markdown files, it must not call the LLM
- **Static analysis is always free.** File scanning, AST parsing, import tracing, git operations, and staleness detection never touch the LLM

### Staleness

> **MVP stores file hashes at generation time** (in File Snapshot and Mission File Reference) but does not check or act on them. This is forward-compatible — v1.1 activates staleness detection without schema changes.

- *(v1.1)* Staleness is detected via file content hash, not timestamp. A file is stale if its current hash differs from the stored hash in File Snapshot
- *(v1.1)* Staleness is checked at session start (when the user opens an active campaign), not continuously
- *(v1.1)* Stale missions are flagged, not silently invalidated. The user sees which missions reference changed files and can choose to refresh them (which triggers a targeted LLM call) or proceed anyway

---

## 7. UI/UX

> This section describes the experience, not the implementation. Specific widget choices and layout code belong in the build phase.

### Application Model

Unfamiliar is a **persistent interactive session**, not a series of discrete CLI commands. The user launches the app, enters an investigation, and stays in the session until they're done for the day. The feel is a text-adventure game or TTRPG — you tell it what you're doing, it describes what happens.

**Entry points** (via Typer, before the TUI launches):
- `unfamiliar investigate /path/to/repo` — start a new campaign or resume an existing one
- `unfamiliar campaigns` — list all campaigns with status (orphaned campaigns show "path not found" warning)
- `unfamiliar resume` — resume the most recent active campaign
- `unfamiliar reconnect <campaign> /new/path/to/repo` — re-link an orphaned campaign to a new repo location
- `unfamiliar upgrade` — upgrade an older campaign to the current schema version, enabling new features without losing progress

Once inside, the Textual TUI takes over.

### Main Interface Layout

The persistent TUI has these regions:

- **Header** — campaign name, character, theme, session stats (missions completed today, total progress)
- **Command reference** — visible list of available commands with themed aliases. Always accessible, never hidden
- **Main content area** — where narrative, mission details, briefings, and responses render. Scrollable
- **Command input** — text input at the bottom where the user types commands

### Commands

Commands use a **canonical + alias system.** The canonical command always works. The themed alias is displayed in the UI and also accepted as input.

v1 commands (Film Noir aliases):

| Canonical      | Noir Alias         | What it does                                                         |
| -------------- | ------------------ | -------------------------------------------------------------------- |
| `next`         | `investigate`      | Show available missions, pick one to start                           |
| `complete`     | `file report`      | Complete the current mission (choose method)                         |
| `status`       | `case board`       | Campaign overview — progress, available chains, stats                |
| `briefing`     | `case file`        | Re-read the codebase briefing                                        |
| `mission`      | `lead`             | Show details of the current active mission                           |
| `notebook`     | `case notes`       | *(v1.1)* Print the path to the notebook file                         |
| `unlock`       | `break in`         | Force a locked mission to available (escape hatch for system errors) |
| `help`         | `call in a marker` | Show all commands and what they do                                   |
| `quit`         | `bury the day`     | End the session (campaign persists)                                  |
| `end campaign` | `close the case`   | End the campaign - final reporting, codebase exploration is complete |

### Key Screens

#### First Launch (New Campaign)

1. Codebase analysis runs with a progress indicator (static analysis pass, then LLM pass)
2. Briefing renders in the main content area — plain language, no theme
3. *(v1.1)* Character selection — three options with descriptions, styled as a choice panel. **Explicit note** that character affects mission order only
4. Campaign reveal — initial mission chains appear with themed titles and descriptions
5. Transition to the main investigation loop

#### Session Resume (Existing Campaign)

1. "Welcome back, detective" (themed greeting)
2. Quick recap: where you left off, what's available
3. Straight into the main investigation loop

> *(v1.1 adds staleness warnings on resume: list of changed files and affected missions, option to refresh)*

#### Mission View

When the user selects a mission:
- Themed narrative intro ("A tip came in about the warehouse district...")
- Plain technical instructions: files to look at, line numbers, what to investigate
- Completion condition clearly stated
- Estimated time and difficulty visible
- Field report question shown (if they choose that completion method)

#### Completion View

When the user completes a mission:
- User marks mission complete (self-report)
- Themed narrative outro connecting what was learned to the bigger picture
- Unlock notification if new missions/chains became available
- Updated progress stats

> *(v1.1 adds completion method choice — annotation / field report / self-report — with lightweight AI feedback for annotation and field report)*

#### Case Board (Status)

- Progress by category — seven categories with completion percentage
- Active mission chains with progress indicators
- Total missions completed / available / locked
- Security-tagged mission count and completion

### Theme Architecture

A theme is a **configuration package**, not a code change. Each theme defines:

| Component | What it controls |
|---|---|
| **TCSS stylesheet** | Colors, borders, backgrounds, text styles for every widget |
| **Command aliases** | Themed names for each canonical command |
| **Vocabulary** | What to call missions, chains, the campaign, completion, the notebook, etc. |
| **Narrative tone** | System prompt modifier for LLM-generated mission text |
| **Sidekick personas** | Per-category character names and personalities (future feature) |

Themes are stored as files in the package (e.g., `themes/film_noir/`) and referenced by the `theme` field on Campaign. v1 ships with Film Noir only. Adding a new theme means adding a new directory with these files — no code changes required.

The visual theme (TCSS) is swapped at runtime when a campaign loads.

### Design Principles

- **Clarity over cleverness.** Themed language adds flavor but must never obscure what the user is actually supposed to do. Technical instructions are always plain
- **Information density is low.** One thing at a time in the main content area. No dashboards with 6 panels of data. The user reads, acts, sees the result
- **Progress feels tangible.** Completing a mission should produce a visible change — stats update, new content unlocks, the narrative acknowledges it
- **Session boundaries are clean.** The user can quit at any point and resume exactly where they left off. No lost state, no "you need to finish this mission before quitting"

---

## 8. Non-Functional Requirements

### Performance

- **Static analysis pass** should complete in seconds for typical codebases (<1000 files). It's CPU-bound, no network
- **LLM analysis pass** duration depends on codebase size and model speed. The system should:
  - Estimate time before the LLM pass begins, based on file count and module count from static analysis
  - Warn the user if estimated time exceeds 15 minutes
  - Show a progress bar with per-module or per-step progress during the LLM pass
- **Day-to-day session usage** (mission work, progress tracking, status views) must be instant — all data served from local SQLite and Markdown files. No LLM calls, no network dependency
- **Staleness checks** on session resume should complete in seconds (file hash comparisons against stored snapshots)

### Offline Capability

- Once a campaign is generated, **all mission work is fully offline.** No internet or LLM access required to view missions, complete them, update progress, or use the notebook
- Operations that require the LLM (initial analysis, staleness refresh, campaign summary, field report/annotation feedback) require network access and will fail gracefully with a clear message if offline
- The tool must never silently fail or hang due to network unavailability

### Accessibility

Full accessibility is a project priority. The MVP establishes the architectural foundation; v1.1 delivers the plain text renderer.

- **Architecture enforces presentation separation (MVP):** strict separation between data/logic and presentation layers. Every screen is a data query rendered by whichever mode is active. This separation is load-bearing — it enables plain mode in v1.1 without refactoring
- **Keyboard-only navigation (MVP)** — all TUI functionality accessible without a mouse
- **High contrast and color-blind-safe palettes (MVP)** — each theme includes an accessible color variant. No information conveyed by color alone
- **All generated artifacts are Markdown (MVP)** — briefing, completion summaries are readable in any editor or assistive tool, independent of rendering mode
- *(v1.1)* **`--plain` mode** — plain text output to stdout with no ANSI escape codes, no cursor manipulation, no styling. Fully screen-reader compatible. Activated via `unfamiliar --plain investigate /path/to/repo` or a persistent config setting
- *(v1.1)* Both modes expose identical functionality. Same commands, same data, same campaign state. The only difference is presentation
- *(v1.1)* `--plain` mode also serves non-accessibility uses: piping output to files, running in CI environments, minimal terminal emulators, SSH sessions with limited capabilities

### Token Efficiency

- The system is designed for developers who may have rate-limited or pay-per-token LLM access
- The hybrid analysis strategy (static analysis first, targeted LLM second) minimizes token usage
- A typical campaign requires **8-10 LLM calls minimum** (1 analysis + 7 category-level mission generation + completion summary), plus additional calls for annotation/field report feedback and staleness refresh as needed
- The system must never make an LLM call that the user didn't explicitly or implicitly request

### Portability

- Runs on macOS, Linux, and Windows (any platform that supports Python 3.10+ and a modern terminal emulator)
- No OS-specific dependencies beyond Python stdlib and pip-installable packages
- SQLite requires no external database server

---

## 9. Release Scope

### MVP (v1.0) — Core Investigation Loop

The MVP proves the core loop works: analyze → generate missions → work through them → track progress. Everything below is required for the first usable release.

| Feature | Scope |
|---|---|
| Static analysis pipeline | Python, TypeScript, and JavaScript adapters. Well-documented adapter interface for future languages. LLM fallback for unsupported languages (directory walking + raw file analysis with user notification) |
| Security analysis | Hardcoded secret detection, dependency CVE scanning, security posture summary in briefing. Security-relevant missions tagged across all categories |
| LLM integration | Chunked analysis: 1 briefing call + 7 category-level mission generation calls. Built-in universal coding standards (no user-customizable standards directory yet) |
| Mission system | Chains with prerequisites. Self-report completion only. Progress tracking per category |
| Campaign lifecycle | Create, persist, resume, upgrade. SQLite + Markdown artifacts. One campaign per codebase. Forward-compatible schema |
| TUI | Textual app with persistent session. Canonical commands with Film Noir themed aliases. Film Noir theme applied to narrative text and TCSS styling |
| Data model | Campaign, Briefing, Module, Mission, Mission Chain, Chain-Mission Link, Mission Prerequisite, Mission File Reference, File Snapshot. Module-Mission many-to-many with primary flag |

### v1.1 — Depth & Personalization

These features layer onto the working MVP. Each is additive — none changes the foundation.

| Feature | What it adds |
|---|---|
| Mode selection (onboarding/assessment) | Filters which missions are required for campaign completion. MVP runs onboarding mode only |
| Character selection | Sorts mission presentation order by specialty track (60/40 weighting). MVP uses balanced default order |
| Annotation & field report completion | Two additional completion methods with LLM feedback. Requires LLM feedback subsystem |
| Staleness detection | File hash comparison on session resume, stale mission flagging, targeted LLM refresh |
| TypeScript/JavaScript adapters | Additional language support using the adapter interface built in MVP |
| User-customizable standards | `~/.unfamiliar/standards/` directory with universal and per-language overrides |
| Entry Point & Dependency entities | Promoted from Module descriptions to full entities with Module-Dependency junction. Enables entry point coverage and dependency coverage gamification |
| Notebook | `notebook.md` creation in campaign directory with default headings. System references notebook entries in mission context (passive — no active parsing) |
| Plain mode (`--plain`) | Screen-reader-compatible plain text output. Same commands and data, no ANSI/TUI |
| `reconnect` command | Re-link orphaned campaigns when repo path changes |
| ~~Command alias system~~ | ~~Themed aliases alongside canonical commands~~ — moved to MVP |
| ~~TypeScript/JavaScript adapters~~ | ~~Additional language support using the adapter interface built in MVP~~ — moved to MVP |
| Mutation testing analysis | Auto-detect mutation reports (mutmut). "Kill the mutant" missions for weak tests. Requires user to have mutation testing configured |

### Out of Scope (all versions of v1)

These are explicitly **not included in any v1.x release.** Several are planned for future versions (see Section 5). Listing them here to prevent scope creep during the build.

#### Deferred to Future Versions

- **Themes beyond Film Noir** — architecture supports selectable themes; v1 ships with one. Adding themes is configuration, not code
- **AI sidekick** — architecture supports it; not in v1. No LLM calls during mission execution
- **Language adapters beyond Python, TypeScript, and JavaScript** — all three ship in MVP. Adapter interface documented for community contributions of additional languages
- **Cross-codebase reporting** — career-level stats across campaigns. Central storage architecture supports this; reporting layer is deferred
- **Natural language command input** — commands are keywords in v1. Natural language parsing (via LLM) is a future enhancement once the sidekick exists
- **Web UI** — browser-based frontend with visual animations. Same backend, different renderer. Deferred — Textual TUI is the v1 experience
- **Custom user-described themes** — "give me a mashup of 1950s sci-fi and Atlantis." Requires LLM-generated theme packages. Deferred
- **Active notebook parsing** — system reading the notebook to inform mission suggestions. v1 notebook is passive
- **Scoped investigation mode** — feature-targeted campaigns. Requires scope input, module-aware filtering, scoped completion criteria
- **User-controlled analysis depth** — token budget selection at campaign start

### Version Compatibility

- **Upgrades are non-destructive** — v1.1 adds new tables and features without modifying existing campaign data
- **Forward-compatible schema** — MVP includes fields for v1.1 features (mode, character) even though they're not exposed
- **`unfamiliar upgrade` command** — populates new entities for older campaigns via static analysis. No LLM calls, no mission regeneration, no loss of progress
- **Older campaigns remain functional** — users can delay upgrading indefinitely; campaigns work, just without new features
- **Upgrade notification** — dismissable banner on session start when opening a campaign with an older schema version

#### Ruled Out

- **Team/multiplayer mode** — this tool serves individual developer understanding. Adding competition or collaboration doesn't serve that purpose
- **Subscription-based monetization** — usage pattern (2-3 codebases per job) doesn't support recurring billing. Future monetization, if any, would be per-codebase or one-time
- **Code modification or auto-fixing** — the tool directs investigation, it does not change code. Code annotations are the user's voluntary choice during mission completion
- **Editor/IDE plugins** — the tool is a standalone terminal application. IDE integration (VS Code extension, JetBrains plugin) is not planned for v1 or near-term future
- **Hosted/cloud version** — the tool runs locally on the user's machine. No SaaS, no server, no account required

---

## 10. Coverage Confirmation

### Summary of Decisions

| Section | Key Decisions |
|---|---|
| Problem & Purpose | Codebase investigation tool for developers with ADHD/gamification affinity. Two modes: onboarding (learn a new codebase) and assessment (audit a familiar one). Campaign-based with a win state |
| User Stories | 6 MVP stories: briefing, campaign reveal, mission execution, progress tracking, campaign completion. Notebook deferred to v1.1. Mode & character selection already scoped to v1.1 |
| Tech Stack | Python 3.10+, LangGraph/LangChain, Textual + Rich TUI, SQLite + Markdown, Tree-sitter, Typer. Model-agnostic LLM integration. Python, TypeScript, and JavaScript adapters |
| Data Model | Campaign (1:1 with codebase), Briefing, Module, Entry Point, Dependency, Mission, Mission Chain (many-to-many with Mission), Module-Mission (many-to-many), File Snapshot. Mode, character, and theme are fields, not entities |
| Future Features | Selectable themes, AI sidekick with per-category personas, language adapters, cross-codebase reporting, scoped investigation mode, export, web UI. All validated against v1 data model |
| Business Rules | One campaign per codebase, mode and character are permanent. **Prerequisites: hybrid algorithmic + LLM, max depth 3, unlock escape hatch**. Self-report completion only (annotation/field report v1.1), no LLM calls for mission presentation or completion, staleness hashes stored but not checked (v1.1 activates) |
| UI/UX | Persistent Textual TUI session, command alias system (canonical + themed), Film Noir v1 theme, theme architecture supports future themes via config packages |
| Non-Functional | Offline mission work, architectural separation of data/logic from presentation (enables v1.1 `--plain` mode), token-efficient hybrid analysis, cross-platform portability |
| Release Scope | MVP = core loop (Python/TS/JS adapters, self-report completion, onboarding mode, Film Noir TUI with command aliases, forward-compatible schema, presentation-separated architecture). v1.1 = modes, characters, annotation/field report completion, staleness detection, notebook, plain mode renderer, user standards |
| Out of Scope | Team mode, subscription monetization, code modification, IDE plugins, hosted/cloud version. Non-destructive upgrades via `unfamiliar upgrade` command |

### Investigation Categories

| Category | Focus |
|---|---|
| Architecture | Module structure, entry points, component connections |
| Domain & Business Logic | Core workflows, business rules, what the app does and why, failure modes |
| Data Flow | Schema, state, data movement through the system |
| Dependencies | External services, APIs, key libraries, boundaries, configuration |
| Conventions | Patterns, idioms, error handling, naming |
| Testing | Coverage, quality, untested paths |
| Technical Debt | Code smells, violations, structural risks |

**Cross-cutting:** Security is not a category but a tag applied across all seven. Missions in any category can be flagged security-relevant when they touch auth flows, data boundaries, input validation, sensitive data handling, or dependency vulnerabilities.

### Open Questions

- **Notebook integration depth (deferred):** Active parsing of the notebook to inform mission suggestions. v1 starts passive

---

> Your requirements doc is at `_planning/requirements.md`. Take a look and make any edits you want before running `/plan:init`. You don't need to finalize everything — you can always revisit with `/plan:interrogate` before starting a phase.
