Repository navigation
feat: unified MCP server with memory, task, and reflection tools - #11
Questi0nM4rk wants to merge 24 commits into
Conversation
Epic 6 Phase 1+2: Infrastructure and data layer for the unified MCP server. - Replace sentence-transformers with httpx+pydantic (lighter deps) - Rewrite schema.surql with HNSW vector index, BM25 full-text, views - Add Pydantic models: Memory, Task, Project, SearchResult, ErrorResponse - Add EmbeddingProvider (OpenAI text-embedding-3-small via httpx) - Add EmbeddingCache (SHA-256 keyed LRU, configurable max_size) - 164 tests passing, ruff + pyright clean Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…Service 44 tests covering all service methods before implementation (TDD RED phase): - EmbeddingService: cache hit/miss, batch with partial cache, ordering - MemoryService: store, read, update, delete, link, stats, auto_link - SearchService: query embedding, filters, graph, snippet truncation Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
23 tests covering all 7 memory tools (store, search, read, update, delete, link, stats) plus server app, name, entry points, and ping tool. All tests RED - implementation pending. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add 7 memory tool functions (store, search, read, update, delete, link, stats) with service delegation and ErrorResponse error handling. Migrate server from low-level Server to FastMCP for @app.tool() support. Wire up tool registration via app.add_tool() and lazy service init in run_server(). 23 tests pass covering all tool functions, error paths, depth clamping, default arguments, and server app/name/entry points. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Services layer for the unified MCP server: - EmbeddingService: caching wrapper over EmbeddingProvider + EmbeddingCache with batch support that only calls API for uncached texts - MemoryService: CRUD operations (store, read, update, delete, link, stats) with auto-linking on store and graph traversal on read - SearchService: hybrid vector search with filters (type, project, tags), snippet truncation, and optional graph inclusion All 44 tests GREEN. Ruff lint + format clean. Full suite: 231/231 passing. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
30 tests covering TaskService (create, get_next, complete, list) and task tool functions (delegation, error handling, validation). All tests currently RED - implementation pending. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
26 tests covering ReflectionService (reflect, improved_attempt, model_effectiveness) and the corresponding tool handler functions. All tests fail (RED phase) - implementation follows. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- TaskService with create_task, get_next_task, complete_task, list_tasks - Task tool handlers with error handling and validation - TaskService exported from services __init__ - 4 task tools registered in MCP server (create_task, get_next_task, complete_task, list_tasks) - TaskService initialized in run_server() and injected via init_task_tools() 30/30 task tests passing, 277/277 existing tests unaffected. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Phase 5 of unified MCP: ReflectionService with 3 methods (reflect, improved_attempt, model_effectiveness) and corresponding tool handlers. - reflect: analyzes failures, stores structured episodes in memory table - improved_attempt: queries similar past episodes for guidance - model_effectiveness: recommends model based on historical success rates Registered 3 new tools in server.py, updated services __init__.py. All 287 tests pass, ruff clean. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
|
Warning Rate limit exceeded
⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. WalkthroughA unified MCP server consolidates four separate services into a single codeagent-mcp backed by SurrealDB, with OpenAI embeddings, Pydantic models for Memory/Task/Project entities, comprehensive tool handlers, an exception registry system, and extensive test coverage. Changes
Sequence DiagramssequenceDiagram
participant Client as MCP Client
participant Server as FastMCP Server
participant MemSvc as MemoryService
participant EmbSvc as EmbeddingService
participant DB as SurrealDB
participant OpenAI as OpenAI API
Client->>Server: store(content, type, title, ...)
Server->>MemSvc: store(MemoryCreate)
MemSvc->>EmbSvc: embed(content)
EmbSvc->>OpenAI: POST /v1/embeddings
OpenAI-->>EmbSvc: [embedding_vector]
EmbSvc-->>MemSvc: [embedding_vector]
MemSvc->>DB: CREATE memory<br/>{type, content, embedding, ...}
DB-->>MemSvc: {memory_id, ...}
MemSvc->>MemSvc: _auto_link(memory_id, embedding)
MemSvc->>DB: Query similar<br/>memories (cosine)
DB-->>MemSvc: [similar_ids]
MemSvc->>DB: CREATE relates_to<br/>relations
DB-->>MemSvc: [relation_ids]
MemSvc-->>Server: {memory_id, ...}
Server-->>Client: {memory_id, ...}
sequenceDiagram
participant Client as MCP Client
participant Server as FastMCP Server
participant SearchSvc as SearchService
participant EmbSvc as EmbeddingService
participant DB as SurrealDB
participant OpenAI as OpenAI API
Client->>Server: search(query, memory_type, project, ...)
Server->>SearchSvc: search(query)
SearchSvc->>EmbSvc: embed(query)
EmbSvc->>OpenAI: POST /v1/embeddings
OpenAI-->>EmbSvc: [query_embedding]
EmbSvc-->>SearchSvc: [query_embedding]
SearchSvc->>DB: SELECT * FROM memory<br/>WHERE type = $type<br/>AND project = $project<br/>ORDER BY vec_score DESC<br/>LIMIT max_results
DB-->>SearchSvc: [{id, title, type,<br/>content, vec_score}]
SearchSvc->>DB: SELECT * FROM relates_to<br/>WHERE id IN [result_ids]<br/>(if include_graph)
DB-->>SearchSvc: [related_memory_ids]
SearchSvc-->>Server: {index: [...],<br/>details: [...],<br/>total_count: N}
Server-->>Client: {index, details, total_count}
sequenceDiagram
participant Client as MCP Client
participant Server as FastMCP Server
participant ReflectSvc as ReflectionService
participant EmbSvc as EmbeddingService
participant DB as SurrealDB
participant OpenAI as OpenAI API
Client->>Server: improve_attempt(task, original_output, error_pattern)
Server->>ReflectSvc: improved_attempt(task, original_output, error_pattern)
ReflectSvc->>EmbSvc: embed(query_with_error)
EmbSvc->>OpenAI: POST /v1/embeddings
OpenAI-->>EmbSvc: [query_embedding]
EmbSvc-->>ReflectSvc: [query_embedding]
ReflectSvc->>DB: SELECT * FROM memory<br/>WHERE type = "episode"<br/>ORDER BY embedding<br/>VEC::DISTANCE DESC
DB-->>ReflectSvc: [{id, title, metadata,<br/>content, vec_score}]
ReflectSvc->>ReflectSvc: filter_by_similarity(threshold)
ReflectSvc-->>Server: {similar_episodes: [...],<br/>guidance: ...,<br/>confidence: 0.X}
Server-->>Client: {similar_episodes, guidance, confidence}
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 39
🤖 Fix all issues with AI agents
In `@src/codeagent/mcp/embeddings/provider.py`:
- Around line 85-101: The _request method creates a new httpx.AsyncClient per
call and omits a timeout; update the Embeddings provider class to instantiate
and reuse a single AsyncClient with an explicit timeout instead of creating one
inside _request. Add a client attribute (e.g., self._httpx_client) initialized
in __init__ or lazily on first use, configure httpx.Timeout with sensible
values, replace the context-managed client creation in _request (and any other
callers) to use self._httpx_client.post(..., timeout=...) and ensure the client
is properly closed when the provider is shut down or garbage-collected (provide
a close/async_close method if needed).
In `@src/codeagent/mcp/models/__init__.py`:
- Around line 27-44: The __all__ export list in the module (the __all__ variable
containing "ErrorCode", "ErrorResponse", "Memory", "MemoryCreate", "MemoryType",
"MemoryUpdate", "SearchResponse", "SearchResult", "Project", "Task",
"TaskCreate", "TaskStatus", "TaskType") is flagged by Ruff RUF022 for not being
alphabetically sorted; to preserve your domain grouping, add a noqa suppression
by appending a comment "# noqa: RUF022" to the __all__ assignment line (i.e.,
the line that defines __all__) so Ruff will ignore sorting, or alternatively
alphabetically sort the entries inside __all__ if you prefer to enforce
isort-style order.
In `@src/codeagent/mcp/models/memory.py`:
- Line 58: The confidence fields lack validation against the documented 0.0–1.0
range; update the Pydantic model declarations for confidence in Memory
(confidence: float = 1.0), MemoryCreate, and MemoryUpdate to use Field(ge=0.0,
le=1.0, default=1.0) (or Field(ge=0.0, le=1.0) with the existing default) so
values are constrained to the 0.0–1.0 range and validation errors are raised for
out-of-bounds inputs.
In `@src/codeagent/mcp/server.py`:
- Around line 58-62: In run_server(), move the lazy imports for
ReflectionService and TaskService so they are grouped with the other service
imports (SurrealDBClient, EmbeddingCache, EmbeddingProvider, EmbeddingService,
MemoryService, SearchService) at the top of the function for consistency, and
remove the duplicate ReflectionService/TaskService import statements currently
present later in the function (the ones at lines 82-83) so each service is
imported exactly once and imports are co-located.
- Line 67: Remove the unused noqa suppression by deleting the trailing "# noqa:
S106 - Default dev creds" from the password assignment (the
os.getenv("SURREAL_PASS", "root") expression) in src/codeagent/mcp/server.py so
the line simply sets password=os.getenv("SURREAL_PASS", "root") without the noqa
comment; ensure no other S106 suppressions remain unused in the surrounding
scope.
- Around line 64-93: After successfully calling db.connect()
(SurrealDBClient.connect), ensure the rest of the post-connect initialization
and app.run_stdio_async() are executed inside a try block and always call await
db.close() in a finally block; move all subsequent setup (initialize_schema,
EmbeddingProvider/EmbeddingCache/EmbeddingService, MemoryService, SearchService,
memory_tools.init_memory_tools, ReflectionService,
reflect_tools.init_reflection_tools, TaskService, task_tools.init_task_tools and
await app.run_stdio_async()) into the try and put await db.close() in finally so
the database connection is closed even if any of those steps or
app.run_stdio_async() raises.
In `@src/codeagent/mcp/services/embedding_service.py`:
- Line 65: Replace the silent filtering of `results` at the return statement
with a defensive assertion or explicit cast: check that no element in `results`
is None (and optionally that len(results) equals the expected number of inputs)
and raise a clear error if the invariant is violated, or use
typing.cast(list[list[float]], results) to explicitly tell the type checker;
target the `results` variable and the return expression in embedding_service.py
(the line currently doing `return [r for r in results if r is not None]`) so the
function fails loudly on unexpected provider behavior rather than silently
dropping entries.
In `@src/codeagent/mcp/services/memory_service.py`:
- Around line 185-212: _auto_link currently issues up to 5 sequential RELATE
queries (via self._db.query) which increases latency and allows exceptions to
bubble up and fail store(); change _auto_link to (1) build a single batched
multi-statement RELATE query or a parameterized RELATE ...;RELATE ... string
that links all qualifying memories in one DB round-trip using the same params
structure, and (2) make _auto_link resilient by wrapping its body in try/except
so failures are logged (use process logger or self._logger) and do not propagate
to store(); update callers (store()) to await the new best-effort _auto_link but
not rely on it for transactional success.
- Around line 75-88: The update method in MemoryService is assigning the literal
string "time::now()" to updated_at which will be stored as a string; change this
by either (A) using a raw SurQL update so the database evaluates time::now()
(replace the call to self._db.update in MemoryService.update with a raw UPDATE
<memory_id> SET updated_at = time::now(), ... or run a parameterized query that
sets updated_at = time::now()), or (B) set the timestamp in Python before
calling self._db.update (e.g., compute a UTC datetime string/ISO timestamp and
assign data["updated_at"] = <iso-utc-string>); locate this fix in the update
method of class MemoryService (method name update, references to
self._db.update, MemoryUpdate, and self._embedding) and ensure embedding logic
for "content" remains unchanged.
In `@src/codeagent/mcp/services/reflection_service.py`:
- Around line 161-234: The model_effectiveness function builds params including
"pattern" but never applies it to the WHERE clause, so task_pattern is ignored;
update the filters construction to include a condition referencing the $pattern
param (e.g., add a filter like "metadata.task_pattern LIKE $pattern" or whatever
column fits your schema) before joining into where, ensure params["pattern"]
remains set from task_pattern, and then leave the existing query call
(self._db.query(..., params)) unchanged so the DB uses the pattern filter;
reference: model_effectiveness, params, where, and the self._db.query call.
In `@src/codeagent/mcp/services/search_service.py`:
- Around line 1-5: The docstrings claim a hybrid HNSW+BM25+RRF search but the
implementation in search() is vector-only; either implement BM25+RRF or change
docs. To fix, either (A) implement full-text BM25 scoring and Reciprocal Rank
Fusion in the search method: add a BM25 text query against your text index (or
use an existing tokenizer/Whoosh/Elasticsearch/SQLite FTS), compute BM25 scores,
normalize and combine with the existing vector cosine scores using RRF (apply
rank-based reciprocal scores and sum), and return fused ranks; or (B) update the
module and class docstrings and any references to accurately state that
SearchService.search() currently performs vector-only cosine similarity search
(remove mentions of BM25 and RRF). Target the module/class docstrings and the
search() implementation in this file when applying the change.
- Line 72: The noqa directive on the surql query string is suppressing an unused
E501; remove E501 and keep only S608. Locate the f-string assigned to the
variable surql in search_service.py (the SELECT ...
vector::similarity::cosine(...) query) and update the inline comment from "#
noqa: S608, E501" to just "# noqa: S608" so only the actual required suppression
remains.
- Around line 27-35: The search method's boolean parameter include_graph should
be made keyword-only to avoid accidental positional passing; modify the
signature of async def search(...) by inserting a positional-only separator so
that include_graph can only be provided as a keyword (e.g., introduce a * before
include_graph in the parameter list), update any callers of SearchService.search
to pass include_graph by name, and run tests to ensure no call sites rely on
positional booleans; the symbols to change are the method name search and the
parameter include_graph.
- Around line 97-105: The current loop issues N+1 queries when include_graph is
true because for each row you call self._db.query with row.get("id"); instead
batch all row IDs before the loop (collect ids from the rows returned by the
initial query), run a single _db.query to fetch all related graph results for
those IDs, then map the returned related results by id and attach them to each
detail in the existing loop (the variables/functions to update are
include_graph, self._db.query usage, row.get("id"), detail and
details.append(detail)). Ensure the batched SurQL uses an IN/$ids-style lookup
and then merge the mapping so each detail["related"] is populated without
per-row round-trips.
In `@src/codeagent/mcp/services/task_service.py`:
- Around line 40-69: get_next_task currently restricts results with
"array::len(depends_on) = 0", which only returns tasks that never had
dependencies; change the WHERE logic used in the self._db.query call so it
returns tasks whose dependencies are either empty or all have status = 'done'
(i.e., check referenced tasks' status instead of array length). Update the SQL
built in get_next_task (the f"SELECT * FROM task WHERE {where} ..." call) to use
a NOT EXISTS or equivalent subquery/unnest that looks up each element of
depends_on and ensures no dependent task exists with status != 'done' (or
include an explicit join/subquery against the task table to confirm all
depends_on entries are completed), keeping the project filter and the
ordering/limit logic unchanged; adjust any params handling as needed so
_db.query still receives the same params dict.
In `@src/codeagent/mcp/tools/memory.py`:
- Around line 19-35: _globals _memory_service and _search_service are currently
typed as Any and default to None which can cause cryptic AttributeError if used
before init; add typed Optional[...] annotations for these globals and implement
small accessor functions (e.g., get_memory_service() and get_search_service())
that check the corresponding global and raise a clear RuntimeError if None, then
update callers to use these accessors; remove the unused "# noqa: PLW0603"
comment and ensure init_memory_tools(memory_service, search_service) still sets
the globals but without suppressing linter warnings.
- Around line 63-76: The current try block wraps both MemoryCreate(...) (which
can raise pydantic ValidationError) and _memory_service.store(create) (which can
raise service/DB errors), causing all failures to be reported as
ErrorCode.VALIDATION_ERROR; split the logic so you first construct the
MemoryCreate and catch pydantic.ValidationError to return ErrorResponse with
ErrorCode.VALIDATION_ERROR, then call await _memory_service.store(create) inside
its own try/except to catch service/DB exceptions and return an ErrorResponse
with an appropriate service error code (e.g., ErrorCode.SERVICE_ERROR or
ErrorCode.INTERNAL_ERROR); refer to MemoryCreate, MemoryType,
_memory_service.store, ErrorResponse, and ErrorCode.VALIDATION_ERROR when
applying the changes.
- Around line 79-110: The issue is that the boolean parameter include_graph in
the search function can be passed positionally (e.g. search("q", None, None,
None, 10, True)), which violates FBT001/FBT002; fix it by making include_graph
keyword-only by changing the search signature to place a bare '*' before
include_graph (e.g. keep max_results: int = 10, then add ', *, include_graph:
bool = False') so callers must use include_graph=<bool>; update any internal or
external callers if needed; target the search function and the include_graph
parameter in src/codeagent/mcp/tools/memory.py.
In `@src/codeagent/mcp/tools/reflect.py`:
- Around line 66-67: The catch-all except blocks in reflect.py are mapping every
error to ErrorCode.DB_ERROR (see the ErrorResponse creation in the except blocks
around the shown diff and the other occurrences at the blocks around lines 91–92
and 114–115); update those handlers to catch specific exception types first
(e.g., catch httpx.HTTPStatusError and any embedding-client exceptions and
return ErrorResponse(error=str(e), code=ErrorCode.EMBEDDING_ERROR)), catch
network/timeout exceptions (e.g., httpx.TimeoutException or requests.Timeout)
and return ErrorCode.NETWORK_TIMEOUT, catch pydantic/validation exceptions and
return ErrorCode.VALIDATION_ERROR, and only keep a final broad except Exception
as e that returns ErrorCode.INTERNAL_ERROR; ensure each modified except
constructs ErrorResponse(error=str(e), code=ErrorCode.<appropriate>) and apply
these changes to all three locations (the except blocks referenced in the diff
and the two other occurrences).
- Around line 17-27: Remove the unused `noqa: PLW0603` suppression and stop
silencing a non-enabled rule in init_reflection_tools; edit the function
signature to drop the comment " # noqa: PLW0603" and keep assigning to the
global _reflection_service as before, and optionally replace the parameter type
Any with a more specific Protocol or interface for the reflection service (or
add a TODO/comment if defining a Protocol isn’t practical now) to improve type
safety.
- Around line 55-67: Add an explicit None-guard at the start of each reflection
tool function (the one calling _reflection_service.reflect and the functions
improved_attempt and model_effectiveness) to check if _reflection_service is
None and immediately return an ErrorResponse with a clear message like
"Reflection service not initialized; call init_reflection_tools()" (use the
existing ErrorResponse/ ErrorCode types to match current error shape), so
AttributeError from calling methods on None is not confused with DB errors;
apply the same guard to improved_attempt and model_effectiveness and keep the
existing try/except for other runtime errors.
In `@src/codeagent/mcp/tools/task.py`:
- Around line 68-85: The current try/except around TaskCreate(...) and await
_task_service.create_task(create) maps all exceptions to
ErrorCode.VALIDATION_ERROR; split validation and service calls so only Pydantic
ValidationError from TaskCreate is caught and returned as
ErrorResponse(error=..., code=ErrorCode.VALIDATION_ERROR). Then wrap the await
_task_service.create_task(create) in its own try/except and map non-validation
failures (e.g., DB exceptions) to a different error code such as
ErrorCode.INTERNAL_ERROR or re-raise, referencing TaskCreate,
_task_service.create_task, ErrorResponse and ErrorCode.VALIDATION_ERROR in the
changes.
- Around line 19-32: The module currently exposes a global _task_service that
can be None and causes confusing AttributeErrors; change its annotation to
Optional[Any] and remove the unused "# noqa: PLW0603" comment, then add a single
accessor function get_task_service() that checks _task_service and raises a
clear RuntimeError (e.g., "task tools not initialized; call init_task_tools()")
when None; update all task tool functions to call get_task_service() instead of
directly using _task_service so callers fail fast with a clear message.
In `@tests/mcp/test_embedding_service.py`:
- Around line 60-70: The test function
test_embed_uses_default_cache_when_none_provided is marked with
`@pytest.mark.asyncio` but contains no awaits and should be a regular synchronous
test; remove the `@pytest.mark.asyncio` decorator and change the function
signature from async def to def (leaving the body as-is that constructs
mock_provider, instantiates EmbeddingService and asserts
isinstance(service._cache, EmbeddingCache)) so it runs as a normal pytest test
without unnecessary asyncio overhead.
In `@tests/mcp/test_memory_service.py`:
- Around line 377-418: The test
TestMemoryServiceAutoLink.test_auto_link_creates_edges_for_similar_memories
currently asserts mock_db.query.call_count == 3 which is brittle; update the
assertion strategy for service._auto_link to be resilient to changes in how
RELATEs are issued by verifying that the similarity search was executed and that
at least one subsequent query contains a RELATE operation: keep the
similarity-search check (e.g., that mock_db.query was called and returned the
expected similarity result) and replace the strict call_count assertion with
checks over mock_db.query.call_args_list to ensure one call contains the
similarity search pattern and at least one later call's query string or payload
includes "RELATE" (or the RELATE-equivalent used by the implementation) so the
test validates intent without relying on exact number of queries.
- Around line 221-231: The tests unpack a three-tuple from _make_service() but
the second/third element mock_embedding is unused; rename it by prefixing with
an underscore (e.g., change "service, mock_db, mock_embedding = _make_service()"
to "service, mock_db, _mock_embedding = _make_service()") in the affected tests
(test_update_skips_embedding_for_metadata_only, test_update_returns_result, and
any other tests in this file that unpack mock_embedding but don't use it) so
Ruff RUF059 warning is resolved; ensure you update all identical unpackings in
tests/mcp/test_memory_service.py.
- Around line 10-44: The helper functions _make_memory_create,
_make_memory_update and _make_service currently annotate returns as object which
hides real APIs; change their return annotations to the concrete types
MemoryCreate, MemoryUpdate and MemoryService (and for _make_service the tuple
should be (MemoryService, AsyncMock, AsyncMock)) so callers get proper type
info; keep the local imports inside the functions but use forward references
(string annotations) or guard imports with TYPE_CHECKING (or rely on from
__future__ import annotations already present) so the annotations resolve
without hoisting the imports.
In `@tests/mcp/test_memory.py`:
- Around line 14-48: Replace the multiple near-identical tests that assert
MemoryType members equal specific string values with a single parametrized
pytest test to reduce duplication: create one test (e.g.,
test_memory_type_values) decorated with pytest.mark.parametrize over tuples of
("member", "value") for the pairs KNOWLEDGE/"knowledge", EPISODE/"episode",
DECISION/"decision", PATTERN/"pattern", CODE_CHUNK/"code_chunk"; inside the test
import MemoryType and use getattr(MemoryType, member) == value to assert each
mapping, and keep the separate test that asserts
isinstance(MemoryType.KNOWLEDGE, str) if desired for the string-type check.
In `@tests/mcp/test_models_init.py`:
- Around line 15-79: The tests use weak "assert X is not None" checks after
importing symbols (e.g., Memory, MemoryCreate, MemoryUpdate, SearchResult,
SearchResponse, Task, TaskCreate, Project, ErrorResponse) which don't verify the
exported type; change each to a meaningful assertion such as asserting class
shape or inheritance (for example assert issubclass(Memory, BaseModel) or assert
issubclass(MemoryCreate, BaseModel) for pydantic models), for enums keep value
checks like assert TaskStatus.PENDING == "pending" and assert TaskType.TASK ==
"task", and for other concrete classes assert presence of expected attributes or
methods (e.g., hasattr(Task, "id") or hasattr(Project, "name")) to ensure the
correct symbols are exported rather than any placeholder.
In `@tests/mcp/test_reflection_service.py`:
- Around line 10-21: Update the _make_service return annotation so callers get
proper autocompletion: change the return type from tuple[object, AsyncMock,
AsyncMock] to a typed ReflectionService tuple (e.g., tuple[ReflectionService,
AsyncMock, AsyncMock] or tuple["ReflectionService", AsyncMock, AsyncMock]). To
make this work, either move the line "from
codeagent.mcp.services.reflection_service import ReflectionService" to module
scope or add from __future__ import annotations and keep the import inside the
function while using the forward-reference string form; keep the function body
unchanged except for the updated type hint.
In `@tests/mcp/test_reflection_tools.py`:
- Around line 31-108: Consolidate the duplicated tests
test_reflect_calls_service and test_reflect_passes_all_parameters by keeping a
single test (e.g., test_reflect_calls_service) that patches
ref_mod._reflection_service with mock_svc, awaits ref_mod.reflect(...) with the
full parameter set, asserts mock_svc.reflect.assert_awaited_once_with(...) to
verify the exact call, and then also inspects mock_svc.reflect.call_args[1] (or
the returned result) for the additional per-key assertions (feedback_type,
model_used, code_context, file_path); remove the redundant
test_reflect_passes_all_parameters to eliminate overlap.
In `@tests/mcp/test_schema.py`:
- Around line 45-51: The current tests test_analyzer_uses_blank_tokenizer and
test_analyzer_uses_camel_tokenizer use overly broad substring checks on
schema_content; update their assertions to look for a more specific tokenizer
context (e.g., assert "TOKENIZERS blank" in schema_content for
test_analyzer_uses_blank_tokenizer and assert "TOKENIZERS camel" in
schema_content for test_analyzer_uses_camel_tokenizer) so the tests only match
the tokenizer definitions and avoid false positives.
- Around line 196-199: The test_task_has_type_assert currently checks for the
broad substring '"task"' in schema_content which can match unrelated
occurrences; update the assertion to look for the specific type constraint on
the "type" column (e.g., the table column name "type" together with the
ASSERT/CHECK or enum/IN clause that restricts values to 'task' and 'epic') by
modifying test_task_has_type_assert to assert that schema_content contains a
precise snippet such as the CHECK/ASSERT clause or enum definition referencing
"type" and both 'task' and 'epic' (use the test function name
test_task_has_type_assert and the schema_content variable to locate and change
the assertion).
In `@tests/mcp/test_search_service.py`:
- Around line 136-163: The test test_search_includes_graph_when_requested
currently only checks that "related" exists in result["details"][0]; update it
to assert the actual content (e.g., that result["details"][0]["related"] ==
["memory:def"] or contains "memory:def") so the graph traversal result from
mock_db (the second query in _make_service sequence) is correctly propagated by
service.search; locate the test function name
test_search_includes_graph_when_requested and add a concrete assertion on
result["details"][0]["related"] after the existing length check.
In `@tests/mcp/test_server.py`:
- Around line 41-45: The test test_server_has_ping_tool currently only imports
callable ping instead of verifying registration; change it to either (A) make
the test async and import the app from codeagent.mcp.server then await
app.list_tools() and assert 'ping' (or the ping tool id) is present, or (B) keep
it synchronous but import the app's tool manager (e.g., app.tool_manager or
ToolManager instance) and inspect its internal registry/collection for the ping
tool, asserting it is registered; target the test_server_has_ping_tool function
and use app.list_tools() when awaiting in an async test or the manager's
registry attribute when using the sync approach.
In `@tests/mcp/test_task_service.py`:
- Around line 10-31: Change the helper return annotations to concrete types:
update _make_task_create to return TaskCreate instead of object and annotate
_make_service to return tuple[TaskService, AsyncMock] instead of tuple[object,
AsyncMock]; import TaskCreate and TaskService (or reference them in type
comments) and ensure AsyncMock is imported from unittest.mock so the
type-checker can validate callers of _make_task_create and _make_service.
In `@tests/test_embeddings.py`:
- Around line 50-132: Tests duplicate httpx.AsyncClient mock setup across
TestEmbeddingProviderEmbed (and TestEmbeddingProviderEmbedBatch); extract a
helper or fixture to build the mock client and reuse it. Create a helper (e.g.,
_mock_openai_client(response_data, status_code=200,
raise_for_status_effect=None)) that constructs MagicMock/httpx.Response and
AsyncMock/httpx.AsyncClient with __aenter__/__aexit__ and post returning the
response, then call that helper from the tests (or register it as a pytest
fixture) and keep assertions around EmbeddingProvider.embed unchanged; update
test methods in TestEmbeddingProviderEmbed and TestEmbeddingProviderEmbedBatch
to use the helper/fixture and remove the repeated mock_response/mock_client
boilerplate.
- Line 23: Remove the unused "# noqa: S106" suppressions from the test file by
deleting the trailing "# noqa: S106" on the EmbeddingProvider instantiation
lines (e.g., the "provider = EmbeddingProvider(api_key=\"sk-test-key\")"
occurrence) and the other test lines that pass literal api_key strings; ensure
you remove the same unused suppression from all similar provider/api_key
instantiation sites in tests/test_embeddings.py so no residual S106 noqa
directives remain.
- Around line 317-330: The tests use weak "is not None" checks; replace them
with meaningful assertions that validate the exported symbols are actual
classes/types: import the inspect module and assert
inspect.isclass(EmbeddingProvider) for the EmbeddingProvider export and assert
inspect.isclass(EmbeddingCache) for the EmbeddingCache export (referencing the
EmbeddingProvider and EmbeddingCache symbols in tests/test_embeddings.py) so the
tests verify the exported symbols are real class objects rather than just
non-None values.
Critical: - Fix time::now() stored as literal string in memory_service (use datetime.now(UTC)) Services: - Reuse httpx.AsyncClient with 30s timeout instead of creating per-request - Add close() to EmbeddingProvider for proper cleanup - Wrap auto_link in try/except (best-effort, non-blocking) - Batch RELATE queries into single multi-statement call - Fix task_pattern unused in reflection_service WHERE clause - Fix search_service docstrings (vector similarity, not hybrid) - Make optional params keyword-only in search_service - Batch graph queries (WHERE id IN $ids) instead of N+1 - Document depends_on filtering contract in task_service - Add defensive assertion in embed_batch Tools: - Proper typing for module globals (Service | None instead of Any) - Add None guards at top of every tool function - Separate validation errors from service errors (distinct error codes) - Make include_graph keyword-only in memory.search() - Remove unused noqa directives Models: - Add confidence bounds validation (ge=0.0, le=1.0) - Sort __all__ alphabetically Server: - Consolidate lazy imports at top of run_server() - Wrap startup in try/finally for db.close() and provider.close() Tests: - Parametrize MemoryType enum tests - Use identity assertions (assert X is Y) where appropriate - Concrete return types for helper factories - Extract httpx mock helper to reduce duplication - Remove overlapping reflection test - More specific schema assertions - Fix tool count assertion (14 tools in modules, ping is in server) 301 tests passing, ruff clean. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 18
🤖 Fix all issues with AI agents
In `@src/codeagent/mcp/embeddings/provider.py`:
- Around line 92-113: Handle empty input fast and add defensive parsing: in
embed_batch (and/or before calling _request) short-circuit when texts is an
empty list and return [] immediately to avoid a useless API call; in _request
wrap parsing in a try/except and validate the response shape—first call
response.json() inside a try, ensure the result contains a "data" key that is a
list, and that each item has required "index" and "embedding" keys (and that
"embedding" is a list of numbers); if validation fails, raise a clear
RuntimeError (or custom error) that includes the raw response body and a short
message about which key was missing or malformed so callers get actionable
diagnostics; keep using response.raise_for_status() before parsing to preserve
HTTP error behavior.
In `@src/codeagent/mcp/models/memory.py`:
- Around line 134-148: SearchResponse and SearchService.search() are
inconsistent: SearchResponse.details is typed as list[Memory] but
SearchService.search() returns raw dict rows; fix by either making the model
match runtime output or making the service return typed models—prefer the
minimal fix: change SearchResponse.details to list[dict[str, Any]] (or
list[Any]) so it reflects the actual returned rows, and update any usages of
SearchResponse or SearchService.search() accordingly; alternatively, if you
prefer strong typing, modify SearchService.search() to construct and return a
SearchResponse instance by mapping each detail dict to Memory.parse_obj(detail)
before returning.
In `@src/codeagent/mcp/server.py`:
- Around line 71-94: Move the try/finally to start immediately after await
db.connect() so that all setup calls (await db.initialize_schema(...),
EmbeddingProvider(), EmbeddingCache(), EmbeddingService(...),
MemoryService(...), SearchService(...), memory_tools.init_memory_tools(...),
ReflectionService(...), reflect_tools.init_reflection_tools(...),
TaskService(...), task_tools.init_task_tools(...), and awaiting
app.run_stdio_async()) are inside the try block to ensure resources are cleaned
on setup failure; in the finally ensure both provider.close() and db.close()
always run even if provider.close() raises (e.g., call provider.close() inside
its own try/except or try/finally and then always call await db.close()) so
neither resource is leaked.
In `@src/codeagent/mcp/services/reflection_service.py`:
- Around line 55-100: The reflect() implementation always sets
metadata["outcome"] = "failure", which prevents model_effectiveness from ever
counting successes; update reflect (or its caller) to determine outcome
dynamically and store it in metadata instead of hardcoding "failure" — e.g., add
an outcome parameter to reflect() or derive outcome from feedback_type/output
(set metadata = { "outcome": outcome, ... } where outcome is "success" or
"failure"), and ensure the episode creation and returned dict include that
computed outcome so model_effectiveness can correctly count successes.
- Around line 215-226: The current selection loop can promote a model with 0%
success over the "sonnet" default because best_rate starts at 0.0; change the
update logic in the loop over model_stats so you only consider models with at
least one success (i.e., stats["success"] > 0 or rate > 0) before applying the
comparison that sets best_model and best_rate; keep the existing tie-break on
stats["total"] but ensure it only runs when rate > 0 so a zero-success model
cannot replace the default (update the condition involving best_rate, rate,
stats["success"], and stats["total"] accordingly).
- Around line 81-92: The reflect() implementation currently calls
self._db.create("memory", ...) directly which bypasses MemoryService.store() and
therefore skips Zettelkasten-style auto-linking (MemoryService._auto_link());
update reflect() to call MemoryService.store(...) with the same payload (type,
content, title, metadata, embedding, tags, confidence) so the auto-linking logic
runs, or if bypass is intentional, add a clear comment explaining why and
document that created_at/updated_at are left to SurrealDB defaults; ensure you
reference the MemoryService.store method and preserve the existing fields passed
to the direct create.
In `@src/codeagent/mcp/services/search_service.py`:
- Around line 53-58: The params dict includes "query" but the SurQL only uses
$emb, $limit and filter params, so "$query" is dead data; fix by either removing
"query" from the params dict or wire it into the SurQL if intended. Concretely,
in the function that builds params (the params variable alongside
query_embedding and max_results) remove the "query": query entry, or update the
SurQL string (the SurQL variable used for the vector search) to reference $query
where appropriate (e.g., in a text match clause) and ensure any dynamic filter
logic uses it consistently.
In `@src/codeagent/mcp/services/task_service.py`:
- Around line 15-146: The get_next_task and complete_task methods in TaskService
currently return plain-string error dicts (e.g. {"code": "NOT_FOUND"}); change
them to return a consistent ErrorResponse shape by importing ErrorResponse and
ErrorCode and returning ErrorResponse(error="...",
code=ErrorCode.NOT_FOUND).model_dump() (or alternatively set "code":
ErrorCode.NOT_FOUND if you prefer minimal change) inside get_next_task and
complete_task so callers always receive the enum-backed error format; update
references to TaskService.get_next_task and TaskService.complete_task
accordingly.
- Around line 78-108: complete_task currently always writes resolved_by and
summary into the UPDATE statement (via the SQL passed to self._db.query), which
can overwrite existing values with None; change complete_task to build the
UPDATE dynamically so resolved_by and summary SET clauses are only included when
their arguments are not None (keep updating status and updated_at
unconditionally), and adjust the params dict accordingly before calling
self._db.query (reference: complete_task, self._db.query, task table fields
resolved_by/summary/task_id).
- Around line 34-38: The code assumes self._db.create("task", data) returns a
non-empty list and does result = result[0], which will raise IndexError if an
empty list is returned; update the method in
src/codeagent/mcp/services/task_service.py (the block using create.model_dump(),
self._db.create, and variable result) to defensively handle an empty-list result
from self._db.create by checking if isinstance(result, list) and either
returning None or raising a clear error if not result (empty), otherwise set
result = result[0]; ensure callers can handle the chosen behavior and keep the
rest of the flow unchanged.
In `@src/codeagent/mcp/tools/task.py`:
- Line 42: The parameter name `type` in create_task and list_tasks shadows the
Python builtin; rename the parameter to `task_type` in both function signatures
(create_task, list_tasks) and update all references inside those functions and
any internal call sites in the same module or tests to use `task_type`; also
update any dicts or payload keys only if they currently depend on the parameter
name (leave external API payload keys unchanged unless required) so lint
warnings (Pylint W0622) are resolved and behavior is preserved.
In `@tests/mcp/test_reflection_tools.py`:
- Around line 18-25: The test test_init_reflection_tools_sets_service mutates
module-level state by calling ref_mod.init_reflection_tools(mock_svc) and
leaving ref_mod._reflection_service set; change the test to save the original
value of ref_mod._reflection_service (or use pytest's monkeypatch to set and
restore it) and restore that original after the assertion so the module-level
state is not leaked to other tests (refer to ref_mod.init_reflection_tools and
the _reflection_service symbol when making the change).
In `@tests/mcp/test_schema.py`:
- Around line 201-206: The test_task_has_status_assert uses broad substring
checks on schema_content that can match other places; change it to assert the
full status ASSERT clause instead (match the complete "$value IN [...]"
expression) so it only verifies the enum constraint. In the
test_task_has_status_assert function, replace the four separate checks for
'"pending"', '"in_progress"', '"done"', and '"blocked"' with a single assertion
that schema_content contains the exact ASSERT clause for the task status (e.g.
the string representing '$value IN ["pending","in_progress","done","blocked"]')
to ensure the test targets the enum constraint and not other occurrences like
the pending_tasks view.
- Around line 229-233: The assertions in test_recent_failures_view are too
generic; update the checks on schema_content to assert a specific WHERE clause
fragment such as 'outcome = "failure"' (or the exact quoting used in your SQL)
and include the view name recent_failures to ensure the test verifies the
intended filter; modify the test_recent_failures_view function to replace the
loose asserts for "outcome" and "failure" with an assertion that the combined
condition (e.g., 'outcome = "failure"') appears in schema_content alongside the
DEFINE TABLE recent_failures AS check.
- Around line 171-174: The test_project_prefix_unique_index currently checks
"project_prefix" and "UNIQUE" separately on schema_content which can match
unrelated UNIQUE indexes; update the assertion to verify that the project_prefix
index is declared as unique by matching the combined pattern (for example
require "CREATE UNIQUE INDEX" or a regex like
CREATE\s+UNIQUE\s+INDEX.*\bproject_prefix\b) against schema_content so the
presence of the unique modifier is tied specifically to the project_prefix
index.
In `@tests/mcp/test_server.py`:
- Around line 92-110: The test_test_all_14_tools_accounted_for currently asserts
a hardcoded length (len(all_tools) == 14) which always passes; change it to
compare the constructed expected tool list (memory_tools, task_tools,
reflection_tools -> all_tools) against the actual registered tools on the
running application instead: obtain the app/server instance used in other tests
(e.g., the app fixture or server object) and query its tool registry (the method
or attribute that holds registered tools on the app) to assert the counts and/or
names match the expected all_tools entries, then keep the existing callable
check using getattr(mod, name) to ensure each expected tool is present and
callable.
In `@tests/mcp/test_task_service.py`:
- Around line 33-84: Add a new async test in TestTaskServiceCreateTask that
ensures TaskService.create_task raises on an empty-list response from the
underlying DB: call _make_service() to get service and mock_db, set
mock_db.create.return_value = [], call _make_task_create() and then assert the
service.create_task(create) raises (e.g., with pytest.raises(IndexError));
reference the create_task method and mock_db.create to locate where to insert
the test (name it test_create_task_raises_on_empty_list_response).
In `@tests/test_embeddings.py`:
- Around line 25-28: The conditional uses a truthiness check on
raise_for_status_effect; change the branch to explicitly test for None by using
"if raise_for_status_effect is not None:" so the behavior matches its type
annotation (Exception | None) and then set
mock_response.raise_for_status.side_effect = raise_for_status_effect when not
None, otherwise assign mock_response.raise_for_status = MagicMock() (references:
raise_for_status_effect and mock_response.raise_for_status).
Round 2 CodeRabbit fixes (18 comments): - provider.py: empty-input short-circuit, defensive API response parsing - server.py: widen try/finally scope to cover all setup after db.connect() - reflection_service.py: add outcome param (default "failure"), document direct DB bypass, fix 0%-success tie-breaking in model_effectiveness - search_service.py: remove dead params["query"] - task_service.py: guard empty db.create list, conditional SET in complete_task, use ErrorCode enum in error dicts - tools/task.py: rename type -> task_type to avoid shadowing builtin - models/memory.py: SearchResponse.details type to list[dict[str, Any]] - test_reflection_tools.py: monkeypatch to prevent module state leak - test_schema.py: specific assertions for unique index, status, views - test_server.py: verify tools against app registry instead of arithmetic - test_task_service.py: add empty-list edge case test - test_embeddings.py: explicit is not None check Internal code review fixes: - embedding_service.py: replace assert with RuntimeError (not stripped by -O optimization) - precommit.py: fix pyright type error (Dumper -> MultilineDumper) - ruff format: auto-format 8 files 302 tests passing, ruff check + format clean. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 16
🤖 Fix all issues with AI agents
In `@src/codeagent/mcp/embeddings/provider.py`:
- Around line 16-18: The docstring promises async context manager support but
the provider class that creates the httpx.AsyncClient lacks
__aenter__/__aexit__; add async def __aenter__(self): return self and async def
__aexit__(self, exc_type, exc, tb): await self.close() (or call the existing
close method) so using "async with <ProviderClass>()" properly returns the
instance and releases the httpx.AsyncClient connection pool; reference the
provider class that constructs the AsyncClient and its close() method when
making the change.
In `@src/codeagent/mcp/services/memory_service.py`:
- Around line 134-190: The stats() implementation is safe but can be optimized
to reduce DB round trips: replace the three separate queries (the calls that
populate total, by_type, and by_project) with a single multi-statement SQL
string built using the existing where variable (e.g., "SELECT count() AS total
FROM memory{where} GROUP ALL; SELECT type, count() AS count FROM memory{where}
GROUP BY type; SELECT project, count() AS count FROM memory{where} GROUP BY
project"), call self._db.query once with params, then unpack the returned list
into total, by_type, and by_project result slots and reuse the existing parsing
logic to build total_val, type_dict, and project_dict. Ensure the where
construction and parameterization remain unchanged and remove or keep the noqa:
S608 flags as appropriate.
- Around line 192-221: In _auto_link, replace the brute-force similarity query
that uses vector::similarity::cosine(...) with SurrealDB's KNN operator to
leverage the HNSW index: query for id and vector::distance::knn() AS score from
memory, include the clause "WHERE id != $id AND embedding <|5,200|> $emb", ORDER
BY score (ascending) LIMIT 5, and keep using the same params {"emb": embedding,
"id": memory_id}; then continue filtering results by score and building the
RELATE statements as before.
- Around line 55-80: The read method currently issues self._db.query("UPDATE $id
SET access_count += 1...") before checking existence, which upserts ghost
records; change read so it first calls self._db.select(memory_id) (the existence
check in read), return the NOT_FOUND error if no result, and only then call
self._db.query to increment access_count/last_accessed for the found memory_id;
keep the existing related_memories graph query (the "related" query) unchanged
and attach it to the result after the access-count update.
In `@src/codeagent/mcp/services/reflection_service.py`:
- Around line 82-97: The current code in ReflectionService bypasses
MemoryService and calls self._db.create(...) but then assumes result[0] exists
when result is a list, risking IndexError; add the same defensive check used in
TaskService.create_task: after calling self._db.create verify result is not an
empty list (and raise a RuntimeError with a clear message if it is), otherwise
extract episode_id safely from result[0] (or from result when not a list);
update the handling around the variables result and episode_id (and the method
that creates episodes) to mirror TaskService.create_task's guard.
- Around line 28-39: The service method ReflectionService.reflect now accepts an
outcome parameter but the MCP tool function reflect (in
src/codeagent/mcp/tools/reflect.py) does not expose or forward it, so outcome
remains hardcoded "failure"; update the tool's reflect function signature to
accept outcome: str = "failure" and pass that outcome value through to the
service call (and any episode dict construction) so episodes created by the tool
reflect() propagate the true outcome for model_effectiveness tracking.
In `@src/codeagent/mcp/services/search_service.py`:
- Around line 104-127: The details dict currently only adds a "related" key when
include_graph is True and row_id exists in related_map, causing consumers to
handle missing keys; inside the loop in the function that builds index/details
(uses variables rows, detail, row_id, related_map, include_graph), change the
logic so that when include_graph is True you always set detail["related"] =
related_map.get(row_id, []) (i.e., assign an empty list when no entry exists)
before appending detail, ensuring a consistent shape for all returned detail
objects.
In `@src/codeagent/mcp/services/task_service.py`:
- Around line 61-80: The truthy check `if project:` silently treats empty string
as unset and omits the project filter; change this to an explicit None check
(`if project is not None`) so an empty-string project is passed through and
added to `params` and `filters` (update the same pattern in `list_tasks` lines
referenced), ensuring the query uses the provided value even when it's an empty
string and preserving the behavior that only None means "no filter".
In `@tests/mcp/test_memory.py`:
- Around line 234-311: Add a parametrized pytest that asserts creating a Memory
with out-of-range confidence raises ValidationError: import Memory, MemoryType,
ValidationError, UTC and datetime, then parametrize bad values (e.g., -0.1, 1.1,
2.0) and inside with pytest.raises(ValidationError) call Memory(...,
confidence=bad_confidence, created_at=now, updated_at=now, embedding=[],
content="test", type=MemoryType.KNOWLEDGE) to validate the Field ge=0.0 le=1.0
constraint on the Memory model.
In `@tests/mcp/test_reflection_service.py`:
- Around line 226-298: Add a test to cover tie-breaking in
TestModelEffectiveness: create a new async test (e.g.,
test_model_effectiveness_tie_breaks_prefers_higher_success_count) that uses
_make_service(), sets mock_db.query.return_value to a dataset where two models
(e.g., "haiku" and "opus") end up with the same success rate but different
absolute success counts (so success_rate equal but one model has more
successes), call service.model_effectiveness(...), and assert the
recommended_model is the model with the higher absolute success count (and
verify the per-model stats contain the expected success/failure totals);
reference service.model_effectiveness and mock_db.query to locate where to
inject the mocked results.
In `@tests/mcp/test_schema.py`:
- Around line 45-51: The test named test_analyzer_uses_camel_tokenizer is
misleading because it asserts the full tokenizer string ("TOKENIZERS blank,
class, camel") rather than only the camel tokenizer; update the test to match
intent by either renaming the function to test_analyzer_tokenizer_list (or
similar) to reflect that it verifies the full list, or split into separate tests
(e.g., test_analyzer_uses_blank_tokenizer, test_analyzer_uses_class_tokenizer,
test_analyzer_uses_camel_tokenizer) each asserting their respective substring;
locate and update the function test_analyzer_uses_camel_tokenizer in
tests/mcp/test_schema.py and adjust the assertion names accordingly so test
names match their assertions.
- Around line 204-207: The test_task_has_priority_assert currently checks
generic substrings "$value >= 1" and "$value <= 5" which can match any ASSERT;
update test_task_has_priority_assert to assert the priority field context in
schema_content (e.g. that the "priority" field definition exists) and then
verify the ASSERT clause tied to that field (preferably the full one-line ASSERT
for priority such as the substring containing the priority field name plus the
"$value >= 1" and "$value <= 5" checks) so the assertions only match the
priority field; modify assertions that reference schema_content in
test_task_has_priority_assert accordingly.
- Around line 61-68: The test_memory_has_type_field assertion is too broad
because it checks individual strings like '"knowledge"' rather than the full
enum constraint; update test_memory_has_type_field to assert the complete ASSERT
clause that defines allowed values for the memory type (match the pattern used
in task type/status tests) by checking that schema_content contains the full
"$value IN ['knowledge','episode','decision','pattern','code_chunk']" (or the
exact formatting used in schema) so the test validates the DEFINE FIELD type ...
ASSERT constraint rather than any scattered occurrences of those words.
- Around line 209-219: The current tests test_task_id_unique_index,
test_task_status_index, and test_task_project_index only check for index names;
change each to assert the full CREATE INDEX definition string (the same level of
specificity as the project prefix test) so the schema_content is validated
exactly. In the functions test_task_id_unique_index, test_task_status_index, and
test_task_project_index, replace the simple name checks with assertions that
schema_content contains the exact index DDL fragment (e.g., the full "CREATE
INDEX IF NOT EXISTS ... ON task ..." or the unique index clause for task_id)
matching how the project prefix test asserts its index definition.
In `@tests/mcp/test_task_service.py`:
- Around line 154-214: Add a new async test mirroring
test_complete_task_includes_resolved_by that calls TaskService.complete_task
with summary set and asserts the DB query includes the SET clause and parameter:
arrange service, mock_db from _make_service(), call await
service.complete_task("CA-001", summary="All done"), then inspect
mock_db.query.call_args to assert the SQL string (call_args[0][0]) contains
"summary = $summary" and the params (call_args[0][1]) include summary == "All
done"; name the test test_complete_task_includes_summary and follow the same
mock_db.query return pattern as the other tests.
In `@tests/mcp/test_task_tools.py`:
- Around line 15-25: The test leaks module-level state by permanently setting
task_mod._task_service to a plain object; fix it by saving the original value
before calling init_task_tools and restoring it after the assertion (e.g.,
original = getattr(task_mod, "_task_service", sentinel);
task_mod.init_task_tools(mock_svc); assert ...; if sentinel: delattr(task_mod,
"_task_service") else: setattr(task_mod, "_task_service", original)).
Alternatively use monkeypatch.setattr(task_mod, "_task_service", original,
raising=False) to restore; reference symbols:
TestInitTaskTools.test_init_task_tools_sets_service, codeagent.mcp.tools.task,
init_task_tools, _task_service.
|
@coderabbitai resolve |
✅ Actions performedComments resolved and changes approved. |
Resolve merge conflicts from main integration: - pyproject.toml: main's 2-space format + our pydantic/httpx deps - server.py: keep full Epic 6 implementation - precommit.py: auto-merged cleanly Fix 226 ruff violations from new strict config (select = ["ALL"]): - TC001: Move runtime-unnecessary imports into TYPE_CHECKING blocks - A002: Rename shadowed builtins (type->memory_type, id->memory_id) - E501: Break long lines to fit 88-char limit - PLR2004: Extract magic numbers into named constants - PLR0913/PLW0603/PLC0415: Add noqa for intentional patterns - PT023: Add parentheses to pytest marks - SLF001: Allow private member access in tests - Update all test calls to match renamed parameters Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
# Conflicts: # pyproject.toml # ruff.toml # src/codeagent/mcp/server.py
The mypy hook uses `uv run mypy` but CI was missing uv installation. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
mypy fails because it's not in project dependencies. The project uses pyright for type checking (configured in pyproject.toml). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Code Review - Issues FoundIssue 1:
|
Biome expects 'include' (singular) in override blocks. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Code reviewFound 1 issue: Issue:
|
Add comprehensive documentation for the unified MCP rewrite: - Design ideas: unified memory system, SurrealDB features, enterprise patterns - Schema reference: complete SurrealDB schema with HNSW, BM25, changefeeds - Tool reference: 15 unified tools replacing 36 from 4 separate MCPs - Current architecture docs for migration reference - Epic 6/7/8 implementation plans Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Stream B: Remove configs, templates, and hooks owned by ai-guardrails. These are now installed via `ai-guardrails-init --force --ci`. Keep only codeagent-specific files (languages.yaml, CLAUDE.md.template, skill-template.md). Add lib/hooks/ to .gitignore (symlinked at init). Stream C: Add quality-gates skill documenting enforcement architecture. Update python skill with project conventions (future annotations, TYPE_CHECKING pattern, A002 avoidance, acceptable noqa patterns). - Add mypy to dev dependencies - Add coverage config (branch=true, fail_under=85) - Fix pip-audit hook nesting in pre-commit config - Relax markdownlint: disable cosmetic rules formatters can't fix - Reinstall check.yml with lint + test jobs via ai-guardrails Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
…fig, shellcheck Small focused skills for each quality tool in ai-guardrails: - biome: v2 TS/JS config, naming, no-any, no-default-export, array syntax - ruff: ALL rules, banned APIs, complexity limits, per-file-ignores - rustfmt: formatting style, import grouping, nightly features - stylua: Lua formatting config - editorconfig: cross-editor baseline, language-specific overrides - shellcheck: lint + shfmt format, common errors, set -euo pipefail These skills persist tooling knowledge across context compactions. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 45
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
.coderabbit.yaml (1)
53-57: 🧹 Nitpick | 🔵 TrivialAdd the future annotations requirement to Python path instructions.
The retrieved learning indicates that Python files should include
from __future__ import annotationsat the start. This requirement is currently missing from the Python-specific path instructions.📋 Proposed addition
- path: "**/*.py" instructions: | + - Ensure 'from __future__ import annotations' at the start of file - Enforce type hints on all function signatures - Check for proper exception handling (no bare except) - Verify docstrings on public functions/classesBased on learnings: "Include 'from future import annotations' at the start of all Python files"
🤖 Fix all issues with AI agents
In @.coderabbit.yaml:
- Line 51: Update the misleading comment line that says "Uncomment and customize
for your project" to clearly state the actual state of the following
configuration: either indicate that the path_instructions block is active by
default (referencing the path_instructions key) or change it to a true example
by commenting out or removing the active path_instructions entries; specifically
edit the comment immediately above path_instructions to reflect Option 1 (active
defaults) or Option 2 (examples to uncomment) so users aren’t misled about
whether path_instructions will be applied.
In @.github/workflows/check.yml:
- Around line 65-72: The CI step named "Run tests with coverage" currently
generates an XML coverage report via the --cov-report=xml flag but never uploads
or publishes it; either remove the --cov-report=xml option from the pytest
command in that step or add a follow-up step (e.g., an "Upload coverage XML"
artifact step or a Codecov upload step) to upload the generated coverage xml so
it's consumed by downstream tools; update the workflow to match your intent
(remove the flag if unused, or add an actions/upload-artifact or codecov action
after the pytest step) and ensure the pytest step and any new upload step
reference the same XML filename produced by pytest.
- Around line 59-60: The workflow has an inconsistent action pin: the step named
"Install uv" uses astral-sh/setup-uv@v4 while the lint job uses
astral-sh/setup-uv@v5; update the "Install uv" step to use the same version
(astral-sh/setup-uv@v5) so both jobs are pinned consistently to v5.
In @.gitignore:
- Line 11: The project is ignoring the dependency lockfile "uv.lock", which
prevents committing a reproducible lock for this application; remove "uv.lock"
from the .gitignore entry so the lockfile can be tracked, add and commit the
generated uv.lock to the repository, and ensure CI and developer workflows use
that committed uv.lock to pin dependency versions (look for the "uv.lock" line
in .gitignore and delete it, then git add/commit the resulting uv.lock file).
In @.pre-commit-config.yaml:
- Around line 36-40: The .pre-commit-config contains three identical repo
entries for "https://github.com/pre-commit/pre-commit-hooks" at rev v5.0.0 (each
declaring hooks like id: detect-private-key); consolidate these into a single
repo block containing all hooks used (e.g., detect-private-key and any others
currently repeated) so the repo is declared once, or if separation is
intentional, add a clarifying comment above each block; update the single repo
block to list every required hook id to replace the three duplicated blocks.
- Around line 14-21: The pre-commit hook entry "lib/hooks/format-and-stage.sh"
referenced by the hook id "format-and-stage" does not exist; either add the
missing executable script at lib/hooks/format-and-stage.sh (make it executable
and implement the formatting + staging logic expected by the hook) or
remove/replace the hook entry in .pre-commit-config.yaml (update the "entry" to
an existing script or delete the hook block) so that pre-commit no longer fails
on every run.
- Around line 152-164: The mypy pre-commit hook (id: mypy, name: "python - mypy
type check (strict)") will fail because additional_dependencies is empty while
the project uses third-party libs; either remove the mypy hook entirely from
.pre-commit-config.yaml if pyright is the canonical checker, or populate
additional_dependencies with the required packages/stubs (e.g., types-pydantic,
types-requests or relevant stub packages and the actual third-party packages
like pydantic, httpx, surrealdb) and/or relax strict flags so mypy can run in
the isolated env; also consider adjusting the global fail_fast setting if you
keep the hook to avoid blocking downstream hooks on one mypy failure.
In `@docs/ideas/enterprise-memory-patterns.md`:
- Line 131: Update the sentence "Our 15 tools is the right balance for a unified
system." to use correct subject-verb agreement by replacing "is" with "are" so
it reads "Our 15 tools are the right balance for a unified system."; locate the
sentence in the markdown content that currently starts with "Our 15 tools is"
and make this single-word verb change.
In `@docs/ideas/unified-memory-system.md`:
- Line 96: Change the phrasing that currently reads "Should `decision` type
memories be auto-created from `/plan` output?" to use a hyphenated compound
modifier: "Should `decision-type` memories be auto-created from `/plan`
output?"—update the instance referencing "decision type" to "decision-type" to
correct the grammar.
- Line 48: Update the incorrect architecture path string in
docs/ideas/unified-memory-system.md: replace the path literal
"codeagent/src/codeagent/mcp/" with the correct repository path
"src/codeagent/mcp/" so references (e.g., to files like
src/codeagent/mcp/services/reflection_service.py) match the actual repo layout.
In `@docs/mcp-tool-reference.md`:
- Around line 140-149: The docs example for the `stats` response includes
`avg_confidence` and `total_links` which are not returned by the actual
MemoryService.stats() implementation; either update the example to match the
real output (only `total`, `by_type`, `by_project`) or extend
`MemoryService.stats()` to compute and return `avg_confidence` and
`total_links`; locate the `MemoryService.stats()` method and either add
aggregation logic to compute average confidence and total links from stored
memories (and include those keys in the returned object) or remove those keys
from the docs JSON example so consumers see the actual schema.
- Around line 106-112: Doc mismatch: the delete operation lists parameter `id`
but the implementation expects `memory_id`; update the docs to match the code by
renaming the parameter in the parameters table from `id` to `memory_id`, adjust
the description if needed to mention "Memory record ID", and ensure the same
naming is used consistently for the read/update/delete entries so they align
with the function signature that uses memory_id.
- Around line 43-53: The docs list parameters that don't match the
implementation: update the reference to match the actual search tool and
SearchService.search() signature by renaming the `type` doc entry to
`memory_type` and remove the `max_tokens` parameter from the table (or, if the
feature was intended, add/implement `max_tokens` handling in
SearchService.search() and src/codeagent/mcp/tools/memory.py). Ensure the docs
and the code (SearchService.search and the search tool implementation) use the
same parameter names and semantics.
- Around line 74-98: The docs for the tools `read` and `update` list the
parameter as `id` but the implemented tool functions expect `memory_id`; fix the
mismatch by making the external API consistent: either update the documentation
tables to rename the `id` parameter to `memory_id` (and update the description)
for both `read` and `update`, or modify the tool functions (`read`, `update`) to
accept `id` (or accept both `id` and `memory_id` and map `id` -> `memory_id`) so
consumers passing `id` work; ensure the chosen change is applied consistently to
the parameter lists and examples for both tools.
In `@docs/plans/epic6-unified-mcp.md`:
- Line 37: The documented file paths incorrectly include a redundant
"codeagent/" prefix; update the occurrences to use the package-root path
"src/codeagent" instead — e.g., change references to SurrealDBClient from
"codeagent/src/codeagent/mcp/db/client.py" to "src/codeagent/mcp/db/client.py"
and similarly fix the file-structure diagram entry
"codeagent/src/codeagent/mcp/" to "src/codeagent/mcp/". Ensure all mentions in
this document are consistent with pyproject.toml's packages =
[\"src/codeagent\"] so the class name SurrealDBClient and any other identifiers
still point to the correct file location.
In `@docs/surrealdb-schema-reference.md`:
- Around line 308-314: The example shows AsyncSurreal/db.signin using
os.getenv("SURREAL_PASS", "codeagent") which conflicts with the Docker Compose
startup that uses --pass root; update the example so the default matches Docker
(change the SURREAL_PASS default to "root") or alternatively update the Docker
Compose flag to use --pass codeagent — ensure you modify the AsyncSurreal signin
call (the SURREAL_PASS default) or the Compose startup password so both use the
same value and update any accompanying comment to reflect the chosen credential.
- Around line 143-157: The SurQL block "DEFINE EVENT auto_link" is documented
but not present in the deployed schema; update the docs to avoid confusion by
either removing the SurQL snippet or adding a clear one-line note immediately
above it stating that this event is shown for reference only and that
auto-linking is implemented in Python via MemoryService._auto_link() (and not
defined in the DB schema), and optionally add a pointer to the Python
implementation for reference.
- Line 185: The documentation entry showing "DEFINE TABLE task SCHEMAFULL
CHANGEFEED 90d;" is inconsistent with the actual schema and tests; update that
line in docs/surrealdb-schema-reference.md to read "DEFINE TABLE task SCHEMAFULL
CHANGEFEED 30d" so the documented CHANGEFEED duration for the task table matches
the schema definition (DEFINE TABLE task SCHEMAFULL CHANGEFEED 30d) and the test
assertion.
In `@framework/skills/biome/SKILL.md`:
- Line 14: The bare URL on the Schema line (Schema:
`https://biomejs.dev/schemas/2.3.12/schema.json`) violates markdownlint MD034;
update that line to either wrap the URL in angle brackets (e.g., Schema:
`<https://biomejs.dev/schemas/2.3.12/schema.json>`) or convert it into a proper
markdown link (e.g., Schema: `[biome
schema](https://biomejs.dev/schemas/2.3.12/schema.json)`) so the schema
reference no longer appears as a bare URL.
In `@framework/skills/editorconfig/SKILL.md`:
- Around line 38-43: The section titled "C# Naming (via EditorConfig)" mixes
naming rules and using-directive ordering; rename the header to "C# Conventions"
or split it into two subsections—e.g., "C# Naming" covering the two bullets
about Public members and Private fields, and "Using directive ordering" covering
"System directives sorted first" and "Separate import directive groups"—then
update the list bullets under the new headers so each rule (Public members:
PascalCase, Private fields: `_camelCase` with underscore prefix, System
directives sorted first, Separate import directive groups) is clearly scoped to
the appropriate subsection.
In `@framework/skills/quality-gates/SKILL.md`:
- Around line 100-102: Update the documentation to clarify that pyright is the
primary type checker used by CI and mypy is optional/supplementary: in the CI
pipeline section mention that the pipeline runs uv run pyright (primary) and
that uv run mypy src/ --strict is provided as an optional local check for
stricter/mypy-specific rules; reference the commands shown (uv run pyright and
uv run mypy src/ --strict) and add one sentence indicating mypy is intentionally
not run in CI to avoid confusion.
In `@framework/skills/shellcheck/SKILL.md`:
- Around line 1-65: Add a short "References" section to SKILL.md linking to the
official ShellCheck (https://www.shellcheck.net and
https://github.com/koalaman/shellcheck), shfmt (https://github.com/mvdan/sh),
and pre-commit (https://pre-commit.com) docs; place it near the existing
headings "Shellcheck", "Shfmt", or "Pre-commit Config" so readers can quickly
jump to authoritative documentation for the linting/formatting flags and usage
examples.
In `@src/codeagent/mcp/server.py`:
- Around line 75-79: The SurrealDBClient instantiation uses insecure fallback
credentials (username="root", password="root") which can silently allow
misconfigured deployments; update the code around SurrealDBClient/db to stop
using hardcoded defaults — require SURREAL_USER and SURREAL_PASS to be present
or, if ENVIRONMENT (or a similar env flag) == "development", allow explicit dev
defaults; otherwise log a clear error and raise/exit when the vars are missing
so production cannot proceed with dev creds. Use the existing symbols
SurrealDBClient and db and check SURREAL_URL/SURREAL_USER/SURREAL_PASS (and
ENVIRONMENT or NODE_ENV) to control behavior.
- Around line 60-73: Remove the unused "# noqa: PLC0415" suppressions from the
import lines that bring in SurrealDBClient, EmbeddingCache, EmbeddingProvider,
EmbeddingService, MemoryService, ReflectionService, SearchService, and
TaskService in server.py; edit each import statement to delete the trailing "#
noqa: PLC0415" so the imports remain unchanged but the unused linter-directive
is removed, then run the linter to confirm no PLC0415 warnings remain.
In `@src/codeagent/mcp/services/memory_service.py`:
- Around line 46-48: The call to self._db.create("memory", data) in store() can
return an empty list and then result[0] will raise IndexError; mirror the guard
used in TaskService.create_task by checking for an empty list before indexing.
After awaiting self._db.create(...), replace the current isinstance(result,
list) block with: if isinstance(result, list): if not result: return None (or
set result = None) else: result = result[0]; keep the rest of store() unchanged
and ensure callers can handle a None return.
- Line 72: MemoryService.read() returns a raw string "NOT_FOUND" instead of
using the shared enum, causing inconsistent error shapes with TaskService;
import and use ErrorCode.NOT_FOUND in MemoryService.read() (replace the literal
"NOT_FOUND" return with ErrorCode.NOT_FOUND) and ensure the ErrorCode import is
added at the top so the returned object becomes {"error": "Memory not found",
"code": ErrorCode.NOT_FOUND}.
In `@src/codeagent/mcp/services/reflection_service.py`:
- Line 29: Remove the unused `noqa` directives from this module: delete `# noqa:
PLR0913` on the `reflect` coroutine definition and delete the `# noqa: PLR0915`
comment on the other function in this file that currently has it (search for the
`# noqa: PLR0915` token). After removal, run ruff/linters to confirm no
remaining unused `noqa` comments and only add back specific `noqa` tokens if a
future lint rule is truly being suppressed for a known, justified reason.
In `@src/codeagent/mcp/services/search_service.py`:
- Line 31: Remove the unused noqa directive on the async def search function
signature: locate the "async def search" definition and delete the trailing " #
noqa: C901, PLR0912, PLR0913, PLR0915" (or replace it with a minimal noqa that
corresponds to any actually triggered rule if one exists); ensure no other noqa
comments remain on that function so linters (Ruff) no longer report RUF100.
In `@src/codeagent/mcp/tools/memory.py`:
- Line 42: Remove the unused noqa suppressions: delete the "noqa: PLW0603" on
the global declaration for _memory_service and _search_service and delete the
"noqa: PLR0913" tokens found on the subsequent function definitions (the three
occurrences reported around lines 47, 96, 160) so that only meaningful lint
suppressions remain; locate the occurrences by searching for the "noqa: PLW0603"
and "noqa: PLR0913" annotations in src/codeagent/mcp/tools/memory.py and remove
those tokens (leave surrounding code and signatures unchanged).
- Around line 186-197: The update() handler currently builds MemoryUpdate and
calls _memory_service.update inside one try, so any ValidationError from
MemoryUpdate gets misclassified as ErrorCode.DB_ERROR; split it to mirror
store(): wrap construction of MemoryUpdate in its own try/except that catches
ValidationError (from pydantic) and return an ErrorResponse with the
validation/invalid-input error code, then separately call await
_memory_service.update(upd) inside a second try/except that catches general
Exception and returns ErrorResponse(error=str(e), code=ErrorCode.DB_ERROR).
Reference MemoryUpdate, ValidationError, _memory_service.update, ErrorResponse,
and ErrorCode.DB_ERROR when making the changes.
In `@src/codeagent/mcp/tools/task.py`:
- Around line 36-40: Remove the unused noqa directives by deleting the "noqa:
PLW0603" on the line with the global _task_service declaration and removing
"noqa: PLR0913" from the create_task function definition; leave the global
_task_service assignment and the create_task signature intact so linting
warnings are resolved without altering functionality.
In `@tests/mcp/test_embedding_service.py`:
- Line 13: Replace every decorator occurrence of `@pytest.mark.asyncio`() with the
bare form `@pytest.mark.asyncio` across the async test functions in this module;
locate each instance of the symbol "@pytest.mark.asyncio()" (there are 9
occurrences flagged) and remove the trailing parentheses so the decorator is
used without calling it.
In `@tests/mcp/test_memory_service.py`:
- Line 49: Replace all usages of the decorator '@pytest.mark.asyncio()' with
'@pytest.mark.asyncio' in this file (there are 24 occurrences); search for the
exact token '@pytest.mark.asyncio()' and remove the parentheses so each async
test decorator is '@pytest.mark.asyncio' (no other code changes required).
In `@tests/mcp/test_memory_tools.py`:
- Line 33: Replace all occurrences of the decorator using parentheses — change
every instance of `@pytest.mark.asyncio`() to `@pytest.mark.asyncio` in
tests/mcp/test_memory_tools.py so the async test functions (those decorated with
`@pytest.mark.asyncio`()) use the correct decorator form; update all 17 flagged
places to remove the trailing () to satisfy Ruff PT023 and keep the decorator
applied to the same test coroutine functions.
- Around line 18-27: The test test_init_memory_tools_sets_services mutates
module globals and must restore them; update the test signature to accept the
monkeypatch fixture, capture originals via orig_mem = getattr(mem_mod,
"_memory_service", None) and orig_search = getattr(mem_mod, "_search_service",
None), call mem_mod.init_memory_tools(mock_mem, mock_search) and run the
assertions, then use monkeypatch.setattr(mem_mod, "_memory_service", orig_mem,
raising=False) and monkeypatch.setattr(mem_mod, "_search_service", orig_search,
raising=False) so the original _memory_service and _search_service values are
restored automatically at teardown; reference symbols:
test_init_memory_tools_sets_services, mem_mod, init_memory_tools,
_memory_service, _search_service, monkeypatch.
In `@tests/mcp/test_memory.py`:
- Around line 14-23: The parametrize decorator should pass test parameter names
as a tuple rather than a comma-separated string; update the
pytest.mark.parametrize call that targets ("attr, expected_value") to use a
tuple like ("attr", "expected_value") so the decorator in
tests/mcp/test_memory.py (the parametrized test function using attr and
expected_value) receives a proper tuple of parameter names.
In `@tests/mcp/test_reflection_service.py`:
- Line 26: Multiple test functions use the decorated form `@pytest.mark.asyncio`()
which triggers Ruff PT023; remove the parentheses and replace every occurrence
with the bare decorator `@pytest.mark.asyncio` across this file (and other test
files flagged), locating each instance where the decorator is applied to async
test functions (search for the symbol "@pytest.mark.asyncio()") and change it to
"@pytest.mark.asyncio".
In `@tests/mcp/test_reflection_tools.py`:
- Line 35: Several test functions use the decorator "@pytest.mark.asyncio()"
which triggers Ruff PT023; remove the parentheses so the decorator is just
"@pytest.mark.asyncio". Search for all occurrences of the decorator in
tests/mcp/test_reflection_tools.py (and other test files if present) and replace
"@pytest.mark.asyncio()" with "@pytest.mark.asyncio" on each test function
definition.
In `@tests/mcp/test_schema.py`:
- Line 18: The test fixture decorator currently uses parentheses as
`@pytest.fixture()` which triggers Ruff PT001; change the decorator to use the
bare form `@pytest.fixture` (remove the parentheses) where the fixture is
declared in tests/mcp/test_schema.py so the function decorated by pytest.fixture
uses the correct syntax.
In `@tests/mcp/test_search_service.py`:
- Line 26: The tests use the decorator form "@pytest.mark.asyncio()" with empty
parentheses which Ruff flags; change all occurrences of "@pytest.mark.asyncio()"
to the decorator without parens "@pytest.mark.asyncio" in
tests/mcp/test_search_service.py (replace each instance at the ten locations
noted) so the async test methods use the recommended decorator form.
- Around line 10-20: The _make_service helper currently types its return as
tuple[object, AsyncMock, AsyncMock], losing the concrete SearchService type;
change the return annotation to tuple[SearchService, AsyncMock, AsyncMock] and
ensure SearchService is visible to the annotation (either import SearchService
at module scope or wrap the import in a TYPE_CHECKING guard or use a string
forward reference "SearchService"); update the function signature and keep the
existing local import/use of SearchService so callers receive proper type
checking and autocompletion for the service variable.
In `@tests/mcp/test_task_service.py`:
- Line 36: The test decorators use the callable form `@pytest.mark.asyncio()`
which triggers Ruff PT023; replace all occurrences in this file by removing the
parentheses and using the decorator `@pytest.mark.asyncio` instead. Search for
any async test functions annotated with `@pytest.mark.asyncio()` in this file
(e.g., on functions referenced in this diff) and update each decorator to the
non-callable form to satisfy the linter.
In `@tests/mcp/test_task_tools.py`:
- Line 31: Replace all uses of the pytest async marker that include parentheses
(e.g. `@pytest.mark.asyncio`()) with the correct form `@pytest.mark.asyncio` across
this test file; search for occurrences of the decorator in
tests/mcp/test_task_tools.py (there are 12 flagged) and remove the trailing ()
so each async test function uses `@pytest.mark.asyncio` without parentheses.
In `@tests/test_embeddings.py`:
- Line 82: There are six occurrences of the pytest asyncio decorator using
parentheses; replace each `@pytest.mark.asyncio()` with `@pytest.mark.asyncio`
(remove the parentheses) in tests/test_embeddings.py so the decorator conforms
to Ruff PT023; make this change for all six occurrences and run the test/linters
to verify.
- Around line 48-61: Add the detect-secrets allowlist pragma to the fake API key
string literals used in the tests to suppress false positives: update the two
occurrences in test_init_with_explicit_api_key and
test_init_reads_api_key_from_env (the "sk-test-key" and "sk-env-key" literals in
tests/test_embeddings.py) by appending the comment "# pragma: allowlist secret"
to each string literal so the pre-commit secret detector ignores these test-only
keys while leaving the EmbeddingProvider initialization logic unchanged.
| # Path-Specific Instructions | ||
| # ============================================ | ||
| # Custom review focus per file pattern | ||
| # Uncomment and customize for your project |
There was a problem hiding this comment.
Clarify the comment - the examples below are already active.
The comment suggests users should "uncomment" the configuration, but the path_instructions below (lines 52-77) are already active and will be applied to matching files. This could mislead users into thinking these are inactive examples.
Consider revising to reflect the actual state:
📝 Suggested comment revisions
Option 1 - If these should remain active defaults:
- # Uncomment and customize for your project
+ # Customize these active rules for your projectOption 2 - If these should be examples to uncomment:
# Uncomment and customize for your project
path_instructions:
- - path: "**/*.py"
- instructions: |
- - Enforce type hints on all function signatures
+ # - path: "**/*.py"
+ # instructions: |
+ # - Enforce type hints on all function signatures📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| # Uncomment and customize for your project | |
| # Customize these active rules for your project |
🤖 Prompt for AI Agents
In @.coderabbit.yaml at line 51, Update the misleading comment line that says
"Uncomment and customize for your project" to clearly state the actual state of
the following configuration: either indicate that the path_instructions block is
active by default (referencing the path_instructions key) or change it to a true
example by commenting out or removing the active path_instructions entries;
specifically edit the comment immediately above path_instructions to reflect
Option 1 (active defaults) or Option 2 (examples to uncomment) so users aren’t
misled about whether path_instructions will be applied.
| - name: Install uv | ||
| uses: astral-sh/setup-uv@v4 |
There was a problem hiding this comment.
Inconsistent setup-uv version: v4 here vs v5 in the lint job (Line 35).
This looks like a copy-paste oversight. Pin both jobs to the same version for consistency.
Proposed fix
- name: Install uv
- uses: astral-sh/setup-uv@v4
+ uses: astral-sh/setup-uv@v5📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| - name: Install uv | |
| uses: astral-sh/setup-uv@v4 | |
| - name: Install uv | |
| uses: astral-sh/setup-uv@v5 |
🤖 Prompt for AI Agents
In @.github/workflows/check.yml around lines 59 - 60, The workflow has an
inconsistent action pin: the step named "Install uv" uses astral-sh/setup-uv@v4
while the lint job uses astral-sh/setup-uv@v5; update the "Install uv" step to
use the same version (astral-sh/setup-uv@v5) so both jobs are pinned
consistently to v5.
| - name: Run tests with coverage | ||
| run: | | ||
| uv run pytest tests/ \ | ||
| --cov=src \ | ||
| --cov-branch \ | ||
| --cov-report=term-missing \ | ||
| --cov-report=xml \ | ||
| --cov-fail-under=85 |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Coverage XML is generated but never uploaded.
The --cov-report=xml output isn't uploaded as an artifact or sent to a coverage service. If you plan to use Codecov or similar, add an upload step; otherwise, remove the XML report to keep the config clean.
🤖 Prompt for AI Agents
In @.github/workflows/check.yml around lines 65 - 72, The CI step named "Run
tests with coverage" currently generates an XML coverage report via the
--cov-report=xml flag but never uploads or publishes it; either remove the
--cov-report=xml option from the pytest command in that step or add a follow-up
step (e.g., an "Upload coverage XML" artifact step or a Codecov upload step) to
upload the generated coverage xml so it's consumed by downstream tools; update
the workflow to match your intent (remove the flag if unused, or add an
actions/upload-artifact or codecov action after the pytest step) and ensure the
pytest step and any new upload step reference the same XML filename produced by
pytest.
| htmlcov/ | ||
|
|
||
| # uv lock (generated) | ||
| uv.lock |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check project configuration in pyproject.toml
echo "=== Checking pyproject.toml for project type ==="
rg -n 'name.*=.*"codeagent"' pyproject.toml
echo ""
rg -n '\[project\]|\[tool\.poetry\]' pyproject.toml | head -10
echo ""
echo "=== Full pyproject.toml (first 50 lines) ==="
head -50 pyproject.tomlRepository: Questi0nM4rk/codeagent
Length of output: 1403
🏁 Script executed:
#!/bin/bash
echo "=== .gitignore content (lines 8-15) ==="
sed -n '8,15p' .gitignore
echo ""
echo "=== Checking if uv.lock exists ==="
ls -la uv.lock 2>&1 || echo "uv.lock does not exist"Repository: Questi0nM4rk/codeagent
Length of output: 267
Consider committing uv.lock to ensure reproducible builds.
This is an application project (confirmed by the CLI and MCP server entry points in pyproject.toml), and lock files should generally be committed for applications to ensure reproducible builds and consistent dependency versions across development, CI, and production environments. Ignoring uv.lock could lead to version drift and non-reproducible builds.
🤖 Prompt for AI Agents
In @.gitignore at line 11, The project is ignoring the dependency lockfile
"uv.lock", which prevents committing a reproducible lock for this application;
remove "uv.lock" from the .gitignore entry so the lockfile can be tracked, add
and commit the generated uv.lock to the repository, and ensure CI and developer
workflows use that committed uv.lock to pin dependency versions (look for the
"uv.lock" line in .gitignore and delete it, then git add/commit the resulting
uv.lock file).
| - repo: local | ||
| hooks: | ||
| - id: format-and-stage | ||
| name: format and stage | ||
| entry: lib/hooks/format-and-stage.sh | ||
| language: script | ||
| always_run: true | ||
| pass_filenames: false |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check if the format-and-stage script exists and is executable
fd -t f 'format-and-stage.sh' --exec ls -la {}
echo "---"
# Also check the exact expected path
if [ -f "lib/hooks/format-and-stage.sh" ]; then
echo "FOUND: lib/hooks/format-and-stage.sh"
head -10 "lib/hooks/format-and-stage.sh"
else
echo "MISSING: lib/hooks/format-and-stage.sh"
fiRepository: Questi0nM4rk/codeagent
Length of output: 108
🏁 Script executed:
#!/bin/bash
# Check what exists in lib directory
echo "=== Checking lib directory ==="
if [ -d "lib" ]; then
ls -la lib/
echo ""
echo "=== Checking for hooks subdirectory ==="
if [ -d "lib/hooks" ]; then
ls -la lib/hooks/
else
echo "lib/hooks directory does not exist"
fi
else
echo "lib directory does not exist"
fi
echo ""
echo "=== Looking for any hook-related files ==="
fd -t f 'hook' --max-results 10Repository: Questi0nM4rk/codeagent
Length of output: 169
Remove or provide the missing lib/hooks/format-and-stage.sh script.
The hook configuration references lib/hooks/format-and-stage.sh (line 17), but neither the lib directory nor the script exist in the repository. With always_run: true, this will cause every pre-commit invocation to fail immediately.
🤖 Prompt for AI Agents
In @.pre-commit-config.yaml around lines 14 - 21, The pre-commit hook entry
"lib/hooks/format-and-stage.sh" referenced by the hook id "format-and-stage"
does not exist; either add the missing executable script at
lib/hooks/format-and-stage.sh (make it executable and implement the formatting +
staging logic expected by the hook) or remove/replace the hook entry in
.pre-commit-config.yaml (update the "entry" to an existing script or delete the
hook block) so that pre-commit no longer fails on every run.
| class TestSearchServiceSearch: | ||
| """Tests for SearchService.search() method.""" | ||
|
|
||
| @pytest.mark.asyncio() |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Ruff PT023: use @pytest.mark.asyncio without parentheses.
All 10 test methods use @pytest.mark.asyncio() with empty parens. Ruff recommends dropping them. Applies to lines 26, 37, 63, 78, 93, 110, 123, 136, 165, 191.
🧰 Tools
🪛 Ruff (0.14.14)
[warning] 26-26: Use @pytest.mark.asyncio over @pytest.mark.asyncio()
Remove parentheses
(PT023)
🤖 Prompt for AI Agents
In `@tests/mcp/test_search_service.py` at line 26, The tests use the decorator
form "@pytest.mark.asyncio()" with empty parentheses which Ruff flags; change
all occurrences of "@pytest.mark.asyncio()" to the decorator without parens
"@pytest.mark.asyncio" in tests/mcp/test_search_service.py (replace each
instance at the ten locations noted) so the async test methods use the
recommended decorator form.
| class TestTaskServiceCreateTask: | ||
| """Tests for TaskService.create_task() method.""" | ||
|
|
||
| @pytest.mark.asyncio() |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Remove parentheses from @pytest.mark.asyncio() across all async tests.
Ruff PT023 flags all 18 occurrences in this file. Use @pytest.mark.asyncio without parentheses.
🧰 Tools
🪛 Ruff (0.14.14)
[warning] 36-36: Use @pytest.mark.asyncio over @pytest.mark.asyncio()
Remove parentheses
(PT023)
🤖 Prompt for AI Agents
In `@tests/mcp/test_task_service.py` at line 36, The test decorators use the
callable form `@pytest.mark.asyncio()` which triggers Ruff PT023; replace all
occurrences in this file by removing the parentheses and using the decorator
`@pytest.mark.asyncio` instead. Search for any async test functions annotated
with `@pytest.mark.asyncio()` in this file (e.g., on functions referenced in
this diff) and update each decorator to the non-callable form to satisfy the
linter.
| class TestCreateTask: | ||
| """Tests for the create_task() tool function.""" | ||
|
|
||
| @pytest.mark.asyncio() |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Remove parentheses from @pytest.mark.asyncio() across all async tests.
Ruff PT023 flags all 12 occurrences in this file. Use @pytest.mark.asyncio without parentheses.
🧰 Tools
🪛 Ruff (0.14.14)
[warning] 31-31: Use @pytest.mark.asyncio over @pytest.mark.asyncio()
Remove parentheses
(PT023)
🤖 Prompt for AI Agents
In `@tests/mcp/test_task_tools.py` at line 31, Replace all uses of the pytest
async marker that include parentheses (e.g. `@pytest.mark.asyncio`()) with the
correct form `@pytest.mark.asyncio` across this test file; search for occurrences
of the decorator in tests/mcp/test_task_tools.py (there are 12 flagged) and
remove the trailing () so each async test function uses `@pytest.mark.asyncio`
without parentheses.
| def test_init_with_explicit_api_key(self) -> None: | ||
| """EmbeddingProvider accepts an explicit API key.""" | ||
| from codeagent.mcp.embeddings.provider import EmbeddingProvider | ||
|
|
||
| provider = EmbeddingProvider(api_key="sk-test-key") | ||
| assert provider._api_key == "sk-test-key" | ||
|
|
||
| def test_init_reads_api_key_from_env(self, monkeypatch: pytest.MonkeyPatch) -> None: | ||
| """EmbeddingProvider reads OPENAI_API_KEY from environment when no key given.""" | ||
| from codeagent.mcp.embeddings.provider import EmbeddingProvider | ||
|
|
||
| monkeypatch.setenv("OPENAI_API_KEY", "sk-env-key") | ||
| provider = EmbeddingProvider() | ||
| assert provider._api_key == "sk-env-key" |
There was a problem hiding this comment.
CI failure: detect-secrets flags fake API key strings.
The pipeline reports secret detection errors on lines 53 and 61. These are clearly test-only fake keys, but the pre-commit hook still blocks. Add # pragma: allowlist secret to suppress:
🔧 Proposed fix
def test_init_with_explicit_api_key(self) -> None:
"""EmbeddingProvider accepts an explicit API key."""
from codeagent.mcp.embeddings.provider import EmbeddingProvider
- provider = EmbeddingProvider(api_key="sk-test-key")
- assert provider._api_key == "sk-test-key"
+ provider = EmbeddingProvider(api_key="sk-test-key") # pragma: allowlist secret
+ assert provider._api_key == "sk-test-key" # pragma: allowlist secret
def test_init_reads_api_key_from_env(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""EmbeddingProvider reads OPENAI_API_KEY from environment when no key given."""
from codeagent.mcp.embeddings.provider import EmbeddingProvider
- monkeypatch.setenv("OPENAI_API_KEY", "sk-env-key")
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-env-key") # pragma: allowlist secret
provider = EmbeddingProvider()
- assert provider._api_key == "sk-env-key"
+ assert provider._api_key == "sk-env-key" # pragma: allowlist secret🧰 Tools
🪛 GitHub Actions: Check
[error] 53-53: detect-secrets: Potential secrets about to be committed to git repo! Secret Type: Secret Keyword at line 53. Consider adding pragma: allowlist secret or remove the secret.
[error] 61-61: detect-secrets: Potential secrets about to be committed to git repo! Secret Type: Secret Keyword at line 61. Consider adding pragma: allowlist secret or remove the secret.
🤖 Prompt for AI Agents
In `@tests/test_embeddings.py` around lines 48 - 61, Add the detect-secrets
allowlist pragma to the fake API key string literals used in the tests to
suppress false positives: update the two occurrences in
test_init_with_explicit_api_key and test_init_reads_api_key_from_env (the
"sk-test-key" and "sk-env-key" literals in tests/test_embeddings.py) by
appending the comment "# pragma: allowlist secret" to each string literal so the
pre-commit secret detector ignores these test-only keys while leaving the
EmbeddingProvider initialization logic unchanged.
| class TestEmbeddingProviderEmbed: | ||
| """Tests for EmbeddingProvider.embed() single-text embedding.""" | ||
|
|
||
| @pytest.mark.asyncio() |
There was a problem hiding this comment.
Ruff PT023: Remove parentheses from @pytest.mark.asyncio().
Ruff flags all 6 occurrences (lines 82, 101, 131, 161, 189, 214). Use @pytest.mark.asyncio without parentheses.
🔧 Proposed fix (apply to all 6 locations)
- `@pytest.mark.asyncio`()
+ `@pytest.mark.asyncio`Apply at lines 82, 101, 131, 161, 189, and 214.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| @pytest.mark.asyncio() | |
| `@pytest.mark.asyncio` |
🧰 Tools
🪛 Ruff (0.14.14)
[warning] 82-82: Use @pytest.mark.asyncio over @pytest.mark.asyncio()
Remove parentheses
(PT023)
🤖 Prompt for AI Agents
In `@tests/test_embeddings.py` at line 82, There are six occurrences of the pytest
asyncio decorator using parentheses; replace each `@pytest.mark.asyncio()` with
`@pytest.mark.asyncio` (remove the parentheses) in tests/test_embeddings.py so
the decorator conforms to Ruff PT023; make this change for all six occurrences
and run the test/linters to verify.
| ## Architecture | ||
|
|
||
| ``` | ||
| codeagent/src/codeagent/mcp/ |
There was a problem hiding this comment.
Architecture path prefix looks incorrect.
The path shows codeagent/src/codeagent/mcp/ but based on the actual repo structure (e.g., src/codeagent/mcp/services/reflection_service.py), this should be src/codeagent/mcp/.
Suggested fix
-codeagent/src/codeagent/mcp/
+src/codeagent/mcp/📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| codeagent/src/codeagent/mcp/ | |
| src/codeagent/mcp/ |
🤖 Prompt for AI Agents
In `@docs/ideas/unified-memory-system.md` at line 48, Update the incorrect
architecture path string in docs/ideas/unified-memory-system.md: replace the
path literal "codeagent/src/codeagent/mcp/" with the correct repository path
"src/codeagent/mcp/" so references (e.g., to files like
src/codeagent/mcp/services/reflection_service.py) match the actual repo layout.
|
|
||
| ## Open Questions | ||
|
|
||
| - Should `decision` type memories be auto-created from `/plan` output? |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Minor grammar: use a hyphen to form the compound modifier.
decision type → decision-type.
-- Should `decision` type memories be auto-created from `/plan` output?
+- Should `decision-type` memories be auto-created from `/plan` output?📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| - Should `decision` type memories be auto-created from `/plan` output? | |
| - Should `decision-type` memories be auto-created from `/plan` output? |
🧰 Tools
🪛 LanguageTool
[grammar] ~96-~96: Use a hyphen to join words.
Context: ... ## Open Questions - Should decision type memories be auto-created from `/pla...
(QB_NEW_EN_HYPHEN)
🤖 Prompt for AI Agents
In `@docs/ideas/unified-memory-system.md` at line 96, Change the phrasing that
currently reads "Should `decision` type memories be auto-created from `/plan`
output?" to use a hyphenated compound modifier: "Should `decision-type` memories
be auto-created from `/plan` output?"—update the instance referencing "decision
type" to "decision-type" to correct the grammar.
| def test_init_memory_tools_sets_services(self) -> None: | ||
| """init_memory_tools should set the module-level service globals.""" | ||
| from codeagent.mcp.tools import memory as mem_mod | ||
|
|
||
| mock_mem = object() | ||
| mock_search = object() | ||
| mem_mod.init_memory_tools(mock_mem, mock_search) | ||
|
|
||
| assert mem_mod._memory_service is mock_mem | ||
| assert mem_mod._search_service is mock_search |
There was a problem hiding this comment.
test_init_memory_tools_sets_services leaks module-level state.
Same pattern as test_task_tools.py — this test permanently sets mem_mod._memory_service and mem_mod._search_service without restoring them. Use monkeypatch to restore after assertion.
Proposed fix
- def test_init_memory_tools_sets_services(self) -> None:
+ def test_init_memory_tools_sets_services(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""init_memory_tools should set the module-level service globals."""
from codeagent.mcp.tools import memory as mem_mod
+ orig_mem = mem_mod._memory_service
+ orig_search = mem_mod._search_service
mock_mem = object()
mock_search = object()
mem_mod.init_memory_tools(mock_mem, mock_search)
assert mem_mod._memory_service is mock_mem
assert mem_mod._search_service is mock_search
+ monkeypatch.setattr(mem_mod, "_memory_service", orig_mem)
+ monkeypatch.setattr(mem_mod, "_search_service", orig_search)As per coding guidelines, "Avoid shared state between tests in Python test files".
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| def test_init_memory_tools_sets_services(self) -> None: | |
| """init_memory_tools should set the module-level service globals.""" | |
| from codeagent.mcp.tools import memory as mem_mod | |
| mock_mem = object() | |
| mock_search = object() | |
| mem_mod.init_memory_tools(mock_mem, mock_search) | |
| assert mem_mod._memory_service is mock_mem | |
| assert mem_mod._search_service is mock_search | |
| def test_init_memory_tools_sets_services(self, monkeypatch: pytest.MonkeyPatch) -> None: | |
| """init_memory_tools should set the module-level service globals.""" | |
| from codeagent.mcp.tools import memory as mem_mod | |
| orig_mem = mem_mod._memory_service | |
| orig_search = mem_mod._search_service | |
| mock_mem = object() | |
| mock_search = object() | |
| mem_mod.init_memory_tools(mock_mem, mock_search) | |
| assert mem_mod._memory_service is mock_mem | |
| assert mem_mod._search_service is mock_search | |
| monkeypatch.setattr(mem_mod, "_memory_service", orig_mem) | |
| monkeypatch.setattr(mem_mod, "_search_service", orig_search) |
🤖 Prompt for AI Agents
In `@tests/mcp/test_memory_tools.py` around lines 18 - 27, The test
test_init_memory_tools_sets_services mutates module globals and must restore
them; update the test signature to accept the monkeypatch fixture, capture
originals via orig_mem = getattr(mem_mod, "_memory_service", None) and
orig_search = getattr(mem_mod, "_search_service", None), call
mem_mod.init_memory_tools(mock_mem, mock_search) and run the assertions, then
use monkeypatch.setattr(mem_mod, "_memory_service", orig_mem, raising=False) and
monkeypatch.setattr(mem_mod, "_search_service", orig_search, raising=False) so
the original _memory_service and _search_service values are restored
automatically at teardown; reference symbols:
test_init_memory_tools_sets_services, mem_mod, init_memory_tools,
_memory_service, _search_service, monkeypatch.
| class TestReflect: | ||
| """Tests for ReflectionService.reflect() method.""" | ||
|
|
||
| @pytest.mark.asyncio() |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Remove parentheses from @pytest.mark.asyncio() across the file.
Ruff PT023 flags all 16 occurrences. Use the bare decorator form @pytest.mark.asyncio instead.
Example fix (apply to all occurrences)
- `@pytest.mark.asyncio`()
+ `@pytest.mark.asyncio`📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| @pytest.mark.asyncio() | |
| `@pytest.mark.asyncio` |
🧰 Tools
🪛 Ruff (0.14.14)
[warning] 26-26: Use @pytest.mark.asyncio over @pytest.mark.asyncio()
Remove parentheses
(PT023)
🤖 Prompt for AI Agents
In `@tests/mcp/test_reflection_service.py` at line 26, Multiple test functions use
the decorated form `@pytest.mark.asyncio`() which triggers Ruff PT023; remove the
parentheses and replace every occurrence with the bare decorator
`@pytest.mark.asyncio` across this file (and other test files flagged), locating
each instance where the decorator is applied to async test functions (search for
the symbol "@pytest.mark.asyncio()") and change it to "@pytest.mark.asyncio".
| class TestReflect: | ||
| """Tests for the reflect() tool function.""" | ||
|
|
||
| @pytest.mark.asyncio() |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Remove parentheses from @pytest.mark.asyncio() across the file.
Same Ruff PT023 issue as in the service tests — all 8 occurrences should use @pytest.mark.asyncio without parentheses.
🧰 Tools
🪛 Ruff (0.14.14)
[warning] 35-35: Use @pytest.mark.asyncio over @pytest.mark.asyncio()
Remove parentheses
(PT023)
🤖 Prompt for AI Agents
In `@tests/mcp/test_reflection_tools.py` at line 35, Several test functions use
the decorator "@pytest.mark.asyncio()" which triggers Ruff PT023; remove the
parentheses so the decorator is just "@pytest.mark.asyncio". Search for all
occurrences of the decorator in tests/mcp/test_reflection_tools.py (and other
test files if present) and replace "@pytest.mark.asyncio()" with
"@pytest.mark.asyncio" on each test function definition.
…ndit, gitleaks, vulture, pip-audit, codespell, taplo Complete coverage of all tools in the ai-guardrails pre-commit pipeline. Each skill captures the tool's config, common errors, suppression syntax, and commands. These persist across context compactions. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 5
🤖 Fix all issues with AI agents
In `@framework/skills/bandit/SKILL.md`:
- Line 8: The sentence "Complementary to semgrep - focuses on Python idioms."
has awkward punctuation; replace the hyphen with an em dash and make it a
complete clause (for example: "Complementary to Semgrep — focused on Python
idioms." or "Complementary to Semgrep — it focuses on Python idioms.") so the
grammar and formatting are tightened; update the SKILL.md sentence accordingly
and capitalize "Semgrep" for consistency.
- Line 12: The parenthetical claim "(excludes tests)" is incorrect for the
command `bandit -ll -ii -r`; update SKILL.md by either removing that
parenthetical or changing the command to actually exclude tests (e.g., replace
with `bandit -ll -ii -r -x tests` or add a note that exclusion requires `-x` or
a Bandit config file), and make the wording explicit so readers know the correct
way to exclude test directories.
In `@framework/skills/gitleaks/SKILL.md`:
- Around line 38-41: Polish the remediation bullets in SKILL.md for consistent
imperative phrasing and clearer wording: change Step 2 to a full sentence like
"Move the secret to an environment variable or a secrets manager." and rewrite
Step 3 to read "Reference the secret via os.environ['KEY_NAME'] or from a
gitignored .env file." Ensure Steps 2 and 3 match the imperative style of Steps
1 and 4 and preserve the example code formatting for os.environ["KEY_NAME"].
In `@framework/skills/semgrep/SKILL.md`:
- Around line 1-62: The table separator under the "Common Findings" section uses
inconsistent dash counts ("| ------- | --- |"); update that separator row to use
equal-length dashes to match the header ("| Finding | Fix |") — e.g., replace "|
------- | --- |" with a consistent separator like "| -------- | ---- |" so the
markdown table renders and looks consistent; locate the header "| Finding | Fix
|" and the following separator row to make the change.
In `@framework/skills/taplo/SKILL.md`:
- Line 26: Update the workaround sentence in SKILL.md to use clearer wording:
replace the phrase “gitignore all untracked files before committing” (the
Workaround line) with “add untracked files to .gitignore before committing” so
it reads as an instruction to add files to the .gitignore file; ensure
punctuation and capitalization match the surrounding text and run a quick
spell/grammar check.
|
|
||
| # Bandit Skill | ||
|
|
||
| Python-specific security linter. Complementary to semgrep - focuses on Python idioms. |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Tighten grammar/formatting.
“Complementary to semgrep - focuses on Python idioms.” reads awkwardly; use an em dash.
✍️ Suggested wording
-Python-specific security linter. Complementary to semgrep - focuses on Python idioms.
+Python-specific security linter. Complementary to semgrep — focuses on Python idioms.🤖 Prompt for AI Agents
In `@framework/skills/bandit/SKILL.md` at line 8, The sentence "Complementary to
semgrep - focuses on Python idioms." has awkward punctuation; replace the hyphen
with an em dash and make it a complete clause (for example: "Complementary to
Semgrep — focused on Python idioms." or "Complementary to Semgrep — it focuses
on Python idioms.") so the grammar and formatting are tightened; update the
SKILL.md sentence accordingly and capitalize "Semgrep" for consistency.
|
|
||
| ## How It Runs | ||
|
|
||
| Pre-commit hook: `bandit -ll -ii -r` (excludes tests). |
There was a problem hiding this comment.
Fix or clarify the “excludes tests” claim.
bandit -ll -ii -r does not exclude tests on its own; that requires -x or config. Either update the command or remove the parenthetical.
🔧 Suggested doc tweak
-Pre-commit hook: `bandit -ll -ii -r` (excludes tests).
+Pre-commit hook: `bandit -ll -ii -r` (use `-x tests/` or config to exclude tests).📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| Pre-commit hook: `bandit -ll -ii -r` (excludes tests). | |
| Pre-commit hook: `bandit -ll -ii -r` (use `-x tests/` or config to exclude tests). |
🤖 Prompt for AI Agents
In `@framework/skills/bandit/SKILL.md` at line 12, The parenthetical claim
"(excludes tests)" is incorrect for the command `bandit -ll -ii -r`; update
SKILL.md by either removing that parenthetical or changing the command to
actually exclude tests (e.g., replace with `bandit -ll -ii -r -x tests` or add a
note that exclusion requires `-x` or a Bandit config file), and make the wording
explicit so readers know the correct way to exclude test directories.
| 1. **Remove the secret from code immediately** | ||
| 2. Move to environment variable or secrets manager | ||
| 3. Reference via `os.environ["KEY_NAME"]` or `.env` file (gitignored) | ||
| 4. If already committed: rotate the secret (it's in git history) |
There was a problem hiding this comment.
Polish the remediation steps for grammar/clarity.
Step 2 is a fragment and Step 3 reads a bit terse. Suggest tightening both for consistency.
Proposed edit
-2. Move to environment variable or secrets manager
-3. Reference via `os.environ["KEY_NAME"]` or `.env` file (gitignored)
+2. Move it to an environment variable or a secrets manager
+3. Reference it via `os.environ["KEY_NAME"]` or a `.env` file (gitignored)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| 1. **Remove the secret from code immediately** | |
| 2. Move to environment variable or secrets manager | |
| 3. Reference via `os.environ["KEY_NAME"]` or `.env` file (gitignored) | |
| 4. If already committed: rotate the secret (it's in git history) | |
| 1. **Remove the secret from code immediately** | |
| 2. Move it to an environment variable or a secrets manager | |
| 3. Reference it via `os.environ["KEY_NAME"]` or a `.env` file (gitignored) | |
| 4. If already committed: rotate the secret (it's in git history) |
🤖 Prompt for AI Agents
In `@framework/skills/gitleaks/SKILL.md` around lines 38 - 41, Polish the
remediation bullets in SKILL.md for consistent imperative phrasing and clearer
wording: change Step 2 to a full sentence like "Move the secret to an
environment variable or a secrets manager." and rewrite Step 3 to read
"Reference the secret via os.environ['KEY_NAME'] or from a gitignored .env
file." Ensure Steps 2 and 3 match the imperative style of Steps 1 and 4 and
preserve the example code formatting for os.environ["KEY_NAME"].
| --- | ||
| name: semgrep | ||
| description: Semgrep SAST security scanner. Activates when dealing with security issues, vulnerability scanning, or CI security checks. | ||
| --- | ||
|
|
||
| # Semgrep Skill | ||
|
|
||
| Static Application Security Testing (SAST). Catches security vulnerabilities via pattern matching. | ||
|
|
||
| ## How It Runs | ||
|
|
||
| - **Pre-commit**: `semgrep --config auto --error --jobs 1` (excludes tests) | ||
| - **CI**: Separate step after pre-commit (runs in parallel with lint) | ||
| - **CI command**: `semgrep --config auto --error --exclude tests/` | ||
|
|
||
| `--config auto` uses Semgrep's curated ruleset (OWASP top 10, language-specific). | ||
|
|
||
| ## What It Catches | ||
|
|
||
| - SQL injection patterns | ||
| - XSS vulnerabilities | ||
| - Command injection | ||
| - Path traversal | ||
| - Hardcoded secrets/credentials | ||
| - Insecure deserialization | ||
| - SSRF patterns | ||
| - Dangerous function calls (`eval`, `exec`, `os.system`) | ||
|
|
||
| ## Common Findings | ||
|
|
||
| | Finding | Fix | | ||
| | ------- | --- | | ||
| | `python.lang.security.audit.exec-detected` | Don't use `exec()`. Refactor. | | ||
| | `python.lang.security.audit.eval-detected` | Don't use `eval()`. Use `ast.literal_eval()` if needed. | | ||
| | `python.lang.security.audit.subprocess-shell-true` | Use `subprocess.run(["cmd", "arg"])` not `shell=True` | | ||
| | `python.lang.security.deserialization.avoid-pickle` | Use JSON or msgpack instead | | ||
| | `generic.secrets.security.detected-generic-secret` | Move to env var or secrets manager | | ||
|
|
||
| ## Suppressing (very rare) | ||
|
|
||
| ```python | ||
| # nosemgrep: python.lang.security.audit.exec-detected | ||
| exec(trusted_code) # Reason: sandboxed execution in test harness | ||
| ``` | ||
|
|
||
| Requires explicit justification. Security suppressions are reviewed in PR. | ||
|
|
||
| ## Commands | ||
|
|
||
| ```bash | ||
| # Scan current directory | ||
| semgrep --config auto --error | ||
|
|
||
| # Scan specific path | ||
| semgrep --config auto --error src/ | ||
|
|
||
| # Exclude tests | ||
| semgrep --config auto --error --exclude tests/ | ||
|
|
||
| # Verbose (show rule IDs) | ||
| semgrep --config auto --error --verbose | ||
| ``` |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Excellent documentation!
This Semgrep skill documentation is clear, well-structured, and follows markdown best practices. The spelling, grammar, and formatting are all correct. The document effectively covers:
- Runtime contexts and command syntax
- Security patterns Semgrep detects
- Common findings with actionable fixes
- Suppression syntax with security review requirements
- Practical command examples
No links are present to verify, and the content is technically accurate.
Optional nitpick: The table separator on line 32 uses inconsistent dash counts (| ------- | --- |). While valid markdown, using equal-length separators (e.g., | ------- | --- | → | -------- | ---- |) would improve visual consistency.
As per coding guidelines: Check for spelling and grammar, verify links are valid, ensure consistent formatting (for **/*.md files).
🤖 Prompt for AI Agents
In `@framework/skills/semgrep/SKILL.md` around lines 1 - 62, The table separator
under the "Common Findings" section uses inconsistent dash counts ("| ------- |
--- |"); update that separator row to use equal-length dashes to match the
header ("| Finding | Fix |") — e.g., replace "| ------- | --- |" with a
consistent separator like "| -------- | ---- |" so the markdown table renders
and looks consistent; locate the header "| Finding | Fix |" and the following
separator row to make the change.
|
|
||
| ## Known Issue: Stash Conflict | ||
|
|
||
| Taplo reformats `pyproject.toml` (e.g., expanding inline arrays to multiline), which can conflict with the `format-and-stage` hook's stash mechanism when untracked files exist. **Workaround**: gitignore all untracked files before committing. |
There was a problem hiding this comment.
Clarify the workaround wording.
“gitignore all untracked files” reads as a verb; recommend “add untracked files to .gitignore” for clarity.
As per coding guidelines "Check for spelling and grammar".
🤖 Prompt for AI Agents
In `@framework/skills/taplo/SKILL.md` at line 26, Update the workaround sentence
in SKILL.md to use clearer wording: replace the phrase “gitignore all untracked
files before committing” (the Workaround line) with “add untracked files to
.gitignore before committing” so it reads as an instruction to add files to the
.gitignore file; ensure punctuation and capitalization match the surrounding
text and run a quick spell/grammar check.
Add `.suppression-allowlist` with approved inline suppression patterns (BLE001, PLR0913, PLC0415, PLW0603, type: ignore[override], SC2317, SC2329). Add `detect-suppression-comments` hook to pre-commit config so unapproved inline suppressions are blocked at commit time. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add `.guardrails-exceptions.toml` as the single source of truth for all lint/type/analysis exceptions. The `codeagent generate-configs` command reads this registry and produces ruff.toml, biome.json, .codespellrc, and .suppression-allowlist from base templates + project exceptions. Key components: - registry.py: Parse and validate the TOML registry - generators/: Per-tool config generators (ruff, biome, markdownlint, codespell, allowlist, pyright) - CLI command: `codeagent generate-configs [--dry-run]` - init_cmd.py: Scaffold registry on `codeagent init` - 24 tests covering registry parsing and all generators AI agents cannot modify the registry file. Only the project owner can add exceptions, each requiring a documented reason. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 12
🤖 Fix all issues with AI agents
In @.guardrails-exceptions.toml:
- Around line 58-61: Duplicate codespell skip lists exist: the keys
global.codespell.skip and skip.codespell contain identical values causing two
sources of truth; remove the duplication by consolidating the list into a single
canonical key (choose either global.codespell.skip or skip.codespell), update
any tooling/config that reads the other key to point to the chosen one (or add a
clear comment documenting which key is authoritative), and delete the redundant
section (ensure the identical array of paths/ignore_words from skip.codespell is
moved or referenced under the retained key).
In @.pre-commit-config.yaml:
- Line 11: The YAML value for the Node version is being parsed as a float and
losing the patch component; update the node entry (the "node" key value) to be a
string by surrounding the version with quotes (e.g., "20.11.0") or prefixing
with a pipe/explicit string style so YAML preserves the full version text;
ensure the node: value is changed from 20.11.0 to a quoted string to prevent
truncation.
In `@biome.json`:
- Around line 297-347: The overrides array contains a duplicate block and uses
the deprecated key "include" instead of "includes"; update the override that
currently has "include" to use "includes" (so both config override blocks use
"includes") and remove the duplicate override entry so only one config override
remains, ensuring the linter.rules.style.noDefaultExport setting is preserved
for the config/glob patterns referenced by the "*.config.*", "vite.config.*",
"vitest.config.*", "next.config.*", and "tailwind.config.*" includes.
In `@pyproject.toml`:
- Around line 30-35: The project currently depends on both "tomli-w" and
"tomlkit"; consolidate by removing "tomli-w" from pyproject.toml and update the
code that uses tomli-w (referenced in
src/codeagent/guardrails/generators/ruff.py where fresh TOML config is written)
to use tomlkit's writing API instead (the same library already used by
src/codeagent/guardrails/generators/pyright.py for round-trip edits), ensuring
the write logic preserves expected output format and updating any import names
and tests accordingly.
In `@src/codeagent/cli/init_cmd.py`:
- Around line 107-117: When force=True and an existing customized
.guardrails-exceptions.toml will be overwritten by _scaffold_exceptions_file,
add a visible warning before performing the overwrite: detect when
exceptions_path.exists() and force is True, emit a console.print or logger
warning that the existing file will be replaced, then proceed to call
_scaffold_exceptions_file(exceptions_path) and continue to run_generate_configs;
reference the variables and functions exceptions_path, force,
_scaffold_exceptions_file, and run_generate_configs in the change.
In `@src/codeagent/cli/main.py`:
- Around line 92-96: The CLI call to run_generate_configs can let exceptions
from ExceptionRegistry.load (e.g., ValueError for malformed TOML or missing
schema_version and FileNotFoundError for missing files) bubble up as raw
tracebacks; wrap the call to run_generate_configs(project_dir=project_dir,
dry_run=dry_run) in a try/except that catches FileNotFoundError and ValueError
(and an optional generic Exception fallback), print a clear, user-friendly error
message via typer.secho/typer.echo, and then exit with typer.Exit(code=1);
reference run_generate_configs in src/codeagent/cli/main.py and
ExceptionRegistry.load in src/codeagent/guardrails/generate.py to locate the
error sources.
In `@src/codeagent/guardrails/generate.py`:
- Around line 62-98: The generator calls (generate_ruff, generate_biome,
generate_markdownlint, generate_codespell, generate_allowlist, generate_pyright)
should be wrapped individually in try/except blocks so a failure in one doesn't
abort the whole run; catch exceptions, record failures (including exception text
and the target path or config name) into a list, continue with the next
generator, and after all attempts log a summary using console (e.g., which
generators succeeded and which failed with errors) so callers can see partial
results while still surfacing problems; reference registry and project_path as
needed when building the error context.
- Around line 47-54: ExceptionRegistry.load(registry_path) can raise ValueError
on malformed TOML; wrap the load call in a try/except that catches ValueError,
log a clear user-friendly error via console.print (including REGISTRY_FILENAME
and the exception message), and return False instead of allowing the traceback
to propagate; keep the subsequent registry.validate() logic as-is (refer to
ExceptionRegistry.load, registry.validate, REGISTRY_FILENAME, and
console.print).
- Around line 23-26: The function run_generate_configs currently accepts dry_run
as a positional boolean which can be ambiguous; update its signature to force
keyword-only arguments by inserting a positional-only marker (*) before dry_run
(i.e., change def run_generate_configs(project_dir: str = ".", *, dry_run: bool
= False) -> bool:), and ensure any internal references to dry_run remain
unchanged so callers must pass dry_run=... by name.
In `@src/codeagent/guardrails/generators/markdownlint.py`:
- Around line 24-26: _strip_jsonc_comments currently uses a fragile regex that
only removes full-line // comments and can corrupt JSONC with // inside string
values (e.g., URLs); update the function to use a proper JSONC/JSON5 parser (for
example replace the regex approach in _strip_jsonc_comments with loading via
pyjson5 or json5 and re-serializing) so comments are removed safely, or if you
must keep a regex approach, implement a parser-aware removal that skips //
occurrences inside string literals (but prefer using pyjson5/json5 to load and
then dump valid JSON).
In `@src/codeagent/guardrails/registry.py`:
- Around line 132-165: The validate() method currently uses a hardcoded
skip-list ("codespell", "pyright") when iterating self.global_rules; replace
this brittle approach by detecting structured rule values from the data itself:
in validate(), for each tool,rules in self.global_rules.items() check the type
of the rule values (e.g., inspect one or all rule values and if any value is not
a str treat the tool as structured) and only enforce non-empty-string reasons
when the reasons are strings; update the loop over self.global_rules in
validate() (and remove the hardcoded tuple) so the logic uses isinstance(reason,
str) to decide whether to validate and skips tools whose rule values are
non-string or structured.
In `@tests/guardrails/test_registry.py`:
- Around line 192-212: Add a test case that loads the registry via
ExceptionRegistry.load (use the existing full_toml fixture) and asserts that
reg.get_global_ignores("codespell") returns an empty list; this verifies
structured-value tools like codespell (which use skip/ignore_words lists or
dicts) do not produce string-based global ignore reasons. Place the new test
alongside the other TestRegistryHelpers methods (e.g., after
test_get_ruff_ignores) and follow the same pattern of creating reg =
ExceptionRegistry.load(full_toml) and asserting the empty result.
|
|
||
| [global.codespell] | ||
| skip = [".git", "*.lock", "*.baseline", "node_modules", "venv", ".venv"] | ||
| ignore_words = ["brin"] |
There was a problem hiding this comment.
Duplicate codespell skip lists.
global.codespell.skip (line 60) and skip.codespell (line 248) contain identical values. This creates two sources of truth for the same configuration. If the generators consume different sections for different purposes, document which section drives which output; otherwise, consolidate into a single location to avoid drift.
Also applies to: 246-248
🤖 Prompt for AI Agents
In @.guardrails-exceptions.toml around lines 58 - 61, Duplicate codespell skip
lists exist: the keys global.codespell.skip and skip.codespell contain identical
values causing two sources of truth; remove the duplication by consolidating the
list into a single canonical key (choose either global.codespell.skip or
skip.codespell), update any tooling/config that reads the other key to point to
the chosen one (or add a clear comment documenting which key is authoritative),
and delete the redundant section (ensure the identical array of
paths/ignore_words from skip.codespell is moved or referenced under the retained
key).
| default_language_version: | ||
| python: python3.12 | ||
| node: "20.11.0" | ||
| node: 20.11.0 |
There was a problem hiding this comment.
YAML will silently truncate 20.11.0 to 20.11.
Unquoted, YAML parses 20.11.0 as a float 20.11, losing the patch component. This will resolve to the wrong (or nonexistent) Node version.
🐛 Proposed fix
- node: 20.11.0
+ node: "20.11.0"📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| node: 20.11.0 | |
| node: "20.11.0" |
🤖 Prompt for AI Agents
In @.pre-commit-config.yaml at line 11, The YAML value for the Node version is
being parsed as a float and losing the patch component; update the node entry
(the "node" key value) to be a string by surrounding the version with quotes
(e.g., "20.11.0") or prefixing with a pipe/explicit string style so YAML
preserves the full version text; ensure the node: value is changed from 20.11.0
to a quoted string to prevent truncation.
| "overrides": [ | ||
| { | ||
| "include": [ | ||
| "**/tests/fixtures/**" | ||
| ], | ||
| "linter": { | ||
| "enabled": false | ||
| }, | ||
| "formatter": { | ||
| "enabled": false | ||
| } | ||
| }, | ||
| { | ||
| "include": [ | ||
| "*.config.ts", | ||
| "*.config.js", | ||
| "*.config.mjs", | ||
| "*.config.cjs", | ||
| "vite.config.*", | ||
| "vitest.config.*", | ||
| "next.config.*", | ||
| "tailwind.config.*" | ||
| ], | ||
| "linter": { | ||
| "rules": { | ||
| "style": { | ||
| "noDefaultExport": "off" | ||
| } | ||
| } | ||
| } | ||
| }, | ||
| { | ||
| "includes": [ | ||
| "*.config.ts", | ||
| "*.config.js", | ||
| "*.config.mjs", | ||
| "*.config.cjs", | ||
| "vite.config.*", | ||
| "vitest.config.*", | ||
| "next.config.*", | ||
| "tailwind.config.*" | ||
| ], | ||
| "linter": { | ||
| "rules": { | ||
| "style": { | ||
| "noDefaultExport": "off" | ||
| } | ||
| } | ||
| } | ||
| } | ||
| ] |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
# First, locate and read the biome.json file to confirm the exact content and line numbers
fd biome.jsonRepository: Questi0nM4rk/codeagent
Length of output: 76
🌐 Web query:
Biome v2 overrides includes schema documentation
💡 Result:
In Biome v2, overrides are documented in the main configuration reference:
overrides.<ITEM>.includes: “A list of glob patterns of files for which to apply customised settings.” (Only the first matching override is applied, because order matters.) [1]
Example (from the docs):
{
"overrides": [
{
"includes": ["scripts/*.js"]
// ...settings that apply only to those files
}
]
}[1]
JSON Schema (for editor autocomplete/validation)
Biome publishes a JSON Schema for biome.json / biome.jsonc:
- Local (from npm package):
./node_modules/@biomejs/biome/configuration_schema.json[1] - Hosted (versioned):
https://biomejs.dev/schemas/<version>/schema.json(the docs show examples like.../schemas/2.3.11/schema.json) [1]
And here’s a v2 guide example of using overrides (showing includes in practice): [2]
{
"overrides": [
{
"includes": ["package.json"],
"json": { "formatter": { "expand": "auto" } }
}
]
}Sources: Configuration reference [1], v2 upgrade guide example [2].
🏁 Script executed:
# Read biome.json to confirm the exact content at lines 297-347
sed -n '297,347p' biome.jsonRepository: Questi0nM4rk/codeagent
Length of output: 994
Replace include with includes and remove the duplicate override block.
Biome v2 overrides use includes (not include). Lines 299 and 310 use the invalid v1 key name. Additionally, the second and third override blocks (lines 309–327 and 328–346) are duplicates—the first uses the wrong key, the second uses the correct one. Update both include keys to includes and remove the duplicate block.
Proposed fix
"overrides": [
{
- "include": [
+ "includes": [
"**/tests/fixtures/**"
],
"linter": {
"enabled": false
},
"formatter": {
"enabled": false
}
},
{
- "include": [
+ "includes": [
"*.config.ts",
"*.config.js",
"*.config.mjs",
"*.config.cjs",
"vite.config.*",
"vitest.config.*",
"next.config.*",
"tailwind.config.*"
],
"linter": {
"rules": {
"style": {
"noDefaultExport": "off"
}
}
}
- },
- {
- "includes": [
- "*.config.ts",
- "*.config.js",
- "*.config.mjs",
- "*.config.cjs",
- "vite.config.*",
- "vitest.config.*",
- "next.config.*",
- "tailwind.config.*"
- ],
- "linter": {
- "rules": {
- "style": {
- "noDefaultExport": "off"
- }
- }
- }
}
]📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| "overrides": [ | |
| { | |
| "include": [ | |
| "**/tests/fixtures/**" | |
| ], | |
| "linter": { | |
| "enabled": false | |
| }, | |
| "formatter": { | |
| "enabled": false | |
| } | |
| }, | |
| { | |
| "include": [ | |
| "*.config.ts", | |
| "*.config.js", | |
| "*.config.mjs", | |
| "*.config.cjs", | |
| "vite.config.*", | |
| "vitest.config.*", | |
| "next.config.*", | |
| "tailwind.config.*" | |
| ], | |
| "linter": { | |
| "rules": { | |
| "style": { | |
| "noDefaultExport": "off" | |
| } | |
| } | |
| } | |
| }, | |
| { | |
| "includes": [ | |
| "*.config.ts", | |
| "*.config.js", | |
| "*.config.mjs", | |
| "*.config.cjs", | |
| "vite.config.*", | |
| "vitest.config.*", | |
| "next.config.*", | |
| "tailwind.config.*" | |
| ], | |
| "linter": { | |
| "rules": { | |
| "style": { | |
| "noDefaultExport": "off" | |
| } | |
| } | |
| } | |
| } | |
| ] | |
| "overrides": [ | |
| { | |
| "includes": [ | |
| "**/tests/fixtures/**" | |
| ], | |
| "linter": { | |
| "enabled": false | |
| }, | |
| "formatter": { | |
| "enabled": false | |
| } | |
| }, | |
| { | |
| "includes": [ | |
| "*.config.ts", | |
| "*.config.js", | |
| "*.config.mjs", | |
| "*.config.cjs", | |
| "vite.config.*", | |
| "vitest.config.*", | |
| "next.config.*", | |
| "tailwind.config.*" | |
| ], | |
| "linter": { | |
| "rules": { | |
| "style": { | |
| "noDefaultExport": "off" | |
| } | |
| } | |
| } | |
| } | |
| ] |
🧰 Tools
🪛 Biome (2.3.13)
[error] 299-299: Found an unknown key include.
Known keys:
(deserialize)
[error] 310-310: Found an unknown key include.
Known keys:
(deserialize)
🤖 Prompt for AI Agents
In `@biome.json` around lines 297 - 347, The overrides array contains a duplicate
block and uses the deprecated key "include" instead of "includes"; update the
override that currently has "include" to use "includes" (so both config override
blocks use "includes") and remove the duplicate override entry so only one
config override remains, ensuring the linter.rules.style.noDefaultExport setting
is preserved for the config/glob patterns referenced by the "*.config.*",
"vite.config.*", "vitest.config.*", "next.config.*", and "tailwind.config.*"
includes.
| "pydantic>=2.0.0", | ||
| "httpx>=0.25.0", | ||
| "tree-sitter>=0.20.0", | ||
| "tree-sitter-languages>=1.8.0", | ||
| "tomli-w>=1.0", | ||
| "tomlkit>=0.12", |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check where tomli-w and tomlkit are actually imported/used
echo "=== tomli_w usage ==="
rg -n "tomli_w" --type=py
echo ""
echo "=== tomlkit usage ==="
rg -n "tomlkit" --type=pyRepository: Questi0nM4rk/codeagent
Length of output: 593
Consider consolidating TOML dependencies.
Both tomli-w (used in src/codeagent/guardrails/generators/ruff.py for writing fresh config) and tomlkit (used in src/codeagent/guardrails/generators/pyright.py for round-trip format-preserving edits) are included. While both serve slightly different purposes, tomlkit can handle both use cases. Consider whether the marginal benefit of tomli-w for simple writes justifies the additional dependency, or consolidate on tomlkit alone.
🤖 Prompt for AI Agents
In `@pyproject.toml` around lines 30 - 35, The project currently depends on both
"tomli-w" and "tomlkit"; consolidate by removing "tomli-w" from pyproject.toml
and update the code that uses tomli-w (referenced in
src/codeagent/guardrails/generators/ruff.py where fresh TOML config is written)
to use tomlkit's writing API instead (the same library already used by
src/codeagent/guardrails/generators/pyright.py for round-trip edits), ensuring
the write logic preserves expected output format and updating any import names
and tests accordingly.
| # Scaffold .guardrails-exceptions.toml if not present | ||
| exceptions_path = project_path / ".guardrails-exceptions.toml" | ||
| if not exceptions_path.exists() or force: | ||
| _scaffold_exceptions_file(exceptions_path) | ||
| console.print("[green]\u2713[/] Created .guardrails-exceptions.toml") | ||
|
|
||
| # Generate merged configs from registry + base templates | ||
| if exceptions_path.exists(): | ||
| from codeagent.guardrails.generate import run_generate_configs | ||
|
|
||
| run_generate_configs(project_dir=str(project_path)) |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Scaffold + generate flow looks correct.
The ordering is sound: scaffold if missing (or forced), then generate configs from whatever exceptions file exists. The lazy import on line 115 is appropriate for CLI modules per the project's own exceptions registry.
One note: when force=True and the user has a customized .guardrails-exceptions.toml, this overwrites it with the minimal scaffold template before regenerating configs. If this is intentional (full reset), consider logging a warning to make the destructive overwrite visible.
💡 Optional: warn before overwriting a customized file
exceptions_path = project_path / ".guardrails-exceptions.toml"
- if not exceptions_path.exists() or force:
+ if not exceptions_path.exists():
+ _scaffold_exceptions_file(exceptions_path)
+ console.print("[green]\u2713[/] Created .guardrails-exceptions.toml")
+ elif force:
+ console.print("[yellow]⚠[/] Overwriting existing .guardrails-exceptions.toml")
_scaffold_exceptions_file(exceptions_path)
console.print("[green]\u2713[/] Created .guardrails-exceptions.toml")🤖 Prompt for AI Agents
In `@src/codeagent/cli/init_cmd.py` around lines 107 - 117, When force=True and an
existing customized .guardrails-exceptions.toml will be overwritten by
_scaffold_exceptions_file, add a visible warning before performing the
overwrite: detect when exceptions_path.exists() and force is True, emit a
console.print or logger warning that the existing file will be replaced, then
proceed to call _scaffold_exceptions_file(exceptions_path) and continue to
run_generate_configs; reference the variables and functions exceptions_path,
force, _scaffold_exceptions_file, and run_generate_configs in the change.
| # Load and validate | ||
| registry = ExceptionRegistry.load(registry_path) | ||
| errors = registry.validate() | ||
| if errors: | ||
| console.print(f"[red]Validation errors in {REGISTRY_FILENAME}:[/]") | ||
| for err in errors: | ||
| console.print(f" - {err}") | ||
| return False |
There was a problem hiding this comment.
Unhandled ValueError from ExceptionRegistry.load() on malformed TOML.
If the registry file exists but contains invalid TOML, ExceptionRegistry.load() raises ValueError. This would propagate as an unhandled exception with a traceback instead of a user-friendly error message.
🐛 Proposed fix
# Load and validate
- registry = ExceptionRegistry.load(registry_path)
+ try:
+ registry = ExceptionRegistry.load(registry_path)
+ except ValueError as e:
+ console.print(f"[red]Error loading {REGISTRY_FILENAME}: {e}[/]")
+ return False
errors = registry.validate()🤖 Prompt for AI Agents
In `@src/codeagent/guardrails/generate.py` around lines 47 - 54,
ExceptionRegistry.load(registry_path) can raise ValueError on malformed TOML;
wrap the load call in a try/except that catches ValueError, log a clear
user-friendly error via console.print (including REGISTRY_FILENAME and the
exception message), and return False instead of allowing the traceback to
propagate; keep the subsequent registry.validate() logic as-is (refer to
ExceptionRegistry.load, registry.validate, REGISTRY_FILENAME, and
console.print).
| # Generate ruff.toml | ||
| base_ruff = configs_dir / "ruff.toml" | ||
| if base_ruff.exists(): | ||
| generate_ruff(registry, base_ruff, project_path / "ruff.toml") | ||
| console.print("[green]\u2713[/] Generated ruff.toml") | ||
|
|
||
| # Generate biome.json | ||
| base_biome = configs_dir / "biome.json" | ||
| if base_biome.exists(): | ||
| generate_biome(registry, base_biome, project_path / "biome.json") | ||
| console.print("[green]\u2713[/] Generated biome.json") | ||
|
|
||
| # Generate .markdownlint.jsonc | ||
| base_mdlint = configs_dir / ".markdownlint.jsonc" | ||
| if base_mdlint.exists(): | ||
| generate_markdownlint( | ||
| registry, | ||
| base_mdlint, | ||
| project_path / ".markdownlint.jsonc", | ||
| ) | ||
| console.print("[green]\u2713[/] Generated .markdownlint.jsonc") | ||
|
|
||
| # Generate .codespellrc | ||
| if registry.global_rules.get("codespell"): | ||
| generate_codespell(registry, project_path / ".codespellrc") | ||
| console.print("[green]\u2713[/] Generated .codespellrc") | ||
|
|
||
| # Generate .suppression-allowlist | ||
| if registry.inline_suppressions: | ||
| generate_allowlist(registry, project_path / ".suppression-allowlist") | ||
| console.print("[green]\u2713[/] Generated .suppression-allowlist") | ||
|
|
||
| # Merge pyright into pyproject.toml | ||
| pyproject = project_path / "pyproject.toml" | ||
| if pyproject.exists() and registry.global_rules.get("pyright"): | ||
| generate_pyright(registry, pyproject) | ||
| console.print("[green]\u2713[/] Updated pyproject.toml [tool.pyright]") |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
No error handling around individual generator calls.
If any generator fails (e.g., corrupt base template, disk full), the exception aborts the entire run without generating remaining configs. Consider wrapping each generator call in a try/except to continue generating the rest and report failures at the end.
🤖 Prompt for AI Agents
In `@src/codeagent/guardrails/generate.py` around lines 62 - 98, The generator
calls (generate_ruff, generate_biome, generate_markdownlint, generate_codespell,
generate_allowlist, generate_pyright) should be wrapped individually in
try/except blocks so a failure in one doesn't abort the whole run; catch
exceptions, record failures (including exception text and the target path or
config name) into a list, continue with the next generator, and after all
attempts log a summary using console (e.g., which generators succeeded and which
failed with errors) so callers can see partial results while still surfacing
problems; reference registry and project_path as needed when building the error
context.
| def _strip_jsonc_comments(text: str) -> str: | ||
| """Remove // comments from JSONC content.""" | ||
| return re.sub(r"^\s*//.*$", "", text, flags=re.MULTILINE) |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
_strip_jsonc_comments is fragile for edge cases.
The regex r"^\s*//.*$" only strips full-line // comments. It would also strip lines containing // inside JSON string values (e.g., URLs like "homepage": "https://example.com"). For markdownlint configs this is low risk, but consider using a proper JSONC parser (e.g., json5 or pyjson5) if the base template may contain such values in the future.
🤖 Prompt for AI Agents
In `@src/codeagent/guardrails/generators/markdownlint.py` around lines 24 - 26,
_strip_jsonc_comments currently uses a fragile regex that only removes full-line
// comments and can corrupt JSONC with // inside string values (e.g., URLs);
update the function to use a proper JSONC/JSON5 parser (for example replace the
regex approach in _strip_jsonc_comments with loading via pyjson5 or json5 and
re-serializing) so comments are removed safely, or if you must keep a regex
approach, implement a parser-aware removal that skips // occurrences inside
string literals (but prefer using pyjson5/json5 to load and then dump valid
JSON).
| def validate(self) -> list[str]: | ||
| """Validate the registry for completeness. | ||
|
|
||
| Returns: | ||
| List of validation error strings. Empty means valid. | ||
|
|
||
| """ | ||
| errors: list[str] = [] | ||
|
|
||
| # Check global ruff rules have non-empty reasons | ||
| for tool, rules in self.global_rules.items(): | ||
| if tool in ("codespell", "pyright"): | ||
| continue # These use structured values, not string reasons | ||
| for rule, reason in rules.items(): | ||
| if isinstance(reason, str) and not reason.strip(): | ||
| errors.append( | ||
| f"global.{tool}.{rule}: empty reason", | ||
| ) | ||
|
|
||
| # Check file exceptions have reasons | ||
| for i, fe in enumerate(self.file_exceptions): | ||
| if not fe.reason: | ||
| errors.append( | ||
| f"file_exceptions[{i}]: missing reason", | ||
| ) | ||
|
|
||
| # Check inline suppressions have reasons | ||
| for i, sup in enumerate(self.inline_suppressions): | ||
| if not sup.reason: | ||
| errors.append( | ||
| f"inline_suppressions[{i}]: missing reason", | ||
| ) | ||
|
|
||
| return errors |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Hardcoded tool skip-list in validate() is a maintenance concern.
Line 143 hardcodes ("codespell", "pyright") as tools that use structured values. If a new tool with structured config is added, this list must be manually updated or validation will produce false positives.
Consider deriving this from a class-level constant or from the data itself (e.g., checking whether any value is non-string).
🤖 Prompt for AI Agents
In `@src/codeagent/guardrails/registry.py` around lines 132 - 165, The validate()
method currently uses a hardcoded skip-list ("codespell", "pyright") when
iterating self.global_rules; replace this brittle approach by detecting
structured rule values from the data itself: in validate(), for each tool,rules
in self.global_rules.items() check the type of the rule values (e.g., inspect
one or all rule values and if any value is not a str treat the tool as
structured) and only enforce non-empty-string reasons when the reasons are
strings; update the loop over self.global_rules in validate() (and remove the
hardcoded tuple) so the logic uses isinstance(reason, str) to decide whether to
validate and skips tools whose rule values are non-string or structured.
| class TestRegistryHelpers: | ||
| """Test helper methods on ExceptionRegistry.""" | ||
|
|
||
| def test_get_ruff_ignores(self, full_toml: Path) -> None: | ||
| reg = ExceptionRegistry.load(full_toml) | ||
| ignores = reg.get_global_ignores("ruff") | ||
| assert "W191" in ignores | ||
| assert "D" in ignores | ||
|
|
||
| def test_get_file_exceptions_for_tool(self, full_toml: Path) -> None: | ||
| reg = ExceptionRegistry.load(full_toml) | ||
| ruff_exceptions = reg.get_file_exceptions("ruff") | ||
| assert len(ruff_exceptions) == 1 | ||
| assert ruff_exceptions[0].tool == "ruff" | ||
|
|
||
| biome_exceptions = reg.get_file_exceptions("biome") | ||
| assert len(biome_exceptions) == 1 | ||
|
|
||
| def test_get_file_exceptions_empty(self, full_toml: Path) -> None: | ||
| reg = ExceptionRegistry.load(full_toml) | ||
| assert reg.get_file_exceptions("shellcheck") == [] |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Good test coverage with proper isolation.
Tests are well-structured with meaningful assertions and no shared state. Consider adding a test for get_global_ignores("codespell") to verify structured-value tools return an empty list (since skip and ignore_words are lists/dicts, not string reasons).
🤖 Prompt for AI Agents
In `@tests/guardrails/test_registry.py` around lines 192 - 212, Add a test case
that loads the registry via ExceptionRegistry.load (use the existing full_toml
fixture) and asserts that reg.get_global_ignores("codespell") returns an empty
list; this verifies structured-value tools like codespell (which use
skip/ignore_words lists or dicts) do not produce string-based global ignore
reasons. Place the new test alongside the other TestRegistryHelpers methods
(e.g., after test_get_ruff_ignores) and follow the same pattern of creating reg
= ExceptionRegistry.load(full_toml) and asserting the empty result.
The generator now checks the project's configs/ directory first for base templates before falling back to the global install path. This fixes generation failing when get_configs_dir() resolves to the wrong package. Also restores configs/ruff.toml, configs/biome.json, and configs/.markdownlint.jsonc as base templates for the generator. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Document the new .guardrails-exceptions.toml workflow, codeagent generate-configs command, and the two-layer architecture (base templates + project exceptions). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Fix all issues with AI agents
In `@configs/.markdownlint.jsonc`:
- Around line 61-65: The MD009 and MD010 rule entries are disabled but currently
sit beneath the comment marker "// === ENABLED - Actually useful ===", which is
misleading; update the config by moving the "MD009": false and "MD010": false
entries out from under that enabled section and place them under the "// ===
DISABLED - Time wasters ===" comment (or alternatively add a new comment like
"// Delegated to other tools" and move them there) so the boolean settings match
the surrounding heading; ensure you only relocate the lines for MD009 and MD010
and keep their values unchanged.
In `@ruff.toml`:
- Around line 18-36: The ignore list contains a redundant configuration: the
broad "D" entry already disables the entire pydocstyle category, so the specific
"D206" and "D300" entries are dead; remove the individual "D206" and "D300"
entries from the ignore array (leaving "D" intact) to eliminate redundant
ignores and clean up the config.
- Around line 39-47: The ruff.toml contains dead configuration blocks
[lint.pydocstyle] and [lint.flake8-annotations] because the D and ANN rule
categories are already ignored in the [lint] ignore list (the D and ANN
entries), so either remove these no-op sections or document why they are
retained for future use; update the file by deleting the [lint.pydocstyle] and
[lint.flake8-annotations] sections if you want them gone, or add a concise
inline comment next to each header explaining they are intentionally kept as
examples/placeholders for re-enabling pydocstyle and flake8-annotations rules
later, referencing the section names [lint.pydocstyle] and
[lint.flake8-annotations] and the D/ANN ignore entries so reviewers understand
the relationship.
In `@src/codeagent/guardrails/generate.py`:
- Around line 71-101: The code silently skips generating configs when
_find_base(...) returns None; update the ruff/biome/markdownlint blocks so that
after calling _find_base("ruff.toml"), _find_base("biome.json"), and
_find_base(".markdownlint.jsonc") you add an else branch that calls
console.print with a warning (e.g., "[yellow]Warning:[/] base template
'ruff.toml' not found, skipping generation") to inform the user which template
was missing; apply the same pattern to the generate_ruff, generate_biome, and
generate_markdownlint flows so missing-base cases are logged instead of silent.
| // MD009: Trailing spaces - handled by trailing-whitespace hook | ||
| "MD009": false, | ||
|
|
||
| // MD010: No hard tabs - handled by editorconfig | ||
| "MD010": false, |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
MD009 and MD010 are placed under the "ENABLED - Actually useful" heading but are set to false.
These two disabled rules sit below the // === ENABLED - Actually useful === comment (Line 44), which is misleading. Move them up into the // === DISABLED - Time wasters === section for consistency, or add a sub-heading (e.g., // Delegated to other tools) to clarify.
🤖 Prompt for AI Agents
In `@configs/.markdownlint.jsonc` around lines 61 - 65, The MD009 and MD010 rule
entries are disabled but currently sit beneath the comment marker "// ===
ENABLED - Actually useful ===", which is misleading; update the config by moving
the "MD009": false and "MD010": false entries out from under that enabled
section and place them under the "// === DISABLED - Time wasters ===" comment
(or alternatively add a new comment like "// Delegated to other tools" and move
them there) so the boolean settings match the surrounding heading; ensure you
only relocate the lines for MD009 and MD010 and keep their values unchanged.
| ignore = [ | ||
| # === Formatter conflicts === | ||
| "W191", # tab-indentation | ||
| "E111", # indentation-with-invalid-multiple | ||
| "E114", # indentation-with-invalid-multiple-comment | ||
| "E117", # over-indented | ||
| "D206", # indent-with-spaces | ||
| "D300", # triple-single-quotes | ||
| "Q000", # bad-quotes-inline-string | ||
| "Q001", # bad-quotes-multiline-string | ||
| "Q002", # bad-quotes-docstring | ||
| "Q003", # avoidable-escaped-quote | ||
| "COM812", # missing-trailing-comma | ||
| "COM819", # prohibited-trailing-comma | ||
| "ISC001", # single-line-implicit-string-concatenation | ||
| "ISC002", # multi-line-implicit-string-concatenation | ||
|
|
||
| # === Disabled rule groups === | ||
| "D", # pydocstyle - docstrings not enforced yet | ||
| "ANN", # annotations - using mypy --strict for type checking | ||
|
|
||
| # === Project-wide exceptions === | ||
| "TD003", # TODOs use Epic numbers, not issue links | ||
| "FIX002", # TODOs are intentional reminders, not errors | ||
| "ANN", | ||
| "COM812", | ||
| "COM819", | ||
| "D", | ||
| "D206", | ||
| "D300", | ||
| "E111", | ||
| "E114", | ||
| "E117", | ||
| "FIX002", | ||
| "ISC001", | ||
| "ISC002", | ||
| "Q000", | ||
| "Q001", | ||
| "Q002", | ||
| "Q003", | ||
| "TD003", | ||
| "W191", |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Redundant individual rule ignores D206 and D300 when the entire D category is already ignored.
Since "D" (Line 22) disables all pydocstyle rules, the individual "D206" (Line 23) and "D300" (Line 24) entries are dead config. Remove them to reduce noise.
Proposed fix
ignore = [
"ANN",
"COM812",
"COM819",
"D",
- "D206",
- "D300",
"E111",📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| ignore = [ | |
| # === Formatter conflicts === | |
| "W191", # tab-indentation | |
| "E111", # indentation-with-invalid-multiple | |
| "E114", # indentation-with-invalid-multiple-comment | |
| "E117", # over-indented | |
| "D206", # indent-with-spaces | |
| "D300", # triple-single-quotes | |
| "Q000", # bad-quotes-inline-string | |
| "Q001", # bad-quotes-multiline-string | |
| "Q002", # bad-quotes-docstring | |
| "Q003", # avoidable-escaped-quote | |
| "COM812", # missing-trailing-comma | |
| "COM819", # prohibited-trailing-comma | |
| "ISC001", # single-line-implicit-string-concatenation | |
| "ISC002", # multi-line-implicit-string-concatenation | |
| # === Disabled rule groups === | |
| "D", # pydocstyle - docstrings not enforced yet | |
| "ANN", # annotations - using mypy --strict for type checking | |
| # === Project-wide exceptions === | |
| "TD003", # TODOs use Epic numbers, not issue links | |
| "FIX002", # TODOs are intentional reminders, not errors | |
| "ANN", | |
| "COM812", | |
| "COM819", | |
| "D", | |
| "D206", | |
| "D300", | |
| "E111", | |
| "E114", | |
| "E117", | |
| "FIX002", | |
| "ISC001", | |
| "ISC002", | |
| "Q000", | |
| "Q001", | |
| "Q002", | |
| "Q003", | |
| "TD003", | |
| "W191", | |
| ignore = [ | |
| "ANN", | |
| "COM812", | |
| "COM819", | |
| "D", | |
| "E111", | |
| "E114", | |
| "E117", | |
| "FIX002", | |
| "ISC001", | |
| "ISC002", | |
| "Q000", | |
| "Q001", | |
| "Q002", | |
| "Q003", | |
| "TD003", | |
| "W191", |
🤖 Prompt for AI Agents
In `@ruff.toml` around lines 18 - 36, The ignore list contains a redundant
configuration: the broad "D" entry already disables the entire pydocstyle
category, so the specific "D206" and "D300" entries are dead; remove the
individual "D206" and "D300" entries from the ignore array (leaving "D" intact)
to eliminate redundant ignores and clean up the config.
| [lint.pydocstyle] | ||
| convention = "google" | ||
|
|
||
| [lint.flake8-annotations] | ||
| allow-star-arg-any = false | ||
| ignore-fully-untyped = false | ||
| mypy-init-return = true | ||
| suppress-dummy-args = false | ||
| suppress-none-returning = false |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
[lint.pydocstyle] and [lint.flake8-annotations] sections are no-ops.
The entire D and ANN rule categories are ignored in the [lint] ignore list (Lines 19, 22). These configuration sections have no effect since their corresponding rules are never activated. If these categories are intentionally disabled, consider removing the dead sections or adding a comment explaining they're kept as documentation for when the rules are re-enabled.
🤖 Prompt for AI Agents
In `@ruff.toml` around lines 39 - 47, The ruff.toml contains dead configuration
blocks [lint.pydocstyle] and [lint.flake8-annotations] because the D and ANN
rule categories are already ignored in the [lint] ignore list (the D and ANN
entries), so either remove these no-op sections or document why they are
retained for future use; update the file by deleting the [lint.pydocstyle] and
[lint.flake8-annotations] sections if you want them gone, or add a concise
inline comment next to each header explaining they are intentionally kept as
examples/placeholders for re-enabling pydocstyle and flake8-annotations rules
later, referencing the section names [lint.pydocstyle] and
[lint.flake8-annotations] and the D/ANN ignore entries so reviewers understand
the relationship.
| # Generate ruff.toml | ||
| base_ruff = _find_base("ruff.toml") | ||
| if base_ruff: | ||
| generate_ruff(registry, base_ruff, project_path / "ruff.toml") | ||
| console.print("[green]\u2713[/] Generated ruff.toml") | ||
|
|
||
| # Generate biome.json | ||
| base_biome = _find_base("biome.json") | ||
| if base_biome: | ||
| generate_biome(registry, base_biome, project_path / "biome.json") | ||
| console.print("[green]\u2713[/] Generated biome.json") | ||
|
|
||
| # Generate .markdownlint.jsonc | ||
| base_mdlint = _find_base(".markdownlint.jsonc") | ||
| if base_mdlint: | ||
| generate_markdownlint( | ||
| registry, | ||
| base_mdlint, | ||
| project_path / ".markdownlint.jsonc", | ||
| ) | ||
| console.print("[green]\u2713[/] Generated .markdownlint.jsonc") | ||
|
|
||
| # Generate .codespellrc | ||
| if registry.global_rules.get("codespell"): | ||
| generate_codespell(registry, project_path / ".codespellrc") | ||
| console.print("[green]\u2713[/] Generated .codespellrc") | ||
|
|
||
| # Generate .suppression-allowlist | ||
| if registry.inline_suppressions: | ||
| generate_allowlist(registry, project_path / ".suppression-allowlist") | ||
| console.print("[green]\u2713[/] Generated .suppression-allowlist") |
There was a problem hiding this comment.
Silent skip when base templates are missing — no user feedback.
When _find_base() returns None, the corresponding config is silently skipped with no output. A user expecting ruff.toml or biome.json to be generated will get no indication that the base template was not found. Consider printing a warning for each missing template so users can diagnose issues.
Proposed fix (example for ruff; apply the same pattern to biome and markdownlint)
# Generate ruff.toml
base_ruff = _find_base("ruff.toml")
if base_ruff:
generate_ruff(registry, base_ruff, project_path / "ruff.toml")
console.print("[green]\u2713[/] Generated ruff.toml")
+ else:
+ console.print("[yellow]⚠[/] Skipped ruff.toml (no base template found)")🤖 Prompt for AI Agents
In `@src/codeagent/guardrails/generate.py` around lines 71 - 101, The code
silently skips generating configs when _find_base(...) returns None; update the
ruff/biome/markdownlint blocks so that after calling _find_base("ruff.toml"),
_find_base("biome.json"), and _find_base(".markdownlint.jsonc") you add an else
branch that calls console.print with a warning (e.g., "[yellow]Warning:[/] base
template 'ruff.toml' not found, skipping generation") to inform the user which
template was missing; apply the same pattern to the generate_ruff,
generate_biome, and generate_markdownlint flows so missing-base cases are logged
instead of silent.
Summary
Epic 6 (partial): Consolidate separate MCP servers into a single
codeagent-mcpserver backed by SurrealDB.What's included
app.add_tool()Tools (15 total)
Test coverage
Not included (deferred)
index_filetool) - needs further studyTest plan
uv run --python 3.12 pytest tests/ -v→ 287 passeduv run --python 3.12 ruff check src/ tests/→ All checks passed🤖 Generated with Claude Code
Summary by CodeRabbit