# Knowledge model

DevWorkspace stores **knowledge**, not code: concise statements about the project, each with provenance. Stored facts are a cache of evidence, never a replacement for it.

## Authority

```text
USER DECISIONS
   ↓
CURRENT REPOSITORY EVIDENCE   (what the code says right now)
   ↓
VERIFIED DEVWORKSPACE FACTS
   ↓
AI-DERIVED FINDINGS
   ↓
OLD SESSION INFORMATION
```

Enforced in `knowledge/facts.ts`: a lower-authority write never silently replaces a higher-authority fact (`CONFLICT` error with a hint), except when the existing fact is already `STALE`. Deterministic detection (rank 4) may replace an AI-verified fact (rank 3) because it reflects the repository *now*. User decisions (rank 5) are never replaced by an agent and are never auto-staled; if their sources change they are flagged *for human review*.

## A fact

```json
{
  "key": "auth.session-store",
  "value": "Sessions are stored in Redis",
  "source": "src/auth/session.ts",
  "sourceType": "ai",
  "sources": ["src/auth/session.ts"],
  "sourceHashes": { "src/auth/session.ts": "sha256…" },
  "confidence": "HIGH",
  "status": "VERIFIED",
  "createdAt": "…", "updatedAt": "…", "lastVerifiedAt": "…"
}
```

- **status:** `VERIFIED`, `DETECTED`, `INFERRED`, `USER_DECISION`, `UNKNOWN`, `STALE`
- **confidence:** `HIGH`, `MEDIUM`, `LOW`
- **sourceType:** `detector`, `file`, `git`, `user`, `ai`

Uncertainty is first-class: record `INFERRED`/`LOW` or `UNKNOWN` rather than guessing.

## Staleness

Each fact lists the repository files that evidence it and stores their SHA-256 at the time of recording. `devworkspace refresh` re-hashes those sources: a changed or removed source marks the fact `STALE` with a reason. Only stale facts are handed to the agent in the refresh prompt (incremental, not a full re-analysis). The agent re-checks and runs `devworkspace fact verify <key>` (re-hash, mark verified), corrects the fact, or removes it. Facts without sources cannot be proven stale, so cite files.

Generated files are not evidence by themselves: re-running `analyze` rewrites `.devworkspace/analysis/*`, which must not invalidate unrelated facts. A fact may cite a section of the discovery report as `.devworkspace/analysis/discovery.json#ci` (fingerprint of that section only), and a bare `discovery.json` citation is narrowed to the section named by the fact's key (`ci.none` depends on `ci`). Any other generated file is ignored. `status`, `refresh --dry-run` and `doctor` all use the same read-only check, so they agree, and each stale fact says which evidence changed. A fact recorded before a dependency was tracked adopts its current fingerprint instead of going stale.

Content hashing is deliberately conservative: *any* byte change to a cited file triggers re-validation. It over-reports rather than silently trusting old context.

Deterministic (`detector`) facts are simply re-derived on every `analyze`/`refresh`; ones that no longer apply are removed (they are derived data and come back if the evidence returns), so they never produce a warning nobody can clear.

## What to store / not store

Store: architecture, business rules, important modules, conventions, commands, test strategy, deployment facts, integrations, decisions, known constraints, important unresolved problems.

Never store: source files, `node_modules`/generated output, chat transcripts, temporary logs, secrets or env values, machine-specific absolute paths. The CLI enforces the last two (secret patterns and absolute paths are rejected) and `doctor` re-checks.

## Other records

- **Decisions** (`decisions/0001-title.md`): human-readable Markdown with front matter; append-only. Superseding marks the old decision `superseded` and keeps its text.
- **Tasks** (`tasks/…`): see [testing.md](testing.md) and [routing.md](routing.md).
- **Sessions**: goal, work completed, areas, tests run, decisions, remaining issues, next step. Never a transcript.
- **Context documents** (`context/*.md`): `architecture.md`, `conventions.md`, `testing.md`, `integrations.md` are written by the agent during onboarding and kept short.

## Progressive loading

The generated instructions tell the agent to load context in levels and stop at the shallowest one that answers the request: (1) instructions → (2) `devworkspace context --topic …` → (3) relevant decisions → (4) Graphify → (5) specific source files → (6) tests/implementation. "Where is customer uniqueness checked?" stops at level 4–5; "Refactor the customer validation architecture" goes to level 6.

### Task-aware context (`context --for`)

`devworkspace context --for "<request>"` classifies the request (same classifier as `task new`) and prints only what it needs, each item with the reason it is included:

- facts whose key, value or source match the request's keywords, plus type groups (stack and conventions for implementation tasks; known issues for bugs; authorization and tenant rules for security);
- checks of the package the request names, or of the packages with uncommitted code changes, otherwise all checks; none for questions and documentation;
- decisions by title and file (never their text) and context documents by name (never embedded);
- the safety rules, always, and the list of commands DevWorkspace will not run by itself whenever their checks are included.

Detector-derived facts whose value equals another selected fact's are folded into it in the output, and very long detector values are clipped with a pointer to `context --topic <key>`. Human- and AI-authored facts are never folded or clipped, and nothing is removed from `facts.json`. Output is deterministic. Plain `context` is unchanged.

Routing note (0.3.0): requests naming cross-tenant access, tenant isolation, CSRF/XSS, SQL injection, IDOR, CVEs or privilege escalation are classified SECURITY even when they begin with "fix" (they were BUG), so the exploit-test and review gates apply.

### Discovery cache

`analyze` and `refresh` reuse the previous detection result from `.devworkspace/local/cache/discovery.json` (git-ignored, never exported) only when the scan result, the content of every manifest detection reads, the project name, the scan limit and the DevWorkspace version are identical. The directory scan and the Git query always run; the cache is a shortcut for recomputation, never evidence. `--dry-run`, `status`, `doctor` and `context` never write it. Delete the `local/cache` folder at any time.
