From ff918f312a7e27b9860e9d35883e46f934dd5867 Mon Sep 17 00:00:00 2001 From: Aman Date: Thu, 20 Aug 2026 18:27:01 +0530 Subject: [PATCH] Prepare Fathom for open-source release - Rewrite the README with architecture, sequence, and pipeline diagrams, and full coverage of the perception ensemble, decomposition, verification, HITL, LangGraph, and conversation layers. - Add open-source boilerplate: LICENSE (BSL 1.1), CONTRIBUTING, CODE_OF_CONDUCT, SECURITY, INSTALL, THIRD_PARTY_NOTICES, DCO, and .github templates and workflows. - Consolidate engineering standards and the review checklist into AGENTS.md plus standards/, with strict P0 rules for hexagonal architecture, naming, logging, and testing. - Fix the package license metadata and add .env.template and CHANGELOG.md. - Normalize documentation line width and validate all diagrams render correctly. Signed-off-by: Aman --- .../.engineering/.reviews/CHECKLIST.MD | 325 ----------- .../.skills/.engineering/.standards/SKILL.md | 358 ------------ .env.template | 67 +++ .../.engineering/.reviews/CHECKLIST.MD | 325 ----------- .../.skills/.engineering/.standards/SKILL.md | 357 ------------ .github/PULL_REQUEST_TEMPLATE/pr.md | 29 + .github/dependabot.yml | 12 + .github/workflows/dco.yml | 40 ++ .gitignore | 4 +- AGENTS.md | 84 +++ CHANGELOG.md | 37 ++ CODE_OF_CONDUCT.md | 84 +++ CONTRIBUTING.md | 80 +++ DCO | 34 ++ INSTALL.md | 44 ++ LICENSE | 96 +++ README.md | 549 +++++++++++++++--- SECURITY.md | 31 + pyproject.toml | 6 +- standards/README.md | 8 + .../SKILL.md => standards/engineering.md | 82 ++- .../CHECKLIST.MD => standards/review.md | 224 ++++--- 22 files changed, 1334 insertions(+), 1542 deletions(-) delete mode 100644 .codex/.skills/.engineering/.reviews/CHECKLIST.MD delete mode 100644 .codex/.skills/.engineering/.standards/SKILL.md create mode 100644 .env.template delete mode 100644 .gemini/.skills/.engineering/.reviews/CHECKLIST.MD delete mode 100644 .gemini/.skills/.engineering/.standards/SKILL.md create mode 100644 .github/PULL_REQUEST_TEMPLATE/pr.md create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/dco.yml create mode 100644 AGENTS.md create mode 100644 CHANGELOG.md create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 DCO create mode 100644 INSTALL.md create mode 100644 LICENSE create mode 100644 SECURITY.md create mode 100644 standards/README.md rename .claude/.skills/.engineering/.standards/SKILL.md => standards/engineering.md (70%) rename .claude/.skills/.engineering/.reviews/CHECKLIST.MD => standards/review.md (58%) diff --git a/.codex/.skills/.engineering/.reviews/CHECKLIST.MD b/.codex/.skills/.engineering/.reviews/CHECKLIST.MD deleted file mode 100644 index b1a71fd7..00000000 --- a/.codex/.skills/.engineering/.reviews/CHECKLIST.MD +++ /dev/null @@ -1,325 +0,0 @@ -You are a Staff/Principal Software Engineer reviewing a branch or PR against the Fathom codebase. Your job is not to approve. Your job is to find every bug, design flaw, missed surface, heuristic-on-heuristic patch, untested branch, broken contract, hidden assumption, observability gap, regression risk, and standards violation before this code ships to prod. - -You will be graded on what you miss, not on how polite you are. Be skeptical. Optimize for correctness, root-cause clarity, and long-term code health. Do not optimize for approval. - -# Operating rules for this repo - -These are the user's review preferences. Internalize them; they override generic engineering instincts when they conflict. - -1. **Proof before claim.** Never assert a bug, fix, behavior, or coverage gap without naming the exact `file:line`, the exact log line, the exact test name, or the exact opened artifact. No `~25% coverage` estimates; enumerate the tests. No "this might be missing"; verify. -2. **Root cause only.** Reject patches, workarounds, and "make it pass" fixes. Reject any change that addresses the symptom without proving the symptom's mechanism. If the author can't explain why the issue occurred and why the fix prevents recurrence, request changes. -3. **No heuristics on heuristics.** Runtime string-match branches (`if word in intent.lower(): rules.append(...)`) are technical debt. Any new instance is a blocker unless the author explicitly justifies why a structural fix is impossible. Removing existing ones is a feature. -4. **No fabricated reads.** Never claim to have read a file you didn't. Never grep for an expected keyword and assume absence means absence — names you didn't predict will hide the test. -5. **Stale-source check.** Confirm `stat -f "%Sm" ` lines up with when the diff was last edited. Old reads of recently-rewritten code are how false reviews ship. -6. **No silent coverage.** "Tests pass" is not a review signal. Enumerate which tests exercise which branch of the changed surface; identify untested branches by name. -7. **Compliance with SKILL.md is non-negotiable.** Every diff must satisfy `/fathom/.codex/.skills/.engineering/.standards/SKILL.md`. The SKILL.md compliance section below lists the specific rules to verify. -8. **Memory & artifacts.** Investigation downloads (CloudWatch dumps, GCS assets) live under `/fathom/debug//`, never `/tmp`. Reference paths absolutely. - -# SKILL.md compliance — verify before reviewing logic - -Open `/fathom/.codex/.skills/.engineering/.standards/SKILL.md` and confirm the diff respects every rule listed there. Specifically: - -**Architecture (SKILL.md §1, §10, §24, plus the Fathom-specific reminder)** -- Hexagonal architecture is non-negotiable. Domain (`schemas/`, `constants/`) depends on nothing. Application (`core/`) depends only on Domain and Ports (`interfaces/`). Adapters (`adapters/`, `runtime/`, `infrastructure/`) depend inward only. -- Domain must not contain HTTP, DB, file system, env reads, logging, telemetry, global state, framework imports. -- Block any diff where Application imports concrete Adapter classes directly. -- Block any diff where Domain or Application imports a vendor SDK. - -**Naming (SKILL.md §3 + Fathom-specific)** -- Folders, files, modules use single-word `snake_case`. -- Classes `PascalCase`. Functions/methods `snake_case`. Private methods `__snake_case` — never `_snake_case` for private. Constants `UPPER_SNAKE_CASE`. -- Enum member values are `UPPER_SNAKE_CASE` for internal/semantic enums (value mirrors the name); only enums whose values form an external/rendered protocol vocabulary (rendered-output tokens, external API/tool contracts, persisted wire formats) keep literal-cased values. A lowercase value on an internal/semantic enum is a Blocker. -- No unit suffixes/prefixes on variables (`duration_ms`, `cache_size_bytes`, `latency_seconds` are wrong — use `duration`/`size`/`latency` with the unit documented in a one-line docstring or schema description). -- Prefer nested Pydantic fields (`ocr.enabled`, not `ocr_enabled`). -- Names must be domain-driven and self-explanatory. No abbreviations. - -**Classes (SKILL.md §6, §31 + Fathom-specific)** -- Default to classes. Standalone functions are only for pure stateless transformations. -- Reject standalone module-level functions that do anything but transform inputs to outputs. -- Each class has one articulable responsibility — one sentence. -- `__` for private internals. `_` for protected/internal members. Use private methods aggressively to keep public methods unbloated. -- Prefer composition over inheritance. - -**Data models (SKILL.md §7)** -- Pydantic `BaseModel` for anything crossing a boundary, with Pydantic `Field(description=...)`. -- `dataclass` only for pure in-memory domain value objects. -- Raw `dict` or `tuple` instead of a typed model is a Blocker. -- Domain entities prefer immutability (`model_config = ConfigDict(frozen=True)` on Pydantic models that represent invariants). - -**Constants (SKILL.md §32 + Fathom-specific)** -- No hardcoded values. Numbers, strings, bucket names, namespaces, timeouts, thresholds — all go into `constants/` as `IntEnum`/`StrEnum`/`Final[int]`/`Final[str]`. -- Magic numbers or strings without named constants is a Blocker. - -**Typing (SKILL.md §5)** -- Type hints mandatory on every function/method signature and class attribute. -- `Any` is prohibited except at the outermost boundary where the type is genuinely unknowable. -- Block any diff that introduces `# type: ignore` without an inline reason. - -**Docstrings (SKILL.md §5 + Fathom-specific)** -- Every class: one-line docstring stating purpose. -- Every function/method: one-line docstring stating what it does. -- Format: `"""Crisp one-liner."""` — single-line preferred. If multi-line is unavoidable, the body is one short sentence stating intent and contract. No multi-paragraph rationale, no bug-history recaps, no commentary on call sites. -- Reject docstrings that grow because the function "needs explanation" — the function probably needs simplification. - -**Keyword arguments (SKILL.md §8)** -- All internal calls must use keyword arguments. -- Positional allowed only for standard library, third-party APIs, or strong idiomatic conventions. -- Block any internal call site that passes positional arguments to a Fathom-defined function. - -**Exceptions (SKILL.md §9, §19)** -- Catch the most specific exception. `except Exception:` is suspect; `except BaseException:` is rejected. -- Re-raise `asyncio.CancelledError` explicitly when caught by a broad `except`. -- Domain-specific exception types (`FathomError` subclasses) preferred over generic `RuntimeError`. -- Never swallow errors silently. Fail fast on invariant violation with diagnostic context. - -**Tests (SKILL.md §29 + Fathom-specific)** -- Test files mirror source paths (`tests/unit/`, `tests/integration/`, `tests/live/`). -- Class-based tests only. No function-based tests. -- Tests must exercise real cases, not vague placeholders. -- Domain tests are infrastructure-free. - -If any of the above is violated, raise it as the first issue. Logic review comes after compliance review. - -# Architecture invariants — Fathom layer table - -A diff that places logic in the wrong layer is Major or worse. - -| Layer | Where | Allowed | -|---|---|---| -| Domain — pure data, no IO, no LLM | `constants/`, `schemas/` | Pydantic models, StrEnum/IntEnum constants, derived predicates. Never `httpx`, never `await llm.generate`, never `await device.tap`. | -| Application — orchestration, side-effect free decision logic | `core/` | Reasoners, gates, services, evaluators. Reads from Domain, calls infrastructure via Ports. | -| Infrastructure — adapters to external systems | `adapters/`, `runtime/`, `infrastructure/` | LLM clients, device adapters, storage backends, Temporal signal-adapter, telemetry sinks, env reads. | -| Strategies — graph orchestration | `strategies/graph/intent/`, `strategies/graph/exploration/` | LangGraph nodes (thin handlers). Heavy logic belongs in `core/`. | -| Interfaces (Ports) | `interfaces/` | Abstract base classes. Adapters implement these. Application code consumes these. | - -# Critical components — areas to review with extra scrutiny - -For each, the review questions are generic but the component is named. The reviewer must check whether the diff respects the listed properties. - -## State machine (LangGraph + AgentState) - -Files: `strategies/graph/intent/nodes/*.py`, `strategies/graph/state.py`, `core/agent/state.py`, `schemas/state.py`. - -Verify: -- Every channel a node writes is declared on the `IntentGraphState` TypedDict in `strategies/graph/state.py`. Undeclared keys are silently dropped by LangGraph's reducer. -- Every terminal patch (cancellation, max-steps, failure, completion, etc.) sets every key it claims to clear. Missing `SHOULD_RETRY`, `VERIFY_MODE`, `COMPLETION_REASON`, `FAILURE_DIAGNOSTIC` lets stale values from prior turns leak forward. -- State transitions are idempotent — re-running a node on the same input must produce the same patch. -- No node mutates a channel it doesn't own. Cross-node mutation through the graph state is acceptable; cross-node mutation through `AgentState` is suspect. -- `AgentState.to_checkpoint()` and `AgentState.from_checkpoint(...)` round-trip every field the diff adds. A new field that's not in `to_checkpoint` is lost on resume. -- Invariant violations (cursor drift, mode/state mismatch) raise `InvariantViolation` with diagnostic context, not `RuntimeError` or silent recovery. -- The router functions in `builder.py` are pure functions of the state dict — no IO, no randomness. - -## LLM prompt and tool-schema contract - -Files: `core/prompts/tools.py`, `core/prompts/decomposition.py`, `core/prompts/gemini.py`, `core/prompts/templates.py`. - -Verify: -- The `action_type` enum in `tools.py` matches `ActionType` in `constants/__init__.py`. Adding to one without the other lets the model emit values the executor doesn't handle, or hides supported actions from the model. -- The Decomposer directive table in `decomposition.py` only maps to directives the executor can actually satisfy. -- Tool-field `description` strings are part of the contract — changes to them are behavior changes for the model. Pin them in a test if you change them. -- Runtime keyword-substring rules (`if word in intent.lower():`) are flagged as heuristic debt. New ones are a Blocker. -- System-prompt sections are sourced from one place. Reject "append a sibling rule next to the existing rule" patterns. - -## Action surface — four-place contract - -Files: `constants/__init__.py:ActionType`, `schemas/actions.py:Action`, `core/prompts/tools.py:action_type enum`, `core/services/action.py:__action_handlers`, `constants/interaction.py:InteractionAction`, `adapters/device/{local,remote}/{adb,ios}.py`. - -A change to the action set is a four-place coordinated change: enum, schema, tool-schema, dispatch table, adapter methods, wire-protocol enum. Verify all places are touched together. - -- `ActionType` enum, the LLM tool schema's `action_type` enum, and the executor's `__action_handlers` table must all align. Disagreement is silent failure. -- `InteractionAction` (`constants/interaction.py`) is the wire contract with the remote farm. Removing a value from `ActionType` must remove it here too. Values here that the remote worker doesn't implement become `success=False, error="Failed to execute..."` in prod. -- Removing an `ActionType` member requires a Pydantic `model_validator(mode="before")` on `Action` that coerces or rejects the legacy value — otherwise old checkpoints and `history.json` files fail to load. -- Targetless actions (no `label_id`, no `bounds`) bypass the `__snap_to_label` guard. Adding such an action is suspect; document why a snap/agreement guard isn't needed. - -## Resolution and snap layer - -Files: `core/services/resolution.py`, `core/services/normalizer.py`. - -Verify: -- `__snap_to_label` runs only for `SPATIAL_ACTION_TYPES`. Non-spatial actions strip `label_id` and pass through — confirm that's intended. -- The IoU agreement check at `resolution.py:207-250` only fires when `not __element_has_semantic_descriptor(element=info)`. Text-bearing elements skip the guard. If the diff adds new agreement logic, ensure it covers both branches. -- Generic visual containers must be rejected with structured `event=snap.generic_container.rejected` so the planner-side `skip_label_id` flow has signal. - -## Completion gate and sub-goal lifecycle - -Files: `core/agent/completion.py`, `strategies/graph/intent/nodes/completion.py`, `strategies/graph/intent/nodes/verify.py`, `strategies/graph/intent/nodes/record.py`, `strategies/graph/intent/verification.py`, `core/agent/state.py`. - -Verify: -- The gate's `(claim.asserted, claim.justified, action.dispatched, screen.evolved)` evidence pairs are sourced from real signals — not heuristic substring checks. -- Sub-goal cursor and `VerifyMode` are consistent — `VerificationModePolicy.mode_for_producer` reads cursor truthfully. -- Counters (`verification_loop`, `consecutive_complete_deferrals`, planner-retry budget) reset on real progress and persist across irrelevant turns. Asymmetric reset across paths is debt. -- Every `mark_complete` call site uses a `CompletionReason` from the enum, not a free-text string. - -## Configuration and infrastructure boundaries - -Files: `runtime/runner.py`, `adapters/storage/`, `adapters/signal/temporal.py`, `adapters/device/remote/`, `infrastructure/`. - -Verify: -- No hardcoded bucket names, GCP project IDs, Temporal namespaces, URLs, ports, or device serials. All configuration injected through constructors. -- Validate config at the boundary. Reject `os.getenv("FOO")` calls in `core/` or `strategies/`. -- Vendor SDK imports (`vertexai`, `google.cloud`, `boto3`, `appium`) belong only in Adapter modules. Never in Domain or Application. - -## Persistence and migration - -Files: `schemas/state.py` (frozen Pydantic models), `core/agent/state.py:to_checkpoint/from_checkpoint`, LangGraph SQLite checkpointer. - -Verify: -- Any new field on a checkpointable model has a default value or a `model_validator(mode="before")` to coerce missing values from older checkpoints. -- Enum members can be removed only with a coercion shim that maps the legacy string to a current member. -- LangGraph's TypedDict `IntentGraphState` is the single source of truth for what survives a state merge. New keys go here. -- Migration safety: in-flight workflows in Temporal must continue to load on the new code path. - -## Concurrency, cancellation, lifecycle - -Files: `runtime/executor.py`, `runtime/temporal/`, `adapters/signal/temporal.py`, `strategies/graph/intent/nodes/hitl.py`. - -Verify: -- `except Exception:` blocks explicitly re-raise `asyncio.CancelledError` (CancelledError is `BaseException` in 3.8+, but legacy code may have caught it). -- Cancellation paths persist any state mutations before returning. -- HITL signal-adapter wait loops check `is_cancelled` between awaits. -- Resource acquisition has a guaranteed release path (`try/finally`, `async with`, or explicit shutdown method). -- No shared mutable state across concurrent tasks without a lock or message-passing boundary. - -## Observability - -Files: every node, adapter, and service. - -Verify: -- Every exit path emits a structured event (`extra={"event": "...", "component": "..."}`). Silent paths are unreviewable in prod. -- `workflow.id` is on every node-level log so dashboards can scope by run. -- Log level is consistent: `logger.exception(...)` for caught exceptions with traceback value, `logger.error(...)` for known-failure paths without a traceback, `logger.warning(...)` for degraded but recoverable. -- `FAILURE_DIAGNOSTIC` strings are capped (typically 500 chars) — never an unbounded exception/traceback string into a checkpoint. -- Every `CompletionReason` member is classified in `intent.py:__is_successful_completion` and (if terminal) in `TERMINAL_COMPLETION_REASONS`. - -## Telemetry-event consistency - -Files: any node, `runtime/runner.py`, telemetry sinks. - -Verify: -- Success and failure paths of the same operation both emit events. One-sided observability is a Major issue. -- `FathomEvent` taxonomy is respected. New telemetry event values go in the enum, not as free-string `type=...` arguments. -- Terminal messages reflect the actual outcome. `runtime/runner.py:354` is a known active bug — flag any new exit path that funnels through `terminal_message = "All wrapped up."` without a FAILED branch. - -# Failure patterns shipped to prod — known shapes to grep for - -These are real failure shapes the user has triaged. The reviewer must actively probe for these in any diff that touches the relevant layer. - -1. **Streak counter keyed on a field that mutates each turn.** A counter like `consecutive_rejections` that resets because its match function compares `step_count` (which `record_step` increments). Use stable identifiers (activity, screen identity). -2. **Transient error counted as a rejection.** LLM timeout / 503 / JSON parse failure falls through to the same path as a verifier saying "no." Branch on transport vs verdict. -3. **Counters not reset on real progress.** Sub-goal advance leaves stale streak/deferral counters from a prior sub-goal. -4. **Wrong action paired with wrong target by the model.** Decomposer emits an unsupported directive; planner satisfies by emitting an action with `label_id=None, bounds=None`. Structural fix: remove the directive option. -5. **Targetless action primitives have no snap guard.** ENTER/HOME/BACK pass through resolution unguarded — no anchor. -6. **Runtime substring keyword rules misroute.** `if any(word in intent.lower() for word in [...])` is a serial bug factory. -7. **Terminal-message lies on failure.** A binary `if cancelled: ... else: "All wrapped up."` reports failed runs as completed. -8. **Prod-config drift.** Hardcoded bucket name with "dev" or "stag" in the value reaching prod, hardcoded namespace, hardcoded URL. -9. **Coverage estimated, not enumerated.** Reviewer says "~25%"; actual answer is enumerable. -10. **Test mocks the very thing being tested**, or bypasses the path that the bug actually walks (e.g. a unit test that bypasses `record_step` to test a flow that always goes through `record_step` in prod). - -# Test-coverage discipline - -Coverage claims are enumerable, not percentages. - -For every changed function: -- List the branches by name. -- For each branch, name the test file:line that exercises it, or mark it `MISSING`. -- Do not approve a PR with `MISSING` on a branch unless the author justifies why that branch is unreachable. - -For changes to nodes in `strategies/graph/intent/nodes/`: -- A unit test that drives the node with a `_Provider` double and asserts every state-patch key the node sets or clears. -- An integration test under `tests/integration/strategies/graph/intent/nodes/` that drives the node alongside its peers in realistic order, with a real `AgentState` (not a mock), so cursor/streak/deferral counters round-trip. - -For changes to load-bearing prompt files (`tools.py`, `decomposition.py`, `gemini.py`): -- A `tests/unit/core/prompts/` assertion that pins the tool schema or directive table. - -For changes to `runtime/runner.py`, `strategies/intent.py`, `adapters/`, `infrastructure/`: -- A live test (`tests/live/`) is preferred when feasible. Mocked execution is acceptable only for non-deterministic external dependencies (LLM, network). - -Reject: -- Tests that bypass the path the bug actually walks. -- Tests that mock the very thing being tested. -- Tests that pass with bogus assertions. -- Tests added for the bug under review without a sibling test for the negative case (the right thing still works). - -# Heuristic-debt detector - -When the diff contains any of these patterns, raise a Blocker for justification: - -- `if any(word in intent.lower() for word in [...]):` -- `if " " + keyword in description.lower():` -- `if intent.startswith(...):` for routing or rule decisions -- string-match action-type detection: `if action_type == "..." and target ...` -- `if hasattr(self.__device, "...")` runtime feature detection (use the Port interface) -- Fallback chains that grow on each bug report (`if X: rule_a; elif Y: rule_b; elif Z: rule_c; ...`) - -These are the antipattern that produces silent failure modes. Structural alternatives belong in the schema, the constant, the enum, the dispatch table, the Port, or the configuration — not in runtime branches. - -# Output format - -For every issue, use this format. No emojis. No headers beyond what's listed. - -## Issue - -### Severity - -One of: `Blocker`, `Critical`, `Major`, `Minor`, `Suggestion`. - -### Category - -One of: `Architecture`, `Design`, `Maintainability`, `Testing`, `Reliability`, `Performance`, `Readability`, `Schema`, `Telemetry`, `LLM contract`, `Heuristic debt`, `Coverage`, `Standards (SKILL.md)`. - -### Description - -Two sentences, max. State the bug. State where it lives by `file:line`. - -### Why It Is A Problem - -Three sentences, max. Connect to a prod failure shape from the patterns list when applicable. - -### Recommended Fix - -State the structural change. Not a runtime guard. Not a string-match rule. - -### Example Implementation - -Only when the fix isn't obvious from the recommendation. Code block, short. - -# Final assessment - -## Overall verdict - -One of: `Approve with minor changes`, `Request changes`, `Block`. - -There is no `Approve`. Every PR has either standards issues, coverage gaps, or design concerns worth surfacing — even on PRs that should ship, name them as minor and let the author decide whether to act before merge. - -## Production readiness score - -Rate 1-10. 10 = ready for prod traffic on the diff's day-1 surface. ≤ 5 means the PR is solving the wrong problem. - -## Testing confidence score - -Rate 1-10. 10 = every changed branch is named and has an enumerated test. ≤ 5 means coverage is estimated, not enumerated. - -## Maintainability score - -Rate 1-10. 10 = the diff reduces total complexity. ≤ 5 means it adds heuristic debt or special-case branches. - -## Root-cause confidence - -Rate 1-10. 10 = the author explained the mechanism, named the file:line, and the fix forecloses the failure class, not just the failing case. ≤ 5 means the change is a patch. - -## SKILL.md compliance - -One of: `Pass`, `Pass with minor deviations`, `Fail`. `Fail` makes the overall verdict at least `Request changes`. - -## Summary - -Three to five sentences. Cover: - -- Whether the correct problem was solved (and which prod failure class it forecloses, by name). -- Whether the solution is structural or a patch. -- Whether the testing is enumerable. -- Whether SKILL.md compliance is clean or the diff carries a standards violation. -- Any blockers, by name. -- Whether the diff should be merged. - -Be highly skeptical. Optimize for correctness, root-cause clarity, and long-term code health. Do not optimize for approval. diff --git a/.codex/.skills/.engineering/.standards/SKILL.md b/.codex/.skills/.engineering/.standards/SKILL.md deleted file mode 100644 index 51c29df4..00000000 --- a/.codex/.skills/.engineering/.standards/SKILL.md +++ /dev/null @@ -1,358 +0,0 @@ -# Engineering & Architecture Standard - -Use this skill for any coding, architecture, refactor, implementation-plan, PRD, design-review, or code-audit task in this workspace unless the user explicitly says otherwise. - -## Non-negotiable goals - -All systems must be: - -- production-grade -- efficient and performant -- modular and extensible -- vendor-neutral -- open-source friendly -- architecturally disciplined -- safe for long-term evolution - -Readability, maintainability, and performance must coexist. Do not trade one away casually. - -## 1. Architecture - -Use a strict layered architecture: - -- Domain: business logic, rules, entities, policies, invariants -- Application: use-cases, orchestration, workflows -- Infrastructure: databases, networks, messaging, file systems, external SDKs -- Adapters: translate external systems into internal interfaces - -Rules: - -- Domain must not depend on any other layer. -- Application depends only on Domain. -- Infrastructure and Adapters depend inward only. -- All cross-layer communication must use explicit interfaces or protocols. -- Business decisions belong only in Domain. -- Application coordinates execution but does not make business decisions. -- No layer may bypass another. -- Abstractions must not leak across boundaries. - -## 2. Core principles - -- production-grade reliability -- efficient use of time and memory -- clear modular architecture -- strict SOLID adherence -- vendor neutrality -- deterministic behavior where possible -- architecture/design before library selection -- performance, readability, and maintainability are all mandatory - -## 3. Naming - -- no unnecessary abbreviations -- prefer precise, domain-driven names -- names must be self-explanatory - -Formats: - -- Class: `PascalCase` -- Function / Method: `snake_case` -- Private Method: `__snake_case` -- Protected / Internal: `_snake_case` -- Constant: `UPPER_SNAKE_CASE` -- Enum member name: `UPPER_SNAKE_CASE` -- Enum member value: `UPPER_SNAKE_CASE` for internal/semantic enums (the value mirrors the member name). The only exception is an enum whose values form an external or rendered protocol vocabulary — tokens emitted verbatim into rendered output, an external API/tool contract, or a persisted wire format — which keep their literal protocol form. -- Module: `snake_case` - -## 4. Imports - -- imports at the top of the file -- no circular imports -- order imports as: - - standard library - - third-party - - internal modules - -## 5. Typing and documentation - -- strong type hints are mandatory on function signatures, method signatures, and class attributes -- every class needs one concise docstring stating purpose -- every function/method needs one concise docstring stating what it does -- doc-strings describe intent and contract, not implementation detail -- avoid redundant inline comments -- `Any` is prohibited except at the outermost boundary where type is genuinely unknowable - -## 6. Classes and encapsulation - -- default to classes for behavior -- module-level functions are only for pure stateless transformations -- classes must have one clearly articulable responsibility -- expose the minimum public surface -- use `__` for truly private implementation details -- use `_` for protected/internal members -- prefer composition over inheritance -- never use class attributes as a substitute for injected dependencies - -## 7. Data models - -- use Pydantic `BaseModel` for entities, validated value models, and anything crossing a boundary -- never use `@dataclass` anywhere in the repository -- use an ordinary class only for behavior-only objects that are not entities -- never use raw `dict` or `tuple` instead of a typed model -- prefer immutable domain entities/value objects where possible -- validate at the boundary; Domain may assume valid data - -## 8. Keyword arguments - -- all internal calls must use keyword arguments -- positional arguments are allowed only for standard library, third-party APIs, or strong idiomatic conventions - -## 9. Exceptions - -- catch the most specific exception possible -- name exception variables descriptively, e.g. `exception` -- prefer domain-specific exception types -- never swallow errors silently -- re-raise or wrap with context at boundaries -- error messages must be actionable - -## 10. Domain purity and state - -Domain must never contain: - -- HTTP/network calls -- database access -- file system operations -- environment reads -- logging or telemetry -- global state or singletons -- framework-specific imports - -Rules: - -- Domain is stateless by default -- inject all configuration -- pass all state explicitly -- Domain must be testable with no infrastructure - -## 11. Extensibility and composition - -- components must be replaceable without changing calling code -- no hardcoded providers in core logic -- all integrations must be swappable through interfaces -- prefer composition over inheritance -- preferred patterns: Strategy, Adapter, Factory, Repository, Port/Adapter - -## 12. API design - -- avoid breaking changes -- maintain backward compatibility where possible -- all inputs/outputs must use explicit typed schemas -- APIs must fail clearly and deterministically -- internal types must not leak through public surfaces - -## 13. Configuration - -- never hardcode configuration -- inject configuration through constructors or initialization -- Domain remains configuration-agnostic -- validate configuration schemas at the boundary - -## 14. Dependency policy - -- use open-source libraries with permissive licenses -- avoid hidden paid-tier lock-in -- avoid vendor lock-in in core/application layers -- isolate all external systems behind interfaces/adapters -- never import a vendor SDK directly into Domain or Application - -## 15. Reuse policy - -- inspect existing code before writing new code -- reuse when correct and well-structured -- refactor when logic is recoverable but structure is wrong -- rewrite only when fundamentally flawed -- never duplicate as a shortcut - -## 16. Deterministic behavior - -- avoid hidden side effects -- avoid implicit/global state -- same input should produce same output where practical -- inject time, randomness, environment, flags, locale, and other non-deterministic inputs - -## 17. Boundary validation - -- validate and normalize all external input before Application or Domain logic -- fail early with explicit structured errors -- never trust external data -- Domain should only see validated typed data -- validation belongs in Adapter or Infrastructure, not Domain - -## 18. Idempotency - -- retryable/re-playable operations must be idempotent -- prevent duplicate or corrupted state on re-entry -- use idempotency keys or natural deduplication where needed -- document which operations are idempotent - -## 19. Fail fast - -- detect invalid state and invariant violations immediately -- raise explicit structured exceptions with diagnostic context -- never silently recover from unexpected conditions -- prefer hard failures in development over hidden corruption - -## 20. Concurrency - -- avoid shared mutable state across concurrent paths -- prefer message passing and event-driven coordination -- protect critical sections explicitly -- ensure thread safety of shared resources -- avoid unnecessary locking -- concurrency boundaries must be explicit and documented - -## 21. Resource safety - -- every acquired resource must have a guaranteed release path -- use context managers / structured lifecycle management -- avoid unbounded growth in queues, caches, pools, and in-memory collections -- resource exhaustion must fail explicitly - -## 22. Performance awareness - -- identify hot paths during design -- avoid unnecessary allocations and copies on hot paths -- avoid repeated expensive operations; cache/batch deliberately -- choose the right data structure -- avoid avoidable `O(n^2)` paths -- performance must be measurable in production -- do not optimize blindly; measure first - -## 23. Observability - -Minimum expectations: - -- structured machine-parseable logging at significant boundaries -- actionable error messages with context -- correlation identifiers -- metrics for throughput, error rate, and latency -- tracing at latency/failure/retry boundaries - -Rules: - -- observability is part of design, not an afterthought -- logging belongs only in outer layers -- silent failures are unacceptable -- logs must be actionable without requiring source-code access - -## 24. Isolation of external systems - -Dependency direction must be: - -`External System -> Adapter -> Interface -> Application / Domain` - -Rules: - -- Domain and Application depend only on interfaces -- all external interactions go through adapters -- every external dependency must be replaceable, mockable, and testable - -## 25. Backward compatibility - -- public interfaces stay stable once exposed -- prefer additive change -- plan and phase breaking changes explicitly -- lifecycle: extend -> deprecate -> remove -- define versioning before first external consumer - -## 26. Migration safety - -- schema changes must be backward compatible first -- data migrations should be reversible where feasible -- deployments must not break in-flight work -- prefer phased migration over hard cut over -- every migration needs a rollback path - -## 27. System evolution - -- avoid locking the future architecture to today's implementation -- prefer composition -- keep boundaries clear and enforced -- keep coupling low -- every module/boundary must have a one-sentence role - -## 28. Security awareness - -- validate all external input -- do not leak internal details to untrusted consumers -- defensively validate external responses -- never log sensitive data -- authn/authz must be enforced at the boundary - -## 29. Testing philosophy - -Levels: - -- unit tests for Domain logic -- integration tests for infrastructure/adapter seams -- end-to-end tests for workflows - -Rules: - -- Domain tests must be infrastructure-free -- tests must be deterministic -- test observable behavior, not internals -- critical path coverage is non-negotiable - -## 30. Controlled complexity - -- avoid deep inheritance -- avoid monolithic classes -- break logic into small testable components -- refactor to reduce complexity when needed - -## 31. Ownership and responsibility - -- every component must have a narrow one-sentence role -- split modules that do unrelated work -- respect ownership boundaries -- do not reach into internals across boundaries - -## 32. Style rules - -Prohibited: - -- emojis in code/comments/doc-strings -- AI-style filler comments -- TODO without a ticket/issue reference -- logging or telemetry inside Domain -- global mutable state -- magic numbers or strings without named constants - -## How to apply this skill - -When implementing or reviewing: - -- first evaluate whether the current code respects the layer boundaries -- identify any violations of typing, boundary validation, determinism, or dependency policy -- prefer corrective refactors before adding new logic on top of bad structure -- if a requested change conflicts with these standards, call out the conflict explicitly -- when producing plans or PRDs, map proposed modules and data flow back to these rules - -## Fathom-specific reminder - -For Fathom work, below are strictly compulsory to follow - -- Proper layered and nested structure, be it folder, files, or classes, entities, it's fields, and always use single word names for folder, files, etc... -- Proper usages of design pattern, considering all basic coding concepts like OOPS, SOLID, SRP, OCP, LSP, Hexagonal Architecture -- Using Pydantic for entities with Fields, 1 line descriptions, and defining it at correct files/location (schemas) -- No hardcoded constants/values, define things inside constants (Use IntEnum, StrEnum, etc...) -- Don't use any unit(ms, s, etc..) as prefix/suffix for any variables/fields, use description to convey what it means -- Use elegant, beautiful, sort, generic names for functions, variables, fields (Eg: For Pydantic/Fields, I prefer nested fields, Eg: ocr.enabled and not ocr_enabled, etc...) -- Always use __ and not _ for private methods/variables, and use __methods to make code readable, making function non-bloated, etc... -- Doc string should be in format of """\n Crisp, to the point doc-string\n""" and """doc-string""" -- UTs should follow same file/folder structure, and each UT should be class, no function based UTs, and UT should cover actual real cases and not vague, random, fake cases -- I don't like standalone functions at all, everything should be class with proper functions (instance method, class/static methods depending on its nature) -- Nothing should violate HEXAGONAL ARCHITECTURE In any case, We've to maintain SRP, OOPS, Other basic coding standards at all cost, this is non-negotiable -``` diff --git a/.env.template b/.env.template new file mode 100644 index 00000000..2c19f95c --- /dev/null +++ b/.env.template @@ -0,0 +1,67 @@ +# --------------------------------------------------------------------------- +# Model access (required) — one vision-language model backs the whole agent. +# --------------------------------------------------------------------------- + +# Direct Gemini API key. Get one from Google AI Studio and paste it here. +GEMINI_API_KEY=your-api-key-here + +# Model id to drive. Set this to a model your key or project can actually access. +GEMINI_MODEL=gemini-2.5-flash + +# --------------------------------------------------------------------------- +# Vertex AI (optional) — use this instead of a direct key to run through GCP. +# Leave GEMINI_API_KEY unset when you go this route. +# --------------------------------------------------------------------------- + +# VERTEX_LOCATION=us-central1 +# VERTEX_PROJECT_ID=your-gcp-project +# GOOGLE_APPLICATION_CREDENTIALS=/absolute/path/to/service-account.json + +# --------------------------------------------------------------------------- +# Perception subsystems (optional) — each is on by default; set to false to skip +# the corresponding pass and trade a little accuracy for speed. +# --------------------------------------------------------------------------- + +# FATHOM_OBSERVATION_CV=false +# FATHOM_OBSERVATION_OCR=false +# FATHOM_OBSERVATION_ICON=false +# FATHOM_OBSERVATION_OVERLAY=false +# FATHOM_OBSERVATION_KEYBOARD=false + +# --------------------------------------------------------------------------- +# Ensemble localization (optional) — turn on multi-member voting for grounding +# and list the members that should participate in the vote. +# --------------------------------------------------------------------------- + +# FATHOM_ENSEMBLE_LOCALIZER=false +# FATHOM_ENSEMBLE_LOCALIZER_MEMBERS=gemini,ocr,icon + +# --------------------------------------------------------------------------- +# Priority / adaptive inference (optional) — let the model adapter shed load and +# recover automatically when the provider gets slow or starts rejecting calls. +# --------------------------------------------------------------------------- + +# FATHOM_LLM_PRIORITY_ENABLED=false +# FATHOM_LLM_PRIORITY_MODE=adaptive + +# --------------------------------------------------------------------------- +# Conversation / observability store (optional) — the interaction layer records +# threads, messages, tasks, and scripts. It defaults to an in-memory noop store; +# point it at Postgres to keep durable history. Setting a DSN selects Postgres. +# --------------------------------------------------------------------------- + +# FATHOM_INTERACTION_BACKEND=postgres +# FATHOM_INTERACTION_POSTGRES_DSN=postgresql://user:password@localhost:5432/fathom + +# --------------------------------------------------------------------------- +# Paths (optional) — override where run logs and bundled assets are read/written. +# --------------------------------------------------------------------------- + +# FATHOM_RUN_LOGS_PATH=./run-logs +# FATHOM_ASSETS_PATH=./assets + +# --------------------------------------------------------------------------- +# Tests (optional) — live tests call a real model and are skipped unless opted in. +# --------------------------------------------------------------------------- + +# FATHOM_RUN_LIVE_TESTS=1 diff --git a/.gemini/.skills/.engineering/.reviews/CHECKLIST.MD b/.gemini/.skills/.engineering/.reviews/CHECKLIST.MD deleted file mode 100644 index b1a71fd7..00000000 --- a/.gemini/.skills/.engineering/.reviews/CHECKLIST.MD +++ /dev/null @@ -1,325 +0,0 @@ -You are a Staff/Principal Software Engineer reviewing a branch or PR against the Fathom codebase. Your job is not to approve. Your job is to find every bug, design flaw, missed surface, heuristic-on-heuristic patch, untested branch, broken contract, hidden assumption, observability gap, regression risk, and standards violation before this code ships to prod. - -You will be graded on what you miss, not on how polite you are. Be skeptical. Optimize for correctness, root-cause clarity, and long-term code health. Do not optimize for approval. - -# Operating rules for this repo - -These are the user's review preferences. Internalize them; they override generic engineering instincts when they conflict. - -1. **Proof before claim.** Never assert a bug, fix, behavior, or coverage gap without naming the exact `file:line`, the exact log line, the exact test name, or the exact opened artifact. No `~25% coverage` estimates; enumerate the tests. No "this might be missing"; verify. -2. **Root cause only.** Reject patches, workarounds, and "make it pass" fixes. Reject any change that addresses the symptom without proving the symptom's mechanism. If the author can't explain why the issue occurred and why the fix prevents recurrence, request changes. -3. **No heuristics on heuristics.** Runtime string-match branches (`if word in intent.lower(): rules.append(...)`) are technical debt. Any new instance is a blocker unless the author explicitly justifies why a structural fix is impossible. Removing existing ones is a feature. -4. **No fabricated reads.** Never claim to have read a file you didn't. Never grep for an expected keyword and assume absence means absence — names you didn't predict will hide the test. -5. **Stale-source check.** Confirm `stat -f "%Sm" ` lines up with when the diff was last edited. Old reads of recently-rewritten code are how false reviews ship. -6. **No silent coverage.** "Tests pass" is not a review signal. Enumerate which tests exercise which branch of the changed surface; identify untested branches by name. -7. **Compliance with SKILL.md is non-negotiable.** Every diff must satisfy `/fathom/.codex/.skills/.engineering/.standards/SKILL.md`. The SKILL.md compliance section below lists the specific rules to verify. -8. **Memory & artifacts.** Investigation downloads (CloudWatch dumps, GCS assets) live under `/fathom/debug//`, never `/tmp`. Reference paths absolutely. - -# SKILL.md compliance — verify before reviewing logic - -Open `/fathom/.codex/.skills/.engineering/.standards/SKILL.md` and confirm the diff respects every rule listed there. Specifically: - -**Architecture (SKILL.md §1, §10, §24, plus the Fathom-specific reminder)** -- Hexagonal architecture is non-negotiable. Domain (`schemas/`, `constants/`) depends on nothing. Application (`core/`) depends only on Domain and Ports (`interfaces/`). Adapters (`adapters/`, `runtime/`, `infrastructure/`) depend inward only. -- Domain must not contain HTTP, DB, file system, env reads, logging, telemetry, global state, framework imports. -- Block any diff where Application imports concrete Adapter classes directly. -- Block any diff where Domain or Application imports a vendor SDK. - -**Naming (SKILL.md §3 + Fathom-specific)** -- Folders, files, modules use single-word `snake_case`. -- Classes `PascalCase`. Functions/methods `snake_case`. Private methods `__snake_case` — never `_snake_case` for private. Constants `UPPER_SNAKE_CASE`. -- Enum member values are `UPPER_SNAKE_CASE` for internal/semantic enums (value mirrors the name); only enums whose values form an external/rendered protocol vocabulary (rendered-output tokens, external API/tool contracts, persisted wire formats) keep literal-cased values. A lowercase value on an internal/semantic enum is a Blocker. -- No unit suffixes/prefixes on variables (`duration_ms`, `cache_size_bytes`, `latency_seconds` are wrong — use `duration`/`size`/`latency` with the unit documented in a one-line docstring or schema description). -- Prefer nested Pydantic fields (`ocr.enabled`, not `ocr_enabled`). -- Names must be domain-driven and self-explanatory. No abbreviations. - -**Classes (SKILL.md §6, §31 + Fathom-specific)** -- Default to classes. Standalone functions are only for pure stateless transformations. -- Reject standalone module-level functions that do anything but transform inputs to outputs. -- Each class has one articulable responsibility — one sentence. -- `__` for private internals. `_` for protected/internal members. Use private methods aggressively to keep public methods unbloated. -- Prefer composition over inheritance. - -**Data models (SKILL.md §7)** -- Pydantic `BaseModel` for anything crossing a boundary, with Pydantic `Field(description=...)`. -- `dataclass` only for pure in-memory domain value objects. -- Raw `dict` or `tuple` instead of a typed model is a Blocker. -- Domain entities prefer immutability (`model_config = ConfigDict(frozen=True)` on Pydantic models that represent invariants). - -**Constants (SKILL.md §32 + Fathom-specific)** -- No hardcoded values. Numbers, strings, bucket names, namespaces, timeouts, thresholds — all go into `constants/` as `IntEnum`/`StrEnum`/`Final[int]`/`Final[str]`. -- Magic numbers or strings without named constants is a Blocker. - -**Typing (SKILL.md §5)** -- Type hints mandatory on every function/method signature and class attribute. -- `Any` is prohibited except at the outermost boundary where the type is genuinely unknowable. -- Block any diff that introduces `# type: ignore` without an inline reason. - -**Docstrings (SKILL.md §5 + Fathom-specific)** -- Every class: one-line docstring stating purpose. -- Every function/method: one-line docstring stating what it does. -- Format: `"""Crisp one-liner."""` — single-line preferred. If multi-line is unavoidable, the body is one short sentence stating intent and contract. No multi-paragraph rationale, no bug-history recaps, no commentary on call sites. -- Reject docstrings that grow because the function "needs explanation" — the function probably needs simplification. - -**Keyword arguments (SKILL.md §8)** -- All internal calls must use keyword arguments. -- Positional allowed only for standard library, third-party APIs, or strong idiomatic conventions. -- Block any internal call site that passes positional arguments to a Fathom-defined function. - -**Exceptions (SKILL.md §9, §19)** -- Catch the most specific exception. `except Exception:` is suspect; `except BaseException:` is rejected. -- Re-raise `asyncio.CancelledError` explicitly when caught by a broad `except`. -- Domain-specific exception types (`FathomError` subclasses) preferred over generic `RuntimeError`. -- Never swallow errors silently. Fail fast on invariant violation with diagnostic context. - -**Tests (SKILL.md §29 + Fathom-specific)** -- Test files mirror source paths (`tests/unit/`, `tests/integration/`, `tests/live/`). -- Class-based tests only. No function-based tests. -- Tests must exercise real cases, not vague placeholders. -- Domain tests are infrastructure-free. - -If any of the above is violated, raise it as the first issue. Logic review comes after compliance review. - -# Architecture invariants — Fathom layer table - -A diff that places logic in the wrong layer is Major or worse. - -| Layer | Where | Allowed | -|---|---|---| -| Domain — pure data, no IO, no LLM | `constants/`, `schemas/` | Pydantic models, StrEnum/IntEnum constants, derived predicates. Never `httpx`, never `await llm.generate`, never `await device.tap`. | -| Application — orchestration, side-effect free decision logic | `core/` | Reasoners, gates, services, evaluators. Reads from Domain, calls infrastructure via Ports. | -| Infrastructure — adapters to external systems | `adapters/`, `runtime/`, `infrastructure/` | LLM clients, device adapters, storage backends, Temporal signal-adapter, telemetry sinks, env reads. | -| Strategies — graph orchestration | `strategies/graph/intent/`, `strategies/graph/exploration/` | LangGraph nodes (thin handlers). Heavy logic belongs in `core/`. | -| Interfaces (Ports) | `interfaces/` | Abstract base classes. Adapters implement these. Application code consumes these. | - -# Critical components — areas to review with extra scrutiny - -For each, the review questions are generic but the component is named. The reviewer must check whether the diff respects the listed properties. - -## State machine (LangGraph + AgentState) - -Files: `strategies/graph/intent/nodes/*.py`, `strategies/graph/state.py`, `core/agent/state.py`, `schemas/state.py`. - -Verify: -- Every channel a node writes is declared on the `IntentGraphState` TypedDict in `strategies/graph/state.py`. Undeclared keys are silently dropped by LangGraph's reducer. -- Every terminal patch (cancellation, max-steps, failure, completion, etc.) sets every key it claims to clear. Missing `SHOULD_RETRY`, `VERIFY_MODE`, `COMPLETION_REASON`, `FAILURE_DIAGNOSTIC` lets stale values from prior turns leak forward. -- State transitions are idempotent — re-running a node on the same input must produce the same patch. -- No node mutates a channel it doesn't own. Cross-node mutation through the graph state is acceptable; cross-node mutation through `AgentState` is suspect. -- `AgentState.to_checkpoint()` and `AgentState.from_checkpoint(...)` round-trip every field the diff adds. A new field that's not in `to_checkpoint` is lost on resume. -- Invariant violations (cursor drift, mode/state mismatch) raise `InvariantViolation` with diagnostic context, not `RuntimeError` or silent recovery. -- The router functions in `builder.py` are pure functions of the state dict — no IO, no randomness. - -## LLM prompt and tool-schema contract - -Files: `core/prompts/tools.py`, `core/prompts/decomposition.py`, `core/prompts/gemini.py`, `core/prompts/templates.py`. - -Verify: -- The `action_type` enum in `tools.py` matches `ActionType` in `constants/__init__.py`. Adding to one without the other lets the model emit values the executor doesn't handle, or hides supported actions from the model. -- The Decomposer directive table in `decomposition.py` only maps to directives the executor can actually satisfy. -- Tool-field `description` strings are part of the contract — changes to them are behavior changes for the model. Pin them in a test if you change them. -- Runtime keyword-substring rules (`if word in intent.lower():`) are flagged as heuristic debt. New ones are a Blocker. -- System-prompt sections are sourced from one place. Reject "append a sibling rule next to the existing rule" patterns. - -## Action surface — four-place contract - -Files: `constants/__init__.py:ActionType`, `schemas/actions.py:Action`, `core/prompts/tools.py:action_type enum`, `core/services/action.py:__action_handlers`, `constants/interaction.py:InteractionAction`, `adapters/device/{local,remote}/{adb,ios}.py`. - -A change to the action set is a four-place coordinated change: enum, schema, tool-schema, dispatch table, adapter methods, wire-protocol enum. Verify all places are touched together. - -- `ActionType` enum, the LLM tool schema's `action_type` enum, and the executor's `__action_handlers` table must all align. Disagreement is silent failure. -- `InteractionAction` (`constants/interaction.py`) is the wire contract with the remote farm. Removing a value from `ActionType` must remove it here too. Values here that the remote worker doesn't implement become `success=False, error="Failed to execute..."` in prod. -- Removing an `ActionType` member requires a Pydantic `model_validator(mode="before")` on `Action` that coerces or rejects the legacy value — otherwise old checkpoints and `history.json` files fail to load. -- Targetless actions (no `label_id`, no `bounds`) bypass the `__snap_to_label` guard. Adding such an action is suspect; document why a snap/agreement guard isn't needed. - -## Resolution and snap layer - -Files: `core/services/resolution.py`, `core/services/normalizer.py`. - -Verify: -- `__snap_to_label` runs only for `SPATIAL_ACTION_TYPES`. Non-spatial actions strip `label_id` and pass through — confirm that's intended. -- The IoU agreement check at `resolution.py:207-250` only fires when `not __element_has_semantic_descriptor(element=info)`. Text-bearing elements skip the guard. If the diff adds new agreement logic, ensure it covers both branches. -- Generic visual containers must be rejected with structured `event=snap.generic_container.rejected` so the planner-side `skip_label_id` flow has signal. - -## Completion gate and sub-goal lifecycle - -Files: `core/agent/completion.py`, `strategies/graph/intent/nodes/completion.py`, `strategies/graph/intent/nodes/verify.py`, `strategies/graph/intent/nodes/record.py`, `strategies/graph/intent/verification.py`, `core/agent/state.py`. - -Verify: -- The gate's `(claim.asserted, claim.justified, action.dispatched, screen.evolved)` evidence pairs are sourced from real signals — not heuristic substring checks. -- Sub-goal cursor and `VerifyMode` are consistent — `VerificationModePolicy.mode_for_producer` reads cursor truthfully. -- Counters (`verification_loop`, `consecutive_complete_deferrals`, planner-retry budget) reset on real progress and persist across irrelevant turns. Asymmetric reset across paths is debt. -- Every `mark_complete` call site uses a `CompletionReason` from the enum, not a free-text string. - -## Configuration and infrastructure boundaries - -Files: `runtime/runner.py`, `adapters/storage/`, `adapters/signal/temporal.py`, `adapters/device/remote/`, `infrastructure/`. - -Verify: -- No hardcoded bucket names, GCP project IDs, Temporal namespaces, URLs, ports, or device serials. All configuration injected through constructors. -- Validate config at the boundary. Reject `os.getenv("FOO")` calls in `core/` or `strategies/`. -- Vendor SDK imports (`vertexai`, `google.cloud`, `boto3`, `appium`) belong only in Adapter modules. Never in Domain or Application. - -## Persistence and migration - -Files: `schemas/state.py` (frozen Pydantic models), `core/agent/state.py:to_checkpoint/from_checkpoint`, LangGraph SQLite checkpointer. - -Verify: -- Any new field on a checkpointable model has a default value or a `model_validator(mode="before")` to coerce missing values from older checkpoints. -- Enum members can be removed only with a coercion shim that maps the legacy string to a current member. -- LangGraph's TypedDict `IntentGraphState` is the single source of truth for what survives a state merge. New keys go here. -- Migration safety: in-flight workflows in Temporal must continue to load on the new code path. - -## Concurrency, cancellation, lifecycle - -Files: `runtime/executor.py`, `runtime/temporal/`, `adapters/signal/temporal.py`, `strategies/graph/intent/nodes/hitl.py`. - -Verify: -- `except Exception:` blocks explicitly re-raise `asyncio.CancelledError` (CancelledError is `BaseException` in 3.8+, but legacy code may have caught it). -- Cancellation paths persist any state mutations before returning. -- HITL signal-adapter wait loops check `is_cancelled` between awaits. -- Resource acquisition has a guaranteed release path (`try/finally`, `async with`, or explicit shutdown method). -- No shared mutable state across concurrent tasks without a lock or message-passing boundary. - -## Observability - -Files: every node, adapter, and service. - -Verify: -- Every exit path emits a structured event (`extra={"event": "...", "component": "..."}`). Silent paths are unreviewable in prod. -- `workflow.id` is on every node-level log so dashboards can scope by run. -- Log level is consistent: `logger.exception(...)` for caught exceptions with traceback value, `logger.error(...)` for known-failure paths without a traceback, `logger.warning(...)` for degraded but recoverable. -- `FAILURE_DIAGNOSTIC` strings are capped (typically 500 chars) — never an unbounded exception/traceback string into a checkpoint. -- Every `CompletionReason` member is classified in `intent.py:__is_successful_completion` and (if terminal) in `TERMINAL_COMPLETION_REASONS`. - -## Telemetry-event consistency - -Files: any node, `runtime/runner.py`, telemetry sinks. - -Verify: -- Success and failure paths of the same operation both emit events. One-sided observability is a Major issue. -- `FathomEvent` taxonomy is respected. New telemetry event values go in the enum, not as free-string `type=...` arguments. -- Terminal messages reflect the actual outcome. `runtime/runner.py:354` is a known active bug — flag any new exit path that funnels through `terminal_message = "All wrapped up."` without a FAILED branch. - -# Failure patterns shipped to prod — known shapes to grep for - -These are real failure shapes the user has triaged. The reviewer must actively probe for these in any diff that touches the relevant layer. - -1. **Streak counter keyed on a field that mutates each turn.** A counter like `consecutive_rejections` that resets because its match function compares `step_count` (which `record_step` increments). Use stable identifiers (activity, screen identity). -2. **Transient error counted as a rejection.** LLM timeout / 503 / JSON parse failure falls through to the same path as a verifier saying "no." Branch on transport vs verdict. -3. **Counters not reset on real progress.** Sub-goal advance leaves stale streak/deferral counters from a prior sub-goal. -4. **Wrong action paired with wrong target by the model.** Decomposer emits an unsupported directive; planner satisfies by emitting an action with `label_id=None, bounds=None`. Structural fix: remove the directive option. -5. **Targetless action primitives have no snap guard.** ENTER/HOME/BACK pass through resolution unguarded — no anchor. -6. **Runtime substring keyword rules misroute.** `if any(word in intent.lower() for word in [...])` is a serial bug factory. -7. **Terminal-message lies on failure.** A binary `if cancelled: ... else: "All wrapped up."` reports failed runs as completed. -8. **Prod-config drift.** Hardcoded bucket name with "dev" or "stag" in the value reaching prod, hardcoded namespace, hardcoded URL. -9. **Coverage estimated, not enumerated.** Reviewer says "~25%"; actual answer is enumerable. -10. **Test mocks the very thing being tested**, or bypasses the path that the bug actually walks (e.g. a unit test that bypasses `record_step` to test a flow that always goes through `record_step` in prod). - -# Test-coverage discipline - -Coverage claims are enumerable, not percentages. - -For every changed function: -- List the branches by name. -- For each branch, name the test file:line that exercises it, or mark it `MISSING`. -- Do not approve a PR with `MISSING` on a branch unless the author justifies why that branch is unreachable. - -For changes to nodes in `strategies/graph/intent/nodes/`: -- A unit test that drives the node with a `_Provider` double and asserts every state-patch key the node sets or clears. -- An integration test under `tests/integration/strategies/graph/intent/nodes/` that drives the node alongside its peers in realistic order, with a real `AgentState` (not a mock), so cursor/streak/deferral counters round-trip. - -For changes to load-bearing prompt files (`tools.py`, `decomposition.py`, `gemini.py`): -- A `tests/unit/core/prompts/` assertion that pins the tool schema or directive table. - -For changes to `runtime/runner.py`, `strategies/intent.py`, `adapters/`, `infrastructure/`: -- A live test (`tests/live/`) is preferred when feasible. Mocked execution is acceptable only for non-deterministic external dependencies (LLM, network). - -Reject: -- Tests that bypass the path the bug actually walks. -- Tests that mock the very thing being tested. -- Tests that pass with bogus assertions. -- Tests added for the bug under review without a sibling test for the negative case (the right thing still works). - -# Heuristic-debt detector - -When the diff contains any of these patterns, raise a Blocker for justification: - -- `if any(word in intent.lower() for word in [...]):` -- `if " " + keyword in description.lower():` -- `if intent.startswith(...):` for routing or rule decisions -- string-match action-type detection: `if action_type == "..." and target ...` -- `if hasattr(self.__device, "...")` runtime feature detection (use the Port interface) -- Fallback chains that grow on each bug report (`if X: rule_a; elif Y: rule_b; elif Z: rule_c; ...`) - -These are the antipattern that produces silent failure modes. Structural alternatives belong in the schema, the constant, the enum, the dispatch table, the Port, or the configuration — not in runtime branches. - -# Output format - -For every issue, use this format. No emojis. No headers beyond what's listed. - -## Issue - -### Severity - -One of: `Blocker`, `Critical`, `Major`, `Minor`, `Suggestion`. - -### Category - -One of: `Architecture`, `Design`, `Maintainability`, `Testing`, `Reliability`, `Performance`, `Readability`, `Schema`, `Telemetry`, `LLM contract`, `Heuristic debt`, `Coverage`, `Standards (SKILL.md)`. - -### Description - -Two sentences, max. State the bug. State where it lives by `file:line`. - -### Why It Is A Problem - -Three sentences, max. Connect to a prod failure shape from the patterns list when applicable. - -### Recommended Fix - -State the structural change. Not a runtime guard. Not a string-match rule. - -### Example Implementation - -Only when the fix isn't obvious from the recommendation. Code block, short. - -# Final assessment - -## Overall verdict - -One of: `Approve with minor changes`, `Request changes`, `Block`. - -There is no `Approve`. Every PR has either standards issues, coverage gaps, or design concerns worth surfacing — even on PRs that should ship, name them as minor and let the author decide whether to act before merge. - -## Production readiness score - -Rate 1-10. 10 = ready for prod traffic on the diff's day-1 surface. ≤ 5 means the PR is solving the wrong problem. - -## Testing confidence score - -Rate 1-10. 10 = every changed branch is named and has an enumerated test. ≤ 5 means coverage is estimated, not enumerated. - -## Maintainability score - -Rate 1-10. 10 = the diff reduces total complexity. ≤ 5 means it adds heuristic debt or special-case branches. - -## Root-cause confidence - -Rate 1-10. 10 = the author explained the mechanism, named the file:line, and the fix forecloses the failure class, not just the failing case. ≤ 5 means the change is a patch. - -## SKILL.md compliance - -One of: `Pass`, `Pass with minor deviations`, `Fail`. `Fail` makes the overall verdict at least `Request changes`. - -## Summary - -Three to five sentences. Cover: - -- Whether the correct problem was solved (and which prod failure class it forecloses, by name). -- Whether the solution is structural or a patch. -- Whether the testing is enumerable. -- Whether SKILL.md compliance is clean or the diff carries a standards violation. -- Any blockers, by name. -- Whether the diff should be merged. - -Be highly skeptical. Optimize for correctness, root-cause clarity, and long-term code health. Do not optimize for approval. diff --git a/.gemini/.skills/.engineering/.standards/SKILL.md b/.gemini/.skills/.engineering/.standards/SKILL.md deleted file mode 100644 index 4c57dc51..00000000 --- a/.gemini/.skills/.engineering/.standards/SKILL.md +++ /dev/null @@ -1,357 +0,0 @@ -# Engineering & Architecture Standard - -Use this skill for any coding, architecture, refactor, implementation-plan, PRD, design-review, or code-audit task in this workspace unless the user explicitly says otherwise. - -## Non-negotiable goals - -All systems must be: - -- production-grade -- efficient and performant -- modular and extensible -- vendor-neutral -- open-source friendly -- architecturally disciplined -- safe for long-term evolution - -Readability, maintainability, and performance must coexist. Do not trade one away casually. - -## 1. Architecture - -Use a strict layered architecture: - -- Domain: business logic, rules, entities, policies, invariants -- Application: use-cases, orchestration, workflows -- Infrastructure: databases, networks, messaging, file systems, external SDKs -- Adapters: translate external systems into internal interfaces - -Rules: - -- Domain must not depend on any other layer. -- Application depends only on Domain. -- Infrastructure and Adapters depend inward only. -- All cross-layer communication must use explicit interfaces or protocols. -- Business decisions belong only in Domain. -- Application coordinates execution but does not make business decisions. -- No layer may bypass another. -- Abstractions must not leak across boundaries. - -## 2. Core principles - -- production-grade reliability -- efficient use of time and memory -- clear modular architecture -- strict SOLID adherence -- vendor neutrality -- deterministic behavior where possible -- architecture/design before library selection -- performance, readability, and maintainability are all mandatory - -## 3. Naming - -- no unnecessary abbreviations -- prefer precise, domain-driven names -- names must be self-explanatory - -Formats: - -- Class: `PascalCase` -- Function / Method: `snake_case` -- Private Method: `__snake_case` -- Protected / Internal: `_snake_case` -- Constant: `UPPER_SNAKE_CASE` -- Enum member name: `UPPER_SNAKE_CASE` -- Enum member value: `UPPER_SNAKE_CASE` for internal/semantic enums (the value mirrors the member name). The only exception is an enum whose values form an external or rendered protocol vocabulary — tokens emitted verbatim into rendered output, an external API/tool contract, or a persisted wire format — which keep their literal protocol form. -- Module: `snake_case` - -## 4. Imports - -- imports at the top of the file -- no circular imports -- order imports as: - - standard library - - third-party - - internal modules - -## 5. Typing and documentation - -- strong type hints are mandatory on function signatures, method signatures, and class attributes -- every class needs one concise docstring stating purpose -- every function/method needs one concise docstring stating what it does -- docstrings describe intent and contract, not implementation detail -- avoid redundant inline comments -- `Any` is prohibited except at the outermost boundary where type is genuinely unknowable - -## 6. Classes and encapsulation - -- default to classes for behavior -- module-level functions are only for pure stateless transformations -- classes must have one clearly articulable responsibility -- expose the minimum public surface -- use `__` for truly private implementation details -- use `_` for protected/internal members -- prefer composition over inheritance -- never use class attributes as a substitute for injected dependencies - -## 7. Data models - -- use Pydantic `BaseModel` for anything crossing a boundary -- use `dataclass` only for pure in-memory domain value objects with no validation/serialization requirement -- never use raw `dict` or `tuple` instead of a typed model -- prefer immutable domain entities/value objects where possible -- validate at the boundary; Domain may assume valid data - -## 8. Keyword arguments - -- all internal calls must use keyword arguments -- positional arguments are allowed only for standard library, third-party APIs, or strong idiomatic conventions - -## 9. Exceptions - -- catch the most specific exception possible -- name exception variables descriptively, e.g. `exception` -- prefer domain-specific exception types -- never swallow errors silently -- re-raise or wrap with context at boundaries -- error messages must be actionable - -## 10. Domain purity and state - -Domain must never contain: - -- HTTP/network calls -- database access -- file system operations -- environment reads -- logging or telemetry -- global state or singletons -- framework-specific imports - -Rules: - -- Domain is stateless by default -- inject all configuration -- pass all state explicitly -- Domain must be testable with no infrastructure - -## 11. Extensibility and composition - -- components must be replaceable without changing calling code -- no hardcoded providers in core logic -- all integrations must be swappable through interfaces -- prefer composition over inheritance -- preferred patterns: Strategy, Adapter, Factory, Repository, Port/Adapter - -## 12. API design - -- avoid breaking changes -- maintain backward compatibility where possible -- all inputs/outputs must use explicit typed schemas -- APIs must fail clearly and deterministically -- internal types must not leak through public surfaces - -## 13. Configuration - -- never hardcode configuration -- inject configuration through constructors or initialization -- Domain remains configuration-agnostic -- validate configuration schemas at the boundary - -## 14. Dependency policy - -- use open-source libraries with permissive licenses -- avoid hidden paid-tier lock-in -- avoid vendor lock-in in core/application layers -- isolate all external systems behind interfaces/adapters -- never import a vendor SDK directly into Domain or Application - -## 15. Reuse policy - -- inspect existing code before writing new code -- reuse when correct and well-structured -- refactor when logic is recoverable but structure is wrong -- rewrite only when fundamentally flawed -- never duplicate as a shortcut - -## 16. Deterministic behavior - -- avoid hidden side effects -- avoid implicit/global state -- same input should produce same output where practical -- inject time, randomness, environment, flags, locale, and other non-deterministic inputs - -## 17. Boundary validation - -- validate and normalize all external input before Application or Domain logic -- fail early with explicit structured errors -- never trust external data -- Domain should only see validated typed data -- validation belongs in Adapter or Infrastructure, not Domain - -## 18. Idempotency - -- retryable/replayable operations must be idempotent -- prevent duplicate or corrupted state on re-entry -- use idempotency keys or natural deduplication where needed -- document which operations are idempotent - -## 19. Fail fast - -- detect invalid state and invariant violations immediately -- raise explicit structured exceptions with diagnostic context -- never silently recover from unexpected conditions -- prefer hard failures in development over hidden corruption - -## 20. Concurrency - -- avoid shared mutable state across concurrent paths -- prefer message passing and event-driven coordination -- protect critical sections explicitly -- ensure thread safety of shared resources -- avoid unnecessary locking -- concurrency boundaries must be explicit and documented - -## 21. Resource safety - -- every acquired resource must have a guaranteed release path -- use context managers / structured lifecycle management -- avoid unbounded growth in queues, caches, pools, and in-memory collections -- resource exhaustion must fail explicitly - -## 22. Performance awareness - -- identify hot paths during design -- avoid unnecessary allocations and copies on hot paths -- avoid repeated expensive operations; cache/batch deliberately -- choose the right data structure -- avoid avoidable `O(n^2)` paths -- performance must be measurable in production -- do not optimize blindly; measure first - -## 23. Observability - -Minimum expectations: - -- structured machine-parseable logging at significant boundaries -- actionable error messages with context -- correlation identifiers -- metrics for throughput, error rate, and latency -- tracing at latency/failure/retry boundaries - -Rules: - -- observability is part of design, not an afterthought -- logging belongs only in outer layers -- silent failures are unacceptable -- logs must be actionable without requiring source-code access - -## 24. Isolation of external systems - -Dependency direction must be: - -`External System -> Adapter -> Interface -> Application / Domain` - -Rules: - -- Domain and Application depend only on interfaces -- all external interactions go through adapters -- every external dependency must be replaceable, mockable, and testable - -## 25. Backward compatibility - -- public interfaces stay stable once exposed -- prefer additive change -- plan and phase breaking changes explicitly -- lifecycle: extend -> deprecate -> remove -- define versioning before first external consumer - -## 26. Migration safety - -- schema changes must be backward compatible first -- data migrations should be reversible where feasible -- deployments must not break in-flight work -- prefer phased migration over hard cutover -- every migration needs a rollback path - -## 27. System evolution - -- avoid locking the future architecture to today's implementation -- prefer composition -- keep boundaries clear and enforced -- keep coupling low -- every module/boundary must have a one-sentence role - -## 28. Security awareness - -- validate all external input -- do not leak internal details to untrusted consumers -- defensively validate external responses -- never log sensitive data -- authn/authz must be enforced at the boundary - -## 29. Testing philosophy - -Levels: - -- unit tests for Domain logic -- integration tests for infrastructure/adapter seams -- end-to-end tests for workflows - -Rules: - -- Domain tests must be infrastructure-free -- tests must be deterministic -- test observable behavior, not internals -- critical path coverage is non-negotiable - -## 30. Controlled complexity - -- avoid deep inheritance -- avoid monolithic classes -- break logic into small testable components -- refactor to reduce complexity when needed - -## 31. Ownership and responsibility - -- every component must have a narrow one-sentence role -- split modules that do unrelated work -- respect ownership boundaries -- do not reach into internals across boundaries - -## 32. Style rules - -Prohibited: - -- emojis in code/comments/docstrings -- AI-style filler comments -- TODO without a ticket/issue reference -- logging or telemetry inside Domain -- global mutable state -- magic numbers or strings without named constants - -## How to apply this skill - -When implementing or reviewing: - -- first evaluate whether the current code respects the layer boundaries -- identify any violations of typing, boundary validation, determinism, or dependency policy -- prefer corrective refactors before adding new logic on top of bad structure -- if a requested change conflicts with these standards, call out the conflict explicitly -- when producing plans or PRDs, map proposed modules and data flow back to these rules - -## Fathom-specific reminder - -For Fathom work, below are strictly compulsory to follow - -- Proper layered and nested structure, be it folder, files, or classes, entities, it's fields, and always use single word names for folder, files, etc... -- Proper usages of design pattern, considering all basic coding concepts like OOPS, SOLID, SRP, OCP, LSP, Hexagonal Architecture -- Using Pydantic for entities with Fields, 1 line descriptions, and defining it at correct files/location (schemas) -- No hardcoded constants/values, define things inside constants (Use IntEnum, StrEnum, etc...) -- Don't use any unit(ms, s, etc..) as prefix/suffix for any variables/fields, use description to convey what it means -- Use elegant, beautiful, sort, generic names for functions, variables, fields (Eg: For Pydantic/Fields, I prefer nested fields, Eg: ocr.enabled and not ocr_enabled, etc...) -- Always use __ and not _ for private methods/variables, and use __methods to make code readable, making function non-bloated, etc... -- Doc string should be in format of """\n Crisp, to the point doc-string\n""" and """doc-string""" -- UTs should follow same file/folder structure, and each UT should be class, no function based UTs, and UT should cover actual real cases and not vague, random, fake cases -- I don't like standalone functions at all, everything should be class with proper functions (instance method, class/static methods depending on its nature) -- Nothing should violate HEXAGONAL ARCHITECTURE In any case, We've to maintain SRP, OOPS, Other basic coding standards at all cost, this is non-negotiable -``` diff --git a/.github/PULL_REQUEST_TEMPLATE/pr.md b/.github/PULL_REQUEST_TEMPLATE/pr.md new file mode 100644 index 00000000..1f4c5d9a --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE/pr.md @@ -0,0 +1,29 @@ +## Outcome + +Describe the observable outcome and explicit non-goals. + +## Design + +| Field | Decision | +| --- | --- | +| Capability | | +| Owner | | +| Layer | | +| Contract | | +| Dependencies | | +| State | | +| Failures | | +| Files | | +| Tests | | +| Verification | | + +Use `N/A` only with a reason. + +## Evidence + +- [ ] I read the applicable standards in [`AGENTS.md`](../AGENTS.md). +- [ ] Each changed file has one primary responsibility. +- [ ] Dependencies point toward the owner of policy; boundaries use typed contracts. +- [ ] Focused tests cover behavior and failure paths. +- [ ] `pre-commit` passes and focused tests are green. +- [ ] Every commit is signed off (`git commit -s`; see CONTRIBUTING.md and DCO). diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..e4cb8591 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,12 @@ +version: 2 + +updates: + - package-ecosystem: pip + directory: / + schedule: + interval: weekly + + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly diff --git a/.github/workflows/dco.yml b/.github/workflows/dco.yml new file mode 100644 index 00000000..de9c5a20 --- /dev/null +++ b/.github/workflows/dco.yml @@ -0,0 +1,40 @@ +name: dco + +on: + pull_request: + branches: [main] + +permissions: + contents: read + +jobs: + sign-off: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + ref: ${{ github.event.pull_request.head.sha }} + + - name: Verify Developer Certificate of Origin sign-off + env: + BASE: ${{ github.event.pull_request.base.sha }} + HEAD: ${{ github.event.pull_request.head.sha }} + run: | + missing=0 + for commit in $(git rev-list "$BASE".."$HEAD"); do + author="$(git show -s --format='%an <%ae>' "$commit")" + case "$author" in + *"[bot]"*) echo "skipping automated commit $commit by $author"; continue ;; + esac + if git show -s --format='%B' "$commit" | grep -qiE "^Signed-off-by: .+ <.+@.+>$"; then + continue + fi + echo "::error::commit $commit by $author is missing a Signed-off-by line" + missing=1 + done + if [ "$missing" -ne 0 ]; then + echo "Sign off your commits with 'git commit -s'. See CONTRIBUTING.md and DCO." + exit 1 + fi + echo "All commits are signed off." diff --git a/.gitignore b/.gitignore index 45d21381..f7b28a7d 100644 --- a/.gitignore +++ b/.gitignore @@ -204,13 +204,13 @@ __marimo__/ # Custom *.db .DS_Store + logs/ assets/ debug/ secrets/ scripts/ +research/ documents/ debugging/ -research/ -debug/scroll/poc/ tests/fixtures/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..9240bea8 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,84 @@ +# Agent Instructions + +These instructions are mandatory for every contributor and coding agent — human or model — +working in this repository. Read them in full before you change any tracked file, and never +rely on remembered context in their place. + +Two documents carry the detailed rules, and both are binding. Read both before you design or +edit anything: + +- [standards/engineering.md](standards/engineering.md) — the engineering standard: hexagonal + architecture, naming, typing, data models, logging, and the P0 rules that must never be + broken. +- [standards/review.md](standards/review.md) — the checklist every change is judged against + before it merges, and how to run an independent review. + +When this file and a linked standard disagree, the standard wins. When any rule is unclear or +a material decision is unresolved, stop and ask rather than guess. + +## 1. Understand the work + +Before changing tracked files: + +1. read the request and identify the expected outcome; +2. inspect the current working tree; +3. read the files that own the affected behavior; +4. read the applicable standards and accepted decisions; +5. identify affected boundaries, state, failures, compatibility, security, and tests; +6. stop and ask when a material product or architecture decision is unresolved. + +Never treat remembered context as repository evidence. Re-read relevant source after context +compaction, a handoff, a user correction, or a material scope change. + +## 2. Design before editing + +- Resolve every owner, boundary, dependency, state, failure, file, test, and verification + decision before starting an implementation slice. +- Apply SOLID, separation of concerns, high cohesion, low coupling, dependency inversion, and + composition over inheritance where applicable. +- Preserve the repository's hexagonal layering — the core is pure and depends only on typed + ports; devices, models, and storage plug in as adapters. This direction is enforced by the + tests under `tests/architecture/`. +- Give every module and type one clear responsibility. +- Use strict single-word names; represent multi-word concepts through meaningful nesting. A + leading underscore marks non-public identifiers. +- Use `UPPER_SNAKE_CASE` only for internal semantic string values; preserve values defined by + an external protocol or public contract. +- Use keyword arguments for project-owned calls that pass multiple values. +- Model entities, validated value objects, and anything crossing a boundary with Pydantic + `BaseModel`. Never use `@dataclass`. Validate at the boundary; the domain may assume valid data. +- Do not introduce a dependency, abstraction, interface, or framework without a demonstrated + requirement. +- Treat each slice as a fresh repository review — re-read the applicable standards and owning + code instead of relying on conversation memory. + +## 3. Make the smallest complete change + +- Stay within the requested scope; preserve unrelated and pre-existing work. +- Keep domain policy out of adapters and infrastructure; keep constants, contracts, models, + errors, ports, use cases, adapters, and validators in their owning layer. +- Use explicit, typed contracts at every boundary. Raw `dict`/`tuple` must not cross layers. +- Keep secrets, credentials, and captured user data inside their approved boundaries. +- Do not add speculative features or future-facing scaffolding. +- Keep each module focused on one responsibility rather than growing without bound. +- Do not write unnecessary comments; a justified technical comment is normally one line. + +## 4. Verify with evidence + +1. run the narrowest relevant checks while editing; +2. run the repository checks for the changed area — `ruff check .`, `ruff format --check .`, + `mypy src`, and `pytest`; +3. test real integrations when the result depends on real provider behavior (live tests are + opt-in: `FATHOM_RUN_LIVE_TESTS=1`); +4. inspect the fresh complete diff and working-tree status; +5. review the diff against the design decisions above. + +Never label a failure pre-existing, flaky, or unrelated without reproduction and baseline +evidence. A required check that does not yet exist must be reported as unavailable, not +simulated through prose. + +## 5. Report honestly + +Report the outcome, the changed files, the decisions made, the checks run and their exact +scope, and any unresolved risks or blocked checks. Do not claim approval, completeness, +compliance, or production readiness that has not been demonstrated. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..0bc3d8e8 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,37 @@ +# Changelog + +All notable changes to Fathom are documented here. The format is based on +[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project follows +[Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +Changes landing on the main branch that have not yet been cut into a release are listed +here. + +## [1.1.0] - 2026-08-20 + +Initial public release under the Business Source License 1.1. + +### Added + +- Hexagonal agent core that turns a plain-language intent into grounded device actions on + both Android and iOS, driven entirely by a vision-language model. +- Pluggable ports and adapters for device, model, and perception, wired through a + `FathomBuilder` so any backend can be swapped without touching the core. +- Perception ensemble with opt-in OCR, icon, computer-vision, keyboard, and overlay passes, + plus multi-member localization voting for more reliable grounding. +- Intent decomposition into ordered sub-goals and a LangGraph state machine with + check-pointing, so a run can pause, resume, and replan mid-flight. +- Evidence-driven completion that advances only on observed success, command success, or + captured proof, rather than on model self-reports. +- Human-in-the-loop support to ask the operator, pause, and resume through a signal port. +- Conversation and observability layer recording threads, messages, tasks, and scripts, + with an in-memory default and an optional Postgres backend. +- Priority and adaptive inference that sheds load and recovers when the model provider + slows down or starts rejecting calls. +- Typed `FathomConfiguration` surface plus environment overrides for every optional + subsystem, documented in `.env.template`. + +[Unreleased]: https://github.com/DrizzDev/fathom/compare/v1.1.0...HEAD +[1.1.0]: https://github.com/DrizzDev/fathom/releases/tag/v1.1.0 diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..cc794f15 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,84 @@ + +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at conduct@drizz.dev. All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of actions. + +**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..0218fda3 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,80 @@ +# Contributing to Fathom + +Thanks for your interest in improving Fathom. This guide covers how to build, test, and +submit changes. + +## License and sign-off + +Fathom is distributed under the Business Source License 1.1 (converting to Apache-2.0 on the +date in [LICENSE](LICENSE)). By contributing, you agree that your contribution is licensed +under those same terms. + +Every commit must carry a Developer Certificate of Origin sign-off. Add one by committing +with `-s`: + +```sh +git commit -s -m "Your message" +``` + +This appends a `Signed-off-by: Your Name ` line, which certifies that you +wrote the change or otherwise have the right to submit it under the project license (see +[DCO](DCO)). Pull requests whose commits are not signed off will not pass the sign-off check. + +## Prerequisites + +- **Python 3.11+** +- A vision-language model — a Gemini API key, or Vertex AI credentials +- For device work: Android `adb` / platform-tools, or Xcode and the iOS SDK (WebDriverAgent) + +## Build and verify + +```sh +git clone git@github.com:DrizzDev/fathom.git +cd fathom +pip install -e . +pip install -r requirements.txt +pre-commit install +``` + +CI runs `pre-commit` on every pull request. Run the same checks locally before opening one: + +```sh +pre-commit run --all-files # ruff, formatting, mypy, and repository checks +pytest # tests +``` + +Live tests (which call a real model) are opt-in and skipped by default; set +`FATHOM_RUN_LIVE_TESTS=1` to run them. + +## Standards + +This codebase follows the engineering standards and review checklist in [`AGENTS.md`](AGENTS.md). +In short: + +- One primary responsibility per file; dependencies point toward the owner of policy. +- Boundaries use explicit, typed contracts; the hexagonal layering is enforced by the tests + under `tests/architecture/`. +- Entities and anything crossing a boundary use Pydantic `BaseModel` — never `@dataclass`. +- Focused tests cover real behavior and failure paths, not mocks for their own sake. +- Documentation changes with public behavior, configuration, or architecture. +- Never commit secrets, real `.env` files, device serials, screenshots, or captured + hierarchies. + +## Submitting changes + +1. Open a topic branch from the default branch. +2. Keep the change focused; add tests for new behavior and failure paths. +3. Sign off every commit (`git commit -s`). +4. Make sure `ruff`, `mypy`, and `pytest` pass. +5. Open a pull request and fill in the template, describing the motivation, the change, and + any compatibility or migration considerations. A maintainer will review it; CI must pass + before merge. + +External contributors work from a fork: fork the repository, push your branch to your fork, +and open a pull request against `main`. + +## Reporting bugs and requesting features + +Use GitHub Issues, with clear reproduction steps and your environment (OS, Python version, +device/emulator). For security vulnerabilities, do **not** open a public issue — see +[SECURITY.md](SECURITY.md) and use private reporting instead. diff --git a/DCO b/DCO new file mode 100644 index 00000000..49b8cb05 --- /dev/null +++ b/DCO @@ -0,0 +1,34 @@ +Developer Certificate of Origin +Version 1.1 + +Copyright (C) 2004, 2006 The Linux Foundation and its contributors. + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + + +Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +(a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +(b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +(c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +(d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. diff --git a/INSTALL.md b/INSTALL.md new file mode 100644 index 00000000..6b33c490 --- /dev/null +++ b/INSTALL.md @@ -0,0 +1,44 @@ +# Install Fathom + +## Before you start + +- **Python 3.11+** +- **A device to drive** — an Android device or emulator reachable over `adb` (`adb devices` + should list it), or an iOS device or simulator behind a WebDriverAgent gateway +- **A vision-language model** — a Gemini API key, or Vertex AI credentials + +## 1. Install + +```bash +pip install git+https://github.com/DrizzDev/fathom.git +``` + +Or from a clone, for development: + +```bash +git clone https://github.com/DrizzDev/fathom.git +cd fathom +pip install -e . +``` + +## 2. Configure + +Set your model key (and, for Vertex, your project) in the environment or a local `.env`: + +```bash +export GEMINI_API_KEY="..." # or configure Vertex: VERTEX_PROJECT_ID, VERTEX_LOCATION +``` + +Confirm your device is reachable: + +```bash +adb devices # Android — note the serial for the quickstart +``` + +## 3. Run + +Follow the quickstart in the [README](README.md#quickstart) to wire the device, model, and +perception adapters and run your first intent. For iOS, swap in the `IOSDevice` and +`IOSNativePerceptionAdapter` adapters — they satisfy the same ports. + +A `fathom` command-line entrypoint is also installed; run `fathom --help` for its usage. diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..7a61cd6a --- /dev/null +++ b/LICENSE @@ -0,0 +1,96 @@ +Business Source License 1.1 + +License text copyright (c) 2017 MariaDB Corporation Ab, All Rights Reserved. +"Business Source License" is a trademark of MariaDB Corporation Ab. + +----------------------------------------------------------------------------- + +Parameters + +Licensor: Drizz Automation Technologies Private Limited + +Licensed Work: Fathom + The Licensed Work is (c) 2026 Drizz Automation Technologies + Private Limited. + +Additional Use Grant: You may use, run, and deploy the Licensed Work for any + purpose, including internal production use, provided you + do not offer the Licensed Work, or a modified version of + it, to third parties as a commercial or hosted service, + or as a product that competes with Drizz. + +Change Date: 2030-08-15 + +Change License: Apache License, Version 2.0 + +----------------------------------------------------------------------------- + +Terms + +The Licensor hereby grants you the right to copy, modify, create derivative +works, redistribute, and make non-production use of the Licensed Work. The +Licensor may make an Additional Use Grant, above, permitting limited production +use. + +Effective on the Change Date, or the fourth anniversary of the first publicly +available distribution of a specific version of the Licensed Work under this +License, whichever comes first, the Licensor hereby grants you rights under the +terms of the Change License, and the rights granted in the paragraph above +terminate. + +If your use of the Licensed Work does not comply with the requirements +currently in effect as described in this License, you must purchase a +commercial license from the Licensor, its affiliated entities, or authorized +resellers, or you must refrain from using the Licensed Work. + +All copies of the original and modified Licensed Work, and derivative works of +the Licensed Work, are subject to this License. This License applies separately +for each version of the Licensed Work and the Change Date may vary for each +version of the Licensed Work released by Licensor. + +You must conspicuously display this License on each original or modified copy of +the Licensed Work. If you receive the Licensed Work in original or modified form +from a third party, the terms and conditions set forth in this License apply to +your use of that work. + +Any use of the Licensed Work in violation of this License will automatically +terminate your rights under this License for the current and all other versions +of the Licensed Work. + +This License does not grant you any right in any trademark or logo of Licensor +or its affiliates (provided that you may use a trademark or logo of Licensor as +expressly required by this License). + +TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON AN +"AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EXPRESS +OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND TITLE. + +MariaDB hereby grants you permission to use this License's text to license your +works, and to refer to it using the trademark "Business Source License", as long +as you comply with the Covenants of Licensor below. + +Covenants of Licensor + +In consideration of the right to use this License's text and the "Business +Source License" name and trademark, Licensor covenants to MariaDB, and to all +other recipients of the licensed work to be provided by Licensor: + +1. To specify as the Change License the GPL Version 2.0 or later, or a license + that is compatible with GPL Version 2.0 or later, where "compatible" means + that software provided under the Change License can be included in a program + with software provided under GPL Version 2.0 or later. Where the Change + License is not compatible with GPL Version 2.0 or later, Licensor must + specify an alternative license that is compatible with the terms of this + Covenant. To be clear, this Covenant does not affect the terms under which + the software provided under the Change License can be used. + +2. To specify a Change Date. + +3. To not modify this License in any other way. + +Notice + +The Business Source License (this document, or the "License") is not an Open +Source license. However, the Licensed Work will eventually be made available +under an Open Source License, as stated in this License. diff --git a/README.md b/README.md index 3725e2f8..cb4ad6a5 100644 --- a/README.md +++ b/README.md @@ -1,135 +1,516 @@ # Fathom -**Fathom** is a robust agentic framework for mobile automation, designed to reliably execute complex workflows using visual understanding and intelligent planning. +**Fathom is an execution harness for mobile agents.** Hand it a plain-language goal — *"log in and +open the orders page"* — and it drives a real device, **iOS or Android**, to completion: reading each +screen, deciding the next action, dispatching it, verifying the action actually happened, and +recovering when it stalls. + +It owns the hard parts between a high-level goal and low-level taps — decomposing intent into +sub-goals, grounding to the right on-screen element, breaking out of loops, and asking a human when +genuinely stuck — so whatever sits on top (an agent, a test author, a generated script) works in +*intent*, not taps. + +The same core runs two ways — a goal-directed **intent run** or an autonomous **self-exploration** +crawl — and you drive it from an in-process **SDK**, a **CLI**, or a durable **Temporal** worker. +Device, model, and storage sit behind typed ports, so switching Android to iOS, Gemini to Vertex, or +local to cloud is a configuration change, not a rewrite. + +## Highlights + +- **Two strategies, one core.** Drive toward a specific goal with an **intent run**, or map an app + automatically with **self-exploration** — both are LangGraph state machines over the same ports. +- **Host-agnostic.** Run the same agent from an **SDK builder**, a **CLI**, or a **Temporal** worker + for durable, resumable execution with out-of-process human-in-the-loop control. +- **Plug-and-play.** Every capability — device, model, perception, memory, knowledge, storage, + telemetry, conversation, signals — is a typed **port** with swappable **adapters**. Wire the ones + you need with a fluent builder; replace any of them without touching the core. +- **Configurable end to end.** A single typed `FathomConfiguration` turns subsystems on and off and + tunes them: which perception signals run, ensemble membership, elevated-capacity inference, storage + backends, checkpointing, per-device settings, and the qualifier — all with safe defaults. +- **Cross-platform.** iOS (over WebDriverAgent) and Android (over ADB) sit behind the same device and + perception ports; you swap the adapter, not your code. +- **Evidence-based.** A sub-goal advances only when the screen, a matched action, or a committed + capture proves it — never because the model claimed success. +- **Observable.** Every run is recorded as a structured conversation (threads, messages, tasks, + artifacts, generated scripts) behind an interaction port, alongside structured telemetry. + +## Two ways to drive a device + +Fathom ships two strategies. Both share the same grounding, execution, and recording primitives and the +same LangGraph infrastructure; they differ in what they are trying to achieve. + +### Intent runs — goal-directed + +Given a plain-language goal and an app, Fathom qualifies the intent, decomposes it into ordered +sub-goals, and works toward them one turn at a time. Each turn perceives the screen, makes one +vision-language-model decision, localizes and dispatches the action, and then proves the sub-goal from +evidence before advancing. One pass through the loop: -It bridges the gap between high-level intent ("login to the app") and low-level execution (adb taps/swipes), handling retry logic, error recovery, and loop detection automatically. +```mermaid +%%{init: { + "theme": "base", + "fontFamily": "Arial", + "flowchart": {"htmlLabels": false}, + "themeVariables": { + "background": "#FCFBF8", + "primaryColor": "#F3EFF9", + "primaryTextColor": "#334155", + "primaryBorderColor": "#B8A6D1", + "lineColor": "#94A3B8", + "secondaryColor": "#EDF7F4", + "tertiaryColor": "#F8F3EA", + "clusterBkg": "#FAF8F4", + "clusterBorder": "#D9D3C8", + "edgeLabelBackground": "#FCFBF8" + } +}}%% + +flowchart TD + subgraph Prepare["PREPARE"] + direction LR + Goal["Goal"] --> Qualify["Qualify"] --> Decompose["Decompose"] + end + + subgraph Turn["ONE TURN"] + direction LR + Ground["Ground"] --> Analyze["Analyze"] --> Execute["Execute"] --> Observe["Observe"] + end + + subgraph Outcome["OUTCOME"] + direction LR + Retry["Retry"] + Prove{"Proven?"} + Advance["Advance"] + Escalate["Escalate"] + end + + Decompose --> Ground + Observe --> Prove + Prove -->|Not Yet| Retry --> Ground + Prove -->|Yes| Advance --> More{"More Goals?"} + More -->|Yes| Ground + More -->|No| Result["IntentResult"] + Prove -->|Stuck| Escalate +``` + +Before the loop begins, a **qualifier** decides whether the intent is an executable UI task, and a +**decomposer** breaks it into ordered sub-goals. Each turn then runs **Ground** (capture + perceive), +**Analyze** (one vision-language-model call), **Supervise** (localize the target), **Execute** +(dispatch the gesture), **Observe** (did the screen change?), **Record** (persist the step), and +**Verify** (adjudicate the sub-goal from evidence, then advance, retry, or escalate). + +### Self-exploration — autonomous app-mapping + +With no goal to chase, Fathom can explore an app on its own: it repeatedly grounds the current screen, +asks the model for one *unique interactive element* to try, executes it, and records the screen and the +transition into an **app-map** (screens keyed by a visual fingerprint, plus the actions tried on each). +It tracks a frontier of screens that still have unexplored elements and keeps going until it runs out +of steps or time, or the frontier is empty. Exploration is **visual-only** — it does not use the +accessibility hierarchy — and produces a coverage map rather than a pass/fail result. + +```mermaid +%%{init: { + "theme": "base", + "fontFamily": "Arial", + "flowchart": {"htmlLabels": false}, + "themeVariables": { + "background": "#FCFBF8", + "primaryColor": "#F3EFF9", + "primaryTextColor": "#334155", + "primaryBorderColor": "#B8A6D1", + "lineColor": "#94A3B8", + "secondaryColor": "#EDF7F4", + "tertiaryColor": "#F8F3EA", + "clusterBkg": "#FAF8F4", + "clusterBorder": "#D9D3C8", + "edgeLabelBackground": "#FCFBF8" + } +}}%% + +flowchart TD + Start["Start"] --> Ground + + subgraph Explore["EXPLORE"] + direction LR + Ground["Capture"] --> Discover["Discover"] --> Execute["Execute"] + end + + subgraph Learn["LEARN"] + direction LR + Record["Record"] --> Map[("App Map")] --> Frontier{"Frontier Remains?"} + end + + Execute --> Record + Frontier -->|Yes| Ground + Frontier -->|No| Done["Complete"] +``` + +> Self-exploration is an earlier-stage capability than intent runs. Frontier tracking and the app-map +> are in place; richer path-replay navigation between screens is still being built out. -## Features +## Running Fathom -- **Intelligent Agent**: Uses LLMs (Gemini, etc.) to understand screen content and plan actions. -- **Robust Workflow Engine**: Built-in state management, check-pointing, and retry logic. -- **Real Device Support**: First-class support for ADB and Appium, controlling real phones and emulators. -- **Auto-Recovery**: Detects loops (stuck on same screen) and automatically attempts recovery (Back -> Home). -- **Hybrid State Hashing**: Efficiently tracks visited states using perceptual, structural, and content hashing. +The same runner core — `FathomRunner`, with `run_intent` and `run_exploration` — sits behind three host +surfaces. You pick a strategy by choosing a run method (SDK), a subcommand (CLI), or a workflow +(Temporal); all three support both strategies. -## Installation +```mermaid +%%{init: { + "theme": "base", + "fontFamily": "Arial", + "flowchart": {"htmlLabels": false}, + "themeVariables": { + "background": "#FCFBF8", + "primaryColor": "#F3EFF9", + "primaryTextColor": "#334155", + "primaryBorderColor": "#B8A6D1", + "lineColor": "#94A3B8", + "secondaryColor": "#EDF7F4", + "tertiaryColor": "#F8F3EA", + "clusterBkg": "#FAF8F4", + "clusterBorder": "#D9D3C8", + "edgeLabelBackground": "#FCFBF8" + } +}}%% + +flowchart TB + subgraph Entry["HOST SURFACES"] + direction LR + Hosts["CLI · SDK · Temporal"] + Runner["FathomRunner"] + Hosts --> Runner + end + + subgraph Execution["RUN STRATEGIES"] + direction LR + Strategies["Intent Run · Self-Exploration"] + Ports["Typed Ports and Adapters"] + Strategies --> Ports + end + + Runner --> Strategies +``` + +- **SDK (in-process).** `Fathom.builder()` returns a fluent builder; wire the ports you need and call + `build()` to get a `FathomRunner`, then `await runner.run_intent(...)` or `run_exploration(...)`. Best + when Fathom is embedded inside a larger Python service. +- **CLI.** The installed `fathom` command exposes `fathom run ""` for an intent run and + `fathom explore` for autonomous mapping, with flags for platform, device, model key, and step budget. + Best for quick local runs and scripting. +- **Temporal (durable).** Optional `fathom[temporal]` extra. `FathomWorkflow` and + `FathomExplorationWorkflow` run on a worker; the real work happens in retryable, heartbeated + activities, and Temporal **signals** (`pause`, `resume`, `inject`, `cancel`) let a human steer or + interrupt a live run from **outside the process** — surviving restarts. Best for production fleets and + long-running, resumable jobs with human-in-the-loop control. + +## Architecture + +Fathom is a **hexagonal (ports-and-adapters)** application, and the layering is mandatory. The core +agent logic is pure and depends only on typed ports; the outside world — hosts, devices, models, +storage — plugs in as adapters. That is what keeps the core testable, vendor-neutral, cross-platform, +and host-agnostic. + +```mermaid +%%{init: { + "theme": "base", + "fontFamily": "Arial", + "flowchart": {"htmlLabels": false}, + "themeVariables": { + "background": "#FCFBF8", + "primaryColor": "#F3EFF9", + "primaryTextColor": "#334155", + "primaryBorderColor": "#B8A6D1", + "lineColor": "#94A3B8", + "secondaryColor": "#EDF7F4", + "tertiaryColor": "#F8F3EA", + "clusterBkg": "#FAF8F4", + "clusterBorder": "#D9D3C8", + "edgeLabelBackground": "#FCFBF8" + } +}}%% + +flowchart TB + subgraph Application["APPLICATION"] + direction LR + Hosts["Hosts"] --> Runner["FathomRunner"] --> Core["Agent Core"] + end + + subgraph Integration["INTEGRATION BOUNDARY"] + direction LR + Ports["Typed Ports"] --> Adapters["Pluggable Adapters"] + end + + Core --> Ports +``` + +## Inside the pipeline + +These stages power an intent run. Each concern is its own layer behind a port, so it can be tuned, +replaced, or turned off independently. + +- **Qualification.** An intent qualifier decides whether a request is an executable UI task before any + device work happens, so gibberish and conversational prompts never reach the device. It runs on its + own model configuration and can be disabled entirely. +- **Decomposition.** The decomposer turns one intent into an ordered list of typed sub-goals — observed + outcomes, command postconditions, or captures — each carrying the evidence that will later prove it. +- **Perception and the ensemble.** Perception reads the screen through layered signals — the platform + view hierarchy plus optional OCR, icon-template, and computer-vision detectors. Ensemble services + merge multiple detectors and localizers and let them vote, so grounding degrades gracefully instead + of failing when any one signal is weak. Every signal is opt-in through configuration. +- **Grounding.** Locating a target falls back through progressively richer signals rather than tapping + blind, so it works whether or not a clean hierarchy is available. + +```mermaid +%%{init: { + "theme": "base", + "fontFamily": "Arial", + "flowchart": {"htmlLabels": false}, + "themeVariables": { + "background": "#FCFBF8", + "primaryColor": "#F3EFF9", + "primaryTextColor": "#334155", + "primaryBorderColor": "#B8A6D1", + "lineColor": "#94A3B8", + "secondaryColor": "#EDF7F4", + "tertiaryColor": "#F8F3EA", + "clusterBkg": "#FAF8F4", + "clusterBorder": "#D9D3C8", + "edgeLabelBackground": "#FCFBF8" + } +}}%% + +flowchart TD + subgraph Structured["STRUCTURED SIGNALS"] + direction LR + Target["Target"] --> Signals{"Match?"} + Signals -->|Yes| Bounds["On-Screen Bounds"] + end + + subgraph Fallback["VISUAL FALLBACK"] + direction LR + Vision["Visual Localization"] --> Resolved{"Resolved?"} + Resolved -->|No| Unresolved["Report Unresolved"] + end + + Signals -->|No| Vision + Resolved -->|Yes| Bounds +``` + +- **Planning.** The intent graph is a **LangGraph** state machine with typed channels and a checkpoint + store, so a run can pause, resume, and survive a process restart. Nodes are thin handlers; the heavy + decision logic lives in the pure core. +- **Verification and completion.** Completion is evidence-driven: each turn produces typed evidence, + and an advancement policy decides the outcome — never the model's word alone. + +```mermaid +%%{init: { + "theme": "base", + "fontFamily": "Arial", + "flowchart": {"htmlLabels": false}, + "themeVariables": { + "background": "#FCFBF8", + "primaryColor": "#F3EFF9", + "primaryTextColor": "#334155", + "primaryBorderColor": "#B8A6D1", + "lineColor": "#94A3B8", + "secondaryColor": "#EDF7F4", + "tertiaryColor": "#F8F3EA", + "clusterBkg": "#FAF8F4", + "clusterBorder": "#D9D3C8", + "edgeLabelBackground": "#FCFBF8" + } +}}%% + +flowchart TD + Evidence["Typed Turn Evidence"] --> Policy["Advancement Policy"] + Policy --> Result{"Decision"} + Result -->|Proven| Advance["ADVANCE"] + Result -->|Not Proven| Retain["RETAIN AND RETRY"] + Result -->|Stuck or Refuted| Escalate["ESCALATE OR FAIL"] +``` + +- **Human-in-the-loop.** When the agent is genuinely stuck, or when a step needs a human, an HITL + service asks a question and waits on the signal port. It pauses and resumes the run cleanly, records + the exchange, and injects the answer as guidance. Under the Temporal host this becomes durable and + out-of-process — a human can pause, inject context, or cancel a live run from anywhere. +- **Conversation and observability.** Every run is recorded through an interaction port as a structured + conversation — threads, messages, tasks, linked artifacts, and generated scripts — so a run is fully + re-constructable after the fact. Ships with a Postgres adapter and a no-op adapter for local use. + +## Plug-and-play + +Nothing in the core is bound to a vendor. Each concern is a typed port with one or more adapters, and +you assemble a runner by wiring only the ports you need. Four ports are required — **device, model, +perception, conversation** — and the rest default to sensible local implementations. + +- **Device:** ADB for Android, WebDriverAgent for iOS, and remote-device adapters; replace them through + `DevicePort`. +- **Model:** Gemini through a direct API key or Vertex AI; replace it through `LLMPort`. +- **Perception:** Android, iOS, and remote perception with optional OCR, icon, and CV ensembles; + replace them through `PerceptionPort`. +- **Conversation:** Postgres and no-op adapters; replace them through `InteractionPort`. +- **Memory and knowledge:** SQLite by default; replace them through `MemoryPort` and `KnowledgePort`. +- **Storage:** local, GCS, and composite adapters; replace them through `StoragePort`. +- **Signals:** no-op, interactive, socket, and Temporal adapters; replace them through `SignalPort`. +- **Telemetry and summarization:** structured logging, Redis, and LLM summarization adapters behind + their corresponding ports. + +The same Gemini adapter serves both hosted options: pass an **API key** for direct Gemini, or provide +**Vertex AI** project and credentials instead, and it routes accordingly — no code change. + +## Configuration + +Everything is configured through one typed `FathomConfiguration` with safe defaults, plus environment +variables for credentials. You choose which perception signals run (OCR, CV, icon, overlay), the +ensemble members, whether elevated-capacity inference is enabled, the storage backends, per-device +settings for Android and iOS, checkpointing, and whether the intent qualifier runs — without editing +core code. A copy-ready `.env.template` documents the full set; the most common variables: + +| Variable | Purpose | +| --- | --- | +| `GEMINI_API_KEY` | API key for the Gemini model adapter | +| `GEMINI_MODEL` | Model id to use — set this to a model your key can access | +| `VERTEX_PROJECT_ID` / `VERTEX_LOCATION` | Use Vertex AI instead of a direct API key | +| `GOOGLE_APPLICATION_CREDENTIALS` | Path to a service-account JSON for Vertex | + +## Requirements + +- **Python 3.11+** +- A **vision-language model** — a **Gemini API key**, or Vertex AI credentials +- **A real device, emulator, or simulator** — Android over **ADB** (`adb devices` should list it), or + iOS over a **WebDriverAgent** gateway +- **Optional:** a running **Temporal** cluster, only if you use the durable host + +## Install ```bash pip install git+https://github.com/DrizzDev/fathom.git ``` -Or for development: +With the optional durable host: + +```bash +pip install "fathom[temporal] @ git+https://github.com/DrizzDev/fathom.git" +``` + +From source (for development): ```bash git clone https://github.com/DrizzDev/fathom.git cd fathom -pip install -e "." +pip install -e . ``` -## Quick Start +## Quickstart -### 1. Configuration +Set your model key and pick a device serial (`adb devices` prints it): -Set up your tools (ADB and Vision): +```bash +export GEMINI_API_KEY="..." # your Gemini API key +``` -```python -from fathom.tools.device import ADBDeviceTool, ADBConfig -from fathom.tools.vision import GeminiVisionTool, GeminiConfig -from fathom.tools.capture import ADBCaptureTool - -# Initialize tools -device = ADBDeviceTool(ADBConfig(device_serial="emulator-5554")) -capture = ADBCaptureTool() -vision = GeminiVisionTool(GeminiConfig(api_key="YOUR_API_KEY")) +### CLI — the fastest way + +```bash +# Goal-directed intent run +fathom run "Open the orders page and confirm the latest order is delivered" \ + --platform android --serial emulator-5554 --max-steps 40 + +# Autonomous self-exploration (experimental) +fathom explore --platform android --serial emulator-5554 --max-steps 60 ``` -### 2. Run an Intent Workflow +Run `fathom --help`, `fathom run --help`, or `fathom explore --help` for every flag (iOS options, +Vertex, interactive human-in-the-loop, verbosity, and more). + +### SDK — embed it in Python -Execute a specific goal: +Wire an adapter for each required port with the fluent builder, then run an intent: ```python import asyncio -from fathom.workflows import IntentWorkflow, WorkflowConfig - -async def main(): - workflow = IntentWorkflow( - workflow_id="login-flow-001", - device=device, - capture=capture, - vision=vision, - intent="Login with username 'user' and password 'pass'", - config=WorkflowConfig( - max_steps=50, - step_timeout=10.0 - ) +import os + +from fathom.runtime.builder import Fathom +from fathom.adapters.device.local.adb import ADBDevice +from fathom.adapters.llm.gemini import GeminiLLM +from fathom.adapters.perception.android import AndroidPerceptionAdapter +from fathom.adapters.interaction.noop import NoopInteraction +from fathom.schemas.run import Principal + + +async def main() -> None: + device = ADBDevice(serial="emulator-5554") + llm = GeminiLLM(api_key=os.environ["GEMINI_API_KEY"]) + + interaction = NoopInteraction() + perception = AndroidPerceptionAdapter(device=device, include_hierarchy=True) + + runner = ( + Fathom.builder() + .with_llm(port=llm) + .with_device(port=device) + .with_perception(port=perception) + .with_interaction(port=interaction) + .build() ) - result = await workflow.execute() + result = await runner.run_intent( + max_steps=40, + request_id="run-001", + package_name="com.example.app", + intent="Open the orders page and confirm the latest order is delivered", + principal=Principal(tenant="demo", operator="you", agent="fathom", conversation="thread-001"), + ) + print(result) + await runner.cleanup() - if result.status == "success": - print("Login successful!") - else: - print(f"Failed: {result.error}") if __name__ == "__main__": asyncio.run(main()) ``` -### 3. Run an Exploration Workflow +To map an app instead of chasing a goal, call `runner.run_exploration(...)` with the same `request_id` +and `principal`. For **iOS**, swap the two platform adapters — `IOSDevice` and +`IOSNativePerceptionAdapter` — and leave the rest unchanged; they satisfy the same ports. -Discover available screens and actions: +### Temporal — durable and resumable -```python -from fathom.workflows import ExplorationWorkflow - -async def explore(): - explorer = ExplorationWorkflow( - device=device, - vision=vision, - capture=capture, - workflow_id="explore-001", - config=WorkflowConfig(max_steps=100) - ) +Register `FathomWorkflow` / `FathomExplorationWorkflow` and the `FathomActivities` on a worker, then +start a workflow from your client. The activity does the work and heartbeats progress; the workflow +carries durable state and accepts `pause` / `resume` / `inject` / `cancel` signals so a human can steer +a live run across process restarts. See the `fathom.runtime.temporal` package for the worker wiring. - result = await explorer.execute() - print(f"Discovered {result.unique_screens} unique screens") - print(f"Coverage: {result.coverage_percentage:.1f}%") +## Privacy & data -if __name__ == "__main__": - asyncio.run(explore()) -``` - -## Architecture +To plan actions, Fathom captures screenshots and the on-screen view hierarchy of the app under +automation. By default these artifacts stay on the local machine; cloud upload is off unless you +explicitly enable a cloud storage backend and provide a bucket. Only run Fathom against apps and data +you are authorized to automate. -Fathom is built in layers: +## Contributing -1. **Workflows**: High-level orchestration (Intent, Exploration). Manages lifecycle and results. -2. **Agent Strategy**: The "brain" logic (Loop detection, Recovery, Planning, Reasoning). -3. **Tools**: Interfaces for outside world (Device, Vision, Capture). -4. **Orchestration**: Execution engine (Step tracking, retries, history). - -```mermaid -graph TD - Workflow --> Strategy - Strategy --> Reasoner - Strategy --> Planner - Planner --> Tools - Tools --> Device - Tools --> Cloud_API -``` +Contributions are welcome — see [`CONTRIBUTING.md`](CONTRIBUTING.md), the engineering standards in +[`AGENTS.md`](AGENTS.md), and our [`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md). To report a security issue +privately, see [`SECURITY.md`](SECURITY.md). ## Development -Install dev dependencies and pre-commit hooks: - ```bash +pip install -e . pip install -r requirements.txt pre-commit install ``` -Run checks: +Run the same checks CI runs: ```bash -ruff check . -mypy src +pre-commit run --all-files # ruff, formatting, mypy, and repository checks +pytest # tests ``` + +## License + +Fathom is released under the **Business Source License 1.1** — see [`LICENSE`](LICENSE). Under BSL, the +source is available now and converts to a fully open-source license on the date stated in the license +file. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000..67b93a08 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,31 @@ +# Security Policy + +## Reporting a vulnerability + +Please do **not** open a public issue for security vulnerabilities. + +Report privately through GitHub's +[private vulnerability reporting](https://github.com/DrizzDev/fathom/security/advisories/new), +or email **security@drizz.dev**. + +Please include: + +- a description of the issue and its impact, +- steps to reproduce or a proof of concept, +- the affected version and your environment (OS, Python version). + +We aim to acknowledge a report within three business days and to keep you updated as we +investigate and prepare a fix. Please give us a reasonable window to release a fix before +any public disclosure. + +## Data handling + +To plan actions, Fathom captures screenshots and the on-screen view hierarchy of the app +under automation. These artifacts are written to the local machine by default; cloud upload +is off unless you explicitly enable a cloud storage backend and provide a bucket. Only run +Fathom against apps and data you are authorized to automate, and never commit captured +screenshots, hierarchies, device serials, or `.env` files. + +## Supported versions + +Security fixes are provided for the latest released version. diff --git a/pyproject.toml b/pyproject.toml index 82d7d69f..69dc93b7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,7 +8,7 @@ version = "1.1.0" readme = "README.md" description = "Vision-driven agent orchestration framework for UI crawling" -license = "MIT" +license = "BUSL-1.1" requires-python = ">=3.11" authors = [ { name = "Drizz", email = "tech@drizz.dev" }, @@ -28,7 +28,7 @@ keywords = [ classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", - "License :: OSI Approved :: MIT License", + "License :: Other/Proprietary License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.11", @@ -192,7 +192,7 @@ disallow_subclassing_any = false # inside test modules. search-path = ["src", "."] project-includes = ["src/**/*.py", "tests/**/*.py"] -project-excludes = ["**/.venv/**", "**/__pycache__/**"] +project-excludes = ["**/.venv/**", "**/__pycache__/**", "**/*.toml"] fallback-python-interpreter-name = "python" [tool.pytest.ini_options] diff --git a/standards/README.md b/standards/README.md new file mode 100644 index 00000000..a60b8ea6 --- /dev/null +++ b/standards/README.md @@ -0,0 +1,8 @@ +# Engineering standards + +The detailed rules every contributor and coding agent follows in this repository. +Start from [`AGENTS.md`](../AGENTS.md) at the repository root; this directory holds the +full detail it points to. + +- [engineering.md](engineering.md) — the engineering and architecture standard. +- [review.md](review.md) — the review checklist applied to every change. diff --git a/.claude/.skills/.engineering/.standards/SKILL.md b/standards/engineering.md similarity index 70% rename from .claude/.skills/.engineering/.standards/SKILL.md rename to standards/engineering.md index fae3ee4b..1527b319 100644 --- a/.claude/.skills/.engineering/.standards/SKILL.md +++ b/standards/engineering.md @@ -1,6 +1,7 @@ # Engineering & Architecture Standard -Use this skill for any coding, architecture, refactor, implementation-plan, PRD, design-review, or code-audit task in this workspace unless the user explicitly says otherwise. +Apply this standard to any coding, architecture, refactor, implementation-plan, design-review +or code-audit task in this repository unless explicitly stated otherwise. ## Non-negotiable goals @@ -16,6 +17,32 @@ All systems must be: Readability, maintainability, and performance must coexist. Do not trade one away casually. +## P0 — non-negotiable rules + +These rules are blockers. A change that violates any of them does not merge, regardless of what else it +accomplishes. + +- **Hexagonal architecture is mandatory.** The whole system is built on ports and adapters, and every + change must honor the layering: the pure core depends only on typed ports, and vendors, devices, and + infrastructure live behind adapters. There is no exception and no "just this once." +- **No standalone functions.** Everything is a class with appropriate instance, class, or static + methods. A module-level function is allowed only for a genuinely pure, stateless transformation — + never for behavior, state, or orchestration. A single stray standalone function is a blocker. +- **No random flags or variables.** Do not sprinkle ad-hoc booleans, string flags, or loose variables + to steer behavior. Model control flow with explicit state machines, enums, and typed models; state + that drives a decision belongs in a state object, not a local variable threaded through calls. +- **One-word, generic names.** Folders, files, and modules use a single generic `snake_case` word. + Represent multi-word concepts through nesting, not compound names. Long, ugly compound identifiers + are rejected on sight. +- **Dot notation wherever it fits.** Prefer nested structure over flattened compound names — Pydantic + fields read as `ocr.enabled`, not `ocr_enabled`. Group related settings and values under a parent so + the shape, not the string, carries the meaning. +- **Structured logging only.** Every significant boundary emits a structured, machine-parseable event + with a stable `event` and `component`, never a bare formatted string. Logging lives in outer layers, + never in the domain, and never records sensitive values. +- **No `@dataclass` anywhere.** Pydantic `BaseModel` is the only entity and boundary model, with + `Field(description=...)` on each field; raw `dict`/`tuple` must never cross a layer boundary. + ## 1. Architecture Use a strict layered architecture: @@ -61,7 +88,10 @@ Formats: - Protected / Internal: `_snake_case` - Constant: `UPPER_SNAKE_CASE` - Enum member name: `UPPER_SNAKE_CASE` -- Enum member value: `UPPER_SNAKE_CASE` for internal/semantic enums (the value mirrors the member name). The only exception is an enum whose values form an external or rendered protocol vocabulary — tokens emitted verbatim into rendered output, an external API/tool contract, or a persisted wire format — which keep their literal protocol form. +- Enum member value: `UPPER_SNAKE_CASE` for internal/semantic enums (the value mirrors the member name). + The only exception is an enum whose values form an external or rendered protocol vocabulary — + tokens emitted verbatim into rendered output, an external API/tool contract, or a persisted wire + format — which keep their literal protocol form. - Module: `snake_case` ## 4. Imports @@ -300,10 +330,24 @@ Levels: Rules: -- Domain tests must be infrastructure-free -- tests must be deterministic -- test observable behavior, not internals -- critical path coverage is non-negotiable +- Domain tests must be infrastructure-free, deterministic, and assert observable behavior, not internals. +- Every test is a class (no function-based tests) and mirrors the source file and folder structure. +- Add a test only when it pins real behavior. Each test states a concrete input and asserts a concrete + output or state transition; it must be able to fail if the behavior regresses. + +What to test, deliberately: + +- The happy path of the changed behavior, plus each distinct branch and every failure and edge path. +- Boundary and invariant conditions — empty, missing, malformed, over-limit, and the exact threshold. +- For a bug fix, both the failing case and the sibling negative case (that the correct thing still works). +- The real path the behavior walks in production — never a path the test itself fabricates to pass. + +What is not a test, and must not be added: + +- Asserting that a mock was called, or mocking the very thing under test, with no assertion on real output. +- Restating what `__init__` set (a getter or round-trip), or asserting only `is not None` / `isinstance`. +- Re-testing framework behavior (that Pydantic rejects a wrong type, that an enum equals its literal). +- "No exception raised" with no outcome checked, or an assertion that cannot fail. ## 30. Controlled complexity @@ -330,7 +374,7 @@ Prohibited: - global mutable state - magic numbers or strings without named constants -## How to apply this skill +## How to apply this standard When implementing or reviewing: @@ -344,15 +388,23 @@ When implementing or reviewing: For Fathom work, below are strictly compulsory to follow -- Proper layered and nested structure, be it folder, files, or classes, entities, it's fields, and always use single word names for folder, files, etc... +- Proper layered and nested structure, be it folder, files, or classes, entities, it's fields + and always use single word names for folder, files, etc... - Proper usages of design pattern, considering all basic coding concepts like OOPS, SOLID, SRP, OCP, LSP, Hexagonal Architecture - Using Pydantic for entities with Fields, 1 line descriptions, and defining it at correct files/location (schemas) - No hardcoded constants/values, define things inside constants (Use IntEnum, StrEnum, etc...) - Don't use any unit(ms, s, etc..) as prefix/suffix for any variables/fields, use description to convey what it means -- Use elegant, beautiful, sort, generic names for functions, variables, fields (Eg: For Pydantic/Fields, I prefer nested fields, Eg: ocr.enabled and not ocr_enabled, etc...) -- Always use __ and not _ for private methods/variables, and use __methods to make code readable, making function non-bloated, etc... -- Doc string should be in format of """\n Crisp, to the point doc-string\n""" and """doc-string""" -- UTs should follow same file/folder structure, and each UT should be class, no function based UTs, and UT should cover actual real cases and not vague, random, fake cases -- I don't like standalone functions at all, everything should be class with proper functions (instance method, class/static methods depending on its nature) -- Nothing should violate HEXAGONAL ARCHITECTURE In any case, We've to maintain SRP, OOPS, Other basic coding standards at all cost, this is non-negotiable -``` +- Use elegant, short, generic names for functions, variables, and fields. Prefer nested fields for Pydantic models (`ocr.enabled`, not `ocr_enabled`). +- Always use `__` (not `_`) for private methods and variables, to keep functions readable and un-bloated. +- Docstrings always use the multi-line form, with the triple-quotes on their own lines, even for one-liners: + + ```python + """ + Crisp, to-the-point docstring. + """ + ``` + +- Unit tests mirror the source file and folder structure; every test is a class (no function-based tests) and covers real cases + not vague or fabricated ones. +- Avoid standalone functions; model behavior as classes with appropriate instance, class, or static methods. +- Nothing may violate the hexagonal architecture; SRP, OOP, and the other standards above are non-negotiable. diff --git a/.claude/.skills/.engineering/.reviews/CHECKLIST.MD b/standards/review.md similarity index 58% rename from .claude/.skills/.engineering/.reviews/CHECKLIST.MD rename to standards/review.md index 851f2925..5bdec9a3 100644 --- a/.claude/.skills/.engineering/.reviews/CHECKLIST.MD +++ b/standards/review.md @@ -1,78 +1,114 @@ -You are a Staff/Principal Software Engineer reviewing a branch or PR against the Fathom codebase. Your job is not to approve. Your job is to find every bug, design flaw, missed surface, heuristic-on-heuristic patch, untested branch, broken contract, hidden assumption, observability gap, regression risk, and standards violation before this code ships to prod. - -You will be graded on what you miss, not on how polite you are. Be skeptical. Optimize for correctness, root-cause clarity, and long-term code health. Do not optimize for approval. +You are a Staff/Principal Software Engineer reviewing a branch or PR against the Fathom codebase. Your job is not to approve. +Your job is to find every bug, design flaw, missed surface, heuristic-on-heuristic patch, untested branch, broken contract +hidden assumption, observability gap, regression risk, and standards violation before this code ships to prod. + +You will be graded on what you miss, not on how polite you are. Be skeptical. +Optimize for correctness, root-cause clarity, and long-term code health. Do not optimize for approval. + +# How to run this review + +- Run this as an independent pass in its own context, not folded into the change that produced the + diff. A fresh reviewer, unattached to the author's reasoning, catches what the author's context hides. +- Load and strictly follow this file and the [engineering standard](engineering.md). They are the + contract, not suggestions; when they conflict with generic engineering instincts, they win. +- Optimize for token and context budget. Read the diff and the files that own the changed behavior, not + the whole repository. Pull only the surrounding context each hunk needs, verify claims with targeted + greps and file reads, and spend depth on the load-bearing changes rather than skimming everything + shallowly. Depth on what matters beats breadth on what does not. +- The P0 rules in the engineering standard are automatic blockers here: any hexagonal violation, any + standalone function, ad-hoc flags in place of a state machine, non-generic or multi-word file and + folder names, flattened names that should be dot-nested, unstructured logging, or any `@dataclass`. # Operating rules for this repo -These are the user's review preferences. Internalize them; they override generic engineering instincts when they conflict. - -1. **Proof before claim.** Never assert a bug, fix, behavior, or coverage gap without naming the exact `file:line`, the exact log line, the exact test name, or the exact opened artifact. No `~25% coverage` estimates; enumerate the tests. No "this might be missing"; verify. -2. **Root cause only.** Reject patches, workarounds, and "make it pass" fixes. Reject any change that addresses the symptom without proving the symptom's mechanism. If the author can't explain why the issue occurred and why the fix prevents recurrence, request changes. -3. **No heuristics on heuristics.** Runtime string-match branches (`if word in intent.lower(): rules.append(...)`) are technical debt. Any new instance is a blocker unless the author explicitly justifies why a structural fix is impossible. Removing existing ones is a feature. -4. **No fabricated reads.** Never claim to have read a file you didn't. Never grep for an expected keyword and assume absence means absence — names you didn't predict will hide the test. -5. **Stale-source check.** Confirm `stat -f "%Sm" ` lines up with when the diff was last edited. Old reads of recently-rewritten code are how false reviews ship. -6. **No silent coverage.** "Tests pass" is not a review signal. Enumerate which tests exercise which branch of the changed surface; identify untested branches by name. -7. **Compliance with SKILL.md is non-negotiable.** Every diff must satisfy `/fathom/.claude/.skills/.engineering/.standards/SKILL.md`. The SKILL.md compliance section below lists the specific rules to verify. -8. **Memory & artifacts.** Investigation downloads (CloudWatch dumps, GCS assets) live under `/fathom/debug//`, never `/tmp`. Reference paths absolutely. - -# SKILL.md compliance — verify before reviewing logic - -Open `/fathom/.claude/.skills/.engineering/.standards/SKILL.md` and confirm the diff respects every rule listed there. Specifically: - -**Architecture (SKILL.md §1, §10, §24, plus the Fathom-specific reminder)** -- Hexagonal architecture is non-negotiable. Domain (`schemas/`, `constants/`) depends on nothing. Application (`core/`) depends only on Domain and Ports (`interfaces/`). Adapters (`adapters/`, `runtime/`, `infrastructure/`) depend inward only. +These are the review preferences for this repository. Internalize them; they override generic engineering instincts when they conflict. + +1. **Proof before claim.** Never assert a bug, fix, behavior, or coverage gap without naming the exact `file:line` + the exact log line, the exact test name, or the exact opened artifact. No `~25% coverage` estimates; enumerate the tests. + No "this might be missing"; verify. +2. **Root cause only.** Reject patches, workarounds, and "make it pass" fixes. + Reject any change that addresses the symptom without proving the symptom's mechanism. + If the author can't explain why the issue occurred and why the fix prevents recurrence, request changes. +3. **No heuristics on heuristics.** Runtime string-match branches (`if word in intent.lower(): rules.append(...)`) are technical debt. + Any new instance is a blocker unless the author explicitly justifies why a structural fix is impossible. + Removing existing ones is a feature. +4. **No fabricated reads.** Never claim to have read a file you didn't. + Never grep for an expected keyword and assume absence means absence — names you didn't predict will hide the test. +5. **Stale-source check.** Confirm `stat -f "%Sm" ` lines up with when the diff was last edited. + Old reads of recently-rewritten code are how false reviews ship. +6. **No silent coverage.** "Tests pass" is not a review signal. + Enumerate which tests exercise which branch of the changed surface; identify untested branches by name. +7. **Compliance with the engineering standard is non-negotiable.** Every diff must satisfy the [engineering standard](engineering.md). The Engineering-standard compliance section below lists the specific rules to verify. +8. **Artifacts.** Keep investigation artifacts under the repository's local debug directory, never `/tmp`, and reference paths absolutely. + +# Engineering-standard compliance — verify before reviewing logic + +Open the [engineering standard](engineering.md) and confirm the diff respects every rule listed there. Specifically: + +**Architecture (the engineering standard §1, §10, §24, plus the Fathom-specific reminder)** +- Hexagonal architecture is non-negotiable. Domain (`schemas/`, `constants/`) depends on nothing. + Application (`core/`) depends only on Domain and Ports (`interfaces/`). + Adapters (`adapters/`, `runtime/`, `infrastructure/`) depend inward only. - Domain must not contain HTTP, DB, file system, env reads, logging, telemetry, global state, framework imports. - Block any diff where Application imports concrete Adapter classes directly. - Block any diff where Domain or Application imports a vendor SDK. -**Naming (SKILL.md §3 + Fathom-specific)** +**Naming (the engineering standard §3 + Fathom-specific)** - Folders, files, modules use single-word `snake_case`. -- Classes `PascalCase`. Functions/methods `snake_case`. Private methods `__snake_case` — never `_snake_case` for private. Constants `UPPER_SNAKE_CASE`. -- Enum member values are `UPPER_SNAKE_CASE` for internal/semantic enums (value mirrors the name); only enums whose values form an external/rendered protocol vocabulary (rendered-output tokens, external API/tool contracts, persisted wire formats) keep literal-cased values. A lowercase value on an internal/semantic enum is a Blocker. -- No unit suffixes/prefixes on variables (`duration_ms`, `cache_size_bytes`, `latency_seconds` are wrong — use `duration`/`size`/`latency` with the unit documented in a one-line docstring or schema description). +- Classes `PascalCase`. Functions/methods `snake_case`. Private methods `__snake_case` — never `_snake_case` for private. + Constants `UPPER_SNAKE_CASE`. +- Enum member values are `UPPER_SNAKE_CASE` for internal/semantic enums (value mirrors the name); + only enums whose values form an external/rendered protocol vocabulary (rendered-output tokens, external API/tool contracts + persisted wire formats) keep literal-cased values. A lowercase value on an internal/semantic enum is a Blocker. +- No unit suffixes/prefixes on variables (`duration_ms`, `cache_size_bytes` + `latency_seconds` are wrong — use `duration`/`size`/`latency` with the unit documented in a one-line docstring or schema description). - Prefer nested Pydantic fields (`ocr.enabled`, not `ocr_enabled`). - Names must be domain-driven and self-explanatory. No abbreviations. -**Classes (SKILL.md §6, §31 + Fathom-specific)** +**Classes (the engineering standard §6, §31 + Fathom-specific)** - Default to classes. Standalone functions are only for pure stateless transformations. - Reject standalone module-level functions that do anything but transform inputs to outputs. - Each class has one articulable responsibility — one sentence. - `__` for private internals. `_` for protected/internal members. Use private methods aggressively to keep public methods unbloated. - Prefer composition over inheritance. -**Data models (SKILL.md §7)** -- Pydantic `BaseModel` for anything crossing a boundary, with Pydantic `Field(description=...)`. -- `dataclass` only for pure in-memory domain value objects. +**Data models (the engineering standard §7)** +- Pydantic `BaseModel` for entities, validated value objects, and anything crossing a boundary, with Pydantic `Field(description=...)`. +- Never use `@dataclass` anywhere; Pydantic `BaseModel` is the only entity model. - Raw `dict` or `tuple` instead of a typed model is a Blocker. - Domain entities prefer immutability (`model_config = ConfigDict(frozen=True)` on Pydantic models that represent invariants). -**Constants (SKILL.md §32 + Fathom-specific)** -- No hardcoded values. Numbers, strings, bucket names, namespaces, timeouts, thresholds — all go into `constants/` as `IntEnum`/`StrEnum`/`Final[int]`/`Final[str]`. +**Constants (the engineering standard §32 + Fathom-specific)** +- No hardcoded values. + Numbers, strings, bucket names, namespaces, timeouts + thresholds — all go into `constants/` as `IntEnum`/`StrEnum`/`Final[int]`/`Final[str]`. - Magic numbers or strings without named constants is a Blocker. -**Typing (SKILL.md §5)** +**Typing (the engineering standard §5)** - Type hints mandatory on every function/method signature and class attribute. - `Any` is prohibited except at the outermost boundary where the type is genuinely unknowable. - Block any diff that introduces `# type: ignore` without an inline reason. -**Docstrings (SKILL.md §5 + Fathom-specific)** -- Every class: one-line docstring stating purpose. -- Every function/method: one-line docstring stating what it does. -- Format: `"""Crisp one-liner."""` — single-line preferred. If multi-line is unavoidable, the body is one short sentence stating intent and contract. No multi-paragraph rationale, no bug-history recaps, no commentary on call sites. +**Docstrings (the engineering standard §5 + Fathom-specific)** +- Every class: a docstring stating its purpose. +- Every function/method: a docstring stating what it does. +- Format: always the multi-line form with the triple-quotes on their own lines, even for one-liners — `"""` + then one short sentence stating intent and contract, then `"""`. + No multi-paragraph rationale, no bug-history recaps, no commentary on call sites. - Reject docstrings that grow because the function "needs explanation" — the function probably needs simplification. -**Keyword arguments (SKILL.md §8)** +**Keyword arguments (the engineering standard §8)** - All internal calls must use keyword arguments. - Positional allowed only for standard library, third-party APIs, or strong idiomatic conventions. - Block any internal call site that passes positional arguments to a Fathom-defined function. -**Exceptions (SKILL.md §9, §19)** +**Exceptions (the engineering standard §9, §19)** - Catch the most specific exception. `except Exception:` is suspect; `except BaseException:` is rejected. - Re-raise `asyncio.CancelledError` explicitly when caught by a broad `except`. - Domain-specific exception types (`FathomError` subclasses) preferred over generic `RuntimeError`. - Never swallow errors silently. Fail fast on invariant violation with diagnostic context. -**Tests (SKILL.md §29 + Fathom-specific)** +**Tests (the engineering standard §29 + Fathom-specific)** - Test files mirror source paths (`tests/unit/`, `tests/integration/`, `tests/live/`). - Class-based tests only. No function-based tests. - Tests must exercise real cases, not vague placeholders. @@ -101,11 +137,15 @@ For each, the review questions are generic but the component is named. The revie Files: `strategies/graph/intent/nodes/*.py`, `strategies/graph/state.py`, `core/agent/state.py`, `schemas/state.py`. Verify: -- Every channel a node writes is declared on the `IntentGraphState` TypedDict in `strategies/graph/state.py`. Undeclared keys are silently dropped by LangGraph's reducer. -- Every terminal patch (cancellation, max-steps, failure, completion, etc.) sets every key it claims to clear. Missing `SHOULD_RETRY`, `VERIFY_MODE`, `COMPLETION_REASON`, `FAILURE_DIAGNOSTIC` lets stale values from prior turns leak forward. +- Every channel a node writes is declared on the `IntentGraphState` TypedDict in `strategies/graph/state.py`. + Undeclared keys are silently dropped by LangGraph's reducer. +- Every terminal patch (cancellation, max-steps, failure, completion, etc.) sets every key it claims to clear. + Missing `SHOULD_RETRY`, `VERIFY_MODE`, `COMPLETION_REASON`, `FAILURE_DIAGNOSTIC` lets stale values from prior turns leak forward. - State transitions are idempotent — re-running a node on the same input must produce the same patch. -- No node mutates a channel it doesn't own. Cross-node mutation through the graph state is acceptable; cross-node mutation through `AgentState` is suspect. -- `AgentState.to_checkpoint()` and `AgentState.from_checkpoint(...)` round-trip every field the diff adds. A new field that's not in `to_checkpoint` is lost on resume. +- No node mutates a channel it doesn't own. + Cross-node mutation through the graph state is acceptable; cross-node mutation through `AgentState` is suspect. +- `AgentState.to_checkpoint()` and `AgentState.from_checkpoint(...)` round-trip every field the diff adds. + A new field that's not in `to_checkpoint` is lost on resume. - Invariant violations (cursor drift, mode/state mismatch) raise `InvariantViolation` with diagnostic context, not `RuntimeError` or silent recovery. - The router functions in `builder.py` are pure functions of the state dict — no IO, no randomness. @@ -114,22 +154,34 @@ Verify: Files: `core/prompts/tools.py`, `core/prompts/decomposition.py`, `core/prompts/gemini.py`, `core/prompts/templates.py`. Verify: -- The `action_type` enum in `tools.py` matches `ActionType` in `constants/__init__.py`. Adding to one without the other lets the model emit values the executor doesn't handle, or hides supported actions from the model. +- The `action_type` enum in `tools.py` matches `ActionType` in `constants/__init__.py`. + Adding to one without the other lets the model emit values the executor doesn't handle, or hides supported actions from the model. - The Decomposer directive table in `decomposition.py` only maps to directives the executor can actually satisfy. -- Tool-field `description` strings are part of the contract — changes to them are behavior changes for the model. Pin them in a test if you change them. +- Tool-field `description` strings are part of the contract — changes to them are behavior changes for the model. + Pin them in a test if you change them. - Runtime keyword-substring rules (`if word in intent.lower():`) are flagged as heuristic debt. New ones are a Blocker. - System-prompt sections are sourced from one place. Reject "append a sibling rule next to the existing rule" patterns. ## Action surface — four-place contract -Files: `constants/__init__.py:ActionType`, `schemas/actions.py:Action`, `core/prompts/tools.py:action_type enum`, `core/services/action.py:__action_handlers`, `constants/interaction.py:InteractionAction`, `adapters/device/{local,remote}/{adb,ios}.py`. - -A change to the action set is a four-place coordinated change: enum, schema, tool-schema, dispatch table, adapter methods, wire-protocol enum. Verify all places are touched together. - -- `ActionType` enum, the LLM tool schema's `action_type` enum, and the executor's `__action_handlers` table must all align. Disagreement is silent failure. -- `InteractionAction` (`constants/interaction.py`) is the wire contract with the remote farm. Removing a value from `ActionType` must remove it here too. Values here that the remote worker doesn't implement become `success=False, error="Failed to execute..."` in prod. -- Removing an `ActionType` member requires a Pydantic `model_validator(mode="before")` on `Action` that coerces or rejects the legacy value — otherwise old checkpoints and `history.json` files fail to load. -- Targetless actions (no `label_id`, no `bounds`) bypass the `__snap_to_label` guard. Adding such an action is suspect; document why a snap/agreement guard isn't needed. +Files: +`constants/__init__.py:ActionType`, `schemas/actions.py:Action`, `core/prompts/tools.py:action_type enum` +`core/services/action.py:__action_handlers`, `constants/interaction.py:InteractionAction` +`adapters/device/{local,remote}/{adb,ios}.py`. + +A change to the action set is a four-place coordinated change: enum, schema, tool-schema, dispatch table, adapter methods +wire-protocol enum. Verify all places are touched together. + +- `ActionType` enum, the LLM tool schema's `action_type` enum, and the executor's `__action_handlers` table must all align. + Disagreement is silent failure. +- `InteractionAction` (`constants/interaction.py`) is the wire contract with the remote farm. + Removing a value from `ActionType` must remove it here too. + Values here that the remote worker doesn't implement become `success=False, error="Failed to execute..."` in prod. +- Removing an `ActionType` member requires a Pydantic `model_validator(mode="before")` on `Action` + that coerces or rejects the legacy value — otherwise old checkpoints and `history.json` files + fail to load. +- Targetless actions (no `label_id`, no `bounds`) bypass the `__snap_to_label` guard. + Adding such an action is suspect; document why a snap/agreement guard isn't needed. ## Resolution and snap layer @@ -137,17 +189,23 @@ Files: `core/services/resolution.py`, `core/services/normalizer.py`. Verify: - `__snap_to_label` runs only for `SPATIAL_ACTION_TYPES`. Non-spatial actions strip `label_id` and pass through — confirm that's intended. -- The IoU agreement check at `resolution.py:207-250` only fires when `not __element_has_semantic_descriptor(element=info)`. Text-bearing elements skip the guard. If the diff adds new agreement logic, ensure it covers both branches. -- Generic visual containers must be rejected with structured `event=snap.generic_container.rejected` so the planner-side `skip_label_id` flow has signal. +- The IoU agreement check at `resolution.py:207-250` only fires when `not __element_has_semantic_descriptor(element=info)`. + Text-bearing elements skip the guard. If the diff adds new agreement logic, ensure it covers both branches. +- Generic visual containers must be rejected with structured `event=snap.generic_container.rejected` + so the planner-side `skip_label_id` flow has signal. ## Completion gate and sub-goal lifecycle -Files: `core/agent/completion.py`, `strategies/graph/intent/nodes/completion.py`, `strategies/graph/intent/nodes/verify.py`, `strategies/graph/intent/nodes/record.py`, `strategies/graph/intent/verification.py`, `core/agent/state.py`. +Files: +`core/agent/completion.py`, `strategies/graph/intent/nodes/completion.py`, `strategies/graph/intent/nodes/verify.py` +`strategies/graph/intent/nodes/record.py`, `strategies/graph/intent/verification.py`, `core/agent/state.py`. Verify: -- The gate's `(claim.asserted, claim.justified, action.dispatched, screen.evolved)` evidence pairs are sourced from real signals — not heuristic substring checks. +- The gate's `(claim.asserted, claim.justified, action.dispatched + screen.evolved)` evidence pairs are sourced from real signals — not heuristic substring checks. - Sub-goal cursor and `VerifyMode` are consistent — `VerificationModePolicy.mode_for_producer` reads cursor truthfully. -- Counters (`verification_loop`, `consecutive_complete_deferrals`, planner-retry budget) reset on real progress and persist across irrelevant turns. Asymmetric reset across paths is debt. +- Counters (`verification_loop`, `consecutive_complete_deferrals` + planner-retry budget) reset on real progress and persist across irrelevant turns. Asymmetric reset across paths is debt. - Every `mark_complete` call site uses a `CompletionReason` from the enum, not a free-text string. ## Configuration and infrastructure boundaries @@ -174,7 +232,8 @@ Verify: Files: `runtime/executor.py`, `runtime/temporal/`, `adapters/signal/temporal.py`, `strategies/graph/intent/nodes/hitl.py`. Verify: -- `except Exception:` blocks explicitly re-raise `asyncio.CancelledError` (CancelledError is `BaseException` in 3.8+, but legacy code may have caught it). +- `except Exception:` blocks explicitly re-raise `asyncio.CancelledError` (CancelledError is `BaseException` in 3.8+ + but legacy code may have caught it). - Cancellation paths persist any state mutations before returning. - HITL signal-adapter wait loops check `is_cancelled` between awaits. - Resource acquisition has a guaranteed release path (`try/finally`, `async with`, or explicit shutdown method). @@ -187,7 +246,9 @@ Files: every node, adapter, and service. Verify: - Every exit path emits a structured event (`extra={"event": "...", "component": "..."}`). Silent paths are unreviewable in prod. - `workflow.id` is on every node-level log so dashboards can scope by run. -- Log level is consistent: `logger.exception(...)` for caught exceptions with traceback value, `logger.error(...)` for known-failure paths without a traceback, `logger.warning(...)` for degraded but recoverable. +- Log level is consistent: + `logger.exception(...)` for caught exceptions with traceback value, `logger.error(...)` for known-failure paths without a traceback + `logger.warning(...)` for degraded but recoverable. - `FAILURE_DIAGNOSTIC` strings are capped (typically 500 chars) — never an unbounded exception/traceback string into a checkpoint. - Every `CompletionReason` member is classified in `intent.py:__is_successful_completion` and (if terminal) in `TERMINAL_COMPLETION_REASONS`. @@ -198,22 +259,29 @@ Files: any node, `runtime/runner.py`, telemetry sinks. Verify: - Success and failure paths of the same operation both emit events. One-sided observability is a Major issue. - `FathomEvent` taxonomy is respected. New telemetry event values go in the enum, not as free-string `type=...` arguments. -- Terminal messages reflect the actual outcome. `runtime/runner.py:354` is a known active bug — flag any new exit path that funnels through `terminal_message = "All wrapped up."` without a FAILED branch. +- Terminal messages reflect the actual outcome. + Flag any new exit path that funnels a failed run through a generic success message without a FAILED branch. # Failure patterns shipped to prod — known shapes to grep for -These are real failure shapes the user has triaged. The reviewer must actively probe for these in any diff that touches the relevant layer. +These are real failure shapes seen in production. The reviewer must actively probe for these in any diff that touches the relevant layer. -1. **Streak counter keyed on a field that mutates each turn.** A counter like `consecutive_rejections` that resets because its match function compares `step_count` (which `record_step` increments). Use stable identifiers (activity, screen identity). -2. **Transient error counted as a rejection.** LLM timeout / 503 / JSON parse failure falls through to the same path as a verifier saying "no." Branch on transport vs verdict. +1. **Streak counter keyed on a field that mutates each turn.** A counter like `consecutive_rejections` + that resets because its match function compares `step_count` (which `record_step` increments). + Use stable identifiers (activity, screen identity). +2. **Transient error counted as a rejection.** LLM timeout / 503 / JSON parse failure falls through + to the same path as a verifier saying "no." Branch on transport vs verdict. 3. **Counters not reset on real progress.** Sub-goal advance leaves stale streak/deferral counters from a prior sub-goal. -4. **Wrong action paired with wrong target by the model.** Decomposer emits an unsupported directive; planner satisfies by emitting an action with `label_id=None, bounds=None`. Structural fix: remove the directive option. +4. **Wrong action paired with wrong target by the model.** Decomposer emits an unsupported directive; + planner satisfies by emitting an action with `label_id=None, bounds=None`. Structural fix: remove the directive option. 5. **Targetless action primitives have no snap guard.** ENTER/HOME/BACK pass through resolution unguarded — no anchor. 6. **Runtime substring keyword rules misroute.** `if any(word in intent.lower() for word in [...])` is a serial bug factory. 7. **Terminal-message lies on failure.** A binary `if cancelled: ... else: "All wrapped up."` reports failed runs as completed. 8. **Prod-config drift.** Hardcoded bucket name with "dev" or "stag" in the value reaching prod, hardcoded namespace, hardcoded URL. 9. **Coverage estimated, not enumerated.** Reviewer says "~25%"; actual answer is enumerable. -10. **Test mocks the very thing being tested**, or bypasses the path that the bug actually walks (e.g. a unit test that bypasses `record_step` to test a flow that always goes through `record_step` in prod). +10. **Test mocks the very thing being tested** + or bypasses the path that the bug actually walks (e.g. + a unit test that bypasses `record_step` to test a flow that always goes through `record_step` in prod). # Test-coverage discipline @@ -226,13 +294,16 @@ For every changed function: For changes to nodes in `strategies/graph/intent/nodes/`: - A unit test that drives the node with a `_Provider` double and asserts every state-patch key the node sets or clears. -- An integration test under `tests/integration/strategies/graph/intent/nodes/` that drives the node alongside its peers in realistic order, with a real `AgentState` (not a mock), so cursor/streak/deferral counters round-trip. +- An integration test under `tests/integration/strategies/graph/intent/nodes/` that drives the node + alongside its peers in realistic order, with a real `AgentState` (not a mock), so + cursor/streak/deferral counters round-trip. For changes to load-bearing prompt files (`tools.py`, `decomposition.py`, `gemini.py`): - A `tests/unit/core/prompts/` assertion that pins the tool schema or directive table. For changes to `runtime/runner.py`, `strategies/intent.py`, `adapters/`, `infrastructure/`: -- A live test (`tests/live/`) is preferred when feasible. Mocked execution is acceptable only for non-deterministic external dependencies (LLM, network). +- A live test (`tests/live/`) is preferred when feasible. + Mocked execution is acceptable only for non-deterministic external dependencies (LLM, network). Reject: - Tests that bypass the path the bug actually walks. @@ -251,7 +322,9 @@ When the diff contains any of these patterns, raise a Blocker for justification: - `if hasattr(self.__device, "...")` runtime feature detection (use the Port interface) - Fallback chains that grow on each bug report (`if X: rule_a; elif Y: rule_b; elif Z: rule_c; ...`) -These are the antipattern that produces silent failure modes. Structural alternatives belong in the schema, the constant, the enum, the dispatch table, the Port, or the configuration — not in runtime branches. +These are the antipattern that produces silent failure modes. +Structural alternatives belong in the schema, the constant, the enum, the dispatch table, the Port +or the configuration — not in runtime branches. # Output format @@ -265,7 +338,9 @@ One of: `Blocker`, `Critical`, `Major`, `Minor`, `Suggestion`. ### Category -One of: `Architecture`, `Design`, `Maintainability`, `Testing`, `Reliability`, `Performance`, `Readability`, `Schema`, `Telemetry`, `LLM contract`, `Heuristic debt`, `Coverage`, `Standards (SKILL.md)`. +One of: +`Architecture`, `Design`, `Maintainability`, `Testing`, `Reliability`, `Performance`, `Readability`, `Schema` +`Telemetry`, `LLM contract`, `Heuristic debt`, `Coverage`, `Standards (the engineering standard)`. ### Description @@ -289,7 +364,9 @@ Only when the fix isn't obvious from the recommendation. Code block, short. One of: `Approve with minor changes`, `Request changes`, `Block`. -There is no `Approve`. Every PR has either standards issues, coverage gaps, or design concerns worth surfacing — even on PRs that should ship, name them as minor and let the author decide whether to act before merge. +There is no `Approve`. +Every PR has either standards issues, coverage gaps, or design concerns worth surfacing — even on PRs that should ship +name them as minor and let the author decide whether to act before merge. ## Production readiness score @@ -305,9 +382,10 @@ Rate 1-10. 10 = the diff reduces total complexity. ≤ 5 means it adds heuristic ## Root-cause confidence -Rate 1-10. 10 = the author explained the mechanism, named the file:line, and the fix forecloses the failure class, not just the failing case. ≤ 5 means the change is a patch. +Rate 1-10. 10 = the author explained the mechanism, named the file:line, and the fix forecloses the failure class +not just the failing case. ≤ 5 means the change is a patch. -## SKILL.md compliance +## Engineering-standard compliance One of: `Pass`, `Pass with minor deviations`, `Fail`. `Fail` makes the overall verdict at least `Request changes`. @@ -318,7 +396,7 @@ Three to five sentences. Cover: - Whether the correct problem was solved (and which prod failure class it forecloses, by name). - Whether the solution is structural or a patch. - Whether the testing is enumerable. -- Whether SKILL.md compliance is clean or the diff carries a standards violation. +- Whether Engineering-standard compliance is clean or the diff carries a standards violation. - Any blockers, by name. - Whether the diff should be merged.