1 Commits

Author SHA1 Message Date
Alexandre Teixeira cb6c28113a docs(discovery): publish provisional feature baseline 2026-07-26 12:44:34 +01:00
62 changed files with 9979 additions and 1322 deletions
-1
View File
@@ -189,7 +189,6 @@ SEARXNG_INSTANCE=http://localhost:8080
# ODYSSEUS_EMAIL_COMPOSE_UPLOAD_MAX_BYTES=26214400 # email compose attachment (25 MB)
# ODYSSEUS_STT_MAX_AUDIO_BYTES=26214400 # speech-to-text audio (25 MB)
# ODYSSEUS_ICS_MAX_BYTES=10485760 # calendar .ics import (10 MB)
# ODYSSEUS_TTS_CACHE_MAX_BYTES=524288000 # TTS cache (500 MB)
# ============================================================
# Host Docker access (explicit opt-in)
+3 -10
View File
@@ -153,16 +153,6 @@ module.exports = async ({ github, context, core }) => {
}
}
const LABEL_BAD = 'needs more info';
const LABEL_GOOD = 'ready for review';
// Closed issues are no longer awaiting review.
// This also prevents later edits to closed issues from restoring the label.
if (issue.state === 'closed') {
await dropLabel(LABEL_GOOD);
return;
}
// ── Find existing bot comment to update in-place ──────────────────────────
const MARKER = '<!-- issue-description-check -->';
const { data: comments } = await github.rest.issues.listComments({
@@ -170,6 +160,9 @@ module.exports = async ({ github, context, core }) => {
});
const existing = comments.find(c => c.user.type === 'Bot' && c.body.includes(MARKER));
const LABEL_BAD = 'needs more info';
const LABEL_GOOD = 'ready for review';
if (failures.length === 0) {
if (existing) {
await github.rest.issues.deleteComment({ owner, repo, comment_id: existing.id });
@@ -2,7 +2,7 @@ name: ci / issue description check
on:
issues:
types: [opened, edited, reopened, closed]
types: [opened, edited, reopened]
permissions:
issues: write
+3 -3
View File
@@ -692,7 +692,7 @@ from routes.history.history_routes import setup_history_routes
app.include_router(setup_history_routes(session_manager, upload_handler=upload_handler))
# Search
from routes.search.search_routes import setup_search_routes
from routes.search_routes import setup_search_routes
app.include_router(setup_search_routes(config))
# Presets
@@ -820,7 +820,7 @@ set_ai_rag_manager(rag_manager, personal_docs_mgr)
logger.info("AI interaction tools initialized (session, memory, RAG, UI control)")
# Webhooks
from routes.webhook.webhook_routes import setup_webhook_routes
from routes.webhook_routes import setup_webhook_routes
app.include_router(setup_webhook_routes(webhook_manager, auth_manager, session_manager, api_key_manager))
# API Tokens
@@ -852,7 +852,7 @@ app.include_router(setup_codex_routes(
))
app.include_router(setup_claude_routes())
from routes.vault.vault_routes import setup_vault_routes
from routes.vault_routes import setup_vault_routes
app.include_router(setup_vault_routes())
# Contacts (CardDAV)
-1
View File
@@ -67,7 +67,6 @@ services:
- ODYSSEUS_EMAIL_COMPOSE_UPLOAD_MAX_BYTES=${ODYSSEUS_EMAIL_COMPOSE_UPLOAD_MAX_BYTES:-26214400}
- ODYSSEUS_STT_MAX_AUDIO_BYTES=${ODYSSEUS_STT_MAX_AUDIO_BYTES:-26214400}
- ODYSSEUS_ICS_MAX_BYTES=${ODYSSEUS_ICS_MAX_BYTES:-10485760}
- ODYSSEUS_TTS_CACHE_MAX_BYTES=${ODYSSEUS_TTS_CACHE_MAX_BYTES}
- DATA_BRAVE_API_KEY=${DATA_BRAVE_API_KEY:-}
- GOOGLE_API_KEY=${GOOGLE_API_KEY:-}
- GOOGLE_PSE_CX=${GOOGLE_PSE_CX:-}
-1
View File
@@ -66,7 +66,6 @@ services:
- ODYSSEUS_EMAIL_COMPOSE_UPLOAD_MAX_BYTES=${ODYSSEUS_EMAIL_COMPOSE_UPLOAD_MAX_BYTES:-26214400}
- ODYSSEUS_STT_MAX_AUDIO_BYTES=${ODYSSEUS_STT_MAX_AUDIO_BYTES:-26214400}
- ODYSSEUS_ICS_MAX_BYTES=${ODYSSEUS_ICS_MAX_BYTES:-10485760}
- ODYSSEUS_TTS_CACHE_MAX_BYTES=${ODYSSEUS_TTS_CACHE_MAX_BYTES}
- DATA_BRAVE_API_KEY=${DATA_BRAVE_API_KEY:-}
- GOOGLE_API_KEY=${GOOGLE_API_KEY:-}
- GOOGLE_PSE_CX=${GOOGLE_PSE_CX:-}
-1
View File
@@ -55,7 +55,6 @@ services:
- ODYSSEUS_EMAIL_COMPOSE_UPLOAD_MAX_BYTES=${ODYSSEUS_EMAIL_COMPOSE_UPLOAD_MAX_BYTES:-26214400}
- ODYSSEUS_STT_MAX_AUDIO_BYTES=${ODYSSEUS_STT_MAX_AUDIO_BYTES:-26214400}
- ODYSSEUS_ICS_MAX_BYTES=${ODYSSEUS_ICS_MAX_BYTES:-10485760}
- ODYSSEUS_TTS_CACHE_MAX_BYTES=${ODYSSEUS_TTS_CACHE_MAX_BYTES}
- DATA_BRAVE_API_KEY=${DATA_BRAVE_API_KEY:-}
- GOOGLE_API_KEY=${GOOGLE_API_KEY:-}
- GOOGLE_PSE_CX=${GOOGLE_PSE_CX:-}
+62
View File
@@ -0,0 +1,62 @@
# Discovery Baseline Status
## Purpose and scope
This package is a commit-pinned discovery baseline and feature index for the `discovery` branch at frozen commit `d8a2059df8e53bc7275c45339849d14c8651e73c`. It inventories **79 feature records** across **16 domains** to help maintainers locate likely implementation areas and identify validation gaps. It is not an authoritative architecture reference or a runtime-certification record.
The canonical inventory is [`feature-catalog.json`](feature-catalog.json); [`feature-catalog.md`](feature-catalog.md) and the files in [`domains/`](domains/) are derived reading views. See [`audit-method.md`](audit-method.md) for the status and maturity definitions.
## What maintainers may use now
- Use the catalog and domain views as a frozen discovery index, including their feature IDs, stated scope, likely source locations, and declared runtime prerequisites.
- Treat a catalog status such as `verified` as meaning implementation was identified during discovery. It does **not** mean every evidence locator, line range, test claim, or runtime behaviour has passed semantic validation.
- Use the structural checks to confirm package shape and cross-view consistency; use the evidence validator to assess whether individual evidence assertions are semantically supported.
## Validation snapshot
Structural validation passes: the catalog has 79 records, the 16 domain views match it, and the package structural validators pass. All 11 focused evidence-validator tests pass.
The evidence validator found **170 evidence entries**: **82 valid**, **66 invalid**, **6 ambiguous**, and **16 unsupported**. Its non-zero exit is expected while those semantic evidence defects remain.
Structural validity checks the documentation schema, record counts, derived-view consistency, file existence, line-range bounds, links, and public-safety rules. Semantic evidence validity additionally checks whether the cited locator exists, falls within its cited range, uses a supported parser, and actually supports the feature claim. Passing the former does not establish the latter.
## E2 review decisions
E2 means directly relevant automated test evidence supports the feature claim; a test files existence alone is insufficient. The generated evidence report was used to reassess all ten E2 records.
| Feature | Decision | Reason |
|---|---|---|
| `CHAT-001` | Retain E2 | Two cited tests directly exercise documented streaming-related behaviour. |
| `MODEL-006` | Retain E2 | The cited device-flow test exercises the Copilot start/poll contract and verification URI. |
| `MODEL-007` | Retain E2 | The cited device-flow test exercises the ChatGPT subscription contract and verification URI. |
| `RESEARCH-003` | Demote to E1 | The cited test covers ranking, not provider connectivity or dispatch; the route-to-provider implementation path was identified. |
| `DOCUMENT-002` | Demote to E1 | The cited marker test does not support form processing or rendering; the document route does call the PDF form handlers. |
| `EMAIL-001` | Demote to E1 | The cited health test is narrower than setup, SMTP, and polling; application setup invokes the email router and its poller. |
| `SECURITY-002` | Demote to E1 | Relevant vault-password tests exist, but the cited test locator is fabricated; the application mounts the vault route implementation. |
| `SECURITY-004` | Demote to E1 | Relevant injection tests exist, but the cited locator names are fabricated; callers use the documented context guard. |
| `SECURITY-005` | Demote to E1 | Relevant guard tests exist, but the cited locator names are fabricated; route code calls the documented URL guard. |
| `PLATFORM-009` | Demote to E0 | The manifests and diagnostic script establish discovered operational artifacts, not a traced application path or directly relevant automated test. |
The current maturity distribution is **E0: 68**, **E1: 8**, **E2: 3**, **E3: 0**, **E4: 0**. Runtime validation is still pending where the catalog says it requires external services, interactive authentication, specialised hardware, or host Docker GPU support.
## Known discovery caveats
- `AGENT-004` includes a legacy no-op activity-log shim rather than active assistant-log behaviour.
- `FRONTEND-007` points to a missing `static/backgrounds.html` target; its existing variant pages do not make that route functional.
- `RESEARCH-003` retains a compatibility module that aliases the canonical search implementation, and `DOCUMENT-002` separates optional PDF viewing from form handling.
- Secret-storage and vault-command handling are distinct implementation areas; this index does not make an end-to-end security guarantee.
## Recommended next documentation work
Repair semantic evidence selectively while architecture and operations documentation is written, beginning with the seven E2 demotions and maintainer-owned feature descriptions. Do not wait for the complete evidence queue before documenting the system. Record controlled runtime observations when external services, credentials, hardware, or Docker GPU access are available, and label unsupported claims explicitly.
## Validation commands
```bash
PYTHONDONTWRITEBYTECODE=1 python3 docs/discovery/tools/validate_discovery_docs.py --repo-root .
PYTHONDONTWRITEBYTECODE=1 python3 docs/discovery/tools/validate_discovery_consistency.py
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest docs/discovery/tools/test_validate_discovery_evidence.py -v
PYTHONDONTWRITEBYTECODE=1 python3 docs/discovery/tools/validate_discovery_evidence.py --repo-root . --catalog docs/discovery/feature-catalog.json --output-dir <local-report-directory>
```
Supply a local report directory outside `docs/discovery/` for the final command so generated reports are not added to the package.
+21
View File
@@ -0,0 +1,21 @@
# Odysseus Discovery Package
## Provisional discovery baseline
This is a commit-pinned discovery baseline and feature index for the `discovery` branch at `d8a2059df8e53bc7275c45339849d14c8651e73c`. It contains 79 feature records across 16 domains. It is **not** an authoritative architecture reference, a runtime certification, or a claim that every evidence citation is semantically valid.
Read [`BASELINE-STATUS.md`](BASELINE-STATUS.md) first for the publication status, evidence-validation totals, E2 decisions, known caveats, and the recommended next documentation work.
## Package contents
- [`feature-catalog.json`](feature-catalog.json) is the canonical machine-readable catalog.
- [`feature-catalog.md`](feature-catalog.md) and [`domains/`](domains/) are derived reading views.
- [`audit-method.md`](audit-method.md) defines feature status and evidence maturity.
- [`references/source-provenance.md`](references/source-provenance.md) records the frozen snapshot.
- [`tools/`](tools/) contains the structural, consistency, and evidence validators.
A feature status such as `verified` means implementation was identified during discovery. It does not mean every evidence locator, line range, test claim, or runtime behaviour has passed semantic validation.
## Validation
Run the commands in [`BASELINE-STATUS.md`](BASELINE-STATUS.md#validation-commands). Structural checks and semantic evidence checks have different purposes; see that status document for the current results and interpretation.
+80
View File
@@ -0,0 +1,80 @@
# Odysseus Functional Audit Methodology
## Purpose
This document specifies the methodology and evidence standards for the read-only discovery audit of **Odysseus**.
## Snapshot Baseline
- **Repository**: `odysseus-dev/odysseus`
- **Audit Target Branch**: `discovery`
- **Frozen Commit SHA**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Snapshot Date**: `2026-07-23T14:49:02Z`
- **Audit Mode**: Read-Only inventory & documentation review
## Rules of Engagement
1. **No Code Mutations**: Application code and tests outside `docs/discovery/` remain untouched.
2. **No External Operations**: No GitHub issues, PRs, comments, labels, or branch mutations.
3. **Zero Inferred Success**: Documentation claims require empirical evidence of implementation and reachability. Filenames, README descriptions, and docstrings alone do not constitute proof.
4. **Strict Status Categorization**: All capabilities are assigned exactly one authorized status:
- `verified`: Implemented, reachable, and supported by code evidence.
- `partial`: Partially implemented or missing full frontend/backend connection.
- `disabled`: Gated off by default feature flags or configuration.
- `experimental`: Active but requiring non-standard hardware or runtimes.
- `legacy`: Obsolete feature retained for backwards compatibility.
- `dead-code-candidate`: Code exists but is unreachable from UI or API routes.
- `unverified`: Implementation present but untestable without external secrets or hardware.
## Evidence Maturity Scale
Evidence maturity is evaluated independently from catalog feature status. A feature status such as `verified` records that implementation was identified during discovery; it is not a statement that every evidence locator, test claim, line range, or runtime behaviour has passed semantic validation.
- **E0 - Discovered**: Candidate identified in documentation, route declaration, or source file.
- **E1 - Code-path traced**: Frontend/API entry point connected through services and data handlers.
- **E2 - Test-backed**: At least one directly relevant automated test assertion supports the feature claim. A test file's existence, an unrelated assertion, or an invalid test locator does not establish E2.
- **E3 - Runtime-validated**: Maintainer reproduced behavior in a recorded local environment.
- **E4 - Maintainer-accepted**: Maintainers accepted the feature description and support status.
## Audit Workflow
```mermaid
flowchart TD
P0["Phase 0: Snapshot Isolation<br/>(Commit d8a2059)"] --> P1["Phase 1: Codebase Discovery<br/>(Routes, Services, Static JS, Specs)"]
P1 --> P2["Phase 2: Feature Reachability & Verification<br/>(Route matching, FE entrypoints, tests)"]
P2 --> P3["Phase 3: Catalog & Evidence Compilation<br/>(File paths, symbols, exact line ranges)"]
P3 --> P4["Phase 4: Quality & Integrity Audit<br/>(100% path existence check, schema validation)"]
```
### Phase 0: Snapshot Isolation
The audit is pinned to git commit `d8a2059df8e53bc7275c45339849d14c8651e73c`. All file paths, symbol declarations, and line ranges map strictly to this commit.
### Phase 1: Codebase Discovery
All top-level and nested directories were traversed, including:
- Backend Entry Points (`app.py`, `routes/`, `routes/*/*.py`, `companion/`)
- Core Framework (`core/database.py`, `core/session_manager.py`, `core/auth.py`)
- Business Logic Services (`src/`, `services/`, `mcp_servers/`)
- Frontend Assets (`static/app.js`, `static/js/`, `static/index.html`)
- Test Suites (`tests/`, `tests/cli/`, `tests/streaming/`)
- Operations & Docker (`Dockerfile`, `docker-compose*.yml`, `scripts/`)
### Phase 2: Verification Protocol
For each feature candidate, the following table was evaluated:
- **User Reachability**: Frontend UI element, modal, route, or CLI script.
- **API Entrypoint**: FastAPI `@router` declaration or WebSocket/SSE handler.
- **Backend Execution**: Concrete Python module method, service, or tool call.
- **Data Persistence**: Disk file, SQLite table, or vector collection.
- **Test Coverage**: Automated test file executing assertions against the component.
### Phase 3: Evidence Linking Standard
Every feature entry in `feature-catalog.json` contains a structured `evidence` list with:
- `path`: Relative path from repository root.
- `symbol`: Route, class, function, or element symbol name.
- `line_range`: Inclusive line range (e.g. `L120-L250`).
- `explanation`: Short factual statement proving reachability or implementation.
### Phase 4: Quality Check & Schema Constraints
Before finalization:
1. Every evidence file path is validated against the checkout.
2. Every Markdown entry matches `feature-catalog.json`.
3. Recommendation language is separated from empirical factual observations.
+153
View File
@@ -0,0 +1,153 @@
# Agent
Features in this document are generated from [`../feature-catalog.json`](../feature-catalog.json), the canonical inventory.
## AGENT-001 — Autonomous Agent Loop & Tool Execution Engine
- **Domain**: `agent`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Executes multi-step agent reasoning loops, tool invocation parsing, and automated response generation.
### Evidence summary
- `src/agent_loop.py``run_agent_loop` — Core loop evaluating model tool requests and executing handlers.
- `src/tool_execution.py``execute_tool_call` — Dispatches tool invocation requests to underlying tool handlers.
### Unknowns
- Infinite tool loop if termination condition fails.
## AGENT-002 — Scheduled Tasks & Event Bus Dispatcher
- **Domain**: `agent`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Schedules background recurring or delayed tasks, emits event bus triggers, and executes automated flows.
### Evidence summary
- `routes/task_routes.py``@router.get('')` — Fetches active scheduled tasks.
- `src/task_scheduler.py``TaskScheduler` — Async task scheduler dispatching cron and delay triggers.
### Unknowns
- Task execution failure handling on system restart.
## AGENT-003 — Webhook Event Subscriptions & Trigger Processing
- **Domain**: `agent`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Manages incoming/outgoing webhook subscriptions, endpoint authentication tokens, and event triggers.
### Evidence summary
- `routes/webhook_routes.py``@router.get('/webhooks')` — Returns list of registered webhooks.
- `src/webhook_manager.py``WebhookManager` — Handles payload delivery and signature verification.
### Unknowns
- SSRF risks when contacting external webhook URLs if unvalidated.
## AGENT-004 — Assistant Settings, Task Check-Ins & Background Job Monitor
- **Domain**: `agent`
- **Status**: `partial`
- **Evidence Maturity**: `E1`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Manages per-user assistant sessions and scheduled check-in settings, drains background job completions, and retains a legacy no-op activity logging shim.
### Evidence summary
- `routes/assistant_routes.py``setup_assistant_routes` — Active assistant session, settings, manual check-in, run-status and timezone-list endpoints, including the owner-scoping guards.
- `src/bg_monitor.py``_drain_agent` — Runs the agent loop headless against a session to produce the background-job follow-up turn.
- `src/bg_monitor.py``_run_followup` — Drains completed background jobs and auto-continues the owning session, deferring while a live turn is in progress.
- `src/assistant_log.py``log_to_assistant` — Legacy no-op activity logging shim retained for existing callers; documented as inactive rather than as current behaviour.
### Unknowns
- Route `/api/assistant/logs` cited in legacy docs is absent from assistant router.
- Existing unit test `tests/cli/test_logs_cli_resolve_nonstring.py` tests CLI target-name resolution logic, not active assistant routes or bg_monitor execution loop.
## AGENT-005 — Model Context Protocol (MCP) Server Integration
- **Domain**: `agent`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Integrates external MCP servers over stdio/SSE to expand agent capabilities dynamically.
### Evidence summary
- `routes/mcp_routes.py``setup_mcp_routes` — Exposes management endpoints for external MCP servers.
- `src/mcp_manager.py``McpManager` — Manages MCP server subprocess lifecycles.
### Unknowns
- Subprocess leaks if external MCP server process fails to terminate clean.
## AGENT-006 — AI Interaction Tools & Pipeline Orchestration
- **Domain**: `agent`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Provides specialized AI interaction tools for agent self-debugging, debate, and multi-model collaboration.
### Evidence summary
- `src/ai_interaction.py``init_ai_interaction_tools` — Registers specialized multi-agent interaction primitives.
- `src/builtin_actions.py``execute_builtin_action` — Executes pre-built action intent sequences.
### Unknowns
- High API token consumption during extended agent debates.
## AGENT-007 — Subprocess & Background Job Execution Tools
- **Domain**: `agent`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Provides sandboxed bash/shell tool execution capabilities with output streaming and background tracking.
### Evidence summary
- `src/agent_tools/subprocess_tools.py``run_command` — Executes shell commands in background/foreground.
- `src/bg_jobs.py``JobManager` — Tracks async background subprocess tasks.
### Unknowns
- Arbitrary shell command execution permissions if sandbox confinement fails.
+45
View File
@@ -0,0 +1,45 @@
# Calendar
Features in this document are generated from [`../feature-catalog.json`](../feature-catalog.json), the canonical inventory.
## CALENDAR-001 — CalDAV Calendar Synchronization & Account Setup
- **Domain**: `calendar`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: pending — Requires a controlled external CalDAV server.
### Purpose
Connects to remote CalDAV servers (Apple iCloud, Nextcloud, Google) to sync calendar event feeds.
### Evidence summary
- `routes/calendar_routes.py``setup_calendar_routes` — Exposes CalDAV setup and manual sync trigger routes.
- `src/caldav_sync.py``CalDavSync` — Fetches and parses remote iCalendar VEVENT objects.
### Unknowns
- Invalid SSL certificates on self-hosted CalDAV servers.
## CALENDAR-002 — Calendar Event Operations & iCalendar Parsing
- **Domain**: `calendar`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Creates, updates, deletes, and displays calendar events with timezone conversion and reminder notifications.
### Evidence summary
- `routes/calendar_routes.py``@router.get('/events')` — Fetches calendar events for requested date window.
- `src/tools/calendar.py``CalendarTool` — Agent tool for creating and modifying calendar entries.
### Unknowns
- Recurring RRULE event expansion calculation bugs across leap years.
+197
View File
@@ -0,0 +1,197 @@
# Chat
Features in this document are generated from [`../feature-catalog.json`](../feature-catalog.json), the canonical inventory.
## CHAT-001 — Core Chat Streaming & SSE Message Generation
- **Domain**: `chat`
- **Status**: `verified`
- **Evidence Maturity**: `E2`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: pending — Requires access to a live LLM provider endpoint (OpenAI API key or local Ollama server).
### Purpose
Handles real-time Server-Sent Events (SSE) chat streaming, token rendering, and model response generation.
### Evidence summary
- `routes/chat_routes.py``chat_stream` — POST /api/chat_stream SSE endpoint; builds the shared chat context, then dispatches to the chat-mode or agent-mode streaming path.
- `routes/chat_helpers.py``build_chat_context` — Shared context builder invoked by chat_stream; runs message preprocessing and assembles the memory/RAG/web context preface.
- `src/chat_handler.py``ChatHandler.preprocess_message` — Message preprocessing (attachments, URLs, tool preprocessing) reached from build_chat_context via routes/chat_helpers.py:preprocess.
- `src/chat_processor.py``ChatProcessor.build_context_preface` — Builds the retrieval and web-source context preface injected into the streamed request.
- `src/llm_core.py``stream_llm_with_fallback` — Chat-mode streaming dispatcher called from chat_stream; wraps stream_llm with an ordered provider fallback chain.
- `src/llm_core.py``stream_llm` — Per-request streaming entry wrapped by stream_llm_with_fallback; acquires the local model slot and delegates to _stream_llm_inner.
- `src/agent_loop.py``stream_agent_loop` — Agent-mode streaming path called from chat_stream when the request selects agent mode.
- `tests/test_chat_metrics.py``test_stream_llm_passes_through_llamacpp_timings` — Inspected unit test asserting stream_llm forwards backend generation timings into the emitted metrics chunk.
- `tests/test_resend_message_nondestructive.py``test_resend_message_does_not_truncate_by_default` — Inspected unit test asserting the frontend resend path does not truncate prior conversation turns.
### Unknowns
- Stream interruption on connection drops requires retry logic.
## CHAT-002 — Session Management & Conversation State
- **Domain**: `chat`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Manages session creation, listing, switching, renaming, and persistence of conversation metadata.
### Evidence summary
- `routes/session_routes.py``@router.get('/api/sessions')` — Lists active sessions filtered by user owner scope.
- `core/session_manager.py``SessionManager` — Provides thread-safe session storage operations.
### Unknowns
- Concurrent file writes to sessions.json under high load.
## CHAT-003 — Chat History & Message Editing/Truncation
- **Domain**: `chat`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Provides history retrieval, message content updating, message deletion, and history branch truncation.
### Evidence summary
- `routes/history/history_routes.py``@router.get('/api/history/{session_id}')` — Fetches message history timeline for a session.
- `routes/history_routes.py``_sys.modules[__name__] = _canonical` — Backward-compatibility shim module.
### Unknowns
- Truncating messages re-indexes context window and clears cached tool calls.
## CHAT-004 — File & Multimodal Attachment Handling
- **Domain**: `chat`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Handles uploading, mime validation, image preview, vision encoding, and file attachments in chat messages.
### Evidence summary
- `routes/upload_routes.py``@router.post('')` — Accepts multi-part file uploads and generates vision metadata.
- `src/upload_handler.py``UploadHandler.save_file` — Validates upload size and atomicity on disk.
### Unknowns
- Large file uploads may consume server disk space if cleanup task fails.
## CHAT-005 — Chat Message Search
- **Domain**: `chat`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Enables full-text keyword search across stored chat messages and sessions.
### Evidence summary
- `routes/search_routes.py``setup_search_routes` — Registers chat message search endpoint.
- `src/session_search.py``search_sessions` — Executes query matching against session transcripts.
### Unknowns
- Full table scans on un-indexed text columns for very large databases.
## CHAT-006 — System Prompts & Preset Management
- **Domain**: `chat`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Provides creation, selection, and customization of system prompt presets for chat sessions.
### Evidence summary
- `routes/preset_routes.py``setup_preset_routes` — API routes for listing and modifying system prompt presets.
- `src/preset_manager.py``PresetManager` — Disk-backed manager for prompt presets.
### Unknowns
- Invalid JSON syntax in user presets file can corrupt preset loading.
## CHAT-007 — Emoji Rendering & Twemoji SVG Proxy
- **Domain**: `chat`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Proxies Twemoji SVG icons locally to render flat SVG emojis in message text without external CDN dependencies.
### Evidence summary
- `routes/emoji_routes.py``setup_emoji_routes` — Serves locally cached Twemoji SVGs.
### Unknowns
- First request fetches SVG from remote CDN before caching locally.
## CHAT-008 — Input History Recall (Arrow Up)
- **Domain**: `chat`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Allows users to cycle through previously sent prompt messages in the chat composer input using Arrow-Up/Down keys.
### Evidence summary
- `static/js/composerArrowUpRecall.js``initComposerRecall` — Listens for ArrowUp keypress on composer textarea.
### Unknowns
- Client-side browser storage limits.
## CHAT-009 — Context Window Compaction & Truncation
- **Domain**: `chat`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Compacts session transcript history when prompt size exceeds context limits using summarization.
### Evidence summary
- `routes/history/history_routes.py``@router.post('/api/session/{session_id}/compact')` — Triggers context summarization and compaction.
- `src/context_compactor.py``compact_context` — Executes context token pruning and summary generation.
### Unknowns
- Aggressive compaction may discard subtle user instructions.
+24
View File
@@ -0,0 +1,24 @@
# Contact
Features in this document are generated from [`../feature-catalog.json`](../feature-catalog.json), the canonical inventory.
## CONTACT-001 — CardDAV Contact Management & Address Book Integration
- **Domain**: `contact`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Connects to CardDAV servers, imports VCard contacts, and provides contact lookup for email/calendar autocomplete.
### Evidence summary
- `routes/contacts/contacts_routes.py``@router.get('/list')` — Returns contact list filtered by search query.
- `src/tools/contacts.py``ContactsTool` — Agent tool for querying user address book contacts.
### Unknowns
- VCard 3.0 vs 4.0 property parsing mismatches.
+85
View File
@@ -0,0 +1,85 @@
# Cookbook
Features in this document are generated from [`../feature-catalog.json`](../feature-catalog.json), the canonical inventory.
## COOKBOOK-001 — Local Model Download & Recipe Lifecycle Management
- **Domain**: `cookbook`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Downloads HuggingFace models, configures execution parameters, and manages local GGUF/MLX model servers.
### Evidence summary
- `routes/cookbook_routes.py``setup_cookbook_routes` — Exposes model downloading and process serving endpoints.
- `static/js/cookbook.js``initCookbook` — UI manager for local model library.
### Unknowns
- Disk space exhaustion during multi-gigabyte GGUF weights downloads.
## COOKBOOK-002 — Hardware Model Fitting ('What Fits?') Analysis Engine
- **Domain**: `cookbook`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Calculates RAM/VRAM requirements, quantized size, and context overhead to determine model compatibility.
### Evidence summary
- `routes/hwfit_routes.py``setup_hwfit_routes` — Calculates hardware model compatibility.
- `services/hwfit/fit.py``calculate_fit` — Performs parameter and memory fit calculations.
### Unknowns
- Inaccurate VRAM estimation for non-standard KV-cache quantization.
## COOKBOOK-003 — HuggingFace & MLX Model Discovery Services
- **Domain**: `cookbook`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Searches HuggingFace Hub and local MLX model repositories for compatible GGUF and MLX weights.
### Evidence summary
- `services/hwfit/hf_discovery.py``search_hf_models` — Queries HuggingFace API for model tags and files.
### Unknowns
- HuggingFace API rate limits when searching without an API token.
## COOKBOOK-004 — Host Docker Access for Inference Container Runtimes
- **Domain**: `cookbook`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: pending — Requires Docker access and supported physical GPU hardware.
### Purpose
Detects and connects to host Docker engine to launch containerized Ollama, vLLM, or SGLang runtimes.
### Evidence summary
- `src/host_docker_access.py``HostDockerAccess` — Interacts with host docker daemon.
### Unknowns
- Permission denied accessing docker socket on non-root setups.
+108
View File
@@ -0,0 +1,108 @@
# Document
Features in this document are generated from [`../feature-catalog.json`](../feature-catalog.json), the canonical inventory.
## DOCUMENT-001 — Document & Canvas Artifact Management
- **Domain**: `document`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Renders dynamic canvas documents, handles live editing, markdown preview, and side-by-side artifact display.
### Evidence summary
- `routes/document_routes.py``setup_document_routes` — Registers document artifact CRUD routes.
- `static/js/document.js``initDocumentView` — Renders interactive canvas document panel.
### Unknowns
- Concurrent edits on the same document artifact.
## DOCUMENT-002 — PDF Form Processing & High-Fidelity Rendering
- **Domain**: `document`
- **Status**: `verified`
- **Evidence Maturity**: `E1`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: pending — Requires optional PyMuPDF (`fitz`) or pypdf runtime dependency.
### Purpose
Extracts form fields from PDF files, fills dynamic values, and generates PDF previews.
### Evidence summary
- `src/pdf_runtime.py``load_pymupdf_for_pdf_viewer` — Loads optional PyMuPDF runtime for PDF viewing.
- `src/pdf_forms.py``extract_form_fields` — Handles PDF form field extraction and filling.
- `tests/test_document_pdf_marker.py``test_marker_removed_without_eating_following_text` — Tests PDF text extraction wrapper stripping without content corruption.
### Unknowns
- Complex XFA PDF forms may not extract cleanly with standard pdf parsers.
## DOCUMENT-003 — Personal Document Indexing & RAG Retrieval
- **Domain**: `document`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Indexes local user documents (PDF, DOCX, TXT) into ChromaDB for semantic vector retrieval.
### Evidence summary
- `routes/personal_routes.py``setup_personal_routes` — Personal document RAG indexing and search API endpoints.
- `src/personal_docs.py``PersonalDocsManager` — Handles file text chunking and vector storage.
### Unknowns
- Slow vector embedding indexing step for massive multi-thousand page documents.
## DOCUMENT-004 — Document Conversion & Text Extraction Engine
- **Domain**: `document`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Converts office formats (.docx, .xlsx, .pptx) and HTML into clean Markdown text representations.
### Evidence summary
- `src/markitdown_runtime.py``convert_to_markdown` — Converts binary office documents into structured Markdown text.
### Unknowns
- Formatting loss when parsing legacy binary doc/xls files.
## DOCUMENT-005 — Document Library UI Navigation
- **Domain**: `document`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Provides dedicated UI view for browsing, filtering, and organizing saved user documents.
### Evidence summary
- `static/js/documentLibrary.js``initDocumentLibrary` — Renders document library navigation grid.
- `app.py``serve_library` — Serves SPA shell for /library route.
### Unknowns
- Large folder trees may cause initial DOM render slowdown.
+87
View File
@@ -0,0 +1,87 @@
# Email
Features in this document are generated from [`../feature-catalog.json`](../feature-catalog.json), the canonical inventory.
## EMAIL-001 — Email Account Setup, IMAP/SMTP Connection & Polling
- **Domain**: `email`
- **Status**: `verified`
- **Evidence Maturity**: `E1`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: pending — Requires a controlled live IMAP account and network access.
### Purpose
Configures IMAP/SMTP email accounts, validates TLS certificates, and polls background inbox updates.
### Evidence summary
- `routes/email_routes.py``setup_email_routes` — Sets up email account management and synchronization routes.
- `routes/email_pollers.py``_start_poller` — Background poller for email inbox synchronization.
- `tests/test_service_health_email.py``test_email_ok_all_connect` — Tests IMAP connection health probing and status reporting.
### Unknowns
- Account lockouts if bad credentials are repeatedly polled.
## EMAIL-002 — Email Searching, Threading & Message Operations
- **Domain**: `email`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Parses email headers, folds signatures, groups messages into threads, and executes full-text email search.
### Evidence summary
- `routes/email_routes.py``@router.get('/search')` — Executes search across cached email headers and text.
- `src/email_thread_parser.py``parse_email_thread` — Builds conversation tree from Message-ID and In-Reply-To headers.
### Unknowns
- Malformed MIME email structures failing HTML sanitization.
## EMAIL-003 — Email Composition, Draft Management & Sending
- **Domain**: `email`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: pending — Requires a controlled live SMTP account and network access.
### Purpose
Creates, saves, and dispatches HTML/plaintext email messages via SMTP.
### Evidence summary
- `routes/email_routes.py``@router.post('/send')` — Sends email message via user SMTP credentials.
### Unknowns
- SMTP connection drop mid-send causing unsent mail state.
## EMAIL-004 — Email MCP Server & Codex Integration Bridge
- **Domain**: `email`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Exposes constrained email reading and draft capabilities to external Codex / MCP agents with scope checks.
### Evidence summary
- `mcp_servers/email_server.py``EmailMcpServer` — MCP server exposing email tools over stdio/SSE.
- `routes/codex_routes.py``setup_codex_routes` — Bridge endpoints for external Codex plugin integration.
### Unknowns
- Unauthorized mail sending if token scopes are improperly scoped.
+149
View File
@@ -0,0 +1,149 @@
# Frontend
Features in this document are generated from [`../feature-catalog.json`](../feature-catalog.json), the canonical inventory.
## FRONTEND-001 — Single Page Application Shell & Client Router
- **Domain**: `frontend`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Main HTML5 SPA shell, DOM lifecycle initializers, tab navigation, and deep-link route handlers.
### Evidence summary
- `static/index.html``index.html` — Main SPA entry point containing modal roots and CSS bundles.
- `app.py``serve_index` — Serves index.html with dynamically generated CSP nonces.
### Unknowns
- Stale browser static cache if asset hashing is omitted during deployment.
## FRONTEND-002 — Dynamic Theme, Color System & Custom Fonts
- **Domain**: `frontend`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Supports dark/light themes, custom CSS variables, color picker controls, and user font uploads.
### Evidence summary
- `static/js/theme.js``applyTheme` — Applies custom HSL theme variables to DOM document root.
- `routes/font_routes.py``setup_font_routes` — Allows uploading and serving custom WOFF2 font files.
### Unknowns
- Flash of unstyled content (FOUC) on slow connections.
## FRONTEND-003 — Window Manager, Tile Layout & Modal Control System
- **Domain**: `frontend`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Manages draggable tool windows, snapped multi-tile viewports, modal dialog Z-ordering, and ESC key stacks.
### Evidence summary
- `static/js/modalManager.js``ModalManager` — Controls modal open/close transitions and focus trapping.
- `static/js/tileManager.js``TileManager` — Handles viewport split-pane grid arrangements.
### Unknowns
- Overlap artifacts when opening many simultaneous tool floating windows.
## FRONTEND-004 — Global Keyboard Shortcuts & Accessibility Controls
- **Domain**: `frontend`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Provides configurable hotkeys (Ctrl+K search, Esc close, Alt+1-9 tabs) and high-contrast accessibility options.
### Evidence summary
- `static/js/keyboard-shortcuts.js``initShortcuts` — Binds global keydown handlers for system shortcuts.
- `static/js/a11y.js``initA11y` — Applies ARIA roles and dyslexic font toggles.
### Unknowns
- Browser keybinding collisions with browser default hotkeys.
## FRONTEND-005 — Markdown, LaTeX & Code Block Streaming Renderer
- **Domain**: `frontend`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Parses incoming SSE markdown streams, renders KaTeX math formulas, syntax-highlighted code, and interactive runners.
### Evidence summary
- `static/js/markdown.js``renderMarkdown` — Converts markdown prose to HTML nodes with syntax highlighting.
- `static/js/streamingSegmenter.js``Segmenter` — Parses un-closed markdown fences during live stream.
### Unknowns
- DOM thrashing if streaming segmenter updates UI too frequently.
## FRONTEND-006 — Interactive Tour & Guided Onboarding System
- **Domain**: `frontend`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Presents interactive step-by-step feature tours and UI tooltip hints for new users.
### Evidence summary
- `static/js/tourHints.js``startTour` — Renders guided feature tour overlays over target UI elements.
### Unknowns
- Tour step misalignment if window is resized mid-tour.
## FRONTEND-007 — Background Effects Prototyping Sandbox
- **Domain**: `frontend`
- **Status**: `dead-code-candidate`
- **Evidence Maturity**: `E1`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Standalone sandbox page for prototyping visual background animations, waves, and whirlpool effects.
### Evidence summary
- `app.py``serve_backgrounds` — Serves visual background sandbox HTML page route.
- `static/wave-variants.html``wave-variants.html` — Interactive background effect prototyping sandbox variant.
### Unknowns
- Route `/backgrounds` in app.py L918 attempts to serve `static/backgrounds.html` which is missing from disk; variant templates `wave-variants.html` and `whirlpool-variants.html` exist.
+170
View File
@@ -0,0 +1,170 @@
# Media
Features in this document are generated from [`../feature-catalog.json`](../feature-catalog.json), the canonical inventory.
## MEDIA-001 — Gallery Image Library & Album Operations
- **Domain**: `media`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Organizes images into custom albums, provides grid browsing, tagging, and album metadata management.
### Evidence summary
- `routes/gallery/gallery_routes.py``@router.get('/api/gallery/library')` — Fetches image library list with tag filters.
- `static/js/gallery.js``initGallery` — Main gallery grid renderer and uploader.
### Unknowns
- Thumbnail generation overhead for high-resolution RAW camera images.
## MEDIA-002 — Image Processing, AI Upscaling & Style Transfer
- **Domain**: `media`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Executes local image enhancement, background removal, face sharpening, and AI upscaling operations.
### Evidence summary
- `routes/gallery/gallery_routes.py``@router.post('/api/gallery/ai-upscale')` — Runs RealESRGAN image upscaling.
- `routes/gallery/gallery_routes.py``@router.post('/api/image/remove-bg')` — Executes background removal pass.
### Unknowns
- High GPU memory allocation when upscaling 4K images.
## MEDIA-003 — Interactive Image Canvas Editor & Persisted Drafts
- **Domain**: `media`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Provides full multi-layer raster canvas editor, brush tools, transforms, masks, and draft project persistence.
### Evidence summary
- `routes/editor_draft_routes.py``setup_editor_draft_routes` — API routes for saving and loading canvas project drafts.
- `static/js/editor/history-panel.js``HistoryManager` — Canvas undo/redo stack manager.
### Unknowns
- Browser memory leak if multi-gigabyte layer undo buffers are kept indefinitely.
## MEDIA-004 — Text-to-Speech (TTS) Synthesis Service
- **Domain**: `media`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Synthesizes spoken audio from text using local Kokoro, EdgeTTS, or OpenAI TTS engines.
### Evidence summary
- `routes/tts_routes.py``@router.post('/synthesize')` — Synthesizes TTS audio clip.
- `services/tts/tts_service.py``TTSService` — Provider abstraction layer for audio speech generation.
### Unknowns
- Audio synthesis latency on CPU-only hardware setups.
## MEDIA-005 — Speech-to-Text (STT) Audio Transcription Service
- **Domain**: `media`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Transcribes user audio recordings into text using faster-whisper or local speech models.
### Evidence summary
- `routes/stt_routes.py``@router.post('/transcribe')` — Accepts multipart audio file and returns transcription text.
- `services/stt/stt_service.py``STTService` — Whisper audio transcription engine wrapper.
### Unknowns
- Missing ffmpeg system dependency prevents audio format decoding.
## MEDIA-006 — Digital Signature Stamp Storage & Placement
- **Domain**: `media`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Stores transparent PNG user signatures and stamps for placement onto PDF forms and documents.
### Evidence summary
- `routes/signature_routes.py``setup_signature_routes` — CRUD endpoints for managing user signature PNG stamps.
### Unknowns
- Cross-site scripting if signature image titles contain unescaped user input.
## MEDIA-007 — Generated Image Artifact Route & MCP Integration
- **Domain**: `media`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Serves generated AI artwork artifacts and integrates with image generation MCP server.
### Evidence summary
- `app.py``serve_generated_image` — Serves generated image artifacts with cache headers.
- `src/generated_images.py``resolve_generated_image_path` — Confines requested image path within artifacts directory.
### Unknowns
- Path traversal vulnerability if filename parameter is un-sanitized.
## MEDIA-008 — Native MLX Image Bridge (macOS Apple Silicon)
- **Domain**: `media`
- **Status**: `experimental`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: pending — Requires Apple Silicon, macOS tooling, and the compiled MLX bridge.
### Purpose
Native Apple Swift bridge for hardware-accelerated diffusion and MLX image colorization on macOS.
### Evidence summary
- `swift/odysseus-mlx-image-bridge/Package.swift``Package` — Swift package manifest for native MLX image bridge.
- `scripts/mlx_image_server.py``main` — Python daemon wrapping native Swift MLX binary.
### Unknowns
- Binary build requires Xcode command line tools build step (`build-macos-app.sh`).
+24
View File
@@ -0,0 +1,24 @@
# Memory
Features in this document are generated from [`../feature-catalog.json`](../feature-catalog.json), the canonical inventory.
## MEMORY-001 — Persistent Long-Term Memory & Vector Indexing
- **Domain**: `memory`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Extracts facts, user preferences, and temporal memories from chat sessions into vector/relational storage.
### Evidence summary
- `routes/memory/memory_routes.py``@router.get('')` — Fetches long-term user memory timeline.
- `services/memory/memory_extractor.py``MemoryExtractor` — LLM-driven fact extraction from conversation transcripts.
### Unknowns
- Conflicting memory facts extracted from contradictory user prompts.
+177
View File
@@ -0,0 +1,177 @@
# Model
Features in this document are generated from [`../feature-catalog.json`](../feature-catalog.json), the canonical inventory.
## MODEL-001 — Multi-Provider LLM Model Discovery & Metadata Management
- **Domain**: `model`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Discovers models from OpenAI, Anthropic, Ollama, vLLM, LMStudio, OpenRouter, and Google AI Studio endpoints.
### Evidence summary
- `routes/model_routes.py``@router.get('/api/models')` — Returns unified list of available models across providers.
- `src/model_discovery.py``ModelDiscovery.discover_all` — Queries connected provider endpoints for available model IDs.
### Unknowns
- Remote endpoint timeouts may slow down full discovery refresh.
## MODEL-002 — Model Capability & Context Limits Detection
- **Domain**: `model`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Detects vision, tool calling, reasoning, and context window limits for connected model endpoints.
### Evidence summary
- `src/model_capabilities.py``get_model_capabilities` — Maps model names to vision and tool support flags.
- `src/endpoint_resolver.py``resolve_endpoint_headers` — Resolves auth headers and target URLs for model endpoints.
### Unknowns
- Incorrect context limit metadata for unlisted custom fine-tunes.
## MODEL-003 — LLM Core Provider Communication & Fallback Routing
- **Domain**: `model`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: pending — Provider dispatch, header injection and fallback advancement are only observable against a reachable LLM provider endpoint; not exercised in this documentation pass.
### Purpose
Manages HTTP request dispatching, authorization header injection, and fallback provider routing for LLM calls.
### Evidence summary
- `src/llm_core.py``llm_call_async` — Non-streaming provider request dispatcher: resolves the endpoint, injects authorization headers and executes the HTTP call.
- `src/llm_core.py``llm_call_async_with_fallback` — Ordered fallback wrapper that retries llm_call_async across the configured candidate endpoints.
- `src/llm_core.py``stream_llm_with_fallback` — Ordered fallback wrapper for the streaming path; advances to the next candidate when a provider yields an empty completion.
### Unknowns
- Unexpected API changes in upstream third-party model providers.
## MODEL-004 — Model Selection & Display Ordering Preferences
- **Domain**: `model`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Allows pinning, sorting, and hiding specific models in the UI selection dropdown.
### Evidence summary
- `routes/model_routes.py``@router.post('/order')` — Saves custom model display order preference.
### Unknowns
- Stale model IDs in custom order lists after model endpoints are removed.
## MODEL-005 — Side-by-Side Model Comparison (A/B Testing)
- **Domain**: `model`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Enables dual-model side-by-side response evaluation, arena scoring, and latency comparison.
### Evidence summary
- `routes/compare/compare_routes.py``@router.post('/start')` — Starts a parallel dual-model comparison stream.
- `static/js/compare/index.js``initCompareView` — Renders side-by-side model chat panes.
### Unknowns
- High memory and network usage when streaming two model responses simultaneously.
## MODEL-006 — GitHub Copilot Device Flow Authentication
- **Domain**: `model`
- **Status**: `verified`
- **Evidence Maturity**: `E2`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: pending — Requires an interactive GitHub Copilot OAuth device-flow account.
### Purpose
Authenticates with GitHub Copilot via OAuth device flow to use Copilot models directly.
### Evidence summary
- `routes/copilot_routes.py``setup_copilot_routes` — Builds the Copilot device-flow router at prefix /api/copilot, wiring _start_device_flow and _poll_device_flow.
- `routes/device_flow.py``create_device_flow_router` — Shared factory registering POST /device/start and POST /device/poll under the caller-supplied prefix.
- `src/copilot.py``request_device_code` — Issues the GitHub device-code request that begins the Copilot OAuth device flow.
- `src/copilot.py``poll_access_token` — Polls GitHub for the access token once the user has authorized the device code.
- `tests/test_provider_device_flow_js.py``test_copilot_success_uses_complete_verification_uri` — Inspected unit test asserting the Copilot device-flow runner surfaces the complete verification URI returned by the backend.
### Unknowns
- Token expiration requires manual device re-authentication.
## MODEL-007 — ChatGPT Subscription Device Flow Authentication
- **Domain**: `model`
- **Status**: `verified`
- **Evidence Maturity**: `E2`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: pending — Requires an interactive ChatGPT subscription OAuth flow.
### Purpose
Authenticates with ChatGPT Pro/Plus subscription tokens via device login flow.
### Evidence summary
- `routes/chatgpt_subscription_routes.py``setup_chatgpt_subscription_routes` — Builds the ChatGPT subscription device-flow router at prefix /api/chatgpt-subscription.
- `routes/device_flow.py``create_device_flow_router` — Shared factory registering POST /device/start and POST /device/poll under the caller-supplied prefix.
- `src/chatgpt_subscription.py``request_device_code` — Issues the ChatGPT device-authorization request that begins the subscription OAuth device flow.
- `src/chatgpt_subscription.py``poll_device_auth` — Polls the ChatGPT device-authorization endpoint for completion using the stored device_auth_id and user_code.
- `tests/test_provider_device_flow_js.py``test_chatgpt_success_uses_plain_verification_uri` — Inspected unit test asserting the ChatGPT device-flow runner uses the plain verification URI rather than the Copilot complete-URI form.
### Unknowns
- Changes in OpenAI auth endpoint security challenges.
## MODEL-008 — Embedding Model Lane & Vector Provider Setup
- **Domain**: `model`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Configures local sentence-transformers, FastEmbed, or remote OpenAI embedding model lanes.
### Evidence summary
- `routes/embedding_routes.py``setup_embedding_routes` — Provides embedding provider configuration endpoints.
- `src/embeddings.py``EmbeddingManager` — Generates dense vector embeddings for RAG and memory.
### Unknowns
- First-time download of heavy PyTorch model weights on CPU-only machines.
+24
View File
@@ -0,0 +1,24 @@
# Note
Features in this document are generated from [`../feature-catalog.json`](../feature-catalog.json), the canonical inventory.
## NOTE-001 — Interactive Notes & Checklist Management
- **Domain**: `note`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Provides Google Keep-style notes, rich markdown text, checklist items, pinning, color tags, and reminders.
### Evidence summary
- `routes/note/note_routes.py``@router.get('')` — Lists all user notes with pin and archive states.
- `static/js/notes.js``initNotesView` — Main interactive notes grid and modal manager.
### Unknowns
- Concurrent edits on note item checkboxes.
+213
View File
@@ -0,0 +1,213 @@
# Platform
Features in this document are generated from [`../feature-catalog.json`](../feature-catalog.json), the canonical inventory.
## PLATFORM-001 — Application Initialization & Lifespan Management
- **Domain**: `platform`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Orchestrates server startup, database table migration, background daemon initialization, and clean shutdown.
### Evidence summary
- `app.py``_lifespan` — FastAPI lifespan context manager executing startup tasks.
- `src/app_initializer.py``initialize_app` — Initializes app directories, DB schemas, and logging.
### Unknowns
- Un-handled exceptions during startup halt application launch.
## PLATFORM-002 — System Health, Readiness & Version Monitoring APIs
- **Domain**: `platform`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Exposes Liveness (/api/health), Readiness (/api/ready), App Version (/api/version), and Client Perf APIs.
### Evidence summary
- `app.py``readiness_check` — Performs system component integrity check.
- `src/readiness.py``check_readiness` — Checks database, storage, and key paths for read/write access.
### Unknowns
- Readiness check delays if verifying connectivity to offline remote endpoints.
## PLATFORM-003 — Database Schema, Migrations & SQLite Persistence
- **Domain**: `platform`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Defines core relational tables (users, tokens, tasks, sessions) and executes automated SQLite schema upgrades.
### Evidence summary
- `core/database.py``init_db` — Creates ORM tables and establishes connection pool.
- `scripts/update_database.py``run_migrations` — Applies missing schema columns and indices.
### Unknowns
- SQLite file lock contention under high concurrent write loads.
## PLATFORM-004 — User Data Export & Import Backup Infrastructure
- **Domain**: `platform`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Exports complete user workspace state (sessions, memory, skills, notes, presets) into a zip archive.
### Evidence summary
- `routes/backup_routes.py``setup_backup_routes` — Handles workspace data export and import upload unpack.
- `docs/backup-restore.md``Documentation` — Backup and restore operational documentation.
### Unknowns
- Corrupt archive files causing partial data restore.
## PLATFORM-005 — File Cleanup & Storage Maintenance Engine
- **Domain**: `platform`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Scans data directories for orphaned files, old uploads, temporary vision images, and frees disk space.
### Evidence summary
- `routes/cleanup/cleanup_routes.py``@router.get('/preview')` — Previews reclaimable disk space across storage directories.
- `src/cleanup_service.py``CleanupService` — Executes filesystem purge of orphaned asset files.
### Unknowns
- Deletes files uploaded in active sessions if retention window is set too short.
## PLATFORM-006 — System Health & RAG Diagnostic Suite
- **Domain**: `platform`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Executes real-time integrity diagnostics across ChromaDB, SearXNG, local models, and network interfaces.
### Evidence summary
- `routes/diagnostics_routes.py``setup_diagnostics_routes` — Runs subsystem health check suite.
- `src/service_health.py``collect_health_status` — Inspects vector database, email, search, and local provider status.
### Unknowns
- Diagnostic timeout if external search provider is unreachable.
## PLATFORM-007 — Desktop CLI Utilities & Shell Integration Tools
- **Domain**: `platform`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Provides command-line interface tools (`odysseus`, `odysseus-mcp`, `odysseus-mail`) for terminal usage.
### Evidence summary
- `scripts/_lib/cli.py``main` — Shared CLI framework for terminal helper commands.
- `scripts/odysseus``odysseus` — Main terminal launcher script.
### Unknowns
- Outdated CLI scripts if backend API schemas change.
## PLATFORM-008 — Desktop Companion App Integration
- **Domain**: `platform`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Provides API routes and pairing mechanisms for the native macOS/desktop menu bar companion app.
### Evidence summary
- `companion/routes.py``setup_companion_routes` — Endpoints for pairing and status sync with desktop companion.
- `companion/pairing.py``PairingManager` — Generates and validates companion pairing codes.
### Unknowns
- Pairing code expiration timing window.
## PLATFORM-009 — Docker Containerization & GPU Hardware Manifests
- **Domain**: `platform`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: pending — Requires Docker GPU pass-through and compatible host drivers.
### Purpose
Provides multi-stage Dockerfile and Docker Compose manifests for CPU, NVIDIA CUDA, and AMD ROCm GPUs.
### Evidence summary
- `Dockerfile``multi-stage-build` — Multi-stage container build environment.
- `docker-compose.gpu-nvidia.yml``nvidia-gpu-manifest` — NVIDIA GPU pass-through container specification.
- `scripts/check-docker-gpu.sh``check-docker-gpu` — Automated diagnostic test script for host NVIDIA GPU passthrough.
### Unknowns
- Driver version incompatibility with host NVIDIA/AMD kernel drivers.
## PLATFORM-010 — Legacy FAISS Vector Index Migration Script
- **Domain**: `platform`
- **Status**: `legacy`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Legacy utility script to migrate older FAISS vector indices into ChromaDB.
### Evidence summary
- `scripts/migrate_faiss_to_chroma.py``migrate_faiss` — Reads FAISS vector index files and writes to ChromaDB collection.
### Unknowns
- Superseded by native ChromaDB vector index pipeline.
+86
View File
@@ -0,0 +1,86 @@
# Research
Features in this document are generated from [`../feature-catalog.json`](../feature-catalog.json), the canonical inventory.
## RESEARCH-001 — Deep Research Execution Engine & SSE Progress Streaming
- **Domain**: `research`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Executes multi-step recursive deep research tasks, web page scraping, synthesis, and streams live progress.
### Evidence summary
- `routes/research/research_routes.py``@router.post('/api/research/start')` — Initiates deep research job.
- `src/deep_research.py``DeepResearchEngine` — Recursive search and summary crawler.
### Unknowns
- High memory consumption when parsing multi-megabyte HTML target pages.
## RESEARCH-002 — Research Library, Detail View & Image Controls
- **Domain**: `research`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Stores completed research reports, generated diagrams, reference links, and manages image visibility.
### Evidence summary
- `routes/research/research_routes.py``@router.get('/api/research/library')` — Returns all saved research reports.
### Unknowns
- Orphaned report files if storage directory is modified out-of-band.
## RESEARCH-003 — Web Search Engine Integration (SearXNG & Multi-Provider)
- **Domain**: `research`
- **Status**: `verified`
- **Evidence Maturity**: `E1`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: pending — Requires an active SearXNG instance or external search API provider.
### Purpose
Queries SearXNG, DuckDuckGo, or Google Search instances to retrieve web search snippets.
### Evidence summary
- `routes/search_routes.py``setup_search_routes` — Defines /api/search, /api/search/config, and /api/search/query endpoints.
- `src/search/core.py``SearchEngine` — Compatibility module aliasing services.search.core.
- `tests/test_search_ranking.py``test_news_queries_prefer_news_sources_over_sports_and_social_results` — Tests search result domain ranking and scoring.
### Unknowns
- Search provider IP throttling or rate-limiting.
## RESEARCH-004 — Research Result Peeking & Topic Spinoff Generation
- **Domain**: `research`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Extracts preliminary research snippets and spawns child research sessions focused on specific sub-topics.
### Evidence summary
- `routes/research/research_routes.py``@router.post('/api/research/spinoff/{session_id}')` — Spawns child research session for specific query.
### Unknowns
- Deep recursion tree depth when spawning multiple nested spinoffs.
+154
View File
@@ -0,0 +1,154 @@
# Security
Features in this document are generated from [`../feature-catalog.json`](../feature-catalog.json), the canonical inventory.
## SECURITY-001 — Authentication, Session Cookies & User Management
- **Domain**: `security`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Handles bcrypt password hashing, session cookie issuance, authentication enforcement, and user administration.
### Evidence summary
- `routes/auth_routes.py``@router.post('/login')` — Authenticates credentials and sets session cookie.
- `core/auth.py``AuthManager` — Handles user creation, password verification, and session tokens.
### Unknowns
- Cookie session hijack if deployed over unencrypted HTTP without HTTPS cookie flags.
## SECURITY-002 — System Vault Encrypted Secret Storage
- **Domain**: `security`
- **Status**: `verified`
- **Evidence Maturity**: `E1`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: pending — Requires installed Bitwarden CLI (`bw`) executable.
### Purpose
Encrypts API keys, passphrases, and third-party secrets on disk using AES-GCM / PBKDF2 key derivation.
### Evidence summary
- `routes/vault_routes.py``setup_vault_routes` — Admin routes for vault configuration, login, unlock, lock, and logout.
- `src/secret_storage.py``SecretStorage` — Fernet symmetric key DB secret encryption.
- `tests/test_vault_password_not_in_argv.py``test_bw_password_not_in_argv` — Verifies master password is fed via stdin and never appears in process argv.
### Unknowns
- Loss of vault master passphrase renders all encrypted secrets permanently unrecoverable.
## SECURITY-003 — API Token Management & Scope Access Control
- **Domain**: `security`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Generates scoped API bearer tokens (read/write/admin) for external tool and script authentication.
### Evidence summary
- `routes/api_token_routes.py``setup_api_token_routes` — Exposes API token creation, scope assignment, and revocation.
- `core/database.py``ApiToken` — SQLAlchemy ORM schema for API tokens and permissions.
### Unknowns
- Leaked API bearer tokens with excessive permission scopes.
## SECURITY-004 — Prompt Security & Injection Defense Engine
- **Domain**: `security`
- **Status**: `verified`
- **Evidence Maturity**: `E1`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Scans system prompts and external inputs for prompt injection attempts, jailbreaks, and sensitive data leaks.
### Evidence summary
- `src/prompt_security.py``untrusted_context_message` — Wraps untrusted context with guard delimiters and sets metadata.trusted = False.
- `src/tool_security.py``NON_ADMIN_BLOCKED_TOOLS` — Enforces tool execution safety for non-admin user roles.
- `tests/test_skill_index_prompt_injection.py``test_skill_index` — Verifies skill index descriptions cannot leak into trusted system prompts.
- `tests/test_tool_output_prompt_injection.py``test_tool_output` — Tool output injection guards.
### Unknowns
- False positives blocking legitimate complex coding or security prompts.
## SECURITY-005 — URL & Path Confinement Security Guards
- **Domain**: `security`
- **Status**: `verified`
- **Evidence Maturity**: `E1`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Prevents SSRF attacks and path traversal by validating target IP addresses and resolving symlinks.
### Evidence summary
- `src/url_safety.py``check_outbound_url` — Rejects non-HTTP(S) schemes, link-local, cloud metadata SSRF addresses.
- `src/url_security.py``validate_public_http_url` — Validates public-facing endpoints.
- `tests/test_url_safety.py``test_url_safety` — Scheme validation, cloud metadata SSRF rejection, IP classification.
- `tests/test_tool_path_confinement.py``test_path_confinement` — Path traversal checks.
- `tests/test_workspace_confine.py``test_workspace_confine` — Workspace confinement checks.
### Unknowns
- DNS rebinding attacks if IP address is re-resolved post-validation.
## SECURITY-006 — HTTP Security Headers Middleware
- **Domain**: `security`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Injects standard OWASP HTTP security headers (CSP, HSTS, X-Content-Type-Options, X-Frame-Options).
### Evidence summary
- `core/middleware.py``SecurityHeadersMiddleware` — Sets strict security headers and CSP nonces on HTTP responses.
### Unknowns
- Strict Content Security Policy (CSP) blocking third-party embedded web resources.
## SECURITY-007 — Admin System Data Wipe ('Danger Zone')
- **Domain**: `security`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Provides administrative reset operations to wipe sessions, cache, uploaded files, or factory reset state.
### Evidence summary
- `routes/admin_wipe/admin_wipe_routes.py``@router.delete('/wipe/{kind}')` — Executes systemic data wipe based on requested scope.
### Unknowns
- Accidental catastrophic data loss if triggered without user confirmation.
+24
View File
@@ -0,0 +1,24 @@
# Skill
Features in this document are generated from [`../feature-catalog.json`](../feature-catalog.json), the canonical inventory.
## SKILL-001 — Dynamic Skill Management & Code Execution Engine
- **Domain**: `skill`
- **Status**: `verified`
- **Evidence Maturity**: `E0`
- **Commit Verified**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Runtime Validation**: not-required — No separate environment-dependent runtime validation was identified during this documentation pass.
### Purpose
Allows users to create, import, edit, test, and execute custom Python/Markdown skills dynamically.
### Evidence summary
- `routes/skills_routes.py``setup_skills_routes` — Exposes CRUD and remote import routes for user skills.
- `services/memory/skills.py``SkillsManager` — Handles skill storage, parsing, and execution.
### Unknowns
- Arbitrary code execution risks if skill import URL is untrusted.
File diff suppressed because it is too large Load Diff
+85
View File
@@ -0,0 +1,85 @@
# Feature Catalog
This is a human-readable index derived from [`feature-catalog.json`](feature-catalog.json). The JSON file is canonical.
| ID | Feature | Domain | Status | Evidence | Runtime |
|---|---|---|---|---|---|
| `AGENT-001` | Autonomous Agent Loop & Tool Execution Engine | `agent` | `verified` | `E0` | not required |
| `AGENT-002` | Scheduled Tasks & Event Bus Dispatcher | `agent` | `verified` | `E0` | not required |
| `AGENT-003` | Webhook Event Subscriptions & Trigger Processing | `agent` | `verified` | `E0` | not required |
| `AGENT-004` | Assistant Settings, Task Check-Ins & Background Job Monitor | `agent` | `partial` | `E1` | not required |
| `AGENT-005` | Model Context Protocol (MCP) Server Integration | `agent` | `verified` | `E0` | not required |
| `AGENT-006` | AI Interaction Tools & Pipeline Orchestration | `agent` | `verified` | `E0` | not required |
| `AGENT-007` | Subprocess & Background Job Execution Tools | `agent` | `verified` | `E0` | not required |
| `CALENDAR-001` | CalDAV Calendar Synchronization & Account Setup | `calendar` | `verified` | `E0` | pending |
| `CALENDAR-002` | Calendar Event Operations & iCalendar Parsing | `calendar` | `verified` | `E0` | not required |
| `CHAT-001` | Core Chat Streaming & SSE Message Generation | `chat` | `verified` | `E2` | pending |
| `CHAT-002` | Session Management & Conversation State | `chat` | `verified` | `E0` | not required |
| `CHAT-003` | Chat History & Message Editing/Truncation | `chat` | `verified` | `E0` | not required |
| `CHAT-004` | File & Multimodal Attachment Handling | `chat` | `verified` | `E0` | not required |
| `CHAT-005` | Chat Message Search | `chat` | `verified` | `E0` | not required |
| `CHAT-006` | System Prompts & Preset Management | `chat` | `verified` | `E0` | not required |
| `CHAT-007` | Emoji Rendering & Twemoji SVG Proxy | `chat` | `verified` | `E0` | not required |
| `CHAT-008` | Input History Recall (Arrow Up) | `chat` | `verified` | `E0` | not required |
| `CHAT-009` | Context Window Compaction & Truncation | `chat` | `verified` | `E0` | not required |
| `CONTACT-001` | CardDAV Contact Management & Address Book Integration | `contact` | `verified` | `E0` | not required |
| `COOKBOOK-001` | Local Model Download & Recipe Lifecycle Management | `cookbook` | `verified` | `E0` | not required |
| `COOKBOOK-002` | Hardware Model Fitting ('What Fits?') Analysis Engine | `cookbook` | `verified` | `E0` | not required |
| `COOKBOOK-003` | HuggingFace & MLX Model Discovery Services | `cookbook` | `verified` | `E0` | not required |
| `COOKBOOK-004` | Host Docker Access for Inference Container Runtimes | `cookbook` | `verified` | `E0` | pending |
| `DOCUMENT-001` | Document & Canvas Artifact Management | `document` | `verified` | `E0` | not required |
| `DOCUMENT-002` | PDF Form Processing & High-Fidelity Rendering | `document` | `verified` | `E1` | pending |
| `DOCUMENT-003` | Personal Document Indexing & RAG Retrieval | `document` | `verified` | `E0` | not required |
| `DOCUMENT-004` | Document Conversion & Text Extraction Engine | `document` | `verified` | `E0` | not required |
| `DOCUMENT-005` | Document Library UI Navigation | `document` | `verified` | `E0` | not required |
| `EMAIL-001` | Email Account Setup, IMAP/SMTP Connection & Polling | `email` | `verified` | `E1` | pending |
| `EMAIL-002` | Email Searching, Threading & Message Operations | `email` | `verified` | `E0` | not required |
| `EMAIL-003` | Email Composition, Draft Management & Sending | `email` | `verified` | `E0` | pending |
| `EMAIL-004` | Email MCP Server & Codex Integration Bridge | `email` | `verified` | `E0` | not required |
| `FRONTEND-001` | Single Page Application Shell & Client Router | `frontend` | `verified` | `E0` | not required |
| `FRONTEND-002` | Dynamic Theme, Color System & Custom Fonts | `frontend` | `verified` | `E0` | not required |
| `FRONTEND-003` | Window Manager, Tile Layout & Modal Control System | `frontend` | `verified` | `E0` | not required |
| `FRONTEND-004` | Global Keyboard Shortcuts & Accessibility Controls | `frontend` | `verified` | `E0` | not required |
| `FRONTEND-005` | Markdown, LaTeX & Code Block Streaming Renderer | `frontend` | `verified` | `E0` | not required |
| `FRONTEND-006` | Interactive Tour & Guided Onboarding System | `frontend` | `verified` | `E0` | not required |
| `FRONTEND-007` | Background Effects Prototyping Sandbox | `frontend` | `dead-code-candidate` | `E1` | not required |
| `MEDIA-001` | Gallery Image Library & Album Operations | `media` | `verified` | `E0` | not required |
| `MEDIA-002` | Image Processing, AI Upscaling & Style Transfer | `media` | `verified` | `E0` | not required |
| `MEDIA-003` | Interactive Image Canvas Editor & Persisted Drafts | `media` | `verified` | `E0` | not required |
| `MEDIA-004` | Text-to-Speech (TTS) Synthesis Service | `media` | `verified` | `E0` | not required |
| `MEDIA-005` | Speech-to-Text (STT) Audio Transcription Service | `media` | `verified` | `E0` | not required |
| `MEDIA-006` | Digital Signature Stamp Storage & Placement | `media` | `verified` | `E0` | not required |
| `MEDIA-007` | Generated Image Artifact Route & MCP Integration | `media` | `verified` | `E0` | not required |
| `MEDIA-008` | Native MLX Image Bridge (macOS Apple Silicon) | `media` | `experimental` | `E0` | pending |
| `MEMORY-001` | Persistent Long-Term Memory & Vector Indexing | `memory` | `verified` | `E0` | not required |
| `MODEL-001` | Multi-Provider LLM Model Discovery & Metadata Management | `model` | `verified` | `E0` | not required |
| `MODEL-002` | Model Capability & Context Limits Detection | `model` | `verified` | `E0` | not required |
| `MODEL-003` | LLM Core Provider Communication & Fallback Routing | `model` | `verified` | `E0` | pending |
| `MODEL-004` | Model Selection & Display Ordering Preferences | `model` | `verified` | `E0` | not required |
| `MODEL-005` | Side-by-Side Model Comparison (A/B Testing) | `model` | `verified` | `E0` | not required |
| `MODEL-006` | GitHub Copilot Device Flow Authentication | `model` | `verified` | `E2` | pending |
| `MODEL-007` | ChatGPT Subscription Device Flow Authentication | `model` | `verified` | `E2` | pending |
| `MODEL-008` | Embedding Model Lane & Vector Provider Setup | `model` | `verified` | `E0` | not required |
| `NOTE-001` | Interactive Notes & Checklist Management | `note` | `verified` | `E0` | not required |
| `PLATFORM-001` | Application Initialization & Lifespan Management | `platform` | `verified` | `E0` | not required |
| `PLATFORM-002` | System Health, Readiness & Version Monitoring APIs | `platform` | `verified` | `E0` | not required |
| `PLATFORM-003` | Database Schema, Migrations & SQLite Persistence | `platform` | `verified` | `E0` | not required |
| `PLATFORM-004` | User Data Export & Import Backup Infrastructure | `platform` | `verified` | `E0` | not required |
| `PLATFORM-005` | File Cleanup & Storage Maintenance Engine | `platform` | `verified` | `E0` | not required |
| `PLATFORM-006` | System Health & RAG Diagnostic Suite | `platform` | `verified` | `E0` | not required |
| `PLATFORM-007` | Desktop CLI Utilities & Shell Integration Tools | `platform` | `verified` | `E0` | not required |
| `PLATFORM-008` | Desktop Companion App Integration | `platform` | `verified` | `E0` | not required |
| `PLATFORM-009` | Docker Containerization & GPU Hardware Manifests | `platform` | `verified` | `E0` | pending |
| `PLATFORM-010` | Legacy FAISS Vector Index Migration Script | `platform` | `legacy` | `E0` | not required |
| `RESEARCH-001` | Deep Research Execution Engine & SSE Progress Streaming | `research` | `verified` | `E0` | not required |
| `RESEARCH-002` | Research Library, Detail View & Image Controls | `research` | `verified` | `E0` | not required |
| `RESEARCH-003` | Web Search Engine Integration (SearXNG & Multi-Provider) | `research` | `verified` | `E1` | pending |
| `RESEARCH-004` | Research Result Peeking & Topic Spinoff Generation | `research` | `verified` | `E0` | not required |
| `SECURITY-001` | Authentication, Session Cookies & User Management | `security` | `verified` | `E0` | not required |
| `SECURITY-002` | System Vault Encrypted Secret Storage | `security` | `verified` | `E1` | pending |
| `SECURITY-003` | API Token Management & Scope Access Control | `security` | `verified` | `E0` | not required |
| `SECURITY-004` | Prompt Security & Injection Defense Engine | `security` | `verified` | `E1` | not required |
| `SECURITY-005` | URL & Path Confinement Security Guards | `security` | `verified` | `E1` | not required |
| `SECURITY-006` | HTTP Security Headers Middleware | `security` | `verified` | `E0` | not required |
| `SECURITY-007` | Admin System Data Wipe ('Danger Zone') | `security` | `verified` | `E0` | not required |
| `SKILL-001` | Dynamic Skill Management & Code Execution Engine | `skill` | `verified` | `E0` | not required |
@@ -0,0 +1,28 @@
# Source Provenance & Audit Baseline
## Target Repository & Snapshot
- **Repository**: `odysseus-dev/odysseus`
- **Branch**: `discovery`
- **Pinned Commit SHA**: `d8a2059df8e53bc7275c45339849d14c8651e73c`
- **Snapshot Date**: `2026-07-23T14:49:02Z`
## Discovery Package Organization
The public discovery documentation package under `docs/discovery/` is structured as follows:
- `feature-catalog.json`: Canonical machine-readable JSON catalog containing 79 feature records.
- `feature-catalog.md`: Human-readable summary derived from `feature-catalog.json`.
- `BASELINE-STATUS.md`: Publication status, evidence-validation snapshot, and durable maintainer guidance.
- `audit-method.md`: Audit rules, scope, and evidence maturity definitions (E0 to E4).
- `domains/`: 16 functional domain markdown files detailing feature implementations.
- `references/`: Audit provenance and repository snapshot metadata.
- `tools/`: Structural, consistency, and evidence validators with focused evidence-validator tests.
## Exclusion Principles
This public documentation package explicitly excludes:
- Internal planning artifacts or private meeting notes.
- Machine-specific filesystem paths or user environments.
- API keys, credentials, or private service endpoints.
- Application code or automated test mutations.
@@ -0,0 +1,224 @@
#!/usr/bin/env python3
"""Focused negative tests for validate_discovery_evidence.py."""
from __future__ import annotations
import importlib.util
import shutil
import sys
import tempfile
import unittest
from pathlib import Path
MODULE_PATH = Path(__file__).with_name("validate_discovery_evidence.py")
SPEC = importlib.util.spec_from_file_location("validate_discovery_evidence", MODULE_PATH)
assert SPEC and SPEC.loader
validator = importlib.util.module_from_spec(SPEC)
sys.modules[SPEC.name] = validator
SPEC.loader.exec_module(validator)
class FakeJavascriptParser:
supported = True
reason = "test parser"
def __init__(self, symbols: list[validator.Located] | None = None) -> None:
self.symbols = symbols or []
def parse(self, path: Path) -> list[validator.Located]:
return self.symbols
class UnsupportedJavascriptParser:
supported = False
reason = "no repository-local parser"
class EvidenceNegativeTests(unittest.TestCase):
def setUp(self) -> None:
self.temp = tempfile.TemporaryDirectory()
self.root = Path(self.temp.name)
(self.root / "sample.py").write_text(
"from fastapi import APIRouter\n"
"router = APIRouter(prefix='/api')\n"
"\n"
"class ChatHandler:\n"
" def preprocess_message(self):\n"
" return True\n"
"\n"
"@router.post('/chat')\n"
"def chat_stream():\n"
" return True\n",
encoding="utf-8",
)
(self.root / "sample.js").write_text(
"export const present = () => true;\n", encoding="utf-8"
)
(self.root / "sample.sh").write_text(
"#!/usr/bin/env bash\nreal_function() {\n return 0\n}\n",
encoding="utf-8",
)
self.backup = self.root / "copied-backups"
self.backup.mkdir()
for path in self.root.glob("sample.*"):
shutil.copy2(path, self.backup / path.name)
def tearDown(self) -> None:
for backup in self.backup.iterdir():
target = self.root / backup.name
shutil.copy2(backup, target)
self.assertEqual(target.read_bytes(), backup.read_bytes())
self.temp.cleanup()
def validate(
self,
evidence: dict[str, str],
javascript_parser: object | None = None,
) -> validator.Validation:
return validator.validate_evidence(
self.root,
"TEST-001",
0,
evidence,
javascript_parser or FakeJavascriptParser(),
)
def test_missing_python_symbol(self) -> None:
result = self.validate(
{
"path": "sample.py",
"kind": "python-function",
"locator": "fabricated",
"line_range": "L1-L1",
"explanation": "negative fixture",
}
)
self.assertEqual(result.result, "invalid-locator")
def test_incorrect_qualified_method(self) -> None:
result = self.validate(
{
"path": "sample.py",
"kind": "python-method",
"locator": "WrongHandler.preprocess_message",
"line_range": "L5-L6",
"explanation": "negative fixture",
}
)
self.assertEqual(result.result, "invalid-locator")
def test_symbol_outside_cited_range(self) -> None:
result = self.validate(
{
"path": "sample.py",
"kind": "python-method",
"locator": "ChatHandler.preprocess_message",
"line_range": "L1-L2",
"explanation": "negative fixture",
}
)
self.assertEqual(result.result, "locator-outside-range")
def test_fabricated_test_function(self) -> None:
result = self.validate(
{
"path": "sample.py",
"kind": "test-function",
"locator": "test_fabricated",
"line_range": "L1-L2",
"explanation": "negative fixture",
}
)
self.assertEqual(result.result, "invalid-locator")
def test_nonexistent_javascript_symbol_with_parser(self) -> None:
result = self.validate(
{
"path": "sample.js",
"kind": "javascript-function",
"locator": "missing",
"line_range": "L1-L1",
"explanation": "negative fixture",
},
FakeJavascriptParser(
[validator.Located("present", "javascript-export", 1, 1)]
),
)
self.assertEqual(result.result, "invalid-locator")
def test_unsupported_javascript_parser(self) -> None:
result = self.validate(
{
"path": "sample.js",
"kind": "javascript-function",
"locator": "present",
"line_range": "L1-L1",
"explanation": "negative fixture",
},
UnsupportedJavascriptParser(),
)
self.assertEqual(result.result, "unsupported")
def test_route_path_mismatch(self) -> None:
result = self.validate(
{
"path": "sample.py",
"kind": "python-route",
"locator": "POST /api/wrong -> chat_stream",
"line_range": "L9-L10",
"explanation": "negative fixture",
}
)
self.assertEqual(result.result, "invalid-locator")
self.assertIn("path", result.problem or "")
def test_http_method_mismatch(self) -> None:
result = self.validate(
{
"path": "sample.py",
"kind": "python-route",
"locator": "GET /api/chat -> chat_stream",
"line_range": "L9-L10",
"explanation": "negative fixture",
}
)
self.assertEqual(result.result, "invalid-locator")
self.assertIn("method", result.problem or "")
def test_shell_function_mismatch(self) -> None:
result = self.validate(
{
"path": "sample.sh",
"kind": "shell-function",
"locator": "fabricated",
"line_range": "L1-L4",
"explanation": "negative fixture",
}
)
self.assertEqual(result.result, "invalid-locator")
def test_invalid_file_level_evidence(self) -> None:
result = self.validate(
{
"path": "missing.file",
"kind": "file",
"explanation": "negative fixture",
}
)
self.assertEqual(result.result, "invalid-path")
def test_file_level_evidence_rejects_fake_symbol(self) -> None:
result = self.validate(
{
"path": "sample.sh",
"kind": "file",
"locator": "whole-script",
"explanation": "negative fixture",
}
)
self.assertEqual(result.result, "invalid-locator")
if __name__ == "__main__":
unittest.main()
+592
View File
@@ -0,0 +1,592 @@
#!/usr/bin/env python3
from __future__ import annotations
import json
import re
import sys
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parents[1]
CATALOG_PATH = ROOT / "feature-catalog.json"
CATALOG_MD_PATH = ROOT / "feature-catalog.md"
DOMAINS_DIR = ROOT / "domains"
REVIEWS_DIR = ROOT / "reviews"
EXPECTED_COMMIT = "d8a2059df8e53bc7275c45339849d14c8651e73c"
EXPECTED_FEATURES = 79
EXPECTED_DOMAINS = 16
VALID_STATUSES = {
"verified",
"partial",
"disabled",
"experimental",
"legacy",
"dead-code-candidate",
"unverified",
}
VALID_MATURITY = {"E0", "E1", "E2", "E3", "E4"}
VALID_RUNTIME = {
"not-required",
"pending",
"blocked",
"completed",
}
REQUIRED_FIELDS = {
"id",
"domain",
"name",
"purpose",
"status",
"evidence_maturity",
"verified_at_commit",
"evidence",
"runtime_validation",
}
FEATURE_ID_RE = re.compile(r"^[A-Z][A-Z0-9]*-\d{3}$")
DOMAIN_HEADING_RE = re.compile(
r"^##\s+`?([A-Z][A-Z0-9]*-\d{3})`?"
r"\s+(?:—|-)\s+(.+?)\s*$"
)
DOMAIN_FIELD_RE = re.compile(
r"^-\s+\*\*"
r"(Domain|Status|Evidence Maturity|Commit Verified)"
r"\*\*:\s*(.*?)\s*$"
)
DOMAIN_RUNTIME_RE = re.compile(
r"^-\s+\*\*Runtime Validation\*\*:\s*(.*?)\s*$"
)
REVIEW_HEADING_RE = re.compile(
r"^###\s+(?:\d+\.\s+)?"
r"([A-Z][A-Z0-9]*-\d{3})"
r"\s+(?:—|-)\s+.+$"
)
REVIEW_RESULT_RE = re.compile(
r"^-\s+\*\*Resulting Status(?:\s+and|/)\s+Maturity\*\*:"
r"\s*`([^`]+)`\s*/\s*`([^`]+)`\s*$"
)
def clean(value: str) -> str:
value = value.strip()
if (
len(value) >= 2
and value.startswith("`")
and value.endswith("`")
):
return value[1:-1].strip()
return value
def load_catalog(errors: list[str]) -> list[dict[str, Any]]:
try:
data = json.loads(
CATALOG_PATH.read_text(encoding="utf-8")
)
except Exception as exc:
errors.append(f"Unable to read catalog: {exc}")
return []
if isinstance(data, list):
features = data
elif isinstance(data, dict) and isinstance(data.get("features"), list):
features = data["features"]
else:
errors.append(
"Catalog must be an array or contain a features array"
)
return []
if not all(isinstance(feature, dict) for feature in features):
errors.append("Every catalog feature must be an object")
return []
return features
def validate_catalog(
features: list[dict[str, Any]],
errors: list[str],
) -> None:
if len(features) != EXPECTED_FEATURES:
errors.append(
f"Expected {EXPECTED_FEATURES} features, "
f"found {len(features)}"
)
ids = [feature.get("id") for feature in features]
duplicates = sorted(
feature_id
for feature_id, count in Counter(ids).items()
if feature_id and count > 1
)
if duplicates:
errors.append(
"Duplicate feature IDs: " + ", ".join(duplicates)
)
for index, feature in enumerate(features):
feature_id = feature.get("id")
label = (
feature_id
if isinstance(feature_id, str)
else f"<index:{index}>"
)
missing = sorted(
field
for field in REQUIRED_FIELDS
if feature.get(field) in (None, "", [])
)
if missing:
errors.append(
f"{label}: missing fields: {', '.join(missing)}"
)
if (
not isinstance(feature_id, str)
or not FEATURE_ID_RE.fullmatch(feature_id)
):
errors.append(f"{label}: invalid feature ID")
if feature.get("status") not in VALID_STATUSES:
errors.append(
f"{label}: invalid status "
f"{feature.get('status')!r}"
)
if feature.get("evidence_maturity") not in VALID_MATURITY:
errors.append(
f"{label}: invalid maturity "
f"{feature.get('evidence_maturity')!r}"
)
if feature.get("verified_at_commit") != EXPECTED_COMMIT:
errors.append(
f"{label}: incorrect verified_at_commit"
)
runtime = feature.get("runtime_validation")
if not isinstance(runtime, dict):
errors.append(
f"{label}: runtime_validation must be an object"
)
continue
required = runtime.get("required")
runtime_status = runtime.get("status")
reason = runtime.get("reason")
if not isinstance(required, bool):
errors.append(
f"{label}: runtime required must be boolean"
)
if runtime_status not in VALID_RUNTIME:
errors.append(
f"{label}: invalid runtime status "
f"{runtime_status!r}"
)
if not isinstance(reason, str) or not reason.strip():
errors.append(
f"{label}: runtime reason is blank"
)
if required is False and runtime_status != "not-required":
errors.append(
f"{label}: required=false requires not-required"
)
if required is True and runtime_status == "not-required":
errors.append(
f"{label}: required=true cannot be not-required"
)
def parse_domain(
path: Path,
errors: list[str],
) -> dict[str, dict[str, str]]:
records: dict[str, dict[str, str]] = {}
current_id: str | None = None
for line_number, line in enumerate(
path.read_text(encoding="utf-8").splitlines(),
start=1,
):
heading = DOMAIN_HEADING_RE.match(line)
if heading:
current_id = heading.group(1)
if current_id in records:
errors.append(
f"{path.relative_to(ROOT)}:{line_number}: "
f"duplicate heading {current_id}"
)
records[current_id] = {
"Name": heading.group(2).strip(),
}
continue
field = DOMAIN_FIELD_RE.match(line)
if field and current_id:
value = clean(field.group(2))
if not value:
errors.append(
f"{path.relative_to(ROOT)}:{line_number}: "
f"blank {field.group(1)}"
)
records[current_id][field.group(1)] = value
continue
runtime = DOMAIN_RUNTIME_RE.match(line)
if runtime and current_id:
value = clean(runtime.group(1))
runtime_status = re.split(
r"\s+(?:—|-)\s+",
value,
maxsplit=1,
)[0]
records[current_id]["Runtime Validation"] = (
runtime_status.strip("` ")
)
return records
def validate_domains(
features: list[dict[str, Any]],
errors: list[str],
) -> None:
catalog = {
feature["id"]: feature
for feature in features
if feature.get("id")
}
expected_by_domain: defaultdict[str, set[str]] = defaultdict(set)
for feature in features:
expected_by_domain[feature["domain"]].add(feature["id"])
paths = sorted(DOMAINS_DIR.glob("*.md"))
if len(paths) != EXPECTED_DOMAINS:
errors.append(
f"Expected {EXPECTED_DOMAINS} domain files, "
f"found {len(paths)}"
)
all_found: set[str] = set()
for path in paths:
domain = path.stem
records = parse_domain(path, errors)
found = set(records)
expected = expected_by_domain.get(domain, set())
all_found.update(found)
if found != expected:
missing = sorted(expected - found)
extra = sorted(found - expected)
errors.append(
f"{domain}: missing={missing}, unexpected={extra}"
)
for feature_id, record in records.items():
feature = catalog.get(feature_id)
if feature is None:
continue
expected_values = {
"Name": feature["name"],
"Domain": feature["domain"],
"Status": feature["status"],
"Evidence Maturity": feature["evidence_maturity"],
"Commit Verified": feature["verified_at_commit"],
"Runtime Validation": (
feature["runtime_validation"]["status"]
),
}
for field, expected_value in expected_values.items():
actual = record.get(field)
if actual != expected_value:
errors.append(
f"{path.relative_to(ROOT)}: "
f"{feature_id} {field}: "
f"{actual!r} != {expected_value!r}"
)
if all_found != set(catalog):
errors.append(
"Domain Markdown IDs do not match catalog JSON"
)
def validate_catalog_markdown(
features: list[dict[str, Any]],
errors: list[str],
) -> None:
expected = {
feature["id"]: feature
for feature in features
}
found: dict[str, list[str]] = {}
for line in CATALOG_MD_PATH.read_text(
encoding="utf-8"
).splitlines():
if not line.startswith("|"):
continue
cells = [
cell.strip()
for cell in line.strip().strip("|").split("|")
]
if len(cells) < 6:
continue
feature_id = clean(cells[0])
if FEATURE_ID_RE.fullmatch(feature_id):
found[feature_id] = cells
if set(found) != set(expected):
errors.append(
"feature-catalog.md IDs do not match JSON"
)
for feature_id, cells in found.items():
feature = expected[feature_id]
runtime = feature["runtime_validation"]
runtime_display = (
runtime["status"]
if runtime["required"]
else "not required"
)
actual = {
"name": cells[1].replace("\\|", "|"),
"domain": clean(cells[2]),
"status": clean(cells[3]),
"maturity": clean(cells[4]),
"runtime": clean(cells[5]),
}
wanted = {
"name": feature["name"],
"domain": feature["domain"],
"status": feature["status"],
"maturity": feature["evidence_maturity"],
"runtime": runtime_display,
}
for field, expected_value in wanted.items():
if actual[field] != expected_value:
errors.append(
f"feature-catalog.md: {feature_id} "
f"{field}: {actual[field]!r} "
f"!= {expected_value!r}"
)
def validate_reviews(
features: list[dict[str, Any]],
errors: list[str],
) -> int:
catalog = {
feature["id"]: feature
for feature in features
}
checked = 0
for path in sorted(
REVIEWS_DIR.glob("evidence-sample-*.md")
):
current_id: str | None = None
results: set[str] = set()
for line_number, line in enumerate(
path.read_text(encoding="utf-8").splitlines(),
start=1,
):
heading = REVIEW_HEADING_RE.match(line)
if heading:
current_id = heading.group(1)
continue
result = REVIEW_RESULT_RE.match(line)
if not result or current_id is None:
continue
status, maturity = result.groups()
results.add(current_id)
checked += 1
feature = catalog.get(current_id)
if feature is None:
errors.append(
f"{path.relative_to(ROOT)}:{line_number}: "
f"unknown feature {current_id}"
)
continue
if feature["status"] != status:
errors.append(
f"{current_id}: review status {status!r} "
f"!= catalog {feature['status']!r}"
)
if feature["evidence_maturity"] != maturity:
errors.append(
f"{current_id}: review maturity {maturity!r} "
f"!= catalog "
f"{feature['evidence_maturity']!r}"
)
if path.name == "evidence-sample-01.md" and len(results) != 12:
errors.append(
f"{path.relative_to(ROOT)}: expected 12 "
f"review results, found {len(results)}"
)
return checked
def validate_whitespace(errors: list[str]) -> None:
for path in sorted(ROOT.rglob("*")):
if not path.is_file():
continue
if path.suffix not in {".md", ".json", ".py", ".txt"}:
continue
for line_number, line in enumerate(
path.read_text(
encoding="utf-8",
errors="replace",
).splitlines(),
start=1,
):
if line != line.rstrip(" \t"):
errors.append(
f"{path.relative_to(ROOT)}:{line_number}: "
"trailing whitespace"
)
if any(ROOT.rglob("*.pyc")):
errors.append("Generated .pyc files exist")
if any(
path.is_dir()
for path in ROOT.rglob("__pycache__")
):
errors.append("__pycache__ exists")
def main() -> int:
errors: list[str] = []
features = load_catalog(errors)
reviewed = 0
if features:
validate_catalog(features, errors)
validate_domains(features, errors)
validate_catalog_markdown(features, errors)
reviewed = validate_reviews(features, errors)
validate_whitespace(errors)
print(f"Catalog Features: {len(features)}")
print(
"Unique Feature IDs:",
len({feature.get("id") for feature in features}),
)
print(
"Domain Files:",
len(list(DOMAINS_DIR.glob("*.md"))),
)
if features:
print(
"Statuses:",
dict(
Counter(
feature.get("status")
for feature in features
)
),
)
print(
"Evidence Maturity:",
dict(
Counter(
feature.get("evidence_maturity")
for feature in features
)
),
)
print(
"Runtime Validation:",
dict(
Counter(
(
feature.get(
"runtime_validation",
{},
).get("required"),
feature.get(
"runtime_validation",
{},
).get("status"),
)
for feature in features
)
),
)
print(f"Review Results Checked: {reviewed}")
print(f"Consistency Errors: {len(errors)}")
for error in errors:
print(f"ERROR: {error}")
return 1 if errors else 0
if __name__ == "__main__":
sys.exit(main())
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env python3
"""Validate the Odysseus public discovery documentation package."""
from __future__ import annotations
import argparse
import json
import re
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
REPO_ROOT = ROOT.parents[1]
CATALOG_PATH = ROOT / "feature-catalog.json"
DOMAINS_DIR = ROOT / "domains"
EXPECTED_COMMIT = "d8a2059df8e53bc7275c45339849d14c8651e73c"
ALLOWED_STATUSES = {
"verified", "partial", "disabled", "experimental", "legacy",
"dead-code-candidate", "unverified"
}
LINE_RANGE_RE = re.compile(r"^L([1-9]\d*)-L([1-9]\d*)$")
FEATURE_HEADING_RE = re.compile(
r"^##\s+`?([A-Z][A-Z0-9]*-\d{3})`?\s+(?:—|-)\s+.+$",
re.MULTILINE,
)
LINK_RE = re.compile(r"(?<!!)\[[^\]]*\]\(([^)]+)\)")
FORBIDDEN_TERMS_RE = re.compile(
r"(roadforge|kanban|matrix|owner link|editor link|github support|"
r"private maintainer|OD-AUD-|[A-Z]{2,10}-AUD-\d+|TASK-\d+)",
re.IGNORECASE,
)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Validate Odysseus discovery docs.")
parser.add_argument(
"--repo-root",
type=Path,
default=REPO_ROOT,
help="Path to Odysseus repository root.",
)
return parser.parse_args()
def validate() -> int:
args = parse_args()
repo_root = args.repo_root.resolve()
errors: list[str] = []
# 1. Validate Catalog JSON existence and content
if not CATALOG_PATH.is_file():
errors.append(f"Missing catalog file: {CATALOG_PATH}")
print(f"Errors: {len(errors)}")
for e in errors:
print(f"ERROR: {e}")
return 1
try:
catalog = json.loads(CATALOG_PATH.read_text(encoding="utf-8"))
except Exception as e:
errors.append(f"Failed to parse catalog JSON: {e}")
print(f"Errors: {len(errors)}")
for err in errors:
print(f"ERROR: {err}")
return 1
if not isinstance(catalog, list):
errors.append("feature-catalog.json must be a JSON array")
return 1
feature_ids = [item.get("id") for item in catalog if isinstance(item, dict)]
if len(feature_ids) != 79:
errors.append(f"Expected 79 unique feature IDs, found {len(feature_ids)}")
if len(feature_ids) != len(set(feature_ids)):
errors.append("Duplicate feature IDs found in catalog JSON")
# Domain catalog counts
catalog_domain_counts: dict[str, int] = {}
for item in catalog:
if not isinstance(item, dict):
errors.append("Catalog item is not an object")
continue
fid = item.get("id", "<missing>")
status = item.get("status")
domain = item.get("domain", "").lower()
catalog_domain_counts[domain] = catalog_domain_counts.get(domain, 0) + 1
if status not in ALLOWED_STATUSES:
errors.append(f"{fid}: Invalid status '{status}'")
evidence_list = item.get("evidence")
if not isinstance(evidence_list, list) or not evidence_list:
errors.append(f"{fid}: Missing or empty evidence list")
continue
for ev in evidence_list:
if not isinstance(ev, dict):
errors.append(f"{fid}: Evidence item is not an object")
continue
path_str = ev.get("path")
lr_str = str(ev.get("line_range", ""))
if not path_str or Path(path_str).is_absolute() or ".." in Path(path_str).parts:
errors.append(f"{fid}: Unsafe or invalid path '{path_str}'")
continue
# Check path exists in repo
target_path = repo_root / path_str
if not target_path.is_file():
errors.append(f"{fid}: Referenced path '{path_str}' does not exist on disk")
continue
# Check line range format & bounds
m = LINE_RANGE_RE.fullmatch(lr_str)
if not m:
errors.append(f"{fid}: Invalid line range format '{lr_str}' for path '{path_str}'")
continue
start, end = int(m.group(1)), int(m.group(2))
lines_cnt = len(target_path.read_text(encoding="utf-8", errors="ignore").splitlines())
if start > end or end > lines_cnt or start < 1:
errors.append(
f"{fid}: Line range '{lr_str}' exceeds file length ({lines_cnt} lines) in '{path_str}'"
)
# 2. Check Domain Markdown files
md_feature_ids: list[str] = []
domain_files = sorted(DOMAINS_DIR.glob("*.md"))
for df in domain_files:
domain_name = df.stem.lower()
content = df.read_text(encoding="utf-8")
found_ids = FEATURE_HEADING_RE.findall(content)
md_feature_ids.extend(found_ids)
if len(found_ids) != catalog_domain_counts.get(domain_name, 0):
errors.append(
f"Domain '{domain_name}' count mismatch: catalog has {catalog_domain_counts.get(domain_name, 0)}, Markdown has {len(found_ids)}"
)
if sorted(md_feature_ids) != sorted(feature_ids):
errors.append("Markdown domain feature IDs do not match catalog JSON feature IDs")
# 3. Check for forbidden/private terms, sensitive credentials, and broken links across all docs
for md_file in ROOT.rglob("*.md"):
rel_md = md_file.relative_to(ROOT)
content = md_file.read_text(encoding="utf-8")
# Forbidden terms scan
forbidden_matches = FORBIDDEN_TERMS_RE.findall(content)
if forbidden_matches:
errors.append(
f"{rel_md}: Found forbidden/internal terms: {set(forbidden_matches)}"
)
# Broken local link check
for target in LINK_RE.findall(content):
target = target.strip().strip("<>")
if not target or target.startswith(("#", "http://", "https://", "mailto:")):
continue
target_path = target.split("#", 1)[0]
resolved = (md_file.parent / target_path).resolve()
if not resolved.exists():
errors.append(f"{rel_md}: Broken local link '{target}'")
print(f"Catalog Features: {len(catalog)}")
print(f"Domain Files: {len(domain_files)}")
print(f"Validation Errors: {len(errors)}")
for err in errors:
print(f"ERROR: {err}")
return 1 if errors else 0
if __name__ == "__main__":
sys.exit(validate())
File diff suppressed because it is too large Load Diff
+1 -4
View File
@@ -38,10 +38,7 @@ python-dateutil
caldav
cryptography
bcrypt
# Built-in servers use the v1 low-level Server decorator API. MCP SDK v2 is a
# breaking rewrite, so keep fresh installs on the maintained v1 line until the
# servers are migrated together.
mcp<2
mcp
pyotp
qrcode[pil]
croniter
-5
View File
@@ -1,5 +0,0 @@
"""Search route domain package (slice 2j, #4082/#4071).
Contains search_routes.py, migrated from the flat routes/ directory.
Backward-compat shim at routes/search_routes.py re-exports from here.
"""
-111
View File
@@ -1,111 +0,0 @@
"""Search routes — /api/search/config GET, /api/search POST."""
import logging
from typing import Dict, Any
from fastapi import APIRouter, Request
import time
from services.search import get_search_config, comprehensive_web_search, PROVIDER_INFO
from services.search.core import _call_provider
from services.search.providers import _get_provider_key, _get_search_instance
logger = logging.getLogger(__name__)
async def _request_values(request: Request) -> Dict[str, Any]:
"""Accept JSON, form data, or query params for search endpoints.
The browser UI posts FormData, while the agent's generic app_api tool
posts JSON. FastAPI Form(...) rejects JSON with a 422 before our handler
runs, which made the model think SearXNG was broken.
"""
values: Dict[str, Any] = dict(request.query_params)
content_type = (request.headers.get("content-type") or "").lower()
try:
if "application/json" in content_type:
body = await request.json()
if isinstance(body, dict):
values.update(body)
else:
form = await request.form()
values.update(dict(form))
except Exception:
pass
return values
def setup_search_routes(config) -> APIRouter:
router = APIRouter(tags=["search"])
@router.get("/api/search/config")
async def get_search_settings() -> Dict[str, Any]:
return get_search_config()
@router.post("/api/search")
async def do_web_search(request: Request) -> Dict[str, Any]:
"""Standalone web search — returns context string + source list.
Used by Compare mode to pre-search once and share results across panes.
"""
values = await _request_values(request)
query = str(values.get("query") or values.get("q") or "").strip()
if not query:
return {"context": "", "sources": [], "error": "query is required"}
time_filter = values.get("time_filter") or values.get("freshness")
if time_filter is not None:
time_filter = str(time_filter).strip() or None
try:
context, sources = comprehensive_web_search(
query, return_sources=True, time_filter=time_filter,
)
return {"context": context, "sources": sources}
except Exception as e:
logger.error(f"Standalone web search failed: {e}")
return {"context": "", "sources": [], "error": str(e)}
@router.get("/api/search/providers")
async def list_search_providers():
"""Return available search providers with config status."""
providers = []
for pid, (label, needs_key, needs_url) in PROVIDER_INFO.items():
if pid == "disabled":
continue
available = True
if needs_key and not _get_provider_key(pid):
available = False
if needs_url and pid == "searxng" and not _get_search_instance():
available = False
providers.append({
"id": pid,
"label": label,
"available": available,
})
return providers
@router.post("/api/search/query")
async def search_with_provider(request: Request) -> Dict[str, Any]:
"""Search using a specific provider. Used by compare search mode."""
values = await _request_values(request)
query = str(values.get("query") or values.get("q") or "").strip()
provider = str(values.get("provider") or "").strip()
try:
count = int(values.get("count") or values.get("limit") or 10)
except Exception:
count = 10
if not query:
return {"results": [], "provider": provider, "error": "query is required"}
if provider not in PROVIDER_INFO or provider == "disabled":
return {"results": [], "provider": provider, "error": "Unknown provider"}
t0 = time.time()
try:
results = _call_provider(provider, query, min(count, 20))
elapsed = round(time.time() - t0, 2)
return {"results": results, "provider": provider, "time": elapsed}
except Exception as e:
elapsed = round(time.time() - t0, 2)
logger.error(f"Search provider {provider} failed: {e}")
return {"results": [], "provider": provider, "time": elapsed, "error": str(e)}
return router
+107 -9
View File
@@ -1,13 +1,111 @@
"""Backward-compat shim — canonical location is routes/search/search_routes.py.
"""Search routes — /api/search/config GET, /api/search POST."""
This module is replaced in ``sys.modules`` by the canonical module object so
that ``import routes.search_routes`` and ``from routes.search_routes import X``
keep resolving to the canonical module. Keeps existing import paths working
after slice 2j (#4082/#4071).
"""
import logging
from typing import Dict, Any
import sys as _sys
from fastapi import APIRouter, Request
from routes.search import search_routes as _canonical # noqa: F401
import time
_sys.modules[__name__] = _canonical
from services.search import get_search_config, comprehensive_web_search, PROVIDER_INFO
from services.search.core import _call_provider
from services.search.providers import _get_provider_key, _get_search_instance
logger = logging.getLogger(__name__)
async def _request_values(request: Request) -> Dict[str, Any]:
"""Accept JSON, form data, or query params for search endpoints.
The browser UI posts FormData, while the agent's generic app_api tool
posts JSON. FastAPI Form(...) rejects JSON with a 422 before our handler
runs, which made the model think SearXNG was broken.
"""
values: Dict[str, Any] = dict(request.query_params)
content_type = (request.headers.get("content-type") or "").lower()
try:
if "application/json" in content_type:
body = await request.json()
if isinstance(body, dict):
values.update(body)
else:
form = await request.form()
values.update(dict(form))
except Exception:
pass
return values
def setup_search_routes(config) -> APIRouter:
router = APIRouter(tags=["search"])
@router.get("/api/search/config")
async def get_search_settings() -> Dict[str, Any]:
return get_search_config()
@router.post("/api/search")
async def do_web_search(request: Request) -> Dict[str, Any]:
"""Standalone web search — returns context string + source list.
Used by Compare mode to pre-search once and share results across panes.
"""
values = await _request_values(request)
query = str(values.get("query") or values.get("q") or "").strip()
if not query:
return {"context": "", "sources": [], "error": "query is required"}
time_filter = values.get("time_filter") or values.get("freshness")
if time_filter is not None:
time_filter = str(time_filter).strip() or None
try:
context, sources = comprehensive_web_search(
query, return_sources=True, time_filter=time_filter,
)
return {"context": context, "sources": sources}
except Exception as e:
logger.error(f"Standalone web search failed: {e}")
return {"context": "", "sources": [], "error": str(e)}
@router.get("/api/search/providers")
async def list_search_providers():
"""Return available search providers with config status."""
providers = []
for pid, (label, needs_key, needs_url) in PROVIDER_INFO.items():
if pid == "disabled":
continue
available = True
if needs_key and not _get_provider_key(pid):
available = False
if needs_url and pid == "searxng" and not _get_search_instance():
available = False
providers.append({
"id": pid,
"label": label,
"available": available,
})
return providers
@router.post("/api/search/query")
async def search_with_provider(request: Request) -> Dict[str, Any]:
"""Search using a specific provider. Used by compare search mode."""
values = await _request_values(request)
query = str(values.get("query") or values.get("q") or "").strip()
provider = str(values.get("provider") or "").strip()
try:
count = int(values.get("count") or values.get("limit") or 10)
except Exception:
count = 10
if not query:
return {"results": [], "provider": provider, "error": "query is required"}
if provider not in PROVIDER_INFO or provider == "disabled":
return {"results": [], "provider": provider, "error": "Unknown provider"}
t0 = time.time()
try:
results = _call_provider(provider, query, min(count, 20))
elapsed = round(time.time() - t0, 2)
return {"results": results, "provider": provider, "time": elapsed}
except Exception as e:
elapsed = round(time.time() - t0, 2)
logger.error(f"Search provider {provider} failed: {e}")
return {"results": [], "provider": provider, "time": elapsed, "error": str(e)}
return router
+1 -1
View File
@@ -1409,7 +1409,7 @@ def setup_skills_routes(skills_manager: SkillsManager) -> APIRouter:
# Prefer the configured DEFAULT (→ Utility) model — not the current chat
# session's model. Fall back to the caller's session model only if unset.
url, model, headers = resolve_endpoint("utility", owner=user)
url, model, headers = resolve_endpoint("default", owner=user)
if not url or not model:
url = url or ((body.get("endpoint_url") or "").strip() or None)
model = model or ((body.get("model") or "").strip() or None)
-5
View File
@@ -1,5 +0,0 @@
"""Vault route domain package (slice 2k, #4082/#4071).
Contains vault_routes.py, migrated from the flat routes/ directory.
Backward-compat shim at routes/vault_routes.py re-exports from here.
"""
-242
View File
@@ -1,242 +0,0 @@
"""
vault_routes.py
Vaultwarden / Bitwarden CLI integration config and unlock endpoints.
Stores the BW_SESSION key in data/vault.json with restrictive permissions.
"""
import json
import logging
import os
import shutil
import asyncio
from pathlib import Path
from datetime import datetime
from fastapi import APIRouter, Request
from pydantic import BaseModel
from core.middleware import require_admin
from core.platform_compat import IS_WINDOWS, safe_chmod, which_tool
from src.constants import VAULT_FILE as _VAULT_FILE
logger = logging.getLogger(__name__)
VAULT_FILE = Path(_VAULT_FILE)
def _find_bw() -> str:
"""Locate the bw binary, checking PATH and common npm-global locations.
On Windows the Bitwarden CLI shim is `bw.cmd`/`bw.exe`, resolved by
which_tool via PATHEXT.
"""
p = which_tool("bw")
if p:
return p
if IS_WINDOWS:
appdata = os.environ.get("APPDATA", os.path.expanduser("~"))
for candidate in (
os.path.join(appdata, "npm", "bw.cmd"),
os.path.join(appdata, "npm", "bw.exe"),
):
if os.path.isfile(candidate):
return candidate
return "bw"
home = os.path.expanduser("~")
for candidate in (
f"{home}/.npm-global/bin/bw",
f"{home}/.nvm/versions/node/*/bin/bw",
"/usr/local/bin/bw",
"/opt/homebrew/bin/bw",
):
if "*" in candidate:
import glob
for m in glob.glob(candidate):
if os.path.isfile(m) and os.access(m, os.X_OK):
return m
elif os.path.isfile(candidate) and os.access(candidate, os.X_OK):
return candidate
return "bw" # fall back to PATH lookup (will FileNotFoundError, handled below)
def _load_config() -> dict:
if VAULT_FILE.exists():
try:
data = json.loads(VAULT_FILE.read_text(encoding="utf-8"))
return data if isinstance(data, dict) else {}
except Exception:
pass
return {}
def _save_config(cfg: dict):
VAULT_FILE.parent.mkdir(parents=True, exist_ok=True)
VAULT_FILE.write_text(json.dumps(cfg, indent=2), encoding="utf-8")
# POSIX: restrict the BW_SESSION store to 0o600. Windows: no-op (profile dir
# is ACL-restricted already).
safe_chmod(str(VAULT_FILE), 0o600)
async def _run_bw(args: list, session: str = None, input_text: str = None,
bw_password: str = None) -> tuple:
env = {}
env.update(os.environ)
if session:
env["BW_SESSION"] = session
# Secrets must never be passed as argv — process arguments are world-readable
# via `ps` / `/proc/<pid>/cmdline` to any local user. Keep --passwordenv
# support for bw commands that need it; unlock/login callers should prefer
# stdin so the master password is not left in the child environment either.
if bw_password is not None:
env["BW_PASSWORD"] = bw_password
bw_path = _find_bw()
try:
proc = await asyncio.create_subprocess_exec(
bw_path, *args,
stdin=asyncio.subprocess.PIPE if input_text else None,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
env=env,
)
except FileNotFoundError:
return "", "bw CLI not installed (install `nodejs-bitwarden-cli` or `bitwarden-cli`)", 127
except Exception as e:
return "", f"Failed to launch bw: {e}", 1
try:
stdout, stderr = await proc.communicate(input=input_text.encode() if input_text else None)
except Exception as e:
return "", f"bw subprocess error: {e}", 1
return stdout.decode(errors="replace").strip(), stderr.decode(errors="replace").strip(), proc.returncode
class VaultConfig(BaseModel):
server_url: str = ""
email: str = ""
class VaultUnlockRequest(BaseModel):
master_password: str
class VaultLoginRequest(BaseModel):
email: str
master_password: str
def setup_vault_routes():
router = APIRouter(prefix="/api/vault", tags=["vault"])
@router.get("/config")
async def get_config(request: Request):
"""Return vault config (no sensitive fields)."""
require_admin(request)
cfg = _load_config()
return {
"server_url": cfg.get("server_url", ""),
"email": cfg.get("email", ""),
"unlocked": bool(cfg.get("session")),
"unlocked_at": cfg.get("unlocked_at", ""),
"bw_installed": await _check_bw_installed(),
}
@router.post("/config")
async def save_config(req: VaultConfig, request: Request):
"""Save vault URL + email. Runs 'bw config server' to point at Vaultwarden."""
require_admin(request)
cfg = _load_config()
cfg["server_url"] = req.server_url.strip().rstrip("/")
cfg["email"] = req.email.strip()
if cfg["server_url"]:
_, stderr, rc = await _run_bw(["config", "server", cfg["server_url"]])
if rc != 0:
return {"ok": False, "error": f"bw config failed: {stderr[:300]}"}
_save_config(cfg)
return {"ok": True}
@router.post("/login")
async def login(req: VaultLoginRequest, request: Request):
"""Log in to Vaultwarden (required once per account)."""
require_admin(request)
cfg = _load_config()
# Update email
cfg["email"] = req.email
_save_config(cfg)
stdout, stderr, rc = await _run_bw(
["login", req.email, "--raw"],
input_text=req.master_password + "\n",
)
if rc != 0:
# Already logged in is OK
if "already logged in" in stderr.lower():
return {"ok": True, "already": True}
return {"ok": False, "error": f"Login failed: {stderr[:300]}"}
# bw login --raw prints session key on success (when 2FA disabled)
if stdout:
cfg["session"] = stdout
cfg["unlocked_at"] = datetime.utcnow().isoformat()
_save_config(cfg)
return {"ok": True}
@router.post("/unlock")
async def unlock(req: VaultUnlockRequest, request: Request):
"""Unlock the vault and save the session key."""
require_admin(request)
# Pass the master password on stdin, not argv. argv is visible through
# `ps` / /proc/<pid>/cmdline; stdin also avoids leaving the secret in
# the child process environment.
stdout, stderr, rc = await _run_bw(
["unlock", "--raw"],
input_text=req.master_password + "\n",
)
if rc != 0:
return {"ok": False, "error": f"Unlock failed: {stderr[:300]}"}
session = stdout.strip()
if not session:
return {"ok": False, "error": "bw returned empty session"}
cfg = _load_config()
cfg["session"] = session
cfg["unlocked_at"] = datetime.utcnow().isoformat()
_save_config(cfg)
return {"ok": True, "message": "Vault unlocked"}
@router.post("/lock")
async def lock(request: Request):
"""Lock the vault (clear session from config)."""
require_admin(request)
cfg = _load_config()
cfg.pop("session", None)
cfg.pop("unlocked_at", None)
_save_config(cfg)
# Also tell bw to lock
await _run_bw(["lock"])
return {"ok": True, "message": "Vault locked"}
@router.post("/logout")
async def logout(request: Request):
"""Log out of the Bitwarden CLI completely."""
require_admin(request)
await _run_bw(["logout"])
cfg = _load_config()
cfg.pop("session", None)
cfg.pop("email", None)
cfg.pop("unlocked_at", None)
_save_config(cfg)
return {"ok": True}
return router
async def _check_bw_installed() -> bool:
try:
proc = await asyncio.create_subprocess_exec(
_find_bw(), "--version",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
await proc.communicate()
return proc.returncode == 0
except Exception:
return False
+237 -9
View File
@@ -1,14 +1,242 @@
"""Backward-compat shim — canonical location is routes/vault/vault_routes.py.
"""
vault_routes.py
This module is replaced in ``sys.modules`` by the canonical module object so
that ``import routes.vault_routes``, ``from routes.vault_routes import X``,
and the ``import ... as vr`` + ``monkeypatch.setattr(vr, ...)`` pattern used
by test_vault_password_not_in_argv.py all operate on the *same* object.
Keeps existing import paths working after slice 2k (#4082/#4071).
Vaultwarden / Bitwarden CLI integration config and unlock endpoints.
Stores the BW_SESSION key in data/vault.json with restrictive permissions.
"""
import sys as _sys
import json
import logging
import os
import shutil
import asyncio
from pathlib import Path
from datetime import datetime
from fastapi import APIRouter, Request
from pydantic import BaseModel
from routes.vault import vault_routes as _canonical # noqa: F401
from core.middleware import require_admin
from core.platform_compat import IS_WINDOWS, safe_chmod, which_tool
from src.constants import VAULT_FILE as _VAULT_FILE
_sys.modules[__name__] = _canonical
logger = logging.getLogger(__name__)
VAULT_FILE = Path(_VAULT_FILE)
def _find_bw() -> str:
"""Locate the bw binary, checking PATH and common npm-global locations.
On Windows the Bitwarden CLI shim is `bw.cmd`/`bw.exe`, resolved by
which_tool via PATHEXT.
"""
p = which_tool("bw")
if p:
return p
if IS_WINDOWS:
appdata = os.environ.get("APPDATA", os.path.expanduser("~"))
for candidate in (
os.path.join(appdata, "npm", "bw.cmd"),
os.path.join(appdata, "npm", "bw.exe"),
):
if os.path.isfile(candidate):
return candidate
return "bw"
home = os.path.expanduser("~")
for candidate in (
f"{home}/.npm-global/bin/bw",
f"{home}/.nvm/versions/node/*/bin/bw",
"/usr/local/bin/bw",
"/opt/homebrew/bin/bw",
):
if "*" in candidate:
import glob
for m in glob.glob(candidate):
if os.path.isfile(m) and os.access(m, os.X_OK):
return m
elif os.path.isfile(candidate) and os.access(candidate, os.X_OK):
return candidate
return "bw" # fall back to PATH lookup (will FileNotFoundError, handled below)
def _load_config() -> dict:
if VAULT_FILE.exists():
try:
data = json.loads(VAULT_FILE.read_text(encoding="utf-8"))
return data if isinstance(data, dict) else {}
except Exception:
pass
return {}
def _save_config(cfg: dict):
VAULT_FILE.parent.mkdir(parents=True, exist_ok=True)
VAULT_FILE.write_text(json.dumps(cfg, indent=2), encoding="utf-8")
# POSIX: restrict the BW_SESSION store to 0o600. Windows: no-op (profile dir
# is ACL-restricted already).
safe_chmod(str(VAULT_FILE), 0o600)
async def _run_bw(args: list, session: str = None, input_text: str = None,
bw_password: str = None) -> tuple:
env = {}
env.update(os.environ)
if session:
env["BW_SESSION"] = session
# Secrets must never be passed as argv — process arguments are world-readable
# via `ps` / `/proc/<pid>/cmdline` to any local user. Keep --passwordenv
# support for bw commands that need it; unlock/login callers should prefer
# stdin so the master password is not left in the child environment either.
if bw_password is not None:
env["BW_PASSWORD"] = bw_password
bw_path = _find_bw()
try:
proc = await asyncio.create_subprocess_exec(
bw_path, *args,
stdin=asyncio.subprocess.PIPE if input_text else None,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
env=env,
)
except FileNotFoundError:
return "", "bw CLI not installed (install `nodejs-bitwarden-cli` or `bitwarden-cli`)", 127
except Exception as e:
return "", f"Failed to launch bw: {e}", 1
try:
stdout, stderr = await proc.communicate(input=input_text.encode() if input_text else None)
except Exception as e:
return "", f"bw subprocess error: {e}", 1
return stdout.decode(errors="replace").strip(), stderr.decode(errors="replace").strip(), proc.returncode
class VaultConfig(BaseModel):
server_url: str = ""
email: str = ""
class VaultUnlockRequest(BaseModel):
master_password: str
class VaultLoginRequest(BaseModel):
email: str
master_password: str
def setup_vault_routes():
router = APIRouter(prefix="/api/vault", tags=["vault"])
@router.get("/config")
async def get_config(request: Request):
"""Return vault config (no sensitive fields)."""
require_admin(request)
cfg = _load_config()
return {
"server_url": cfg.get("server_url", ""),
"email": cfg.get("email", ""),
"unlocked": bool(cfg.get("session")),
"unlocked_at": cfg.get("unlocked_at", ""),
"bw_installed": await _check_bw_installed(),
}
@router.post("/config")
async def save_config(req: VaultConfig, request: Request):
"""Save vault URL + email. Runs 'bw config server' to point at Vaultwarden."""
require_admin(request)
cfg = _load_config()
cfg["server_url"] = req.server_url.strip().rstrip("/")
cfg["email"] = req.email.strip()
if cfg["server_url"]:
_, stderr, rc = await _run_bw(["config", "server", cfg["server_url"]])
if rc != 0:
return {"ok": False, "error": f"bw config failed: {stderr[:300]}"}
_save_config(cfg)
return {"ok": True}
@router.post("/login")
async def login(req: VaultLoginRequest, request: Request):
"""Log in to Vaultwarden (required once per account)."""
require_admin(request)
cfg = _load_config()
# Update email
cfg["email"] = req.email
_save_config(cfg)
stdout, stderr, rc = await _run_bw(
["login", req.email, "--raw"],
input_text=req.master_password + "\n",
)
if rc != 0:
# Already logged in is OK
if "already logged in" in stderr.lower():
return {"ok": True, "already": True}
return {"ok": False, "error": f"Login failed: {stderr[:300]}"}
# bw login --raw prints session key on success (when 2FA disabled)
if stdout:
cfg["session"] = stdout
cfg["unlocked_at"] = datetime.utcnow().isoformat()
_save_config(cfg)
return {"ok": True}
@router.post("/unlock")
async def unlock(req: VaultUnlockRequest, request: Request):
"""Unlock the vault and save the session key."""
require_admin(request)
# Pass the master password on stdin, not argv. argv is visible through
# `ps` / /proc/<pid>/cmdline; stdin also avoids leaving the secret in
# the child process environment.
stdout, stderr, rc = await _run_bw(
["unlock", "--raw"],
input_text=req.master_password + "\n",
)
if rc != 0:
return {"ok": False, "error": f"Unlock failed: {stderr[:300]}"}
session = stdout.strip()
if not session:
return {"ok": False, "error": "bw returned empty session"}
cfg = _load_config()
cfg["session"] = session
cfg["unlocked_at"] = datetime.utcnow().isoformat()
_save_config(cfg)
return {"ok": True, "message": "Vault unlocked"}
@router.post("/lock")
async def lock(request: Request):
"""Lock the vault (clear session from config)."""
require_admin(request)
cfg = _load_config()
cfg.pop("session", None)
cfg.pop("unlocked_at", None)
_save_config(cfg)
# Also tell bw to lock
await _run_bw(["lock"])
return {"ok": True, "message": "Vault locked"}
@router.post("/logout")
async def logout(request: Request):
"""Log out of the Bitwarden CLI completely."""
require_admin(request)
await _run_bw(["logout"])
cfg = _load_config()
cfg.pop("session", None)
cfg.pop("email", None)
cfg.pop("unlocked_at", None)
_save_config(cfg)
return {"ok": True}
return router
async def _check_bw_installed() -> bool:
try:
proc = await asyncio.create_subprocess_exec(
_find_bw(), "--version",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
await proc.communicate()
return proc.returncode == 0
except Exception:
return False
-5
View File
@@ -1,5 +0,0 @@
"""Webhook route domain package (slice 2l, #4082/#4071).
Contains webhook_routes.py, migrated from the flat routes/ directory.
Backward-compat shim at routes/webhook_routes.py re-exports from here.
"""
-395
View File
@@ -1,395 +0,0 @@
"""Webhook, API Token, and sync chat routes."""
import uuid
import logging
from typing import Optional
import httpx
from fastapi import APIRouter, HTTPException, Request, Form
from pydantic import BaseModel, Field
from core.database import SessionLocal, Webhook, ModelEndpoint
from src.auth_helpers import owner_filter
from src.url_security import validate_public_http_url
from src.webhook_manager import WebhookManager, validate_webhook_url, validate_events
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api", tags=["webhooks"])
# Input limits
MAX_NAME_LEN = 100
MAX_URL_LEN = 2048
MAX_SECRET_LEN = 256
MAX_MESSAGE_LEN = 32_000
from core.middleware import require_admin as _require_admin
def _select_api_chat_fallback_endpoint(db, token_owner: Optional[str]):
"""First enabled ModelEndpoint visible to token_owner — their own rows plus
legacy null-owner ("shared") rows. Owner-scoped: an unscoped .first() would
let a chat-scoped token fall back onto another user's private endpoint and
silently spend that owner's API key/quota. Prefer owner rows before shared
rows. Fails closed to null-owner rows only when token_owner is absent.
Does not validate base_url admin-configured local/LAN endpoints remain allowed.
"""
query = db.query(ModelEndpoint).filter(ModelEndpoint.is_enabled == True) # noqa: E712
if token_owner:
query = owner_filter(query, ModelEndpoint, token_owner)
return query.order_by(ModelEndpoint.owner.desc(), ModelEndpoint.created_at).first()
return query.filter(ModelEndpoint.owner == None).order_by(ModelEndpoint.created_at).first() # noqa: E711
def _caller_owns_session(sess_owner, caller) -> bool:
"""Strict session-ownership gate for the token-authenticated sync-chat
endpoint (`POST /api/v1/chat`).
Mirrors ``_verify_session_owner`` in session_routes.py and the null-owner
gates in notes/calendar/gallery: a caller may resume a session ONLY when
its owner matches them exactly. A null/empty session owner (legacy or
migrated rows) is deliberately NOT resumable by an arbitrary token the
old ``sess_owner and sess_owner != caller`` form skipped the check whenever
``sess_owner`` was falsy, so any chat-scoped token (e.g. a paired mobile
device) could resume such a session, inject a message, and read back its
history and reuse the owner's endpoint credentials. Fail closed: an
unresolvable caller also returns False.
"""
if not caller:
return False
return sess_owner == caller
def setup_webhook_routes(
webhook_manager: WebhookManager,
auth_manager,
session_manager=None,
api_key_manager=None,
) -> APIRouter:
@router.get("/webhooks")
def list_webhooks(request: Request):
_require_admin(request)
db = SessionLocal()
try:
hooks = db.query(Webhook).all()
return [
{
"id": w.id,
"name": w.name,
"url": w.url,
"has_secret": bool(w.secret),
"events": w.events.split(",") if w.events else [],
"is_active": w.is_active,
"last_triggered_at": w.last_triggered_at.isoformat() if w.last_triggered_at else None,
"last_status_code": w.last_status_code,
"last_error": w.last_error,
"created_at": w.created_at.isoformat() if w.created_at else None,
}
for w in hooks
]
finally:
db.close()
@router.post("/webhooks")
def create_webhook(
request: Request,
name: str = Form(""),
url: str = Form(""),
secret: str = Form(""),
events: str = Form(""),
):
_require_admin(request)
name = name.strip()[:MAX_NAME_LEN]
if not name:
raise HTTPException(400, "Webhook name is required")
try:
url = validate_webhook_url(url)
except ValueError as e:
raise HTTPException(400, str(e))
try:
events = validate_events(events)
except ValueError as e:
raise HTTPException(400, str(e))
secret_val = secret.strip()[:MAX_SECRET_LEN] or None
# Encrypt the secret at rest using the same Fernet key as API keys
encrypted_secret = None
if secret_val and api_key_manager:
encrypted_secret = api_key_manager.encrypt_api_key(secret_val)
elif secret_val:
encrypted_secret = secret_val # Fallback if no encryption available
webhook_id = str(uuid.uuid4())[:8]
db = SessionLocal()
try:
db.add(Webhook(
id=webhook_id,
name=name,
url=url,
secret=encrypted_secret,
events=events,
is_active=True,
))
db.commit()
finally:
db.close()
return {"id": webhook_id, "name": name}
@router.post("/webhooks/{webhook_id}/test")
async def test_webhook(request: Request, webhook_id: str):
_require_admin(request)
db = SessionLocal()
try:
wh = db.query(Webhook).filter(Webhook.id == webhook_id).first()
if not wh:
raise HTTPException(404, "Webhook not found")
url, secret = wh.url, wh.secret
finally:
db.close()
await webhook_manager.deliver_test(webhook_id, url, secret)
return {"status": "sent"}
@router.patch("/webhooks/{webhook_id}")
def toggle_webhook(request: Request, webhook_id: str):
_require_admin(request)
db = SessionLocal()
try:
wh = db.query(Webhook).filter(Webhook.id == webhook_id).first()
if not wh:
raise HTTPException(404, "Webhook not found")
wh.is_active = not wh.is_active
db.commit()
return {"id": webhook_id, "is_active": wh.is_active}
finally:
db.close()
@router.delete("/webhooks/{webhook_id}")
def delete_webhook(request: Request, webhook_id: str):
_require_admin(request)
db = SessionLocal()
try:
deleted = db.query(Webhook).filter(Webhook.id == webhook_id).delete()
db.commit()
if not deleted:
raise HTTPException(404, "Webhook not found")
finally:
db.close()
return {"status": "deleted"}
# ================================================================
# Sync Chat Endpoint (for n8n / Make / Activepieces)
# ================================================================
# Known provider base URLs — auto-resolved from api_key prefix or model name
KNOWN_PROVIDERS = {
"deepseek": "https://api.deepseek.com/v1",
"openai": "https://api.openai.com/v1",
"mistral": "https://api.mistral.ai/v1",
"groq": "https://api.groq.com/openai/v1",
"together": "https://api.together.xyz/v1",
"openrouter": "https://openrouter.ai/api/v1",
"ollama": "https://ollama.com/api",
"opencode-zen": "https://opencode.ai/zen/v1",
"opencode-go": "https://opencode.ai/zen/go/v1",
"fireworks": "https://api.fireworks.ai/inference/v1",
"venice": "https://api.venice.ai/api/v1",
"kimi-code": "https://api.kimi.com/coding/v1",
"kimicode": "https://api.kimi.com/coding/v1",
}
# Model prefix → provider mapping for auto-detection
MODEL_PROVIDER_MAP = {
"deepseek": "deepseek",
"gpt-": "openai",
"o1": "openai",
"o3": "openai",
"o4": "openai",
"mistral": "mistral",
"llama": "groq",
"mixtral": "groq",
"kimi-for-coding": "kimi-code",
"kimi": "kimi-code",
}
def _resolve_base_url(model: Optional[str], provider: Optional[str]) -> Optional[str]:
"""Try to auto-resolve a base URL from provider name or model prefix."""
if provider and provider.lower() in KNOWN_PROVIDERS:
return KNOWN_PROVIDERS[provider.lower()]
if model:
model_lower = model.lower()
for prefix, prov in MODEL_PROVIDER_MAP.items():
if model_lower.startswith(prefix):
return KNOWN_PROVIDERS[prov]
return None
class SyncChatRequest(BaseModel):
message: str = Field(..., max_length=MAX_MESSAGE_LEN)
model: Optional[str] = Field(None, max_length=200)
session: Optional[str] = Field(None, max_length=100)
api_key: Optional[str] = Field(None, max_length=256)
base_url: Optional[str] = Field(None, max_length=MAX_URL_LEN)
provider: Optional[str] = Field(None, max_length=50)
@router.post("/v1/chat")
async def sync_chat(request: Request, body: SyncChatRequest):
if not getattr(request.state, "api_token", False):
raise HTTPException(403, "This endpoint requires an API token")
scopes = set(getattr(request.state, "api_token_scopes", []) or [])
if "chat" not in scopes:
raise HTTPException(403, "API token is not scoped for chat")
token_owner = getattr(request.state, "api_token_owner", None)
from core.models import ChatMessage
from src.llm_core import llm_call_async
from src.endpoint_resolver import build_chat_url, build_headers, build_models_url, normalize_base
message = body.message.strip()
if not message:
raise HTTPException(400, "Message is required")
session_id = body.session
sess = None
# --- Case 1: Resume an existing session ---
if session_id and session_manager:
try:
sess = session_manager.get_session(session_id)
except (KeyError, Exception):
raise HTTPException(404, "Session not found")
# SECURITY: verify the API-token's user owns this session — without
# this any token holder could resume any user's chat by passing its
# ID. The token's user is on request.state.user (set by API-token
# middleware); fall back to require_user if not present.
try:
from src.auth_helpers import get_current_user as _gcu
_tok_user = token_owner or getattr(request.state, "user", None) or _gcu(request)
except Exception:
_tok_user = None
# Strict ownership (see _caller_owns_session): fail closed so a
# null-owner / cross-owner session can't be resumed by an arbitrary
# chat-scoped token.
_sess_owner = getattr(sess, "owner", None)
if not _caller_owns_session(_sess_owner, _tok_user):
raise HTTPException(404, "Session not found")
# --- Case 2: Direct API key + model (no pre-configured endpoint needed) ---
if not sess and body.api_key:
api_key = body.api_key.strip()
model = body.model or "deepseek-chat"
# Validate only token-supplied direct base_url; auto-resolved known-provider
# URLs are not subject to extra local/LAN blocking beyond existing provider logic.
direct_base_url = body.base_url.strip().rstrip("/") if body.base_url else None
if direct_base_url:
try:
base_url = validate_public_http_url(direct_base_url)
except ValueError as e:
detail = str(e).replace("URL", "base_url", 1)
raise HTTPException(400, detail)
else:
base_url = _resolve_base_url(model, body.provider)
if not base_url:
raise HTTPException(400,
"Could not auto-detect provider. Pass base_url (e.g. 'https://api.deepseek.com/v1') "
"or provider ('deepseek', 'openai', 'groq', etc.)")
base_url = normalize_base(base_url)
endpoint_url = build_chat_url(base_url)
if not session_manager:
raise HTTPException(500, "Session manager not available")
sid = str(uuid.uuid4())
sess = session_manager.create_session(
session_id=sid, name="API Chat", endpoint_url=endpoint_url,
model=model, owner=token_owner,
)
sess.headers = build_headers(api_key, base_url)
session_manager.save_sessions()
session_id = sid
# --- Case 3: Fall back to first configured ModelEndpoint ---
if not sess:
db = SessionLocal()
try:
ep = _select_api_chat_fallback_endpoint(db, token_owner)
finally:
db.close()
if not ep:
raise HTTPException(400,
"No session, api_key, or configured endpoints. "
"Pass api_key + model, or configure an endpoint in Admin.")
base_url = normalize_base(ep.base_url)
endpoint_url = build_chat_url(base_url)
model = body.model or "auto"
api_key = ep.api_key
if getattr(ep, "provider_auth_id", None):
try:
from src.endpoint_resolver import resolve_endpoint_runtime
base_url, api_key = resolve_endpoint_runtime(ep, owner=token_owner)
endpoint_url = build_chat_url(base_url)
except Exception:
raise HTTPException(500, "Could not resolve endpoint credentials")
if model == "auto":
try:
async with httpx.AsyncClient(timeout=5) as client:
models_url = build_models_url(base_url)
hdrs = build_headers(api_key, base_url)
if models_url:
resp = await client.get(models_url, headers=hdrs)
resp.raise_for_status()
data = resp.json()
items = data if isinstance(data, list) else (data.get("data") or [])
ids = [m.get("id") for m in items if isinstance(m, dict) and m.get("id")]
if not ids and isinstance(data, dict):
ids = [
m.get("name") or m.get("model")
for m in (data.get("models") or [])
if m.get("name") or m.get("model")
]
else:
import json as _json
ids = _json.loads(ep.cached_models or "[]")
model = ids[0] if ids else "auto"
except Exception:
raise HTTPException(500, "Could not discover models from endpoint")
if not session_manager:
raise HTTPException(500, "Session manager not available")
sid = str(uuid.uuid4())
sess = session_manager.create_session(
session_id=sid, name="API Chat", endpoint_url=endpoint_url,
model=model, owner=token_owner,
)
if api_key:
sess.headers = build_headers(api_key, base_url)
session_manager.save_sessions()
session_id = sid
# --- Send message and get response ---
sess.add_message(ChatMessage("user", message))
messages = [{"role": m.role, "content": m.content} for m in sess.history]
reply = await llm_call_async(
sess.endpoint_url, sess.model, messages,
headers=sess.headers, timeout=120,
)
sess.add_message(ChatMessage("assistant", reply))
session_manager.save_sessions()
webhook_manager.fire_and_forget("chat.completed", {
"session_id": session_id, "model": sess.model,
"user_message": message[:2000], "response": reply[:2000],
})
return {"response": reply, "session_id": session_id, "model": sess.model}
return router
+391 -12
View File
@@ -1,16 +1,395 @@
"""Backward-compat shim — canonical location is routes/webhook/webhook_routes.py.
"""Webhook, API Token, and sync chat routes."""
This module is replaced in ``sys.modules`` by the canonical module object so
that ``import routes.webhook_routes``, ``from routes.webhook_routes import X``,
``importlib.import_module("routes.webhook_routes")``, and the
``__import__("routes.webhook_routes", fromlist=[...])`` + ``setattr(wh_mod,
...)`` pattern used by test_null_owner_gates.py all operate on the *same*
object. Keeps existing import paths working after slice 2l (#4082/#4071).
Source-introspection tests read the canonical file by path.
"""
import uuid
import logging
from typing import Optional
import sys as _sys
import httpx
from fastapi import APIRouter, HTTPException, Request, Form
from pydantic import BaseModel, Field
from routes.webhook import webhook_routes as _canonical # noqa: F401
from core.database import SessionLocal, Webhook, ModelEndpoint
from src.auth_helpers import owner_filter
from src.url_security import validate_public_http_url
from src.webhook_manager import WebhookManager, validate_webhook_url, validate_events
_sys.modules[__name__] = _canonical
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api", tags=["webhooks"])
# Input limits
MAX_NAME_LEN = 100
MAX_URL_LEN = 2048
MAX_SECRET_LEN = 256
MAX_MESSAGE_LEN = 32_000
from core.middleware import require_admin as _require_admin
def _select_api_chat_fallback_endpoint(db, token_owner: Optional[str]):
"""First enabled ModelEndpoint visible to token_owner — their own rows plus
legacy null-owner ("shared") rows. Owner-scoped: an unscoped .first() would
let a chat-scoped token fall back onto another user's private endpoint and
silently spend that owner's API key/quota. Prefer owner rows before shared
rows. Fails closed to null-owner rows only when token_owner is absent.
Does not validate base_url admin-configured local/LAN endpoints remain allowed.
"""
query = db.query(ModelEndpoint).filter(ModelEndpoint.is_enabled == True) # noqa: E712
if token_owner:
query = owner_filter(query, ModelEndpoint, token_owner)
return query.order_by(ModelEndpoint.owner.desc(), ModelEndpoint.created_at).first()
return query.filter(ModelEndpoint.owner == None).order_by(ModelEndpoint.created_at).first() # noqa: E711
def _caller_owns_session(sess_owner, caller) -> bool:
"""Strict session-ownership gate for the token-authenticated sync-chat
endpoint (`POST /api/v1/chat`).
Mirrors ``_verify_session_owner`` in session_routes.py and the null-owner
gates in notes/calendar/gallery: a caller may resume a session ONLY when
its owner matches them exactly. A null/empty session owner (legacy or
migrated rows) is deliberately NOT resumable by an arbitrary token the
old ``sess_owner and sess_owner != caller`` form skipped the check whenever
``sess_owner`` was falsy, so any chat-scoped token (e.g. a paired mobile
device) could resume such a session, inject a message, and read back its
history and reuse the owner's endpoint credentials. Fail closed: an
unresolvable caller also returns False.
"""
if not caller:
return False
return sess_owner == caller
def setup_webhook_routes(
webhook_manager: WebhookManager,
auth_manager,
session_manager=None,
api_key_manager=None,
) -> APIRouter:
@router.get("/webhooks")
def list_webhooks(request: Request):
_require_admin(request)
db = SessionLocal()
try:
hooks = db.query(Webhook).all()
return [
{
"id": w.id,
"name": w.name,
"url": w.url,
"has_secret": bool(w.secret),
"events": w.events.split(",") if w.events else [],
"is_active": w.is_active,
"last_triggered_at": w.last_triggered_at.isoformat() if w.last_triggered_at else None,
"last_status_code": w.last_status_code,
"last_error": w.last_error,
"created_at": w.created_at.isoformat() if w.created_at else None,
}
for w in hooks
]
finally:
db.close()
@router.post("/webhooks")
def create_webhook(
request: Request,
name: str = Form(""),
url: str = Form(""),
secret: str = Form(""),
events: str = Form(""),
):
_require_admin(request)
name = name.strip()[:MAX_NAME_LEN]
if not name:
raise HTTPException(400, "Webhook name is required")
try:
url = validate_webhook_url(url)
except ValueError as e:
raise HTTPException(400, str(e))
try:
events = validate_events(events)
except ValueError as e:
raise HTTPException(400, str(e))
secret_val = secret.strip()[:MAX_SECRET_LEN] or None
# Encrypt the secret at rest using the same Fernet key as API keys
encrypted_secret = None
if secret_val and api_key_manager:
encrypted_secret = api_key_manager.encrypt_api_key(secret_val)
elif secret_val:
encrypted_secret = secret_val # Fallback if no encryption available
webhook_id = str(uuid.uuid4())[:8]
db = SessionLocal()
try:
db.add(Webhook(
id=webhook_id,
name=name,
url=url,
secret=encrypted_secret,
events=events,
is_active=True,
))
db.commit()
finally:
db.close()
return {"id": webhook_id, "name": name}
@router.post("/webhooks/{webhook_id}/test")
async def test_webhook(request: Request, webhook_id: str):
_require_admin(request)
db = SessionLocal()
try:
wh = db.query(Webhook).filter(Webhook.id == webhook_id).first()
if not wh:
raise HTTPException(404, "Webhook not found")
url, secret = wh.url, wh.secret
finally:
db.close()
await webhook_manager.deliver_test(webhook_id, url, secret)
return {"status": "sent"}
@router.patch("/webhooks/{webhook_id}")
def toggle_webhook(request: Request, webhook_id: str):
_require_admin(request)
db = SessionLocal()
try:
wh = db.query(Webhook).filter(Webhook.id == webhook_id).first()
if not wh:
raise HTTPException(404, "Webhook not found")
wh.is_active = not wh.is_active
db.commit()
return {"id": webhook_id, "is_active": wh.is_active}
finally:
db.close()
@router.delete("/webhooks/{webhook_id}")
def delete_webhook(request: Request, webhook_id: str):
_require_admin(request)
db = SessionLocal()
try:
deleted = db.query(Webhook).filter(Webhook.id == webhook_id).delete()
db.commit()
if not deleted:
raise HTTPException(404, "Webhook not found")
finally:
db.close()
return {"status": "deleted"}
# ================================================================
# Sync Chat Endpoint (for n8n / Make / Activepieces)
# ================================================================
# Known provider base URLs — auto-resolved from api_key prefix or model name
KNOWN_PROVIDERS = {
"deepseek": "https://api.deepseek.com/v1",
"openai": "https://api.openai.com/v1",
"mistral": "https://api.mistral.ai/v1",
"groq": "https://api.groq.com/openai/v1",
"together": "https://api.together.xyz/v1",
"openrouter": "https://openrouter.ai/api/v1",
"ollama": "https://ollama.com/api",
"opencode-zen": "https://opencode.ai/zen/v1",
"opencode-go": "https://opencode.ai/zen/go/v1",
"fireworks": "https://api.fireworks.ai/inference/v1",
"venice": "https://api.venice.ai/api/v1",
"kimi-code": "https://api.kimi.com/coding/v1",
"kimicode": "https://api.kimi.com/coding/v1",
}
# Model prefix → provider mapping for auto-detection
MODEL_PROVIDER_MAP = {
"deepseek": "deepseek",
"gpt-": "openai",
"o1": "openai",
"o3": "openai",
"o4": "openai",
"mistral": "mistral",
"llama": "groq",
"mixtral": "groq",
"kimi-for-coding": "kimi-code",
"kimi": "kimi-code",
}
def _resolve_base_url(model: Optional[str], provider: Optional[str]) -> Optional[str]:
"""Try to auto-resolve a base URL from provider name or model prefix."""
if provider and provider.lower() in KNOWN_PROVIDERS:
return KNOWN_PROVIDERS[provider.lower()]
if model:
model_lower = model.lower()
for prefix, prov in MODEL_PROVIDER_MAP.items():
if model_lower.startswith(prefix):
return KNOWN_PROVIDERS[prov]
return None
class SyncChatRequest(BaseModel):
message: str = Field(..., max_length=MAX_MESSAGE_LEN)
model: Optional[str] = Field(None, max_length=200)
session: Optional[str] = Field(None, max_length=100)
api_key: Optional[str] = Field(None, max_length=256)
base_url: Optional[str] = Field(None, max_length=MAX_URL_LEN)
provider: Optional[str] = Field(None, max_length=50)
@router.post("/v1/chat")
async def sync_chat(request: Request, body: SyncChatRequest):
if not getattr(request.state, "api_token", False):
raise HTTPException(403, "This endpoint requires an API token")
scopes = set(getattr(request.state, "api_token_scopes", []) or [])
if "chat" not in scopes:
raise HTTPException(403, "API token is not scoped for chat")
token_owner = getattr(request.state, "api_token_owner", None)
from core.models import ChatMessage
from src.llm_core import llm_call_async
from src.endpoint_resolver import build_chat_url, build_headers, build_models_url, normalize_base
message = body.message.strip()
if not message:
raise HTTPException(400, "Message is required")
session_id = body.session
sess = None
# --- Case 1: Resume an existing session ---
if session_id and session_manager:
try:
sess = session_manager.get_session(session_id)
except (KeyError, Exception):
raise HTTPException(404, "Session not found")
# SECURITY: verify the API-token's user owns this session — without
# this any token holder could resume any user's chat by passing its
# ID. The token's user is on request.state.user (set by API-token
# middleware); fall back to require_user if not present.
try:
from src.auth_helpers import get_current_user as _gcu
_tok_user = token_owner or getattr(request.state, "user", None) or _gcu(request)
except Exception:
_tok_user = None
# Strict ownership (see _caller_owns_session): fail closed so a
# null-owner / cross-owner session can't be resumed by an arbitrary
# chat-scoped token.
_sess_owner = getattr(sess, "owner", None)
if not _caller_owns_session(_sess_owner, _tok_user):
raise HTTPException(404, "Session not found")
# --- Case 2: Direct API key + model (no pre-configured endpoint needed) ---
if not sess and body.api_key:
api_key = body.api_key.strip()
model = body.model or "deepseek-chat"
# Validate only token-supplied direct base_url; auto-resolved known-provider
# URLs are not subject to extra local/LAN blocking beyond existing provider logic.
direct_base_url = body.base_url.strip().rstrip("/") if body.base_url else None
if direct_base_url:
try:
base_url = validate_public_http_url(direct_base_url)
except ValueError as e:
detail = str(e).replace("URL", "base_url", 1)
raise HTTPException(400, detail)
else:
base_url = _resolve_base_url(model, body.provider)
if not base_url:
raise HTTPException(400,
"Could not auto-detect provider. Pass base_url (e.g. 'https://api.deepseek.com/v1') "
"or provider ('deepseek', 'openai', 'groq', etc.)")
base_url = normalize_base(base_url)
endpoint_url = build_chat_url(base_url)
if not session_manager:
raise HTTPException(500, "Session manager not available")
sid = str(uuid.uuid4())
sess = session_manager.create_session(
session_id=sid, name="API Chat", endpoint_url=endpoint_url,
model=model, owner=token_owner,
)
sess.headers = build_headers(api_key, base_url)
session_manager.save_sessions()
session_id = sid
# --- Case 3: Fall back to first configured ModelEndpoint ---
if not sess:
db = SessionLocal()
try:
ep = _select_api_chat_fallback_endpoint(db, token_owner)
finally:
db.close()
if not ep:
raise HTTPException(400,
"No session, api_key, or configured endpoints. "
"Pass api_key + model, or configure an endpoint in Admin.")
base_url = normalize_base(ep.base_url)
endpoint_url = build_chat_url(base_url)
model = body.model or "auto"
api_key = ep.api_key
if getattr(ep, "provider_auth_id", None):
try:
from src.endpoint_resolver import resolve_endpoint_runtime
base_url, api_key = resolve_endpoint_runtime(ep, owner=token_owner)
endpoint_url = build_chat_url(base_url)
except Exception:
raise HTTPException(500, "Could not resolve endpoint credentials")
if model == "auto":
try:
async with httpx.AsyncClient(timeout=5) as client:
models_url = build_models_url(base_url)
hdrs = build_headers(api_key, base_url)
if models_url:
resp = await client.get(models_url, headers=hdrs)
resp.raise_for_status()
data = resp.json()
items = data if isinstance(data, list) else (data.get("data") or [])
ids = [m.get("id") for m in items if isinstance(m, dict) and m.get("id")]
if not ids and isinstance(data, dict):
ids = [
m.get("name") or m.get("model")
for m in (data.get("models") or [])
if m.get("name") or m.get("model")
]
else:
import json as _json
ids = _json.loads(ep.cached_models or "[]")
model = ids[0] if ids else "auto"
except Exception:
raise HTTPException(500, "Could not discover models from endpoint")
if not session_manager:
raise HTTPException(500, "Session manager not available")
sid = str(uuid.uuid4())
sess = session_manager.create_session(
session_id=sid, name="API Chat", endpoint_url=endpoint_url,
model=model, owner=token_owner,
)
if api_key:
sess.headers = build_headers(api_key, base_url)
session_manager.save_sessions()
session_id = sid
# --- Send message and get response ---
sess.add_message(ChatMessage("user", message))
messages = [{"role": m.role, "content": m.content} for m in sess.history]
reply = await llm_call_async(
sess.endpoint_url, sess.model, messages,
headers=sess.headers, timeout=120,
)
sess.add_message(ChatMessage("assistant", reply))
session_manager.save_sessions()
webhook_manager.fire_and_forget("chat.completed", {
"session_id": session_id, "model": sess.model,
"user_message": message[:2000], "response": reply[:2000],
})
return {"response": reply, "session_id": session_id, "model": sess.model}
return router
+2 -2
View File
@@ -50,7 +50,7 @@ import json
import logging
import re
from dataclasses import dataclass, field
from datetime import datetime, timezone
from datetime import datetime
from typing import Any, Dict, List, Optional
logger = logging.getLogger(__name__)
@@ -441,4 +441,4 @@ class Skill:
def _now_iso() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
return datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
-53
View File
@@ -2,7 +2,6 @@
"""Multi-provider TTS service — dispatches to local Kokoro, OpenAI-compatible API, or browser."""
import io
import os
import wave
import logging
import hashlib
@@ -42,11 +41,6 @@ class TTSService:
self.cache_dir = Path(cache_dir)
self.cache_dir.mkdir(parents=True, exist_ok=True)
self._kokoro = None # lazy-init
try:
self.max_cache_bytes = int(os.getenv("ODYSSEUS_TTS_CACHE_MAX_BYTES", 500 * 1024 * 1024))
except ValueError:
self.max_cache_bytes = 500 * 1024 * 1024
# ── Settings ──
@@ -95,53 +89,6 @@ class TTSService:
ext = ".mp3" if (len(data) >= 3 and (data[:3] == b'ID3' or (data[0] == 0xff and (data[1] & 0xe0) == 0xe0))) else ".wav"
(self.cache_dir / f"{key}{ext}").write_bytes(data)
self._enforce_cache_limit()
def _enforce_cache_limit(self):
"""Evicts oldest files if the cache exceeds the configured byte limit."""
if self.max_cache_bytes <= 0:
return
try:
files = []
total_size = 0
# Safely scan files and sum sizes, ignoring files deleted mid-scan
for f in self.cache_dir.iterdir():
try:
if f.is_file() and f.suffix.lower() in (".mp3", ".wav"):
files.append(f)
total_size += f.stat().st_size
except OSError:
continue
if total_size > self.max_cache_bytes:
logger.info(
f"TTS cache ({total_size} bytes) exceeded limit ({self.max_cache_bytes} bytes). Evicting oldest files."
)
# Sort files by modification time (oldest first)
try:
files.sort(key=lambda f: f.stat().st_mtime)
except OSError as e:
logger.warning(f"Failed to sort cache files by mtime: {e}")
# Trim down to 80% of max capacity
target_size = self.max_cache_bytes * 0.8
while files and total_size > target_size:
f = files.pop(0)
try:
size = f.stat().st_size
f.unlink()
total_size -= size
except OSError as e:
logger.warning(f"Failed to evict cache file {f}: {e}")
continue
except Exception as e:
logger.warning(f"Error enforcing TTS cache limit: {e}", exc_info=True)
def clear_cache(self):
count = 0
for f in self.cache_dir.glob("*.*"):
+1 -1
View File
@@ -12,7 +12,7 @@ import json
import re
import time
import logging
from typing import Any, AsyncGenerator, List, Dict, Optional, Set
from typing import AsyncGenerator, List, Dict, Optional, Set
from urllib.parse import urlparse
from src.llm_core import (
+7 -19
View File
@@ -1237,27 +1237,15 @@ def _anthropic_rejects_temperature(model: str) -> bool:
return False
# `(?<![a-z])` anchors "opus" to a word boundary so a substring match like
# `oct-opus`/`octopus-4-8` can't be read as Opus (it would otherwise strip
# temperature). Both version components are capped at 1-2 digits and forbid a
# trailing digit, so an 8-digit date can never be read as a version number:
# `claude-opus-4-20250514` (Opus 4.0) parses as major-only rather than reading
# `20250514` as a giant minor, and `claude-3-opus-20240229` (legacy Claude 3
# Opus, date directly after "opus-") fails to match at all rather than reading
# the date as a giant major. Dated 4.7+ snapshots (`claude-opus-4-7-20260201`)
# keep their explicit minor and are still matched.
#
# The minor is optional and a missing minor reads as `.0`, so major-only ids
# like `claude-opus-5` are correctly treated as >= 4.7 (issue #5753). Without
# this, every Opus 5 call kept `temperature` and failed with HTTP 400 — visible
# only on paths that pass a temperature, e.g. scheduled tasks inheriting
# `stream_agent_loop`'s 0.3 default, which returned empty responses.
match = re.search(
r"(?<![a-z])opus[-_]?(\d{1,2})(?!\d)(?:[-_.](\d{1,2})(?!\d))?", model.lower()
)
# temperature). Cap the minor at 1-2 digits and forbid a trailing digit so a
# dated id like `claude-opus-4-20250514` (Opus 4.0) parses as major-only (no
# minor match, kept) instead of reading the date `20250514` as a giant minor
# that would falsely test >= 4.7. Dated 4.7+ snapshots (`claude-opus-4-7-
# 20260201`) keep their explicit minor and are still matched.
match = re.search(r"(?<![a-z])opus[-_]?(\d+)[-_.](\d{1,2})(?!\d)", model.lower())
if not match:
return False
major = int(match.group(1))
minor = int(match.group(2)) if match.group(2) else 0
return (major, minor) >= (4, 7)
return (int(match.group(1)), int(match.group(2))) >= (4, 7)
# Reasoning effort level sent to Mistral thinking-capable models. Mistral's
# API accepts "high", "medium", "low", "none" — see
+7 -13
View File
@@ -758,36 +758,30 @@ export function mdToHtml(src, opts) {
// Remove empty paragraphs
s = s.replace(/<p><\/p>/g, '');
// Every restore below passes a function replacer rather than the block string
// itself. With a string replacement, `String.replace` reads `$&`, `` $` ``,
// `$'` and `$$` in the *replacement* as substitution patterns, so a restored
// block containing them is corrupted: `$&` re-inserts the placeholder, `` $` ``
// and `$'` splice in the surrounding document, and `$$` collapses to `$`. Those
// sequences are ordinary content in fenced code (`perl -pe 's/x/$& y/'`,
// `echo "$$USD"`). A function replacer inserts its return value verbatim.
// CRITICAL: Restore allowed HTML blocks first
allowedHtmlBlocks.forEach((block, index) => {
s = s.replace(`___ALLOWED_HTML_${index}___`, () => block);
s = s.replace(`___ALLOWED_HTML_${index}___`, block);
});
// Restore math blocks
mathBlocks.forEach((block, index) => {
s = s.replace(`___MATH_BLOCK_${index}___`, () => block);
s = s.replace(`___MATH_BLOCK_${index}___`, block);
});
// Restore mermaid diagram blocks
mermaidBlocks.forEach((block, index) => {
s = s.replace(`___MERMAID_BLOCK_${index}___`, () => block);
s = s.replace(`___MERMAID_BLOCK_${index}___`, block);
});
// CRITICAL: Restore code blocks at the end
codeBlocks.forEach((block, index) => {
s = s.replace(`___CODE_BLOCK_${index}___`, () => block);
s = s.replace(`___CODE_BLOCK_${index}___`, block);
});
// Restore inline code spans last, so placeholders carried inside restored
// <a>/allowed-HTML blocks are resolved too.
// <a>/allowed-HTML blocks are resolved too. The function replacer keeps the
// escaped code literal — e.g. a shell snippet like `echo $1` is not treated
// as a regex back-reference.
inlineCodeBlocks.forEach((block, index) => {
s = s.replace(`___INLINE_CODE_${index}___`, () => block);
});
+22 -25
View File
@@ -3031,14 +3031,12 @@ async function initEmailAccountsSettings() {
const body = {
name: el('eaf-name').value.trim() || el('eaf-from').value.trim(),
from_address: el('eaf-from').value.trim(),
display_name: el('eaf-display-name').value.trim(),
imap_host: el('eaf-imap-host').value.trim(),
imap_port: parseInt(el('eaf-imap-port').value) || 993,
imap_user: el('eaf-imap-user').value.trim(),
imap_starttls: el('eaf-imap-starttls').checked,
smtp_host: el('eaf-smtp-host').value.trim(),
smtp_port: parseInt(el('eaf-smtp-port').value) || 587,
smtp_security: el('eaf-smtp-security').value,
smtp_user: el('eaf-imap-user').value.trim(),
};
if (!body.name) { el('eaf-msg').textContent = 'Enter a Name or Email first'; el('eaf-msg').style.color = 'var(--red)'; return; }
@@ -5790,30 +5788,29 @@ export function close() {
window.history.replaceState(null, '', clean);
const success = sp.has('email_oauth_success');
const errMsg = sp.get('email_oauth_error') || '';
// Open settings → integrations once the document is ready. This module owns
// the open() API, so it does not need to wait for a window-level alias.
function _showResult() {
open('integrations');
// Brief toast-style banner.
const banner = document.createElement('div');
banner.textContent = success
? 'Google account connected — email is ready'
: `Google OAuth failed: ${errMsg || 'unknown error'}`;
Object.assign(banner.style, {
position: 'fixed', bottom: '24px', left: '50%', transform: 'translateX(-50%)',
background: success ? 'var(--accent, #50fa7b)' : 'var(--red, #ff5555)',
color: '#000', padding: '8px 18px', borderRadius: '6px', fontSize: '12px',
fontWeight: '600', zIndex: '99999', pointerEvents: 'none',
boxShadow: '0 2px 12px rgba(0,0,0,0.3)',
});
document.body.appendChild(banner);
setTimeout(() => banner.remove(), 4000);
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', _showResult, { once: true });
} else {
_showResult();
// Open settings → integrations after the app has initialised.
function _tryOpen() {
if (window.settingsModule && typeof window.settingsModule.open === 'function') {
window.settingsModule.open('integrations');
// Brief toast-style banner.
const banner = document.createElement('div');
banner.textContent = success
? 'Google account connected — email is ready'
: `Google OAuth failed: ${errMsg || 'unknown error'}`;
Object.assign(banner.style, {
position: 'fixed', bottom: '24px', left: '50%', transform: 'translateX(-50%)',
background: success ? 'var(--accent, #50fa7b)' : 'var(--red, #ff5555)',
color: '#000', padding: '8px 18px', borderRadius: '6px', fontSize: '12px',
fontWeight: '600', zIndex: '99999', pointerEvents: 'none',
boxShadow: '0 2px 12px rgba(0,0,0,0.3)',
});
document.body.appendChild(banner);
setTimeout(() => banner.remove(), 4000);
} else {
setTimeout(_tryOpen, 100);
}
}
_tryOpen();
})();
const settingsModule = { open, close, initIntegrations, initUnifiedIntegrations, syncAdminVisibility, refreshAiModelEndpoints };
+1 -1
View File
@@ -76,7 +76,7 @@ def _load_webhook_routes_for_test(monkeypatch):
module_name = "routes.webhook_routes_under_test"
spec = importlib.util.spec_from_file_location(
module_name,
Path(__file__).resolve().parent.parent / "routes" / "webhook" / "webhook_routes.py",
Path(__file__).resolve().parent.parent / "routes" / "webhook_routes.py",
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
@@ -1,15 +0,0 @@
"""Regression coverage for SMTP security saved before Google OAuth."""
from pathlib import Path
_REPO = Path(__file__).resolve().parents[1]
def test_email_tab_oauth_connect_persists_selected_smtp_security():
source = (_REPO / "static" / "js" / "settings.js").read_text(encoding="utf-8")
start = source.index("el('eaf-oauth-btn').addEventListener")
handler_body = source[start:source.index("if (!body.name)", start)]
assert "smtp_security: el('eaf-smtp-security').value" in handler_body
assert "display_name: el('eaf-display-name').value.trim()" in handler_body
@@ -1,19 +0,0 @@
"""Regression coverage for the settings UI after Google OAuth redirects."""
from pathlib import Path
_REPO = Path(__file__).resolve().parents[1]
def test_oauth_redirect_uses_the_module_local_settings_api():
source = (_REPO / "static" / "js" / "settings.js").read_text(encoding="utf-8")
handler = source[
source.index("(function _handleOauthRedirect"):
source.index("const settingsModule =")
]
assert "open('integrations');" in handler
assert "window.settingsModule" not in handler
assert "window.__odysseusAppStarted" not in handler
assert "document.addEventListener('DOMContentLoaded', _showResult, { once: true })" in handler
-86
View File
@@ -1,86 +0,0 @@
"""Regression coverage for issue-description label lifecycle events."""
import json
import shutil
import subprocess
from pathlib import Path
import pytest
_REPO = Path(__file__).resolve().parent.parent
_CHECKER = _REPO / ".github" / "scripts" / "check-issue-description.js"
_WORKFLOW = _REPO / ".github" / "workflows" / "issue-description-check.yml"
pytestmark = pytest.mark.skipif(not shutil.which("node"), reason="node not on PATH")
def _run_closed_issue(action):
harness = r"""
const checkIssueDescription = require(process.argv[1]);
const action = process.argv[2];
const calls = [];
const unexpected = (name) => async () => {
throw new Error(`${name} should not be called for a closed issue`);
};
const github = {
rest: {
issues: {
removeLabel: async (params) => calls.push({ method: 'removeLabel', params }),
getLabel: unexpected('getLabel'),
addLabels: unexpected('addLabels'),
listComments: unexpected('listComments'),
createComment: unexpected('createComment'),
updateComment: unexpected('updateComment'),
deleteComment: unexpected('deleteComment'),
},
},
};
const context = {
payload: {
action,
issue: { number: 42, state: 'closed', body: '', labels: [] },
},
repo: { owner: 'odysseus-dev', repo: 'odysseus' },
};
const core = {
warning: unexpected('core.warning'),
setFailed: unexpected('core.setFailed'),
};
checkIssueDescription({ github, context, core })
.then(() => process.stdout.write(JSON.stringify(calls)))
.catch((error) => {
console.error(error);
process.exitCode = 1;
});
"""
proc = subprocess.run(
["node", "-e", harness, str(_CHECKER), action],
capture_output=True,
text=True,
cwd=str(_REPO),
timeout=30,
)
assert proc.returncode == 0, proc.stderr
return json.loads(proc.stdout)
def test_workflow_handles_issue_closures():
workflow = _WORKFLOW.read_text()
assert "types: [opened, edited, reopened, closed]" in workflow
@pytest.mark.parametrize("action", ["closed", "edited"])
def test_closed_issue_only_drops_ready_for_review(action):
assert _run_closed_issue(action) == [
{
"method": "removeLabel",
"params": {
"owner": "odysseus-dev",
"repo": "odysseus",
"issue_number": 42,
"name": "ready for review",
},
}
]
+1 -25
View File
@@ -29,13 +29,6 @@ from src.llm_core import _anthropic_rejects_temperature, _build_anthropic_payloa
"anthropic/claude-opus-4-7", # tolerate a provider-prefixed id
"claude-opus-4-10", # future minor still >= 4.7
"claude-opus-5-0", # future major
# Major-only ids: a missing minor reads as `.0`, so these are >= 4.7 too
# (issue #5753). Before the fix the version pattern required a minor, so
# these fell through to "accepts temperature" and every call 400'd.
"claude-opus-5",
"claude-opus-5-20260101", # major-only + dated snapshot
"anthropic/claude-opus-5", # major-only behind a provider prefix
"claude-opus-6", # future major-only
],
)
def test_opus_47_plus_rejects_temperature(model):
@@ -55,10 +48,7 @@ def test_opus_47_plus_rejects_temperature(model):
"claude-opus-4-6-20251201", # dated 4.6 snapshot — older, still keeps temperature
"claude-sonnet-4-6",
"claude-3-5-sonnet",
"claude-3-opus-20240229", # legacy Claude 3 Opus — date directly after
# "opus-", so the major must not swallow it as version 20240229 (that is
# what makes capping the major at 1-2 digits necessary once the minor
# became optional in #5753).
"claude-3-opus-20240229", # legacy Claude 3 Opus — no opus-N-M pattern, kept
"claude-haiku-4-5",
"claude-x",
"octopus-4-8", # "opus" only as a substring of another word — must not match
@@ -97,20 +87,6 @@ def test_payload_keeps_temperature_for_older_models():
assert _payload("claude-3-5-sonnet", 1.2)["temperature"] == 1.0
def test_payload_omits_temperature_for_major_only_opus_5():
# Issue #5753: the scheduled-task path calls stream_agent_loop() without a
# temperature and inherits its 0.3 default, so `claude-opus-5` 400'd on every
# run and surfaced as "the model returned an empty response". Interactive chat
# leaves temperature None and never hit it.
assert "temperature" not in _payload("claude-opus-5", 0.3)
def test_payload_keeps_temperature_for_legacy_claude_3_opus():
# Guards the major-digit cap: `opus-20240229` must not parse as version
# 20240229, or Claude 3 Opus would silently lose the caller's temperature.
assert _payload("claude-3-opus-20240229", 0.5)["temperature"] == 0.5
def test_payload_keeps_temperature_for_dated_opus_4_0():
# Anthropic's dated id for Opus 4.0 (claude-opus-4-20250514) is in this repo's
# ANTHROPIC_MODELS list. The date must not be misread as a >= 4.7 minor, or the
-44
View File
@@ -214,50 +214,6 @@ def test_inline_code_content_is_html_escaped(node_available):
assert "<b>" not in html
def test_fenced_code_keeps_dollar_ampersand(node_available):
# Issue #5663: the block-restore pass used a string replacement, so `$&` in a
# restored block was read as "the matched text" and re-inserted the
# placeholder. `perl -pe 's/world/$& again/'` rendered as
# "s/world/___CODE_BLOCK_0___amp; again/" — the trailing "amp;" is the orphan
# left behind after `$&` consumed the `$&` of the escaped `$&amp;`.
html = _run_markdown_case(
"```sh\necho \"hello world\" | perl -pe 's/world/$& again/'\n```"
)
assert "___CODE_BLOCK_" not in html
assert "s/world/$&amp; again/" in html
assert "amp; again" not in html.replace("$&amp; again", "")
def test_fenced_code_keeps_dollar_backtick_and_quote(node_available):
# `` $` `` and `$'` splice the text before/after the placeholder into the
# block. Unlike `$&` these leave no placeholder behind — the characters just
# vanish — so assert the content survives verbatim.
html = _run_markdown_case("```sh\nsed \"s/$`/x/\" && sed \"s/$'/y/\"\n```")
assert "___CODE_BLOCK_" not in html
assert "s/$`/x/" in html
assert "s/$&#39;/y/" in html
def test_fenced_code_keeps_double_dollar(node_available):
# `$$` collapsed to a single `$` in the restored block.
html = _run_markdown_case('```sh\necho "$$USD and $$"\n```')
assert "$$USD and $$" in html
def test_mermaid_block_keeps_dollar_ampersand(node_available):
# The mermaid restore site had the same hazard: a node label containing `$&`
# re-inserted the ___MERMAID_BLOCK_n___ placeholder into the diagram source,
# which then fails to parse. The math and allowed-HTML sites are fixed the
# same way; they need KaTeX/sanitizer conditions this harness doesn't set up.
html = _run_markdown_case('```mermaid\ngraph TD; A["$&"] --> B;\n```')
assert "___MERMAID_BLOCK_" not in html
assert "$&amp;" in html
def test_currency_dollar_amounts_are_not_rendered_as_math(node_available):
# "$5 to $10" used to pair the two dollar signs as inline-math delimiters
# and render "5 to" through KaTeX. Pandoc-style rules now reject it: the
@@ -1,15 +0,0 @@
"""Regression coverage for the built-in MCP servers' SDK compatibility line."""
from pathlib import Path
REQUIREMENTS = Path(__file__).resolve().parents[1] / "requirements.txt"
def test_mcp_requirement_excludes_breaking_v2_sdk():
requirements = [
line.split("#", 1)[0].strip().replace(" ", "")
for line in REQUIREMENTS.read_text(encoding="utf-8").splitlines()
]
assert "mcp<2" in requirements
-11
View File
@@ -1,11 +0,0 @@
"""Regression test for the search route shim (slice 2j, #4082/#4071)."""
import importlib
import routes.search_routes as _shim_search # noqa: F401
def test_legacy_and_canonical_search_module_are_same_object():
legacy = importlib.import_module("routes.search_routes")
canonical = importlib.import_module("routes.search.search_routes")
assert legacy is canonical
-58
View File
@@ -1,58 +0,0 @@
"""Regression for issue #5697 — skill timestamps must not use ``datetime.utcnow()``.
``_now_iso()`` builds the ``created`` value in skill frontmatter. ``utcnow()``
returns a *naive* datetime and has been deprecated since Python 3.12, scheduled
for removal. The replacement must stay timezone-aware while keeping the
serialized ``YYYY-MM-DDTHH:MM:SSZ`` shape, so skill files written by older
versions keep parsing.
The UTC check matters on its own: a bare ``datetime.now()`` also produces the
right shape, but emits local wall time, which would silently backdate or
postdate skills for every user outside UTC.
"""
import os
import re
import time
import warnings
from datetime import datetime, timezone
import pytest
from services.memory.skill_format import _now_iso
_ISO_Z = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$")
def test_now_iso_keeps_serialized_shape():
assert _ISO_Z.match(_now_iso())
def test_now_iso_emits_no_deprecation_warning():
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
_now_iso()
assert not [w for w in caught if issubclass(w.category, DeprecationWarning)]
@pytest.mark.skipif(
not hasattr(time, "tzset"),
reason="time.tzset is unavailable on this platform",
)
def test_now_iso_is_utc_not_local_time():
"""Pin UTC under a non-UTC local timezone, where the two visibly diverge."""
original_tz = os.environ.get("TZ")
os.environ["TZ"] = "Asia/Amman" # UTC+3, never UTC
time.tzset()
try:
emitted = datetime.strptime(_now_iso(), "%Y-%m-%dT%H:%M:%SZ").replace(
tzinfo=timezone.utc
)
drift = abs((emitted - datetime.now(timezone.utc)).total_seconds())
assert drift < 60, f"timestamp is {drift}s off UTC — local time leaked in"
finally:
if original_tz is None:
os.environ.pop("TZ", None)
else:
os.environ["TZ"] = original_tz
time.tzset()
@@ -1,97 +0,0 @@
import os
import time
from pathlib import Path
import pytest
# Adjust the import path if your file is directly in ./services instead of ./services/tts
from services.tts.tts_service import TTSService
def test_cache_under_limit(tmp_path, monkeypatch):
"""Test that writing a file under the size limit does not trigger eviction."""
# Set a tiny limit: 100 bytes
monkeypatch.setenv("ODYSSEUS_TTS_CACHE_MAX_BYTES", "100")
# Initialize service with pytest's temporary directory
service = TTSService(cache_dir=str(tmp_path))
# Write a 40-byte file (under the 100-byte limit)
service._put_cache("test_key", b"x" * 40)
# Verify the file was written and nothing was deleted
files = list(tmp_path.glob("*.*"))
assert len(files) == 1
assert sum(f.stat().st_size for f in files) == 40
def test_cache_exceeds_limit_triggers_eviction(tmp_path, monkeypatch):
"""Test that exceeding the limit evicts the oldest files down to 80% capacity."""
# Set limit to 100 bytes. 80% target capacity will be 80 bytes.
monkeypatch.setenv("ODYSSEUS_TTS_CACHE_MAX_BYTES", "100")
service = TTSService(cache_dir=str(tmp_path))
# 1. Setup: Manually create two older files (40 bytes each)
file1 = tmp_path / "oldest.wav"
file2 = tmp_path / "middle.wav"
file1.write_bytes(b"a" * 40)
file2.write_bytes(b"b" * 40)
# Spoof timestamps so file1 is explicitly older than file2
now = time.time()
os.utime(file1, (now - 100, now - 100)) # 100 seconds ago
os.utime(file2, (now - 50, now - 50)) # 50 seconds ago
# 2. Action: Write a 3rd file using the service method (40 bytes)
# Total cache is now 120 bytes, which exceeds 100.
# It should delete oldest (file1) to drop to 80 bytes (which matches the 80% target).
service._put_cache("newest", b"c" * 40)
# 3. Assertions
# The newest file should exist (saved as .wav because it lacks MP3 magic bytes)
newest_file = tmp_path / "newest.wav"
assert not file1.exists(), "The oldest file should have been evicted."
assert file2.exists(), "The middle file should still exist."
assert newest_file.exists(), "The newest file should have been saved."
# Verify the final directory size is <= 80 bytes
total_size = sum(f.stat().st_size for f in tmp_path.glob("*.*"))
assert total_size <= 80
def test_cache_limit_disabled(tmp_path, monkeypatch):
"""Test that setting max bytes to 0 disables eviction."""
monkeypatch.setenv("ODYSSEUS_TTS_CACHE_MAX_BYTES", "0")
service = TTSService(cache_dir=str(tmp_path))
# Write 3 large files that would normally trigger eviction
service._put_cache("file1", b"x" * 1000)
service._put_cache("file2", b"x" * 1000)
service._put_cache("file3", b"x" * 1000)
# Ensure nothing was deleted
files = list(tmp_path.glob("*.*"))
assert len(files) == 3
assert sum(f.stat().st_size for f in files) == 3000
def test_cache_eviction_handles_unlink_error_gracefully(tmp_path, monkeypatch):
"""Test that if unlinking a file fails, _put_cache still succeeds without raising."""
service = TTSService(cache_dir=str(tmp_path))
service.max_cache_bytes = 50
# Create a file to evict
old_file = tmp_path / "old.wav"
old_file.write_bytes(b"x" * 40)
# Monkeypatch unlink on Path objects to simulate a PermissionError / file-lock failure
def mock_unlink(self_path):
raise OSError("Permission denied / file locked")
monkeypatch.setattr(Path, "unlink", mock_unlink)
# Writing a new file triggers eviction which encounters the mocked unlink error
try:
service._put_cache("new_key", b"y" * 40)
except Exception as e:
pytest.fail(f"_put_cache raised an exception during failed eviction: {e}")
# The new file should still be written successfully
assert (tmp_path / "new_key.wav").exists()
-11
View File
@@ -1,11 +0,0 @@
"""Regression test for the vault route shim (slice 2k, #4082/#4071)."""
import importlib
import routes.vault_routes as _shim_vault # noqa: F401
def test_legacy_and_canonical_vault_module_are_same_object():
legacy = importlib.import_module("routes.vault_routes")
canonical = importlib.import_module("routes.vault.vault_routes")
assert legacy is canonical
-11
View File
@@ -1,11 +0,0 @@
"""Regression test for the webhook route shim (slice 2l, #4082/#4071)."""
import importlib
import routes.webhook_routes as _shim_webhook # noqa: F401
def test_legacy_and_canonical_webhook_module_are_same_object():
legacy = importlib.import_module("routes.webhook_routes")
canonical = importlib.import_module("routes.webhook.webhook_routes")
assert legacy is canonical