# KnowHub V1.1 — AI Features Design

**Version:** 1.0 | **Date:** 2026-03-19 | **Status:** Design Final
**Prerequisite:** DESIGN.md (V3 single source of truth)

---

## Design Principle

**Agents create. Humans manage. AI helps humans manage better.**

Generating content is the agent's job. The AI in KnowHub's console is the manager's assistant — it helps the human understand, evaluate, and improve what agents created. Every AI feature must pass three tests:

1. **Illumination** (Hara): Does it reveal something already present but hard to see?
2. **Next action** (Zhang): After the user sees the result, is there an obvious thing to do?
3. **Invisibility** (Jobs): Does it feel like the product is smart, not like the user is operating an AI?

---

## V1.1 AI Features (5 features, final cut)

### Feature 1: Smart Upload — Extract Metadata on File Upload

- **Purpose:** Every uploaded file gets name, description, tags, and type without the user filling forms.
- **Trigger:** Automatic — fires when user uploads a file to Knowledge or Skills tab.
- **AI prompt (brief):** "Given this file content and filename, extract: a concise title, a one-sentence description written for an AI agent to determine relevance, 2-5 tags, and classify as reference/procedure/template (knowledge) or skill (if YAML frontmatter with name+description detected). Respond as JSON."
- **Output:** Import Review screen pre-filled with extracted metadata. All fields editable inline. User sees what the agent will see during index scan.
- **Next action:** User confirms (one click) or edits a field, then confirms. File saved with metadata frontmatter.
- **UI placement:** Intercepts the existing Upload flow. After file picker, before save. Full-width modal: left side shows file preview, right side shows extracted metadata fields.
- **Fallback (no LLM):** Metadata fields are blank. Title defaults to filename. User fills manually. Upload still works.

### Feature 2: Skill Analyzer — Evaluate Skill Quality

- **Purpose:** Help the human judge whether an agent-created skill is well-written, complete, and effective.
- **Trigger:** Manual — "Analyze" button on Skill Detail view, next to Edit/Share/Duplicate.
- **AI prompt (brief):** "Analyze this SKILL.md for quality. Score 1-5 on: clarity (are steps unambiguous?), completeness (missing parameters? no examples? no error handling?), specificity (vague instructions like 'do it well'?), efficiency (unnecessary steps?). For each score below 4, provide one concrete fix. Respond as JSON."
- **Output:** Inline panel below the skill header showing four score bars (clarity, completeness, specificity, efficiency) with the specific fix suggestion next to any low score. Collapsed by default after first view.
- **Next action:** User clicks a fix suggestion, which pre-populates the edit view with the suggested change highlighted. Or user dismisses if scores are satisfactory.
- **UI placement:** Slides open below the skill header in SkillDetail, pushing content down. Styled with the skill's green accent. Persisted in localStorage so it does not re-run on every view.
- **Fallback (no LLM):** "Analyze" button hidden. Feature does not appear.

### Feature 3: Duplicate & Contradiction Detector — Memory Hygiene

- **Purpose:** Surface duplicate and contradictory memories so the human can clean up what agents left behind.
- **Trigger:** Semi-automatic — runs when user opens the Memories tab if there are 10+ memories. Shows a banner: "3 potential issues found" with a "Review" link.
- **AI prompt (brief):** "Given these memory titles and contents, identify: (a) groups of memories that say the same thing (duplicates), (b) pairs of memories that contradict each other. For each group/pair, explain why in one sentence. Respond as JSON."
- **Output:** A "Memory Hygiene" drawer (slides from right) showing grouped issues. Each group shows the memory titles, the relationship (duplicate/contradiction), and the one-sentence explanation.
- **Next action:** For duplicates: "Keep best, delete others" — user picks one to keep, rest are deleted in one click. For contradictions: user reads both, deletes the wrong one or comments on both to clarify.
- **UI placement:** Banner at top of Memories tab (dismissible, re-checks weekly). Drawer opens over the memory list. Uses the memory amber accent.
- **Fallback (no LLM):** Banner never appears. Feature does not exist. Memories tab works as before.

### Feature 4: Skill Identifier — Auto-Classify Uploaded Content

- **Purpose:** When a user uploads a file, determine if it is a skill or knowledge document — especially for files without YAML frontmatter that the rule-based detector might miss.
- **Trigger:** Automatic — part of the Smart Upload flow (Feature 1). Runs after metadata extraction.
- **AI prompt (brief):** "Given this file content, determine if it is: (a) a skill — it describes a procedure an agent should execute, with steps, parameters, or decision logic; or (b) knowledge — it is reference material an agent should consult. Respond with classification and confidence (high/medium/low) and one-sentence reasoning."
- **Output:** In the Import Review screen, a type badge (Skill or Knowledge) with confidence indicator. If confidence is medium/low, shows the reasoning and a toggle to override.
- **Next action:** User confirms or overrides the classification. File is saved to `/skills/` or `/knowledge/` accordingly.
- **UI placement:** Integrated into Feature 1's Import Review screen as the type selector. Replaces the manual type dropdown with an AI-suggested badge + override toggle.
- **Fallback (no LLM):** Falls back to rule-based detection (YAML frontmatter check, numbered steps heuristic). User sees the type dropdown with the heuristic's best guess.

### Feature 5: Knowledge Staleness Check — Flag Outdated Content

- **Purpose:** Identify knowledge documents that may be outdated based on temporal references, version numbers, or age.
- **Trigger:** Semi-automatic — runs as a background check when the Knowledge tab loads. Shows a subtle indicator on stale cards.
- **AI prompt (brief):** "Given this document's content and last-modified date, identify if it contains: (a) date references older than 6 months, (b) version numbers that may be outdated, (c) references to tools/APIs that may have changed. If any found, provide a one-sentence summary of what may need updating. Respond as JSON."
- **Output:** An outlined warning badge on the Knowledge card: "May need review" with tooltip showing the reason. On the detail view, a yellow banner at top: "This document references [specific thing] from [date]. Consider reviewing."
- **Next action:** User clicks the banner to open Edit mode, or dismisses it. Dismissal is remembered (localStorage) until the document is modified again.
- **UI placement:** Badge on KnowledgeCard component. Banner in KnowledgeDetail header, below metadata. Uses a muted amber/warning color, not the memory amber.
- **Fallback (no LLM):** Simple date-based check only: if last-modified > 6 months, show "Not updated in X months" badge. No content analysis.

---

## AI Configuration Module

### Settings UI

New tab in Settings page: "AI Configuration" (icon: `Sparkles` from lucide-react).

```
Settings > AI Configuration

┌─────────────────────────────────────────────────────┐
│  LLM PROVIDER                                       │
│                                                     │
│  Provider:    [OpenAI ▾]  [Anthropic]  [Custom]     │
│  API Key:     [•••••••••••••••••]     [Test]        │
│  Model:       [gpt-4o-mini ▾]                       │
│  Base URL:    [https://api.openai.com/v1]           │
│                                                     │
│  Status: ● Connected (tested 2 min ago)             │
├─────────────────────────────────────────────────────┤
│  ENABLED FEATURES                                   │
│                                                     │
│  [✓] Smart Upload (extract metadata on file upload) │
│  [✓] Skill Analyzer (evaluate skill quality)        │
│  [✓] Memory Hygiene (duplicate/contradiction check) │
│  [✓] Content Classification (skill vs knowledge)    │
│  [✓] Staleness Check (flag outdated knowledge)      │
│                                                     │
│  Token budget:  [1000 ▾] tokens per request (max)   │
├─────────────────────────────────────────────────────┤
│  USAGE THIS MONTH                                   │
│                                                     │
│  Requests: 47    Tokens: ~23,400    Est. cost: $0.12│
└─────────────────────────────────────────────────────┘
```

### API Route Design

All AI calls go through Next.js API routes. Keys never reach the browser.

| Route | Method | Input | Output |
|-------|--------|-------|--------|
| `POST /api/ai/extract-metadata` | POST | `{ content, filename }` | `{ title, description, tags[], type }` |
| `POST /api/ai/classify-content` | POST | `{ content, filename }` | `{ classification, confidence, reasoning }` |
| `POST /api/ai/analyze-skill` | POST | `{ skillMd }` | `{ scores: {clarity,completeness,specificity,efficiency}, fixes[] }` |
| `POST /api/ai/check-memories` | POST | `{ memories: {id,title,content}[] }` | `{ duplicates: group[], contradictions: pair[] }` |
| `POST /api/ai/check-staleness` | POST | `{ content, lastModified, filename }` | `{ isStale, reasons[], summary }` |

**Request headers:** `X-KnowHub-AI-Provider`, `X-KnowHub-AI-Key`, `X-KnowHub-AI-Model`, `X-KnowHub-AI-BaseURL` — same localStorage-to-header pattern as auth proxy.

**Architecture:**
```
Browser (no AI keys) → Next.js /api/ai/* → LLM Provider API
                         ↑ reads config from request headers
```

**Rate limiting:** Client-side debounce (staleness checks batch per tab load, not per card). Server-side: max 10 requests/minute per session.

**Error handling:** On LLM failure, features degrade silently. No error modals. Toast with "AI analysis unavailable" if user explicitly triggered it (Skill Analyzer). Background features (staleness, classification) simply do not show results.

### Fallback Behavior Summary

| Feature | With LLM | Without LLM |
|---------|----------|-------------|
| Smart Upload | AI-extracted metadata pre-filled | Blank fields, filename as title |
| Skill Analyzer | Quality scores + fix suggestions | Button hidden entirely |
| Memory Hygiene | Duplicate/contradiction detection | Banner never appears |
| Content Classification | AI classification + confidence | Rule-based heuristic only |
| Staleness Check | Content-aware temporal analysis | Date-based "not updated in X months" |

**The product is fully functional without LLM configuration.** AI features are additive polish, not core dependencies.

---

## Features Explicitly Deferred

| Feature | Why Deferred |
|---------|-------------|
| **AI skill generation** | Agent's job, not the console's. The user's insight: "generating skills is agent work." |
| **Memory summarization** | Summarizing agent memories adds a layer of interpretation. The human should read what the agent actually wrote. |
| **Semantic search** | Requires embedding model + vector storage. Different infrastructure. V2. |
| **Knowledge optimization** ("make this shorter for agents") | High value but complex UX (before/after diff review). V1.2. |
| **Cross-content linking** ("this memory references that doc") | Requires analyzing all content together. Expensive, unclear next action. V2. |
| **Importance re-scoring** ("this memory should rank higher") | Agent should own its own scoring. Human can comment to influence. |
| **Skill usage comparison** ("this skill vs that skill") | Needs usage analytics pipeline that does not exist yet. V2. |
| **Coverage analysis** ("your agent has skills but no supporting docs") | Interesting but fails the "so what" test — unclear action. V2. |
| **Completeness check for knowledge** ("this doc is missing X section") | Nice but low urgency. The staleness check covers the most common case. V1.2. |

---

*Five AI features. Each one reveals something hidden, offers a clear next action, and disappears when not needed. The product works without them. It works better with them.*
