#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Switch to Pyrefly for Python type checking (#6365)
James Brunton5db3cb5346de
diff --git a/.taskfiles/engine.yml b/.taskfiles/engine.ymlindex 23a4f49eef..834f66fc2a 100644--- a/.taskfiles/engine.yml+++ b/.taskfiles/engine.yml@@ -2,7 +2,7 @@ version: '3'vars:RUFF_THREADS: '{{if .STIRLING_CHECK_JOBS}}RAYON_NUM_THREADS={{.STIRLING_CHECK_JOBS}} {{end}}'- PYRIGHT_THREADS: '{{if .STIRLING_CHECK_JOBS}} --threads={{.STIRLING_CHECK_JOBS}}{{end}}'+ PYREFLY_THREADS: '{{if .STIRLING_CHECK_JOBS}} --threads={{.STIRLING_CHECK_JOBS}}{{end}}'tasks:install:@@ -106,7 +106,7 @@ tasks:desc: "Run type checking"deps: [install]cmds:- - 'uv run --locked --group engine --group engine-dev pyright . --warnings{{.PYRIGHT_THREADS}}'+ - 'uv run --locked --group engine --group engine-dev pyrefly check{{.PYREFLY_THREADS}}'test:desc: "Run tests"diff --git a/AGENTS.md b/AGENTS.mdindex efb31d8f1e..9173676890 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -88,15 +88,15 @@ The engine is a Python reasoning service for Stirling: it plans and interprets w#### Python CommandsAll engine commands run from the repo root using Task:-- `task engine:check` — run all checks (typecheck + lint + format-check + test)-- `task engine:fix` — auto-fix lint + formatting-- `task engine:install` — install Python dependencies via uv-- `task engine:dev` — start FastAPI with hot reload (localhost:5001)-- `task engine:test` — run pytest-- `task engine:lint` — run ruff linting-- `task engine:typecheck` — run pyright-- `task engine:format` — format code with ruff-- `task engine:tool-models` — generate `tool_models.py` from the Java OpenAPI spec+- `task engine:check` — run all checks+- `task engine:fix` — auto-fix code issues+- `task engine:install` — install Python dependencies+- `task engine:dev` — start server in dev mode+- `task engine:test` — run the tests+- `task engine:lint` — run linters+- `task engine:typecheck` — run type checkers+- `task engine:format` — run formatters+- `task engine:tool-models` — generate tool models from the Java OpenAPI specThe project structure is defined in `engine/pyproject.toml`. Any new dependencies should be listed there, followed by running `task engine:install`.diff --git a/engine/pyproject.toml b/engine/pyproject.tomlindex 877595900b..70438d2e90 100644--- a/engine/pyproject.toml+++ b/engine/pyproject.toml@@ -30,7 +30,7 @@ engine = [engine-dev = ["anyio>=4.14.2","datamodel-code-generator[ruff]==0.64.0",- "pyright>=1.1.411",+ "pyrefly==1.4.1","pytest>=9.1.1","referencing>=0.37.0","ruff==0.15.5",@@ -104,15 +104,6 @@ select = [[tool.ruff.lint.isort]known-first-party = ["stirling", "tests"]-[tool.pyright]-pythonVersion = "3.13"-reportImportCycles = "warning"-reportUnnecessaryCast = "warning"-reportUnnecessaryTypeIgnoreComment = "warning"-reportUnusedImport = "warning"-reportUnknownParameterType = "warning"-reportDeprecated = "warning"-[tool.pytest.ini_options]testpaths = ["tests"]# ``tests`` is on the path so test modules can import shared helpers (e.g.@@ -121,3 +112,23 @@ pythonpath = ["src", "tests"]# Use importlib import mode so test directories don't need __init__.py files# and duplicate basenames (e.g. multiple test_routes.py) collect cleanly.addopts = "--import-mode=importlib"++[tool.pyrefly]+python-version = "3.13.0"+search-path = [+ "src",+ "tests",+]+# Disallow `type: ignore` comments to encourage accurate error codes to be used in ignore comments+# Pyrefly won't flag `type: ignore [wrong-code]`, but it will flag `pyrefly: ignore [wrong-code]`+enabled-ignores = ["pyrefly"]+min-severity = "warn"++[tool.pyrefly.errors]+deprecated = "warn"+implicit-any = "warn"+redundant-cast = "warn"+unused-ignore = "warn"+# TODO: Add equivalents to:+# - reportImportCycles+# - reportUnusedImportdiff --git a/engine/src/stirling/agents/contradiction/detector.py b/engine/src/stirling/agents/contradiction/detector.pyindex c075ae342b..ac44b6eea2 100644--- a/engine/src/stirling/agents/contradiction/detector.py+++ b/engine/src/stirling/agents/contradiction/detector.py@@ -109,7 +109,7 @@ class _SubjectMapping(BaseModel):class _SummaryStats(BaseModel):"""Stats handed to the summary LLM. Typed (rather than a raw dictJSON-dumped at the call site) so the prompt payload's shape lives- in one place and pyright can catch field-name typos.+ in one place and pyrefly can catch field-name typos."""pages_examined: int = Field(ge=0)diff --git a/engine/src/stirling/agents/ledger/agent.py b/engine/src/stirling/agents/ledger/agent.pyindex f000b604e4..c675bd28bb 100644--- a/engine/src/stirling/agents/ledger/agent.py+++ b/engine/src/stirling/agents/ledger/agent.py@@ -478,6 +478,7 @@ class MathAuditorAgent:logger.info("[math-auditor-agent] extracting figures from page %d (%d chars)", folio.page, len(text))prompt = f"Page {folio.page + 1} text:\n{text}"+ figures: list[ExtractedFigure] = []try:result = await self._figure_extractor.run(prompt)figures = result.output.figures@@ -487,7 +488,6 @@ class MathAuditorAgent:folio.page,exc_info=True,)- figures = []logger.debug("TOOL (extract_figures)\nArgs: %s\nResult: %s",diff --git a/engine/src/stirling/agents/pdf_edit.py b/engine/src/stirling/agents/pdf_edit.pyindex 42ad76aa94..77cec1ed1d 100644--- a/engine/src/stirling/agents/pdf_edit.py+++ b/engine/src/stirling/agents/pdf_edit.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport loggingfrom collections.abc import Iterable-from typing import Literal, overload+from typing import Literal, Protocol, overloadfrom pydantic import Fieldfrom pydantic_ai import Agent@@ -109,6 +109,16 @@ class PdfEditSelectionAgent:return result.output+class ParameterSelector(Protocol):+ async def select(+ self,+ request: PdfEditRequest,+ operation_plan: list[ToolEndpoint],+ operation_index: int,+ generated_steps: list[ToolOperationStep],+ ) -> ParamToolModel: ...++class PdfEditParameterSelector:def __init__(self, runtime: AppRuntime) -> None:self.runtime = runtime@@ -182,7 +192,7 @@ class PdfEditParameterSelector:class PdfEditAgent:def __init__(self, runtime: AppRuntime) -> None:self.runtime = runtime- self.parameter_selector = PdfEditParameterSelector(runtime)+ self.parameter_selector: ParameterSelector = PdfEditParameterSelector(runtime)self.shortlist: OperationRanker = runtime.operation_shortlistasync def orchestrate(self, request: OrchestratorRequest) -> PdfEditResponse:diff --git a/engine/src/stirling/api/engine_auth.py b/engine/src/stirling/api/engine_auth.pyindex c30b9f7429..888f270208 100644--- a/engine/src/stirling/api/engine_auth.py+++ b/engine/src/stirling/api/engine_auth.py@@ -59,7 +59,7 @@ class EngineSharedSecretMiddleware(BaseHTTPMiddleware):if require is None:require = settings.engine_require_authself._secret = secret or ""- self._require = bool(require)+ self._require = requireif self._secret:logger.info("Engine shared-secret enforcement ENABLED: non-public routes require a valid %s"diff --git a/engine/src/stirling/config/settings.py b/engine/src/stirling/config/settings.pyindex d753884592..93f31287cc 100644--- a/engine/src/stirling/config/settings.py+++ b/engine/src/stirling/config/settings.py@@ -202,7 +202,7 @@ def _enable_http_debug(formatter: logging.Formatter) -> None:lg.setLevel(level)# Idempotent: avoid stacking handlers on settings reload.if not any(getattr(h, "_stirling_http_debug", False) for h in lg.handlers):- handler._stirling_http_debug = True # type: ignore[attr-defined]+ handler._stirling_http_debug = True # pyrefly: ignore [missing-attribute]lg.addHandler(handler)lg.propagate = Falsediff --git a/engine/src/stirling/docparse/chunking.py b/engine/src/stirling/docparse/chunking.pyindex 7a2a122728..d31ac1f230 100644--- a/engine/src/stirling/docparse/chunking.py+++ b/engine/src/stirling/docparse/chunking.py@@ -75,7 +75,8 @@ def pack_blocks(blocks: list[MarkdownBlock], chunk_size: int, overlap: int) -> l# Too big to pack whole, so hand it to the character chunker, which applies# its own overlap; that is why nothing carries into or across this branch.emit()- buffer, buffer_len, carry = [], 0, ""+ buffer = []+ carry = ""for piece in chunk_text(markdown, chunk_size=chunk_size, overlap=overlap):chunks.append(DocChunk(@@ -97,7 +98,8 @@ def pack_blocks(blocks: list[MarkdownBlock], chunk_size: int, overlap: int) -> lwhile buffer and _is_heading(buffer[-1].markdown):held.insert(0, buffer.pop())if not buffer:- buffer, held = held, []+ buffer = held+ held = []emit()for heading in held:buffer.append(heading)diff --git a/engine/src/stirling/services/tracking.py b/engine/src/stirling/services/tracking.pyindex b45cb5959a..82712a69ec 100644--- a/engine/src/stirling/services/tracking.py+++ b/engine/src/stirling/services/tracking.py@@ -83,7 +83,7 @@ def _transform_output_choices(choices: list[Any]) -> list[Any]:for choice in choices:if not isinstance(choice, dict) or "parts" not in choice:continue- tool_calls = []+ tool_calls: list[dict[str, Any]] = []for part in choice.get("parts", []):if isinstance(part, dict) and part.get("type") == "tool_call":tool_calls.append(diff --git a/engine/tests/agents/test_orchestrator_pdf_comment.py b/engine/tests/agents/test_orchestrator_pdf_comment.pyindex a9aabaa562..2a7e5d230c 100644--- a/engine/tests/agents/test_orchestrator_pdf_comment.py+++ b/engine/tests/agents/test_orchestrator_pdf_comment.py@@ -50,7 +50,7 @@ async def test_delegate_pdf_review_wires_prompt_to_tool_step(runtime: AppRuntime"stirling.agents.pdf_review.MathIntentClassifier.classify",new=AsyncMock(return_value=False),):- response = await orchestrator.delegate_pdf_review(ctx) # type: ignore[arg-type]+ response = await orchestrator.delegate_pdf_review(ctx) # pyrefly: ignore [bad-argument-type]assert isinstance(response, EditPlanResponse)assert len(response.steps) == 1diff --git a/engine/tests/agents/test_pdf_create.py b/engine/tests/agents/test_pdf_create.pyindex 67fc5abfec..5c42acca5a 100644--- a/engine/tests/agents/test_pdf_create.py+++ b/engine/tests/agents/test_pdf_create.py@@ -364,7 +364,9 @@ async def test_orchestrate_assembles_multiple_chunks(agent: PdfCreateAgent) -> Nresult = await agent.orchestrate(_orchestrator_request("Create a multi-chunk doc"))assert isinstance(result, EditPlanResponse)- document = result.steps[0].parameters.document # type: ignore[union-attr]+ parameters = result.steps[0].parameters+ assert isinstance(parameters, CreatePdfFromHtmlAgentParams)+ document = parameters.documentassert "Introduction text." in documentassert "Details" in document@@ -395,7 +397,9 @@ async def test_orchestrate_applies_planner_inferred_style(agent: PdfCreateAgent)result = await agent.orchestrate(_orchestrator_request("Make an invoice, magenta styling"))assert isinstance(result, EditPlanResponse)- document = result.steps[0].parameters.document # type: ignore[union-attr]+ parameters = result.steps[0].parameters+ assert isinstance(parameters, CreatePdfFromHtmlAgentParams)+ document = parameters.documentassert json.loads(document)["style"]["primaryColor"] == "#ff00ff"@@ -440,6 +444,8 @@ async def test_orchestrate_drops_non_hex_planner_colour(agent: PdfCreateAgent) -result = await agent.orchestrate(_orchestrator_request("make it blue"))assert isinstance(result, EditPlanResponse)- document = result.steps[0].parameters.document # type: ignore[union-attr]+ parameters = result.steps[0].parameters+ assert isinstance(parameters, CreatePdfFromHtmlAgentParams)+ document = parameters.documentassert "rgb(" not in documentassert json.loads(document)["style"]["primaryColor"] is Nonediff --git a/engine/tests/agents/test_whole_doc_reader.py b/engine/tests/agents/test_whole_doc_reader.pyindex 749b847a1a..73b03c858a 100644--- a/engine/tests/agents/test_whole_doc_reader.py+++ b/engine/tests/agents/test_whole_doc_reader.py@@ -57,7 +57,7 @@ class StubEmbedder:@pytest.fixturedef runtime_with_stub_docs(runtime: AppRuntime) -> AppRuntime:stub = DocumentService(- embedder=StubEmbedder(), # type: ignore[arg-type]+ embedder=StubEmbedder(), # pyrefly: ignore [bad-argument-type]store=SqliteVecStore.ephemeral(),default_top_k=runtime.settings.rag_default_top_k,)@@ -217,13 +217,25 @@ async def test_read_full_document_budget_hides_tool_when_exhausted(sentinel: object = object()# Budget intact -> prepare returns the tool.- assert await capability._prepare_read_full_document(None, sentinel) is sentinel # type: ignore[arg-type]+ assert (+ await capability._prepare_read_full_document(+ None, # pyrefly: ignore [bad-argument-type]+ sentinel, # pyrefly: ignore [bad-argument-type]+ )+ is sentinel+ )# Spend the budget.await capability._read_full_document("anything")# Budget spent -> prepare returns None.- assert await capability._prepare_read_full_document(None, sentinel) is None # type: ignore[arg-type]+ assert (+ await capability._prepare_read_full_document(+ None, # pyrefly: ignore [bad-argument-type]+ sentinel, # pyrefly: ignore [bad-argument-type]+ )+ is None+ )@pytest.mark.anyiodiff --git a/engine/tests/contradiction/test_detector.py b/engine/tests/contradiction/test_detector.pyindex b9532e1e3e..d6035d2f6c 100644--- a/engine/tests/contradiction/test_detector.py+++ b/engine/tests/contradiction/test_detector.py@@ -238,7 +238,7 @@ async def test_canonicaliser_batches_oversized_subject_lists(runtime: AppRuntimeseen: list[str] = re.findall(r"subj-\d+", prompt)return _stub_result(_SubjectMapping(aliases=[_SubjectAlias(raw=s, canonical=s) for s in seen]))- detector._subject_canonicaliser.run = _stub # type: ignore[method-assign]+ detector._subject_canonicaliser.run = _stub # pyrefly: ignore [bad-assignment]mapping = await detector._canonicalise_subjects(subjects)@@ -269,7 +269,7 @@ async def test_canonicaliser_batch_conflict_resolved_by_lex_min(runtime: AppRunt# Force two batches by setting a tiny batch size for the call. We do# that by monkey-patching the setting on this detector instance only.object.__setattr__(detector._settings, "contradiction_canonicaliser_batch_size", 1)- detector._subject_canonicaliser.run = _stub # type: ignore[method-assign]+ detector._subject_canonicaliser.run = _stub # pyrefly: ignore [bad-assignment]mapping = await detector._canonicalise_subjects(["x", "y"])# Smaller canonical (lexicographically) wins.@@ -659,7 +659,7 @@ async def test_oversized_bucket_windows_translate_indices_globally(runtime: AppR)raise AssertionError(f"unexpected detector window #{window_count}")- detector._pair_detector.run = _stub_detector # type: ignore[method-assign]+ detector._pair_detector.run = _stub_detector # pyrefly: ignore [bad-assignment]detector._summary_agent.run = AsyncMock(return_value=_stub_result("done"))report = await detector.detect([file_a], principals=PRINCIPALS)@@ -787,7 +787,7 @@ async def test_multi_file_pages_dont_collide_in_validation(runtime: AppRuntime)return [chunk_b]return []- detector._mapper.map_pages = _map_pages # type: ignore[method-assign]+ detector._mapper.map_pages = _map_pages # pyrefly: ignore [bad-assignment]detector._subject_canonicaliser.run = AsyncMock(return_value=_stub_result(_SubjectMapping(aliases=[])))detector._pair_detector.run = AsyncMock(return_value=_stub_result(diff --git a/engine/tests/contradiction/test_question_integration.py b/engine/tests/contradiction/test_question_integration.pyindex 228f245258..7538768969 100644--- a/engine/tests/contradiction/test_question_integration.py+++ b/engine/tests/contradiction/test_question_integration.py@@ -59,7 +59,7 @@ def _claim(page: int, quote: str) -> Claim:@pytest.fixturedef runtime_with_stub_docs(runtime: AppRuntime) -> AppRuntime:stub = DocumentService(- embedder=StubEmbedder(), # type: ignore[arg-type]+ embedder=StubEmbedder(), # pyrefly: ignore [bad-argument-type]store=SqliteVecStore.ephemeral(),default_top_k=runtime.settings.rag_default_top_k,)@@ -76,7 +76,7 @@ async def test_run_answer_agent_builds_agent_with_three_toolsets(constructor and inspect what was wired.Uses pytest's ``monkeypatch`` fixture rather than direct attribute- assignment so pyright sees the swap as a typed test-only operation+ assignment so pyrefly sees the swap as a typed test-only operationand restoration is automatic if the test raises."""file = _file("doc-a", "a.pdf")diff --git a/engine/tests/contradiction/test_review_integration.py b/engine/tests/contradiction/test_review_integration.pyindex 51038790a3..aa44214ea7 100644--- a/engine/tests/contradiction/test_review_integration.py+++ b/engine/tests/contradiction/test_review_integration.py@@ -82,7 +82,7 @@ def _report(*contradictions: Contradiction) -> ContradictionReport:def runtime_with_stub_docs(runtime: AppRuntime) -> AppRuntime:"""Runtime with a non-network DocumentService backed by stub embedder + ephemeral store."""stub = DocumentService(- embedder=StubEmbedder(), # type: ignore[arg-type]+ embedder=StubEmbedder(), # pyrefly: ignore [bad-argument-type]store=SqliteVecStore.ephemeral(),default_top_k=runtime.settings.rag_default_top_k,)@@ -129,7 +129,7 @@ async def test_localiser_prompt_escapes_verdict_tag_injection(return _R()- agent._contradiction_localiser.run = _capture # type: ignore[method-assign]+ agent._contradiction_localiser.run = _capture # pyrefly: ignore [bad-assignment]await agent._build_contradiction_comments_payload("the prompt", report)assert len(captured_prompts) == 1@@ -232,7 +232,7 @@ async def test_contradiction_intent_emits_add_comments_plan(assert step.tool == ToolEndpoint.ADD_COMMENTS# The orchestrator step's ``parameters`` field is a discriminated# union of every tool's params; narrow to the concrete shape we- # know we just produced so pyright doesn't see ``.comments`` as+ # know we just produced so pyrefly doesn't see ``.comments`` as# an attribute lookup against an unrelated CbrToPdfParams (etc.).assert isinstance(step.parameters, AddCommentsParams)serialised = step.parameters.commentsdiff --git a/engine/tests/docparse/test_ingest.py b/engine/tests/docparse/test_ingest.pyindex 533adf3c03..4b111bbfdc 100644--- a/engine/tests/docparse/test_ingest.py+++ b/engine/tests/docparse/test_ingest.py@@ -218,7 +218,11 @@ def test_ingest_rejects_empty_document_id(client: TestClient) -> None:@pytest.mark.anyioasync def test_ingest_reingest_replaces_instead_of_duplicating() -> None:- service = DocumentService(embedder=StubEmbedder(), store=SqliteVecStore.ephemeral(), default_top_k=3) # type: ignore[arg-type]+ service = DocumentService(+ embedder=StubEmbedder(), # pyrefly: ignore [bad-argument-type]+ store=SqliteVecStore.ephemeral(),+ default_top_k=3,+ )app.dependency_overrides[get_document_service] = lambda: servicetry:client = TestClient(app)diff --git a/engine/tests/ledger/test_models.py b/engine/tests/ledger/test_models.pyindex 98b0ef9c85..68a0f55ce0 100644--- a/engine/tests/ledger/test_models.py+++ b/engine/tests/ledger/test_models.py@@ -35,11 +35,10 @@ def test_folio_manifest_round_trip() -> None:assert reloaded == manifest-def test_folio_manifest_round_bounds() -> None:[email protected]("round_value", [0, 4])+def test_folio_manifest_round_bounds(round_value: int) -> None:with pytest.raises(ValidationError):- FolioManifest(session_id="x", page_count=1, folio_types=[FolioType.TEXT], round=0)- with pytest.raises(ValidationError):- FolioManifest(session_id="x", page_count=1, folio_types=[FolioType.TEXT], round=4)+ FolioManifest(session_id="x", page_count=1, folio_types=[FolioType.TEXT], round=round_value)# ---------------------------------------------------------------------------diff --git a/engine/tests/ledger/test_routes.py b/engine/tests/ledger/test_routes.pyindex ca322a6364..535bf1819b 100644--- a/engine/tests/ledger/test_routes.py+++ b/engine/tests/ledger/test_routes.py@@ -12,6 +12,7 @@ from collections.abc import Iteratorfrom decimal import Decimalimport pytest+from conftest import build_app_settingsfrom fastapi.testclient import TestClientfrom stirling.api import app@@ -34,8 +35,6 @@ from stirling.contracts.ledger import (class StubSettingsProvider:def __call__(self) -> AppSettings:- from conftest import build_app_settings-return build_app_settings()diff --git a/engine/tests/test_config_routes.py b/engine/tests/test_config_routes.pyindex 37b3b4ef38..5170b3a56f 100644--- a/engine/tests/test_config_routes.py+++ b/engine/tests/test_config_routes.py@@ -45,7 +45,7 @@ def _client(app.dependency_overrides[load_settings] = previous-def _anthropic_push() -> dict[str, object]:+def _anthropic_push() -> dict[str, dict[str, object]]:return {"models": {"provider": "anthropic",@@ -134,7 +134,7 @@ def test_config_push_unsupported_provider_returns_400_without_swap() -> None:with _client(build_app_settings) as client:before = app.state.runtimepayload = _anthropic_push()- payload["models"]["provider"] = "nonsense-provider" # type: ignore[index]+ payload["models"]["provider"] = "nonsense-provider"response = client.post("/api/v1/config", json=payload)assert response.status_code == 400# Running runtime is untouched when the push is rejected.@@ -226,7 +226,7 @@ def test_config_push_ignores_unknown_fields() -> None:with _client(build_app_settings) as client:payload = _anthropic_push()payload["futureTopLevelField"] = {"anything": 1}- payload["models"]["experimentalFlag"] = True # type: ignore[index]+ payload["models"]["experimentalFlag"] = Trueresponse = client.post("/api/v1/config", json=payload)assert response.status_code == 200assert app.state.settings.smart_model_name == "claude-haiku-4-5"@@ -292,7 +292,7 @@ def test_config_push_rejects_out_of_range_numbers(section: str, field: str, valu"""Out-of-range numbers are rejected by the contract before anything is applied."""with _client(build_app_settings) as client:payload = _anthropic_push()- payload[section][field] = value # type: ignore[index]+ payload[section][field] = valueresponse = client.post("/api/v1/config", json=payload)assert response.status_code == 422# Nothing was applied: the engine is still on its env config.@@ -304,7 +304,7 @@ def test_config_push_allows_zero_max_searches() -> None:"""0 searches is a legitimate "no retrieval" setting, not an out-of-range value."""with _client(build_app_settings) as client:payload = _anthropic_push()- payload["rag"]["maxSearches"] = 0 # type: ignore[index]+ payload["rag"]["maxSearches"] = 0response = client.post("/api/v1/config", json=payload)assert response.status_code == 200assert app.state.settings.rag_max_searches == 0diff --git a/engine/tests/test_documents.py b/engine/tests/test_documents.pyindex bee93a134e..0b08ac7f27 100644--- a/engine/tests/test_documents.py+++ b/engine/tests/test_documents.py@@ -279,7 +279,11 @@ class StubEmbeddingService:def documents() -> DocumentService:"""Each DocumentService test gets its own fresh ephemeral store to avoid dimension conflicts."""store = SqliteVecStore.ephemeral()- return DocumentService(embedder=StubEmbeddingService(), store=store, default_top_k=3) # type: ignore[arg-type]+ return DocumentService(+ embedder=StubEmbeddingService(), # pyrefly: ignore [bad-argument-type]+ store=store,+ default_top_k=3,+ )def _pages(text: str) -> list[PageText]:@@ -508,7 +512,7 @@ async def _invoke_search_knowledge(capability: RagCapability, query: str, max_retoolset = capability.toolsetassert isinstance(toolset, FunctionToolset)tool = toolset.tools["search_knowledge"]- return await tool.function(query=query, max_results=max_results) # type: ignore[call-arg]+ return await tool.function(query=query, max_results=max_results)class TestRagCapability:@@ -637,12 +641,24 @@ class TestRagCapability:cap = RagCapability(documents, principals=OWNER_PRINCIPALS, max_searches=2)tool_def = _dummy_tool_def()- assert await cap._prepare_search_knowledge(None, tool_def) is tool_def # type: ignore[arg-type]+ assert (+ await cap._prepare_search_knowledge(+ None, # pyrefly: ignore [bad-argument-type]+ tool_def, # pyrefly: ignore [bad-argument-type]+ )+ is tool_def+ )await _invoke_search_knowledge(cap, "content")await _invoke_search_knowledge(cap, "content")- assert await cap._prepare_search_knowledge(None, tool_def) is None # type: ignore[arg-type]+ assert (+ await cap._prepare_search_knowledge(+ None, # pyrefly: ignore [bad-argument-type]+ tool_def, # pyrefly: ignore [bad-argument-type]+ )+ is None+ )def _dummy_tool_def() -> object:@@ -660,7 +676,7 @@ def test_many_stores_open_the_same_file_without_locking_out(tmp_path: Path) -> Ndb_path = tmp_path / "rag.db"with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:- stores = list(pool.map(lambda _: SqliteVecStore(db_path), range(8)))+ stores = list(pool.map(SqliteVecStore, [db_path] * 8))assert len(stores) == 8mode = stores[0]._conn.execute("PRAGMA journal_mode").fetchone()[0]diff --git a/engine/tests/test_documents_routes.py b/engine/tests/test_documents_routes.pyindex 4f317bb320..fd41f7f354 100644--- a/engine/tests/test_documents_routes.py+++ b/engine/tests/test_documents_routes.py@@ -49,7 +49,7 @@ class StubEmbedder:def _build_service() -> DocumentService:return DocumentService(- embedder=StubEmbedder(), # type: ignore[arg-type]+ embedder=StubEmbedder(), # pyrefly: ignore [bad-argument-type]store=SqliteVecStore.ephemeral(),default_top_k=3,)diff --git a/engine/tests/test_pdf_question_agent.py b/engine/tests/test_pdf_question_agent.pyindex c26d4b5046..3c6fe375e4 100644--- a/engine/tests/test_pdf_question_agent.py+++ b/engine/tests/test_pdf_question_agent.py@@ -85,7 +85,7 @@ class StubPdfQuestionAgent(PdfQuestionAgent):def runtime_with_stub_rag(runtime: AppRuntime) -> AppRuntime:"""A runtime whose document service uses a stub embedder + ephemeral store."""stub = DocumentService(- embedder=StubEmbedder(), # type: ignore[arg-type]+ embedder=StubEmbedder(), # pyrefly: ignore [bad-argument-type]store=SqliteVecStore.ephemeral(),default_top_k=runtime.settings.rag_default_top_k,)diff --git a/engine/uv.lock b/engine/uv.lockindex a4bab33f4a..2c4eb62709 100644--- a/engine/uv.lock+++ b/engine/uv.lock@@ -1,5 +1,5 @@version = 1-revision = 5+revision = 3requires-python = "==3.13.*"[[package]]@@ -414,7 +414,6 @@ wheels = [name = "engine"version = "0.1.0"source = { editable = "." }-default-groups = [][package.dev-dependencies]cucumber = [@@ -446,7 +445,7 @@ engine = [engine-dev = [{ name = "anyio" },{ name = "datamodel-code-generator", extra = ["ruff"] },- { name = "pyright" },+ { name = "pyrefly" },{ name = "pytest" },{ name = "referencing" },{ name = "ruff" },@@ -505,7 +504,7 @@ engine = [engine-dev = [{ name = "anyio", specifier = ">=4.14.2" },{ name = "datamodel-code-generator", extras = ["ruff"], specifier = "==0.64.0" },- { name = "pyright", specifier = ">=1.1.411" },+ { name = "pyrefly", specifier = "==1.4.1" },{ name = "pytest", specifier = ">=9.1.1" },{ name = "referencing", specifier = ">=0.37.0" },{ name = "ruff", specifier = "==0.15.5" },@@ -821,15 +820,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/79/7b/2c79738432f5c924bef5071f933bcc9efd0473bac3b4aa584a6f7c1c8df8/mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505", size = 4963, upload-time = "2025-04-22T14:54:22.983Z" },]-[[package]]-name = "nodeenv"-version = "1.10.0"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/24/bf/d1bda4f6168e0b2e9e5958945e01910052158313224ada5ce1fb2e1113b8/nodeenv-1.10.0.tar.gz", hash = "sha256:996c191ad80897d076bdfba80a41994c2b47c68e224c542b48feba42ba00f8bb", size = 55611, upload-time = "2025-12-20T14:08:54.006Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/88/b2/d0896bdcdc8d28a7fc5717c305f1a861c26e18c05047949fb371034d98bd/nodeenv-1.10.0-py2.py3-none-any.whl", hash = "sha256:5bb13e3eed2923615535339b3c620e76779af4cb4c6a90deccc9e36b274d3827", size = 23438, upload-time = "2025-12-20T14:08:52.782Z" },-]-[[package]]name = "numpy"version = "2.5.2"@@ -1236,16 +1226,22 @@ wheels = [][[package]]-name = "pyright"-version = "1.1.411"+name = "pyrefly"+version = "1.4.1"source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "nodeenv" },- { name = "typing-extensions" },-]-sdist = { url = "https://files.pythonhosted.org/packages/7e/ab/265f7dc69d28113ebba19092e57b075f41543b2ed048429c5f56e2b88eac/pyright-1.1.411.tar.gz", hash = "sha256:d885a0551f2e763b089a02702174e7f4ba77548cddabc972ab86d1f7f1b0f998", size = 4112861, upload-time = "2026-06-25T02:14:06.37Z" }+sdist = { url = "https://files.pythonhosted.org/packages/ac/30/e9fb605e82022f941c556076088467ddad59800a7ae7b510d4317088ddab/pyrefly-1.4.1.tar.gz", hash = "sha256:1ef91afbaca15336482dd21292974f64a735268ce4990d59e87162d5a097106d", size = 6970842, upload-time = "2026-11-05T02:44:12.316Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/0a/49/385be530a6a5b78d1cbcd5c2e38debc8959a2fc6bdb716f4e581002979fc/pyright-1.1.411-py3-none-any.whl", hash = "sha256:dc7c72a8e2700c55baa127554040e067041ea53ccfd50bf96308cc4291c7d5d9", size = 6181526, upload-time = "2026-06-25T02:14:04.691Z" },+ { url = "https://files.pythonhosted.org/packages/c5/a1/736ef07aa3c87e7db31d246024a98cb6fbf6d48e52784025758f19cca02d/pyrefly-1.4.1-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:9c5a4a3f0ec00ae66a13f5741c355980685111b7008289c0b850e9be931aa3fa", size = 15720162, upload-time = "2026-11-05T02:43:40.304Z" },+ { url = "https://files.pythonhosted.org/packages/0f/9a/0cc181ebbde26f63e96a61fcb4d6262342017cb83fa34f494a13134de6c5/pyrefly-1.4.1-py3-none-macosx_11_0_arm64.whl", hash = "sha256:eaba21336993765373e7e888de90f4d58214ce38994804eef902a6c8148df21f", size = 14994348, upload-time = "2026-11-05T02:43:42.998Z" },+ { url = "https://files.pythonhosted.org/packages/ad/7c/bba5e480eb1620b864e45f7551f7e5014351eb42be4e6b5f0dd036b15071/pyrefly-1.4.1-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:8363f888f19b53d4b40e54d89e65b127ea68cd1cf8604de2824dffdc9d7900e9", size = 15454572, upload-time = "2026-11-05T02:43:45.291Z" },+ { url = "https://files.pythonhosted.org/packages/6b/1b/05f9e265e5b331a23b5a50604e4d4bb25ecb31cf47f37048a765b6c1edf1/pyrefly-1.4.1-py3-none-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:4a1d892483bda655a206b4a7578ab36aebaaf89799a7a9d29d22c0bbdc1b6ba0", size = 16874119, upload-time = "2026-11-05T02:43:48.039Z" },+ { url = "https://files.pythonhosted.org/packages/7a/1e/b85dbfe3cc01585ed153af013aa8685b2970addba454fb257561c411fb87/pyrefly-1.4.1-py3-none-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:5353f958134522a5c45d846825b49e0049dafd73022f68d0db9e54242b3f7eeb", size = 16764013, upload-time = "2026-11-05T02:43:50.495Z" },+ { url = "https://files.pythonhosted.org/packages/2f/c5/0f1a9d1ad13a74e4efcbb8a94a89381e56dfff0d4dceeba8a9f633901c75/pyrefly-1.4.1-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:19c35e7e63a02076fc555bdb0800302b89bb419e3de2814ab8274c0c6ac00158", size = 16079223, upload-time = "2026-11-05T02:43:52.714Z" },+ { url = "https://files.pythonhosted.org/packages/e2/c8/8fd47bfa2e8ab300dcfd4f1d15ef6bd4ed6290ba082a98597d8e8bcd2153/pyrefly-1.4.1-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:6035b0ff640a8e7d751f31e520b3b0dc6bb42c76a57cd43819ca0e9354cd37fe", size = 15473203, upload-time = "2026-11-05T02:43:55.149Z" },+ { url = "https://files.pythonhosted.org/packages/fe/02/3cf7cf460924951891fcbc491f0667c7940e14918ef87a51d9a852bd481a/pyrefly-1.4.1-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:c49122412a990469ee0a9e5a50dd38f6990e42f903b3cc0f7dcf0c7a84997c65", size = 16135278, upload-time = "2026-11-05T02:43:57.334Z" },+ { url = "https://files.pythonhosted.org/packages/9e/ec/0047ba1b722015f95568f28be61928c997fdd4d2e7b78b63e2bb5b8446a2/pyrefly-1.4.1-py3-none-win32.whl", hash = "sha256:dbd065dbdc920b5e1d03bd8f035f59dae4379332ca854df8fe7ddccc43059533", size = 14873931, upload-time = "2026-11-05T02:44:04.64Z" },+ { url = "https://files.pythonhosted.org/packages/5a/d2/5b855b69afc9401f2434abe3e2ded05f3c78905d478beecad05117b2329a/pyrefly-1.4.1-py3-none-win_amd64.whl", hash = "sha256:49d2ac460fffbe5b8e0c20e991bf87978805d7aba3bb7f04d9b53a1a0e1d6430", size = 15741940, upload-time = "2026-11-05T02:44:07.193Z" },+ { url = "https://files.pythonhosted.org/packages/13/84/33b63735654fc3258ee74bbe4a4a6d587c4a0334ba9e8eb17a8d8107bddc/pyrefly-1.4.1-py3-none-win_arm64.whl", hash = "sha256:3b5abcceca279973fa7312c958c06ee760a1b4a3feb9f3b89fd4520e53658aef", size = 14956758, upload-time = "2026-11-05T02:44:09.845Z" },][[package]]