Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ AI code review, multi-agent pipelines, RAG semantic search, and embeddings.
| `timeout` | `Union` | - | - | Seconds each LLM request waits for its reply; `ai.tasks.<task>.timeout` sets one task's. Unset, a request waits 3600 s, and a review's analysis requests 1200 s |
| `tasks` | `AITasksConfig` | `chat=AITaskOverride(provider=None, model=None, reasoning_effort=None, supports_reasoning=None, use_model_sampling=None, temperature=None, top_p=None, context_window=None, num_ctx=None, max_tokens=None, ollama_urls=None, ollama_max_parallel=None, api_base_url=None, max_retries=None, timeout=None) metadata=AITaskOverride(provider=None, model=None, reasoning_effort=None, supports_reasoning=None, use_model_sampling=None, temperature=None, top_p=None, context_window=None, num_ctx=None, max_tokens=None, ollama_urls=None, ollama_max_parallel=None, api_base_url=None, max_retries=None, timeout=None) analysis=AITaskOverride(provider=None, model=None, reasoning_effort=None, supports_reasoning=None, use_model_sampling=None, temperature=None, top_p=None, context_window=None, num_ctx=None, max_tokens=None, ollama_urls=None, ollama_max_parallel=None, api_base_url=None, max_retries=None, timeout=None) verification=AITaskOverride(provider=None, model=None, reasoning_effort=None, supports_reasoning=None, use_model_sampling=None, temperature=None, top_p=None, context_window=None, num_ctx=None, max_tokens=None, ollama_urls=None, ollama_max_parallel=None, api_base_url=None, max_retries=None, timeout=None) compose=AITaskOverride(provider=None, model=None, reasoning_effort=None, supports_reasoning=None, use_model_sampling=None, temperature=None, top_p=None, context_window=None, num_ctx=None, max_tokens=None, ollama_urls=None, ollama_max_parallel=None, api_base_url=None, max_retries=None, timeout=None) embedding=AITaskOverride(provider=None, model='qwen3-embedding:0.6b', reasoning_effort=None, supports_reasoning=None, use_model_sampling=None, temperature=None, top_p=None, context_window=None, num_ctx=None, max_tokens=None, ollama_urls=None, ollama_max_parallel=None, api_base_url=None, max_retries=None, timeout=None)` | - | - |
| `rag` | `AIRAGConfig` | `enabled=True top_k=5 score_threshold=0.35 chunk_size=2400 chunk_overlap=240` | - | - |
| `cache` | `AICacheConfig` | `enabled=True dir=PosixPath('.data/cache/llm') ttl_seconds=604800 max_entries=1000 append_cache=False` | - | - |
| `cache` | `AICacheConfig` | `enabled=True ttl_seconds=604800 max_entries=1000 append_cache=False` | - | - |
| `task_name` | `Union` | - | - | - |

## Open WebUI Configuration (`open_webui`)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-26
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Design

## Context

See proposal.md for motivation and problem analysis. The LLM response cache stores serialised JSON responses to avoid redundant model dispatches. It runs both as an in-memory dictionary and on the filesystem under the configured cache directory.

## Goals / Non-Goals

**Goals:**
- Confine all response cache file reads and writes strictly to `<cache_dir>/<key>.json`.
- Reject malformed or relative keys before filesystem access.
- Invalidate and delete any loaded cache file whose stored `key` does not match the requested key.
- Align cache directory resolution strictly with `data.dir` and `DEVOPS_CLI_DATA_DIR`.
- Ensure clients with `cache_enabled=False` bypass cache reads and writes completely.
- Exclude empty text responses and responses failing schema validation from the cache.

**Non-Goals:**
- Cryptographic signatures for cached entries (not needed once directory isolation and untrusted tree isolation prevent unauthorized writes).
- Backward compatibility for `ai.cache.dir` (pre-1.0 alpha software).

## Decisions

### Decision: Validate keys with strict pattern checking before filesystem access
Check that the requested key starts with `llm_` and contains exactly 64 hexadecimal characters. Any key failing this condition immediately returns `None` for lookups or is rejected on writes, without invoking any filesystem operations.
Rejected alternative: Path resolution and normalization checks (such as `resolve().is_relative_to()`). Evidence: Path resolution still touches the filesystem or parses arbitrary string paths, leaving potential edge cases or symlink complexities. Validating the key format upfront prevents arbitrary path creation entirely.

### Decision: Enforce key equality upon disk load
When loading a cached JSON file from disk, compare the entry `key` attribute against the requested key. If they differ, delete the disk file immediately and treat the lookup as a cache miss.
Rejected alternative: Overwriting the entry key on load. Evidence: Overwriting would allow malicious entries with bad keys to rewrite files or propagate invalid entries across calls.

### Decision: Re-root cache directly under `data.cache_dir / "llm"`
Remove `ai.cache.dir` from `AICacheConfig`. Build the global singleton cache using `settings.data.cache_dir / CONST_LLM_CACHE_DIR_NAME`.
Rejected alternative: Retaining `ai.cache.dir` with fallbacks. Evidence: Dual configuration paths caused the divergence between review runners and `ai cache status/clear` commands. Pre-1.0 policy removes obsolete shims.

### Decision: Delete rejected cached entries upon client lookup validation
In `unified.py: _check_chat_cache`, if `_validate_response_text(cached_entry.content, validator)` fails, delete the entry from both memory and disk via `cache.delete(cache_key)`.
Rejected alternative: Leaving rejected entries on disk until TTL expiry. Evidence: Leaving rejected entries caused repeated failed lookups, bumped access times, and prevented clean replacement.

### Decision: ModelProposal schema enforcement via Pydantic
Set `extra="forbid"` on `ModelProposal` and remove default values from `priority`, `value`, and `effort`.
Rejected alternative: Manual key validation in `chat_structured`. Evidence: Schema enforcement belongs in the Pydantic model definition. Adding ad-hoc dictionary validation in the client introduces fragile heuristics.

## Risks / Trade-offs

- [Risk] Existing tests that used arbitrary short test keys (such as `llm_1`) will fail key validation.
→ Mitigation: Update test fixtures in `tests/test_response_cache.py` to use valid 64-hex SHA-256 keys or helper methods.
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Proposal

## Why

Issue #1014: the response cache trusts the files in its directory and does not validate that loaded entries match requested keys.
An attacker can place malicious entries with directory traversal sequences in the key field or in the directory under review.
This can overwrite files outside the cache directory or serve attacker-controlled model responses without model calls.
Furthermore, empty responses and responses failing schema validation were improperly cached, while cache status and clear commands could resolve an inconsistent cache directory.

## What Changes

- The response cache reads and writes only files named `<cache_dir>/<requested_key>.json`.
- Cache keys must be `llm_` followed by 64 hexadecimal characters. The cache refuses malformed keys before file access.
- When a loaded entry contains a key field that differs from the requested key, the cache deletes the disk file and does not serve it.
- The cache resolves under `<DATA_DIR>/cache/llm` through settings, so `data.dir` and `DEVOPS_CLI_DATA_DIR` move it.
- `ai.cache.dir` is removed from configuration because the cache directory belongs to `data.dir`.
- The CLI commands `devops ai cache status` and `devops ai cache clear` build from settings and inspect `<DATA_DIR>/cache/llm`.
- A client created with `cache_enabled=False` neither reads nor writes the cache, even when a singleton cache exists.
- Model responses with empty or whitespace-only content are never cached.
- When the client rejects a cached entry on lookup, it deletes the entry from memory and disk.
- In `ModelProposal`, set `extra="forbid"` and make `priority`, `value`, and `effort` required fields.
- `chat_structured` does not store replies that fail schema validation in the cache.
- The change fits in one pull request.

## Capabilities

### New Capabilities

- `llm-response-cache`: how LLM responses are cached, validated, and isolated on the workstation filesystem.

### Modified Capabilities

None.

## Impact

- `src/devops_cli/ai/response_cache.py`: key validation, safe lookup, entry deletion, and settings-driven singleton initialization.
- `src/devops_cli/ai/client/unified.py`: empty-content caching exclusion, entry deletion on rejected lookup, and cache resolution.
- `src/devops_cli/config/settings.py` and `src/devops_cli/config/defaults.py`: remove `ai.cache.dir`.
- `src/devops_cli/roadmap/intake_model.py`: update `ModelProposal` schema.
- `tests/test_response_cache.py`, `tests/test_ai_client_structured.py`, `tests/test_review_untrusted_tree.py`, `tests/conftest.py`.

## Feasibility

- The code. At `origin/main` 30c6fa18, `LLMResponseCache` in `src/devops_cli/ai/response_cache.py` resolves `cache_dir` without key validation before file access.
- Key traversal. Testing with keys containing `../` or `/abs/` confirms path concatenation directly without canonical directory confinement.
- Settings alignment. Reviewing `settings.py` confirms `AICacheConfig` previously maintained a distinct `dir` setting decoupled from `DataConfig`.
- Structured schema. Testing `ModelProposal` confirms `extra="ignore"` permits invalid or echo schemas unless restricted by `extra="forbid"`.
- Unit tests verify all isolation requirements offline in temporary directories with local git repositories and stubs.

## Existing Tool Considered

- Disk caching: standard filesystem operations using Python `pathlib.Path` and stdlib `hashlib`.
- SQLite or third-party cache (such as `diskcache`): adds unnecessary binary dependencies and concurrency overhead for simple file-based responses.
- Building the validation logic in-tree requires minimal tokens and adds zero new runtime dependencies.
- Internal code removed: deletes `AICacheConfig.dir` and custom directory routing branches.
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Spec Delta

## Purpose

Provides secure persistent caching for LLM responses, ensuring strict directory isolation and preventing malicious traversal attacks.

## ADDED Requirements

### Requirement: Cache keys are validated before file access
The response cache SHALL accept only keys that begin with `llm_` followed by 64 hexadecimal characters. The cache SHALL reject any malformed key before accessing or modifying the filesystem.

#### Scenario: Malformed key rejected
- **WHEN** a caller requests or stores an entry with a key that contains directory traversal sequences or non-hexadecimal characters
- **THEN** the cache rejects the operation without accessing or writing files

### Requirement: Loaded entries must match requested keys
The response cache SHALL verify that loaded entries contain a key identical to the requested key. If the stored key in the file differs from the requested key, the cache SHALL delete the disk file and return no entry.

#### Scenario: Stored key mismatch
- **WHEN** a cached JSON file on disk contains a key that differs from the requested key
- **THEN** the cache deletes the file on disk and returns a cache miss

### Requirement: Cache directory resolves under data directory
The response cache SHALL resolve its storage directory under `<DATA_DIR>/cache/llm`. The configuration `data.dir` and the environment variable `DEVOPS_CLI_DATA_DIR` SHALL determine the cache root.

#### Scenario: Custom data directory configured
- **WHEN** `DEVOPS_CLI_DATA_DIR` is set to an isolated directory
- **THEN** all cache operations and CLI commands read and write inside `<DEVOPS_CLI_DATA_DIR>/cache/llm`

### Requirement: Empty and schema-failing responses are not cached
The AI client SHALL not store responses whose content is empty or contains only whitespace in the cache. The structured client SHALL not store replies that fail schema validation.

#### Scenario: Empty response with thinking block
- **WHEN** a model returns an empty text response containing thinking blocks
- **THEN** the client returns the response to the caller and writes no cache file

#### Scenario: Response fails schema validation
- **WHEN** a structured model response fails Pydantic schema validation on attempt 1
- **THEN** the client deletes any invalid entry at the key and stores no failing reply

### Requirement: Disabled cache clients bypass cache
An AI client configured with disabled caching SHALL neither read nor write the response cache.

#### Scenario: Cache disabled client execution
- **WHEN** an AI client is initialized with `cache_enabled=False`
- **THEN** multiple identical requests dispatch to the provider and create no cache files
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Tasks

## 1. Response cache directory confinement and key validation

- [x] 1.1 Write failing tests in `tests/test_response_cache.py` asserting that keys must be `llm_` followed by 64 hexadecimal characters, that malformed keys (`../x`, `/abs/x`, non-hex) are rejected before any filesystem access, that entries on disk with mismatched keys are deleted and not served, and that `delete()` removes entries from memory and disk. Verify with `uv run devops ci test tests/test_response_cache.py`.
- [x] 1.2 Implement `is_valid_cache_key`, strict key validation before disk operations, key equality verification on disk load, and `delete()` in `src/devops_cli/ai/response_cache.py`. Update existing tests in `tests/test_response_cache.py` that used arbitrary non-hex keys. Verify with `uv run devops ci test tests/test_response_cache.py` and `uv run mypy src/devops_cli/ai/response_cache.py`.
- [x] 1.3 Regenerate CLI documentation. Verify with `uv run devops docs generate --sync-readme` and `uv run devops docs check`.

## 2. Response cache configuration and singleton alignment

- [x] 2.1 Write failing tests in `tests/test_response_cache.py` asserting that the cache directory resolves under `<DATA_DIR>/cache/llm`, that `devops ai cache status` and `devops ai cache clear` read settings, and that a client initialized with `cache_enabled=False` neither reads nor writes the cache even when a singleton cache exists. Verify with `uv run devops ci test tests/test_response_cache.py`.
- [x] 2.2 Remove `dir` from `AICacheConfig` in `src/devops_cli/config/settings.py` and remove `DEFAULT_LLM_CACHE_DATA_DIR` in `src/devops_cli/config/defaults.py`. Update `get_llm_response_cache()` and `_resolve_llm_cache()` in `src/devops_cli/ai/client/unified.py` to build from settings and isolate disabled clients. Update `isolate_llm_response_cache` in `tests/conftest.py` to build via settings and request `isolate_data_dir`. Verify with `uv run devops ci test tests/test_response_cache.py tests/test_data_dir_configuration.py`.
- [x] 2.3 Regenerate CLI documentation. Verify with `uv run devops docs generate --sync-readme` and `uv run devops docs check`.

## 3. Client caching exclusions, rejected entry cleanup, and structured schema enforcement

- [x] 3.1 Write failing tests in `tests/test_response_cache.py`, `tests/test_ai_client_structured.py`, and `tests/test_review_untrusted_tree.py` asserting that empty content replies with thinking blocks are not cached, that rejected lookups delete the entry from memory and disk, that `ModelProposal` forbids extra fields and requires `priority`, `value`, and `effort`, that structured replies failing schema validation are not cached, and that a clone tracking `.data/cache/llm/` files does not serve planted replies. Verify with `uv run devops ci test tests/test_response_cache.py tests/test_ai_client_structured.py tests/test_review_untrusted_tree.py`.
- [x] 3.2 Update `_check_chat_cache` and `_handle_successful_chat_dispatch` in `src/devops_cli/ai/client/unified.py` to delete rejected lookup entries and bypass caching for empty responses. Update `ModelProposal` in `src/devops_cli/roadmap/intake_model.py` with `extra="forbid"` and required fields. Verify with `uv run devops ci test tests/test_response_cache.py tests/test_ai_client_structured.py tests/test_roadmap_intake.py tests/test_review_untrusted_tree.py`.
- [x] 3.3 Regenerate CLI documentation and verify full suite. Verify with `uv run devops docs generate --sync-readme`, `uv run devops docs check`, and `uv run devops ci`.

## Workflow follow-up

- Pending a person: run `devops ai review branch` from inside a scratch clone that tracks a `.data/cache/llm` directory and verify no file under the clone's `.data/` is created or modified.
- Pending a person: review the diff in tuicr (tuicr -r origin/main..HEAD).
45 changes: 45 additions & 0 deletions openspec/specs/llm-response-cache/spec.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# llm-response-cache Specification

## Purpose
Provides secure persistent caching for LLM responses, ensuring strict directory isolation and preventing malicious traversal attacks.

## Requirements

### Requirement: Cache keys are validated before file access
The response cache SHALL accept only keys that begin with `llm_` followed by 64 hexadecimal characters. The cache SHALL reject any malformed key before accessing or modifying the filesystem.

#### Scenario: Malformed key rejected
- **WHEN** a caller requests or stores an entry with a key that contains directory traversal sequences or non-hexadecimal characters
- **THEN** the cache rejects the operation without accessing or writing files

### Requirement: Loaded entries must match requested keys
The response cache SHALL verify that loaded entries contain a key identical to the requested key. If the stored key in the file differs from the requested key, the cache SHALL delete the disk file and return no entry.

#### Scenario: Stored key mismatch
- **WHEN** a cached JSON file on disk contains a key that differs from the requested key
- **THEN** the cache deletes the file on disk and returns a cache miss

### Requirement: Cache directory resolves under data directory
The response cache SHALL resolve its storage directory under `<DATA_DIR>/cache/llm`. The configuration `data.dir` and the environment variable `DEVOPS_CLI_DATA_DIR` SHALL determine the cache root.

#### Scenario: Custom data directory configured
- **WHEN** `DEVOPS_CLI_DATA_DIR` is set to an isolated directory
- **THEN** all cache operations and CLI commands read and write inside `<DEVOPS_CLI_DATA_DIR>/cache/llm`

### Requirement: Empty and schema-failing responses are not cached
The AI client SHALL not store responses whose content is empty or contains only whitespace in the cache. The structured client SHALL not store replies that fail schema validation.

#### Scenario: Empty response with thinking block
- **WHEN** a model returns an empty text response containing thinking blocks
- **THEN** the client returns the response to the caller and writes no cache file

#### Scenario: Response fails schema validation
- **WHEN** a structured model response fails Pydantic schema validation on attempt 1
- **THEN** the client deletes any invalid entry at the key and stores no failing reply

### Requirement: Disabled cache clients bypass cache
An AI client configured with disabled caching SHALL neither read nor write the response cache.

#### Scenario: Cache disabled client execution
- **WHEN** an AI client is initialized with `cache_enabled=False`
- **THEN** multiple identical requests dispatch to the provider and create no cache files
Loading
Loading