From bbeee18b687471c32c2e952788fba9204bb22367 Mon Sep 17 00:00:00 2001 From: jordan Date: Fri, 6 Feb 2026 23:35:41 -0700 Subject: [PATCH] feat: Institutional knowledge vision + roadmap phases 11-15 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Vision Update - Shift from "code-level truth linter" to "self-learning institutional knowledge" - Evidence-based authority model: merit over titles - ProductSpec → 0.95 authority, 1 usage to graduate - Standard (RFC) → 0.85 authority, 3 usages - Research (ADR) → 0.70 authority, 5 usages - Commit only → 0.40 authority, 10 usages - Three-tier knowledge: Policies → Conventions → Observations - Knowledge compounds with every commit ## Gap Analysis - Documented missing features for enterprise pilot - Phases 11-15 spec with implementation details - Evidence detection, scope hierarchy, lifecycle management ## Roadmap Additions - Phase 11: Evidence-Based Authority (🎯 current) - Phase 12: Knowledge Scope Hierarchy - Phase 13: Knowledge Lifecycle Management - Phase 14: Governance Workflows - Phase 15: Evidence Source Integration ## Enterprise Simulation UAT - 6-month simulation: 3 teams, 19 contributors - Month-by-month scenarios with expected outcomes - Success metrics for 90-day and 180-day milestones Co-Authored-By: Claude Opus 4.5 --- .../gap-analysis-institutional-knowledge.md | 627 ++++++++++++++ applications/aphoria/feature.md | 75 -- applications/aphoria/roadmap.md | 360 ++++++++ .../aphoria/uat/enterprise-simulation-uat.md | 796 ++++++++++++++++++ applications/aphoria/vision.md | 373 ++++++-- 5 files changed, 2093 insertions(+), 138 deletions(-) create mode 100644 applications/aphoria/docs/gap-analysis-institutional-knowledge.md delete mode 100644 applications/aphoria/feature.md create mode 100644 applications/aphoria/uat/enterprise-simulation-uat.md diff --git a/applications/aphoria/docs/gap-analysis-institutional-knowledge.md b/applications/aphoria/docs/gap-analysis-institutional-knowledge.md new file mode 100644 index 0000000..296696e --- /dev/null +++ b/applications/aphoria/docs/gap-analysis-institutional-knowledge.md @@ -0,0 +1,627 @@ +# Gap Analysis: Institutional Knowledge Vision + +**Date:** 2026-02-06 +**Status:** Roadmap Planning +**Vision:** Self-learning institutional knowledge that compounds with every commit + +--- + +## Executive Summary + +Aphoria has **strong foundations** for pattern discovery and learning (Phases 7-9), but **critical gaps** exist for the institutional knowledge vision. The missing components center on **authority, governance, scoping, and lifecycle management**. + +### Current State vs. Vision + +| Capability | Current State | Vision State | Gap | +|------------|---------------|--------------|-----| +| Pattern discovery | ✅ Strong | ✅ Strong | None | +| Security scanning | ✅ 24 extractors | ✅ Comprehensive | None | +| Learning/promotion | ✅ Shadow mode works | ✅ Works | None | +| **Authority model** | ❌ Binary (human/auto) | Evidence-based (merit, not titles) | **CRITICAL** | +| **Scope hierarchy** | ❌ Flat team_id | Org → Team → Project | **CRITICAL** | +| **Knowledge lifecycle** | ❌ No deprecation | Active/Deprecated/Superseded | **CRITICAL** | +| **Governance** | ❌ Manual or 0.95 threshold | Evidence-aware approval | **HIGH** | +| **External integration** | ❌ None | ADR/Spec/Standard linking | **HIGH** | + +--- + +## Phase 10: Evidence-Based Authority Model (CRITICAL) + +**Problem:** All patterns treated equally. A random commit carries same weight as a pattern backed by RFC research and product specs. + +**Principle:** Authority comes from **evidence**, not titles. We go by merit. + +**Required Components:** + +### 10.1 Evidence Levels + +```rust +pub enum EvidenceLevel { + /// Just a commit, no supporting context + Commit, + /// Commit + research, ADR, or documentation + Research, + /// Pattern references RFC, OWASP, or external standard + Standard, + /// Pattern linked to product spec, task file, or explicit decision + ProductSpec, +} + +impl EvidenceLevel { + pub fn authority_weight(&self) -> f32 { + match self { + EvidenceLevel::Commit => 0.40, + EvidenceLevel::Research => 0.70, + EvidenceLevel::Standard => 0.85, + EvidenceLevel::ProductSpec => 0.95, + } + } +} +``` + +### 10.2 Evidence Detection + +```rust +pub struct PatternEvidence { + pub level: EvidenceLevel, + pub sources: Vec, +} + +pub enum EvidenceSource { + /// Just the commit itself + Commit { hash: String, author: String }, + + /// ADR or documentation in repo + Adr { path: String, title: String }, + + /// Research notes or investigation + Research { path: String, summary: String }, + + /// External standard reference + Standard { + standard_type: StandardType, // RFC, OWASP, NIST, Vendor + reference: String, // e.g., "RFC 7519 Section 4.1.3" + }, + + /// Product spec or task file + ProductSpec { + path: String, // e.g., "specs/auth-flow.md" + requirement_id: Option, // e.g., "REQ-AUTH-001" + }, +} + +pub enum StandardType { + Rfc, + Owasp, + Nist, + Vendor, + Internal, // Internal policy document +} +``` + +### 10.3 Evidence Detection Logic + +```rust +impl PatternEvidence { + pub fn detect(commit: &Commit, pattern: &Pattern) -> Self { + let mut sources = vec![EvidenceSource::Commit { + hash: commit.hash.clone(), + author: commit.author.clone(), + }]; + + // Check commit message for RFC/standard references + if let Some(std) = extract_standard_reference(&commit.message) { + sources.push(EvidenceSource::Standard { + standard_type: std.std_type, + reference: std.reference, + }); + } + + // Check for linked ADR in same commit + if let Some(adr) = find_linked_adr(commit) { + sources.push(EvidenceSource::Adr { + path: adr.path, + title: adr.title, + }); + } + + // Check for product spec reference + if let Some(spec) = find_linked_spec(commit) { + sources.push(EvidenceSource::ProductSpec { + path: spec.path, + requirement_id: spec.requirement_id, + }); + } + + let level = sources.iter() + .map(|s| s.evidence_level()) + .max() + .unwrap_or(EvidenceLevel::Commit); + + Self { level, sources } + } +} +``` + +### 10.4 Graduation by Evidence + +| Evidence Level | Usages for Convention | Usages for Org Policy | +|----------------|----------------------|----------------------| +| ProductSpec | 1 | 3 (multi-team) | +| Standard | 3 | 5 (multi-team) | +| Research | 5 | 10 (multi-team) | +| Commit | 10 | 25 (multi-team) | + +**A single product spec reference can graduate a pattern immediately.** + +### 10.5 Display with Evidence + +```bash +$ aphoria patterns show "api-versioning" + +Pattern: API Versioning (/api/v{major}/{resource}) +Authority: 0.95 (ProductSpec) +Evidence: + • specs/api-design.md → REQ-API-001 + • ADR-042: API Versioning Strategy + • RFC 7231: HTTP Semantics + +Usages: 25 across 3 teams +Status: Org Convention +``` + +### 10.6 Files to Create/Modify + +| File | Change | +|------|--------| +| `src/evidence/mod.rs` | New module | +| `src/evidence/levels.rs` | EvidenceLevel enum | +| `src/evidence/sources.rs` | EvidenceSource types | +| `src/evidence/detection.rs` | Auto-detection from commits | +| `src/learning/types.rs` | Add evidence to LearnedPattern | +| `src/promotion/pipeline.rs` | Evidence-aware graduation | +| `src/handlers/patterns.rs` | Include evidence in responses | + +--- + +## Phase 11: Knowledge Scope Hierarchy (CRITICAL) + +**Problem:** All knowledge exists at one flat level. No way to say "this applies org-wide" vs "this is just our team's preference." + +**Required Components:** + +### 11.1 Scope Levels + +```rust +pub enum ScopeLevel { + Organization, // Applies to all teams + Team, // Applies to team's projects + Project, // Single project only +} + +pub struct ScopedKnowledge { + pub scope_level: ScopeLevel, + pub scope_id: String, // org_id, team_id, or project_id + pub knowledge: Knowledge, + pub inherited_from: Option>, +} +``` + +### 11.2 Scope Inheritance + +``` +Organization: "TLS 1.3 required" (BLOCK) + └── Team A: (inherits automatically) + └── Team B: "TLS 1.2 allowed for legacy" (OVERRIDE with justification) + └── Project B1: (inherits Team B override) + └── Project B2: (inherits Team B override) +``` + +**Default behavior:** +- Security policies (TLS, auth, secrets): Auto-apply org → team → project +- Conventions (API patterns, error formats): Auto-apply, teams can override with justification +- Observations: Never inherited, team-specific only + +**Resolution rules:** +1. Project-level override wins (if exists with justification) +2. Else team-level (if exists) +3. Else org-level +4. Else external authority (RFC/OWASP) + +**Override requirements:** +- Must provide justification +- Must link to evidence (spec, ADR, or ticket) +- Auditable in SOC 2 reports + +### 11.3 Scope Configuration + +```toml +# .aphoria.toml +[scope] +organization = "acme" +team = "platform" +project = "payment-service" + +[scope.inheritance] +inherit_org = true +inherit_team = true +allow_project_overrides = true # false = strict mode +``` + +### 11.4 Cross-Scope Queries + +```bash +# What patterns does the org enforce? +aphoria patterns --scope org + +# What has my team added on top? +aphoria patterns --scope team --exclude-inherited + +# What's unique to this project? +aphoria patterns --scope project --only-local +``` + +### 11.5 Files to Create/Modify + +| File | Change | +|------|--------| +| `src/scope/mod.rs` | New module | +| `src/scope/levels.rs` | ScopeLevel enum and hierarchy | +| `src/scope/resolution.rs` | Inheritance resolution | +| `src/config/types/scope.rs` | ScopeConfig | +| `src/episteme/local/queries.rs` | Scope-aware queries | +| `src/handlers/patterns.rs` | --scope flag handling | + +--- + +## Phase 12: Knowledge Lifecycle Management (CRITICAL) + +**Problem:** Knowledge exists forever. No way to deprecate patterns or track evolution. + +**Required Components:** + +### 12.1 Knowledge Status + +```rust +pub enum KnowledgeStatus { + Active, + Deprecated { + deprecated_at: u64, + reason: String, + superseded_by: Option, + }, + Archived { + archived_at: u64, + reason: String, + }, +} + +pub struct KnowledgeLifecycle { + pub knowledge_id: String, + pub current_status: KnowledgeStatus, + pub status_history: Vec, + pub expires_at: Option, +} +``` + +### 12.2 Deprecation Flow + +```bash +# Mark pattern as deprecated +aphoria deprecate "use-requests-lib" \ + --reason "Migrating to httpx for async" \ + --superseded-by "use-httpx-lib" \ + --sunset-date 2026-06-01 + +# What happens on scan: +# Old pattern usage → FLAG with migration guidance +# New pattern usage → No flag +``` + +### 12.3 Knowledge Versioning + +```rust +pub struct KnowledgeVersion { + pub version: u32, + pub content_hash: String, // BLAKE3 of knowledge content + pub created_at: u64, + pub created_by: String, + pub changelog: String, +} +``` + +**Use cases:** +- "When did this pattern change?" +- "What was the previous version?" +- "Who made the last update?" + +### 12.4 Expiry and Refresh + +```rust +pub struct KnowledgeExpiry { + pub expires_at: u64, + pub reminder_at: u64, // 30 days before expiry + pub auto_archive: bool, // Archive on expiry? + pub requires_revalidation: bool, // Must be re-approved? +} +``` + +**Use cases:** +- Temporary exceptions expire automatically +- Annual security review required for certain patterns +- Stale knowledge gets flagged for review + +### 12.5 Files to Create/Modify + +| File | Change | +|------|--------| +| `src/lifecycle/mod.rs` | New module | +| `src/lifecycle/status.rs` | Status enum and transitions | +| `src/lifecycle/versioning.rs` | Version tracking | +| `src/lifecycle/expiry.rs` | Expiry and refresh logic | +| `src/handlers/deprecate.rs` | Deprecation command handler | +| `src/cli.rs` | Add `deprecate` command | + +--- + +## Phase 13: Governance Workflows (HIGH) + +**Problem:** Governance is binary: manual review or >0.95 auto-promote. No approval workflows, SLAs, or role-based gates. + +**Required Components:** + +### 13.1 Approval Workflow Definition + +```rust +pub struct ApprovalWorkflow { + pub name: String, + pub applies_to: WorkflowScope, + pub stages: Vec, + pub timeout: Duration, + pub escalation: EscalationPolicy, +} + +pub struct ApprovalStage { + pub name: String, + pub required_approvers: u32, + pub approver_roles: Vec, + pub auto_approve_threshold: Option, +} +``` + +**Example:** +```toml +[[governance.workflows]] +name = "pattern-promotion" +applies_to = "conventions" + +[[governance.workflows.stages]] +name = "team-review" +required_approvers = 1 +approver_roles = ["SeniorEngineer", "Architect"] +auto_approve_threshold = 0.95 + +[[governance.workflows.stages]] +name = "security-review" +required_approvers = 1 +approver_roles = ["SecurityReviewer"] +# No auto-approve for security-sensitive patterns +``` + +### 13.2 Approval State Machine + +``` +PENDING → STAGE_1_PENDING → STAGE_1_APPROVED → STAGE_2_PENDING → APPROVED + ↓ ↓ ↓ + REJECTED REJECTED REJECTED + ↓ ↓ ↓ + ARCHIVED ARCHIVED ARCHIVED +``` + +### 13.3 Approval CLI + +```bash +# List pending approvals +aphoria governance pending + +# Approve a pattern promotion +aphoria governance approve --comment "LGTM" + +# Reject with reason +aphoria governance reject --reason "Too specific to one project" + +# Escalate to next stage +aphoria governance escalate +``` + +### 13.4 Files to Create/Modify + +| File | Change | +|------|--------| +| `src/governance/mod.rs` | New module | +| `src/governance/workflow.rs` | Workflow definitions | +| `src/governance/approval.rs` | Approval state machine | +| `src/governance/store.rs` | Persistence | +| `src/handlers/governance.rs` | CLI handlers | +| `src/cli.rs` | Add `governance` subcommand | + +--- + +## Phase 14: Evidence Source Integration (HIGH) + +**Problem:** Evidence sources (ADRs, specs, standards) aren't automatically linked. Developers must manually reference them. + +**Required Components:** + +### 14.1 ADR Auto-Detection + +```rust +pub struct AdrDetector { + pub patterns: Vec, // e.g., ["docs/adr/*.md", "adr/*.md", "decisions/*.md"] +} + +impl AdrDetector { + pub fn find_linked_adr(&self, commit: &Commit) -> Option { + // Check commit message for ADR-XXX pattern + // Check modified files for ADR documents + // Parse ADR content for related patterns + } +} +``` + +### 14.2 Spec File Detection + +```rust +pub struct SpecDetector { + pub patterns: Vec, // e.g., ["specs/*.md", "*.spec.md", "requirements/*.md"] +} + +impl SpecDetector { + pub fn find_linked_spec(&self, commit: &Commit) -> Option { + // Check for spec file modifications in same commit + // Parse spec for requirement IDs (REQ-XXX) + // Link pattern to requirement + } +} +``` + +### 14.3 Standard Reference Extraction + +```rust +pub fn extract_standard_reference(text: &str) -> Option { + // Match patterns like: + // - "RFC 7519" → Standard(Rfc, "7519") + // - "OWASP A03:2021" → Standard(Owasp, "A03:2021") + // - "NIST SP 800-53" → Standard(Nist, "SP 800-53") +} +``` + +### 14.4 Evidence Display + +```bash +$ aphoria patterns show "api-versioning" + +Pattern: API Versioning (/api/v{major}/{resource}) +Status: Active (Convention) +Scope: Team (Platform) +Authority: 0.95 (ProductSpec) + +Evidence Chain: + 1. ProductSpec: specs/api-design.md → REQ-API-001 + 2. Research: docs/adr/ADR-042-api-versioning.md + 3. Standard: RFC 7231 Section 5.1 + +First seen: 2024-03-15 in payment-service +Usages: 25 across 3 teams +Adoption: 89% of team projects (8/9) +``` + +### 14.5 Files to Create/Modify + +| File | Change | +|------|--------| +| `src/attribution/mod.rs` | New module | +| `src/attribution/git.rs` | Git extraction | +| `src/attribution/directory.rs` | LDAP/SSO integration | +| `src/attribution/display.rs` | Human-readable output | +| `src/handlers/patterns.rs` | Include attribution | + +--- + +## Phase 15: External Knowledge Integration (MEDIUM) + +**Problem:** Internal documentation (ADRs, Confluence) not integrated. Teams maintain knowledge in two places. + +**Required Components:** + +### 15.1 ADR Importer + +```bash +# Import ADRs as authoritative sources +aphoria import adr ./docs/adr/ + +# ADR-042: API Versioning +# Status: Accepted +# → Imports as Tier 1 policy for the project +``` + +### 15.2 Confluence Connector (Future) + +```toml +[integration.confluence] +url = "https://acme.atlassian.net/wiki" +space = "PLATFORM" +label = "aphoria-policy" # Only import pages with this label +``` + +### 15.3 Jira Integration (Future) + +```toml +[integration.jira] +url = "https://acme.atlassian.net" +project = "PLAT" +conflict_link = true # Link conflicts to Jira issues +``` + +### 15.4 Files to Create/Modify + +| File | Change | +|------|--------| +| `src/integration/mod.rs` | New module | +| `src/integration/adr.rs` | ADR parser | +| `src/integration/confluence.rs` | Confluence API client | +| `src/integration/jira.rs` | Jira API client | +| `src/handlers/import.rs` | Import command handlers | + +--- + +## Implementation Priority + +### Must Have for Enterprise Pilot (Phases 10-12) + +| Phase | Feature | Effort | Why Critical | +|-------|---------|--------|--------------| +| **10** | Evidence-based authority | 2 weeks | "Why trust this pattern?" - merit, not titles | +| **11** | Scope hierarchy | 2 weeks | "Does this apply to my team?" | +| **12** | Knowledge lifecycle | 1 week | "Is this still current?" | + +### Should Have for Production (Phases 13-15) + +| Phase | Feature | Effort | Why Important | +|-------|---------|--------|---------------| +| **13** | Governance workflows | 2 weeks | SOC 2 compliance | +| **14** | Evidence source integration | 1 week | Auto-detect ADRs, specs, standards | +| **15** | External integration | 2 weeks | Confluence, Jira linking | + +--- + +## Success Metrics + +### Enterprise Pilot (90 days) + +| Metric | Target | Measurement | +|--------|--------|-------------| +| Patterns captured | 100+ observations | Count in knowledge graph | +| Patterns promoted | 10+ conventions | Count with status=Active | +| Cross-team adoption | 2+ teams connected | Unique team_ids | +| New hire guidance | 5+ accepted suggestions | Accept rate tracking | +| False positive rate | <10% | FP feedback / total flags | + +### Production Ready (180 days) + +| Metric | Target | Measurement | +|--------|--------|-------------| +| Knowledge retention | 0 lost patterns on departures | Audit log | +| Onboarding velocity | 50% faster ramp | Time to first PR | +| Convention adoption | 80% across org | Compliance rate | +| SOC 2 evidence | Audit pass | External validation | + +--- + +## Next Steps + +1. **Finalize Phase 10-12 specs** - Detailed API design +2. **Create enterprise simulation UAT** - Multi-month scenario +3. **Build Phase 10** - Authority model is foundational +4. **Pilot with internal team** - Eat our own dog food +5. **External pilot** - First enterprise customer diff --git a/applications/aphoria/feature.md b/applications/aphoria/feature.md deleted file mode 100644 index 3d0a6ec..0000000 --- a/applications/aphoria/feature.md +++ /dev/null @@ -1,75 +0,0 @@ -# Feature: Dynamic Application Policy - -**Codify your team's decisions as authoritative truth.** - -## The Problem: "It Depends" - -Global standards (RFCs, OWASP) are binary: TLS verification is mandatory; SQL injection is forbidden. - -But most engineering decisions are contextual: -- "This legacy service *must* use TLS 1.2 because clients are old." -- "All services in the `payment` namespace *must* have audit logging enabled." -- "The connection pool *must* be capped at 50 to prevent DB saturation." - -Standard linters can't enforce these because they lack context. They see `min_version = "1.2"` as valid syntax. They don't know that for *this specific app*, it's a critical policy violation (if the policy was 1.3) or a mandatory requirement (if the policy is 1.2). - -## The Solution: Policy as Data - -Aphoria allows you to define a **Local Policy Corpus**. This file lives in your repo (`aphoria-policy.yaml`) and defines the authoritative truths for *this specific project*. - -When Aphoria scans, it treats these rules as **Tier 0 (Regulatory)** — effectively overriding conflicting advice from vendors or general best practices. - -### Example: `aphoria-policy.yaml` - -```yaml -rules: - # 1. Override a Vendor Default - # Vendor says: "Default pool size is 100" (Tier 2) - # Policy says: "We limit to 50" (Tier 0) - - path: "code://rust/citadeldb/db/pool_size" - predicate: "config_value" - value: 50 - tier: "Regulatory" - message: "Internal policy: max 50 connections to prevent potential storms." - - # 2. Enforce a Legacy Constraint - # RFC says: "TLS 1.3 is SHOULD" - # Policy says: "TLS 1.2 is MUST for legacy support" - - path: "code://go/legacy-service/tls/version" - predicate: "min_version" - value: "1.2" - tier: "Clinical" - message: "Legacy clients (ATM network) require TLS 1.2 support." - - # 3. Mandate a Specific Dependency Version - - path: "code://python/data-science/dep/pandas/version" - predicate: "installed_version" - value: "2.1.0" - tier: "Regulatory" - message: "Must use pandas 2.1.0 due to regression in 2.2.x." -``` - -## How It Works - -1. **Ingestion:** On `aphoria scan`, the CLI reads `aphoria-policy.yaml`. -2. **Assertion Creation:** Each rule is converted into a StemeDB Assertion with `SourceClass::Regulatory` (Tier 0) or `SourceClass::Clinical` (Tier 1). -3. **Conflict Detection:** The query engine compares your code's extracted claims against these new assertions. -4. **Enforcement:** - * If Code says `pool_size = 100` and Policy says `50` (Tier 0), the conflict score is high (BLOCK). - * The developer gets a clear error: *"Internal policy: max 50 connections..."* - -## The Enterprise Lens - -For complex organizations, Aphoria supports the **Enterprise Lens**. This lens automatically prioritizes: - -1. **Local Policy (Tier 0 Override)** -2. **Regulatory Standards (RFC/NIST)** -3. **Vendor Documentation** - -This ensures that "Our Truth" wins locally, without polluting the global knowledge graph. You aren't claiming "TLS 1.2 is secure globally" (which is false); you are claiming "TLS 1.2 is required *here*" (which is true). - -## Use Cases - -* **SRE Teams:** Distribute a shared `aphoria-policy.yaml` template to all microservices to enforce timeouts and retries. -* **Security Teams:** Mandate specific crypto libraries or key rotation intervals that go beyond OWASP defaults. -* **Platform Engineering:** Enforce standardized ports, logging formats, and health check endpoints across polyglot repos. diff --git a/applications/aphoria/roadmap.md b/applications/aphoria/roadmap.md index 8056cb0..c2a9edf 100644 --- a/applications/aphoria/roadmap.md +++ b/applications/aphoria/roadmap.md @@ -2670,3 +2670,363 @@ Benchmark Results: | Buyer can see how to contact policy owner | ✓ | | Speed benchmarks documented and reproducible | ✓ | + +--- + +## Phase 11: Evidence-Based Authority 🎯 + +> **Vision:** Authority comes from evidence, not titles. Merit over tenure. + +**Problem:** All patterns treated equally. A random commit carries the same weight as a pattern backed by RFC research and product specs. + +**Principle:** The system rewards documentation, not tenure. + +### Evidence Levels + +| Level | Example | Authority Weight | Graduation Threshold | +|-------|---------|------------------|---------------------| +| ProductSpec | `specs/api-design.md → REQ-API-001` | 0.95 | 1 usage | +| Standard | RFC 7519, OWASP A03:2021 | 0.85 | 3 usages | +| Research | ADR-042, docs/decision-log.md | 0.70 | 5 usages | +| Commit | Just code, no context | 0.40 | 10 usages | + +### 11.1 Evidence Level Types ⬜ + +| Task | Status | +|------|--------| +| Create `src/evidence/mod.rs` module | ⬜ | +| Define `EvidenceLevel` enum (Commit, Research, Standard, ProductSpec) | ⬜ | +| Implement `authority_weight()` method | ⬜ | +| Add evidence level to `LearnedPattern` struct | ⬜ | +| Update pattern display to show evidence level | ⬜ | + +### 11.2 Evidence Source Detection ⬜ + +| Task | Status | +|------|--------| +| Create `EvidenceSource` enum | ⬜ | +| Implement commit message parsing for RFC/standard references | ⬜ | +| Implement ADR file detection (docs/adr/*.md patterns) | ⬜ | +| Implement spec file detection (specs/*.md, *.spec.md) | ⬜ | +| Add `PatternEvidence::detect()` auto-detection | ⬜ | + +### 11.3 Evidence-Aware Graduation ⬜ + +| Task | Status | +|------|--------| +| Update `GraduationManager` thresholds based on evidence | ⬜ | +| ProductSpec: 1 usage → promotion candidate | ⬜ | +| Standard: 3 usages → promotion candidate | ⬜ | +| Research: 5 usages → promotion candidate | ⬜ | +| Commit-only: 10 usages → promotion candidate | ⬜ | +| Add evidence boost to shadow mode evaluation | ⬜ | + +### 11.4 Evidence Display ⬜ + +| Task | Status | +|------|--------| +| Update `aphoria patterns show` to display evidence chain | ⬜ | +| Show evidence level badge in table/JSON output | ⬜ | +| Show linked sources (ADR, spec, RFC) in conflict output | ⬜ | +| Add `--evidence` flag to filter patterns by evidence level | ⬜ | + +### Phase 11 Completion Criteria + +| Metric | Target | +|--------|--------| +| Evidence detection working for 4 source types | ✓ | +| Graduation thresholds vary by evidence level | ✓ | +| Pattern display shows evidence chain | ✓ | +| ProductSpec-backed patterns graduate with 1 usage | ✓ | + +--- + +## Phase 12: Knowledge Scope Hierarchy ⬜ + +> **Vision:** Knowledge applies at the right level - org, team, or project. + +**Problem:** All knowledge exists at one flat level. No way to say "this applies org-wide" vs "this is just our team's preference." + +### Scope Levels + +``` +Organization Level (applies to all teams) +├── Security policies (TLS, auth, secrets) - NO opt-out +├── Compliance requirements (GDPR, SOC 2) +└── Architecture decisions (API gateway, event bus) + +Team Level (applies to team's projects) +├── Coding conventions (naming, error handling) +├── Technology choices (frameworks, libraries) +└── Domain patterns (payment flows, user lifecycle) + +Project Level (applies to single project) +├── Local overrides (justified exceptions) +├── Experimental patterns (not yet proven) +└── Context-specific decisions +``` + +### 12.1 Scope Level Types ⬜ + +| Task | Status | +|------|--------| +| Create `src/scope/mod.rs` module | ⬜ | +| Define `ScopeLevel` enum (Organization, Team, Project) | ⬜ | +| Add `scope_level` and `scope_id` to `LearnedPattern` | ⬜ | +| Add `ScopeConfig` to `.aphoria.toml` | ⬜ | +| Implement `--scope` flag for CLI commands | ⬜ | + +### 12.2 Scope Inheritance ⬜ + +| Task | Status | +|------|--------| +| Implement inheritance resolution (project → team → org) | ⬜ | +| Security policies: auto-apply, no opt-out | ⬜ | +| Conventions: auto-apply, teams can override with justification | ⬜ | +| Observations: never inherited, team-specific only | ⬜ | +| Add `ScopedKnowledge` struct with `inherited_from` chain | ⬜ | + +### 12.3 Scope Override Workflow ⬜ + +| Task | Status | +|------|--------| +| Implement `aphoria scope override` command | ⬜ | +| Require justification for overrides | ⬜ | +| Require evidence link (spec, ADR, ticket) for overrides | ⬜ | +| Store override audit trail | ⬜ | +| Show overrides in SOC 2 reports | ⬜ | + +### 12.4 Cross-Scope Queries ⬜ + +| Task | Status | +|------|--------| +| `aphoria patterns --scope org` (org-level only) | ⬜ | +| `aphoria patterns --scope team --exclude-inherited` | ⬜ | +| `aphoria patterns --scope project --only-local` | ⬜ | +| Show scope in pattern list output | ⬜ | + +### Phase 12 Completion Criteria + +| Metric | Target | +|--------|--------| +| 3 scope levels working (org/team/project) | ✓ | +| Inheritance resolution correct | ✓ | +| Overrides require justification + evidence | ✓ | +| Cross-scope queries functional | ✓ | + +--- + +## Phase 13: Knowledge Lifecycle Management ⬜ + +> **Vision:** Knowledge ages. Patterns can be deprecated and superseded. + +**Problem:** Knowledge exists forever. No way to deprecate patterns or track evolution. + +### Knowledge Status + +``` +Active → Pattern is current, enforced +Deprecated → Pattern is being phased out, migration guidance provided +Superseded → Pattern replaced by another, link to replacement +Archived → Pattern removed from active use, historical only +``` + +### 13.1 Knowledge Status Types ⬜ + +| Task | Status | +|------|--------| +| Create `src/lifecycle/mod.rs` module | ⬜ | +| Define `KnowledgeStatus` enum | ⬜ | +| Add `Deprecated` variant with reason, superseded_by, sunset_date | ⬜ | +| Add `KnowledgeLifecycle` struct with status history | ⬜ | +| Store lifecycle in pattern metadata | ⬜ | + +### 13.2 Deprecation Command ⬜ + +| Task | Status | +|------|--------| +| Implement `aphoria deprecate ` command | ⬜ | +| Require `--reason` flag | ⬜ | +| Optional `--superseded-by ` | ⬜ | +| Optional `--sunset-date ` | ⬜ | +| Notify connected teams on deprecation | ⬜ | + +### 13.3 Migration Guidance ⬜ + +| Task | Status | +|------|--------| +| Show deprecation warning in scan output | ⬜ | +| Link to superseding pattern when available | ⬜ | +| Show migration guide/ADR when linked | ⬜ | +| FLAG (not BLOCK) deprecated pattern usage | ⬜ | +| Track migration progress across projects | ⬜ | + +### 13.4 Migration Tracking Dashboard ⬜ + +| Task | Status | +|------|--------| +| Implement `aphoria migrations status` command | ⬜ | +| Show progress by team (X/Y endpoints migrated) | ⬜ | +| Show days remaining until sunset | ⬜ | +| Show blockers (acknowledged exceptions) | ⬜ | +| Export migration status for reporting | ⬜ | + +### Phase 13 Completion Criteria + +| Metric | Target | +|--------|--------| +| Deprecation command working | ✓ | +| Deprecated patterns show warning in scan | ✓ | +| Migration tracking across projects | ✓ | +| SOC 2 report includes migration status | ✓ | + +--- + +## Phase 14: Governance Workflows ⬜ + +> **Vision:** Clear approval paths for pattern promotion with audit trails. + +**Problem:** Governance is binary: manual review or >0.95 auto-promote. No structured approval workflows. + +### 14.1 Approval Workflow Definition ⬜ + +| Task | Status | +|------|--------| +| Create `src/governance/mod.rs` module | ⬜ | +| Define `ApprovalWorkflow` struct | ⬜ | +| Define `ApprovalStage` with required approvers | ⬜ | +| Support evidence-based auto-approve thresholds | ⬜ | +| Config: define workflows in `.aphoria.toml` | ⬜ | + +### 14.2 Approval State Machine ⬜ + +| Task | Status | +|------|--------| +| Implement state transitions (pending → approved/rejected) | ⬜ | +| Multi-stage approval support | ⬜ | +| Timeout and escalation policies | ⬜ | +| Store approval history with timestamps | ⬜ | + +### 14.3 Approval CLI ⬜ + +| Task | Status | +|------|--------| +| `aphoria governance pending` - list pending approvals | ⬜ | +| `aphoria governance approve --comment "..."` | ⬜ | +| `aphoria governance reject --reason "..."` | ⬜ | +| `aphoria governance escalate ` | ⬜ | +| Show approval status in pattern list | ⬜ | + +### 14.4 SOC 2 Audit Trail ⬜ + +| Task | Status | +|------|--------| +| Full audit log for all governance actions | ⬜ | +| `aphoria audit trail --pattern ` - show timeline | ⬜ | +| Export governance history for auditors | ⬜ | +| Include approver identity and timestamp | ⬜ | + +### Phase 14 Completion Criteria + +| Metric | Target | +|--------|--------| +| Multi-stage approval working | ✓ | +| Approval/reject with comments | ✓ | +| Full audit trail exportable | ✓ | +| SOC 2 evidence includes approval chain | ✓ | + +--- + +## Phase 15: Evidence Source Integration ⬜ + +> **Vision:** ADRs, specs, and standards automatically link to patterns. + +**Problem:** Evidence sources aren't automatically detected. Developers must manually reference them. + +### 15.1 ADR Auto-Detection ⬜ + +| Task | Status | +|------|--------| +| Create `src/evidence/adr.rs` | ⬜ | +| Detect ADR-XXX patterns in commit messages | ⬜ | +| Scan for ADR files in standard locations | ⬜ | +| Parse ADR content for related patterns | ⬜ | +| Link ADR to patterns automatically | ⬜ | + +### 15.2 Spec File Detection ⬜ + +| Task | Status | +|------|--------| +| Create `src/evidence/spec.rs` | ⬜ | +| Detect spec files (specs/*.md, *.spec.md) | ⬜ | +| Parse requirement IDs (REQ-XXX) | ⬜ | +| Link requirements to patterns | ⬜ | +| Show requirement coverage in reports | ⬜ | + +### 15.3 Standard Reference Extraction ⬜ + +| Task | Status | +|------|--------| +| Create `src/evidence/standards.rs` | ⬜ | +| Parse RFC references (RFC 7519) | ⬜ | +| Parse OWASP references (OWASP A03:2021) | ⬜ | +| Parse NIST references (NIST SP 800-53) | ⬜ | +| Auto-link to authoritative corpus | ⬜ | + +### 15.4 Evidence Display ⬜ + +| Task | Status | +|------|--------| +| Show full evidence chain in pattern output | ⬜ | +| Link to source files (ADR, spec) | ⬜ | +| Show external standard references | ⬜ | +| `aphoria patterns --by-evidence` grouping | ⬜ | + +### Phase 15 Completion Criteria + +| Metric | Target | +|--------|--------| +| ADR auto-detection working | ✓ | +| Spec file linking working | ✓ | +| Standard references extracted | ✓ | +| Evidence chain visible in output | ✓ | + +--- + +## Enterprise Pilot Success Metrics + +### 90-Day Pilot Targets + +| Metric | Target | Measurement | +|--------|--------|-------------| +| Patterns captured | 100+ observations | Count in knowledge graph | +| Patterns promoted | 10+ conventions | Count with status=Active | +| Cross-team adoption | 2+ teams connected | Unique team_ids | +| New hire guidance events | 5+ accepted suggestions | Accept rate tracking | +| False positive rate | <10% | FP feedback / total flags | +| Evidence-backed patterns | >50% | Patterns with Research+ evidence | + +### 180-Day Production Targets + +| Metric | Target | Measurement | +|--------|--------|-------------| +| Knowledge retention | 0 lost patterns on departures | Audit log | +| Onboarding velocity | 50% faster ramp | Time to first PR | +| Convention adoption | 80% across org | Compliance rate | +| SOC 2 evidence | Audit pass | External validation | +| Deprecated pattern migration | 90% complete by sunset | Migration tracking | + +--- + +## Enterprise Simulation UAT + +See: `uat/enterprise-simulation-uat.md` + +6-month simulation covering: +- Month 1: Platform team adopts, baseline patterns captured +- Month 2: Payments team joins, cross-team patterns emerge +- Month 3: New hire guided by existing patterns +- Month 4: Mobile team joins, org-level promotion +- Month 5: API versioning deprecated, migration tracked +- Month 6: SOC 2 audit evidence generated + diff --git a/applications/aphoria/uat/enterprise-simulation-uat.md b/applications/aphoria/uat/enterprise-simulation-uat.md new file mode 100644 index 0000000..d124ce2 --- /dev/null +++ b/applications/aphoria/uat/enterprise-simulation-uat.md @@ -0,0 +1,796 @@ +# Enterprise Simulation UAT + +**Scenario:** Acme Corp adopts Aphoria across 3 teams over 6 months +**Goal:** Validate self-learning institutional knowledge at enterprise scale +**Status:** Specification (not yet implemented) + +--- + +## Simulation Overview + +### The Organization + +``` +Acme Corp (Engineering) +├── Platform Team (8 engineers) +│ ├── Alice, Bob (established patterns with specs/ADRs) +│ └── 6 others (1 new hire in Month 3: Jordan) +├── Payments Team (6 engineers) +│ ├── Carol (maintains payment specs) +│ └── 5 others +└── Mobile Team (5 engineers) + └── 5 engineers (1 new hire in Month 4: Kim) +``` + +**Authority model:** Evidence-based, not title-based +- Patterns with ProductSpec → highest authority (0.95) +- Patterns with RFC/Standard → high authority (0.85) +- Patterns with ADR/Research → medium authority (0.70) +- Patterns from commits only → low authority (0.40) + +### The Projects + +| Team | Projects | Languages | Focus | +|------|----------|-----------|-------| +| Platform | api-gateway, auth-service, config-lib | Rust, Go | Infrastructure | +| Payments | payment-processor, billing-service | Python, Go | Transactions | +| Mobile | ios-app, android-app, mobile-bff | Swift, Kotlin, TypeScript | Client apps | + +### The Timeline + +| Month | Event | Expected Outcome | +|-------|-------|------------------| +| **1** | Platform team adopts Aphoria | Baseline patterns captured | +| **2** | Payments team joins | Cross-team patterns emerge | +| **3** | New hire joins Platform | Guided by existing patterns | +| **4** | Mobile team joins + new hire | Team-specific patterns captured | +| **5** | Platform refactors API versioning | Pattern deprecation + migration | +| **6** | SOC 2 audit preparation | Evidence generation | + +--- + +## Month 1: Platform Team Adoption + +### 1.1 Setup + +**Scenario:** Platform team installs Aphoria on all 3 projects. + +```bash +# Each project +cd api-gateway && aphoria init --org acme --team platform +cd auth-service && aphoria init --org acme --team platform +cd config-lib && aphoria init --org acme --team platform +``` + +**Expected:** +- Connected to org knowledge graph +- 0 policies, 0 conventions, 0 observations (fresh start) + +### 1.2 Week 1-2: Baseline Commits + +**Scenario:** Team makes 50 commits across projects with normal development. + +**Commits include:** +- TLS configuration (verify=true in 48, verify=false in 2 test fixtures) +- JWT audience validation (enabled in 45, disabled in 5 internal services) +- API versioning using `/api/v1/{resource}` (consistently in all 15 endpoints) +- Error format `{"error": {"code": X, "message": Y}}` (consistently in all handlers) +- Timeout of 30s (consistent) + +**Expected Observations Captured:** + +| Pattern | Usages | Evidence Level | Authority Weight | +|---------|--------|----------------|------------------| +| API versioning /api/v1/{resource} | 15 | ProductSpec (specs/api-design.md) | 0.95 | +| Error format {"error":{...}} | 12 | Research (ADR-015) | 0.70 | +| 30s default timeout | 8 | Commit only | 0.40 | +| TLS verify=true | 48 | Standard (RFC 8446) | 0.85 | +| JWT aud validation=true | 45 | Standard (RFC 7519) | 0.85 | + +### 1.3 Week 3: Pattern Graduation + +**Scenario:** After 20+ consistent usages, patterns graduate. + +**Test Case 1.3.1:** API versioning graduates to convention (high evidence) +```bash +$ aphoria patterns pending + +Pending Graduation: + [P001] API Versioning: /api/v1/{resource} + Usages: 15 across 3 projects + Evidence: ProductSpec (specs/api-design.md → REQ-API-001) + Authority: 0.95 + Shadow Mode: 100 scans, 0 FPs + Status: Ready for promotion (evidence threshold met with 1 usage) + +$ aphoria patterns promote P001 --scope team + +Promoted: API Versioning → Team Convention (Platform) +``` + +**Expected:** +- Pattern status changes to "Active Convention" +- Scope is "Team: Platform" +- New commits deviating from pattern get FLAG + +### 1.4 Week 4: First Conflict Detection + +**Scenario:** New endpoint added without versioning. + +```python +# billing-service/src/routes.py +@app.route("/invoices") # Missing /api/v1/ prefix +def list_invoices(): + ... +``` + +```bash +$ git commit -m "Add invoice endpoint" + +Aphoria scan: + ⚠ API Versioning: Your team uses /api/v{major}/{resource} + └ Established by @alice (Staff, Platform) - 15 usages + └ Your code: /invoices → Suggest: /api/v1/invoices + + Accept suggestion? [y/n/explain/ignore] +``` + +**Test Case 1.4.1:** Developer accepts suggestion +```bash +> y +# Code updated, commit amended +``` + +**Test Case 1.4.2:** Developer explains deviation +```bash +> explain +# System shows: Pattern origin, ADR link, who to ask +``` + +**Test Case 1.4.3:** Developer ignores (justified) +```bash +> ignore --reason "Legacy endpoint for backward compatibility" --expiry 90d +# Acknowledgment recorded with expiry +``` + +--- + +## Month 2: Payments Team Joins + +### 2.1 Payments Team Setup + +**Scenario:** Payments team connects to same org knowledge graph. + +```bash +cd payment-processor && aphoria init --org acme --team payments +cd billing-service && aphoria init --org acme --team payments +``` + +**Expected:** +- Receives: 12 org policies (RFCs, OWASP) +- Receives: 5 platform conventions (API versioning, error format, etc.) +- Question: Should Platform conventions apply to Payments? + +### 2.2 Cross-Team Pattern Discovery + +**Scenario:** Payments team uses same error format independently. + +```python +# payment-processor/src/handlers.py +def process_payment(req): + if error: + return {"error": {"code": "PAYMENT_FAILED", "message": str(e)}} +``` + +**Test Case 2.2.1:** Pattern recognized as matching Platform convention +```bash +$ git commit -m "Add payment processing" + +Aphoria scan: + ✓ Error format matches org convention + └ Established by Platform Team (12 usages) + └ Your usage is consistent - no action needed + + + Captured: Transaction retry with exponential backoff + → First usage in Payments team +``` + +### 2.3 Team-Specific Patterns + +**Scenario:** Payments uses Stripe SDK with specific patterns. + +```python +# Consistent across payment-processor +stripe.api_key = os.getenv("STRIPE_API_KEY") +stripe.max_network_retries = 3 +stripe.api_version = "2024-04-10" +``` + +**Test Case 2.3.1:** Team-specific pattern captured +```bash +Captured: Stripe SDK configuration pattern + - API version: 2024-04-10 + - Max retries: 3 + - Key from env var + +This is specific to Payments team (not org-wide). +``` + +**Expected:** +- Pattern scoped to Team: Payments +- Does NOT apply to Platform team +- Would apply to new Payments projects + +### 2.4 Cross-Team Conflict + +**Scenario:** Payments uses different timeout than Platform. + +```python +# payment-processor: 60s timeout (transaction needs more time) +# platform: 30s timeout (standard) +``` + +**Test Case 2.4.1:** Conflict detected, scoped resolution +```bash +Aphoria scan: + ⚠ Timeout Conflict: + Platform convention: 30s (8 usages) + Your code: 60s + + This may be intentional for payment processing. + + Options: + [1] Accept Platform convention (30s) + [2] Create Payments team convention (60s) + [3] Acknowledge with reason + +> 2 +Reason: Payment transactions require longer timeouts for bank processing + +Created: Payments team convention (60s timeout) +Note: Platform convention (30s) still applies to Platform projects +``` + +--- + +## Month 3: New Hire Onboarding (Platform) + +### 3.1 Day 1: New Hire Setup + +**Scenario:** Jordan joins Platform team, first commit on day 1. + +```bash +cd auth-service && aphoria init --org acme --team platform + +Connected to Acme Engineering knowledge graph +Your team: Platform + +Knowledge available: + • 12 policies (org-wide, from RFCs/OWASP) + • 5 conventions (Platform team patterns) + • 23 observations (individual patterns, not enforced) + +Quick start: + • Run `aphoria patterns list` to see team conventions + • Run `aphoria scan` before each commit + • Ask @alice or @bob about any flagged patterns +``` + +### 3.2 First Commit: Guided by Conventions + +**Scenario:** Jordan adds new endpoint, doesn't know team patterns. + +```python +# auth-service/src/routes.py (Jordan's code) +@app.route("/users/me") # Missing versioning +def get_current_user(): + if error: + return {"msg": "User not found"} # Wrong error format +``` + +```bash +$ git commit -m "Add current user endpoint" + +Aphoria scan: + ⚠ API Versioning: Your team uses /api/v{major}/{resource} + └ Evidence: ProductSpec (specs/api-design.md → REQ-API-001) + └ Also: ADR-042: API Versioning Strategy + └ Your code: /users/me → Suggest: /api/v1/users/me + + ⚠ Error Format: Your team uses {"error": {"code": X, "message": Y}} + └ Evidence: Research (ADR-015: Error Handling) + └ Your code: {"msg": "..."} → Suggest: {"error": {"code": "...", "message": "..."}} + + Accept suggestions? [y/n/explain] +``` + +**Test Case 3.2.1:** New hire accepts suggestions +```bash +> y +Applied 2 suggestions. Code updated. +``` + +**Expected:** +- Jordan's code updated to match conventions +- Jordan learns team patterns through workflow +- No wiki reading required + +### 3.3 Week 2: Jordan Contributes Pattern + +**Scenario:** Jordan adds logging pattern that becomes team convention. + +```python +# Jordan's consistent logging across 5 commits +logger.info("Starting operation", extra={"operation": "auth", "user_id": user_id}) +``` + +**Test Case 3.3.1:** Pattern captured with low evidence +```bash +Captured: Structured logging with extra context + - Usages: 5 + - Evidence: Commit only (no ADR, no spec, no standard) + - Authority weight: 0.40 + +Status: Observation (not enforced) +Note: Add ADR or link to spec to accelerate promotion +``` + +**Test Case 3.3.2:** Jordan adds ADR → promotion candidate +```bash +# Jordan creates docs/adr/ADR-023-structured-logging.md +# Commits with reference to ADR + +Aphoria scan: + + Captured: Structured logging pattern + → Evidence upgraded: Research (ADR-023) + → Authority weight increased to 0.70 + → Eligible for convention promotion after 5 usages (3 more needed) +``` + +**Test Case 3.3.3:** Pattern linked to ops spec → immediate promotion +```bash +# Jordan links pattern to ops/observability-spec.md + +Aphoria scan: + + Captured: Structured logging pattern + → Evidence upgraded: ProductSpec (ops/observability-spec.md) + → Authority weight: 0.95 + → Ready for promotion (ProductSpec requires only 1 usage) +``` + +--- + +## Month 4: Mobile Team Joins + +### 4.1 Mobile Team Setup + +**Scenario:** Mobile team connects, different language ecosystem. + +```bash +cd mobile-bff && aphoria init --org acme --team mobile +``` + +**Expected:** +- Receives org policies (security) +- Does NOT receive Platform/Payments conventions (different domain) +- Question: Which conventions should apply cross-team? + +### 4.2 New Hire (Mobile) Day 1 + +**Scenario:** Kim joins Mobile team, completely different from Platform. + +```bash +Connected to Acme Engineering knowledge graph +Your team: Mobile + +Knowledge available: + • 12 policies (org-wide security) + • 0 conventions (Mobile team has none yet) + • 0 observations (fresh team) + +Note: Platform and Payments teams have established conventions. + Run `aphoria patterns --scope org` to see if any should apply to Mobile. +``` + +**Test Case 4.2.1:** Mobile creates team-specific conventions + +```typescript +// mobile-bff/src/api.ts +export async function fetchUser(id: string): Promise { + const response = await fetch(`/api/v1/users/${id}`); // Same versioning! + if (!response.ok) { + throw new ApiError(response.status, await response.json()); + } + return response.json(); +} +``` + +```bash +Aphoria scan: + ✓ API versioning /api/v1/{resource} + └ Matches org-wide pattern (Platform + Payments use this) + └ Consider promoting to org convention? + + + Captured: ApiError class for HTTP error handling + → First usage in Mobile team +``` + +### 4.3 Pattern Promotion to Org Level + +**Scenario:** API versioning now used by all 3 teams → org convention. + +```bash +$ aphoria patterns --scope org --candidates + +Org Convention Candidates: + [P042] API Versioning: /api/v{major}/{resource} + Platform Team: 25 usages (established by @alice) + Payments Team: 12 usages (adopted) + Mobile Team: 8 usages (adopted) + + Recommendation: Promote to org convention + Approval required: Admin or 2 Staff Engineers + +$ aphoria patterns promote P042 --scope org --approvers alice@acme.com,carol@acme.com + +Promoted: API Versioning → Org Convention (Acme) +Now applies to all teams by default. +``` + +--- + +## Month 5: Platform Refactors API Versioning + +### 5.1 Pattern Deprecation + +**Scenario:** Platform decides to add version in header, not path. + +```bash +$ aphoria deprecate "api-versioning-path" \ + --reason "Moving to header-based versioning per RFC proposal" \ + --superseded-by "api-versioning-header" \ + --sunset-date 2026-09-01 + +Deprecated: API Versioning (path-based) + Status: DEPRECATED + Sunset: 2026-09-01 + Migration: Use X-API-Version header instead + Superseded by: api-versioning-header + +All teams notified. +``` + +### 5.2 Migration Guidance + +**Scenario:** Payments team commits with old pattern. + +```bash +$ git commit -m "Add refund endpoint" + +Aphoria scan: + ⚠ Deprecated Pattern: Path-based API versioning + └ Status: DEPRECATED (sunset: 2026-09-01) + └ Your code: /api/v1/refunds + └ Migrate to: Header-based versioning (X-API-Version: 1) + └ See: Migration Guide (linked), ADR-089 (linked) + + Options: + [1] Migrate now (update code) + [2] Acknowledge (defer migration) + [3] Explain (I understand, intentional) +``` + +### 5.3 Migration Tracking + +**Scenario:** Dashboard shows migration progress. + +```bash +$ aphoria migrations status + +Migration: Path-based → Header-based API versioning + Sunset: 2026-09-01 (120 days remaining) + + Progress by team: + ├── Platform: 15/25 endpoints migrated (60%) + ├── Payments: 0/12 endpoints migrated (0%) + └── Mobile: 0/8 endpoints migrated (0%) + + Total: 15/45 endpoints (33%) + + Blockers: + • Payments: Legacy client compatibility (acknowledged by @carol) + • Mobile: Waiting for iOS app update +``` + +--- + +## Month 6: SOC 2 Audit Preparation + +### 6.1 Evidence Generation + +**Scenario:** Auditor needs evidence for CC6.1 (Logical Access Controls). + +```bash +$ aphoria audit report --standard soc2 --control CC6.1 + +SOC 2 CC6.1: Logical Access Controls +Generated: 2026-07-15 + +1. Policy Inventory + ├── 15 security policies (org-wide) + ├── 8 team conventions (access-related) + └── All policies signed by authorized approvers + +2. Policy Enforcement Evidence + ├── 847/852 endpoints comply (99.4%) + ├── 5 documented exceptions (acknowledged, tickets linked) + └── 0 unacknowledged violations + +3. Change Control Evidence + ├── All pattern changes have approval chain + ├── Deprecation announced 90+ days before sunset + └── Migration tracking active for 3 patterns + +4. Access Review Evidence + ├── 23 contributors across 3 teams + ├── Role-based authority model configured + └── Seniority weights applied to pattern approvals + +[EXPORT TO PDF] +``` + +### 6.2 Auditor Questions + +**Test Case 6.2.1:** "Show me the approval chain for this policy" +```bash +$ aphoria audit trail --pattern "tls-1.3-required" + +Pattern: TLS 1.3 Required +Status: Active (Org Policy) + +Timeline: + 2024-01-15 Created by alice@acme.com (Staff, Platform) + 2024-01-16 Approved by security-team@acme.com + 2024-01-17 Promoted to org policy by admin@acme.com + 2024-06-01 Reviewed and reconfirmed by ciso@acme.com + +Enforcement: + Commit scans: 1,247 (100% checked) + Violations detected: 23 + Violations resolved: 23 + Current compliance: 100% +``` + +**Test Case 6.2.2:** "Show me exception handling" +```bash +$ aphoria audit exceptions --policy "jwt-audience-validation" + +Exceptions for: JWT Audience Validation Required + +Active Exceptions (5): + [E001] internal-metrics-service + Reason: Internal service, no external exposure + Approved by: alice@acme.com (Staff) + Expires: 2026-12-31 + Ticket: PLAT-1234 + + [E002] legacy-auth-bridge + Reason: Backward compatibility during migration + Approved by: carol@acme.com (Staff) + Expires: 2026-09-01 + Ticket: PAY-567 + + ... 3 more +``` + +--- + +## Test Execution Plan + +### Phase 1: Setup (Week 1) + +| Test ID | Description | Expected | Status | +|---------|-------------|----------|--------| +| SETUP-1 | Create simulated org structure | 3 teams, 19 contributors | | +| SETUP-2 | Initialize knowledge graph | Empty, connected | | +| SETUP-3 | Load RFC/OWASP corpus | 12+ policies | | + +### Phase 2: Month 1 Simulation (Week 2) + +| Test ID | Description | Expected | Status | +|---------|-------------|----------|--------| +| M1-1 | Platform init across 3 projects | Connected, 0 conventions | | +| M1-2 | 50 commits with patterns | 5+ observations captured | | +| M1-3 | Pattern graduation | 3+ conventions promoted | | +| M1-4 | First conflict detection | FLAG with suggestions | | +| M1-5 | Accept/explain/ignore flows | All paths work | | + +### Phase 3: Month 2 Simulation (Week 3) + +| Test ID | Description | Expected | Status | +|---------|-------------|----------|--------| +| M2-1 | Payments team joins | Inherits org policies | | +| M2-2 | Cross-team pattern recognition | Matches Platform conventions | | +| M2-3 | Team-specific pattern capture | Scoped to Payments only | | +| M2-4 | Cross-team conflict resolution | Team override created | | + +### Phase 4: Month 3 Simulation (Week 4) + +| Test ID | Description | Expected | Status | +|---------|-------------|----------|--------| +| M3-1 | New hire day 1 setup | Guided onboarding | | +| M3-2 | First commit guidance | 2+ suggestions provided | | +| M3-3 | Junior pattern capture | Lower authority weight | | +| M3-4 | Senior adoption → promotion | Weight increases | | + +### Phase 5: Month 4 Simulation (Week 5) + +| Test ID | Description | Expected | Status | +|---------|-------------|----------|--------| +| M4-1 | Mobile team joins | Different domain handling | | +| M4-2 | New hire (Mobile) day 1 | Fresh team, org policies | | +| M4-3 | Cross-team pattern detection | Same pattern, 3 teams | | +| M4-4 | Org-level promotion | Admin approval required | | + +### Phase 6: Month 5 Simulation (Week 6) + +| Test ID | Description | Expected | Status | +|---------|-------------|----------|--------| +| M5-1 | Pattern deprecation | Status changes, notified | | +| M5-2 | Migration guidance on commit | Deprecated warning + guide | | +| M5-3 | Migration tracking | Progress by team | | + +### Phase 7: Month 6 Simulation (Week 7) + +| Test ID | Description | Expected | Status | +|---------|-------------|----------|--------| +| M6-1 | SOC 2 report generation | Comprehensive evidence | | +| M6-2 | Approval chain audit | Full timeline | | +| M6-3 | Exception documentation | Linked to tickets | | + +--- + +## Success Criteria + +### Knowledge Compound Metrics + +| Metric | Target | Measurement | +|--------|--------|-------------| +| Observations captured | 100+ | Count in graph | +| Conventions promoted | 15+ | Active conventions | +| Cross-team patterns | 5+ | Multi-team usage | +| Deprecated patterns | 2+ | Lifecycle tested | + +### Onboarding Metrics + +| Metric | Target | Measurement | +|--------|--------|-------------| +| New hire guidance events | 10+ per new hire | Suggestion count | +| Suggestion acceptance rate | >80% | Accepted/offered | +| Time to first compliant commit | <1 day | Timestamp delta | + +### Governance Metrics + +| Metric | Target | Measurement | +|--------|--------|-------------| +| Approval chain completeness | 100% | All patterns have approver | +| Exception documentation | 100% | All exceptions have reason | +| Migration tracking accuracy | 100% | Matches actual state | + +### Audit Readiness + +| Metric | Target | Measurement | +|--------|--------|-------------| +| SOC 2 evidence generation | <5 minutes | Command execution | +| Evidence completeness | All controls covered | Auditor validation | +| Historical accuracy | 100% | Timeline matches reality | + +--- + +## Implementation Notes + +### Simulation Infrastructure + +```rust +pub struct SimulatedOrg { + pub org_id: String, + pub teams: Vec, + pub knowledge_graph: KnowledgeGraph, + pub timeline: SimulationTimeline, +} + +pub struct SimulatedTeam { + pub team_id: String, + pub contributors: Vec, + pub projects: Vec, +} + +pub struct SimulatedContributor { + pub id: String, + pub role: ContributorRole, + pub seniority: u8, + pub joined_at: u64, // Simulation time +} + +pub struct SimulatedCommit { + pub author: String, + pub project: String, + pub patterns: Vec, + pub timestamp: u64, +} +``` + +### Test Fixtures + +``` +uat/fixtures/enterprise-sim/ +├── org-structure.yaml # Org, teams, contributors +├── month-1/ +│ ├── commits.yaml # 50 commits with patterns +│ └── expected.yaml # Expected observations +├── month-2/ +│ ├── commits.yaml +│ └── expected.yaml +├── month-3/ +│ ├── new-hire-commits.yaml +│ └── expected.yaml +├── month-4/ +│ ├── mobile-commits.yaml +│ └── expected.yaml +├── month-5/ +│ ├── deprecation.yaml +│ └── migration-commits.yaml +└── month-6/ + └── audit-queries.yaml +``` + +### Execution Script + +```bash +#!/bin/bash +# run-enterprise-simulation.sh + +set -euo pipefail + +echo "=== Enterprise Simulation UAT ===" + +# Setup +./setup-simulation.sh + +# Month 1 +./simulate-month.sh 1 +./verify-month.sh 1 + +# Month 2 +./simulate-month.sh 2 +./verify-month.sh 2 + +# ... months 3-6 + +# Final metrics +./generate-report.sh + +echo "=== Simulation Complete ===" +``` + +--- + +## Appendix: Feature Dependencies + +This simulation requires the following features from the gap analysis: + +| Feature | Phase | Required For | +|---------|-------|--------------| +| Evidence-based authority | 10 | M1-3 (evidence detection, graduation thresholds) | +| Scope hierarchy | 11 | M2-3 (team-specific patterns) | +| Knowledge lifecycle | 12 | M5-1 (deprecation) | +| Governance workflows | 13 | M4-4 (org-level approval) | +| External integration | 15 | M3-3 (ADR/spec linking) | + +**Evidence Detection Requirements:** +- Commit message parsing for RFC/standard references +- ADR file detection in repo (docs/adr/*.md) +- Product spec linking (specs/*.md, *.spec.md) +- Research document detection + +**Note:** The simulation can be run incrementally as features are implemented. Early months (1-2) require only existing functionality + basic evidence detection. Later months (4-6) require the full feature set. diff --git a/applications/aphoria/vision.md b/applications/aphoria/vision.md index 7183524..8ebbdf0 100644 --- a/applications/aphoria/vision.md +++ b/applications/aphoria/vision.md @@ -1,102 +1,349 @@ # Aphoria -**A code-level truth linter powered by Episteme.** +**Self-learning institutional knowledge that compounds with every commit.** -Aphoria scans a codebase, extracts the decisions embedded in config and code, and checks them against authoritative sources. It finds the places where what your code *does* contradicts what the specs *say*. +Aphoria transforms your organization's implicit decisions into explicit, auditable, shareable knowledge. Every commit teaches the system. Every new hire benefits from what came before. Knowledge compounds instead of walking out the door. --- ## The Problem -Every codebase contains implicit claims. `verify=false` is a claim that TLS verification isn't needed. A JWT library configured without audience validation is a claim that `aud` checking doesn't matter. A hardcoded timeout of 0 is a claim that requests should wait forever. +Every organization has institutional knowledge. It lives in: +- The senior engineer's head ("we always validate JWT audience") +- The config file nobody reads ("verify=false was a hotfix in 2019") +- The Confluence page with 3 views ("our timeout policy is 30s max") +- The Stack Overflow answer the intern copied ("this worked for someone") -These claims are invisible. They live in config files, middleware setup, environment variables, and constructor arguments. Nobody thinks of them as claims. They're "just code." +This knowledge is **invisible, inconsistent, and fragile**: +- When Sarah leaves, her context leaves with her +- New hires copy patterns from 2019 code that predates current standards +- Team A's conventions contradict Team B's - neither knows +- The same mistakes repeat across 50 projects because nobody connected them -But they conflict with authoritative sources. RFC 7519 says audience validation is mandatory. OWASP says TLS verification must be enabled. Vendor documentation says the default timeout exists for a reason. +AI agents make this worse. An agent deploying code doesn't read the RFC. It picks the most confident-sounding answer from training data and acts. The agent doesn't know it's contradicting your team's decision because there's no structured way to check. -Today, the gap between what the code does and what the specs say is discovered in one of three ways: - -1. **A human reviews it.** Expensive, inconsistent, doesn't scale. -2. **A linter catches it.** Only works for known patterns. Can't reason about intent. -3. **Production breaks.** The $180M way. - -AI agents make this worse. An agent deploying code doesn't read the RFC. It picks the most confident-sounding answer from its training data — or the most recent Stack Overflow snippet — and acts. The agent doesn't know it's contradicting a standard because it has no structured way to check. +--- ## The Solution -Aphoria gives codebases an epistemic audit trail. It compares code claims against **The Three Tiers of Truth**: +Aphoria is a **knowledge compounding system** that learns from your organization's decisions as they happen. -1. **Global Truth (Tier 0):** Regulatory standards (RFCs, NIST, GDPR). -2. **Vendor Truth (Tier 2):** Documentation recommendations (AWS, Redis, Postgres). -3. **Local Truth (Tier 0 Override):** **Dynamic Application Policy.** Your team's specific decisions that supersede generic advice. +### The Three Tiers of Knowledge ``` -$ aphoria scan ./citadeldb - -Scanning citadeldb (rust) ... - - code://rust/citadeldb/auth/jwt/audience_validation - Your code: aud validation DISABLED (src/auth/jwt.rs:47) - RFC 7519: aud validation MUST be enabled (Tier 0, confidence 1.0) - Conflict: 0.92 — BLOCK - - code://rust/citadeldb/db/pool_size - Your code: pool_size = 100 (config/db.yaml:12) - Policy: max 50 connections (Tier 0, Internal Policy) - Conflict: 0.85 — BLOCK - - code://rust/citadeldb/http/timeout - Your code: timeout = 0 (no timeout) (config/production.yaml:8) - Vendor: default timeout 30s recommended (Tier 2, confidence 0.7) - Conflict: 0.54 — FLAG - -3 conflicts found (2 BLOCK, 1 FLAG) +┌─────────────────────────────────────────────────────────────────┐ +│ TIER 1: POLICIES (Explicit, Authoritative) │ +│ ───────────────────────────────────────────────────────────── │ +│ • RFC 7519: JWT audience validation required │ +│ • OWASP A03:2021: No SQL string concatenation │ +│ • Internal Policy: TLS 1.3 minimum (signed: CISO, 2024-01) │ +│ → BLOCK on violation, clear remediation path │ +└─────────────────────────────────────────────────────────────────┘ + ▲ + │ Explicit promotion (governance approval) + │ +┌─────────────────────────────────────────────────────────────────┐ +│ TIER 2: CONVENTIONS (Emergent, Team-Approved) │ +│ ───────────────────────────────────────────────────────────── │ +│ • API versioning: /api/v{major}/{resource} │ +│ • Error format: {"error": {"code": X, "message": Y}} │ +│ • Retry pattern: exponential backoff with jitter │ +│ → FLAG on deviation, suggest alignment, explain context │ +└─────────────────────────────────────────────────────────────────┘ + ▲ + │ Automatic graduation (frequency + authority) + │ +┌─────────────────────────────────────────────────────────────────┐ +│ TIER 3: OBSERVATIONS (Learning, Not Enforced) │ +│ ───────────────────────────────────────────────────────────── │ +│ • @alex's logging format (3 usages) │ +│ • @jordan's config pattern (1 usage) │ +│ → Silent capture, potential future convention │ +└─────────────────────────────────────────────────────────────────┘ ``` -Aphoria doesn't lint syntax. It lints *epistemic drift* — the gap between what your code asserts and what authoritative sources (global or local) say. +### The Workflow + +**Day 1: Install Aphoria** +```bash +$ aphoria init --org acme --team platform +Connected to Acme Engineering knowledge graph +Loaded: 12 policies, 47 conventions, 156 observations +``` + +**Every Commit: Learn and Guide** +```bash +$ git commit -m "Add payment processing endpoint" + +Aphoria scan: + ✓ TLS verification enabled (Policy: RFC 8446) + ✓ JWT audience validated (Policy: RFC 7519) + + + Captured: API versioning /api/v1/payments + → This is your 4th endpoint using this pattern + → Graduating to team convention (Platform Team) +``` + +**New Developer Joins:** +```bash +$ git commit -m "Add user profile endpoint" + +Aphoria guidance: + ⚠ API Versioning: Your team uses /api/v{major}/{resource} + └ Established by @alex (Senior, Platform Team) - 12 usages + └ Your code: /user/profile → Suggest: /api/v1/user/profile + + Accept suggestion? [y/n/explain] + > explain + + This pattern was established during the microservices migration. + Consistent versioning enables API gateway routing. + See: ADR-042 (linked), @alex's original commit (linked) +``` + +**Knowledge Compounds:** +``` +Acme Engineering (6 months) +├── 12 Policies (explicit, CISO-signed) +├── 47 Conventions (promoted from 340 observations) +│ └── 89% adoption rate, 0 regressions this quarter +├── 156 Observations (learning, not enforced) +└── 23 Deprecated patterns ("we used to do this, don't anymore") + +New hire onboarding: + • Day 1: Guided by 47 conventions, not 500 raw observations + • Week 1: 3 suggested alignments accepted, 1 explained deviation + • Month 1: Contributed 2 observations, 1 promoted to convention +``` + +--- ## How It Works -1. **Walk the project.** Map directory structure to ConceptPaths under `code://`. -2. **Extract claims.** Pattern-based extractors find security configs, dependency versions, timeout values, auth patterns. -3. **Ingest into Episteme.** Each extracted claim becomes an Assertion with the project's code as the source (Tier 3). -4. **Check for conflicts.** Query Episteme for each concept. If authoritative sources (RFCs, Vendor Docs, or **Local Policies**) disagree with the code claim, the conflict score fires. -5. **Report.** Output the conflicts with source references, conflict scores, and escalation verdicts. +### 1. Capture Decisions Where They Happen -The concept hierarchy is the backbone. `code://rust/citadeldb/auth/jwt/audience_validation` automatically aliases to `rfc://7519/jwt/audience_validation` because they share the `jwt/audience_validation` leaf. The conflict becomes structurally visible without anyone manually connecting the two. +Aphoria runs in your commit flow - the moment decisions become code: -## Who This Is For +```bash +# Pre-commit hook or CI integration +aphoria scan --persist --sync +``` -**Engineering leads** who deploy AI agents and need a pre-flight check. "Before the agent merges this PR, did it contradict any RFCs or our internal connection pooling policy?" +Every scan: +- **Detects** security patterns (TLS, JWT, SQL injection, XSS) +- **Extracts** configuration decisions (timeouts, pool sizes, retry policies) +- **Captures** new patterns as observations +- **Checks** against existing policies and conventions +- **Syncs** to org knowledge graph -**Platform teams** building internal developer tooling. Aphoria integrates into CI as a step between lint and deploy. +### 2. Graduate Patterns Through Governance -**Security teams** who audit configs across multiple services. "Across all our projects, which ones skip certificate verification?" +Not every observation becomes a convention. Graduation requires: + +| Criteria | Threshold | Why | +|----------|-----------|-----| +| Frequency | 5+ usages | Not a one-off hack | +| Consistency | Same pattern | Not random variation | +| Authority | Senior contributor | Not a junior's experiment | +| Time | 30+ days | Not a temporary fix | +| No conflicts | No FPs in shadow mode | Actually works | + +Patterns meeting criteria enter **shadow mode** - running alongside production, collecting feedback, before promotion. + +### 3. Scope Knowledge Appropriately + +Not all knowledge applies everywhere: + +``` +Organization Level (applies to all teams) +├── Security policies (TLS, auth, secrets) +├── Compliance requirements (GDPR, SOC 2) +└── Architecture decisions (API gateway, event bus) + +Team Level (applies to team's projects) +├── Coding conventions (naming, error handling) +├── Technology choices (frameworks, libraries) +└── Domain patterns (payment flows, user lifecycle) + +Project Level (applies to single project) +├── Local overrides (justified exceptions) +├── Experimental patterns (not yet proven) +└── Context-specific decisions +``` + +### 4. Authority from Evidence + +Authority isn't title-based - it's **merit-based**. The weight of a pattern comes from the evidence supporting it: + +``` +Authority Ladder (lowest to highest): + +┌─────────────────────────────────────────────────────────────────┐ +│ LEVEL 4: Product Spec / Task File │ +│ ───────────────────────────────────────────────────────────── │ +│ Pattern linked to explicit product requirement or task. │ +│ "This is what we decided to build." │ +│ Authority: 0.95 │ +└─────────────────────────────────────────────────────────────────┘ + ↑ +┌─────────────────────────────────────────────────────────────────┐ +│ LEVEL 3: RFC / Standard Reference │ +│ ───────────────────────────────────────────────────────────── │ +│ Pattern references authoritative external source. │ +│ "This is what the spec says." │ +│ Authority: 0.85 │ +└─────────────────────────────────────────────────────────────────┘ + ↑ +┌─────────────────────────────────────────────────────────────────┐ +│ LEVEL 2: Research / ADR / Documentation │ +│ ───────────────────────────────────────────────────────────── │ +│ Pattern accompanied by investigation or reasoning. │ +│ "Here's why we chose this." │ +│ Authority: 0.70 │ +└─────────────────────────────────────────────────────────────────┘ + ↑ +┌─────────────────────────────────────────────────────────────────┐ +│ LEVEL 1: Just a Commit │ +│ ───────────────────────────────────────────────────────────── │ +│ Pattern observed in code, no supporting evidence. │ +│ "Someone did this." │ +│ Authority: 0.40 │ +└─────────────────────────────────────────────────────────────────┘ +``` + +A pattern with RFC backing outweighs 100 undocumented commits. The system rewards evidence, not tenure. + +### 5. Deprecate and Evolve + +Knowledge ages. Aphoria tracks lifecycle: + +``` +Pattern: "Use request.get() for HTTP calls" +Status: DEPRECATED (2024-06-01) +Reason: "Migrated to httpx for async support" +Superseded by: "Use httpx.AsyncClient for HTTP calls" +Migration: See ADR-089 +``` + +New code using deprecated patterns gets guidance toward the replacement. + +--- + +## The Enterprise Value + +### For Engineering Leaders + +**Knowledge retention**: When senior engineers leave, their patterns stay. The system captures context, not just code. + +**Faster onboarding**: New hires get contextual guidance from day 1. "Your team does X" instead of "read the wiki." + +**Reduced rework**: Patterns proven across 50 projects stop developers from reinventing (broken) wheels. + +### For Security Teams + +**Continuous compliance**: Every commit is checked. SOC 2 auditors get evidence, not promises. + +**Policy enforcement**: Security policies aren't suggestions - they're enforced in the commit flow. + +**Drift detection**: When code deviates from blessed patterns, you know immediately. + +### For Platform Teams + +**Convention adoption**: Define patterns once, enforce everywhere. Measure adoption rates. + +**Cross-team consistency**: "This is how we do it at Acme" becomes queryable fact. + +**Technical debt visibility**: See which deprecated patterns are still in use, prioritize migration. + +--- + +## Integration Points + +### Claude Code Skill +``` +/aphoria scan # Run scan on current project +/aphoria explain # Explain why this is flagged +/aphoria bless # Promote pattern to convention +/aphoria ack 90d # Acknowledge with expiry +``` + +### Pre-commit Hook +```yaml +# .pre-commit-config.yaml +repos: + - repo: local + hooks: + - id: aphoria + name: Aphoria knowledge check + entry: aphoria scan --exit-code + language: system +``` + +### CI/CD Pipeline +```yaml +# GitHub Actions +- name: Aphoria Scan + run: aphoria scan --format sarif --output results.sarif + +- name: Upload SARIF + uses: github/codeql-action/upload-sarif@v2 + with: + sarif_file: results.sarif +``` + +### Central Knowledge Server +```bash +# Deploy org-wide knowledge graph +aphoria server --org acme --port 18187 + +# Teams connect +aphoria init --server https://aphoria.acme.internal +``` + +--- ## What This Is Not -- **Not a linter.** Linters check syntax rules. Aphoria checks claims against external authoritative sources. -- **Not a SAST tool.** SAST finds vulnerability patterns. Aphoria finds where code decisions contradict standards, which is a superset. -- **Not a replacement for code review.** It augments review by surfacing conflicts that humans miss because they haven't memorized every RFC. +**Not a linter.** Linters check syntax rules you define. Aphoria discovers patterns from behavior and checks against authoritative sources you didn't know existed. -## The Skill Integration +**Not SAST.** SAST finds vulnerability patterns in code. Aphoria finds where code decisions contradict standards - security is just one domain. -Aphoria ships as both a CLI and a Claude Code skill. When working in a project: +**Not a policy wiki.** Wikis are written once and forgotten. Aphoria captures decisions as they happen and surfaces them at the moment they're relevant. -``` -/aphoria scan -``` +**Not AI autocomplete.** Copilot suggests code from the internet. Aphoria surfaces *your org's* decisions at the moment you're about to contradict them. -The skill runs the CLI, ingests claims, queries for conflicts, and reports inline. The developer fixes the conflict or explicitly acknowledges it — which creates a new assertion: "engineering team decided to skip aud validation for internal services" (Tier 3, Expert). Now the disagreement is structured, documented, and visible next time anyone touches that code. - -The acknowledge flow is important. Not every conflict is a bug. Sometimes the code is right and the RFC is too strict for the context. Aphoria doesn't force compliance. It forces *visibility*. The decision to deviate from a standard becomes a recorded, auditable, queryable fact — not an invisible default. +--- ## The Flywheel -Every project Aphoria scans adds claims to Episteme. Every acknowledged deviation adds structured context. Over time: +``` +More commits → More observations captured + ↓ +More observations → Better pattern recognition + ↓ +Better patterns → More accurate guidance + ↓ +More accurate guidance → Higher developer trust + ↓ +Higher trust → More commits with Aphoria + ↓ +More usage → More institutional knowledge + ↓ +More knowledge → Less ramp-up time, fewer mistakes + ↓ +Fewer mistakes → More confidence in AI agents + ↓ +More AI usage → More commits... +``` -- Common false positives get suppressed (the alias "internal services can skip aud" gets registered across projects) -- Common true positives get elevated (the same JWT misconfiguration across 50 projects becomes a systemic signal) -- The authoritative source corpus grows (new RFCs, new OWASP entries, new vendor docs get ingested by research agents triggered by gaps) +The more projects Aphoria scans, the smarter it gets - not through ML magic, but through accumulated structured decisions. Every commit is a vote. Every acknowledgment is context. Every promotion is governance. -The more projects Aphoria scans, the smarter it gets — not through ML, but through accumulated structured disagreement. \ No newline at end of file +--- + +## The Bottom Line + +Your organization makes thousands of decisions every day. Most are invisible. When something breaks, you discover the decision existed only by finding the bug. + +Aphoria makes those decisions visible, auditable, and compounding. Install it on day 1. Let it learn as you build. Watch new hires ramp faster. Watch senior knowledge persist after they leave. Watch cross-team consistency emerge naturally. + +**Your codebase becomes a knowledge graph. Your commits become institutional memory. Your organization gets smarter with every push.**